Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 34 additions & 8 deletions apps/origin-src/src/annotations/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//!
//! Core interprets only the reserved kinds: [`Kind::ABANDON`],
//! [`Kind::CONFLICT`] and [`Kind::DIVERGENT`], and only from the issuers
//! [`Store::authorizes`] names. Every other kind belongs to whoever issues
//! [`RevisionView::authorizes`] names. Every other kind belongs to whoever issues
//! it. Supersession counts only within one issuer: a statement claiming to
//! supersede another issuer's is issued like any other, and the one it
//! names still stands. [`Annotations::supersede`] supersedes an issuer's
Expand All @@ -18,7 +18,8 @@ use std::collections::HashSet;
use origin_platform::{Native, Platform};
use origin_shared::api::Annotation;
use origin_shared::{
ChangeId, EncodedObject, Kind, Principal, Record, RecordId, RevisionId, Statement, StatementId,
ChangeId, EncodedObject, Kind, Principal, Record, RecordId, Revision, RevisionId, Statement,
StatementId,
};

use crate::index::Index;
Expand Down Expand Up @@ -282,13 +283,23 @@ impl<'a, P: Platform> Annotations<'a, P> {
}
}

impl<P: Platform> Store<P> {
/// Where the revisions are read that decide who may issue a reserved kind:
/// a store.
pub trait RevisionView {
/// The revision `id`.
///
/// # Errors
///
/// Fails if it cannot be found or read.
fn revision(&self, id: RevisionId) -> Result<Revision, StoreError>;

/// Whether `statement`'s issuer may issue a statement of its kind, if
/// that kind is reserved:
///
/// - `core.abandon`, about a revision, only the change's creator: the
/// author of its first revision, so no one who took it over, or
/// rebased it, gives it up for them;
/// rebased it, gives it up for them; or an `admin`, which
/// [`Policy::authorizes`](crate::policy::Policy::authorizes) adds;
/// - `core.conflict`, a node, as a landing queue that could not rebase
/// the record, or the author of the revision it's about, listing
/// the conflicts its files still have;
Expand All @@ -299,8 +310,8 @@ impl<P: Platform> Store<P> {
///
/// # Errors
///
/// Fails if a revision cannot be read.
pub fn authorizes(&self, statement: &Statement) -> Result<bool, StoreError> {
/// Fails if the revision it's about cannot be read.
fn authorizes(&self, statement: &Statement) -> Result<bool, StoreError> {
let issuer = &statement.issuer;
if !statement.kind.is_reserved() {
return Ok(true);
Expand All @@ -316,7 +327,7 @@ impl<P: Platform> Store<P> {
Ok(if *kind == Kind::ABANDON {
self.created(subject, issuer)?
} else if *kind == Kind::CONFLICT {
is_node || self.get(subject)?.author == *issuer
is_node || self.revision(subject)?.author == *issuer
} else {
*kind == Kind::DIVERGENT && is_node
})
Expand All @@ -325,14 +336,23 @@ impl<P: Platform> Store<P> {
/// Whether `author` created the change of `revision`: made each
/// revision it evolves from that evolves from none. Records being
/// immutable, there is always one, and no one adds another later.
/// History this view lacks leaves it unknown: no.
///
/// # Errors
///
/// Fails if a revision cannot be read.
fn created(&self, revision: RevisionId, author: &Principal) -> Result<bool, StoreError> {
let mut seen = HashSet::new();
let mut next = vec![revision];
while let Some(id) = next.pop() {
if !seen.insert(id) {
continue;
}
let revision = self.get(id)?;
let revision = match self.revision(id) {
Ok(revision) => revision,
Err(StoreError::NotFound(_)) => return Ok(false),
Err(error) => return Err(error),
};
if revision.predecessors.is_empty() && revision.author != *author {
return Ok(false);
}
Expand All @@ -342,6 +362,12 @@ impl<P: Platform> Store<P> {
}
}

impl<P: Platform> RevisionView for Store<P> {
fn revision(&self, id: RevisionId) -> Result<Revision, StoreError> {
self.get(id)
}
}

/// A failure to issue a statement.
#[derive(Debug, thiserror::Error)]
pub enum AnnotateError {
Expand Down
38 changes: 36 additions & 2 deletions apps/origin-src/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ use origin_shared::access::{Capability, Level, PathAccess, Rights, Targets};
use origin_shared::policy::{KindPattern, Principals, Requirement};
use origin_shared::{
AcceptanceBody, AcceptanceId, EncodedObject, EntryKind, EntryName, InvalidName, InvalidPeriod,
Kind, NodePublicKey, Period, Principal, PrincipalName, Record, RepoPath, TargetName, Tree,
TreeEntry, TreeId,
Kind, NodePublicKey, Period, Principal, PrincipalName, Record, RepoPath, Statement, TargetName,
Tree, TreeEntry, TreeId,
};
use serde::Deserialize;

use crate::annotations::RevisionView;
use crate::store::{Store, StoreError};

/// The policy of a repository.
Expand Down Expand Up @@ -248,6 +249,39 @@ impl Policy {
}
}

/// Whether `statement`'s issuer may issue a statement of its kind: as
/// [`Store::authorizes`] says, or for `core.abandon`, if the policy
/// makes them `admin`.
///
/// # Errors
///
/// Fails if a revision cannot be read.
pub fn authorizes(
&self,
revisions: &impl RevisionView,
statement: &Statement,
) -> Result<bool, StoreError> {
let admin = self.rights(Some(&statement.issuer)).admin;
Self::authorizes_admin(revisions, statement, admin)
}

/// [`Policy::authorizes`], for an issuer who is `admin` or not: as the
/// token they put the statement with narrows their rights, say.
///
/// # Errors
///
/// Fails if a revision cannot be read.
pub fn authorizes_admin(
revisions: &impl RevisionView,
statement: &Statement,
admin: bool,
) -> Result<bool, StoreError> {
if statement.kind == Kind::ABANDON && statement.promoted_from.is_none() && admin {
return Ok(true);
}
revisions.authorizes(statement)
}

/// What `principal`, or an anonymous caller, may do, as the module
/// explains. Anonymous callers never write.
#[must_use]
Expand Down
4 changes: 3 additions & 1 deletion apps/origin-src/src/queue/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,9 @@ impl<P: Platform> Session<'_, '_, P> {
let claims = self.annotations.claims(RecordId::Revision(head))?;
for claim in &claims {
let statement = claim.statement();
if statement.kind == Kind::ABANDON && self.store().authorizes(statement)? {
if statement.kind == Kind::ABANDON
&& self.policy.authorizes(self.store(), statement)?
{
return Err(LandError::Abandoned(change));
}
}
Expand Down
25 changes: 22 additions & 3 deletions apps/origin-src/src/queue/tests/changes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,13 @@ fn pending_landings_round_trip() {

#[test]
fn only_the_creator_of_a_change_abandons_it() {
let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n");
let repo = Repo::new(
"[targets.main]\nauthority = \"node:queue\"\n\
[grants]\nall = [\"land *\", \"annotate *\"]\n\"user:root\" = [\"admin\"]\n",
);
let revision = repo.change_on_main(1, &[("file", "work")]);
let abandon = |issuer: &str| Statement {
let given_up = repo.change_on_main(2, &[("other", "work")]);
let abandon = |issuer: &str, revision| Statement {
subject: RecordId::Revision(revision),
kind: Kind::ABANDON,
verdict: None,
Expand All @@ -205,9 +209,24 @@ fn only_the_creator_of_a_change_abandons_it() {
promoted_from: None,
};
repo.store
.write_all(&[abandon("user:eve").encode()])
.write_all(&[
abandon("user:eve", revision).encode(),
abandon("user:root", given_up).encode(),
])
.unwrap();
assert!(matches!(repo.land(1)[..], [Landing::Landed { .. }]));
let error = repo
.queue()
.land_change(
&mut repo.annotations(),
ChangeId::from_bytes([2; 16]),
&TargetName::MAIN,
)
.unwrap_err();
assert!(
matches!(error, LandError::Abandoned(_)),
"an admin may: {error}"
);
}

#[test]
Expand Down
23 changes: 16 additions & 7 deletions apps/origin-src/src/workspace/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1127,10 +1127,10 @@ impl Workspace {
///
/// # Errors
///
/// Fails if the change cannot be found or diverged, the user didn't
/// create it, so readers would ignore the statement, or the records
/// cannot be written. Then no abandonment is written and nothing is
/// checked out.
/// Fails if the change cannot be found or diverged, the user neither
/// created it nor is an `admin`, so readers would ignore the statement,
/// or the records cannot be written. Then no abandonment is written and
/// nothing is checked out.
pub fn abandon(&mut self, change: Option<&str>, reason: &str) -> Result<(), WorkspaceError> {
let mut working_copy = self.refresh()?;
let index = &working_copy.index;
Expand All @@ -1150,7 +1150,8 @@ impl Workspace {
supersedes: None,
promoted_from: None,
};
if !self.store.authorizes(&statement)? {
// As readers count it.
if !Policy::load(&self.store)?.authorizes(&self.store, &statement)? {
return Err(AnnotateError::Reserved {
kind: statement.kind,
issuer: statement.issuer,
Expand Down Expand Up @@ -1476,16 +1477,24 @@ impl Workspace {
}

/// Who abandoned a revision, and why: only those who may, as
/// [`Store::authorizes`] says.
/// [`Policy::authorizes`] says, as the landing queue counts them.
fn abandonments(
&self,
index: &Index,
revision: RevisionId,
) -> Result<Vec<(Principal, String)>, WorkspaceError> {
let mut abandonments = Vec::new();
let mut policy = None;
for &id in index.statements(RecordId::Revision(revision)) {
let statement = self.store.get(id)?;
if statement.kind == Kind::ABANDON && self.store.authorizes(&statement)? {
if statement.kind != Kind::ABANDON {
continue;
}
let policy = match &policy {
Some(policy) => policy,
None => policy.insert(Policy::load(&self.store)?),
};
if policy.authorizes(&self.store, &statement)? {
let reason = match statement.payload {
Some(payload) => self.text(payload)?,
None => String::new(),
Expand Down
15 changes: 14 additions & 1 deletion apps/origin-src/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ fn init_with_a_malformed_key_leaves_no_repository() {
}

#[test]
fn only_the_creator_of_a_change_abandons_it() {
fn only_the_creator_of_a_change_or_admins_abandon_it() {
let repo = Repo::new();
repo.write("file", "ada's\n");
repo.ok(&["describe", "Ada's change"]);
Expand All @@ -540,6 +540,19 @@ fn only_the_creator_of_a_change_abandons_it() {
assert_eq!(repo.ok(&["statements"]), statements);
fs::write(&config, "user = \"ada\"\n").unwrap();
assert!(!repo.ok(&["show", &change]).contains("bandoned"));

// Once the policy makes eve an admin, she may.
repo.ok(&["new", "--on", "policy"]);
let policy = repo
.read("policy.toml")
.replace("\n# [grants]\n", "\n[grants]\n\"user:eve\" = [\"admin\"]\n");
repo.write("policy.toml", &policy);
repo.ok(&["land"]);
fs::write(&config, "user = \"eve\"\n").unwrap();
repo.ok(&["abandon", &change, "--reason", "Not mine"]);
fs::write(&config, "user = \"ada\"\n").unwrap();
let show = repo.ok(&["show", &change]);
assert!(show.contains("Abandoned by user:eve: Not mine\n"), "{show}");
}

#[test]
Expand Down