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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/origin-src/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion apps/origin-src/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ 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,
};

use crate::index;
use crate::oplog::{Effect, Entry};
use crate::policy::{KindPattern, Requirement};
use crate::queue::{Blocked, Pending, Queue};
use crate::store::{Store, StoreError};

Expand Down
148 changes: 13 additions & 135 deletions apps/origin-src/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -64,28 +66,6 @@ struct TargetRules {
require: Vec<Requirement>,
}

/// 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 {
Expand Down Expand Up @@ -401,30 +381,6 @@ impl Policy {
}
}

impl FromStr for Principals {
type Err = String;

fn from_str(input: &str) -> Result<Self, Self::Err> {
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:<name>`, `node:<name>` or `group:<name>`")
}),
}
}
}

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;

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Duration> {
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<BTreeMap<String, String>> for Retention {
Expand All @@ -549,88 +485,30 @@ impl TryFrom<BTreeMap<String, String>> 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::<Result<_, RetentionError>>()?;
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<Self, Self::Err> {
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.
Expand Down
3 changes: 2 additions & 1 deletion apps/origin-src/src/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;

Expand Down
3 changes: 1 addition & 2 deletions apps/origin-src/src/queue/pending.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down
3 changes: 2 additions & 1 deletion apps/origin-src/src/queue/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;

Expand Down
3 changes: 2 additions & 1 deletion apps/origin-src/src/queue/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;
Expand Down
3 changes: 3 additions & 0 deletions crates/origin-shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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};
Loading
Loading