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