diff --git a/apps/origin-src/src/policy.rs b/apps/origin-src/src/policy.rs index d25a9ae9..61a67b6f 100644 --- a/apps/origin-src/src/policy.rs +++ b/apps/origin-src/src/policy.rs @@ -33,8 +33,8 @@ use std::str::FromStr; use origin_platform::Platform; use origin_shared::{ - AcceptanceId, EncodedObject, EntryKind, EntryName, Kind, NodePublicKey, Principal, - PrincipalName, Record, RepoPath, TargetName, Tree, TreeEntry, TreeId, Verdict, + AcceptanceBody, AcceptanceId, EncodedObject, EntryKind, EntryName, Kind, NodePublicKey, + Principal, PrincipalName, Record, RepoPath, TargetName, Tree, TreeEntry, TreeId, Verdict, }; use serde::Deserialize; @@ -112,6 +112,30 @@ impl Policy { /// The file holding the policy, at the root of the `policy` target. pub const FILE: &str = "policy.toml"; + /// The acceptance of `policy` whose `policy.toml` governs the acceptance + /// `body`, `id`: who must have signed it, and what it had to meet. An + /// acceptance of `policy` is governed by the one before it, which it + /// must name, so a policy never authorizes its own landing. Only the + /// first, which has none before it, is governed by its own. Any other + /// acceptance is governed by the policy it names, which the caller + /// checks is on `policy`'s chain. The landing queue checks what it + /// signs with it, and so must whatever verifies a chain. + /// + /// # Errors + /// + /// Fails if the acceptance names another policy than that rule's, or + /// none. + pub fn governing(id: AcceptanceId, body: &AcceptanceBody) -> Result { + if body.target != TargetName::POLICY.id() { + return body.policy.ok_or(PolicyError::Unnamed(body.seq)); + } + match (body.prev, body.policy) { + (None, None) => Ok(id), + (Some(prev), Some(policy)) if policy == prev => Ok(prev), + _ => Err(PolicyError::NotPredecessor(body.seq)), + } + } + /// The policy in force, at the head of the `policy` target, and the /// acceptance holding it. /// @@ -478,6 +502,14 @@ pub enum PolicyError { /// What is wrong, boxed: it's large, and rare. source: Box, }, + /// An acceptance of `policy`, at this sequence number, names another + /// policy than the acceptance before it. + #[error("acceptance #{0} of `policy` names another policy than the one before it")] + NotPredecessor(u64), + /// An acceptance of another target, at this sequence number, names no + /// policy. + #[error("acceptance #{0} names no policy")] + Unnamed(u64), } #[cfg(test)] diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index df85fd3d..df84d1f9 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -16,11 +16,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. 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. +//! 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) +//! 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. //! 4. **Missing evidence** leaves the landing waiting, until the statements //! are issued and the landing is retried. //! 5. **Otherwise** this node signs an acceptance naming what landed, the @@ -260,7 +261,14 @@ impl<'a, P: Platform> Queue<'a, P> { .store .head(onto)? .ok_or_else(|| LandError::UnknownTarget(onto.clone()))?; - let (policy_head, policy) = Policy::in_force(self.store)?; + // A landing on `policy` is governed by the acceptance before it: its + // tip, whatever the policy it lands says. + let (policy_head, policy) = if *onto == TargetName::POLICY { + let state = self.store.get(tip.acceptance)?.body().state; + (tip.acceptance, Self::check_policy(self.store, state)?) + } else { + Policy::in_force(self.store)? + }; self.authorize(&policy, onto)?; Ok(Session { queue: self, diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index f1b72268..1bf71cb6 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -12,7 +12,7 @@ use origin_shared::{ use crate::annotations::{AnnotateError, Annotations, Claim}; use crate::conflict::Conflicts; -use crate::policy::{Policy, Requirement}; +use crate::policy::{Policy, PolicyError, Requirement}; use crate::store::{Store, StoreError}; use crate::targets::Head; @@ -190,6 +190,14 @@ impl Session<'_, '_, P> { if !candidate.trees.is_empty() { store.write_all(&candidate.trees)?; } + // 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 { + self.queue.authorize(&self.policy, &self.onto)?; + Some(Queue::check_policy(store, candidate.state)?) + } else { + None + }; let mut records: Vec = candidate.revision.into_iter().collect(); let requirements = self.policy.requirements(&self.onto).to_vec(); let mut evidence = Vec::new(); @@ -237,7 +245,11 @@ impl Session<'_, '_, P> { policy: Some(self.policy_head), } .sign(self.queue.key); - records.push(acceptance.encode()); + let encoded = acceptance.encode(); + if Policy::governing(encoded.id().into(), acceptance.body())? != self.policy_head { + return Err(PolicyError::NotPredecessor(acceptance.body().seq).into()); + } + records.push(encoded); store.write_all(&records)?; let id = store.append(&self.onto, &acceptance)?; self.tip = Head { @@ -245,6 +257,10 @@ impl Session<'_, '_, P> { acceptance: id, }; self.state = candidate.state; + if let Some(policy) = landed_policy { + self.policy = policy; + self.policy_head = id; + } Ok(Landing::Landed { proposal: candidate.proposal, source: candidate.source, diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 5dddd237..5da053ef 100644 --- a/apps/origin-src/src/queue/tests/mod.rs +++ b/apps/origin-src/src/queue/tests/mod.rs @@ -3,6 +3,7 @@ mod changes; mod conflicts; mod evidence; +mod policy; use origin_platform::Native; use origin_shared::{ @@ -14,6 +15,7 @@ use origin_shared::{ use super::*; use crate::annotations::Annotations; use crate::conflict::Conflicts; +use crate::policy::{Policy, PolicyError}; use crate::store::Store; use crate::targets::Head; use crate::tree::tests::build; diff --git a/apps/origin-src/src/queue/tests/policy.rs b/apps/origin-src/src/queue/tests/policy.rs new file mode 100644 index 00000000..bb3cd9af --- /dev/null +++ b/apps/origin-src/src/queue/tests/policy.rs @@ -0,0 +1,97 @@ +//! Landing on `policy`, and collection while landings wait. + +use origin_shared::BlobId; + +use super::*; + +#[test] +fn policy_landings_keep_a_valid_policy() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let policy = TargetName::POLICY; + let tip = Base::Acceptance(repo.tip(&policy).acceptance); + for (change, toml) in [(1, "not = [valid"), (2, "[nodes]\n")] { + repo.revision(change, &[], tip, &[("policy.toml", toml)]); + let result = repo + .queue() + .land_change(ChangeId::from_bytes([change; 16]), &policy); + assert!( + matches!( + result, + Err(LandError::InvalidPolicy(_) | LandError::NoAuthority(_)) + ), + "{result:?}" + ); + } + // A valid edit lands, and later landings are under it. + let requiring = repo.policy_toml( + "[targets.main]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"review\", verdict = \"pass\", issuer = \"user:bob\" }]\n", + ); + let encoded = Revision { + change: ChangeId::from_bytes([3; 16]), + predecessors: Vec::new(), + base: tip, + deps: Vec::new(), + snapshot: repo.files(&[("policy.toml", &requiring)]), + description: BlobId::from(EncodedObject::blob(b"").id()), + author: "user:ada".parse().unwrap(), + } + .encode(); + repo.store + .write_all(std::slice::from_ref(&encoded)) + .unwrap(); + let landings = repo + .queue() + .land_change(ChangeId::from_bytes([3; 16]), &policy) + .unwrap(); + assert!( + matches!(landings[..], [Landing::Landed { .. }]), + "{landings:?}" + ); + repo.change_on_main(4, &[("a", "a")]); + assert!(matches!(repo.land(4)[..], [Landing::Pending(_)])); +} + +#[test] +fn each_policy_landing_is_governed_by_the_one_before() { + let repo = Repo::new("[targets.main]\nauthority = \"node:queue\"\n"); + let policy = TargetName::POLICY; + // The first edit requires a review to land on `policy`; the second, + // stacked on it, must then wait for one. + let requiring = repo + .policy_toml("[targets.main]\nauthority = \"node:queue\"\n") + .replace( + "[targets.policy]\nauthority = \"node:queue\"\n", + "[targets.policy]\nauthority = \"node:queue\"\n\ + require = [{ kind = \"review\", verdict = \"pass\", issuer = \"user:bob\" }]\n", + ); + let first = repo.revision( + 1, + &[], + Base::Acceptance(repo.tip(&policy).acceptance), + &[("policy.toml", &requiring)], + ); + let open = repo.policy_toml("[targets.main]\nauthority = \"node:queue\"\n"); + repo.revision(2, &[], Base::Revision(first), &[("policy.toml", &open)]); + let landings = repo + .queue() + .land_change(ChangeId::from_bytes([2; 16]), &policy) + .unwrap(); + assert_eq!(landed(&landings[0]), first); + assert!(matches!(landings[1], Landing::Pending(_)), "{landings:?}"); + + let log = repo.store.log(&policy).unwrap(); + for (seq, &id) in log.iter().enumerate() { + let body = repo.store.get(id).unwrap().body().clone(); + let governing = Policy::governing(id, &body).unwrap(); + assert_eq!(governing, if seq == 0 { id } else { log[seq - 1] }); + } + // An acceptance naming any other policy than the one before it is + // refused, its own included. + let mut body = repo.store.get(log[1]).unwrap().body().clone(); + body.policy = Some(log[1]); + assert!(matches!( + Policy::governing(log[1], &body), + Err(PolicyError::NotPredecessor(1)) + )); +}