diff --git a/AGENTS.md b/AGENTS.md index d7939542..ce68a480 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,9 +35,10 @@ to a hot path (hashing, storage, snapshots, transfer) should come with a benchmark, and its numbers in the pull request. - `just bench`: the divan micro-benchmarks (encoding, store writes, - snapshots, input digests and promotion, landing, reading events, the - server's request latency and long-poll wakeups, syncing a 20,000-file - tree over HTTP, and a fetch that brings nothing from a long history). + snapshots, input digests and promotion, landing, permission checks, + reading events, the server's request latency and long-poll wakeups, + syncing a 20,000-file tree over HTTP, and a fetch that brings nothing + from a long history). - `just bench-git`: times origin against git on a 20,000-file tree with hyperfine, and rewrites `docs/benchmarks.md`. diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index 2b2cbc20..395df508 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -50,6 +50,10 @@ harness = false name = "land" harness = false +[[bench]] +name = "permissions" +harness = false + [[bench]] name = "server" harness = false diff --git a/apps/origin-src/benches/annotations.rs b/apps/origin-src/benches/annotations.rs index a15505d8..3329e234 100644 --- a/apps/origin-src/benches/annotations.rs +++ b/apps/origin-src/benches/annotations.rs @@ -182,7 +182,7 @@ fn promotions_cached(bencher: Bencher<'_, '_>) { let mut annotations = Annotations::open(&store).unwrap(); assert_eq!( annotations - .promotions(RecordId::Revision(target), &issuer) + .promotions(RecordId::Revision(target), &issuer, |_| Ok(true)) .unwrap() .len(), 9 @@ -193,7 +193,7 @@ fn promotions_cached(bencher: Bencher<'_, '_>) { .with_inputs(|| Annotations::new(&store, index.clone())) .bench_local_refs(|annotations| { annotations - .promotions(RecordId::Revision(target), &issuer) + .promotions(RecordId::Revision(target), &issuer, |_| Ok(true)) .unwrap() }); } @@ -214,7 +214,7 @@ fn promotions_uncached(bencher: Bencher<'_, '_>) { }) .bench_local_refs(|annotations| { annotations - .promotions(RecordId::Revision(target), &issuer) + .promotions(RecordId::Revision(target), &issuer, |_| Ok(true)) .unwrap() }); } diff --git a/apps/origin-src/benches/permissions.rs b/apps/origin-src/benches/permissions.rs new file mode 100644 index 00000000..9395d23b --- /dev/null +++ b/apps/origin-src/benches/permissions.rs @@ -0,0 +1,216 @@ +//! The cost of permission checks on a 20k-file tree: walking `main`'s tip +//! for a clone, and landing a change editing one file, each as the owner, +//! who isn't checked, as a user under a policy without path rules, and as +//! one whom path rules withhold a directory from and keep from writing +//! another. Landings sync, so run on a real disk. + +use std::sync::{Arc, LazyLock}; + +use divan::Bencher; +use origin_shared::api::{FetchSnapshot, LandRequest}; +use origin_shared::landing::{Landing, Proposal}; +use origin_shared::pack::Pack; +use origin_shared::{ + AcceptanceId, Base, ChangeId, EncodedObject, EntryKind, EntryName, NodeKey, Record, RecordId, + Revision, TargetName, Tree, TreeEntry, TreeId, +}; +use origin_src::fixture::FixtureTree; +use origin_src::policy::Policy; +use origin_src::service::{Caller, Node, OriginService}; +use origin_src::worktree::{StatCache, Worktree}; + +fn main() { + divan::main(); +} + +const TREE: FixtureTree = FixtureTree::LARGE; + +/// Rules sparing the benchmark's edits, in `dir0`, but withholding `dir3` +/// and keeping `dir5/sub1` read-only, from everyone but `user:ada`. +const RULES: &str = r#" +[[paths]] +path = "dir3" +grants = { all = "none", "user:ada" = "write" } + +[[paths]] +path = "dir5/sub1" +grants = { all = "read", "user:ada" = "write" } +"#; + +/// Who calls. +#[derive(Clone, Copy, Debug)] +enum Who { + /// The node's own user. + Owner, + /// A user, under a policy without path rules. + NoRules, + /// A user, under [`RULES`]. + Rules, +} + +/// A repository whose `main` holds the fixture, under a policy without path +/// rules, and one under [`RULES`]. +struct Setup { + _dirs: [tempfile::TempDir; 2], + open: OriginService, + ruled: OriginService, +} + +static SETUP: LazyLock = LazyLock::new(|| { + let files = tempfile::tempdir().unwrap(); + TREE.write(files.path()).unwrap(); + let repos = tempfile::tempdir().unwrap(); + let node = Node { + name: "hosted".parse().unwrap(), + key: Arc::new(NodeKey::from_bytes(&[7; 32])), + }; + let initial = Policy::initial(&node.name, &node.key.public()); + let create = |name: &str, policy: &str| { + OriginService::create(repos.path().join(name), node.clone(), policy).unwrap() + }; + let open = create("open", &initial); + let ruled = create("ruled", &format!("{initial}{RULES}")); + for service in [&open, &ruled] { + let (tree, _) = Worktree::new(files.path(), service.store()) + .snapshot(&StatCache::default()) + .unwrap(); + let change = put(service, tree); + land(service, &Caller::Owner, change); + } + Setup { + _dirs: [files, repos], + open, + ruled, + } +}); + +impl Setup { + fn service(&self, who: Who) -> &OriginService { + match who { + Who::Owner | Who::NoRules => &self.open, + Who::Rules => &self.ruled, + } + } +} + +impl Who { + fn caller(self) -> Caller { + match self { + Self::Owner => Caller::Owner, + Self::NoRules | Self::Rules => Caller::Principal { + principal: "user:bench".parse().unwrap(), + scope: None, + }, + } + } +} + +/// The tip of `main`. +fn tip(service: &OriginService) -> AcceptanceId { + service + .store() + .head(&TargetName::MAIN) + .unwrap() + .unwrap() + .acceptance +} + +/// Puts a revision of a new change with `snapshot` on `main`'s tip. +fn put(service: &OriginService, snapshot: TreeId) -> ChangeId { + let description = EncodedObject::attachment(b"bench"); + let revision = Revision { + change: ChangeId::random().unwrap(), + predecessors: Vec::new(), + base: Base::Acceptance(tip(service)), + deps: Vec::new(), + snapshot, + description: description.id().into(), + author: "user:bench".parse().unwrap(), + }; + let pack = Pack { + objects: vec![description, revision.encode()], + }; + service.put_records(&Caller::Owner, pack).unwrap(); + revision.change +} + +fn land(service: &OriginService, caller: &Caller, change: ChangeId) { + let request = LandRequest { + proposal: Proposal::Change(change), + onto: None, + }; + let landed = service.land(caller, &request).unwrap(); + assert!(matches!(landed.landings[..], [Landing::Landed { .. }])); +} + +/// The whole snapshot of `main`'s tip, as a clone fetches it. +#[divan::bench(args = [Who::Owner, Who::NoRules, Who::Rules], sample_count = 10)] +fn walk(bencher: Bencher<'_, '_>, who: Who) { + let setup = &*SETUP; + let service = setup.service(who); + let request = FetchSnapshot { + of: RecordId::Acceptance(tip(service)), + have: Vec::new(), + paths: Vec::new(), + skip: 0, + }; + let caller = who.caller(); + bencher.bench(|| service.snapshot(&caller, &request).unwrap()); +} + +/// Landing a change that edits one file, made on the tip. +#[divan::bench(args = [Who::Owner, Who::NoRules, Who::Rules], sample_count = 20)] +fn land_one_edit(bencher: Bencher<'_, '_>, who: Who) { + let setup = &*SETUP; + let service = setup.service(who); + let store = service.store(); + let mut version = 0_u64; + bencher + .with_inputs(|| { + version += 1; + let state = store.get(tip(service)).unwrap().body().state; + let content = EncodedObject::blob(format!("version {version}\n").as_bytes()); + let file = TreeEntry { + kind: EntryKind::File, + id: content.id(), + }; + store.write_all(&[content]).unwrap(); + let snapshot = replace(service, state, &["dir0", "sub0", "file0.rs"], file); + put(service, snapshot) + }) + .bench_local_values(|change| land(service, &who.caller(), change)); +} + +/// `tree`, with `entry` at the path of `components` instead, writing the +/// trees on the way. +fn replace(service: &OriginService, tree: TreeId, components: &[&str], entry: TreeEntry) -> TreeId { + let store = service.store(); + let mut tree: Tree = store.get(tree).unwrap(); + let (name, rest) = components.split_first().unwrap(); + let entry = if rest.is_empty() { + entry + } else { + let subtree = tree.get(name).unwrap().subtree().unwrap(); + TreeEntry { + kind: EntryKind::Tree, + id: replace(service, subtree, rest, entry).into(), + } + }; + tree.insert(EntryName::new(*name).unwrap(), entry); + let encoded = tree.encode(); + store.write_all(std::slice::from_ref(&encoded)).unwrap(); + encoded.id().into() +} + +/// The walk alone, which the read check filters, without reading the +/// objects it lists, on the repository with rules: unchecked, or checked +/// against the user's rights. +#[divan::bench(args = [false, true], sample_count = 20)] +fn walk_ids(bencher: Bencher<'_, '_>, checked: bool) { + let service = &SETUP.ruled; + let store = service.store(); + let state = store.get(tip(service)).unwrap().body().state; + let rights = service.rights(&Who::Rules.caller()).unwrap(); + let access = checked.then_some(&rights.paths); + bencher.bench(|| store.added(state, &[], &[], access).unwrap().len()); +} diff --git a/apps/origin-src/src/annotations/mod.rs b/apps/origin-src/src/annotations/mod.rs index 66aaee6b..b87e2343 100644 --- a/apps/origin-src/src/annotations/mod.rs +++ b/apps/origin-src/src/annotations/mod.rs @@ -498,7 +498,7 @@ mod tests { let promoter = principal("node:queue"); Annotations::open(store) .unwrap() - .promote(RecordId::Revision(revision), &promoter) + .promote(RecordId::Revision(revision), &promoter, |_| Ok(true)) .unwrap() .into_iter() .map(|(_, statement)| { diff --git a/apps/origin-src/src/annotations/promotion.rs b/apps/origin-src/src/annotations/promotion.rs index 41536ff7..91be5765 100644 --- a/apps/origin-src/src/annotations/promotion.rs +++ b/apps/origin-src/src/annotations/promotion.rs @@ -155,10 +155,12 @@ impl Annotations<'_, P> { } /// The statements promoting results to `subject`, as `issuer` would - /// issue them, without writing them, sorted by kind: for each + /// issue them for a caller who `sees` some records, without writing + /// them, sorted by kind: for each /// [promotion group](Statement::promotion_group), the latest statement - /// about another record with the same input digest as the subject, - /// unless its issuer superseded it. Groups whose kind and issuer the + /// about another record the caller sees with the same input digest as + /// the subject, unless its issuer superseded it. So a promotion never + /// copies a result, and its payload, that the caller can't read. Groups whose kind and issuer the /// subject already has a result of, directly or promoted, are skipped: /// a result that ran there wins. A statement has no snapshot, so /// nothing is promoted to one. @@ -171,6 +173,7 @@ impl Annotations<'_, P> { &mut self, subject: RecordId, issuer: &Principal, + mut sees: impl FnMut(RecordId) -> Result, ) -> Result, StoreError> { let Some(snapshot) = self.store.snapshot_of(subject)? else { return Ok(Vec::new()); @@ -202,7 +205,7 @@ impl Annotations<'_, P> { continue; } let statement = self.store.get(id)?; - if self.superseded_by(id, &statement)?.is_none() { + if self.superseded_by(id, &statement)?.is_none() && sees(statement.subject)? { promotions.push(Statement { subject, issuer: issuer.clone(), @@ -220,9 +223,10 @@ impl Annotations<'_, P> { } /// Issues the [`promotions`](Self::promotions) to `subject` as - /// `issuer`, returning them. A promotion refers to its original's - /// payload without writing it, so it [holds the objects](Store::hold_objects) - /// from finding the originals to writing the promotions. + /// `issuer`, for a caller who `sees` some records, returning them. A + /// promotion refers to its original's payload without writing it, so + /// it [holds the objects](Store::hold_objects) from finding the + /// originals to writing the promotions. /// /// # Errors /// @@ -232,9 +236,10 @@ impl Annotations<'_, P> { &mut self, subject: RecordId, issuer: &Principal, + sees: impl FnMut(RecordId) -> Result, ) -> Result, StoreError> { let _held = self.store.hold_objects()?; - let promotions = self.promotions(subject, issuer)?; + let promotions = self.promotions(subject, issuer, sees)?; let encoded: Vec<_> = promotions.iter().map(Statement::encode).collect(); self.store.write_all(&encoded)?; Ok(encoded diff --git a/apps/origin-src/src/annotations/retention.rs b/apps/origin-src/src/annotations/retention.rs index e19c3762..7ea5be3d 100644 --- a/apps/origin-src/src/annotations/retention.rs +++ b/apps/origin-src/src/annotations/retention.rs @@ -241,7 +241,7 @@ mod tests { let issuer = "node:queue".parse().unwrap(); let promotions = Annotations::open(&store) .unwrap() - .promote(second, &issuer) + .promote(second, &issuer, |_| Ok(true)) .unwrap(); done.send(promotions.len()).unwrap(); }); diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index a1a5562e..a88d313c 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -32,6 +32,7 @@ use origin_shared::access::{Capability, PathAccess, Rights}; use origin_shared::event::EventKind; use origin_shared::{ Base, Kind, Object, ObjectId, Principal, RecordId, RepoPath, Revision, RevisionId, Statement, + TargetName, }; use crate::annotations::RevisionView; @@ -341,6 +342,9 @@ pub enum Forbidden { /// A statement of a kind the caller may not issue. #[error("you may not issue `{0}` statements")] Annotate(Kind), + /// A change to a path the caller may not write. + #[error("you may not change `{0}`")] + Write(RepoPath), /// A path the caller may not read. #[error("you may not read `{0}`")] Read(RepoPath), @@ -366,6 +370,9 @@ pub enum Forbidden { /// The attachment. attachment: ObjectId, }, + /// A target the caller may not land on. + #[error("you may not land on `{0}`")] + Land(TargetName), /// A token's scope reaches beyond its issuer's rights. #[error("a token may only narrow your rights, which don't include `{0}`")] Scope(Capability), @@ -396,7 +403,7 @@ mod tests { use origin_shared::pack::Pack; use origin_shared::{ AttachmentId, Base, ChangeId, EncodedObject, EntryKind, EntryName, NodeKey, ObjectKind, - Record, Revision, Statement, TargetName, Tree, TreeEntry, TreeId, + Record, Revision, Statement, Tree, TreeEntry, TreeId, }; use super::*; @@ -534,7 +541,10 @@ grants = { all = "none", "user:ada" = "write" } fn forbidden(result: Result) -> Forbidden { match result { - Err(ServiceError::Forbidden(forbidden)) => forbidden, + Err( + ServiceError::Forbidden(forbidden) + | ServiceError::Land(crate::queue::LandError::Forbidden(forbidden)), + ) => forbidden, other => panic!("expected a refusal, got {other:?}"), } } @@ -680,6 +690,69 @@ grants = { all = "none", "user:ada" = "write" } fixture.put(&eve, objects).unwrap(); } + #[test] + fn landings_never_change_what_the_submitter_cannot_write() { + let fixture = Fixture::new(); + let (ada, eve) = (caller("user:ada"), caller("user:eve")); + let first = fixture.tip(&TargetName::MAIN); + let old_state = fixture.state(&TargetName::MAIN); + let repo = &fixture.repo; + repo.change_on_main(2, &[("protected/file", "v2")]); + repo.land(2); + + // A revision made on an old acceptance doesn't revert what changed + // since: only its own changes land. + let mut files = vec![ + ("README.md", "hello"), + ("src/lib.rs", "fn a() {}"), + ("secrets/key", "hunter2"), + ("protected/file", "keep"), + ]; + files.push(("src/new.rs", "fn b() {}")); + let (old_base, _) = (repo.revision(3, &[], first, &files), old_state); + let landed = fixture + .land(&eve, Proposal::Change(ChangeId::from_bytes([3; 16]))) + .unwrap(); + assert!( + matches!(landed[..], [Landing::Landed { .. }]), + "{old_base} {landed:?}" + ); + let v2 = EncodedObject::blob(b"v2").id(); + assert_eq!(fixture.at_main("protected/file").unwrap().id, v2); + + // A revision someone else made that deletes the file: eve can't + // land it, ada can. + files.retain(|(path, _)| *path != "protected/file"); + repo.revision(4, &[], fixture.tip(&TargetName::MAIN), &files); + let change = Proposal::Change(ChangeId::from_bytes([4; 16])); + assert_eq!( + forbidden(fixture.land(&eve, change.clone())), + Forbidden::Write(path("protected/file")) + ); + assert!(fixture.at_main("protected/file").is_some()); + + // Nor smuggle the deletion in through another target. + let side = TargetName::new("side").unwrap(); + repo.queue() + .create_target(&side, &TargetName::MAIN) + .unwrap(); + repo.queue() + .land_change( + &mut repo.annotations(), + ChangeId::from_bytes([4; 16]), + &side, + ) + .unwrap(); + let from_side = Proposal::Target(side); + assert_eq!( + forbidden(fixture.land(&eve, from_side.clone())), + Forbidden::Write(path("protected/file")) + ); + let landed = fixture.land(&ada, from_side).unwrap(); + assert!(matches!(landed[..], [Landing::Landed { .. }]), "{landed:?}"); + assert!(fixture.at_main("protected/file").is_none()); + } + #[test] fn only_those_who_see_a_revision_succeed_it() { let fixture = Fixture::new(); diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index bfa71ed8..e45cc434 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -17,9 +17,12 @@ //! statement about the revision lists the paths, and the change waits, //! blocked, until a new revision of it merges. //! 3. **Policy.** The policy in force now must name this node as the -//! target's authority. On `policy`, that's the policy of the acceptance -//! before, never the one landing ([`Policy::governing`]). Each of the -//! target's requirements needs a [claim](crate::annotations::Claim) +//! target's authority, and the submitter must write every path the +//! landing changes on the target, whatever it lands: a revision made on +//! an old acceptance, or another target, never reverts or deletes what +//! they may not change. On `policy`, the policy is the acceptance +//! before's, never the one landing's ([`Policy::governing`]). Each of +//! the target's requirements needs a [claim](crate::annotations::Claim) //! about the revision that lands: results with the same input digest //! are promoted to it first, and a valid promotion claims what its //! original does, as its original's issuer. @@ -49,6 +52,7 @@ use std::io; use std::path::PathBuf; use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform}; +use origin_shared::access::{Level, PathAccess}; use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::{ AcceptanceBody, AcceptanceId, ChangeId, EncodedObject, Head, NodeKey, Principal, PrincipalName, @@ -57,6 +61,7 @@ use origin_shared::{ use crate::annotations::{AnnotateError, Annotations}; use crate::conflict::Conflicts; +use crate::permissions::Forbidden; use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; @@ -69,13 +74,30 @@ pub struct Queue<'a, P = Native> { store: &'a Store

