From fa4a849b3fa573ac86f67cf13bdd828c022d9064 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:52 +0100 Subject: [PATCH] feat(permissions): check the statements each caller puts Any caller could put any statement: a review in another's name, a result of a kind only CI issues, a statement about a revision they can't read, or a promotion copying a result they may not see. Puts now go through `permissions::Writer` for a signed-in caller, and anonymous callers only read. A statement's issuer must be the caller, its kind one they annotate, a promotion's too, and they must see what it's about, and for a promotion, its original. Reserved kinds come only from whom the policy names, whoever puts them: an `admin` token narrowed out of `admin` abandons nothing. A record that carries an attachment the repository has brings it, so no one reads one by naming its id. The records of a batch are read before the store's, so a batch can hold revisions and statements about them. Pushes share only the user's own statements: others' are theirs to share, and the remote finds this node's, like divergence, itself. --- AGENTS.md | 11 +- README.md | 11 +- apps/origin-src/benches/sync.rs | 45 ++- apps/origin-src/src/annotations/mod.rs | 3 +- apps/origin-src/src/permissions.rs | 467 +++++++++++++++++++++++- apps/origin-src/src/server.rs | 4 +- apps/origin-src/src/service.rs | 227 ++++++++---- apps/origin-src/src/sync.rs | 31 +- apps/origin-src/src/workspace/remote.rs | 11 +- apps/origin-src/tests/http.rs | 34 +- 10 files changed, 728 insertions(+), 116 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 48642239..d7939542 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,16 +21,13 @@ review bots read and write at the same time, written in Rust. the HTTP routes (`http.rs`) and the command line's commands that the API offers only translate into its calls, so neither duplicates the other. `sync.rs` shares records with a remote (`remote.rs`), which answers the - same calls over the SDK or, for a local path, in-process. + same calls over the SDK or, for a local path, in-process. Every call + takes a `Caller`, authenticated by `auth.rs`; `permissions.rs` filters + what it reads and checks what it writes, by the rights `policy.rs` + resolves from `policy.toml`. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). -## API changes - -Every server feature lives in `OriginService`; transports like HTTP only -translate requests. A new HTTP endpoint also takes a line in the SDK's -`endpoints!` macro, and `just openapi` to update `docs/openapi.json`. - ## Testing & Benchmarks Performance is a primary goal, so benchmarks matter as much as tests. A change diff --git a/README.md b/README.md index 76a80d0f..a207a818 100644 --- a/README.md +++ b/README.md @@ -117,14 +117,6 @@ send each server under `[tokens]`, by its URL (`"http://127.0.0.1:7878" = ""`), or in `$ORIGIN_TOKEN`. See [the design](docs/design.md) for the model. -`origin token issue --scope ... --ttl ` asks the remote -for a token acting for you with a narrower scope, such as `write src`, -`read /`, `annotate ci.*`, `land main` or `admin`; the server verifies it -without storing it. A server's operator signs one for any principal with -`origin token issue --config origin-server.toml --as user:agent-1 --scope -...`. A token never grants more than its principal's rights, lasts at most -7 days, and a token issued with a token expires with it. - `converge` merges the files of a change's heads. A text file two heads changed holds both versions between conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`), and a binary one keeps one side. A `core.conflict` statement @@ -175,7 +167,8 @@ cursor of another log, such as from before the repository was restored, is refused as expired. [`docs/openapi.json`](docs/openapi.json) describes it, and [`origin-client`](crates/origin-client) is its Rust SDK. Callers send -`Authorization: Bearer `; without one, they are anonymous. +`Authorization: Bearer `; without one, they are anonymous, and only +read what everyone may. ## Development diff --git a/apps/origin-src/benches/sync.rs b/apps/origin-src/benches/sync.rs index bc977f0a..b2efd1e2 100644 --- a/apps/origin-src/benches/sync.rs +++ b/apps/origin-src/benches/sync.rs @@ -15,7 +15,7 @@ use origin_shared::api::LandRequest; use origin_shared::landing::{Landing, Proposal}; use origin_shared::pack::Pack; use origin_shared::{ - Base, ChangeId, EncodedObject, Kind, NodeKey, Record, RecordId, Revision, Statement, + Base, ChangeId, EncodedObject, Kind, NodeKey, Principal, Record, RecordId, Revision, Statement, TargetName, TreeId, Verdict, }; use origin_src::auth::{Credentials, StaticTokens}; @@ -100,7 +100,7 @@ static SETUP: LazyLock = LazyLock::new(|| { let store = Store::new(client.path().join(".origin"), Native::default()); store.init().unwrap(); let remote = Remote::open(&url, node.clone(), Some("bench".to_owned())).unwrap(); - let sync = Sync::new(&store, &remote, "laptop".parse().unwrap()); + let sync = Sync::new(&store, &remote, "laptop".parse().unwrap(), bench_user()); sync.fetch_chains(&[TargetName::MAIN]).unwrap(); sync.need(tip.into(), &[]).unwrap(); // The client knows the records, as a fetch would have brought them. @@ -186,6 +186,11 @@ impl Setup { } } +/// The user the benchmarks push as. +fn bench_user() -> Principal { + "user:bench".parse().unwrap() +} + /// The snapshot a clone fetches: every file, into an empty repository. #[divan::bench(sample_count = 10)] fn clone_snapshot(bencher: Bencher<'_, '_>) { @@ -206,7 +211,7 @@ fn clone_snapshot(bencher: Bencher<'_, '_>) { (dir, store) }) .bench_local_refs(|(_, store)| { - let sync = Sync::new(store, &remote, "laptop".parse().unwrap()); + let sync = Sync::new(store, &remote, "laptop".parse().unwrap(), bench_user()); assert!(sync.need(setup.tip.into(), &[]).unwrap()); }); } @@ -217,7 +222,12 @@ fn clone_snapshot(bencher: Bencher<'_, '_>) { fn fetch_100_edited(bencher: Bencher<'_, '_>) { let setup = &*SETUP; let remote = setup.remote(); - let sync = Sync::new(&setup.client, &remote, "laptop".parse().unwrap()); + let sync = Sync::new( + &setup.client, + &remote, + "laptop".parse().unwrap(), + bench_user(), + ); let next = AtomicUsize::new(0); bencher .with_inputs(|| setup.theirs[next.fetch_add(1, Ordering::Relaxed) % SAMPLES as usize]) @@ -232,7 +242,12 @@ fn fetch_100_edited(bencher: Bencher<'_, '_>) { fn push_100_edited(bencher: Bencher<'_, '_>) { let setup = &*SETUP; let remote = setup.remote(); - let sync = Sync::new(&setup.client, &remote, "laptop".parse().unwrap()); + let sync = Sync::new( + &setup.client, + &remote, + "laptop".parse().unwrap(), + bench_user(), + ); let next = AtomicUsize::new(0); bencher .with_inputs(|| { @@ -286,14 +301,14 @@ static HISTORY_SETUP: LazyLock = LazyLock::new(|| { deps: Vec::new(), snapshot: state, description: description.id().into(), - author: "user:bench".parse().unwrap(), + author: bench_user(), } .encode(); let statement = Statement { subject: RecordId::Revision(revision.id().into()), kind: Kind::new("ci.test").unwrap(), verdict: Some(Verdict::Pass), - issuer: "user:bench".parse().unwrap(), + issuer: bench_user(), inputs: None, payload: None, supersedes: None, @@ -311,7 +326,7 @@ static HISTORY_SETUP: LazyLock = LazyLock::new(|| { let store = Store::new(client.path().join(".origin"), Native::default()); store.init().unwrap(); let remote = Remote::open(&url, node, Some("bench".to_owned())).unwrap(); - let sync = Sync::new(&store, &remote, "laptop".parse().unwrap()); + let sync = Sync::new(&store, &remote, "laptop".parse().unwrap(), bench_user()); let fetch = sync.fetch(&[TargetName::MAIN], &changes, None).unwrap(); assert_eq!(fetch.fetched.revisions, HISTORY as usize); let cursor = fetch.cursor; @@ -330,7 +345,12 @@ static HISTORY_SETUP: LazyLock = LazyLock::new(|| { #[divan::bench(sample_count = 20)] fn fetch_unchanged(bencher: Bencher<'_, '_>) { let history = &*HISTORY_SETUP; - let sync = Sync::new(&history.client, &history.remote, "laptop".parse().unwrap()); + let sync = Sync::new( + &history.client, + &history.remote, + "laptop".parse().unwrap(), + bench_user(), + ); bencher.bench_local(|| { let fetch = sync.fetch(&[], &[], Some(&history.cursor)).unwrap(); assert_eq!(fetch.fetched, Fetched::default()); @@ -342,7 +362,12 @@ fn fetch_unchanged(bencher: Bencher<'_, '_>) { #[divan::bench(sample_count = 10)] fn fetch_unchanged_without_cursor(bencher: Bencher<'_, '_>) { let history = &*HISTORY_SETUP; - let sync = Sync::new(&history.client, &history.remote, "laptop".parse().unwrap()); + let sync = Sync::new( + &history.client, + &history.remote, + "laptop".parse().unwrap(), + bench_user(), + ); bencher.bench_local(|| { let fetch = sync.fetch(&[], &[], None).unwrap(); assert_eq!(fetch.fetched, Fetched::default()); diff --git a/apps/origin-src/src/annotations/mod.rs b/apps/origin-src/src/annotations/mod.rs index b3ede0d2..66aaee6b 100644 --- a/apps/origin-src/src/annotations/mod.rs +++ b/apps/origin-src/src/annotations/mod.rs @@ -284,7 +284,8 @@ impl<'a, P: Platform> Annotations<'a, P> { } /// Where the revisions are read that decide who may issue a reserved kind: -/// a store. +/// a store, or a batch being put along with what its store has, so a +/// statement can be about a revision of the same batch. pub trait RevisionView { /// The revision `id`. /// diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index 80e4af49..26dfc65b 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -1,20 +1,37 @@ -//! Enforcing what callers may do, as their -//! [`Rights`](origin_shared::access::Rights) say: what they read -//! of a repository's records. +//! Enforcing what callers may do, as their [`Rights`] say: what they read +//! of a repository's records, and what the records they put may hold. //! //! **Reading.** A caller who reads no path doesn't see the repository at //! all. Otherwise they see its targets and acceptances, every revision that //! changes a path they read, or changes nothing, and the statements about //! what they see. Snapshots withhold the content of the paths they don't //! read (see [`Store::added`]). +//! +//! **Writing.** Anonymous callers only read. A record put is attributed to +//! its caller: a revision's author and a statement's issuer must be them. +//! A statement's kind must be one they annotate, a promotion's too, but +//! for the reserved kinds, whose authors the [policy](crate::policy::Policy::authorizes) +//! names for every caller; and they must see what it's about, and for a promotion, its original: so no +//! one copies a result they can't read. +//! +//! No one reads an attachment by naming its id: a record that carries one +//! the repository has, as a description or a payload, brings it, but for +//! a promotion, which carries its original's. The records of a batch are +//! read before the store's (see [`Batch`]), so a batch may hold revisions +//! and statements about them; those it brings anew are the caller's to +//! see, but not one the store had. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::iter; use origin_platform::Platform; -use origin_shared::access::{Capability, PathAccess}; +use origin_shared::access::{Capability, PathAccess, Rights}; use origin_shared::event::EventKind; -use origin_shared::{Principal, RecordId, RepoPath, Revision, RevisionId}; +use origin_shared::{ + Kind, Object, ObjectId, Principal, RecordId, RepoPath, Revision, RevisionId, Statement, +}; +use crate::annotations::RevisionView; use crate::store::{Store, StoreError}; /// Who calls the service. @@ -138,29 +155,196 @@ impl<'a, P: Platform> Reader<'a, P> { } } +/// The records a batch puts, read before those of the store it's put in, +/// so a record may refer to another of the same batch. +pub struct Batch<'a, P> { + store: &'a Store

