warg_server/policy/record/
mod.rs

1//! Module for server record policy implementations.
2use thiserror::Error;
3use warg_protocol::{package::PackageRecord, registry::PackageName, ProtoEnvelope};
4
5mod authorization;
6pub use authorization::*;
7
8/// Represents a record policy error.
9#[derive(Debug, Error)]
10pub enum RecordPolicyError {
11    /// A special rejection that indicates the record is not
12    /// authorized to be published.
13    ///
14    /// Unauthorized records will never be stored.
15    #[error("unauthorized operation:: {0}")]
16    Unauthorized(String),
17    /// The policy rejected the record with the given message.
18    #[error("record was rejected by policy: {0}")]
19    Rejection(String),
20}
21
22/// The result type returned by record policies.
23pub type RecordPolicyResult<T> = Result<T, RecordPolicyError>;
24
25/// A trait implemented by record policies.
26pub trait RecordPolicy: Send + Sync {
27    /// Checks the record against the policy.
28    fn check(
29        &self,
30        name: &PackageName,
31        record: &ProtoEnvelope<PackageRecord>,
32    ) -> RecordPolicyResult<()>;
33}
34
35/// Represents a collection of record policies.
36///
37/// Record policies are checked in order of their addition
38/// to the collection.
39#[derive(Default)]
40pub struct RecordPolicyCollection {
41    policies: Vec<Box<dyn RecordPolicy>>,
42}
43
44impl RecordPolicyCollection {
45    /// Creates a new record policy collection.
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    /// Pushes a new record policy into the collection.
51    pub fn push(&mut self, policy: impl RecordPolicy + 'static) {
52        self.policies.push(Box::new(policy));
53    }
54}
55
56impl RecordPolicy for RecordPolicyCollection {
57    fn check(
58        &self,
59        name: &PackageName,
60        record: &ProtoEnvelope<PackageRecord>,
61    ) -> RecordPolicyResult<()> {
62        for policy in &self.policies {
63            policy.check(name, record)?;
64        }
65
66        Ok(())
67    }
68}