Skip to main content

safe_chains/engine/
level.rs

1//! Safety levels as predicates over profiles (v1.4 §4.1).
2//!
3//! A [`Level`] is a disjunction of allow [`Clause`]s plus an allow-only set of deny
4//! clauses (the `yolo` subtractive primitive, §4.1). A [`Clause`] is a conjunction of
5//! per-facet bounds — an ordinal ceiling/floor ([`OrdBound`]) or a categorical set —
6//! and an omitted facet is unconstrained. A capability is admissible iff **some**
7//! allow clause admits every one of its facets and **no** deny clause matches it; a
8//! profile passes iff every capability is admissible.
9//!
10//! Nothing here parses TOML or ships a default level yet — this is the algebra and
11//! its contract. Level authoring (TOML → `Level`) and the default set arrive next.
12
13use super::facet::*;
14
15/// An ordinal bound: `min ≤ term ≤ max`, either side optional. `at_most` is a
16/// ceiling (the common risk-facet form); `at_least` a floor (trust facets like
17/// pinning). An omitted side is unconstrained.
18#[derive(Copy, Clone, Debug, PartialEq, Eq)]
19pub struct OrdBound<T> {
20    pub min: Option<T>,
21    pub max: Option<T>,
22}
23
24impl<T: Ord + Copy> OrdBound<T> {
25    /// `term ≤ ceiling`.
26    pub fn at_most(ceiling: T) -> Self {
27        Self { min: None, max: Some(ceiling) }
28    }
29    /// `term ≥ floor`.
30    pub fn at_least(floor: T) -> Self {
31        Self { min: Some(floor), max: None }
32    }
33    /// `term == exact`.
34    pub fn exactly(exact: T) -> Self {
35        Self { min: Some(exact), max: Some(exact) }
36    }
37    /// Whether `term` falls within the bound.
38    pub fn admits(self, term: T) -> bool {
39        self.min.is_none_or(|lo| lo <= term) && self.max.is_none_or(|hi| term <= hi)
40    }
41}
42
43fn ord_admits<T: Ord + Copy>(bound: Option<OrdBound<T>>, term: T) -> bool {
44    bound.is_none_or(|b| b.admits(term))
45}
46
47fn set_admits<T: Eq + Copy>(set: Option<&[T]>, term: T) -> bool {
48    set.is_none_or(|s| s.contains(&term))
49}
50
51/// The single facet constraint a capability failed, named in the taxonomy's own vocabulary.
52///
53/// Exists because the engine was write-only: `admits` answered yes/no and nothing reported WHICH
54/// axis said no, so both a user asking "why was this denied" and an author debugging a resolver had
55/// to bisect by editing facets and re-running. That is not a hypothetical cost — it is how an
56/// incomplete loopback delta got mistaken for a flawed approach.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct FacetMismatch {
59    /// Dotted facet path as the taxonomy spells it (`network.payload`, `locus.remote`).
60    pub facet: &'static str,
61    /// The capability's term (`sends-host-data`).
62    pub actual: &'static str,
63    /// The constraint it failed (`<= fetches`, `one of [pinned, na]`).
64    pub bound: String,
65    /// The same constraint in plain words, for `--explain`.
66    pub plain_bound: Option<String>,
67    /// How many of that axis's terms the bound DOES admit — how close this clause came.
68    ///
69    /// Used to rank clauses, not shown. A level inherits its ancestors' clauses (`developer`
70    /// carries `paranoid`'s `observe` clause), so several can match on operation and the first is
71    /// often the strictest. Reporting that one names a bound the author never intended for this
72    /// capability: a `cat` of a machine-locus path was blamed on `<= temp` (paranoid's read floor)
73    /// when the read bound that actually matters is `<= worktree-trusted`.
74    pub admits_count: usize,
75}
76
77impl std::fmt::Display for FacetMismatch {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        write!(f, "{} = {} (allowed: {})", self.facet, self.actual, self.bound)
80    }
81}
82
83fn ord_mismatch<T: Ord + Copy + FacetTerm>(facet: &'static str, bound: Option<OrdBound<T>>, term: T) -> Option<FacetMismatch> {
84    let b = bound?;
85    if b.admits(term) {
86        return None;
87    }
88    let say = |t: T| super::plain::spoken(facet, t.as_str());
89    let (bound, plain_bound) = match (b.min, b.max) {
90        (None, Some(hi)) => (format!("<= {}", hi.as_str()), say(hi).map(|h| format!("allowed up to: {h}"))),
91        (Some(lo), None) => (format!(">= {}", lo.as_str()), say(lo).map(|l| format!("allowed at least: {l}"))),
92        (Some(lo), Some(hi)) if lo == hi => (format!("{}..={}", lo.as_str(), hi.as_str()), say(lo).map(|l| format!("allowed: {l}"))),
93        (Some(lo), Some(hi)) => {
94            (format!("{}..={}", lo.as_str(), hi.as_str()), say(lo).zip(say(hi)).map(|(l, h)| format!("allowed: {l} to {h}")))
95        }
96        (None, None) => ("any".to_string(), Some("allowed: any".to_string())),
97    };
98    let admits_count = T::all().iter().filter(|t| b.admits(**t)).count();
99    Some(FacetMismatch { facet, actual: term.as_str(), bound, plain_bound, admits_count })
100}
101
102fn set_mismatch<T: PartialEq + Copy + FacetTerm>(facet: &'static str, set: Option<&[T]>, term: T) -> Option<FacetMismatch> {
103    let s = set?;
104    if s.contains(&term) {
105        return None;
106    }
107    let bound = format!("one of [{}]", s.iter().map(|t| t.as_str()).collect::<Vec<_>>().join(", "),);
108    let spoken: Option<Vec<&str>> = s.iter().map(|t| super::plain::spoken(facet, t.as_str())).collect();
109    let plain_bound = spoken.map(|p| format!("allowed: one of: {}", p.join(" / ")));
110    Some(FacetMismatch { facet, actual: term.as_str(), bound, plain_bound, admits_count: s.len() })
111}
112
113/// A conjunction of per-facet constraints. A default (all-`None`) clause admits every
114/// capability. Each ordinal facet takes an [`OrdBound`]; each categorical facet an
115/// allowed set. Fields are flattened per axis — a compound facet is never a single
116/// constraint (the R25 discipline).
117#[derive(Clone, Debug, Default, PartialEq, Eq)]
118pub struct Clause {
119    pub operation: Option<Vec<Operation>>,
120    pub local_locus: Option<OrdBound<LocalLocus>>,
121    pub remote_reach: Option<OrdBound<RemoteReach>>,
122    pub remote_binding: Option<Vec<RemoteBinding>>,
123    pub provenance: Option<OrdBound<Provenance>>,
124    pub scale: Option<OrdBound<Scale>>,
125    pub retrieval: Option<OrdBound<RetrievalGranularity>>,
126    pub authority: Option<OrdBound<Authority>>,
127    pub isolation: Option<OrdBound<Isolation>>,
128    pub reversibility: Option<OrdBound<Reversibility>>,
129    pub persistence_level: Option<OrdBound<PersistenceLevel>>,
130    pub trigger_escape: Option<OrdBound<TriggerEscape>>,
131    pub trigger_kind: Option<Vec<TriggerKind>>,
132    pub disclosure_audience: Option<OrdBound<DisclosureAudience>>,
133    pub disclosure_channel: Option<Vec<Channel>>,
134    pub disclosure_principal: Option<Vec<Principal>>,
135    pub secret_level: Option<OrdBound<SecretLevel>>,
136    pub secret_channel: Option<Vec<Channel>>,
137    pub secret_principal: Option<Vec<Principal>>,
138    pub net_direction: Option<OrdBound<NetDirection>>,
139    pub net_destination: Option<OrdBound<NetDestination>>,
140    pub net_payload: Option<OrdBound<NetPayload>>,
141    pub execution_trust: Option<OrdBound<ExecutionTrust>>,
142    pub supply_source: Option<Vec<SupplySource>>,
143    pub pinning: Option<OrdBound<Pinning>>,
144    pub exec_surface: Option<Vec<ExecSurface>>,
145    pub cost: Option<OrdBound<Cost>>,
146}
147
148impl Clause {
149    /// Whether this clause **admits** `cap` (allow-clause semantics).
150    pub fn admits(&self, cap: &Capability) -> bool {
151        self.check(cap, Role::Allow)
152    }
153
154    /// Whether this clause **matches** `cap` for removal (deny-clause semantics). Differs
155    /// from `admits` only on the optional `supply_chain`: a deny constrained on a
156    /// supply-chain facet does **not** match a capability that has no supply chain (it is
157    /// not in the denied corner), whereas an allow treats the absence as vacuously
158    /// satisfied. Sharing one body with a naive vacuous-true rule would make a
159    /// supply-chain-only deny wrongly match every non-supply-chain capability.
160    fn matches_as_deny(&self, cap: &Capability) -> bool {
161        self.check(cap, Role::Deny)
162    }
163
164    fn check(&self, cap: &Capability, role: Role) -> bool {
165        self.first_mismatch(cap, role).is_none()
166    }
167
168    /// Test-only view of `first_mismatch`. Takes the ROLE: the allow/deny asymmetry on the supply
169    /// chain means an allow-only equivalence proptest cannot see a deny-side inversion (it did not
170    /// — a `?` that reported "no complaint" for a definitely-failing deny got through it).
171    #[cfg(test)]
172    pub(crate) fn first_mismatch_for_test(&self, cap: &Capability, deny_role: bool) -> Option<FacetMismatch> {
173        self.first_mismatch(cap, if deny_role { Role::Deny } else { Role::Allow })
174    }
175
176    #[cfg(test)]
177    pub(crate) fn matches_as_deny_for_test(&self, cap: &Capability) -> bool {
178        self.matches_as_deny(cap)
179    }
180
181    /// The first facet constraint `cap` fails, or `None` if this clause admits it.
182    ///
183    /// `check` is defined in terms of THIS rather than the other way round. A parallel
184    /// "explain" walk beside a separate `&&` chain would drift the moment a facet is added, and a
185    /// diagnostic that disagrees with the predicate is worse than none — it would send an author
186    /// chasing the wrong axis. `clause_diagnostic_agrees_with_admits` pins the equivalence.
187    ///
188    /// Order is the taxonomy's axis order, not severity: it reports A failing facet, not the most
189    /// important one, since a clause is a conjunction and every failure is disqualifying. The one
190    /// exception: `secret.level` is checked straight after the operation, so a secret read is refused
191    /// for the secret rather than for where it sits or for being `exposed`.
192    fn first_mismatch(&self, cap: &Capability, role: Role) -> Option<FacetMismatch> {
193        set_mismatch("operation", self.operation.as_deref(), cap.operation)
194            .or_else(|| ord_mismatch("secret.level", self.secret_level, cap.secret.level))
195            .or_else(|| ord_mismatch("locus.local", self.local_locus, cap.locus.local))
196            .or_else(|| ord_mismatch("locus.remote", self.remote_reach, cap.locus.remote))
197            .or_else(|| set_mismatch("locus.binding", self.remote_binding.as_deref(), cap.locus.binding))
198            .or_else(|| ord_mismatch("locus.provenance", self.provenance, cap.locus.provenance))
199            .or_else(|| ord_mismatch("scale", self.scale, cap.scale))
200            .or_else(|| ord_mismatch("retrieval", self.retrieval, cap.retrieval))
201            .or_else(|| ord_mismatch("authority", self.authority, cap.authority))
202            .or_else(|| ord_mismatch("isolation", self.isolation, cap.isolation))
203            .or_else(|| ord_mismatch("reversibility", self.reversibility, cap.reversibility))
204            .or_else(|| ord_mismatch("persistence.level", self.persistence_level, cap.persistence.level))
205            .or_else(|| ord_mismatch("persistence.trigger.escape", self.trigger_escape, cap.persistence.trigger.escape))
206            .or_else(|| set_mismatch("persistence.trigger.kind", self.trigger_kind.as_deref(), cap.persistence.trigger.kind))
207            .or_else(|| ord_mismatch("disclosure.audience", self.disclosure_audience, cap.disclosure.audience))
208            .or_else(|| set_mismatch("disclosure.channel", self.disclosure_channel.as_deref(), cap.disclosure.channel))
209            .or_else(|| set_mismatch("disclosure.principal", self.disclosure_principal.as_deref(), cap.disclosure.principal))
210            .or_else(|| set_mismatch("secret.channel", self.secret_channel.as_deref(), cap.secret.channel))
211            .or_else(|| set_mismatch("secret.principal", self.secret_principal.as_deref(), cap.secret.principal))
212            .or_else(|| ord_mismatch("network.direction", self.net_direction, cap.network.direction))
213            .or_else(|| ord_mismatch("network.destination", self.net_destination, cap.network.destination))
214            .or_else(|| ord_mismatch("network.payload", self.net_payload, cap.network.payload))
215            .or_else(|| ord_mismatch("execution.trust", self.execution_trust, cap.execution.trust))
216            .or_else(|| self.supply_chain_mismatch(cap.execution.supply_chain, role))
217            .or_else(|| ord_mismatch("cost", self.cost, cap.cost))
218    }
219
220    /// Supply-chain constraints apply only to network-sourced code. For an **allow**, a
221    /// capability with no supply chain (`None`) satisfies them vacuously. For a **deny**,
222    /// a clause that constrains the supply chain does **not** match a `None` capability —
223    /// it is not in the denied corner — while an unconstrained deny is unaffected.
224    fn supply_chain_mismatch(&self, sc: Option<SupplyChain>, role: Role) -> Option<FacetMismatch> {
225        if self.supply_chain_admits(sc, role) {
226            return None;
227        }
228        let Some(sc) = sc else {
229            // A DENY constrained on the supply chain does not match a capability that has none.
230            // `?` here would report "no complaint", which `check` reads as ADMITS — inverting the
231            // rule for exactly the case the asymmetry exists to handle.
232            return Some(FacetMismatch {
233                facet: "execution.supply_chain",
234                actual: "absent",
235                bound: "this clause constrains the supply chain, which this capability has none of".to_string(),
236                plain_bound: None,
237                admits_count: 0,
238            });
239        };
240        set_mismatch("supply_chain.source", self.supply_source.as_deref(), sc.source)
241            .or_else(|| ord_mismatch("supply_chain.pinning", self.pinning, sc.pinning))
242            .or_else(|| set_mismatch("supply_chain.exec_surface", self.exec_surface.as_deref(), sc.exec_surface))
243    }
244
245    fn supply_chain_admits(&self, sc: Option<SupplyChain>, role: Role) -> bool {
246        match sc {
247            None => match role {
248                Role::Allow => true,
249                Role::Deny => self.supply_source.is_none() && self.pinning.is_none() && self.exec_surface.is_none(),
250            },
251            Some(sc) => {
252                set_admits(self.supply_source.as_deref(), sc.source)
253                    && ord_admits(self.pinning, sc.pinning)
254                    && set_admits(self.exec_surface.as_deref(), sc.exec_surface)
255            }
256        }
257    }
258}
259
260/// Which side a clause is evaluated on — the two differ only on absent `supply_chain`.
261#[derive(Copy, Clone, PartialEq, Eq)]
262enum Role {
263    Allow,
264    Deny,
265}
266
267/// A safety level: a name, its allow clauses (disjunction), and its deny clauses
268/// (allow-only subtractive corners, §4.1).
269#[derive(Clone, Debug, Default, PartialEq, Eq)]
270pub struct Level {
271    pub name: String,
272    pub allow: Vec<Clause>,
273    pub deny: Vec<Clause>,
274}
275
276impl Level {
277    /// An empty level (admits only the empty profile). Build it up with
278    /// [`Level::allowing`] / [`Level::denying`].
279    pub fn new(name: impl Into<String>) -> Self {
280        Self { name: name.into(), allow: Vec::new(), deny: Vec::new() }
281    }
282
283    /// Add an allow clause (widens the admissible region).
284    #[must_use]
285    pub fn allowing(mut self, clause: Clause) -> Self {
286        self.allow.push(clause);
287        self
288    }
289
290    /// Add a deny clause (subtracts a corner; never grants).
291    #[must_use]
292    pub fn denying(mut self, clause: Clause) -> Self {
293        self.deny.push(clause);
294        self
295    }
296
297    /// Whether a single capability is admissible: some allow clause admits it and no
298    /// deny clause matches it.
299    /// Why this level does not admit `cap`, or `None` if it does.
300    ///
301    /// A level is a DISJUNCTION of allow clauses, so a rejected capability failed all of them and
302    /// there is a choice of which complaint to report. Clauses are usually split by operation
303    /// (`editor` allows observes under one clause and mutates under another), so the first clause's
304    /// gripe is frequently "operation = mutate, allowed: \[observe\]" — true, useless, and it hides
305    /// the facet the author actually needs to change. Preferring a clause whose OPERATION already
306    /// matches surfaces the real blocker.
307    pub fn nearest_miss(&self, cap: &Capability) -> Option<FacetMismatch> {
308        if self.allow.iter().any(|c| c.admits(cap)) {
309            // Admitted by an allow, so if the level still rejects it a deny clause removed it.
310            return self.deny.iter().find(|c| c.matches_as_deny(cap)).map(|_| FacetMismatch {
311                facet: "deny-clause",
312                actual: "matched",
313                bound: "removed by an explicit deny clause".to_string(),
314                plain_bound: None,
315                admits_count: 0,
316            });
317        }
318        if self.allow.is_empty() {
319            return Some(FacetMismatch {
320                facet: "level",
321                actual: "any capability",
322                bound: "nothing — this level declares no allow clause".to_string(),
323                plain_bound: None,
324                admits_count: 0,
325            });
326        }
327        let on_topic = |c: &&Clause| c.operation.as_ref().is_none_or(|ops| ops.contains(&cap.operation));
328        // Among the clauses that could plausibly have admitted this capability, report the one that
329        // came CLOSEST — the largest `admits_count` on the facet that stopped it. Taking the first
330        // match instead named an inherited ancestor clause's much tighter bound, which points the
331        // reader at a rule that was never meant to cover this capability.
332        let mut candidates: Vec<FacetMismatch> =
333            self.allow.iter().filter(on_topic).filter_map(|c| c.first_mismatch(cap, Role::Allow)).collect();
334        if candidates.is_empty() {
335            candidates = self.allow.iter().filter_map(|c| c.first_mismatch(cap, Role::Allow)).collect();
336        }
337        candidates.into_iter().max_by_key(|m| m.admits_count)
338    }
339
340    pub fn admits_capability(&self, cap: &Capability) -> bool {
341        self.allow.iter().any(|c| c.admits(cap)) && !self.deny.iter().any(|c| c.matches_as_deny(cap))
342    }
343
344    /// Whether a whole profile passes: every capability is admissible. The empty
345    /// profile passes vacuously.
346    pub fn admits(&self, profile: &Profile) -> bool {
347        profile.capabilities.iter().all(|c| self.admits_capability(c))
348    }
349
350    /// Author a level by extending `base` (R27: `extends` only loosens). The result
351    /// inherits `base`'s allow *and* deny clauses unchanged and adds only allow
352    /// clauses — it cannot drop an allow or add a deny, so `extends ⇒ superset` holds
353    /// by construction. `yolo`'s subtractive `deny` is authored directly, never via
354    /// `extend`.
355    #[must_use]
356    pub fn extend(base: &Level, name: impl Into<String>, extra_allow: Vec<Clause>) -> Level {
357        let mut allow = base.allow.clone();
358        allow.extend(extra_allow);
359        Level { name: name.into(), allow, deny: base.deny.clone() }
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use proptest::prelude::*;
367
368    fn cap(op: Operation) -> Capability {
369        Capability::new(op)
370    }
371
372    #[test]
373    fn empty_clause_admits_everything_empty_allow_admits_nothing() {
374        let all = Level::new("all").allowing(Clause::default());
375        let nothing = Level::new("nothing");
376        let destroy = Profile::of(vec![cap(Operation::Destroy)]);
377        assert!(all.admits(&destroy));
378        assert!(!nothing.admits(&destroy));
379        // both admit the empty profile vacuously
380        assert!(all.admits(&Profile::default()));
381        assert!(nothing.admits(&Profile::default()));
382    }
383
384    /// A level INHERITS its ancestors' clauses, so several can match on `operation` and the
385    /// STRICTEST is often first. Reporting that one names a bound never meant for this capability:
386    /// `cat ~/Library/...` was blamed on `<= temp` — paranoid's read floor, inherited by developer —
387    /// when developer's actual read bound is `<= worktree-trusted`. The diagnostic must name the
388    /// clause that came closest, or it sends the reader to fix the wrong rule.
389    #[test]
390    fn nearest_miss_reports_the_clause_that_came_closest_not_the_first() {
391        let strict = Clause {
392            operation: Some(vec![Operation::Observe]),
393            local_locus: Some(OrdBound::at_most(LocalLocus::Temp)),
394            ..Default::default()
395        };
396        let loose = Clause {
397            operation: Some(vec![Operation::Observe]),
398            local_locus: Some(OrdBound::at_most(LocalLocus::WorktreeTrusted)),
399            ..Default::default()
400        };
401        // Strict first, mirroring the inherited-ancestor ordering that produced the bad report.
402        let level = Level::new("two-reads").allowing(strict).allowing(loose);
403        let mut cap = Capability::new(Operation::Observe);
404        cap.locus.local = LocalLocus::Machine;
405
406        let m = level.nearest_miss(&cap).expect("machine locus exceeds both clauses");
407        assert_eq!(m.facet, "locus.local");
408        assert!(
409            m.bound.contains("worktree-trusted"),
410            "named the strictest clause (`{}`); the closest one allows <= worktree-trusted",
411            m.bound,
412        );
413    }
414
415    #[test]
416    fn read_local_admits_a_read_rejects_a_secret_and_a_destroy() {
417        let read_local = Level::new("read-local").allowing(Clause {
418            operation: Some(vec![Operation::Observe]),
419            local_locus: Some(OrdBound::at_most(LocalLocus::User)),
420            secret_level: Some(OrdBound::at_most(SecretLevel::UsesAmbient)),
421            net_direction: Some(OrdBound::at_most(NetDirection::Loopback)),
422            ..Default::default()
423        });
424
425        let plain_read = Profile::of(vec![{
426            let mut c = cap(Operation::Observe);
427            c.locus.local = LocalLocus::Worktree;
428            c
429        }]);
430        assert!(read_local.admits(&plain_read));
431
432        let secret_read = Profile::of(vec![{
433            let mut c = cap(Operation::Observe);
434            c.locus.local = LocalLocus::User;
435            c.secret.level = SecretLevel::Reads;
436            c
437        }]);
438        assert!(!read_local.admits(&secret_read), "cat ~/.ssh/id_rsa must not pass read-local");
439
440        let destroy = Profile::of(vec![cap(Operation::Destroy)]);
441        assert!(!read_local.admits(&destroy));
442    }
443
444    #[test]
445    fn yolo_deny_carves_out_the_catastrophe_corner() {
446        let yolo = Level::new("yolo").allowing(Clause::default()).denying(Clause {
447            operation: Some(vec![Operation::Destroy]),
448            reversibility: Some(OrdBound::at_least(Reversibility::Irreversible)),
449            scale: Some(OrdBound::at_least(Scale::Unbounded)),
450            ..Default::default()
451        });
452
453        // rm -rf ./node_modules — destroy·bounded·recoverable → admitted
454        let bounded = Profile::of(vec![{
455            let mut c = cap(Operation::Destroy);
456            c.scale = Scale::Bounded;
457            c.reversibility = Reversibility::Recoverable;
458            c
459        }]);
460        assert!(yolo.admits(&bounded));
461
462        // rm -rf / — destroy·unbounded·irreversible → denied by the corner
463        let wipe = Profile::of(vec![{
464            let mut c = cap(Operation::Destroy);
465            c.scale = Scale::Unbounded;
466            c.reversibility = Reversibility::Irreversible;
467            c
468        }]);
469        assert!(!yolo.admits(&wipe));
470    }
471
472    #[test]
473    fn supply_chain_gates_network_sourced_code_and_is_vacuous_otherwise() {
474        // a developer-shaped clause: network-sourced execution is fine, but only from a
475        // recognized registry (not an unverified URL).
476        let dev = Level::new("dev").allowing(Clause {
477            execution_trust: Some(OrdBound::at_most(ExecutionTrust::NetworkSourced)),
478            supply_source: Some(vec![
479                SupplySource::PublicRegistry,
480                SupplySource::SignedRepo,
481                SupplySource::PrivateRegistry,
482                SupplySource::Vendored,
483            ]),
484            ..Default::default()
485        });
486
487        // cargo build — network-sourced from a public registry
488        let build = Profile::of(vec![{
489            let mut c = cap(Operation::Execute);
490            c.execution = Execution {
491                trust: ExecutionTrust::NetworkSourced,
492                supply_chain: Some(SupplyChain {
493                    source: SupplySource::PublicRegistry,
494                    pinning: Pinning::HashVerified,
495                    exec_surface: ExecSurface::BuildScript,
496                }),
497            };
498            c
499        }]);
500        assert!(dev.admits(&build), "cargo build from a registry");
501
502        // curl | sh — network-sourced from an unverified URL
503        let curl_sh = Profile::of(vec![{
504            let mut c = cap(Operation::Execute);
505            c.execution = Execution {
506                trust: ExecutionTrust::NetworkSourced,
507                supply_chain: Some(SupplyChain {
508                    source: SupplySource::UnverifiedUrl,
509                    pinning: Pinning::Floating,
510                    exec_surface: ExecSurface::RunArtifact,
511                }),
512            };
513            c
514        }]);
515        assert!(!dev.admits(&curl_sh), "curl | sh is an unverified-url source");
516
517        // cat file — no downloaded code, so the supply-chain constraint is vacuous
518        let plain = Profile::of(vec![cap(Operation::Observe)]);
519        assert!(dev.admits(&plain), "a command with no supply chain passes vacuously");
520    }
521
522    #[test]
523    fn a_supply_chain_deny_does_not_match_a_capability_without_one() {
524        // "deny unverified-url sources" must NOT accidentally deny `cat file` (no supply
525        // chain) — the vacuous-truth asymmetry between allow and deny (review finding #1).
526        let level = Level::new("x")
527            .allowing(Clause::default())
528            .denying(Clause { supply_source: Some(vec![SupplySource::UnverifiedUrl]), ..Default::default() });
529
530        let plain = Profile::of(vec![cap(Operation::Observe)]);
531        assert!(level.admits(&plain), "a supply-chain deny must not match a no-supply-chain cap");
532
533        // but curl|sh (network-sourced, unverified-url) IS still caught by the deny corner
534        let curl_sh = Profile::of(vec![{
535            let mut c = cap(Operation::Execute);
536            c.execution = Execution {
537                trust: ExecutionTrust::NetworkSourced,
538                supply_chain: Some(SupplyChain {
539                    source: SupplySource::UnverifiedUrl,
540                    pinning: Pinning::Floating,
541                    exec_surface: ExecSurface::RunArtifact,
542                }),
543            };
544            c
545        }]);
546        assert!(!level.admits(&curl_sh), "the deny corner still catches the unverified-url source");
547    }
548
549    #[test]
550    fn extend_inherits_deny_and_adds_allow() {
551        let base = Level::new("base")
552            .allowing(Clause { operation: Some(vec![Operation::Observe]), ..Default::default() })
553            .denying(Clause { local_locus: Some(OrdBound::at_least(LocalLocus::Device)), ..Default::default() });
554        let child = Level::extend(
555            &base,
556            "child",
557            vec![Clause { operation: Some(vec![Operation::Create, Operation::Mutate]), ..Default::default() }],
558        );
559
560        assert!(child.admits(&Profile::of(vec![cap(Operation::Create)])), "added allow");
561        assert!(child.admits(&Profile::of(vec![cap(Operation::Observe)])), "inherited allow");
562
563        let device = Profile::of(vec![{
564            let mut c = cap(Operation::Mutate);
565            c.locus.local = LocalLocus::Device;
566            c
567        }]);
568        assert!(!child.admits(&device), "inherited deny still bites");
569    }
570
571    // ── the algebra contract ──────────────────────────────────────────────────────
572    //
573    // Generators live in `super::super::testgen` (shared with the authoring tests).
574    use crate::engine::testgen::{arb_clause, arb_level, arb_profile};
575
576    proptest! {
577        /// Totality: every level yields a decision on every profile, deterministically,
578        /// never a panic (the worst-case rule guarantees a total function).
579        #[test]
580        fn totality(level in arb_level(), profile in arb_profile()) {
581            let first = level.admits(&profile);
582            prop_assert_eq!(first, level.admits(&profile));
583        }
584
585        /// extends ⇒ superset: a level built by `extend` admits everything its base
586        /// admits (R27, encoded structurally).
587        #[test]
588        fn extends_is_a_superset(
589            base in arb_level(),
590            extra in prop::collection::vec(arb_clause(), 0..3),
591            profile in arb_profile(),
592        ) {
593            let extended = Level::extend(&base, "child", extra);
594            prop_assert!(!base.admits(&profile) || extended.admits(&profile));
595        }
596
597        /// deny-monotonicity: adding a deny clause can only *shrink* the admitted set —
598        /// a deny never grants. This is what makes the subtractive primitive safe.
599        #[test]
600        fn deny_only_shrinks(
601            level in arb_level(),
602            extra_deny in arb_clause(),
603            profile in arb_profile(),
604        ) {
605            let stricter = level.clone().denying(extra_deny);
606            prop_assert!(!stricter.admits(&profile) || level.admits(&profile));
607        }
608    }
609}