, + /// Every object of the batch. + supplied: HashSet, + revisions: HashMap, +} + +impl<'a, P: Platform> Batch<'a, P> { + /// The batch of `supplied`, whose records `decoded` are, put in `store`. + pub fn new( + store: &'a Store

, + supplied: HashSet, + decoded: &'a [(ObjectId, Object)], + ) -> Self { + let mut batch = Self { + store, + supplied, + revisions: HashMap::new(), + }; + for (id, object) in decoded { + if let Object::Revision(revision) = object { + batch.revisions.insert((*id).into(), revision); + } + } + batch + } + + /// Whether the batch holds `record`. + fn holds(&self, record: RecordId) -> bool { + self.supplied.contains(&record.into()) + } +} + +impl RevisionView for Batch<'_, P> { + fn revision(&self, id: RevisionId) -> Result { + match self.revisions.get(&id) { + Some(&revision) => Ok(revision.clone()), + None => self.store.get(id), + } + } +} + +/// Checks the records of a batch an authenticated caller puts, as the +/// module explains. +pub struct Writer<'a, P> { + batch: &'a Batch<'a, P>, + principal: &'a Principal, + rights: &'a Rights, + reader: Reader<'a, P>, +} + +impl<'a, P: Platform> Writer<'a, P> { + /// Checks `batch` for `principal`, with `rights`. + #[must_use] + pub fn new(batch: &'a Batch<'a, P>, principal: &'a Principal, rights: &'a Rights) -> Self { + Self { + batch, + principal, + rights, + reader: Reader::new(batch.store, &rights.paths), + } + } + + /// Whether the caller sees `record`: the batch's new records are + /// theirs, but one the store had only if they saw it already. + fn sees(&mut self, record: RecordId) -> Result { + let new = self.batch.holds(record) && !self.batch.store.contains(record.into())?; + Ok(new || self.reader.sees(record)?) + } + + /// Checks that `attachment`, which a `record` carries, comes with the + /// batch if the store has it, unless the caller reads every path: so no + /// one reads an attachment by naming its id. + fn brings(&self, record: &'static str, attachment: ObjectId) -> Result<(), PutError> { + if self.rights.paths.reads_all() + || self.batch.supplied.contains(&attachment) + || !self.batch.store.contains(attachment)? + { + return Ok(()); + } + Err(Forbidden::UnsuppliedAttachment { record, attachment }.into()) + } + + /// Checks a statement put. + /// + /// # Errors + /// + /// Fails if the caller isn't its issuer, may not issue its kind, or + /// doesn't see what it's about or the original it promotes, or if a + /// record cannot be read. + pub fn statement(&mut self, statement: &Statement) -> Result<(), PutError> { + if statement.issuer != *self.principal { + return Err(Forbidden::NotYours { + record: "statement", + by: statement.issuer.clone(), + caller: self.principal.clone(), + } + .into()); + } + // Reserved kinds have authors of their own, which the service + // checks for every caller. + if !statement.kind.is_reserved() && !self.rights.may_annotate(&statement.kind) { + return Err(Forbidden::Annotate(statement.kind.clone()).into()); + } + let original = statement.promoted_from.map(RecordId::Statement); + for record in iter::once(statement.subject).chain(original) { + if !self.sees(record)? { + return Err(PutError::Unseen(record)); + } + } + // A promotion carries its original's, which they see. + if original.is_none() + && let Some(payload) = statement.payload + { + self.brings("statement", payload.into())?; + } + Ok(()) + } +} + /// Something a caller may not do. #[derive(Debug, PartialEq, Eq, thiserror::Error)] pub enum Forbidden { + /// An anonymous caller tried to write. + #[error("anonymous callers only read: sign in with a token")] + Anonymous, /// The owner has no principal to issue a token for. #[error("only a signed-in caller gets a token, for themselves")] NoPrincipal, + /// A record put is attributed to someone else. + #[error("the {record} is by {by}, but you are {caller}")] + NotYours { + /// The kind of record. + record: &'static str, + /// Who it names. + by: Principal, + /// The caller. + caller: Principal, + }, + /// A statement of a kind the caller may not issue. + #[error("you may not issue `{0}` statements")] + Annotate(Kind), /// A path the caller may not read. #[error("you may not read `{0}`")] Read(RepoPath), + /// A record carries an attachment the repository has, as a revision's + /// description or a statement's payload, that its writer didn't bring. + #[error("the {record} carries attachment {attachment}, which it doesn't bring")] + UnsuppliedAttachment { + /// The kind of record. + record: &'static str, + /// The attachment. + attachment: ObjectId, + }, /// 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), } +/// A failure to check a record put. +#[derive(Debug, thiserror::Error)] +pub enum PutError { + /// The caller may not put it. + #[error(transparent)] + Forbidden(#[from] Forbidden), + /// A statement is about a record the caller doesn't see, or promotes + /// one: to them, it doesn't exist. + #[error("record {0} not found")] + Unseen(RecordId), + /// A record or tree cannot be read. + #[error(transparent)] + Store(#[from] StoreError), +} + #[cfg(test)] mod tests { use std::sync::Arc; - use origin_shared::{NodeKey, TargetName}; + use origin_shared::pack::Pack; + use origin_shared::{ + AttachmentId, Base, ChangeId, EncodedObject, NodeKey, ObjectKind, Record, Revision, + Statement, TargetName, TreeEntry, TreeId, + }; use super::*; use crate::queue::tests::Repo; use crate::service::{Node, OriginService, ServiceError}; + use crate::tree::Snapshots; /// Ada writes everything and changes the rules. Eve reads all but /// `secrets`, writes only `src`, and issues reviews and checks. Both @@ -213,6 +397,50 @@ grants = { all = "none", "user:ada" = "write" } let service = OriginService::new(repo.store.clone(), node); Self { repo, service } } + + fn tip(&self, target: &TargetName) -> Base { + Base::Acceptance(self.repo.tip(target).acceptance) + } + + fn state(&self, target: &TargetName) -> TreeId { + self.repo.store.base_snapshot(self.tip(target)).unwrap() + } + + /// A revision of `change` by `author` with `snapshot` on `base`, and + /// its description. + fn revision( + change: u8, + author: &str, + base: Base, + predecessors: Vec, + snapshot: TreeId, + ) -> (RevisionId, Vec) { + let description = EncodedObject::attachment(b"work"); + let revision = Revision { + change: ChangeId::from_bytes([change; 16]), + predecessors, + base, + deps: Vec::new(), + snapshot, + description: description.id().into(), + author: author.parse().unwrap(), + } + .encode(); + (revision.id().into(), vec![description, revision]) + } + + fn put(&self, caller: &Caller, objects: Vec) -> Result<(), ServiceError> { + self.service + .put_records(caller, Pack { objects }) + .map(|_| ()) + } + + /// What `main` holds at `path`. + fn at_main(&self, path: &str) -> Option { + Snapshots::new(&self.repo.store) + .entry_at(self.state(&TargetName::MAIN), &RepoPath::new(path).unwrap()) + .unwrap() + } } fn caller(principal: &str) -> Caller { @@ -222,6 +450,109 @@ grants = { all = "none", "user:ada" = "write" } } } + fn forbidden(result: Result) -> Forbidden { + match result { + Err(ServiceError::Forbidden(forbidden)) => forbidden, + other => panic!("expected a refusal, got {other:?}"), + } + } + + fn path(path: &str) -> RepoPath { + RepoPath::new(path).unwrap() + } + + #[test] + fn records_never_carry_a_file_as_their_attachment() { + let fixture = Fixture::new(); + let eve = caller("user:eve"); + let secret = fixture.at_main("secrets/key").unwrap().id; + + // A revision naming the secret's blob as its description is refused: + // descriptions are attachments, which no file is. + let base = fixture.tip(&TargetName::MAIN); + let crafted = Revision { + change: ChangeId::from_bytes([2; 16]), + predecessors: Vec::new(), + base, + deps: Vec::new(), + snapshot: fixture.state(&TargetName::MAIN), + description: AttachmentId::from(secret), + author: "user:eve".parse().unwrap(), + } + .encode(); + let error = fixture.put(&eve, vec![crafted.clone()]).unwrap_err(); + assert!( + matches!( + error, + ServiceError::WrongKind { + kind: ObjectKind::Attachment, + .. + } + ), + "{error}" + ); + let statement = Statement { + subject: RecordId::Revision(fixture.repo.change_on_main(3, &[])), + kind: Kind::new("review").unwrap(), + verdict: None, + issuer: "user:eve".parse().unwrap(), + inputs: None, + payload: Some(AttachmentId::from(secret)), + supersedes: None, + promoted_from: None, + } + .encode(); + let error = fixture.put(&eve, vec![statement]).unwrap_err(); + assert!( + matches!( + error, + ServiceError::WrongKind { + kind: ObjectKind::Attachment, + .. + } + ), + "{error}" + ); + + // And had one got into the store, fetching it never brings the file. + fixture + .repo + .store + .write_all(std::slice::from_ref(&crafted)) + .unwrap(); + let fetched = fixture.service.records(&eve, &[crafted.id()]).unwrap(); + assert_eq!(fetched.pack.objects, [crafted]); + } + + #[test] + fn tokens_narrowed_out_of_admin_abandon_nothing() { + let fixture = Fixture::new(); + let base = fixture.tip(&TargetName::MAIN); + let state = fixture.state(&TargetName::MAIN); + let (eves, records) = Fixture::revision(31, "user:eve", base, Vec::new(), state); + fixture.put(&caller("user:eve"), records).unwrap(); + let abandon = statement(RecordId::Revision(eves), "core.abandon", "user:ada").encode(); + let reader = scoped("user:ada", &["read /"], in_a_week()); + let refused = fixture.put(&reader, vec![abandon.clone()]).unwrap_err(); + assert_eq!(refused.code(), origin_shared::api::ErrorCode::Forbidden); + let admin = scoped("user:ada", &["admin", "read /"], in_a_week()); + fixture.put(&admin, vec![abandon]).unwrap(); + } + + /// A statement by `issuer` of `kind` about `subject`. + fn statement(subject: RecordId, kind: &str, issuer: &str) -> Statement { + Statement { + subject, + kind: Kind::new(kind).unwrap(), + verdict: None, + issuer: issuer.parse().unwrap(), + inputs: None, + payload: None, + supersedes: None, + promoted_from: None, + } + } + /// `caller`, with a token narrowing them to `scope`, expiring at /// `expires`. fn scoped(principal: &str, scope: &[&str], expires: u64) -> Caller { @@ -240,6 +571,128 @@ grants = { all = "none", "user:ada" = "write" } (now.unwrap() + OriginService::MAX_TOKEN_TTL).as_secs() } + #[test] + fn statements_are_attributed_to_their_issuer() { + let fixture = Fixture::new(); + let revision = RecordId::Revision(fixture.repo.change_on_main(2, &[])); + let statement = |issuer: &str, kind: &str| statement(revision, kind, issuer).encode(); + let eve = caller("user:eve"); + assert!(matches!( + forbidden(fixture.put(&eve, vec![statement("user:ada", "review")])), + Forbidden::NotYours { .. } + )); + fixture + .put(&eve, vec![statement("user:eve", "review")]) + .unwrap(); + let scoped = scoped("user:eve", &["annotate ci.*"], in_a_week()); + assert_eq!( + forbidden(fixture.put(&scoped, vec![statement("user:eve", "lint")])), + Forbidden::Annotate(Kind::new("lint").unwrap()) + ); + assert_eq!( + forbidden(fixture.put(&Caller::Anonymous, vec![statement("user:eve", "x")])), + Forbidden::Anonymous + ); + } + + #[test] + fn statements_are_about_what_their_issuer_sees_and_annotates() { + let fixture = Fixture::new(); + let repo = &fixture.repo; + let hidden = RecordId::Revision(repo.change_on_main(2, &[("secrets/key", "new")])); + let visible = RecordId::Revision(repo.change_on_main(3, &[("src/lib.rs", "fn b() {}")])); + let eve = caller("user:eve"); + let unseen = |result: Result<(), ServiceError>| match result { + Err(ServiceError::UnknownRecord(record)) => record, + other => panic!("expected an unknown record, got {other:?}"), + }; + assert_eq!( + unseen(fixture.put(&eve, vec![statement(hidden, "review", "user:eve").encode()])), + hidden + ); + + // Ada's results about both, which every revision of `main` shares. + let result = |subject| { + Statement { + verdict: Some(origin_shared::Verdict::Pass), + inputs: Some(origin_shared::Inputs { + paths: vec![path("README.md")], + definition: origin_shared::Digest::of(b"test"), + toolchain: origin_shared::Digest::of(b""), + external: false, + }), + ..statement(subject, "ci.test", "user:ada") + } + .encode() + }; + let (of_hidden, of_visible) = (result(hidden), result(visible)); + repo.store + .write_all(&[of_hidden.clone(), of_visible.clone()]) + .unwrap(); + let mine = RecordId::Revision(repo.change_on_main(4, &[("src/lib.rs", "fn c() {}")])); + let promotion = |original: &EncodedObject| { + Statement { + subject: mine, + issuer: "user:eve".parse().unwrap(), + promoted_from: Some(original.id().into()), + ..original.decode_as().unwrap() + } + .encode() + }; + + // Promoting claims nothing new, but still needs the kind. + let reviewer = scoped("user:eve", &["annotate review"], in_a_week()); + assert_eq!( + forbidden(fixture.put(&reviewer, vec![promotion(&of_visible)])), + Forbidden::Annotate(Kind::new("ci.test").unwrap()) + ); + // And copies no result eve can't read. + assert_eq!( + unseen(fixture.put(&eve, vec![promotion(&of_hidden)])), + RecordId::Statement(of_hidden.id().into()) + ); + fixture.put(&eve, vec![promotion(&of_visible)]).unwrap(); + + // Nor does she review one, with a statement about it. + let review = |result: &EncodedObject| { + let subject = RecordId::Statement(result.id().into()); + statement(subject, "review", "user:eve").encode() + }; + assert_eq!( + unseen(fixture.put(&eve, vec![review(&of_hidden)])), + RecordId::Statement(of_hidden.id().into()) + ); + fixture.put(&eve, vec![review(&of_visible)]).unwrap(); + } + + #[test] + fn reserved_kinds_come_from_their_authors_whatever_the_caller_annotates() { + let fixture = Fixture::new(); + let theirs = RecordId::Revision(fixture.repo.change_on_main(2, &[])); + let base = fixture.tip(&TargetName::MAIN); + let (mine, records) = Fixture::revision( + 3, + "user:eve", + base, + Vec::new(), + fixture.state(&TargetName::MAIN), + ); + let abandon = |subject| statement(subject, "core.abandon", "user:eve").encode(); + let eve = caller("user:eve"); + let error = fixture.put(&eve, vec![abandon(theirs)]).unwrap_err(); + assert!( + matches!(&error, ServiceError::Statement { source, .. } + if matches!(**source, crate::annotations::AnnotateError::Reserved { .. })), + "{error}" + ); + assert_eq!(error.code(), origin_shared::api::ErrorCode::Forbidden); + // Eve abandons her own change, put with it, though she annotates + // no `core.*`. + let mut batch = records; + batch.push(abandon(RecordId::Revision(mine))); + fixture.put(&eve, batch).unwrap(); + } + #[test] fn callers_who_read_nothing_see_nothing() { let fixture = Fixture::new(); diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs index 4459eaae..c27c0427 100644 --- a/apps/origin-src/src/server.rs +++ b/apps/origin-src/src/server.rs @@ -40,8 +40,8 @@ use crate::store::Store; /// "user:alice" = "a long random secret" /// ``` /// -/// Paths are relative to the file. Callers without a token are anonymous; -/// the server also takes the scoped tokens it signed (see +/// Paths are relative to the file. Callers without a token are anonymous, +/// and only read; the server also takes the scoped tokens it signed (see /// [`ServerConfig::issue_token`]). #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index a4a85b3e..652a33d1 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -15,9 +15,9 @@ //! queue lock. //! //! Every method takes the [`Caller`], whose [`Rights`] the policy in force -//! resolves: what each caller reads is filtered, as -//! [`permissions`](crate::permissions) explains. Nothing they write is -//! checked yet. +//! resolves, and does only what they allow, as +//! [`permissions`](crate::permissions) explains: what each caller reads is +//! filtered, and what they write is checked. use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; @@ -38,15 +38,16 @@ use origin_shared::landing::{Pending, Proposal}; use origin_shared::object::DecodeError; use origin_shared::pack::{Pack, Packer, Part}; use origin_shared::{ - AcceptanceId, Base, ChangeId, Head, Kind, NodeKey, Object, ObjectId, ObjectKind, Principal, - PrincipalName, RecordId, RepoPath, Statement, StatementId, TargetName, TreeEntry, TreeId, + AcceptanceId, Base, ChangeId, EncodedObject, Head, Kind, NodeKey, Object, ObjectId, ObjectKind, + Principal, PrincipalName, RecordId, RepoPath, Statement, StatementId, TargetName, TreeEntry, + TreeId, }; use crate::annotations::{AnnotateError, Annotations}; use crate::events::{Events, Wakeup}; use crate::index::Index; pub use crate::permissions::Caller; -use crate::permissions::{Forbidden, Reader}; +use crate::permissions::{Batch, Forbidden, PutError, Reader, Writer}; use crate::policy::{Policy, PolicyError}; use crate::queue::{LandError, Queue}; use crate::store::{Store, StoreError}; @@ -589,19 +590,28 @@ impl OriginService { /// So the repository never holds a record it cannot use. A payload must /// be an attachment too, if the repository has it, and a /// `core.conflict`'s, its list, must be there. Acceptances are - /// refused: only a target's authority writes them, by landing. The - /// blobs and trees are durable before the records that refer to them, - /// statements before the revisions they're about, and promotions come - /// last, each checked against its original by - /// [`Store::claim`], once the original and both subjects are stored. - /// Issues `core.divergent` for the changes the revisions made diverge. + /// refused: only a target's authority writes them, by landing. A + /// statement of a reserved kind must come from whom + /// [`Policy::authorizes`] names, whoever puts it. The records a caller + /// other than the owner puts must be theirs, about what they see, and + /// may only change what they write, as + /// [`permissions`](crate::permissions) explains. Records are read from + /// the pack before the repository, so a pack may hold a stack. The blobs and trees + /// are durable before the records that refer to them, statements before + /// the revisions they're about, and promotions come last, each checked + /// against its original by [`Store::claim`], + /// once the original and both subjects are stored. Issues + /// `core.divergent` for the changes the revisions made diverge. /// /// # Errors /// - /// Fails if an object is malformed, an acceptance, or needs an object - /// neither the pack nor the repository has, or one of another kind, if - /// a promotion doesn't match its original, which leaves the other - /// records stored, or if the objects cannot be written. + /// Fails if the caller is anonymous, an object is malformed, an + /// acceptance, or needs an object neither the pack nor the repository + /// has, or one of another kind, if the caller may not put a record, or + /// doesn't see what a statement is about, if a reserved kind's issuer + /// may not issue it, if a promotion doesn't match its original, which + /// leaves the other records stored, or if the objects cannot be + /// written. pub fn put_records(&self, caller: &Caller, pack: Pack) -> Result { self.push(caller, pack, &[]) } @@ -624,6 +634,9 @@ impl OriginService { pack: Pack, expect: &[Expected], ) -> Result { + if *caller == Caller::Anonymous { + return Err(Forbidden::Anonymous.into()); + } // Objects this finds stored stay until what refers to them is. let _held = self.store.hold_objects()?; let held: HashMap> = pack @@ -641,13 +654,14 @@ impl OriginService { let mut statements = Vec::new(); let mut revisions = Vec::new(); let mut promotions = Vec::new(); + let mut decoded = Vec::new(); let mut changes = HashSet::new(); for object in pack.objects { let id = object.id(); - let decoded = object + let record = object .decode() .map_err(|source| ServiceError::Malformed { id, source })?; - for (needed, kind) in Dependencies::of(&decoded).all() { + for (needed, kind) in Dependencies::of(&record).all() { match held.get(&needed) { Some(&held) if held != Some(kind) => { return Err(ServiceError::WrongKind { id, needed, kind }); @@ -667,26 +681,33 @@ impl OriginService { None => return Err(ServiceError::Missing { id, needed }), } } - Self::check_payload(id, &decoded, |id| match held.get(&id) { + Self::check_payload(id, &record, |id| match held.get(&id) { Some(&kind) => Ok(kind), - None => Ok(self + // Made durable with the batch, like any dependency. + None if dependencies.depend(id)? => Ok(self .store .try_read(id)? .and_then(|object| object.kind().ok())), + None => Ok(None), })?; - match decoded { + match record { Object::Acceptance(_) => return Err(ServiceError::Acceptance(id.into())), Object::Blob(_) | Object::Tree(_) | Object::Attachment(_) => snapshots.push(object), - Object::Revision(revision) => { + Object::Revision(ref revision) => { if !revision.predecessors.is_empty() { changes.insert(revision.change); } revisions.push(object); + decoded.push((id, record)); } - Object::Statement(statement) if statement.promoted_from.is_some() => { - promotions.push((object, statement)); + Object::Statement(ref statement) if statement.promoted_from.is_some() => { + promotions.push((object, statement.clone())); + decoded.push((id, record)); + } + Object::Statement(_) => { + statements.push(object); + decoded.push((id, record)); } - Object::Statement(_) => statements.push(object), } } self.check_kinds(&stored)?; @@ -695,6 +716,7 @@ impl OriginService { if !snapshots.is_empty() { new += self.store.write_all(&snapshots)?; } + self.check_writes(caller, &held, &decoded)?; // Held until the records are published, so nothing else moves the // changes in between: see `Store::lock_pushes`. let _pushing = if !revisions.is_empty() || !expect.is_empty() { @@ -712,21 +734,7 @@ impl OriginService { new += self.store.write_all(&layer)?; } } - // An original is never a promotion, so it's stored by now. - let mut checked = Vec::new(); - for (object, statement) in promotions { - let id = object.id().into(); - self.store - .claim(id, statement)? - .map_err(|invalid| ServiceError::Statement { - id, - source: Box::new(invalid.into()), - })?; - checked.push(object); - } - if !checked.is_empty() { - new += self.store.write_all(&checked)?; - } + new += self.put_promotions(promotions)?; if !changes.is_empty() { self.annotations(|annotations| { for &change in &changes { @@ -739,29 +747,63 @@ impl OriginService { Ok(Stored { new: new as u64 }) } - /// Checks that each change of `expect` has the heads it names, of those - /// the caller sees. - fn check_heads(&self, caller: &Caller, expect: &[Expected]) -> Result<(), ServiceError> { + /// Checks that the caller may put the records of `decoded`, which a + /// batch of the objects `held` brings: anyone's statements of a + /// reserved kind must come from whom [`Policy::authorizes`] names, and + /// those of a caller other than the owner must be theirs, as + /// [`permissions`](crate::permissions) explains. + fn check_writes( + &self, + caller: &Caller, + held: &HashMap>, + decoded: &[(ObjectId, Object)], + ) -> Result<(), ServiceError> { + let policy = self.policy()?; let rights = self.rights(caller)?; - let mut reader = Reader::new(&self.store, &rights.paths); - self.annotations(|annotations| { - for expected in expect { - let mut heads = Vec::new(); - for head in annotations.index().heads(expected.change) { - if reader.sees(RecordId::Revision(head))? { - heads.push(head); - } - } - let now: HashSet<_> = heads.iter().collect(); - if now != expected.heads.iter().collect() { - return Err(ServiceError::Moved { - change: expected.change, - heads, - }); - } + let batch = Batch::new(&self.store, held.keys().copied().collect(), decoded); + let Some(principal) = caller.principal() else { + return self.check_records(&batch, decoded, None, |issuer| { + policy.rights(Some(issuer)).admin + }); + }; + // A signed-in caller's token may narrow them out of `admin`. + let writer = Writer::new(&batch, principal, &rights); + self.check_records(&batch, decoded, Some(writer), |_| rights.admin) + } + + /// Checks the records of `batch`, `decoded`, as + /// [`OriginService::check_writes`] explains, with `writer`'s checks for + /// a signed-in caller, whose statements' issuers `admin` says are + /// `admin` or not. + fn check_records( + &self, + batch: &Batch<'_, Native>, + decoded: &[(ObjectId, Object)], + mut writer: Option>, + admin: impl Fn(&Principal) -> bool, + ) -> Result<(), ServiceError> { + for (id, record) in decoded { + // Re-putting a record changes nothing. + if self.store.contains(*id)? { + continue; } - Ok(()) - }) + let Object::Statement(statement) = record else { + continue; + }; + if !Policy::authorizes_admin(batch, statement, admin(&statement.issuer))? { + return Err(ServiceError::Statement { + id: (*id).into(), + source: Box::new(AnnotateError::Reserved { + kind: statement.kind.clone(), + issuer: statement.issuer.clone(), + }), + }); + } + if let Some(writer) = &mut writer { + writer.statement(statement)?; + } + } + Ok(()) } /// Checks that each object of `stored`, which the repository has, is of @@ -812,6 +854,55 @@ impl OriginService { } } + /// Checks that each change of `expect` has the heads it names, of those + /// the caller sees. + fn check_heads(&self, caller: &Caller, expect: &[Expected]) -> Result<(), ServiceError> { + let rights = self.rights(caller)?; + let mut reader = Reader::new(&self.store, &rights.paths); + self.annotations(|annotations| { + for expected in expect { + let mut heads = Vec::new(); + for head in annotations.index().heads(expected.change) { + if reader.sees(RecordId::Revision(head))? { + heads.push(head); + } + } + let now: HashSet<_> = heads.iter().collect(); + if now != expected.heads.iter().collect() { + return Err(ServiceError::Moved { + change: expected.change, + heads, + }); + } + } + Ok(()) + }) + } + + /// Writes the `promotions` [`OriginService::put_records`] puts, once + /// [`Store::claim`] accepts each, returning how many were new. Their + /// originals are never promotions, so they're stored by now. + fn put_promotions( + &self, + promotions: Vec<(EncodedObject, Statement)>, + ) -> Result { + let mut checked = Vec::new(); + for (object, statement) in promotions { + let id = object.id().into(); + self.store + .claim(id, statement)? + .map_err(|invalid| ServiceError::Statement { + id, + source: Box::new(invalid.into()), + })?; + checked.push(object); + } + if checked.is_empty() { + return Ok(0); + } + Ok(self.store.write_all(&checked)?) + } + /// The statements about `subject`, in the order the repository received /// them: none if the caller doesn't see it. /// @@ -1221,7 +1312,8 @@ pub enum ServiceError { #[error("the cursor is of another op log, generation {0}: read from the end")] OtherLog(String), /// A statement put isn't one the repository accepts: a promotion that - /// doesn't match its original. + /// doesn't match its original, or a reserved kind from an issuer who + /// may not issue it. #[error("statement {} cannot be put", .id.short())] Statement { /// The statement. @@ -1240,6 +1332,16 @@ pub enum ServiceError { Store(#[from] StoreError), } +impl From for ServiceError { + fn from(error: PutError) -> Self { + match error { + PutError::Forbidden(error) => Self::Forbidden(error), + PutError::Unseen(record) => Self::UnknownRecord(record), + PutError::Store(error) => Self::Store(error), + } + } +} + impl ServiceError { /// What kind of failure it is, for clients to tell apart. #[must_use] @@ -1262,6 +1364,7 @@ impl ServiceError { | Self::Missing { .. } => ErrorCode::BadRequest, Self::Statement { source, .. } => match &**source { AnnotateError::Store(error) => Self::store_code(error), + AnnotateError::Reserved { .. } => ErrorCode::Forbidden, _ => ErrorCode::BadRequest, }, Self::Forbidden(_) => ErrorCode::Forbidden, diff --git a/apps/origin-src/src/sync.rs b/apps/origin-src/src/sync.rs index 657a4af7..ccab6da2 100644 --- a/apps/origin-src/src/sync.rs +++ b/apps/origin-src/src/sync.rs @@ -23,8 +23,8 @@ //! snapshot, its target's tip. A snapshot is marked while it's fetched //! ([`Store::fetching`]), so one whose fetch was interrupted is fetched //! again rather than taken for whole. -//! - **Pushing** shares revisions, with their snapshots, and statements. It -//! never lands anything. It first compares each change's heads with the +//! - **Pushing** shares revisions, with their snapshots, and the user's +//! statements. It never lands anything. It first compares each change's heads with the //! remote's, and refuses before uploading anything when the remote has a //! revision this node lacks: the change is stale. The remote checks the //! heads again as it publishes the revisions, so a push racing another @@ -76,6 +76,8 @@ pub struct Sync<'a> { remote: &'a Remote, /// This node, which flags the divergence fetched revisions reveal. node: Principal, + /// The user, whose statements pushes share. + user: Principal, /// The most bytes a push's request holds: [`Pack::LIMIT`], but in /// tests. pack_limit: usize, @@ -144,7 +146,7 @@ pub struct Pushed { /// Every object sent: those, and the blobs and trees of their /// snapshots the remote lacked. pub objects: usize, - /// The statements that stay here: they need a record the remote + /// The user's statements that stay here: they need a record the remote /// neither has nor got, such as a statement they supersede about /// another change, or the original they promote. pub unsent: Vec, @@ -356,12 +358,13 @@ impl<'a> Sync<'a> { /// server sends. const EVENTS: u32 = 1024; - /// Syncs `store` with `remote`, as the node `node`. - pub fn new(store: &'a Store, remote: &'a Remote, node: PrincipalName) -> Self { + /// Syncs `store` with `remote`, as the node `node`, for `user`. + pub fn new(store: &'a Store, remote: &'a Remote, node: PrincipalName, user: Principal) -> Self { Self { store, remote, node: Principal::Node(node), + user, pack_limit: Pack::LIMIT, } } @@ -1146,10 +1149,12 @@ impl<'a> Sync<'a> { .collect() } - /// The statements about the revisions of `changes`, and about + /// The user's statements about the revisions of `changes`, and about /// statements about them, that the remote lacks, each after those of /// them it needs, adding each to `shared`; and those that need a record - /// that isn't in `shared`, which stay. + /// that isn't in `shared`, which stay. Others' statements are theirs to + /// share, and this node's own, like divergence, the remote finds + /// itself. fn statements( &self, index: &Index, @@ -1172,7 +1177,10 @@ impl<'a> Sync<'a> { if shared.contains(&id.into()) { continue; } - waiting.push((id, self.store.get(id)?)); + let statement = self.store.get(id)?; + if statement.issuer == self.user { + waiting.push((id, statement)); + } } } let mut ordered = Vec::new(); @@ -1477,7 +1485,12 @@ mod tests { } fn sync(&self) -> Sync<'_> { - Sync::new(&self.store, &self.remote, "laptop".parse().unwrap()) + Sync::new( + &self.store, + &self.remote, + "laptop".parse().unwrap(), + "user:ada".parse().unwrap(), + ) } /// Writes a revision of `change` with `files` on `base`, with every diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs index c31d5f3e..92eb9a0f 100644 --- a/apps/origin-src/src/workspace/remote.rs +++ b/apps/origin-src/src/workspace/remote.rs @@ -112,7 +112,7 @@ impl Workspace { let meta = root.join(Self::META_DIR); let store = Store::new(meta, Native::default()).with_actor(actor.in_workspace(&root)); store.init()?; - let sync = Sync::new(&store, &remote, config.node().clone()); + let sync = Sync::new(&store, &remote, config.node().clone(), config.user()); let cursor = sync.moved(None)?.cursor; sync.fetch_chains(slice::from_ref(target))?; let tip = store @@ -227,9 +227,14 @@ impl Workspace { Ok(self.remote.get_or_init(|| remote).as_ref()) } - /// Syncs with `remote`, as this node. + /// Syncs with `remote`, as this node, for its user. pub(super) fn sync<'s>(&'s self, remote: &'s Remote) -> Sync<'s> { - Sync::new(&self.store, remote, self.config.node().clone()) + Sync::new( + &self.store, + remote, + self.config.node().clone(), + self.config.user(), + ) } /// The repository's remote, which the command needs. diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 7c23562b..6320fc73 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -451,7 +451,7 @@ async fn promotions_must_match_their_original() { subject: RecordId::Revision(made.id), kind: Kind::new("ci.test").unwrap(), verdict: Some(Verdict::Pass), - issuer: "user:ci".parse().unwrap(), + issuer: "user:ada".parse().unwrap(), inputs: Some(Inputs { paths: vec!["a.txt".parse().unwrap()], definition: Digest::of(b"test"), @@ -464,7 +464,6 @@ async fn promotions_must_match_their_original() { }; let promotion = Statement { subject: RecordId::Revision(same.id), - issuer: "user:eve".parse().unwrap(), promoted_from: Some(original.encode().id().into()), ..original.clone() }; @@ -736,11 +735,22 @@ async fn landings_wait_for_evidence() { "{page:?}" ); - repo.put_records(&Pack { + // Only `user:ci` issues them, and only as itself. + let forged = Pack { objects: vec![ci_test(made.id, "user:ci")], - }) - .await - .unwrap(); + }; + assert_eq!( + code(repo.put_records(&forged).await.unwrap_err()), + ErrorCode::Forbidden + ); + let own = Pack { + objects: vec![ci_test(made.id, "user:ada")], + }; + assert_eq!( + code(repo.put_records(&own).await.unwrap_err()), + ErrorCode::Forbidden + ); + server.ci.put_records(&forged).await.unwrap(); let landed = repo.land(&land).await.unwrap(); assert!(matches!(landed.landings[..], [Landing::Landed { .. }])); assert_eq!(repo.landings().await.unwrap(), []); @@ -867,6 +877,18 @@ async fn tells_callers_what_they_may_do_and_issues_narrower_tokens() { .await .unwrap_err(); assert_eq!(code(error), ErrorCode::Forbidden); + + // The agent proposes changes to `src`. + 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(); + // Anonymous callers only read. + let error = server + .anonymous + .put_records(&in_src.pack()) + .await + .unwrap_err(); + assert_eq!(code(error), ErrorCode::Forbidden); } #[tokio::test]