Skip to main content

safe_chains/
verdict.rs

1use std::fmt;
2
3#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
4#[repr(u8)]
5pub enum SafetyLevel {
6    Inert = 0,
7    SafeRead = 1,
8    SafeWrite = 2,
9}
10
11#[derive(Copy, Clone, Debug, PartialEq, Eq)]
12pub enum Verdict {
13    Denied,
14    Allowed(SafetyLevel),
15}
16
17impl Verdict {
18    pub fn combine(self, other: Verdict) -> Verdict {
19        match (self, other) {
20            (Verdict::Denied, _) | (_, Verdict::Denied) => Verdict::Denied,
21            (Verdict::Allowed(a), Verdict::Allowed(b)) => Verdict::Allowed(a.max(b)),
22        }
23    }
24
25    pub fn is_allowed(self) -> bool {
26        matches!(self, Verdict::Allowed(_))
27    }
28}
29
30impl SafetyLevel {
31    /// Resolve a `--level` threshold name to its ceiling. Accepts the current level names
32    /// (`paranoid`/`reader`/`editor`/`developer`/`local-admin`/`network-admin`/`yolo`) and the
33    /// three legacy names (`inert`/`safe-read`/`safe-write`). Returns the ceiling plus, for a
34    /// legacy name, the current name it maps to (so the CLI can print a migration notice).
35    /// `None` for an unknown name.
36    ///
37    /// The engine projects to this coarse 3-value ceiling today, so `editor`/`developer` and the
38    /// `local-admin`/`network-admin`/`yolo` levels all share the `SafeWrite` ceiling — they
39    /// become functionally distinct thresholds once the engine exposes per-level classification
40    /// (the `level.admits(profile)` check) rather than the 3-value projection.
41    pub fn resolve_threshold(name: &str) -> Option<(SafetyLevel, Option<&'static str>)> {
42        Some(match name {
43            "paranoid" => (SafetyLevel::Inert, None),
44            "reader" => (SafetyLevel::SafeRead, None),
45            "editor" | "developer" | "local-admin" | "network-admin" | "yolo" => (SafetyLevel::SafeWrite, None),
46            // Legacy names — kept working so existing setups/muscle-memory don't break; the CLI
47            // prints a one-line notice pointing at the current name.
48            "inert" => (SafetyLevel::Inert, Some("paranoid")),
49            "safe-read" => (SafetyLevel::SafeRead, Some("reader")),
50            "safe-write" => (SafetyLevel::SafeWrite, Some("developer")),
51            _ => return None,
52        })
53    }
54}
55
56impl fmt::Display for SafetyLevel {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        match self {
59            SafetyLevel::Inert => write!(f, "inert"),
60            SafetyLevel::SafeRead => write!(f, "safe-read"),
61            SafetyLevel::SafeWrite => write!(f, "safe-write"),
62        }
63    }
64}
65
66impl fmt::Display for Verdict {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Verdict::Denied => write!(f, "denied"),
70            Verdict::Allowed(level) => write!(f, "allowed ({level})"),
71        }
72    }
73}
74
75impl clap::ValueEnum for SafetyLevel {
76    fn value_variants<'a>() -> &'a [Self] {
77        &[SafetyLevel::Inert, SafetyLevel::SafeRead, SafetyLevel::SafeWrite]
78    }
79
80    fn to_possible_value(&self) -> Option<clap::builder::PossibleValue> {
81        match self {
82            SafetyLevel::Inert => Some(clap::builder::PossibleValue::new("inert")),
83            SafetyLevel::SafeRead => Some(clap::builder::PossibleValue::new("safe-read")),
84            SafetyLevel::SafeWrite => Some(clap::builder::PossibleValue::new("safe-write")),
85        }
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use proptest::prelude::*;
93
94    /// A `SafetyLevel` strategy: enumerate the three variants so `proptest::sample::select` covers
95    /// the whole lattice uniformly and shrinks toward `Inert`. Needed because `Proptest` does not
96    /// derive `Arbitrary` for non-`unit`-carrier enums, and the four-arity `Verdict` strategy is
97    /// built on top of this.
98    fn arb_safety_level() -> proptest::strategy::BoxedStrategy<SafetyLevel> {
99        proptest::sample::select(vec![SafetyLevel::Inert, SafetyLevel::SafeRead, SafetyLevel::SafeWrite]).boxed()
100    }
101
102    /// A `Verdict` strategy: `Denied` plus every `Allowed(level)`. Uniform coverage matters
103    /// because the property tests partition on whether at least one operand is denied — picking
104    /// only `Allowed` values would silently degenerate into a single-case lattice check.
105    fn arb_verdict() -> proptest::strategy::BoxedStrategy<Verdict> {
106        proptest::sample::select(vec![
107            Verdict::Denied,
108            Verdict::Allowed(SafetyLevel::Inert),
109            Verdict::Allowed(SafetyLevel::SafeRead),
110            Verdict::Allowed(SafetyLevel::SafeWrite),
111        ])
112        .boxed()
113    }
114
115    #[test]
116    fn level_ordering() {
117        assert!(SafetyLevel::Inert < SafetyLevel::SafeRead);
118        assert!(SafetyLevel::SafeRead < SafetyLevel::SafeWrite);
119    }
120
121    #[test]
122    fn threshold_names_map_new_and_legacy() {
123        // current names — no legacy notice
124        assert_eq!(SafetyLevel::resolve_threshold("paranoid"), Some((SafetyLevel::Inert, None)));
125        assert_eq!(SafetyLevel::resolve_threshold("reader"), Some((SafetyLevel::SafeRead, None)));
126        assert_eq!(SafetyLevel::resolve_threshold("editor"), Some((SafetyLevel::SafeWrite, None)));
127        assert_eq!(SafetyLevel::resolve_threshold("developer"), Some((SafetyLevel::SafeWrite, None)));
128        assert_eq!(SafetyLevel::resolve_threshold("yolo"), Some((SafetyLevel::SafeWrite, None)));
129
130        // legacy names — same ceiling as before, carrying the current name for the notice
131        assert_eq!(SafetyLevel::resolve_threshold("inert"), Some((SafetyLevel::Inert, Some("paranoid"))));
132        assert_eq!(SafetyLevel::resolve_threshold("safe-read"), Some((SafetyLevel::SafeRead, Some("reader"))));
133        assert_eq!(SafetyLevel::resolve_threshold("safe-write"), Some((SafetyLevel::SafeWrite, Some("developer"))));
134
135        // the legacy inputs preserve their historical ceiling exactly (no setup breaks)
136        assert_eq!(SafetyLevel::resolve_threshold("inert").unwrap().0, SafetyLevel::Inert);
137        assert_eq!(SafetyLevel::resolve_threshold("safe-write").unwrap().0, SafetyLevel::SafeWrite);
138
139        assert_eq!(SafetyLevel::resolve_threshold("nonsense"), None);
140    }
141
142    #[test]
143    fn combine_both_allowed() {
144        let a = Verdict::Allowed(SafetyLevel::Inert);
145        let b = Verdict::Allowed(SafetyLevel::SafeRead);
146        assert_eq!(a.combine(b), Verdict::Allowed(SafetyLevel::SafeRead));
147    }
148
149    #[test]
150    fn combine_one_denied() {
151        let a = Verdict::Allowed(SafetyLevel::Inert);
152        assert_eq!(a.combine(Verdict::Denied), Verdict::Denied);
153        assert_eq!(Verdict::Denied.combine(a), Verdict::Denied);
154    }
155
156    #[test]
157    fn combine_identity() {
158        let a = Verdict::Allowed(SafetyLevel::SafeWrite);
159        let identity = Verdict::Allowed(SafetyLevel::Inert);
160        assert_eq!(identity.combine(a), a);
161    }
162
163    proptest::proptest! {
164        // Invariant (differential). `combine` is the lattice join of the verdict monoid: `Denied`
165        // is the absorbing element and the `SafetyLevel` carries the max. When both operands are
166        // `Allowed` it has to reduce to the `PartialOrd`-derived `max` of the two levels — without
167        // that reduction the engine's "weakest writer wins" semantics break.
168        #[test]
169        fn combine_takes_the_max_of_levels_when_both_allowed(
170            a in arb_safety_level(),
171            b in arb_safety_level(),
172        ) {
173            let joined = Verdict::Allowed(a).combine(Verdict::Allowed(b));
174            let expected = Verdict::Allowed(a.max(b));
175            proptest::prop_assert_eq!(joined, expected);
176        }
177
178        // Invariant. `Denied` is the absorbing element of `combine` from either side, so the
179        // join is `Denied` iff at least one operand is. The converse (right-to-left) direction is
180        // the load-bearing one — `combine` must never synthesise a deny from two allows.
181        #[test]
182        fn combine_is_denied_iff_either_operand_is_denied(
183            a in arb_verdict(),
184            b in arb_verdict(),
185        ) {
186            let joined = a.combine(b);
187            let one_denied = a == Verdict::Denied || b == Verdict::Denied;
188            proptest::prop_assert_eq!(joined == Verdict::Denied, one_denied);
189        }
190
191        // Metamorphic. `combine` is the join of an `Allowed`-monoid-with-bottom lattice, so it
192        // must be associative. Proptest canary: a non-associative `combine` would break every
193        // caller that folds verdicts in a tree (e.g. per-argument aggregation into a command-wide
194        // verdict).
195        #[test]
196        fn combine_is_associative(
197            a in arb_verdict(),
198            b in arb_verdict(),
199            c in arb_verdict(),
200        ) {
201            proptest::prop_assert_eq!(a.combine(b).combine(c), a.combine(b.combine(c)));
202        }
203
204        // Roundtrip. `SafetyLevel`'s `Display` writes the legacy name. For every variant, that
205        // string has to resolve back through `resolve_threshold` to the same level (and never to
206        // `None`). Without this, anything that round-trips a level through a string (config files,
207        // error messages, persisted state) silently flips safety class.
208        #[test]
209        fn level_display_string_resolves_back_to_the_same_level(
210            level in arb_safety_level(),
211        ) {
212            let rendered = level.to_string();
213            let resolved = SafetyLevel::resolve_threshold(&rendered);
214            proptest::prop_assert_eq!(resolved.map(|(ceiling, _)| ceiling), Some(level));
215        }
216    }
217}