Skip to main content

safe_chains/engine/
authoring.rs

1//! Compiling level TOML into [`Level`] values (v1.4 §4.1) — the analogue of
2//! `build_command` for the level language.
3//!
4//! A `[level.<name>]` table carries an optional `extends`, a list of `allow`
5//! clauses, and (for the loosest level only) `deny` clauses. Each clause maps a
6//! facet key to a constraint: an ordinal `"<= term"` / `">= term"` / `"term"`
7//! (exact), or a categorical term / list of terms. Compound facets are nested
8//! tables (`locus = { local = "<= worktree", remote = "none" }`).
9//!
10//! `extends` composes upward only (R27): an extending level inherits its base's
11//! allow *and* deny clauses and may add only allow clauses — declaring `deny` on an
12//! extending level is a compile error.
13
14use std::collections::BTreeMap;
15use std::sync::LazyLock;
16
17use serde::{Deserialize, Serialize};
18
19use super::facet::FacetTerm;
20use super::level::{Clause, Level, OrdBound};
21
22/// The default level set, compiled once from the embedded `levels/default.toml`.
23pub fn default_levels() -> &'static [Level] {
24    static LEVELS: LazyLock<Vec<Level>> = LazyLock::new(|| {
25        build_level_set(include_str!("../../levels/default.toml"))
26            .expect("embedded levels/default.toml must compile")
27    });
28    &LEVELS
29}
30
31/// Compile a TOML level set into levels, resolving `extends` in dependency order.
32pub fn build_level_set(source: &str) -> Result<Vec<Level>, String> {
33    let set: TomlLevelSet = toml::from_str(source).map_err(|e| e.to_string())?;
34    let mut pending: Vec<(String, TomlLevel)> = set.level.into_iter().collect();
35    let mut built: Vec<Level> = Vec::new();
36    let mut by_name: BTreeMap<String, usize> = BTreeMap::new();
37
38    while !pending.is_empty() {
39        let before = pending.len();
40        let mut still = Vec::new();
41        for (name, tl) in pending {
42            let ready = tl.extends.as_ref().is_none_or(|base| by_name.contains_key(base));
43            if ready {
44                let level = compile_level(name.clone(), tl, &built, &by_name)?;
45                by_name.insert(name, built.len());
46                built.push(level);
47            } else {
48                still.push((name, tl));
49            }
50        }
51        if still.len() == before {
52            let names: Vec<&String> = still.iter().map(|(n, _)| n).collect();
53            return Err(format!("unresolved `extends` (cycle or missing base) among {names:?}"));
54        }
55        pending = still;
56    }
57    Ok(built)
58}
59
60fn compile_level(
61    name: String,
62    tl: TomlLevel,
63    built: &[Level],
64    by_name: &BTreeMap<String, usize>,
65) -> Result<Level, String> {
66    let allow = tl
67        .allow
68        .into_iter()
69        .map(build_clause)
70        .collect::<Result<Vec<_>, _>>()
71        .map_err(|e| format!("level `{name}`: {e}"))?;
72    let deny = tl
73        .deny
74        .into_iter()
75        .map(build_clause)
76        .collect::<Result<Vec<_>, _>>()
77        .map_err(|e| format!("level `{name}`: {e}"))?;
78
79    match tl.extends {
80        Some(base_name) => {
81            if !deny.is_empty() {
82                return Err(format!(
83                    "level `{name}` extends `{base_name}` and declares `deny` — extends only \
84                     loosens (R27); author a stricter level from a lower base instead"
85                ));
86            }
87            let idx = *by_name
88                .get(&base_name)
89                .ok_or_else(|| format!("level `{name}`: unknown base `{base_name}`"))?;
90            let base = built
91                .get(idx)
92                .ok_or_else(|| format!("level `{name}`: base index out of range"))?;
93            Ok(Level::extend(base, name, allow))
94        }
95        None => Ok(Level { name, allow, deny }),
96    }
97}
98
99fn build_clause(tc: TomlClause) -> Result<Clause, String> {
100    let mut c = Clause::default();
101    if let Some(v) = tc.operation {
102        c.operation = Some(parse_set(&v)?);
103    }
104    if let Some(l) = tc.locus {
105        c.local_locus = opt_bound(l.local.as_deref())?;
106        c.remote_reach = opt_bound(l.remote.as_deref())?;
107        c.provenance = opt_bound(l.provenance.as_deref())?;
108        if let Some(b) = l.binding {
109            c.remote_binding = Some(parse_set(&b)?);
110        }
111    }
112    c.scale = opt_bound(tc.scale.as_deref())?;
113    c.retrieval = opt_bound(tc.retrieval.as_deref())?;
114    c.authority = opt_bound(tc.authority.as_deref())?;
115    c.isolation = opt_bound(tc.isolation.as_deref())?;
116    c.reversibility = opt_bound(tc.reversibility.as_deref())?;
117    if let Some(p) = tc.persistence {
118        c.persistence_level = opt_bound(p.level.as_deref())?;
119        if let Some(t) = p.trigger {
120            c.trigger_escape = opt_bound(t.escape.as_deref())?;
121            if let Some(k) = t.kind {
122                c.trigger_kind = Some(parse_set(&k)?);
123            }
124        }
125    }
126    if let Some(d) = tc.disclosure {
127        c.disclosure_audience = opt_bound(d.audience.as_deref())?;
128        if let Some(ch) = d.channel {
129            c.disclosure_channel = Some(parse_set(&ch)?);
130        }
131        if let Some(pr) = d.principal {
132            c.disclosure_principal = Some(parse_set(&pr)?);
133        }
134    }
135    if let Some(s) = tc.secret {
136        c.secret_level = opt_bound(s.level.as_deref())?;
137        if let Some(ch) = s.channel {
138            c.secret_channel = Some(parse_set(&ch)?);
139        }
140        if let Some(pr) = s.principal {
141            c.secret_principal = Some(parse_set(&pr)?);
142        }
143    }
144    if let Some(n) = tc.network {
145        c.net_direction = opt_bound(n.direction.as_deref())?;
146        c.net_destination = opt_bound(n.destination.as_deref())?;
147        c.net_payload = opt_bound(n.payload.as_deref())?;
148    }
149    c.execution_trust = opt_bound(tc.execution.as_deref())?;
150    if let Some(sc) = tc.supply_chain {
151        if let Some(s) = sc.source {
152            c.supply_source = Some(parse_set(&s)?);
153        }
154        c.pinning = opt_bound(sc.pinning.as_deref())?;
155        if let Some(e) = sc.exec_surface {
156            c.exec_surface = Some(parse_set(&e)?);
157        }
158    }
159    c.cost = opt_bound(tc.cost.as_deref())?;
160    Ok(c)
161}
162
163fn opt_bound<T: FacetTerm + Ord>(s: Option<&str>) -> Result<Option<OrdBound<T>>, String> {
164    s.map(parse_bound).transpose()
165}
166
167/// Parse an ordinal constraint: `"<= term"`, `">= term"`, `"term"` (exact), or a
168/// two-sided range `">= lo, <= hi"` (a comma-separated floor and ceiling, order
169/// insensitive). A range is the only form that pins both ends — needed where an
170/// admit set is an interior band of the ladder (e.g. an executor locus that is
171/// worktree-local but neither below it, `temp`, nor above it, `user`).
172fn parse_bound<T: FacetTerm + Ord>(s: &str) -> Result<OrdBound<T>, String> {
173    let parts: Vec<&str> = s.split(',').map(str::trim).collect();
174    if parts.len() == 1 {
175        let p = parts[0];
176        return if let Some(rest) = p.strip_prefix("<=") {
177            Ok(OrdBound::at_most(parse_term(rest)?))
178        } else if let Some(rest) = p.strip_prefix(">=") {
179            Ok(OrdBound::at_least(parse_term(rest)?))
180        } else {
181            Ok(OrdBound::exactly(parse_term(p.strip_prefix('=').unwrap_or(p))?))
182        };
183    }
184    let (mut min, mut max) = (None, None);
185    for p in parts {
186        if let Some(rest) = p.strip_prefix("<=") {
187            if max.replace(parse_term(rest)?).is_some() {
188                return Err(format!("bound `{s}` sets `<=` more than once"));
189            }
190        } else if let Some(rest) = p.strip_prefix(">=") {
191            if min.replace(parse_term(rest)?).is_some() {
192                return Err(format!("bound `{s}` sets `>=` more than once"));
193            }
194        } else {
195            return Err(format!("bound `{s}`: each part of a range must be `<=`/`>=`"));
196        }
197    }
198    Ok(OrdBound { min, max })
199}
200
201fn parse_set<T: FacetTerm>(v: &StringOrVec) -> Result<Vec<T>, String> {
202    v.as_slice().iter().map(|s| parse_term(s)).collect()
203}
204
205fn parse_term<T: FacetTerm>(s: &str) -> Result<T, String> {
206    T::from_term(s.trim()).ok_or_else(|| format!("unknown term `{}`", s.trim()))
207}
208
209// ── the TOML schema ────────────────────────────────────────────────────────────
210
211// Serialization mirrors deserialization so a compiled level round-trips back to
212// equivalent TOML (`skip_serializing_if` keeps unset facets out of the output).
213
214#[derive(Deserialize, Serialize)]
215struct TomlLevelSet {
216    #[serde(default)]
217    level: BTreeMap<String, TomlLevel>,
218}
219
220#[derive(Deserialize, Serialize)]
221#[serde(deny_unknown_fields)]
222struct TomlLevel {
223    #[serde(skip_serializing_if = "Option::is_none")]
224    extends: Option<String>,
225    #[serde(default, skip_serializing_if = "Vec::is_empty")]
226    allow: Vec<TomlClause>,
227    #[serde(default, skip_serializing_if = "Vec::is_empty")]
228    deny: Vec<TomlClause>,
229}
230
231#[derive(Deserialize, Serialize, Default)]
232#[serde(deny_unknown_fields)]
233struct TomlClause {
234    #[serde(skip_serializing_if = "Option::is_none")]
235    operation: Option<StringOrVec>,
236    #[serde(skip_serializing_if = "Option::is_none")]
237    locus: Option<TomlLocus>,
238    #[serde(skip_serializing_if = "Option::is_none")]
239    scale: Option<String>,
240    #[serde(skip_serializing_if = "Option::is_none")]
241    retrieval: Option<String>,
242    #[serde(skip_serializing_if = "Option::is_none")]
243    authority: Option<String>,
244    #[serde(skip_serializing_if = "Option::is_none")]
245    isolation: Option<String>,
246    #[serde(skip_serializing_if = "Option::is_none")]
247    reversibility: Option<String>,
248    #[serde(skip_serializing_if = "Option::is_none")]
249    persistence: Option<TomlPersistence>,
250    #[serde(skip_serializing_if = "Option::is_none")]
251    disclosure: Option<TomlDisclosure>,
252    #[serde(skip_serializing_if = "Option::is_none")]
253    secret: Option<TomlSecret>,
254    #[serde(skip_serializing_if = "Option::is_none")]
255    network: Option<TomlNetwork>,
256    #[serde(skip_serializing_if = "Option::is_none")]
257    execution: Option<String>,
258    #[serde(skip_serializing_if = "Option::is_none")]
259    supply_chain: Option<TomlSupplyChain>,
260    #[serde(skip_serializing_if = "Option::is_none")]
261    cost: Option<String>,
262}
263
264#[derive(Deserialize, Serialize)]
265#[serde(deny_unknown_fields)]
266struct TomlLocus {
267    #[serde(skip_serializing_if = "Option::is_none")]
268    local: Option<String>,
269    #[serde(skip_serializing_if = "Option::is_none")]
270    remote: Option<String>,
271    #[serde(skip_serializing_if = "Option::is_none")]
272    binding: Option<StringOrVec>,
273    #[serde(skip_serializing_if = "Option::is_none")]
274    provenance: Option<String>,
275}
276
277#[derive(Deserialize, Serialize)]
278#[serde(deny_unknown_fields)]
279struct TomlPersistence {
280    #[serde(skip_serializing_if = "Option::is_none")]
281    level: Option<String>,
282    #[serde(skip_serializing_if = "Option::is_none")]
283    trigger: Option<TomlTrigger>,
284}
285
286#[derive(Deserialize, Serialize)]
287#[serde(deny_unknown_fields)]
288struct TomlTrigger {
289    #[serde(skip_serializing_if = "Option::is_none")]
290    escape: Option<String>,
291    #[serde(skip_serializing_if = "Option::is_none")]
292    kind: Option<StringOrVec>,
293}
294
295#[derive(Deserialize, Serialize)]
296#[serde(deny_unknown_fields)]
297struct TomlDisclosure {
298    #[serde(skip_serializing_if = "Option::is_none")]
299    audience: Option<String>,
300    #[serde(skip_serializing_if = "Option::is_none")]
301    channel: Option<StringOrVec>,
302    #[serde(skip_serializing_if = "Option::is_none")]
303    principal: Option<StringOrVec>,
304}
305
306#[derive(Deserialize, Serialize)]
307#[serde(deny_unknown_fields)]
308struct TomlSecret {
309    #[serde(skip_serializing_if = "Option::is_none")]
310    level: Option<String>,
311    #[serde(skip_serializing_if = "Option::is_none")]
312    channel: Option<StringOrVec>,
313    #[serde(skip_serializing_if = "Option::is_none")]
314    principal: Option<StringOrVec>,
315}
316
317#[derive(Deserialize, Serialize)]
318#[serde(deny_unknown_fields)]
319struct TomlNetwork {
320    #[serde(skip_serializing_if = "Option::is_none")]
321    direction: Option<String>,
322    #[serde(skip_serializing_if = "Option::is_none")]
323    destination: Option<String>,
324    #[serde(skip_serializing_if = "Option::is_none")]
325    payload: Option<String>,
326}
327
328#[derive(Deserialize, Serialize)]
329#[serde(deny_unknown_fields)]
330struct TomlSupplyChain {
331    #[serde(skip_serializing_if = "Option::is_none")]
332    source: Option<StringOrVec>,
333    #[serde(skip_serializing_if = "Option::is_none")]
334    pinning: Option<String>,
335    #[serde(skip_serializing_if = "Option::is_none")]
336    exec_surface: Option<StringOrVec>,
337}
338
339#[derive(Deserialize, Serialize)]
340#[serde(untagged)]
341enum StringOrVec {
342    One(String),
343    Many(Vec<String>),
344}
345
346impl StringOrVec {
347    fn as_slice(&self) -> &[String] {
348        match self {
349            StringOrVec::One(s) => std::slice::from_ref(s),
350            StringOrVec::Many(v) => v,
351        }
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358    use crate::engine::facet::*;
359
360    fn level<'a>(levels: &'a [Level], name: &str) -> &'a Level {
361        levels.iter().find(|l| l.name == name).expect("level exists")
362    }
363
364    fn observe_at(local: LocalLocus) -> Profile {
365        let mut c = Capability::new(Operation::Observe);
366        c.locus.local = local;
367        Profile::of(vec![c])
368    }
369
370    #[test]
371    fn the_default_ladder_compiles() {
372        let levels = default_levels();
373        let mut names: Vec<&str> = levels.iter().map(|l| l.name.as_str()).collect();
374        names.sort_unstable();
375        assert_eq!(
376            names,
377            ["developer", "editor", "local-admin", "network-admin", "paranoid", "reader", "yolo"],
378        );
379        // yolo is a base level (carries the catastrophe `deny`), so build order isn't the ladder
380        // order — but the mapped auto-approve band MUST stay ascending, since `bridge::project`
381        // returns the first admitting mapped level as the minimum.
382        let raw: Vec<&str> = levels.iter().map(|l| l.name.as_str()).collect();
383        let pos = |n| raw.iter().position(|&x| x == n).expect("level present");
384        assert!(
385            pos("paranoid") < pos("reader") && pos("reader") < pos("editor") && pos("editor") < pos("developer"),
386            "mapped band out of order: {raw:?}",
387        );
388    }
389
390    #[test]
391    fn inert_admits_a_version_probe_but_not_reading_the_worktree() {
392        let levels = default_levels();
393        let inert = level(levels, "paranoid");
394        assert!(inert.admits(&observe_at(LocalLocus::Process)), "node --version");
395        assert!(!inert.admits(&observe_at(LocalLocus::Worktree)), "cat ./notes is above paranoid");
396    }
397
398    #[test]
399    fn read_local_reads_the_worktree_but_refuses_home_extraction_and_writes() {
400        let levels = default_levels();
401        let read_local = level(levels, "reader");
402        assert!(read_local.admits(&observe_at(LocalLocus::Worktree)), "cat ./notes");
403        assert!(read_local.admits(&observe_at(LocalLocus::WorktreeTrusted)), "git status reads .git");
404
405        // home content read — denied by LOCUS, not by any secret detection
406        // (cat ~/.ssh/id_rsa: locus=user, secret=none — cat extracts no credential)
407        assert!(!read_local.admits(&observe_at(LocalLocus::User)), "cat ~/.ssh/id_rsa");
408
409        // a credential-extraction command — denied by the positive secret claim
410        // (security find-generic-password -w: secret=reads, regardless of locus)
411        let extraction = {
412            let mut c = Capability::new(Operation::Observe);
413            c.secret.level = SecretLevel::Reads;
414            Profile::of(vec![c])
415        };
416        assert!(!read_local.admits(&extraction), "keychain extraction");
417
418        assert!(!read_local.admits(&Profile::of(vec![Capability::new(Operation::Create)])), "a write");
419    }
420
421    /// reader reads LOCAL and REMOTE alike (a pure fetch is a read), but the network read is a
422    /// pure fetch, never an egress: `sends-host-data` (exfil) and any remote WRITE stay above it.
423    #[test]
424    fn reader_admits_a_pure_remote_fetch_but_not_exfil_or_remote_writes() {
425        let reader = level(default_levels(), "reader");
426
427        let fetch = {
428            let mut c = Capability::new(Operation::Observe);
429            c.locus.remote = RemoteReach::Arbitrary;
430            c.network.direction = NetDirection::Outbound;
431            c.network.payload = NetPayload::Fetches;
432            c.disclosure.audience = DisclosureAudience::LocalProcess;
433            Profile::of(vec![c])
434        };
435        assert!(reader.admits(&fetch), "curl GET / koyeb list — a pure remote fetch");
436
437        // exfil: the request carries host data OUT — above reader
438        let exfil = {
439            let mut c = Capability::new(Operation::Observe);
440            c.locus.remote = RemoteReach::Arbitrary;
441            c.network.direction = NetDirection::Outbound;
442            c.network.payload = NetPayload::SendsHostData;
443            Profile::of(vec![c])
444        };
445        assert!(!reader.admits(&exfil), "sends-host-data (curl -d @secret) is not a read");
446
447        // a remote WRITE — above reader (this is the nuance that lives on the write side)
448        let remote_write = {
449            let mut c = Capability::new(Operation::Mutate);
450            c.locus.remote = RemoteReach::Fixed;
451            c.network.direction = NetDirection::Outbound;
452            Profile::of(vec![c])
453        };
454        assert!(!reader.admits(&remote_write), "a remote write is network-admin, not reader");
455
456        // paranoid still blocks the network entirely
457        assert!(!level(default_levels(), "paranoid").admits(&fetch), "paranoid blocks all network");
458    }
459
460    #[test]
461    fn write_local_writes_the_worktree_but_not_installs_or_mass_ops() {
462        let levels = default_levels();
463        let write_local = level(levels, "editor");
464
465        let touch = {
466            let mut c = Capability::new(Operation::Create);
467            c.locus.local = LocalLocus::Worktree;
468            Profile::of(vec![c])
469        };
470        assert!(write_local.admits(&touch), "touch build/out");
471        // still reads (inherited)
472        assert!(write_local.admits(&observe_at(LocalLocus::Worktree)));
473
474        let install = {
475            let mut c = Capability::new(Operation::Create);
476            c.locus.local = LocalLocus::Worktree;
477            c.persistence.level = PersistenceLevel::Installing;
478            Profile::of(vec![c])
479        };
480        assert!(!write_local.admits(&install), "installing is above write-local");
481    }
482
483    #[test]
484    fn developer_deletes_within_the_worktree_but_not_beyond_it() {
485        let levels = default_levels();
486        let (write_local, developer) = (level(levels, "editor"), level(levels, "developer"));
487
488        let destroy_at = |local| {
489            let mut c = Capability::new(Operation::Destroy);
490            c.locus.local = local;
491            c.scale = Scale::Unbounded; // rm -rf
492            c.reversibility = Reversibility::Effortful;
493            Profile::of(vec![c])
494        };
495        // recursive/effortful worktree delete admits at developer, but not at write-local
496        assert!(!write_local.admits(&destroy_at(LocalLocus::Worktree)), "rm waits for developer");
497        assert!(developer.admits(&destroy_at(LocalLocus::Worktree)), "rm -rf ./node_modules");
498        // .git/ (worktree-trusted), home, and system deletion stay above developer
499        assert!(!developer.admits(&destroy_at(LocalLocus::WorktreeTrusted)), "rm -rf .git");
500        assert!(!developer.admits(&destroy_at(LocalLocus::User)), "rm -rf ~");
501        assert!(!developer.admits(&destroy_at(LocalLocus::Machine)), "rm -rf /");
502
503        // the boundary is destroy vs create/overwrite: overwriting your own worktree file
504        // (a recoverable create — echo > f, cp ./a ./b) stays at write-local, NOT developer.
505        let overwrite = {
506            let mut c = Capability::new(Operation::Create);
507            c.locus.local = LocalLocus::Worktree;
508            c.reversibility = Reversibility::Recoverable;
509            c.persistence.level = PersistenceLevel::Data;
510            Profile::of(vec![c])
511        };
512        assert!(write_local.admits(&overwrite), "cp ./a ./b is write-local (create), not developer");
513        // developer still inherits every write-local grant
514        let touch = {
515            let mut c = Capability::new(Operation::Create);
516            c.locus.local = LocalLocus::Worktree;
517            Profile::of(vec![c])
518        };
519        assert!(developer.admits(&touch), "developer ⊇ write-local");
520    }
521
522    #[test]
523    fn the_ladder_nests() {
524        let levels = default_levels();
525        let (inert, read, write) =
526            (level(levels, "paranoid"), level(levels, "reader"), level(levels, "editor"));
527        // everything inert admits, read-local and write-local admit too
528        for local in [LocalLocus::Process, LocalLocus::Temp] {
529            let p = observe_at(local);
530            assert!(inert.admits(&p) && read.admits(&p) && write.admits(&p));
531        }
532    }
533
534    /// The two admin flavors are INCOMPARABLE siblings above developer — each flexes a
535    /// disjoint facet region (local-admin down into the machine, network-admin out to the
536    /// network), and BOTH keep developer's `reversibility <= effortful` cap. Only yolo lifts
537    /// it. This is the partial-order the old linear `SafetyLevel` enum could not express.
538    #[test]
539    fn the_admin_flavors_flex_disjoint_regions_and_only_yolo_is_irreversible() {
540        let levels = default_levels();
541        let developer = level(levels, "developer");
542        let local_admin = level(levels, "local-admin");
543        let network_admin = level(levels, "network-admin");
544        let yolo = level(levels, "yolo");
545
546        // sudo: elevated authority on the machine — local-admin admits, network-admin refuses
547        let sudo = {
548            let mut c = Capability::new(Operation::Mutate);
549            c.locus.local = LocalLocus::Machine;
550            c.authority = Authority::Root;
551            Profile::of(vec![c])
552        };
553        assert!(!developer.admits(&sudo), "sudo is above developer");
554        assert!(local_admin.admits(&sudo), "local-admin runs this machine");
555        assert!(!network_admin.admits(&sudo), "network-admin never sudo's the box");
556
557        // remote mutate over the network — network-admin admits, local-admin refuses
558        let remote = {
559            let mut c = Capability::new(Operation::Mutate);
560            c.locus.remote = RemoteReach::Arbitrary;
561            c.network.direction = NetDirection::Outbound;
562            Profile::of(vec![c])
563        };
564        assert!(!developer.admits(&remote), "remote reach is above developer");
565        assert!(network_admin.admits(&remote), "network-admin operates remotes");
566        assert!(!local_admin.admits(&remote), "local-admin never reaches the network");
567
568        // the reversibility spine: irreversible destroy is reserved for yolo, on ANY locus
569        let irreversible = |local, remote| {
570            let mut c = Capability::new(Operation::Destroy);
571            c.locus.local = local;
572            c.locus.remote = remote;
573            c.reversibility = Reversibility::Irreversible;
574            Profile::of(vec![c])
575        };
576        let mkfs = irreversible(LocalLocus::Device, RemoteReach::None); // disk wipe
577        let tf_destroy = irreversible(LocalLocus::Process, RemoteReach::Fixed); // terraform destroy
578        assert!(!local_admin.admits(&mkfs), "mkfs (irreversible) is above local-admin");
579        assert!(!network_admin.admits(&tf_destroy), "terraform destroy (irreversible) is above network-admin");
580        assert!(yolo.admits(&mkfs) && yolo.admits(&tf_destroy), "irreversible destroy is reserved for yolo");
581
582        // but recoverable/effortful destruction in each direction stays at the flavor
583        let effortful_machine = {
584            let mut c = Capability::new(Operation::Destroy);
585            c.locus.local = LocalLocus::Machine;
586            c.scale = Scale::Unbounded;
587            c.reversibility = Reversibility::Effortful;
588            Profile::of(vec![c])
589        };
590        assert!(local_admin.admits(&effortful_machine), "sudo rm -rf /var (recoverable) is local-admin");
591    }
592
593    /// yolo lifts every cap EXCEPT the one catastrophe corner, carved purely by facets:
594    /// `destroy · irreversible · unbounded` (rm -rf /). Everything adjacent — bounded or
595    /// single-target irreversible destroy, or recoverable mass destroy — stays admitted,
596    /// distinguished by facet alone, never by command name.
597    #[test]
598    fn yolo_denies_only_unbounded_irreversible_destroy() {
599        let levels = default_levels();
600        let yolo = level(levels, "yolo");
601
602        let destroy = |scale, rev| {
603            let mut c = Capability::new(Operation::Destroy);
604            c.scale = scale;
605            c.reversibility = rev;
606            c.locus.local = LocalLocus::Machine;
607            Profile::of(vec![c])
608        };
609        // the one refusal: rm -rf / — destroy the world, no recovery, no bound
610        assert!(
611            !yolo.admits(&destroy(Scale::Unbounded, Reversibility::Irreversible)),
612            "rm -rf / is denied even at yolo",
613        );
614        // everything one facet away stays yolo-allowed, by facet:
615        assert!(yolo.admits(&destroy(Scale::Bounded, Reversibility::Irreversible)), "terraform destroy (bounded)");
616        assert!(yolo.admits(&destroy(Scale::Single, Reversibility::Irreversible)), "mkfs (single device)");
617        assert!(yolo.admits(&destroy(Scale::Unbounded, Reversibility::Effortful)), "rm -rf ./x (recoverable)");
618        // and yolo still admits the non-destroy extremes it exists for
619        let wild = {
620            let mut c = Capability::new(Operation::Execute);
621            c.execution.trust = ExecutionTrust::NetworkSourced;
622            c.locus.local = LocalLocus::Kernel;
623            Profile::of(vec![c])
624        };
625        assert!(yolo.admits(&wild), "yolo still admits everything but the catastrophe corner");
626    }
627
628    #[test]
629    fn unknown_term_is_a_compile_error() {
630        let src = r#"
631            [level.x]
632            [[level.x.allow]]
633            scale = "<= enormous"
634        "#;
635        let err = build_level_set(src).unwrap_err();
636        assert!(err.contains("enormous"), "{err}");
637    }
638
639    #[test]
640    fn unknown_facet_key_is_a_compile_error() {
641        let src = r#"
642            [level.x]
643            [[level.x.allow]]
644            operashun = ["observe"]
645        "#;
646        assert!(build_level_set(src).is_err());
647    }
648
649    #[test]
650    fn deny_on_an_extending_level_is_rejected() {
651        let src = r#"
652            [level.base]
653            [[level.base.allow]]
654            operation = ["observe"]
655
656            [level.child]
657            extends = "base"
658            [[level.child.deny]]
659            operation = ["destroy"]
660        "#;
661        let err = build_level_set(src).unwrap_err();
662        assert!(err.contains("R27"), "{err}");
663    }
664
665    #[test]
666    fn scalar_facet_values_parse() {
667        // a set-valued facet given as a scalar (StringOrVec::One), not an array
668        let src = r#"
669            [level.x]
670            [[level.x.allow]]
671            operation = "observe"
672            locus = { binding = "pinned" }
673        "#;
674        let levels = build_level_set(src).expect("compiles");
675        let c = &level(&levels, "x").allow[0];
676        assert_eq!(c.operation, Some(vec![Operation::Observe]));
677        assert_eq!(c.remote_binding, Some(vec![RemoteBinding::Pinned]));
678    }
679
680    #[test]
681    fn a_mutual_extends_cycle_is_a_compile_error() {
682        let src = r#"
683            [level.a]
684            extends = "b"
685            [level.b]
686            extends = "a"
687        "#;
688        assert!(build_level_set(src).is_err());
689    }
690
691    #[test]
692    fn missing_base_is_a_compile_error() {
693        let src = r#"
694            [level.child]
695            extends = "ghost"
696            [[level.child.allow]]
697            operation = ["observe"]
698        "#;
699        assert!(build_level_set(src).is_err());
700    }
701
702    #[test]
703    fn ordinal_operators_parse() {
704        let src = r#"
705            [level.x]
706            [[level.x.allow]]
707            scale = ">= bounded"
708            reversibility = "<= recoverable"
709            authority = "root"
710        "#;
711        let levels = build_level_set(src).expect("compiles");
712        let clause = &level(&levels, "x").allow[0];
713        assert_eq!(clause.scale, Some(OrdBound::at_least(Scale::Bounded)));
714        assert_eq!(clause.reversibility, Some(OrdBound::at_most(Reversibility::Recoverable)));
715        assert_eq!(clause.authority, Some(OrdBound::exactly(Authority::Root)));
716    }
717
718    // ── facet-monotonicity: the coherence check on the authored levels ──────────────
719    //
720    // A level is coherent iff making any command *less* severe never flips it from
721    // admitted to denied. An allow clause with an ordinal *floor* (or an exact bound
722    // on a non-minimum term) would break this — the check exists to catch that in
723    // hand-authored TOML.
724
725    use crate::engine::testgen::{arb_capability, arb_profile, lowered_variants};
726    use proptest::prelude::*;
727
728    fn assert_monotone_from(lvl: &Level, boundary: Capability) {
729        assert!(
730            lvl.admits(&Profile::of(vec![boundary.clone()])),
731            "{}: boundary capability should be admitted",
732            lvl.name,
733        );
734        for lowered in lowered_variants(&boundary) {
735            assert!(
736                lvl.admits(&Profile::of(vec![lowered.clone()])),
737                "{}: admitted a boundary cap but denied it after lowering one facet:\n  {:?}\n  {:?}",
738                lvl.name,
739                boundary,
740                lowered,
741            );
742        }
743    }
744
745    #[test]
746    fn authored_levels_are_monotone_at_their_ceilings() {
747        let levels = default_levels();
748
749        let mut inert_cap = Capability::new(Operation::Observe);
750        inert_cap.locus.local = LocalLocus::Temp;
751        inert_cap.disclosure.audience = DisclosureAudience::LocalProcess;
752        inert_cap.execution.trust = ExecutionTrust::SelfCode;
753        assert_monotone_from(level(levels, "paranoid"), inert_cap);
754
755        let mut read_cap = Capability::new(Operation::Observe);
756        read_cap.locus.local = LocalLocus::WorktreeTrusted;
757        read_cap.secret.level = SecretLevel::UsesAmbient;
758        read_cap.network.direction = NetDirection::Loopback;
759        read_cap.disclosure.audience = DisclosureAudience::LocalProcess;
760        read_cap.execution.trust = ExecutionTrust::SelfCode;
761        assert_monotone_from(level(levels, "reader"), read_cap);
762
763        let mut write_cap = Capability::new(Operation::Mutate);
764        write_cap.locus.local = LocalLocus::Worktree;
765        write_cap.scale = Scale::Bounded;
766        write_cap.reversibility = Reversibility::Recoverable;
767        write_cap.persistence.level = PersistenceLevel::Data;
768        write_cap.secret.level = SecretLevel::UsesAmbient;
769        write_cap.disclosure.audience = DisclosureAudience::LocalProcess;
770        write_cap.execution.trust = ExecutionTrust::CallerInline;
771        assert_monotone_from(level(levels, "editor"), write_cap);
772    }
773
774    // ── union-level completeness: flat DNF's failure mode is a silent gap ────────────
775    //
776    // A level authored as a UNION of allow clauses to mean "allow almost everything" must admit a
777    // capability IFF it is not in that level's ONE intended hole. A missing clause leaves an
778    // accidental gap (a benign capability nothing admits → over-deny); a too-wide clause leaks the
779    // hole (the corner slips in → fail-open). This proves the union has EXACTLY its declared gap —
780    // the guard flat DNF needs before we lean on union constructions. Table-driven: add a row when
781    // a new union-level is authored, and the whole class stays covered.
782    proptest! {
783        #[test]
784        fn union_levels_admit_everything_but_their_declared_gap(cap in arb_capability()) {
785            let gaps: &[(&str, fn(&Capability) -> bool)] = &[
786                // yolo withholds only `destroy · irreversible · unbounded` (rm -rf /), carved by
787                // the union of its allow clauses — never by a deny.
788                ("yolo", |c: &Capability| {
789                    c.operation == Operation::Destroy
790                        && c.reversibility == Reversibility::Irreversible
791                        && c.scale == Scale::Unbounded
792                }),
793            ];
794            let levels = default_levels();
795            for (name, gap) in gaps {
796                let lvl = levels.iter().find(|l| &l.name == name).expect("level present");
797                let admitted = lvl.admits(&Profile::of(vec![cap.clone()]));
798                prop_assert_eq!(
799                    admitted, !gap(&cap),
800                    "level `{}`: capability {:?} admitted={} but intended_admit={}",
801                    name, cap, admitted, !gap(&cap),
802                );
803            }
804        }
805    }
806
807    proptest! {
808        /// For any profile an authored level admits, lowering any single ordinal facet
809        /// of any capability keeps the profile admitted.
810        #[test]
811        fn authored_levels_are_facet_monotone(profile in arb_profile()) {
812            for lvl in default_levels() {
813                if !lvl.admits(&profile) {
814                    continue;
815                }
816                for (i, cap) in profile.capabilities.iter().enumerate() {
817                    for lowered in lowered_variants(cap) {
818                        let mut lowered_profile = profile.clone();
819                        lowered_profile.capabilities[i] = lowered;
820                        prop_assert!(
821                            lvl.admits(&lowered_profile),
822                            "{} broke facet-monotonicity",
823                            lvl.name,
824                        );
825                    }
826                }
827            }
828        }
829    }
830
831    // ── round-trip: Level -> TOML -> Level is identity ──────────────────────────────
832    //
833    // The reverse of build_clause: a compiled clause serializes back to equivalent
834    // TOML that recompiles to the same clause. Mirrors every operator the parser
835    // produces (<=, >=, exact, and the two-sided range).
836
837    fn bound_str<T: FacetTerm>(b: OrdBound<T>) -> String {
838        match (b.min, b.max) {
839            (Some(lo), Some(hi)) if lo == hi => lo.as_str().to_string(),
840            (Some(lo), Some(hi)) => format!(">= {}, <= {}", lo.as_str(), hi.as_str()),
841            (None, Some(hi)) => format!("<= {}", hi.as_str()),
842            (Some(lo), None) => format!(">= {}", lo.as_str()),
843            (None, None) => panic!("empty bound has no representation"),
844        }
845    }
846
847    fn opt_bound_str<T: FacetTerm>(b: Option<OrdBound<T>>) -> Option<String> {
848        b.map(bound_str)
849    }
850
851    fn set_str<T: FacetTerm>(v: &[T]) -> StringOrVec {
852        StringOrVec::Many(v.iter().map(|t| t.as_str().to_string()).collect())
853    }
854
855    fn clause_to_toml(c: &Clause) -> TomlClause {
856        let locus = (c.local_locus.is_some()
857            || c.remote_reach.is_some()
858            || c.remote_binding.is_some()
859            || c.provenance.is_some())
860        .then(|| TomlLocus {
861            local: opt_bound_str(c.local_locus),
862            remote: opt_bound_str(c.remote_reach),
863            binding: c.remote_binding.as_deref().map(set_str),
864            provenance: opt_bound_str(c.provenance),
865        });
866        let persistence = (c.persistence_level.is_some()
867            || c.trigger_escape.is_some()
868            || c.trigger_kind.is_some())
869        .then(|| TomlPersistence {
870            level: opt_bound_str(c.persistence_level),
871            trigger: (c.trigger_escape.is_some() || c.trigger_kind.is_some()).then(|| TomlTrigger {
872                escape: opt_bound_str(c.trigger_escape),
873                kind: c.trigger_kind.as_deref().map(set_str),
874            }),
875        });
876        let disclosure = (c.disclosure_audience.is_some()
877            || c.disclosure_channel.is_some()
878            || c.disclosure_principal.is_some())
879        .then(|| TomlDisclosure {
880            audience: opt_bound_str(c.disclosure_audience),
881            channel: c.disclosure_channel.as_deref().map(set_str),
882            principal: c.disclosure_principal.as_deref().map(set_str),
883        });
884        let secret = (c.secret_level.is_some()
885            || c.secret_channel.is_some()
886            || c.secret_principal.is_some())
887        .then(|| TomlSecret {
888            level: opt_bound_str(c.secret_level),
889            channel: c.secret_channel.as_deref().map(set_str),
890            principal: c.secret_principal.as_deref().map(set_str),
891        });
892        let network = (c.net_direction.is_some()
893            || c.net_destination.is_some()
894            || c.net_payload.is_some())
895        .then(|| TomlNetwork {
896            direction: opt_bound_str(c.net_direction),
897            destination: opt_bound_str(c.net_destination),
898            payload: opt_bound_str(c.net_payload),
899        });
900        let supply_chain = (c.supply_source.is_some()
901            || c.pinning.is_some()
902            || c.exec_surface.is_some())
903        .then(|| TomlSupplyChain {
904            source: c.supply_source.as_deref().map(set_str),
905            pinning: opt_bound_str(c.pinning),
906            exec_surface: c.exec_surface.as_deref().map(set_str),
907        });
908        TomlClause {
909            operation: c.operation.as_deref().map(set_str),
910            locus,
911            scale: opt_bound_str(c.scale),
912            retrieval: opt_bound_str(c.retrieval),
913            authority: opt_bound_str(c.authority),
914            isolation: opt_bound_str(c.isolation),
915            reversibility: opt_bound_str(c.reversibility),
916            persistence,
917            disclosure,
918            secret,
919            network,
920            execution: opt_bound_str(c.execution_trust),
921            supply_chain,
922            cost: opt_bound_str(c.cost),
923        }
924    }
925
926    fn round_trip(levels: &[Level]) -> Vec<Level> {
927        let level = levels
928            .iter()
929            .map(|l| {
930                let tl = TomlLevel {
931                    extends: None,
932                    allow: l.allow.iter().map(clause_to_toml).collect(),
933                    deny: l.deny.iter().map(clause_to_toml).collect(),
934                };
935                (l.name.clone(), tl)
936            })
937            .collect();
938        let source = toml::to_string(&TomlLevelSet { level }).expect("serialize");
939        build_level_set(&source).expect("re-parse serialized levels")
940    }
941
942    fn assert_round_trips(levels: &[Level]) {
943        let round = round_trip(levels);
944        for original in levels {
945            let back = round.iter().find(|l| l.name == original.name).expect("level survives");
946            assert_eq!(original.allow, back.allow, "{} allow clauses", original.name);
947            assert_eq!(original.deny, back.deny, "{} deny clauses", original.name);
948        }
949    }
950
951    #[test]
952    fn authored_levels_round_trip() {
953        assert_round_trips(default_levels());
954    }
955
956    #[test]
957    fn every_facet_round_trips() {
958        // a kitchen-sink level exercising every reverse-conversion branch
959        let src = r#"
960            [level.sink]
961            [[level.sink.allow]]
962            operation = ["observe", "create", "destroy"]
963            locus = { local = "<= machine", remote = "<= fixed", binding = ["pinned", "ambient"] }
964            scale = "<= bounded"
965            authority = "<= root"
966            isolation = "<= vm"
967            reversibility = "<= effortful"
968            persistence = { level = "<= installing", trigger = { escape = "<= boot", kind = ["clock", "event"] } }
969            disclosure = { audience = "<= public", channel = ["filesystem", "network"], principal = ["own"] }
970            secret = { level = ">= reads", channel = ["credential-store"], principal = ["cross"] }
971            network = { direction = "<= outbound", destination = "<= arbitrary", payload = "<= sends-host-data" }
972            execution = "<= network-sourced"
973            supply_chain = { source = ["public-registry", "signed-repo"], pinning = ">= version", exec_surface = ["build-script", "install-hook"] }
974            cost = "<= quota"
975            [[level.sink.deny]]
976            operation = ["destroy"]
977            reversibility = ">= irreversible"
978        "#;
979        let levels = build_level_set(src).expect("compiles");
980        assert_round_trips(&levels);
981    }
982}