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