, key: &'a NodeKey, node: PrincipalName, + /// What the submitter may do with each path. + submitter: PathAccess, } impl<'a, P: Platform> Queue<'a, P> { /// The queues of `store`, run by the node `node`, which signs with /// `key`. pub fn new(store: &'a Store

, key: &'a NodeKey, node: PrincipalName) -> Self { - Self { store, key, node } + Self { + store, + key, + node, + submitter: PathAccess::uniform(Level::Write), + } + } + + /// The queues, landing for a submitter who may do `paths`: everything, + /// by default. + #[must_use] + pub fn submitted_by(self, paths: PathAccess) -> Self { + Self { + submitter: paths, + ..self + } } /// This node, which issues the statements and revisions the queue @@ -453,6 +475,9 @@ pub enum LandError { /// The policy in force cannot be read. #[error(transparent)] Policy(#[from] PolicyError), + /// The submitter may not change what the landing changes. + #[error(transparent)] + Forbidden(#[from] Forbidden), /// A conflict cannot be recorded. #[error(transparent)] Annotate(#[from] AnnotateError), diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index 01faff2a..09d96ba5 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -20,6 +20,7 @@ use crate::ancestry::Ancestry; use crate::annotations::{AnnotateError, Annotations, Claim}; use crate::conflict::Conflicts; use crate::oplog::Effect; +use crate::permissions::{Forbidden, Reader}; use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; @@ -197,6 +198,13 @@ impl Session<'_, '_, P> { if !candidate.trees.is_empty() { store.write_all(&candidate.trees)?; } + if !self.queue.submitter.writes_all() { + for change in store.diff(self.state, candidate.state)? { + if !self.queue.submitter.writes(&change.path) { + return Err(Forbidden::Write(change.path).into()); + } + } + } // What a landing on `policy` lands governs the next one, which // this node must still be the authority of. let landed_policy = if self.onto == TargetName::POLICY { @@ -219,9 +227,13 @@ impl Session<'_, '_, P> { // Promotion reads the revision. store.write_all(&records)?; records.clear(); - let promotions = self - .annotations - .promotions(candidate.subject, &self.queue.principal())?; + // Only from what the submitter sees. + let mut reader = Reader::new(store, &self.queue.submitter); + let promotions = self.annotations.promotions( + candidate.subject, + &self.queue.principal(), + |record| reader.sees(record), + )?; let mut claims = self.annotations.claims(candidate.subject)?; for promotion in promotions { let encoded = promotion.encode(); diff --git a/apps/origin-src/src/queue/tests/evidence.rs b/apps/origin-src/src/queue/tests/evidence.rs index e76dce12..006d0635 100644 --- a/apps/origin-src/src/queue/tests/evidence.rs +++ b/apps/origin-src/src/queue/tests/evidence.rs @@ -60,6 +60,35 @@ fn missing_evidence_waits_and_promoted_results_count() { assert_eq!(promoted.issuer, "node:queue".parse().unwrap()); } +#[test] +fn promotes_only_what_the_submitter_sees() { + let repo = Repo::new( + "[targets.main]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"node:ci\" }]\n", + ); + // A result about a revision changing only `secrets`, whose `src` is + // the docs change's. + let hidden = repo.change_on_main(1, &[("secrets/key", "hunter2")]); + repo.annotations() + .issue(&ci_test(hidden, "node:ci"), None) + .unwrap(); + repo.change_on_main(2, &[("docs/guide.md", "# Guide")]); + let secrets = RepoPath::new("secrets").unwrap(); + let blind = PathAccess::new(Level::Write, [(secrets, Level::None)]); + let waiting = repo + .queue() + .submitted_by(blind) + .land_change( + &mut repo.annotations(), + ChangeId::from_bytes([2; 16]), + &TargetName::MAIN, + ) + .unwrap(); + assert!(matches!(waiting[..], [Landing::Pending(_)]), "{waiting:?}"); + // Whoever reads `secrets` lands it with the result promoted. + assert!(matches!(repo.land(2)[..], [Landing::Landed { .. }])); +} + #[test] fn forged_promotions_are_no_evidence() { let repo = requiring_ci(); @@ -107,7 +136,11 @@ fn replaced_results_are_promoted_again() { let id = annotations.issue(&original, None).unwrap(); Annotations::open(&repo.store) .unwrap() - .promote(RecordId::Revision(new), &"node:queue".parse().unwrap()) + .promote( + RecordId::Revision(new), + &"node:queue".parse().unwrap(), + |_| Ok(true), + ) .unwrap(); // The same passing result runs again, replacing the one promoted. let rerun = Statement { diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 801f5fdf..93100034 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -7,6 +7,7 @@ mod policy; mod targets; use origin_platform::Native; +use origin_shared::access::{Level, PathAccess}; use origin_shared::landing::{Blocked, Landing, Pending, Proposal}; use origin_shared::policy::Requirement; use origin_shared::{ diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 41c9a623..34b74104 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -1021,16 +1021,29 @@ impl OriginService { /// Lands what `request` proposes, with this node as the authority: a /// change with the changes below it the target doesn't have yet, or /// another target's tip. A change lands by default on the target its - /// stack is on. + /// stack is on. The caller must be signed in, may land on the target, + /// and must write every path the landing changes on it. /// /// # Errors /// /// Fails if the change or a target doesn't exist, a target was given - /// no target to land on, this node isn't the target's authority, the - /// change can't land as it is (see [`LandError`]), or the records - /// cannot be read or written. - pub fn land(&self, _caller: &Caller, request: &LandRequest) -> Result { - let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()); + /// no target to land on, the caller may not land there, this node isn't + /// the target's authority, the change can't land as it is (see + /// [`LandError`]), or the records cannot be read or written. + pub fn land(&self, caller: &Caller, request: &LandRequest) -> Result { + if *caller == Caller::Anonymous { + return Err(Forbidden::Anonymous.into()); + } + let rights = self.rights(caller)?; + let may_land = |onto: &TargetName| { + if rights.may_land(onto) { + Ok(()) + } else { + Err(ServiceError::from(Forbidden::Land(onto.clone()))) + } + }; + let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()) + .submitted_by(rights.paths.clone()); let landed = self.annotations(|annotations| { let landed = match &request.proposal { Proposal::Change(change) => { @@ -1038,11 +1051,13 @@ impl OriginService { Some(onto) => onto.clone(), None => self.target_of(annotations.index(), *change)?, }; + may_land(&onto)?; let landings = queue.land_change(annotations, *change, &onto)?; Landings { onto, landings } } Proposal::Target(source) => { let onto = request.onto.clone().ok_or(ServiceError::NoTarget)?; + may_land(&onto)?; let landing = queue.land_target(annotations, source, &onto)?; Landings { onto, @@ -1093,18 +1108,24 @@ impl OriginService { } /// Creates a target at the tip of another, with this node as its - /// authority. + /// authority. The caller must be signed in, and may land on it. /// /// # Errors /// - /// Fails if the name is taken, the other target doesn't exist, the - /// policy wouldn't make this node the new target's authority, or the - /// records cannot be written. + /// Fails if the caller may not land on the target, the name is taken, + /// the other target doesn't exist, the policy wouldn't make this node + /// the new target's authority, or the records cannot be written. pub fn create_target( &self, - _caller: &Caller, + caller: &Caller, request: &NewTarget, ) -> Result { + if *caller == Caller::Anonymous { + return Err(Forbidden::Anonymous.into()); + } + if !self.rights(caller)?.may_land(&request.name) { + return Err(Forbidden::Land(request.name.clone()).into()); + } let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()); let head = queue.create_target(&request.name, &request.from)?; self.wakeup.notify(); @@ -1389,6 +1410,7 @@ impl ServiceError { | LandError::Abandoned(_) | LandError::Unresolved { .. } | LandError::InvalidPolicy(_) => ErrorCode::Conflict, + LandError::Forbidden(_) => ErrorCode::Forbidden, LandError::Store(error) => Self::store_code(error), LandError::Policy(_) | LandError::Annotate(_) => ErrorCode::Internal, }, diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index 89d8abdb..a65f7e9c 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -334,7 +334,10 @@ impl Workspace { let working_copy = self.refresh()?; let revision = working_copy.find_revision(rev)?; let mut annotations = Annotations::new(&self.store, working_copy.index); - let promoted = annotations.promote(RecordId::Revision(revision), &self.node_principal())?; + let promoted = + annotations.promote(RecordId::Revision(revision), &self.node_principal(), |_| { + Ok(true) + })?; if promoted.is_empty() { println!("Nothing to promote to revision {}", revision.short()); } diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 6320fc73..aac0fa71 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -878,10 +878,18 @@ async fn tells_callers_what_they_may_do_and_issues_narrower_tokens() { .unwrap_err(); assert_eq!(code(error), ErrorCode::Forbidden); - // The agent proposes changes to `src`. + // The agent proposes changes to `src`, and lands nothing. let base = main_tip(&server.strict).await; let in_src = Made::nested(change(1), base, &[("src/lib.rs", "fn a() {}")]); agent.put_records(&in_src.pack()).await.unwrap(); + let land = LandRequest { + proposal: Proposal::Change(change(1)), + onto: None, + }; + assert_eq!( + code(agent.land(&land).await.unwrap_err()), + ErrorCode::Forbidden + ); // Anonymous callers only read. let error = server .anonymous