From a4152e3a653faa8f9b7b7b48921e2545d14a3bd7 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:38:05 +0100 Subject: [PATCH] refactor(shared): move statement kind patterns, requirements and periods into origin-shared The HTTP API will show what landing on a target requires and take event filters by statement kind, so its clients need the same types the server reads `policy.toml` with: `Requirement`, `Principals` and `KindPattern`, and the periods retention rules are written in. They move to `origin-shared`'s new `policy` module, and `Period` to its `text` module, unchanged but for their errors: parsing a pattern or a principal set now fails with `InvalidName`, and a period with `InvalidPeriod`, so `RetentionError` wraps them instead of formatting its own messages. --- apps/origin-src/src/cli.rs | 2 +- apps/origin-src/src/events.rs | 2 +- apps/origin-src/src/policy.rs | 148 +++-------------------- apps/origin-src/src/queue/mod.rs | 3 +- apps/origin-src/src/queue/pending.rs | 3 +- apps/origin-src/src/queue/session.rs | 3 +- apps/origin-src/src/queue/tests/mod.rs | 3 +- crates/origin-shared/src/lib.rs | 3 + crates/origin-shared/src/policy.rs | 156 +++++++++++++++++++++++++ crates/origin-shared/src/text.rs | 73 ++++++++++++ 10 files changed, 254 insertions(+), 142 deletions(-) create mode 100644 crates/origin-shared/src/policy.rs create mode 100644 crates/origin-shared/src/text.rs diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index cece8cd6..8968d961 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -9,12 +9,12 @@ use std::str::FromStr; use anyhow::{Context, Result}; use clap::error::ErrorKind; use clap::{Args, CommandFactory, Parser, Subcommand}; +use origin_shared::policy::KindPattern; use origin_shared::{Digest, Inputs, Kind, RepoPath, TargetName, Verdict}; use crate::config::UserConfig; use crate::events::Filter; use crate::oplog::Actor; -use crate::policy::KindPattern; use crate::workspace::{Annotated, Payload, Workspace}; /// A modern, git-compatible source control system. diff --git a/apps/origin-src/src/events.rs b/apps/origin-src/src/events.rs index bcec18ca..61cb639c 100644 --- a/apps/origin-src/src/events.rs +++ b/apps/origin-src/src/events.rs @@ -30,6 +30,7 @@ use std::thread; use std::time::{Duration, Instant}; use origin_platform::{Native, Platform}; +use origin_shared::policy::{KindPattern, Requirement}; use origin_shared::{ AcceptanceId, ChangeId, Kind, Object, ObjectId, Principal, RecordId, RevisionId, StatementId, TargetName, Verdict, @@ -37,7 +38,6 @@ use origin_shared::{ use crate::index; use crate::oplog::{Effect, Entry}; -use crate::policy::{KindPattern, Requirement}; use crate::queue::{Blocked, Pending, Queue}; use crate::store::{Store, StoreError}; diff --git a/apps/origin-src/src/policy.rs b/apps/origin-src/src/policy.rs index f119d2a6..6029fc1c 100644 --- a/apps/origin-src/src/policy.rs +++ b/apps/origin-src/src/policy.rs @@ -37,9 +37,11 @@ use std::str::FromStr; use std::time::Duration; use origin_platform::Platform; +use origin_shared::policy::{KindPattern, Principals, Requirement}; use origin_shared::{ - AcceptanceBody, AcceptanceId, EncodedObject, EntryKind, EntryName, Kind, NodePublicKey, - Principal, PrincipalName, Record, RepoPath, TargetName, Tree, TreeEntry, TreeId, Verdict, + AcceptanceBody, AcceptanceId, EncodedObject, EntryKind, EntryName, InvalidName, InvalidPeriod, + Kind, NodePublicKey, Period, Principal, PrincipalName, Record, RepoPath, TargetName, Tree, + TreeEntry, TreeId, }; use serde::Deserialize; @@ -64,28 +66,6 @@ struct TargetRules { require: Vec, } -/// A statement that landing needs: of `kind`, with `verdict`, from one of -/// `issuer`, about what lands. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct Requirement { - /// The statement's kind. - pub kind: Kind, - /// Its verdict. - pub verdict: Verdict, - /// Who may issue it. - pub issuer: Principals, -} - -/// One user or node, or the members of a group: `user:alice`, -/// `node:ci-1` or `group:runners`. -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub enum Principals { - /// A user or a node. - One(Principal), - /// The members of a group of the policy. - Group(PrincipalName), -} - /// A `[[paths]]` rule: what each grantee may do under a path. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PathRule { @@ -401,30 +381,6 @@ impl Policy { } } -impl FromStr for Principals { - type Err = String; - - fn from_str(input: &str) -> Result { - match input.strip_prefix("group:") { - Some(group) => PrincipalName::new(group) - .map(Self::Group) - .map_err(|error| error.to_string()), - None => input.parse().map(Self::One).map_err(|_| { - format!("`{input}` is not `user:`, `node:` or `group:`") - }), - } - } -} - -impl fmt::Display for Principals { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::One(principal) => principal.fmt(f), - Self::Group(group) => write!(f, "group:{group}"), - } - } -} - impl FromStr for Grantee { type Err = String; @@ -452,12 +408,6 @@ impl FromStr for Access { } } -impl fmt::Display for Requirement { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} {} from {}", self.kind, self.verdict, self.issuer) - } -} - /// An invalid rule in `policy.toml`. #[derive(Debug, PartialEq, Eq, thiserror::Error)] pub enum RuleError { @@ -526,20 +476,6 @@ impl Retention { pub fn is_empty(&self) -> bool { self.rules.is_empty() } - - /// Parses a period: a whole number of seconds (`s`), minutes (`m`), - /// hours (`h`) or days (`d`), such as `90d`. - fn parse_period(period: &str) -> Option { - let unit = match period.chars().last()? { - 's' => 1, - 'm' => 60, - 'h' => 60 * 60, - 'd' => 24 * 60 * 60, - _ => return None, - }; - let count: u64 = period[..period.len() - 1].parse().ok()?; - Some(Duration::from_secs(count.checked_mul(unit)?)) - } } impl TryFrom> for Retention { @@ -549,88 +485,30 @@ impl TryFrom> for Retention { let rules = table .into_iter() .map(|(pattern, period)| { - let duration = Self::parse_period(&period) - .ok_or_else(|| RetentionError::Period(period.clone()))?; - let parsed: KindPattern = pattern.parse()?; - if parsed.is_reserved() { + let Period(duration) = period.parse()?; + let pattern: KindPattern = pattern.parse()?; + if pattern.is_reserved() { return Err(RetentionError::Reserved(pattern)); } - Ok((parsed, duration)) + Ok((pattern, duration)) }) .collect::>()?; Ok(Self { rules }) } } -/// Statement kinds, as retention rules and `origin watch --kind` name -/// them. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum KindPattern { - /// `*`: every kind. - Any, - /// `ci.*`: the kinds under a prefix, not the prefix itself. - Prefix(Kind), - /// `ci.test`: one kind. - Exact(Kind), -} - -impl KindPattern { - /// Whether the pattern only matches reserved kinds: `core.*` or one - /// of them. - fn is_reserved(&self) -> bool { - match self { - Self::Any => false, - Self::Prefix(prefix) => prefix.as_str() == "core" || prefix.is_reserved(), - Self::Exact(kind) => kind.is_reserved(), - } - } - - /// Whether the pattern matches `kind`. - #[must_use] - pub fn matches(&self, kind: &Kind) -> bool { - self.specificity(kind).is_some() - } - - /// How specifically the pattern matches `kind`, if it does: longer - /// prefixes beat shorter ones, and the kind itself beats them all. - fn specificity(&self, kind: &Kind) -> Option<(usize, bool)> { - match self { - Self::Any => Some((0, false)), - Self::Prefix(prefix) => kind - .as_str() - .strip_prefix(prefix.as_str()) - .is_some_and(|rest| rest.starts_with('.')) - .then_some((prefix.as_str().len(), false)), - Self::Exact(exact) => (exact == kind).then_some((exact.as_str().len(), true)), - } - } -} - -impl FromStr for KindPattern { - type Err = RetentionError; - - fn from_str(pattern: &str) -> Result { - let invalid = || RetentionError::Pattern(pattern.to_owned()); - match pattern.strip_suffix(".*") { - _ if pattern == "*" => Ok(Self::Any), - Some(prefix) => Kind::new(prefix).map(Self::Prefix).map_err(|_| invalid()), - None => Kind::new(pattern).map(Self::Exact).map_err(|_| invalid()), - } - } -} - /// An invalid `[retention]` rule. #[derive(Debug, PartialEq, Eq, thiserror::Error)] pub enum RetentionError { /// The key is not a kind, a prefix ending in `.*`, or `*`. - #[error("`{0}` is not a statement kind, a prefix like `ci.*`, or `*`")] - Pattern(String), + #[error(transparent)] + Pattern(#[from] InvalidName), /// The value is not a period. - #[error("`{0}` is not a period like `90d`, `12h`, `30m` or `45s`")] - Period(String), + #[error(transparent)] + Period(#[from] InvalidPeriod), /// The rule names reserved kinds, whose payloads are kept. #[error("`{0}` names reserved kinds, whose payloads core reads and always keeps")] - Reserved(String), + Reserved(KindPattern), } /// A failure to read the policy. diff --git a/apps/origin-src/src/queue/mod.rs b/apps/origin-src/src/queue/mod.rs index 22e57c05..ac78672c 100644 --- a/apps/origin-src/src/queue/mod.rs +++ b/apps/origin-src/src/queue/mod.rs @@ -50,6 +50,7 @@ use std::io; use std::path::PathBuf; use origin_platform::{DurableWrite, LockMode, LockedFile, Native, Platform}; +use origin_shared::policy::Requirement; use origin_shared::{ AcceptanceBody, AcceptanceId, ChangeId, EncodedObject, NodeKey, Principal, PrincipalName, Record, RecordId, RepoPath, RevisionId, Source, StatementId, TargetId, TargetName, Tree, @@ -58,7 +59,7 @@ use origin_shared::{ use crate::annotations::{AnnotateError, Annotations}; use crate::conflict::Conflicts; -use crate::policy::{Policy, PolicyError, Requirement}; +use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; use crate::targets::Head; diff --git a/apps/origin-src/src/queue/pending.rs b/apps/origin-src/src/queue/pending.rs index eec2debb..e6554939 100644 --- a/apps/origin-src/src/queue/pending.rs +++ b/apps/origin-src/src/queue/pending.rs @@ -2,8 +2,7 @@ //! until it can continue. use origin_shared::RecordId; - -use crate::policy::Requirement; +use origin_shared::policy::Requirement; use super::{Blocked, Pending, Proposal}; diff --git a/apps/origin-src/src/queue/session.rs b/apps/origin-src/src/queue/session.rs index 75518fd7..aad88580 100644 --- a/apps/origin-src/src/queue/session.rs +++ b/apps/origin-src/src/queue/session.rs @@ -8,6 +8,7 @@ use std::io; use std::path::PathBuf; use origin_platform::{LockedFile, Platform}; +use origin_shared::policy::Requirement; use origin_shared::{ AcceptanceBody, AcceptanceId, Base, ChangeId, EncodedObject, Kind, Record, RecordId, Revision, RevisionId, Source, StatementId, TargetName, TreeId, @@ -17,7 +18,7 @@ use crate::ancestry::Ancestry; use crate::annotations::{AnnotateError, Annotations, Claim}; use crate::conflict::Conflicts; use crate::oplog::Effect; -use crate::policy::{Policy, PolicyError, Requirement}; +use crate::policy::{Policy, PolicyError}; use crate::store::{Store, StoreError}; use crate::targets::Head; diff --git a/apps/origin-src/src/queue/tests/mod.rs b/apps/origin-src/src/queue/tests/mod.rs index 5f38b39f..e1d15705 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::policy::Requirement; use origin_shared::{ AcceptanceBody, Base, BlobId, ChangeId, Digest, EncodedObject, Inputs, Kind, NodeKey, PrincipalName, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, @@ -16,7 +17,7 @@ use origin_shared::{ use super::*; use crate::annotations::Annotations; use crate::conflict::Conflicts; -use crate::policy::{Policy, PolicyError, Requirement}; +use crate::policy::{Policy, PolicyError}; use crate::store::Store; use crate::targets::Head; use crate::tree::tests::build; diff --git a/crates/origin-shared/src/lib.rs b/crates/origin-shared/src/lib.rs index ed378d3e..b26a12cc 100644 --- a/crates/origin-shared/src/lib.rs +++ b/crates/origin-shared/src/lib.rs @@ -5,8 +5,10 @@ mod id; mod name; pub mod object; mod path; +pub mod policy; mod principal; mod target; +mod text; pub use id::{ AcceptanceId, BlobId, ChangeId, Digest, ObjectId, ParseIdError, RevisionId, StatementId, @@ -21,3 +23,4 @@ pub use object::{ pub use path::RepoPath; pub use principal::{Principal, PrincipalName}; pub use target::TargetName; +pub use text::{InvalidPeriod, Period}; diff --git a/crates/origin-shared/src/policy.rs b/crates/origin-shared/src/policy.rs new file mode 100644 index 00000000..893eaa65 --- /dev/null +++ b/crates/origin-shared/src/policy.rs @@ -0,0 +1,156 @@ +//! The parts of a repository's policy that its API shows: what landing on a +//! target requires, and patterns of statement kinds. + +use std::fmt; +use std::str::FromStr; + +use crate::{InvalidName, Kind, Principal, PrincipalName, Verdict}; + +/// A statement that landing needs: of `kind`, with `verdict`, from one of +/// `issuer`, about what lands. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Requirement { + /// The statement's kind. + pub kind: Kind, + /// Its verdict. + pub verdict: Verdict, + /// Who may issue it. + pub issuer: Principals, +} + +impl fmt::Display for Requirement { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} {} from {}", self.kind, self.verdict, self.issuer) + } +} + +/// One user or node, or the members of a group: `user:alice`, +/// `node:ci-1` or `group:runners`. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Principals { + /// A user or a node. + One(Principal), + /// The members of a group of the policy. + Group(PrincipalName), +} + +impl FromStr for Principals { + type Err = InvalidName; + + fn from_str(input: &str) -> Result { + match input.strip_prefix("group:") { + Some(group) => PrincipalName::new(group).map(Self::Group), + None => input.parse().map(Self::One).map_err(|_| InvalidName { + what: "principal, `user:`, `node:` or `group:`,", + name: input.to_owned(), + }), + } + } +} + +impl fmt::Display for Principals { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::One(principal) => principal.fmt(f), + Self::Group(group) => write!(f, "group:{group}"), + } + } +} + +/// Statement kinds, as retention rules and event filters name them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum KindPattern { + /// `*`: every kind. + Any, + /// `ci.*`: the kinds under a prefix, not the prefix itself. + Prefix(Kind), + /// `ci.test`: one kind. + Exact(Kind), +} + +impl KindPattern { + /// Whether the pattern matches `kind`. + #[must_use] + pub fn matches(&self, kind: &Kind) -> bool { + self.specificity(kind).is_some() + } + + /// Whether the pattern only matches reserved kinds: `core.*` or one + /// of them. + #[must_use] + pub fn is_reserved(&self) -> bool { + match self { + Self::Any => false, + Self::Prefix(prefix) => prefix.as_str() == "core" || prefix.is_reserved(), + Self::Exact(kind) => kind.is_reserved(), + } + } + + /// How specifically the pattern matches `kind`, if it does: longer + /// prefixes beat shorter ones, and the kind itself beats them all. + #[must_use] + pub fn specificity(&self, kind: &Kind) -> Option<(usize, bool)> { + match self { + Self::Any => Some((0, false)), + Self::Prefix(prefix) => kind + .as_str() + .strip_prefix(prefix.as_str()) + .is_some_and(|rest| rest.starts_with('.')) + .then_some((prefix.as_str().len(), false)), + Self::Exact(exact) => (exact == kind).then_some((exact.as_str().len(), true)), + } + } +} + +impl FromStr for KindPattern { + type Err = InvalidName; + + fn from_str(pattern: &str) -> Result { + let invalid = |_| InvalidName { + what: "statement kind, prefix like `ci.*`, or `*`", + name: pattern.to_owned(), + }; + match pattern.strip_suffix(".*") { + _ if pattern == "*" => Ok(Self::Any), + Some(prefix) => Kind::new(prefix).map(Self::Prefix).map_err(invalid), + None => Kind::new(pattern).map(Self::Exact).map_err(invalid), + } + } +} + +impl fmt::Display for KindPattern { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Any => f.write_str("*"), + Self::Prefix(prefix) => write!(f, "{prefix}.*"), + Self::Exact(kind) => kind.fmt(f), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kind_patterns_match_by_prefix() { + let kind = |kind: &str| Kind::new(kind).unwrap(); + let ci: KindPattern = "ci.*".parse().unwrap(); + assert!(ci.matches(&kind("ci.test"))); + assert!(!ci.matches(&kind("ci")), "the prefix itself isn't under it"); + assert!(!ci.matches(&kind("cix.test"))); + assert!("*".parse::().unwrap().matches(&kind("review"))); + for pattern in ["*", "ci.*", "ci.test"] { + assert_eq!(pattern.parse::().unwrap().to_string(), pattern); + } + assert!("ci.**".parse::().is_err()); + } + + #[test] + fn principals_parse_as_they_display() { + for valid in ["user:alice", "node:ci-1", "group:runners"] { + assert_eq!(valid.parse::().unwrap().to_string(), valid); + } + assert!("team:x".parse::().is_err()); + } +} diff --git a/crates/origin-shared/src/text.rs b/crates/origin-shared/src/text.rs new file mode 100644 index 00000000..46b09027 --- /dev/null +++ b/crates/origin-shared/src/text.rs @@ -0,0 +1,73 @@ +//! Values written as text. + +use std::fmt; +use std::str::FromStr; +use std::time::Duration; + +/// A length of time, written as a whole number of seconds (`s`), minutes +/// (`m`), hours (`h`) or days (`d`), such as `90d` or `30s`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Period(pub Duration); + +impl Period { + /// The units, longest first, so a period displays in the largest one + /// that divides it. + const UNITS: [(char, u64); 4] = [('d', 24 * 60 * 60), ('h', 60 * 60), ('m', 60), ('s', 1)]; +} + +impl FromStr for Period { + type Err = InvalidPeriod; + + fn from_str(period: &str) -> Result { + let invalid = || InvalidPeriod(period.to_owned()); + let unit = period.chars().last().ok_or_else(invalid)?; + let &(_, seconds) = Self::UNITS + .iter() + .find(|(name, _)| *name == unit) + .ok_or_else(invalid)?; + let count: u64 = period[..period.len() - 1].parse().map_err(|_| invalid())?; + let total = count.checked_mul(seconds).ok_or_else(invalid)?; + Ok(Self(Duration::from_secs(total))) + } +} + +/// In whole seconds, in the largest unit that divides them. +impl fmt::Display for Period { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let seconds = self.0.as_secs(); + let (unit, size) = Self::UNITS + .into_iter() + .find(|&(_, size)| seconds.is_multiple_of(size) && seconds >= size) + .unwrap_or(('s', 1)); + write!(f, "{}{unit}", seconds / size) + } +} + +/// A string that [`Period`] doesn't parse. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("`{0}` is not a period like `90d`, `12h`, `30m` or `45s`")] +pub struct InvalidPeriod(pub String); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn periods_parse_as_they_display() { + for (text, seconds) in [ + ("90d", 90 * 86_400), + ("12h", 43_200), + ("30m", 1800), + ("45s", 45), + ] { + let period: Period = text.parse().unwrap(); + assert_eq!(period.0, Duration::from_secs(seconds)); + assert_eq!(period.to_string(), text); + } + assert_eq!(Period(Duration::from_secs(120)).to_string(), "2m"); + assert_eq!(Period(Duration::ZERO).to_string(), "0s"); + for invalid in ["", "d", "5", "5w", "-1s", "1.5h"] { + assert!(invalid.parse::().is_err(), "{invalid:?}"); + } + } +}