safe_chains/engine/resolve.rs
1//! The profile resolver — turning a parsed command into its behavior profile
2//! (annex `behavioral-taxonomy-engine`). Runs via `engine::bridge`, which is
3//! AUTHORITATIVE for every command it can resolve (`engine_verdict(tokens).unwrap_or(legacy)`
4//! in `cst::check::leaf_verdict`) — there is no opt-out.
5//!
6//! This file holds the dispatch (`resolve`) and the per-command `resolve_*` functions;
7//! the shared toolkit they build on lives in submodules: [`flags`] (the getopt-style
8//! flag walker), [`locus`] (`classify_locus` — the [`LocalLocus`] ladder that refines the
9//! old `is_safe_write_target` boolean, v1.4 §2.2), and [`capability`] (the builders that
10//! stamp out each `Capability` with the facet pairing its operation warrants).
11
12use super::facet::*;
13use crate::parse::{Token, has_flag};
14
15mod capability;
16mod flags;
17pub(crate) mod locus;
18pub(crate) mod regions;
19#[cfg(test)]
20mod scenarios;
21
22use capability::{
23 breadth_scale, creates, destroys, executes, mutates, observes, observes_path, overwrites,
24 reads_content, reads_path, reads_to_model, relocates, transfer_profile, worst,
25 writes_export_file,
26};
27use flags::{walk_positionals, walk_value};
28use locus::{classify_locus, read_locus, write_locus};
29pub(crate) use locus::{FrozenWrite, anchoring_of, frozen_write_kind, names_credential_store};
30pub(crate) use locus::is_unpinnable;
31
32/// For `for VAR in ITEMS; do …$VAR…`, the representatives to bind `$VAR` to in the body: the
33/// worst-READ item and the worst-WRITE item of the list (they can differ, so a read and a
34/// write of `$VAR` each get their list's worst case). `$VAR` then inherits the list's locus
35/// per operation — the `find … {}`→path binding, one layer up. `None` for an empty list, which
36/// leaves `$VAR` fail-closed (machine). An item the classifier cannot bound — an UNDECLARED command
37/// substitution, a process substitution, arithmetic — worst-cases to machine via a `$`-carrying
38/// sentinel representative. An item from a substitution whose inner command DECLARED its output
39/// locus is bounded, so it is classified like any other path: `for f in $(fd a app/)` reads the
40/// worktree, and `for f in $(fd a /etc)` still lands at machine because that is what the tag says.
41/// (The test here used to be a `__SAFE_CHAINS_` PREFIX match, which caught the bounded sentinel too
42/// and made the loop form deny while the bare `cat $(fd a app/)` was allowed.)
43pub(crate) fn loop_reprs(items: &[String]) -> Option<(String, String)> {
44 if items.is_empty() {
45 return None;
46 }
47 let faced: Vec<(String, LocalLocus, LocalLocus)> = items
48 .iter()
49 .map(|s| {
50 if crate::cst::check::is_opaque_value(s) {
51 ("$loop_sub".to_string(), LocalLocus::Machine, LocalLocus::Machine)
52 } else {
53 (s.clone(), read_locus(s), write_locus(s))
54 }
55 })
56 .collect();
57 let read_item = faced.iter().max_by_key(|(_, r, _)| *r).map(|(s, _, _)| s.clone())?;
58 let write_item = faced.iter().max_by_key(|(_, _, w)| *w).map(|(s, _, _)| s.clone())?;
59 // Freeze against the CURRENT (outer) loop bindings, so an inner representative like `$d/x`
60 // doesn't carry a stale outer variable into the body — nested loops compose.
61 let read_repr = crate::pathctx::expand_vars(&read_item, false).into_owned();
62 let write_repr = crate::pathctx::expand_vars(&write_item, true).into_owned();
63 Some((read_repr, write_repr))
64}
65
66/// The verdict for READING the content of `path` — used to gate an input-redirect source
67/// (`cmd < path`) by its read locus, exactly as an operand read is gated, so `cat < /etc/shadow`
68/// denies like `cat /etc/shadow`. `-` / stdin never reaches here (redirects always name a file).
69pub(crate) fn read_content_verdict(path: &str) -> crate::verdict::Verdict {
70 let cap = reads_path(path, Scale::Single, "reads a redirect source");
71 crate::engine::bridge::project(&Profile::of(vec![cap]))
72}
73
74/// The verdict for WRITING/overwriting `path` — used to gate a legacy writer command's file
75/// operand (`tee`/`shred`/`bzip2`) by its write locus, so `shred /etc/hosts` denies.
76pub(crate) fn write_target_verdict(path: &str) -> crate::verdict::Verdict {
77 let cap = overwrites(write_locus(path), Scale::Single, false);
78 crate::engine::bridge::project(&Profile::of(vec![cap]))
79}
80
81/// Whether REBINDING `path` (removing it, or pointing the name elsewhere) is refused where an
82/// ordinary write is not. Only the trust-root directories answer true.
83///
84/// The nudge needs this, because its "does this reach outside" test reads the read and write faces
85/// only. A grant on `~/.config` opens both, so `rm -rf ~/.config` looked entirely unremarkable to
86/// the nudge while the engine refused it — a denial with no explanation at all, which is the worst
87/// of the outcomes available.
88pub(crate) fn rebind_is_stricter_than_write(path: &str) -> bool {
89 let rebind = overwrites(locus::rebind_locus(path), Scale::Single, false);
90 let refused = !crate::engine::bridge::project(&Profile::of(vec![rebind])).is_allowed();
91 refused && write_target_verdict(path).is_allowed()
92}
93
94/// Judge a path value, taking the WORST element when it is a colon-separated LIST.
95///
96/// The one place the list rule lives, so the environment gate and the flag gate cannot drift apart.
97/// They HAD drifted: the env gate always split on `:` while the flag gate never did, so
98/// `BORG_RSH=x:/tmp/evil` denied and `borg --rsh x:/tmp/evil` — the same operation — was approved.
99///
100/// Splitting is opt-OUT rather than opt-in, because the two mistakes are not symmetric. Treating a
101/// real list as one string is a FAIL-OPEN: `PYTHONPATH=/tmp/evil:/ok` read whole matches no locus
102/// rule and sails through. Treating a single value as a list is merely stricter. So a value splits
103/// unless its entry says it is a single value, and the entries that say so are commands
104/// (`BORG_RSH`, `RSYNC_RSH`) rather than search paths.
105///
106/// A URL is never split: `https://example.com` is not `https` plus `//example.com`, and splitting
107/// it denied every `curl` invocation in the suite.
108pub(crate) fn worst_path_element(
109 value: &str,
110 judge: fn(&str) -> crate::verdict::Verdict,
111 split_list: bool,
112) -> crate::verdict::Verdict {
113 let mut worst = judge(value);
114 if split_list && value.contains(':') && !value.contains("://") {
115 for element in value.split(':').filter(|s| !s.is_empty()) {
116 worst = worst.combine(judge(element));
117 }
118 }
119 worst
120}
121
122
123/// The verdict for EXECUTING the code in file `path` — used to gate an interpreter/runner's
124/// script operand (`bash x.sh`, `python x.py`, `node x.js`, `go run pkg/`) by its EXECUTOR
125/// locus. A worktree-local script is the dev loop → admitted at `developer`; a foreign one
126/// (`/tmp/x.sh`, `~/x.py`, `/usr/local/bin/x`) or an unpinnable path (`$VAR`, glob, `..`
127/// beyond cwd → `machine`) denies. `CallerFile` trust (code from a named file). See
128/// docs/design/behavioral-taxonomy-execution-origin.md.
129pub(crate) fn execute_file_verdict(path: &str) -> crate::verdict::Verdict {
130 // A GLOB executor (`bash *.sh`) names no specific file — the matched code is unknown, so
131 // it cannot be pinned to a worktree executor; deny (design §6). ($VAR/../cmdsub are already
132 // worst-cased by classify_locus.) A glob stays fine as a read/write OPERAND, where every
133 // match is locus-gated; only as an EXECUTOR is the code it would run unknowable.
134 if path.contains(['*', '?', '[']) {
135 return crate::engine::bridge::project(&worst("glob executor — the code that would run is unknown (§6)"));
136 }
137 // A PROCESS-SUBSTITUTION executor (`sh <(curl …)`) runs the OUTPUT of the inner command, not
138 // the inner command. The inner command is checked separately and is usually safe on its own —
139 // `curl` prints, `echo` prints — which is exactly how this hid: `sh <(curl …)` auto-approved
140 // while the identical `curl … | sh` denied. A command that is safe to RUN is not the same as a
141 // command whose output is safe to EXECUTE.
142 //
143 // Only in the executor slot. As a DATA operand the sentinel stays worktree-ordinary on purpose,
144 // because reading a `/dev/fd` pipe really is as safe as the inner command (`diff <(ls) <(ls)`).
145 if path.contains(crate::cst::eval::PROCSUB_SENTINEL) {
146 return crate::engine::bridge::project(&worst(
147 "process-substitution executor — the code that would run is a command's output (§6)",
148 ));
149 }
150 // A URL executor (`borg --rsh http://evil/x`, `rsync -e file:~`) is not a workspace file. The
151 // locus layer admits a network URL at `worktree` on purpose — for a network OPERAND the
152 // command's own handler gates the network, and a URL's `..` is a path segment rather than a
153 // filesystem escape. In an EXECUTOR slot that reasoning inverts: the thing has to be a local
154 // file the project owns, and `http://…` is not one however harmless its `..` are. Third member
155 // of the same family as the glob and process-substitution rules above.
156 if crate::engine::resolve::locus::is_url(path) {
157 return crate::engine::bridge::project(&worst(
158 "URL executor — the code that would run is not a workspace file (§6)",
159 ));
160 }
161 // An executor slot names a PATH. A value carrying whitespace is a command LINE, and judging it
162 // as one path is how `BORG_RSH='sh -c evil'` and `rsync -e 'sh -c evil'` were auto-approved:
163 // the whole string read as one oddly-named executable, which satisfied the bare-name rule.
164 //
165 // Every whitespace-separated token must therefore look like a path. That keeps the documented
166 // space-separated forms working (`LD_PRELOAD='/a.so /b.so'` judges both), while a token that is
167 // not a path — an interpreter's `-c`, the inline code after it — means the value was never a
168 // path and cannot be judged as one. Stated as a requirement ON the value, not as a list of
169 // forbidden programs: `sh -c evil` fails because `-c` is not a path, not because it is `sh`.
170 //
171 // Fail-CLOSED and known to over-deny: `rsync -e 'ssh -p 2222'` is a legitimate idiom that now
172 // refuses, because vetting a transport's own flags is a question this layer cannot answer.
173 if path.split_whitespace().count() > 1 {
174 let mut worst_seen = None;
175 for token in path.split_whitespace() {
176 if token.starts_with('-') {
177 return crate::engine::bridge::project(&worst(
178 "executor value is a command line, not a path — a non-path token means the \
179 code that would run is unknown",
180 ));
181 }
182 let v = execute_file_verdict(token);
183 worst_seen = Some(match worst_seen {
184 None => v,
185 Some(prev) => crate::verdict::Verdict::combine(prev, v),
186 });
187 }
188 return worst_seen.unwrap_or_else(|| {
189 crate::engine::bridge::project(&worst("empty executor value"))
190 });
191 }
192 let cap = executes(classify_locus(path), ExecutionTrust::CallerFile, "runs code from a named file");
193 crate::engine::bridge::project(&Profile::of(vec![cap]))
194}
195
196/// The verdict for running the CURRENT PROJECT's own code — an implicit-project runner
197/// (`cargo run`, `dotnet run`, `swift run`) with no path operand and no redirect out of the
198/// worktree. `SelfCode` @ `Worktree` → admitted at `developer`. A runner redirected out of the
199/// project (`cargo run --manifest-path ~/o/Cargo.toml`) resolves that path through
200/// [`execute_file_verdict`] instead. See docs/design/behavioral-taxonomy-execution-origin.md.
201pub(crate) fn execute_project_verdict() -> crate::verdict::Verdict {
202 let cap = executes(LocalLocus::Worktree, ExecutionTrust::SelfCode, "runs the current project's own code");
203 crate::engine::bridge::project(&Profile::of(vec![cap]))
204}
205
206/// Resolve a command's leaf tokens to its behavior profile, or `None` if the command
207/// has no resolver yet (the caller then worst-cases / falls back to the legacy
208/// classifier — §0 fail-closed). Redirects, substitutions, and chain semantics are the
209/// surrounding CST's job, not this leaf's (annex `…-engine` §1).
210pub fn resolve(tokens: &[Token]) -> Option<Profile> {
211 let arg0 = tokens.first()?;
212 // Canonicalize the invoked token through the registry's alias map (`gcat` → `cat`) BEFORE the
213 // resolver lookup: Homebrew installs GNU coreutils as g-prefixed aliases, and without this
214 // they'd miss every resolver and fall through to the ungated legacy classifier (a fail-open —
215 // `gtee /etc/cron.d/job`, `gcat /etc/shadow`). The `tokens` are passed through unchanged; the
216 // resolver gates operands by position, not by re-reading the command name.
217 let canonical = crate::registry::canonical_name(arg0.command_name());
218 // `sudo`/`doas` ELEVATE the wrapped command's authority — they are a delegating wrapper, not a
219 // command of their own. Resolve the inner command and lift its authority to root (or `other-user`
220 // for `-u`), so the safety of `sudo X` is the safety of `X` run privileged: `sudo cat ./notes`
221 // → a root READ (local-admin), `sudo rm -rf /` → the catastrophe corner (denied everywhere).
222 if canonical == "openssl" {
223 return resolve_openssl(arg0, tokens);
224 }
225 if matches!(canonical, "sudo" | "doas") {
226 return resolve_privilege_wrapper(arg0, tokens);
227 }
228 // Phase 1: a subcommand tagged with a facet archetype (`profile = …`) classifies as that
229 // archetype's static capability — the derived, self-documenting successor to `candidate = true`.
230 // Checked BEFORE command-level behavior, since a subcommand tool carries no `[command.behavior]`.
231 if let Some(names) = crate::registry::sub_archetypes(tokens) {
232 if !trusted_command_path(arg0.as_str()) {
233 return Some(worst("resolvable name invoked from a non-standard path — possible spoof (§0)"));
234 }
235 // An endpoint flag pointed at THIS machine makes the sub a DIFFERENT operation, not the same
236 // one with softened edges: `put-item --endpoint-url http://localhost:8000` writes to a
237 // process here, so `remote-mutate`'s `sends-host-data`, `effortful` reversibility and (for
238 // create) `metered` cost are all describing a cloud service that isn't in the picture. The
239 // sub names the archetype it becomes, so the substitution stays reviewable data rather than
240 // ad-hoc facet arithmetic at resolve time.
241 //
242 // Destroy archetypes may not declare a substitute at all — `assert_no_loopback_profile_on_
243 // destroy` refuses it at build time. We cannot verify the emulator claim (`ssh -L
244 // 8000:dynamodb.us-east-1.amazonaws.com:443` makes `localhost:8000` production, and no
245 // static classifier sees the tunnel), and that lie is only unrecoverable in the destroy
246 // direction.
247 // One capability per archetype (the sub's profile + each present escalating flag); the level
248 // algebra takes the max. Fail-closed: an unknown archetype name → a worst capability, so a
249 // typo or `unclassified` can never silently pass (a proptest catches typos at test time).
250 let mut caps: Vec<Capability> = names
251 .iter()
252 .map(|n| {
253 crate::engine::archetype::archetype(n).cloned().unwrap_or_else(|| {
254 Capability::worst("subcommand/flag declares an unknown archetype (§0)")
255 })
256 })
257 .collect();
258 // Destination-trust (exposure §4): a sub tagged `network_destination` gets its send TARGET
259 // classified onto the base archetype's `locus.provenance` — established remote / literal URL
260 // / opaque `$VAR` — or, for a command-transport form (`ext::…`), worst-cased as RCE.
261 if let Some(dest) = crate::registry::sub_destination_token(tokens) {
262 match destination_provenance(dest) {
263 Some(prov) => {
264 if let Some(base) = caps.first_mut() {
265 base.locus.provenance = prov;
266 }
267 }
268 None => {
269 return Some(worst(
270 "send target is a command transport (ext::…) — runs a local command, RCE (§4)",
271 ));
272 }
273 }
274 }
275 // A `data-export` sub with an OUTPUT-FILE flag (`db dump -f out.sql`) writes its bulk result
276 // to a local file — a SECOND capability beyond the remote read, gated at the file's locus
277 // (worktree write vs a system-path clobber). Absent → the export streams to stdout, so the
278 // profile is the remote read alone.
279 if let Some(path) = crate::registry::sub_output_path_token(tokens) {
280 caps.push(writes_export_file(classify_locus(path)));
281 }
282 // A declared endpoint flag naming THIS machine changes WHERE the call goes, so it changes
283 // exactly the facets the destination determines and nothing else. That boundary is the whole
284 // design: `remote-mutate` describes a cloud service in four places — it reaches a fixed
285 // remote, talks outbound, sends host data off the machine, and bills — and all four are
286 // false for `http://localhost:8000`. Its other facets (what the operation DOES: the
287 // operation itself, scale, retrieval, reversibility, persistence, disclosure) are properties
288 // of the call, not of its destination, and stay untouched.
289 //
290 // Composing rather than substituting a whole "local" archetype matters twice over: the
291 // remote archetypes do not each need a local twin, and nothing here asserts a fact the
292 // destination cannot establish. (An earlier cut swapped in `local-mutate-recoverable`, which
293 // claims `locus.local = worktree` and `persistence = data` — both untrue of a container.)
294 //
295 // DESTROY is skipped here and refused outright at build time by
296 // `assert_loopback_localizes_is_coherent`. The emulator claim is unverifiable: `ssh -L
297 // 8000:dynamodb.<region>.amazonaws.com:443` makes `localhost:8000` production and no static
298 // classifier sees the tunnel. Being wrong costs a stray write; being wrong about a delete
299 // costs the data.
300 if crate::registry::sub_loopback_localizes(tokens) {
301 for c in &mut caps {
302 if c.operation == Operation::Destroy {
303 continue;
304 }
305 c.locus.remote = RemoteReach::None;
306 c.network.direction = NetDirection::Loopback;
307 c.network.payload = NetPayload::None;
308 c.cost = Cost::None;
309 // The archetype's prose describes the cloud call and is now half wrong; say so,
310 // or `--explain` prints "changes remote state" over a profile that reaches no
311 // remote. The facets carry the classification, but the prose is what a human reads.
312 c.because = format!("{} — but the endpoint names this machine, so no remote is reached", c.because);
313 }
314 }
315 return Some(Profile::of(caps));
316 }
317 // A flat command whose top-level classifying flag (`[[command.flag]]`) is present resolves to
318 // that flag's archetype — the flag-triggered mode of a bimodal tool: `age -d` / `sops --decrypt`
319 // reveal plaintext to the model (`decrypt-read`), while the bare/encrypt form falls through to
320 // ordinary resolution below. Checked after the profiled-sub walk (a sub match wins) so a
321 // subcommand form (`sops decrypt`) and the flag form (`sops -d`) both classify.
322 if let Some(names) = crate::registry::command_flag_archetypes(tokens) {
323 if !trusted_command_path(arg0.as_str()) {
324 return Some(worst("resolvable name invoked from a non-standard path — possible spoof (§0)"));
325 }
326 let caps: Vec<Capability> = names
327 .iter()
328 .map(|n| {
329 crate::engine::archetype::archetype(n).cloned().unwrap_or_else(|| {
330 Capability::worst("command flag declares an unknown archetype (§0)")
331 })
332 })
333 .collect();
334 return Some(Profile::of(caps));
335 }
336 // Every facet-classified command declares `[command.behavior]` (the coreutils are all ported;
337 // dd/tar/sed/grep declare a `hook`). No declaration → the command is unresearched for the
338 // engine, so return `None` (the caller falls back to the legacy classifier).
339 let spec = crate::registry::command_behavior(canonical)?;
340 // A resolvable basename reached via a NON-STANDARD path (`./cat`, `/tmp/cat`, `~/bin/grep`)
341 // is not necessarily the real tool — a planted binary named `cat` would be certified as safe
342 // coreutils. Don't certify it; worst-case (§0). Bare names and standard bin paths are
343 // trusted. (Legacy classifies purely by basename and inherits the spoof; the engine is
344 // stricter here, which keeps it never-looser.)
345 if !trusted_command_path(arg0.as_str()) {
346 return Some(worst("resolvable name invoked from a non-standard path — possible spoof (§0)"));
347 }
348 Some(resolve_behavior(spec, tokens))
349}
350
351/// `sudo`/`doas`: resolve the wrapped command and ELEVATE its authority. Authority is the axis every
352/// level below `local-admin` pins to `user`, so a root capability lands at `local-admin` (or `yolo`)
353/// — the projection does the rest. Fail-closed: an unknown sudo option, a root shell/editor
354/// (`-i`/`-s`/`-e`), or an inner command from a non-standard path worst-cases; an unresolved inner
355/// returns `None` so the caller's legacy fallback denies it (never *looser* than the bare command).
356fn resolve_privilege_wrapper(arg0: &Token, tokens: &[Token]) -> Option<Profile> {
357 if !trusted_command_path(arg0.as_str()) {
358 return Some(worst("sudo/doas invoked from a non-standard path — possible spoof (§0)"));
359 }
360 let mut i = 1;
361 let mut run_as_other = false;
362 'scan: while let Some(tok) = tokens.get(i) {
363 let t = tok.as_str();
364 if t == "--" {
365 i += 1;
366 break;
367 }
368 if !t.starts_with('-') || t == "-" {
369 break; // the inner command starts here
370 }
371 if let Some(long) = t.strip_prefix("--") {
372 let (name, glued_val) = match long.split_once('=') {
373 Some((n, _)) => (n, true),
374 None => (long, false),
375 };
376 match name {
377 "login" | "shell" | "edit" => {
378 return Some(worst("sudo -i/-s/-e runs a root shell or editor — arbitrary code as root (§0)"));
379 }
380 "user" | "other-user" => {
381 run_as_other = true;
382 if !glued_val { i += 1; }
383 }
384 "group" | "prompt" | "close-from" | "host" | "role" | "type"
385 | "command-timeout" | "chroot" | "chdir" | "preserve-env" => {
386 // `--preserve-env` is boolean OR `--preserve-env=list`; only the space form of the
387 // others consumes a value. A bare `--preserve-env` just falls through (no skip).
388 if !glued_val && name != "preserve-env" { i += 1; }
389 }
390 "background" | "stdin" | "non-interactive" | "reset-timestamp"
391 | "remove-timestamp" | "set-home" | "askpass" | "help" | "version"
392 | "validate" | "list" | "bell" => {}
393 _ => return Some(worst("sudo: unrecognized option — fail-closed (§0)")),
394 }
395 } else {
396 // A short cluster (`-EH`, `-u root`, `-uroot`). Consume char by char; a valued flag eats
397 // the rest of the token as its value, or the next token if the rest is empty.
398 let rest = &t[1..];
399 for (idx, c) in rest.char_indices() {
400 match c {
401 'i' | 's' | 'e' => {
402 return Some(worst("sudo -i/-s/-e runs a root shell or editor — arbitrary code as root (§0)"));
403 }
404 'u' | 'U' | 'g' | 'p' | 'C' | 'h' | 'r' | 't' | 'T' | 'R' | 'D' => {
405 if c == 'u' || c == 'U' { run_as_other = true; }
406 if idx + c.len_utf8() == rest.len() { i += 1; } // value is the next token
407 i += 1;
408 continue 'scan; // rest of the token was this flag's value
409 }
410 'E' | 'H' | 'k' | 'K' | 'n' | 'b' | 'A' | 'S' | 'P' | 'B' | 'v' | 'l' => {}
411 _ => return Some(worst("sudo: unrecognized option — fail-closed (§0)")),
412 }
413 }
414 }
415 i += 1;
416 }
417 // A valued short flag at end-of-input (`sudo -u`, `doas -r`) consumes a "next token" that isn't
418 // there, pushing `i` one past the end — clamp so the slice can't panic (fail-OPEN crash of the
419 // hook). An overshoot means no command was left to elevate, same as the empty case below.
420 let inner = &tokens[i.min(tokens.len())..];
421 if inner.is_empty() {
422 return None; // `sudo` / `sudo -v` / `sudo -l` — no command to elevate; legacy decides
423 }
424 let elevated = if run_as_other { Authority::OtherUser } else { Authority::Root };
425 let caps = resolve(inner)?
426 .capabilities
427 .into_iter()
428 .map(|mut c| {
429 c.authority = c.authority.max(elevated);
430 c
431 })
432 .collect();
433 Some(Profile::of(caps))
434}
435
436/// openssl decrypt / private-key disclosure resolver. openssl's flag grammar defeats declarative
437/// flag-gating — it accepts `--opt` as an alias for `-opt` on every subcommand, `-text` dumps the
438/// PRIVATE key components to stdout past `-pubout`/`-noout`, and `-out`'s VALUE can itself be stdout
439/// (`-out -`, `-out /dev/stdout`) — so the disclosure-prone subs are classified here in Rust. Returns
440/// `decrypt-read` (→ yolo, denied below) only when private/decrypted material reaches the MODEL
441/// (stdout); returns `None` for public-key ops, to-FILE extraction, encrypt/sign, and the ~30 benign
442/// subs, which fall through to openssl's declarative (allow_all) classification. Fail-closed: a spoofed
443/// path worst-cases; a disclosure sub always yields a verdict rather than abstaining to the permissive
444/// legacy default.
445fn resolve_openssl(arg0: &Token, tokens: &[Token]) -> Option<Profile> {
446 if !trusted_command_path(arg0.as_str()) {
447 return Some(worst("openssl invoked from a non-standard path — possible spoof (§0)"));
448 }
449 let sub = tokens.get(1)?.as_str();
450 let args = &tokens[2..];
451 let discloses = match sub {
452 // Private-key subs: private material reaches the model UNLESS the input is public (`-pubin`),
453 // or it's public-key output (`-pubout`) with no `-text` side channel — and then only if the
454 // (private-key) output actually goes to stdout, not a file.
455 "rsa" | "pkey" | "ec" | "dsa" => {
456 if openssl_flag(args, "-pubin") {
457 false
458 } else if openssl_flag(args, "-text") {
459 true // dumps the private exponent/primes to stdout regardless of -out/-noout/-pubout
460 } else if openssl_flag(args, "-pubout") {
461 false // public-key PEM out, no -text
462 } else {
463 openssl_output_reaches_model(args)
464 }
465 }
466 // PKCS#8 is a private-key format with no public mode; disclosed if it reaches stdout.
467 "pkcs8" => openssl_flag(args, "-text") || openssl_output_reaches_model(args),
468 // Unencrypted key export (`-nodes`/`-noenc`, OpenSSL 3.0 spelling); disclosed if it hits stdout.
469 "pkcs12" => {
470 (openssl_flag(args, "-nodes") || openssl_flag(args, "-noenc"))
471 && openssl_output_reaches_model(args)
472 }
473 // Symmetric decrypt: plaintext to the model only when it goes to stdout.
474 "enc" => openssl_flag(args, "-d") && openssl_output_reaches_model(args),
475 "smime" => openssl_flag(args, "-decrypt") && openssl_output_reaches_model(args),
476 "cms" => {
477 (openssl_flag(args, "-decrypt") || openssl_flag(args, "-EncryptedData_decrypt"))
478 && openssl_output_reaches_model(args)
479 }
480 _ => return None, // benign subs — openssl's declarative (allow_all) classification
481 };
482 if discloses {
483 let cap = crate::engine::archetype::archetype("decrypt-read")
484 .cloned()
485 .unwrap_or_else(|| Capability::worst("decrypt-read archetype missing (§0)"));
486 Some(Profile::of(vec![cap]))
487 } else {
488 None // public / to-file / encrypt / benign → legacy allow_all classification
489 }
490}
491
492/// Whether an openssl BOOLEAN flag (`-d`, `-text`, `-pubout`) is present, accepting the `--` twin
493/// openssl honors on every subcommand (`--d`, `--text`). Value flags use [`openssl_flag_value`].
494fn openssl_flag(args: &[Token], flag: &str) -> bool {
495 args.iter().any(|t| {
496 let s = t.as_str();
497 s == flag || (s.starts_with("--") && s.len() > 2 && &s[1..] == flag)
498 })
499}
500
501/// Whether the sub's OUTPUT reaches the model. FAIL-CLOSED (a path string cannot be soundly matched
502/// against a denylist of device spellings — the OS collapses `//dev/stdout`, `/dev/./stdout`,
503/// `/dev/fd//1` to the same device, and openssl honors the LAST of duplicate `-out`s): the output
504/// reaches the model UNLESS it is provably diverted to a single plain FILE. So it's model-reaching
505/// when `-noout` is absent AND NOT (exactly one `-out` whose value is a plain file). `-noout`
506/// suppresses the PEM output (a validate); `-text` is checked by the caller BEFORE this, since it
507/// dumps to stdout past both `-noout` and `-out`.
508fn openssl_output_reaches_model(args: &[Token]) -> bool {
509 if openssl_flag(args, "-noout") {
510 return false;
511 }
512 let outs = openssl_flag_values(args, "-out");
513 // Diverted to disk ONLY when there is exactly one `-out` naming a plain file. No `-out` (default
514 // stdout), a duplicate `-out` (last-wins — the first is untrustworthy), or a device/`-` value all
515 // reach the model.
516 !matches!(outs.as_slice(), [only] if out_value_is_plain_file(only))
517}
518
519/// Whether an `-out` value names a plain FILE (a safe diversion), as opposed to stdout/`-`, or a
520/// device / fd / console path (`/dev/stdout`, `/dev/stderr`, `/dev/fd/1`, `/proc/self/fd/1`). Collapses
521/// redundant `/`, `.`, and `..` segments first so alternate spellings can't evade. Fail-closed: `-`,
522/// empty, or any `/dev/…` or `/proc/…/fd/…` path is NOT a plain file. (Symlinks are classified by their
523/// literal spelling — out of scope for a static classifier, per AGENTS.md.)
524///
525/// A value that is itself a FLAG token (starts with `-`) is NOT proof of diversion: openssl's own
526/// parser lets a preceding valued flag SWALLOW the `-out` token as its value (`-provider-path -out
527/// -provider-path f.pem` leaves openssl with no `-out` → stdout), and our scan then misreads the next
528/// flag as the filename. The tell in every such bypass is a dash-leading `-out` value — reject it.
529fn out_value_is_plain_file(value: &str) -> bool {
530 if value.is_empty() || value.starts_with('-') {
531 return false;
532 }
533 let norm = collapse_path(value).to_ascii_lowercase();
534 let device_or_fd =
535 norm == "/dev" || norm.starts_with("/dev/") || (norm.starts_with("/proc/") && norm.contains("/fd/"));
536 !device_or_fd
537}
538
539/// Collapse a path's redundant `/` / `.` / `..` segments (what the kernel does before opening it), so
540/// `//dev/stdout`, `/dev/./stdout`, `/dev/fd//1`, `/foo/../dev/stdout` all normalize to the device
541/// path. A leading `..` on a relative path is kept (can't resolve above an unknown cwd).
542fn collapse_path(p: &str) -> String {
543 let absolute = p.starts_with('/');
544 let mut stack: Vec<&str> = Vec::new();
545 for seg in p.split('/') {
546 match seg {
547 "" | "." => {}
548 ".." => {
549 if matches!(stack.last(), Some(&s) if s != "..") {
550 stack.pop();
551 } else if !absolute {
552 stack.push("..");
553 }
554 }
555 s => stack.push(s),
556 }
557 }
558 let joined = stack.join("/");
559 if absolute { format!("/{joined}") } else { joined }
560}
561
562/// Every value of a valued openssl flag (`-out file` / `--out file` / `-out=file` / `--out=file`),
563/// accepting the `--` twin — ALL occurrences, in order (openssl honors the last; the caller fails
564/// closed on duplicates).
565fn openssl_flag_values<'a>(args: &'a [Token], flag: &str) -> Vec<&'a str> {
566 let twin = format!("-{flag}"); // `-out` → `--out`
567 let mut out = Vec::new();
568 let mut i = 0;
569 while i < args.len() {
570 let s = args[i].as_str();
571 if let Some(v) = s
572 .strip_prefix(flag)
573 .or_else(|| s.strip_prefix(twin.as_str()))
574 .and_then(|r| r.strip_prefix('='))
575 {
576 out.push(v);
577 } else if (s == flag || s == twin)
578 && let Some(next) = args.get(i + 1)
579 {
580 out.push(next.as_str());
581 i += 1;
582 }
583 i += 1;
584 }
585 out
586}
587
588/// Classify a network-destination token's PROVENANCE (exposure §4). `None` (a bare invocation) is
589/// the configured default → `Established`. A command-transport form (`ext::<cmd>`) is not a
590/// destination but LOCAL CODE, signalled by a `None` return so the caller worst-cases it as RCE.
591fn destination_provenance(dest: Option<&str>) -> Option<Provenance> {
592 let Some(tok) = dest else {
593 return Some(Provenance::Established);
594 };
595 if tok.starts_with("ext::") {
596 return None; // `git push ext::sh -c …` runs a local command — RCE, not egress
597 }
598 // A variable / substitution: the actual target is not in the command string, so it cannot be
599 // reviewed — the fail-closed case.
600 if tok.contains('$') || tok.contains('`') {
601 return Some(Provenance::Opaque);
602 }
603 // Spelled inline: a URL scheme, an scp-style `user@host:path`, or a filesystem path. Otherwise a
604 // bare word is a reference to a configured remote (established by a prior `clone`/`remote add`).
605 let literal = tok.contains("://")
606 || (tok.contains('@') && tok.contains(':'))
607 || tok.starts_with('/')
608 || tok.starts_with("./")
609 || tok.starts_with("../");
610 Some(if literal { Provenance::Literal } else { Provenance::Established })
611}
612
613/// The generic, declaration-driven resolver: build a `Profile` from a command's
614/// `[command.behavior]` (`BehaviorSpec`) and its tokens. This is the non-legacy classification
615/// path expressed in TOML — the operation + operand-role + flag grammar are data, and this one
616/// function replaces a hardcoded `resolve_*`. Irreducible token logic a declaration can't
617/// express is delegated to a named `hook`.
618fn resolve_behavior(spec: &crate::registry::types::BehaviorSpec, tokens: &[Token]) -> Profile {
619 use crate::registry::types::{BehaviorHook, PositionalRole};
620 if let Some(hook) = spec.hook {
621 return match hook {
622 // grep's hook supplies the operand set (the irreducible token logic); the declared
623 // operation + the builders supply the facets — the composition seam (§8). grep is
624 // observe-only, so its operands become content reads.
625 BehaviorHook::Grep => {
626 let Some(g) = grep_operands(tokens) else {
627 return worst("grep: unrecognized flag or missing pattern — worst-cased (§0)");
628 };
629 let mut caps: Vec<Capability> = g
630 .pattern_files
631 .iter()
632 .map(|f| reads_path(f, Scale::Single, "reads a grep -f pattern file"))
633 .collect();
634 caps.extend(reads_to_model(&g.files, g.scale));
635 Profile::of(caps)
636 }
637 // dd/tar/sed parse their own irregular operand syntax (`key=value`, dashless mode
638 // bundles, a mini-language script) AND build their own multi-role profiles, so their
639 // hook returns the full `Profile` — the parser and the facets are entangled with the
640 // parse and stay in Rust (their DATA — flag/param sets — is small and audited).
641 BehaviorHook::Dd => resolve_dd(tokens),
642 BehaviorHook::Tar => resolve_tar(tokens),
643 BehaviorHook::Sed => resolve_sed(tokens),
644 BehaviorHook::Perl => resolve_perl(tokens),
645 };
646 }
647 // No path operands (echo): a pure stdout emitter, handled BEFORE the flag walk — echo has no
648 // flag grammar (it prints any `-x` verbatim), so walking would wrongly reject it. `observe`
649 // with model disclosure and no fs/net/exec; its args touch nothing.
650 if matches!(spec.positionals, PositionalRole::None) {
651 return match spec.operation {
652 Operation::Observe => {
653 let mut c = Capability::new(Operation::Observe);
654 c.disclosure.audience = DisclosureAudience::LocalProcess;
655 c.because = "behavior: prints its arguments to stdout; no fs/net/exec/secret".to_string();
656 Profile::of(vec![c])
657 }
658 _ => worst("behavior: none-operand role supports only observe (§0)"),
659 };
660 }
661 let long: Vec<&str> = spec.long.iter().map(String::as_str).collect();
662 let valued_long: Vec<&str> = spec.valued_long.iter().map(String::as_str).collect();
663 let Some(operands) = walk_positionals(&spec.short, &spec.valued_short, &long, &valued_long, spec.numeric_shorthand, tokens) else {
664 return worst("behavior: unrecognized flag — worst-cased (§0)");
665 };
666 let scale = behavior_scale(spec, &operands, tokens);
667 // Path-flag values (e.g. `touch -r REF`) are gated alongside the positional operands.
668 let flag_caps = path_flag_caps(spec, tokens);
669 match spec.positionals {
670 PositionalRole::Read => {
671 let mut caps = reads_to_model(&operands, scale);
672 caps.extend(flag_caps);
673 Profile::of(caps)
674 }
675 PositionalRole::Write => {
676 if operands.is_empty() {
677 // `rm --help` prints usage and exits. It is not a write whose target is hidden, so
678 // worst-casing it denied every informational invocation of every write command:
679 // `rm --help`, `mkdir --help`, `rmdir --version`. The flag already passed the
680 // command's own grammar to get here, and no operand survived the walk.
681 //
682 // LONG forms only, the same rule and the same reasoning the output-claim voider
683 // uses below: `-h`/`-V` are not reliably help/version (`sort -h` is human-numeric
684 // sort), so honoring the short spellings here would be guessing.
685 if tokens.iter().skip(1).any(|t| matches!(t.as_str(), "--help" | "--version")) {
686 let mut c = Capability::new(Operation::Observe);
687 c.disclosure.audience = DisclosureAudience::LocalProcess;
688 c.because = "behavior: prints usage and exits; nothing is written".to_string();
689 return Profile::of(vec![c]);
690 }
691 return worst("behavior: write operation with no operand — worst-cased (§0)");
692 }
693 let mut caps: Vec<Capability> = operands
694 .iter()
695 .map(|p| match spec.operation {
696 // A destroy UNBINDS the name, so it reads the rebind face: `rm -rf ~/.config`
697 // removes what the trust root points at, while `touch ~/.config/x` does not.
698 Operation::Destroy => destroys(locus::rebind_locus(p), scale),
699 Operation::Create => creates(classify_locus(p), scale),
700 Operation::Mutate => mutates(classify_locus(p), scale, "behavior: in-place mutate"),
701 _ => Capability::worst("behavior: unsupported write operation — worst-cased (§0)"),
702 })
703 .collect();
704 caps.extend(flag_caps);
705 Profile::of(caps)
706 }
707 PositionalRole::Transfer => resolve_transfer(spec, operands, flag_caps, tokens),
708 // None is handled above (before the flag walk); pattern-then-read routes through a hook
709 // (grep). Neither reaches here, so both fail closed.
710 PositionalRole::None | PositionalRole::PatternThenRead => {
711 worst("behavior: operand role not resolvable without a hook (§0)")
712 }
713 }
714}
715
716/// The transfer arm of `resolve_behavior` (cp/mv/ln): split the operands into sources and a
717/// destination (`-t`/`--target-directory` value, else the last operand), gate each at its locus
718/// — a relocate source at its WRITE face — and fold in any path-flag capabilities. Fails closed
719/// on a missing spec, a missing dest, or a `-t` dest with no sources.
720fn resolve_transfer(
721 spec: &crate::registry::types::BehaviorSpec,
722 operands: Vec<&str>,
723 flag_caps: Vec<Capability>,
724 tokens: &[Token],
725) -> Profile {
726 use crate::registry::types::TransferSource;
727 let Some(t) = &spec.transfer else {
728 return worst("behavior: transfer role without transfer spec — worst-cased (§0)");
729 };
730 // Whether the destination is DEFINITIVELY a container rather than the entry being created.
731 // `-t DIR` says so outright, and with two or more sources the last operand must be a directory
732 // for the command to make sense at all. Only the two-operand form is ambiguous, and there the
733 // conservative reading (the destination is the entry) is the safe one.
734 let (sources, dest, dest_is_container) = if let Some(d) = walk_value(&spec.valued_short, tokens, b't', "--target-directory") {
735 if operands.is_empty() {
736 return worst("behavior: transfer -t with no source operand — worst-cased (§0)");
737 }
738 (operands, d, true)
739 } else {
740 match operands.split_last() {
741 Some((last, rest)) if !rest.is_empty() => (rest.to_vec(), *last, rest.len() >= 2),
742 _ => return worst("behavior: transfer needs a source and a destination — worst-cased (§0)"),
743 }
744 };
745 let no_clobber = if t.clobber_flags.is_empty() {
746 t.no_clobber_flags.iter().any(|f| behavior_flag_present(tokens, f))
747 } else {
748 // A clobber flag PRESENT means overwrite; its absence is the no-clobber default.
749 !t.clobber_flags.iter().any(|f| behavior_flag_present(tokens, f))
750 };
751 let recursive = t.recursive_flags.iter().any(|f| behavior_flag_present(tokens, f));
752 let transfer_scale = breadth_scale(&sources, recursive);
753 // A relocate REMOVES its source, so the source name stops referring to anything: that is a
754 // REBIND, not merely a write, and it is what makes `mv ~/.config elsewhere` a relocation of the
755 // trust root rather than an edit of it.
756 let source_face = match t.source {
757 TransferSource::Relocate => locus::Face::Rebind,
758 TransferSource::Observe => locus::Face::Read,
759 };
760 // `ln` points the destination NAME at something else; `cp`/`mv` write bytes at or under it.
761 // Both are `create`/`transfer`, so only the command's own declaration separates them.
762 //
763 // But the declaration is about the ENTRY the command creates, and `ln -t DIR a` or
764 // `ln a b DIR` puts that entry INSIDE the directory instead of replacing it. Treating those as
765 // rebinds denied `ln -t ~/.config a`, which is an ordinary link into a directory you granted —
766 // the same container-versus-object mistake the write face made before this face existed.
767 let dest_face = if t.rebinds_destination && !dest_is_container {
768 locus::Face::Rebind
769 } else {
770 locus::Face::Write
771 };
772 let mut prof = transfer_profile(
773 &sources,
774 dest,
775 transfer_scale,
776 source_face,
777 dest_face,
778 |loc, sc| match t.source {
779 TransferSource::Observe => observes(loc, sc, "transfer reads the source at its locus"),
780 TransferSource::Relocate => relocates(loc, sc),
781 },
782 |loc, sc| overwrites(loc, sc, no_clobber),
783 );
784 prof.capabilities.extend(flag_caps);
785 prof
786}
787
788/// Capabilities for a command's declared PATH-FLAGS: a valued flag whose value is a path
789/// (`touch -r REF` reads REF's timestamp) is gated by its role's locus, exactly like an operand
790/// — so an out-of-workspace value denies. Folds the `[command.path_gate]` idea into behavior.
791fn path_flag_caps(spec: &crate::registry::types::BehaviorSpec, tokens: &[Token]) -> Vec<Capability> {
792 use crate::registry::types::PathRole;
793 let mut caps = Vec::new();
794 for pf in &spec.path_flags {
795 let short = pf.short.unwrap_or(0);
796 let long = pf.long.as_deref().unwrap_or("");
797 if let Some(v) = walk_value(&spec.valued_short, tokens, short, long) {
798 caps.push(match pf.role {
799 PathRole::Read => observes_path(v, Scale::Single, "behavior: a flag value is a read path"),
800 PathRole::Write => mutates(write_locus(v), Scale::Single, "behavior: a flag value is a write path"),
801 });
802 }
803 }
804 caps
805}
806
807/// The `Scale` for a behavior resolution: `single` always yields one item; `breadth` widens on
808/// operand count, a glob, or a declared unbounded flag (`rm -r`) via `breadth_scale`.
809fn behavior_scale(
810 spec: &crate::registry::types::BehaviorSpec,
811 operands: &[&str],
812 tokens: &[Token],
813) -> Scale {
814 use crate::registry::types::ScaleModel;
815 match spec.scale {
816 ScaleModel::Single => Scale::Single,
817 ScaleModel::Breadth => {
818 let recursive = spec.unbounded_flags.iter().any(|f| behavior_flag_present(tokens, f));
819 breadth_scale(operands, recursive)
820 }
821 }
822}
823
824/// Whether a declared behavior flag (a bare token like `-r` or `--recursive`) is present,
825/// via the shared `has_flag` (which handles short clustering and `--flag=value`).
826fn behavior_flag_present(tokens: &[Token], flag: &str) -> bool {
827 if flag.starts_with("--") {
828 has_flag(tokens, None, Some(flag))
829 } else {
830 has_flag(tokens, Some(flag), None)
831 }
832}
833
834/// A command name with no resolver and no plausible future one — the stable stand-in for
835/// "unresearched" across engine tests. Using a real tool here is a trap: when `rm` gained
836/// a resolver, three tests that used `rm` as their unresearched example silently broke.
837/// A name that will never be a real tool can never be silently repurposed.
838#[cfg(test)]
839pub(crate) const UNRESOLVED_CMD: &[&str] = &["safe-chains-unresolved-sentinel"];
840
841/// Whether `arg0` is a trusted way to invoke a standard tool: a bare name (found via
842/// `$PATH`) or an absolute path under a standard system bin directory. A path elsewhere
843/// (`./x`, `/tmp/x`, `~/bin/x`) may be an impostor.
844fn trusted_command_path(arg0: &str) -> bool {
845 const STD_BINS: &[&str] =
846 &["/usr/bin/", "/bin/", "/usr/local/bin/", "/opt/homebrew/bin/", "/sbin/", "/usr/sbin/"];
847 !arg0.contains('/') || STD_BINS.iter().any(|p| arg0.starts_with(p))
848}
849
850/// The classified operand set of a `grep` invocation: the positional file operands (read at
851/// `scale`, empty = stdin) and the `-f`/`--file` pattern files (each read once). This is the
852/// irreducible token logic a `[command.behavior]` declaration can't express — grep's
853/// pattern-vs-file disambiguation, `-e`/`-f` pattern flags, and the unknown-`--token`-is-a-
854/// pattern heuristic. The declared `operation` (observe) and the builders turn these operands
855/// into capabilities in `resolve_behavior`'s hook arm; this function assigns no facets.
856struct GrepOperands<'a> {
857 files: Vec<&'a str>,
858 pattern_files: Vec<&'a str>,
859 scale: Scale,
860}
861
862/// Walk a `grep` command into its `GrepOperands`, or `None` to fail closed (unrecognized flag,
863/// or no pattern operand). The behavior hook (`BehaviorHook::Grep`) for `commands/text/grep.toml`.
864fn grep_operands(tokens: &[Token]) -> Option<GrepOperands<'_>> {
865 // `-r` (or --recursive); `-R`/--dereference-recursive is not benign and worst-cases
866 // in the walk below, so it needn't be detected here.
867 let recursive = has_flag(tokens, Some("-r"), Some("--recursive"));
868 let scale = if recursive { Scale::Unbounded } else { Scale::Single };
869
870 let mut files = Vec::new(); // positional file operands
871 let mut pattern_files = Vec::new(); // -f/--file pattern files grep reads
872 let mut pattern_from_flag = false;
873 let mut unknown_flag = false;
874 let mut flags_done = false;
875 let mut i = 1;
876 while i < tokens.len() {
877 let t = tokens[i].as_str();
878 let next = tokens.get(i + 1).map(Token::as_str);
879 if !flags_done && t == "--" {
880 flags_done = true;
881 i += 1;
882 } else if flags_done || !t.starts_with('-') || t == "-" {
883 files.push(t);
884 i += 1;
885 } else if t.starts_with("--") {
886 if let Some(v) = t.strip_prefix("--file=") {
887 pattern_from_flag = true;
888 pattern_files.push(v);
889 i += 1;
890 } else if t == "--file" {
891 pattern_from_flag = true;
892 pattern_files.extend(next);
893 i += 2;
894 } else if t == "--regexp" {
895 pattern_from_flag = true;
896 i += 2;
897 } else if t.starts_with("--regexp=") {
898 pattern_from_flag = true;
899 i += 1;
900 } else if grep_long_known(t) {
901 i += 1;
902 } else if grep_long_dangerous(t) {
903 unknown_flag = true;
904 i += 1;
905 } else {
906 // An unrecognized `--token` is not a grep flag: it is the search PATTERN
907 // (grep patterns commonly look like `-->`, `---`, `--foo`). Treat it as a
908 // positional so the file operands classify the read, matching legacy.
909 files.push(t);
910 i += 1;
911 }
912 } else {
913 match grep_short_cluster(t, next) {
914 GrepShort::Unrecognized => {
915 unknown_flag = true;
916 i += 1;
917 }
918 GrepShort::Standalone => i += 1,
919 GrepShort::Pattern { file, consumes_next } => {
920 pattern_files.extend(file);
921 pattern_from_flag = true;
922 i += if consumes_next { 2 } else { 1 };
923 }
924 GrepShort::SkipValue { consumes_next } => i += if consumes_next { 2 } else { 1 },
925 }
926 }
927 }
928
929 if unknown_flag {
930 return None; // unrecognized flag → fail closed (§0)
931 }
932 if files.is_empty() {
933 // No positional operand → grep has no pattern (a `-e`/`-f` pattern still needs a
934 // search target). This is a usage error; the legacy classifier denies it, so the
935 // engine must not be looser — fail closed (§0).
936 return None;
937 }
938
939 if !pattern_from_flag {
940 files.remove(0); // the first positional is the PATTERN, not a file
941 }
942 if recursive && files.is_empty() {
943 files.push("."); // grep -r with no path searches the cwd
944 }
945
946 Some(GrepOperands { files, pattern_files, scale })
947}
948
949/// The outcome of parsing one grep short-option cluster.
950enum GrepShort<'a> {
951 /// An unrecognized short (e.g. `-R`, symlink-dereferencing recursive) → the caller worst-cases.
952 Unrecognized,
953 /// All chars benign; no value taken.
954 Standalone,
955 /// `-e`/`-f` supplied the pattern (so positionals are files); `-f`'s value, if any,
956 /// is a pattern file grep reads.
957 Pattern { file: Option<&'a str>, consumes_next: bool },
958 /// `-m`/`-A`/`-B`/`-C`/`-d` — a count/action value to skip.
959 SkipValue { consumes_next: bool },
960}
961
962/// Parse a grep short-option cluster (e.g. `-ifpatterns`), honoring GNU semantics that a
963/// value-taking short consumes the rest of its cluster (glued) or the next token.
964fn grep_short_cluster<'a>(cluster: &'a str, next: Option<&'a str>) -> GrepShort<'a> {
965 // NB: `r` (recursive) is benign, but `R` (--dereference-recursive) follows symlinks
966 // and can escape the classified locus, so it is NOT benign — it worst-cases. `P`
967 // (PCRE, `--perl-regexp`) IS benign: GNU grep's PCRE2 does not implement Perl's
968 // `(?{code})` execution, so it runs no code — it's just another regex engine like `-E`/`-F`.
969 const BENIGN: &[u8] = b"ivnclLoqswxHhaIrzZEFGbUP";
970 let bytes = cluster.as_bytes();
971 let mut k = 1;
972 while k < bytes.len() {
973 // Non-ASCII bytes aren't flags and would make `cluster[k + 1..]` slice mid-char.
974 if !bytes[k].is_ascii() {
975 return GrepShort::Unrecognized;
976 }
977 let glued = &cluster[k + 1..]; // safe: bytes[k] is ASCII → k+1 is a char boundary
978 let has = !glued.is_empty();
979 match bytes[k] {
980 b'f' => {
981 let file = if has { Some(glued) } else { next };
982 return GrepShort::Pattern { file, consumes_next: !has };
983 }
984 b'e' => return GrepShort::Pattern { file: None, consumes_next: !has },
985 b'm' | b'A' | b'B' | b'C' | b'd' => return GrepShort::SkipValue { consumes_next: !has },
986 b if BENIGN.contains(&b) => k += 1,
987 _ => return GrepShort::Unrecognized,
988 }
989 }
990 GrepShort::Standalone
991}
992
993/// Whether a grep long flag (its `--name`, ignoring any `=value`) is recognized-benign.
994/// `--dereference-recursive` and anything unlisted are not → worst-case (§0).
995fn grep_long_known(flag: &str) -> bool {
996 const KNOWN: &[&str] = &[
997 "--recursive", "--ignore-case", "--invert-match", // NB: --dereference-recursive
998 // (symlink-following) is intentionally absent → worst-case (M2)
999 "--line-number", "--count", "--files-with-matches", "--files-without-match",
1000 "--only-matching", "--perl-regexp", "--word-regexp", "--line-regexp", "--fixed-strings",
1001 "--extended-regexp", "--basic-regexp", "--with-filename", "--no-filename",
1002 "--quiet", "--silent", "--no-messages", "--null", "--byte-offset", "--text",
1003 "--color", "--colour", "--help", "--version", "--after-context", "--before-context",
1004 "--context", "--max-count", "--include", "--exclude", "--exclude-dir",
1005 "--include-dir", "--binary-files", "--devices", "--directories",
1006 ];
1007 let name = flag.split('=').next().unwrap_or(flag);
1008 KNOWN.contains(&name)
1009}
1010
1011/// The long spelling of the dangerous grep short `-R`: `--dereference-recursive` (follows
1012/// symlinks out of the classified locus, M2). Recognized so both spellings worst-case; every
1013/// OTHER unrecognized `--token` is a search pattern, not a flag. (`--perl-regexp`/`-P` is NOT
1014/// here — PCRE2 executes no code, so it is benign, like `-E`/`-F`.)
1015fn grep_long_dangerous(flag: &str) -> bool {
1016 let name = flag.split('=').next().unwrap_or(flag);
1017 matches!(name, "--dereference-recursive")
1018}
1019
1020/// `dd if=IN of=OUT bs=… …` — the operand-model breaker: `dd` takes NO getopt flags or
1021/// positionals, only `key=value` operands, so the shared `Flags`/`positionals` toolkit does
1022/// not apply and it parses its own. `if=` reads (default stdin), `of=` writes (default
1023/// stdout). It is still a transfer at the facet level — `dd if=~/.ssh/id_rsa of=./x` denies
1024/// on the input locus, `dd if=./x of=/dev/rdisk0` denies on the output locus (a raw device
1025/// is beneath the fs) — but the roles arrive inside `key=value`, not positional slots, which
1026/// is why its conservation probe is `Operands::Custom`. `bs`/`count`/`conv`/… are benign
1027/// transfer parameters; any other key, or a non-`key=value` operand, worst-cases (§0).
1028fn resolve_dd(tokens: &[Token]) -> Profile {
1029 const PARAMS: &[&str] = &[
1030 "bs", "ibs", "obs", "cbs", "count", "skip", "seek", "conv", "iflag", "oflag", "status",
1031 ];
1032 let (mut input, mut output) = (None, None);
1033 for t in &tokens[1..] {
1034 let t = t.as_str();
1035 if t == "--help" || t == "--version" {
1036 continue;
1037 }
1038 let Some((key, val)) = t.split_once('=') else {
1039 return worst("dd: non key=value operand — worst-cased (§0)");
1040 };
1041 match key {
1042 "if" => input = Some(val),
1043 "of" => output = Some(val),
1044 k if PARAMS.contains(&k) => {}
1045 _ => return worst("dd: unrecognized operand — worst-cased (§0)"),
1046 }
1047 }
1048 // dd touches exactly one input and one output — a `single` blast radius, whatever the
1049 // data VOLUME. The disk-wipe danger of `of=/dev/rdisk0` is carried by its device locus,
1050 // not by scale.
1051 let input_locus = input.map_or(LocalLocus::Process, read_locus);
1052 match output {
1053 // of= names a sink: read the input into it (no model disclosure) + write the sink.
1054 Some(of) => Profile::of(vec![
1055 observes(input_locus, Scale::Single, "dd reads its input (if=) into the output"),
1056 overwrites(classify_locus(of), Scale::Single, false),
1057 ]),
1058 // no of= → output is stdout, so the input content reaches the model (like `cat`).
1059 None => Profile::of(vec![reads_content(
1060 input_locus,
1061 Scale::Single,
1062 "dd copies its input to stdout (→ the model)",
1063 )]),
1064 }
1065}
1066
1067/// `tar` — the flag-SYNTAX breaker: its options may be written WITHOUT a leading dash
1068/// (`tar czf` == `tar -czf`), so the getopt walker misreads the cluster as a positional; tar
1069/// parses its own. The mode letter splits the profile sharply:
1070/// - create/append (`c`/`r`/`u`): reads each member (source) + writes the archive (dest) —
1071/// a bundler, so `tar czf - ~/.ssh` denies on the member locus (golden-set).
1072/// - list (`t`): reads the archive, prints member names to the model.
1073/// - extract (`x`) and the rarer modes: extraction writes an ARCHIVE-CONTROLLED set of
1074/// paths that `..`-traversal can send anywhere — unknowable without opening the archive,
1075/// so worst-case (§0). Any value-taking option we don't model (`-C`, `-T`, …) or an
1076/// unknown letter also worst-cases.
1077fn resolve_tar(tokens: &[Token]) -> Profile {
1078 let mut p = TarParse::default();
1079 // `-C DIR` changes the directory for the members that FOLLOW it, so a member's real locus
1080 // is `DIR/member` — the same `find … {}`→path binding. tar applies `-C` CUMULATIVELY: each
1081 // `-C` chdir's relative to the already-changed directory, so consecutive `-C / -C etc`
1082 // resolves to `/etc`, not `etc`. Compose relative values onto the active dir (via the same
1083 // `tar_bound` join, which also lets an absolute value replace and routes any `..` through
1084 // the unpinnable guard); stamp each positional with the accumulated dir.
1085 let mut dir: Option<String> = None;
1086 let mut i = 1;
1087 while i < tokens.len() {
1088 let t = tokens[i].as_str();
1089 if t == "-C" || t == "--directory" {
1090 dir = tokens.get(i + 1).map(|d| tar_bound(dir.as_deref(), d.as_str()));
1091 i += 2;
1092 continue;
1093 }
1094 if let Some(d) = t.strip_prefix("--directory=").or_else(|| t.strip_prefix("-C").filter(|d| !d.is_empty())) {
1095 dir = Some(tar_bound(dir.as_deref(), d));
1096 i += 1;
1097 continue;
1098 }
1099 if let Some(long) = t.strip_prefix("--") {
1100 p.long_option(long);
1101 } else if let Some(cluster) = t.strip_prefix('-').filter(|c| !c.is_empty()) {
1102 p.cluster(cluster);
1103 } else if i == 1 {
1104 p.cluster(t); // dashless old-style option bundle (only the first argument)
1105 } else {
1106 p.positionals.push((dir.clone(), t));
1107 }
1108 i += 1;
1109 }
1110 p.into_profile()
1111}
1112
1113/// A tar positional: a member/archive path with the accumulated `-C` directory active when it
1114/// appeared (already composed across consecutive `-C` options).
1115type TarPositional<'a> = (Option<String>, &'a str);
1116
1117/// A tar positional borrowed for classification: (`-C` dir, path).
1118type TarRef<'a> = (Option<&'a str>, &'a str);
1119
1120/// A tar member/archive path resolved against an active `-C` directory: `DIR/path` for a
1121/// relative path, or `path` unchanged when there is no `-C` or the path is absolute (an
1122/// absolute member ignores `-C`).
1123fn tar_bound(dir: Option<&str>, path: &str) -> String {
1124 match dir {
1125 Some(d) if !path.starts_with('/') && !path.starts_with('~') && !path.starts_with('-') => {
1126 format!("{}/{}", d.trim_end_matches('/'), path)
1127 }
1128 _ => path.to_string(),
1129 }
1130}
1131
1132/// Accumulated `tar` parse: the mode, whether `-f` wants an archive, and `reject` — set by
1133/// any option we can't model safely (an unknown letter, or a value-taking option like `-T`
1134/// / `-X` whose ordered operand consumption we don't track). `-C` IS modeled (see
1135/// `resolve_tar`); it only reaches `cluster` inside a mixed bundle, which still worst-cases.
1136#[derive(Default)]
1137struct TarParse<'a> {
1138 mode: Option<u8>,
1139 want_archive: bool,
1140 reject: bool,
1141 long_archive: Option<&'a str>,
1142 /// Each positional with the `-C` directory active when it appeared (`None` = cwd).
1143 positionals: Vec<TarPositional<'a>>,
1144}
1145
1146impl<'a> TarParse<'a> {
1147 fn cluster(&mut self, cluster: &str) {
1148 const NOVAL: &[u8] = b"vzjJZpkmOwhSlPa"; // benign no-value option letters
1149 for b in cluster.bytes() {
1150 match b {
1151 b'c' | b'x' | b't' | b'r' | b'u' | b'A' | b'd' => self.mode = Some(b),
1152 b'f' => self.want_archive = true,
1153 b'C' | b'T' | b'X' | b'b' | b'H' | b'g' | b'K' | b'N' => self.reject = true,
1154 x if NOVAL.contains(&x) => {}
1155 _ => self.reject = true,
1156 }
1157 }
1158 }
1159
1160 fn long_option(&mut self, long: &'a str) {
1161 let name = long.split('=').next().unwrap_or(long);
1162 match name {
1163 "create" => self.mode = Some(b'c'),
1164 "extract" | "get" => self.mode = Some(b'x'),
1165 "list" => self.mode = Some(b't'),
1166 "append" => self.mode = Some(b'r'),
1167 "update" => self.mode = Some(b'u'),
1168 "file" => match long.split_once('=') {
1169 Some((_, v)) => self.long_archive = Some(v),
1170 None => self.want_archive = true,
1171 },
1172 "gzip" | "bzip2" | "xz" | "zstd" | "compress" | "verbose" | "preserve-permissions"
1173 | "same-permissions" | "to-stdout" | "help" | "version" | "dereference" | "totals" => {}
1174 _ => self.reject = true,
1175 }
1176 }
1177
1178 fn into_profile(self) -> Profile {
1179 let Some(mode) = self.mode.filter(|_| !self.reject) else {
1180 return worst("tar: unrecognized/unmodeled option — worst-cased (§0)");
1181 };
1182 // Separate the archive from the members. `--file=X` names it directly; a bare `f`
1183 // (dashless `czf` or dashed `-czf`) takes the FIRST positional as the archive.
1184 let (archive, members): (Option<TarRef>, &[TarPositional]) =
1185 if let Some(a) = self.long_archive {
1186 (Some((None, a)), &self.positionals)
1187 } else if self.want_archive {
1188 match self.positionals.split_first() {
1189 Some((first, rest)) => (Some((first.0.as_deref(), first.1)), rest),
1190 None => return worst("tar: -f without an archive — worst-cased (§0)"),
1191 }
1192 } else {
1193 (None, &self.positionals) // archive is stdin/stdout
1194 };
1195 // A `-` archive (or none) is a stdout/stdin stream, not a file to gate.
1196 let archive_file = archive.filter(|(_, a)| *a != "-");
1197
1198 match mode {
1199 b'c' | b'r' | b'u' => {
1200 let mut caps: Vec<Capability> = members
1201 .iter()
1202 .map(|(dir, m)| observes_path(&tar_bound(dir.as_deref(), m), Scale::Bounded, "tar reads a member into the archive"))
1203 .collect();
1204 if let Some((dir, a)) = archive_file {
1205 caps.push(overwrites(classify_locus(&tar_bound(dir, a)), Scale::Single, false));
1206 }
1207 if caps.is_empty() {
1208 return worst("tar create with no members — worst-cased (§0)");
1209 }
1210 Profile::of(caps)
1211 }
1212 b't' => {
1213 let loc = archive_file.map_or(LocalLocus::Process, |(dir, a)| classify_locus(&tar_bound(dir, a)));
1214 Profile::of(vec![reads_content(loc, Scale::Single, "tar lists the archive's members (names → the model)")])
1215 }
1216 // x (extract) and A/d: archive-controlled, ..-escapable writes → worst-case.
1217 _ => worst("tar extract writes an archive-controlled, ..-escapable path set — worst-cased (§0)"),
1218 }
1219 }
1220}
1221
1222/// `sed` — the read-becomes-WRITE breaker: `sed 's/…/…/' FILE` reads FILE and prints to the
1223/// model, but `sed -i` edits the SAME file operands **in place** (a mutate), so a single
1224/// flag flips the operation on the same slots. Two more wrinkles: `-i` takes an OPTIONAL
1225/// glued suffix (`-i.bak`) the getopt walker can't express, and — like `grep` — the first
1226/// positional is the SCRIPT unless `-e`/`-f` supplied it (`-f` also reads a script file).
1227/// So `sed` parses its own flags.
1228fn resolve_sed(tokens: &[Token]) -> Profile {
1229 // HP-7: sed is a mini-language. Its `e` command/modifier executes text as a shell command
1230 // (RCE), and its `w`/`W`/`r`/`R` commands write/read arbitrary files EMBEDDED in the script —
1231 // both invisible to flag parsing. Scan the script(s): an `e`/unknown command worst-cases; the
1232 // file commands' filenames get gated by locus below (a local write is fine, `/etc/cron.d/x` is
1233 // not), exactly like the operand files.
1234 let script = crate::handlers::coreutils::sed::scan_sed(tokens);
1235 if script.exec || script.unknown {
1236 return worst("sed: script has an `e` exec or unmodeled command — worst-cased (§0, HP-7)");
1237 }
1238 // A `-f`/`--file` script comes from a file we can't read — its `e`/`w`/`r` commands are invisible,
1239 // so we can't verify it (like `awk -f`, `bash script.sh`, mlr `--load`). Worst-case it.
1240 if script.script_file {
1241 return worst("sed: -f runs a script file we can't inspect — worst-cased (§0)");
1242 }
1243 const BOOL: &[u8] = b"nrEsuz"; // no-value short flags
1244 let mut in_place = false;
1245 let mut script_from_flag = false;
1246 let mut script_files: Vec<&str> = Vec::new(); // -f FILE — sed reads these
1247 let mut files: Vec<&str> = Vec::new();
1248 let mut flags_done = false;
1249 let mut i = 1;
1250 while i < tokens.len() {
1251 let t = tokens[i].as_str();
1252 let next = tokens.get(i + 1).map(Token::as_str);
1253 if !flags_done && t == "--" {
1254 flags_done = true;
1255 i += 1;
1256 } else if flags_done || t == "-" || !t.starts_with('-') {
1257 files.push(t);
1258 i += 1;
1259 } else if let Some(long) = t.strip_prefix("--") {
1260 match sed_long(long, next, &mut in_place, &mut script_from_flag, &mut script_files) {
1261 Some(consumed) => i += consumed,
1262 None => return worst("sed: unrecognized flag — worst-cased (§0)"),
1263 }
1264 } else {
1265 match sed_cluster(&t[1..], next, BOOL) {
1266 SedShort::Bad => return worst("sed: unrecognized flag — worst-cased (§0)"),
1267 SedShort::InPlace => {
1268 in_place = true;
1269 i += 1;
1270 }
1271 SedShort::Standalone => i += 1,
1272 SedShort::Script { consumes_next } => {
1273 script_from_flag = true;
1274 i += usize::from(consumes_next) + 1;
1275 }
1276 SedShort::ScriptFile { file, consumes_next } => {
1277 script_from_flag = true;
1278 script_files.extend(file);
1279 i += usize::from(consumes_next) + 1;
1280 }
1281 SedShort::SkipValue { consumes_next } => i += usize::from(consumes_next) + 1,
1282 }
1283 }
1284 }
1285 // Without -e/-f, the first positional is the SCRIPT, not a file.
1286 if !script_from_flag && !files.is_empty() {
1287 files.remove(0);
1288 }
1289 // Blast radius: a glob (`sed -i … *`) or several operands is bounded, not single — so a
1290 // sweeping in-place edit is scored honestly (still worktree-bound by locus; a system or
1291 // home path denies whatever the scale).
1292 let scale = breadth_scale(&files, false);
1293 let mut caps: Vec<Capability> =
1294 script_files.iter().map(|f| observes_path(f, Scale::Single, "sed reads an -f script file")).collect();
1295 // Script-embedded file commands (`w`/`W` write, `r`/`R` read, `s///w` write) — gate each target
1296 // by its locus, just like an operand file.
1297 caps.extend(script.writes.iter().map(|f| mutates(classify_locus(f), Scale::Single, "sed w/W writes a file")));
1298 caps.extend(script.reads.iter().map(|f| observes_path(f, Scale::Single, "sed r/R reads a file")));
1299 if in_place {
1300 caps.extend(files.iter().map(|f| mutates(classify_locus(f), scale, "sed -i edits the file in place")));
1301 } else {
1302 caps.extend(reads_to_model(&files, scale));
1303 }
1304 Profile::of(caps)
1305}
1306
1307/// The locus of the paths a `$( … )` can PRODUCE, or `None` when nothing bounds them.
1308///
1309/// This is a different question from "is the inner command safe to run", and conflating the two is
1310/// a fail-open: `echo` is inert and `$(echo /etc/shadow)` still names a credential file. So a
1311/// command only gets an answer here if it has declared one (`[command.output]`); everything else
1312/// stays unpinnable, exactly as before. See docs/design/behavioral-taxonomy-substitution-locus.md.
1313pub(crate) fn substitution_claim(script: &crate::cst::Script) -> Option<SubClaim> {
1314 // A pipeline's VALUE is its last stage's stdout; the earlier stages feed it and are verdicted
1315 // separately as usual. Pass-through filters (`… | head -1`) emit a SUBSET of what they were
1316 // given, so walking back over them reaches the stage that actually produced the paths.
1317 let [stmt] = script.0.as_slice() else { return None };
1318 let cmds = &stmt.pipeline.commands;
1319 let mut idx = cmds.len().checked_sub(1)?;
1320 loop {
1321 match stage_output_locus(cmds.get(idx)?)? {
1322 StageOutput::Locus(l) => return Some(SubClaim::Locus(l)),
1323 // A pass-through filter emits a SUBSET of its input words, so it cannot turn an atom
1324 // into something with a separator — the claim survives the filter unchanged.
1325 StageOutput::Atom => return Some(SubClaim::Atom),
1326 StageOutput::PassThrough => idx = idx.checked_sub(1)?,
1327 }
1328 }
1329}
1330
1331enum StageOutput {
1332 Locus(LocalLocus),
1333 /// Every word of this stage's stdout is separator-free, so no word can BE a path.
1334 Atom,
1335 /// This stage only filters; ask the stage before it.
1336 PassThrough,
1337}
1338
1339/// What a `$(…)` is known to yield. Two different kinds of claim, which is why this is not an
1340/// `Option<LocalLocus>`: a locus says the value NAMES something at a rung, an atom says the value
1341/// names nothing at all and cannot traverse. The second is the weaker claim and the more useful
1342/// one — it is what lets a literal prefix survive around an interpolated leaf.
1343pub(crate) enum SubClaim {
1344 Locus(LocalLocus),
1345 Atom,
1346}
1347
1348fn stage_output_locus(cmd: &crate::cst::Cmd) -> Option<StageOutput> {
1349 let crate::cst::Cmd::Simple(simple) = cmd else { return None };
1350 let words: Vec<String> = simple.words.iter().map(crate::cst::Word::eval).collect();
1351 use crate::registry::types::OutputLocus;
1352 let (name, args) = words.split_first()?;
1353 // A resolvable name reached from a non-standard path (`./fd`) may not be the real tool, so it
1354 // gets no output-locus claim — the same spoof rule `resolve` applies to the command itself.
1355 if !trusted_command_path(name) {
1356 return None;
1357 }
1358 let token = Token::from_raw(name.clone());
1359 let canonical = crate::registry::canonical_name(token.command_name());
1360 // A SUB's claim wins over the command's, and narrows `args` to what follows the sub path so the
1361 // sub name is not counted as a path operand (`git ls-files src/` must see `src/`, not `ls-files`).
1362 let (rule, args) = match crate::registry::sub_output_locus(canonical, args) {
1363 Some((rule, rest)) => (rule, rest),
1364 None => (crate::registry::command_output_locus(canonical)?, args),
1365 };
1366 // At least one required flag must be present, or the command prints something other than paths
1367 // entirely — `git diff` without `--name-only` prints a patch. Checked before `invalidated_by`
1368 // because it is the stronger condition: absent, there is no claim to invalidate.
1369 if !rule.requires.is_empty() && !rule.requires.iter().any(|r| args.iter().any(|a| flag_present(a, std::slice::from_ref(r)))) {
1370 return None;
1371 }
1372 // `--help` and `--version` replace the command's DATA output with prose, and EVERY output
1373 // claim is a statement about the data. GNU `seq --help` prints
1374 // `<https://www.gnu.org/software/coreutils/>` — slash-bearing words under an `atom` claim that
1375 // says no word can contain a separator. Handled here rather than in each command's
1376 // `invalidated_by` so it holds for claims that do not exist yet: the danger is not seq (whose
1377 // help leaks only URLs, which as paths are relative) but the next atom source whose help
1378 // prints `/etc/foo.conf`, which would hand an ABSOLUTE path to a caller told it was confined.
1379 //
1380 // Long forms only. `-h` and `-V` are not reliably help/version — `sort -h` is human-numeric
1381 // sort — so treating them as informational would void real claims. A command whose OWN grammar
1382 // maps a short flag to help lists it in `invalidated_by` (see seq).
1383 //
1384 // Not caught by the local install: macOS ships BSD seq, whose help is terse and slash-free.
1385 if args.iter().any(|a| a == "--help" || a == "--version") {
1386 return None;
1387 }
1388 // A flag that changes what stdout CONTAINS (`fd -x cat {}` prints file bodies, `fd -l` prints
1389 // `ls -l` rows) voids the claim — the output is no longer a path at all.
1390 if args.iter().any(|a| flag_present(a, &rule.invalidated_by)) {
1391 return None;
1392 }
1393
1394 match rule.locus_from {
1395 // An ATOM names no locus — a separator-free word is not a path and cannot stand in for
1396 // one. It pays off in the PATH layer instead: a literal prefix around a FLANKED atom leaf
1397 // is confinable, because the atom cannot introduce a `/` and the flanking rules out the
1398 // leaf being `.` or `..`. Both halves of that are enforced in `locus::neutralize_atoms`;
1399 // on its own this claim widens nothing, since an atom sentinel is `is_unpinnable`.
1400 OutputLocus::Atom => Some(StageOutput::Atom),
1401 // The cwd is the workspace root by construction (the harness passes it), so `$(pwd)` is a
1402 // worktree path. `pathctx` is what decides whether the cwd itself escaped the root.
1403 OutputLocus::Cwd => Some(StageOutput::Locus(read_locus("."))),
1404 // Output descends the command's own path operands, so it is bounded by their worst read
1405 // locus. `fd x app/ lib/` → worktree; `fd x /` → machine.
1406 OutputLocus::Operands => {
1407 // ANY unpinnable argument voids the claim, checked before the path-shape filter and
1408 // over every argument rather than the ones that look like roots. A `$VAR` root carries
1409 // no `/`, so shape-filtering first read `fd pat $SECRET` as having no root at all and
1410 // reported worktree — while the command searches wherever `$SECRET` points.
1411 if args.iter().any(|a| is_unpinnable(a)) {
1412 return None;
1413 }
1414 let roots = candidate_roots(args, &rule.valued);
1415 // No path operand means the command searches `.` (`fd pattern`), which is the cwd.
1416 let worst = roots.iter().map(|r| read_locus(r)).max().unwrap_or_else(|| read_locus("."));
1417 Some(StageOutput::Locus(worst))
1418 }
1419 // Only a filter when it is filtering: given a file operand it prints that file's CONTENTS,
1420 // which are caller-controlled text and no kind of path.
1421 OutputLocus::Stdin => {
1422 if candidate_roots(args, &rule.valued).is_empty() {
1423 Some(StageOutput::PassThrough)
1424 } else {
1425 None
1426 }
1427 }
1428 }
1429}
1430
1431/// Whether `arg` is one of `flags`, in any spelling that carries a value (`-x`, `--exec`,
1432/// `--exec=…`). A short flag may also be CLUSTERED (`-lx`), so single-char forms are matched
1433/// against the cluster's letters.
1434fn flag_present(arg: &str, flags: &[String]) -> bool {
1435 let head = arg.split('=').next().unwrap_or(arg);
1436 flags.iter().any(|f| {
1437 if head == f {
1438 return true;
1439 }
1440 match (f.strip_prefix('-'), arg.strip_prefix('-')) {
1441 (Some(letter), Some(cluster)) if f.len() == 2 && !arg.starts_with("--") => {
1442 cluster.contains(letter)
1443 }
1444 _ => false,
1445 }
1446 })
1447}
1448
1449/// Every argument that could name a search ROOT, over-approximated on purpose.
1450///
1451/// Under-counting here is a fail-OPEN — a missed root means a lower locus than the command actually
1452/// reaches — so EVERY non-flag argument counts, plus any path glued to a flag
1453/// (`--search-path=/etc`, `-E/etc/x`). Over-counting only ever raises the locus, which denies.
1454///
1455/// It deliberately does NOT ask whether an argument looks like a path. That test (`looks_like_path`)
1456/// keys on a `/` or a `.`, so a bare `~` failed it and `cat $(fd pat ~)` auto-approved a sweep of
1457/// the home directory as though it were worktree-local. A shape heuristic cannot be the last word
1458/// on a question whose wrong answer opens a hole.
1459fn candidate_roots<'a>(args: &'a [String], valued: &[String]) -> Vec<&'a str> {
1460 let mut roots = Vec::new();
1461 let mut skip_value = false;
1462 for a in args {
1463 if std::mem::take(&mut skip_value) {
1464 continue;
1465 }
1466 if a.starts_with('-') {
1467 // `valued` declares "this flag's value is NOT a path" (a count, a separator), so its
1468 // value is skipped in BOTH spellings. Handling only the separated form denied
1469 // `head --lines=5` while `head -n 5` passed — the same operation, two spellings.
1470 let (head, glued_value) = match a.split_once('=') {
1471 Some((h, v)) => (h, Some(v)),
1472 None => (a.as_str(), None),
1473 };
1474 if valued.iter().any(|v| v == head) {
1475 skip_value = glued_value.is_none();
1476 continue;
1477 }
1478 // Otherwise a glued value can still name a root. After `=` the whole value counts —
1479 // keying on `/` alone missed `--search-path=~`, the same blind spot as the shape test.
1480 // Without an `=`, a glued short value starts at the first path-ish character.
1481 let glued = glued_value.or_else(|| a.find(['/', '~']).map(|i| &a[i..]));
1482 if let Some(v) = glued.filter(|v| !v.is_empty()) {
1483 roots.push(v);
1484 }
1485 continue;
1486 }
1487 roots.push(a.as_str());
1488 }
1489 roots
1490}
1491
1492fn resolve_perl(tokens: &[Token]) -> Profile {
1493 // perl's `-e` one-liner is arbitrary code, so the identifier gate in `handlers::perl` decides
1494 // whether the CODE is inert. What that gate cannot do is judge the OPERANDS: it never looked at
1495 // them, which is why `perl -pe s/a/b/ /etc/shadow` used to read a credential file and print it
1496 // to the model. Both halves are needed — an inert one-liner over a system file is still an
1497 // exfiltration, and a worktree file rewritten by unmodeled code is still RCE.
1498 use crate::handlers::perl::PerlCode;
1499 let Some(scan) = crate::handlers::perl::scan_perl(tokens) else {
1500 return worst("perl: unmodeled flag cluster — worst-cased (§0)");
1501 };
1502 match scan.code {
1503 PerlCode::None => {
1504 let mut c = Capability::new(Operation::Observe);
1505 c.disclosure.audience = DisclosureAudience::LocalProcess;
1506 c.because = "perl: reports its own version/usage".to_string();
1507 return Profile::of(vec![c]);
1508 }
1509 // No `-e`/`-E` means the first operand is a SCRIPT FILE whose contents we cannot inspect
1510 // (like `sed -f`, `awk -f`, `bash x.sh`), and a failed identifier gate means the one-liner
1511 // reached outside the modeled vocabulary. Neither is separable from arbitrary execution.
1512 PerlCode::Opaque => return worst("perl: no inspectable -e/-E one-liner — worst-cased (§0)"),
1513 PerlCode::Inspectable => {}
1514 }
1515 // A sweeping in-place edit (`perl -pi -e … *`) is bounded but not single; locus still binds
1516 // each operand, so breadth widens the blast radius without ever admitting a system path.
1517 let files: Vec<&str> = scan.files.iter().map(String::as_str).collect();
1518 let scale = breadth_scale(&files, false);
1519 // No `execute` capability, deliberately. perl does run code, so recording one looks more
1520 // honest — but it is the wrong model here and the experiment says so: an
1521 // `executes(caller-inline)` capability denies at every band, which would take out every perl
1522 // one-liner including the in-place edits this hook exists to admit. The reason it denies is
1523 // that the `execute` rung describes running code of UNKNOWN content, and by this point the
1524 // identifier gate has already established the opposite — the one-liner reaches nothing but
1525 // pure built-ins, no I/O, no exec, no network. What remains observable is the operand reads
1526 // and writes below, and those ARE the profile. If the gate's vocabulary ever admits an
1527 // identifier with side effects, the fix belongs in the gate, not in a capability here.
1528 let caps: Vec<Capability> = if scan.in_place {
1529 files.iter().map(|f| mutates(classify_locus(f), scale, "perl -i edits the file in place")).collect()
1530 } else {
1531 reads_to_model(&files, scale)
1532 };
1533 Profile::of(caps)
1534}
1535
1536/// The outcome of parsing one `sed` short-option cluster.
1537enum SedShort<'a> {
1538 Bad,
1539 Standalone,
1540 InPlace, // -i (rest is the optional suffix)
1541 Script { consumes_next: bool }, // -e SCRIPT
1542 ScriptFile { file: Option<&'a str>, consumes_next: bool }, // -f FILE
1543 SkipValue { consumes_next: bool }, // -l N
1544}
1545
1546fn sed_cluster<'a>(cluster: &'a str, next: Option<&'a str>, boolset: &[u8]) -> SedShort<'a> {
1547 let bytes = cluster.as_bytes();
1548 let mut k = 0;
1549 while k < bytes.len() {
1550 // A flag byte is ASCII; a non-ASCII lead/continuation byte is not a flag, and slicing
1551 // `cluster[k + 1..]` at it would land mid-char and panic. Bail as unrecognized.
1552 if !bytes[k].is_ascii() {
1553 return SedShort::Bad;
1554 }
1555 let glued = &cluster[k + 1..]; // safe: bytes[k] is ASCII → k+1 is a char boundary
1556 let has = !glued.is_empty();
1557 match bytes[k] {
1558 b'i' => return SedShort::InPlace, // -i[SUFFIX]: the rest of the cluster is the suffix
1559 b'e' => return SedShort::Script { consumes_next: !has },
1560 b'f' => {
1561 let file = if has { Some(glued) } else { next };
1562 return SedShort::ScriptFile { file, consumes_next: !has };
1563 }
1564 b'l' if has || next.is_some() => return SedShort::SkipValue { consumes_next: !has }, // -l N
1565 b if boolset.contains(&b) => k += 1,
1566 _ => return SedShort::Bad,
1567 }
1568 }
1569 SedShort::Standalone
1570}
1571
1572/// Parse a `sed` long option, returning how many tokens it consumed, or `None` if unknown.
1573fn sed_long<'a>(
1574 long: &'a str,
1575 next: Option<&'a str>,
1576 in_place: &mut bool,
1577 script_from_flag: &mut bool,
1578 script_files: &mut Vec<&'a str>,
1579) -> Option<usize> {
1580 let name = long.split('=').next().unwrap_or(long);
1581 match name {
1582 "in-place" => *in_place = true, // --in-place[=SUFFIX] (glued only)
1583 "expression" => {
1584 *script_from_flag = true;
1585 return Some(if long.contains('=') { 1 } else { 2 });
1586 }
1587 "file" => {
1588 *script_from_flag = true;
1589 match long.split_once('=') {
1590 Some((_, v)) => script_files.push(v),
1591 None => {
1592 script_files.extend(next);
1593 return Some(2);
1594 }
1595 }
1596 }
1597 "quiet" | "silent" | "regexp-extended" | "null-data" | "separate" | "unbuffered"
1598 | "posix" | "help" | "version" | "debug" | "follow-symlinks" | "sandbox"
1599 | "zero-terminated" | "line-length" => {}
1600 _ => return None,
1601 }
1602 Some(1)
1603}
1604
1605#[cfg(test)]
1606mod tests {
1607 use super::*;
1608
1609 fn toks(parts: &[&str]) -> Vec<Token> {
1610 parts.iter().map(|p| Token::from_test(p)).collect()
1611 }
1612
1613 fn level(name: &str) -> &'static crate::engine::level::Level {
1614 crate::engine::authoring::default_levels()
1615 .iter()
1616 .find(|l| l.name == name)
1617 .expect("level exists")
1618 }
1619
1620 fn inert() -> &'static crate::engine::level::Level {
1621 level("paranoid")
1622 }
1623
1624 fn read_local() -> &'static crate::engine::level::Level {
1625 level("reader")
1626 }
1627
1628 /// `resolve_openssl` contract: a private-key/decrypt form reaching the MODEL classifies as
1629 /// decrypt-read (secret=reads → refused by developer, admitted only by yolo); a public/to-file/
1630 /// validate form ABSTAINS (None → openssl's legacy allow_all); a spoofed path worst-cases.
1631 #[test]
1632 fn openssl_resolver_gates_model_disclosure_only() {
1633 let (dev, yolo) = (level("developer"), level("yolo"));
1634 for parts in [
1635 &["openssl", "rsa", "-in", "priv.pem"][..],
1636 &["openssl", "rsa", "-in", "priv.pem", "-pubout", "-text"], // -text past -pubout
1637 &["openssl", "rsa", "-in", "priv.pem", "-out", "/dev/stdout"], // -out value is stdout
1638 &["openssl", "rsa", "-in", "priv.pem", "-noout", "-text"],
1639 &["openssl", "pkcs8", "-in", "priv.pem"],
1640 &["openssl", "enc", "--d", "-k", "p", "-in", "c"], // --opt alias
1641 &["openssl", "cms", "-EncryptedData_decrypt", "-in", "m"],
1642 &["openssl", "pkcs12", "-in", "f.p12", "-noenc"],
1643 ] {
1644 let p = resolve(&toks(parts)).unwrap_or_else(|| panic!("resolves: {parts:?}"));
1645 assert!(
1646 p.capabilities.iter().any(|c| c.secret.level == SecretLevel::Reads),
1647 "secret=reads: {parts:?}",
1648 );
1649 assert!(!dev.admits(&p), "developer refuses: {parts:?}");
1650 assert!(yolo.admits(&p), "yolo admits: {parts:?}");
1651 }
1652 for parts in [
1653 &["openssl", "rsa", "-in", "priv.pem", "-pubout"][..],
1654 &["openssl", "rsa", "-in", "priv.pem", "-noout"], // validate, no output
1655 &["openssl", "rsa", "-in", "enc.pem", "-out", "clean.pem"], // to a FILE, off the model
1656 &["openssl", "pkey", "-in", "pub.pem", "-pubin", "-text"], // public input → public text
1657 &["openssl", "pkcs12", "-in", "f.p12", "-nodes", "-out", "k.pem"],
1658 &["openssl", "enc", "-e", "-in", "x", "-out", "x.enc", "-k", "p"],
1659 &["openssl", "x509", "-in", "c", "-noout", "-text"],
1660 ] {
1661 assert!(resolve(&toks(parts)).is_none(), "resolver abstains (→ legacy): {parts:?}");
1662 }
1663 }
1664
1665 /// The output-destination check is FAIL-CLOSED: only a single plain-file `-out` diverts the key
1666 /// off the model. Path-normalization spellings, `/dev/stderr`, and duplicate `-out` (openssl honors
1667 /// the last) must all read as model-reaching — the sign-off review found the old device-spelling
1668 /// denylist let these through.
1669 #[test]
1670 fn openssl_output_destination_is_fail_closed() {
1671 let dev = level("developer");
1672 let reaches_model = |args: &[&str]| {
1673 let mut parts = vec!["openssl", "rsa", "-in", "priv.pem"];
1674 parts.extend_from_slice(args);
1675 // decrypt-read (secret=reads, refused by developer) ⇔ the output reached the model; a
1676 // diverted output makes the resolver ABSTAIN (None → openssl's benign legacy).
1677 match resolve(&toks(&parts)) {
1678 None => false,
1679 Some(p) => {
1680 p.capabilities.iter().any(|c| c.secret.level == SecretLevel::Reads) && !dev.admits(&p)
1681 }
1682 }
1683 };
1684 for evasion in [
1685 &["-out", "//dev/stdout"][..],
1686 &["-out", "/dev/./stdout"],
1687 &["-out", "//dev/fd/1"],
1688 &["-out", "/dev/fd//1"],
1689 &["-out=//dev/stdout"],
1690 &["-out", "/dev/stderr"],
1691 &["-out", "/foo/../dev/stdout"],
1692 &["-out", "dup.pem", "-out", "/dev/stdout"], // last-wins
1693 &["-out", "-"],
1694 // openssl's parser lets `-provider-path` swallow the `-out` token → openssl writes to
1695 // stdout; our scan then misreads the trailing flag as the filename. A dash-leading `-out`
1696 // value is the tell → fail closed.
1697 &["-provider-path", "-out", "-provider-path", "safe.pem"],
1698 &["-out", "-anything"],
1699 ] {
1700 assert!(reaches_model(evasion), "must read as model-reaching: {evasion:?}");
1701 }
1702 for diverted in [
1703 &["-out", "clean.pem"][..],
1704 &["-out", "./sub/key.pem"],
1705 &["-out", "devnotes.pem"], // "dev" prefix on a filename is not the /dev device
1706 &["-out", "/home/u/key.pem"],
1707 &["-noout"],
1708 ] {
1709 assert!(!reaches_model(diverted), "must divert off the model: {diverted:?}");
1710 }
1711 }
1712
1713 #[test]
1714 fn echo_resolves_to_a_benign_inert_profile() {
1715 let p = resolve(&toks(&["echo", "hi"])).expect("echo has a resolver");
1716 assert_eq!(p.capabilities.len(), 1);
1717 let c = &p.capabilities[0];
1718 assert_eq!(c.operation, Operation::Observe);
1719 assert_eq!(c.locus.local, LocalLocus::Process);
1720 assert_eq!(c.disclosure.audience, DisclosureAudience::LocalProcess);
1721 assert!(!c.because.is_empty(), "a structural certification cites its reason");
1722 // admitted at the *strictest* level — every facet (network/exec/secret/…) is zero
1723 assert!(inert().admits(&p), "echo is fully certified and inert-safe");
1724 }
1725
1726 #[test]
1727 fn echo_flags_do_not_change_its_profile() {
1728 let bare = resolve(&toks(&["echo", "hi"])).expect("echo");
1729 let flagged = resolve(&toks(&["echo", "-n", "-e", "hi"])).expect("echo -n -e");
1730 assert_eq!(bare, flagged);
1731 assert!(inert().admits(&flagged));
1732 }
1733
1734 #[test]
1735 fn an_unresearched_command_has_no_resolver() {
1736 assert!(resolve(&toks(UNRESOLVED_CMD)).is_none(), "unresearched → caller worst-cases");
1737 assert!(resolve(&[]).is_none(), "empty tokens");
1738 }
1739
1740 #[test]
1741 fn cat_of_a_worktree_file_is_read_local() {
1742 let p = resolve(&toks(&["cat", "./notes.md"])).expect("cat");
1743 assert!(read_local().admits(&p), "cat ./notes.md");
1744 assert!(!inert().admits(&p), "reading a real file is above inert");
1745 }
1746
1747 #[test]
1748 fn cat_beyond_the_worktree_is_denied_by_locus() {
1749 // Secrets, private home, unpinnable, and unrecognized system paths stay denied…
1750 for path in ["~/.ssh/id_rsa", "~/notes", "/etc/shadow", "$SECRET", "../outside", "/var/lib/mysql/data"] {
1751 let p = resolve(&toks(&["cat", path])).expect("cat");
1752 assert!(!read_local().admits(&p), "cat {path} is above read-local by locus");
1753 }
1754 }
1755
1756 #[test]
1757 fn cat_of_machine_config_is_not_admitted() {
1758 // The retreat still holds for machine CONFIG and STATE: these prompt, or the user grants.
1759 // `/usr/share/doc/x` moved out of this list deliberately — see the test below.
1760 for path in ["/etc/hosts", "/etc/os-release", "/usr/local/etc/nginx/nginx.conf", "/var/log/auth.log"] {
1761 let p = resolve(&toks(&["cat", path])).expect("cat");
1762 assert!(!read_local().admits(&p), "cat {path} is no longer auto-approved");
1763 }
1764 }
1765
1766 /// Distributed package CONTENT is read-admitted; its WRITE face is not.
1767 ///
1768 /// The retreat refused whole roots because an audit found them leaking — the macOS keychain,
1769 /// Homebrew service configs under `etc`, auth tokens under `/var/log`. Those all live in a
1770 /// root's machine-local half. Cutting at the layer the FHS already separates keeps the leaks
1771 /// out (`etc`/`var` are never admitted) while ending the friction of refusing a man page or a
1772 /// vendored crate README, whose bytes are public by construction.
1773 #[test]
1774 fn package_content_is_readable_but_never_writable() {
1775 for path in [
1776 "/usr/share/doc/x",
1777 "/usr/share/man/man1/git.1",
1778 "/usr/local/share/doc/x/README",
1779 "/opt/homebrew/lib/node_modules/npm/package.json",
1780 "/Library/Developer/CommandLineTools/usr/include/stdio.h",
1781 "/nix/store/abc/share/doc/README",
1782 "~/.cargo/registry/src/idx/serde-1.0/README.md",
1783 "~/.rustup/toolchains/stable/lib/rustlib/src/core/src/lib.rs",
1784 "~/go/pkg/mod/github.com/x/y@v1/README.md",
1785 "~/.local/share/mise/installs/node/22/README.md",
1786 ] {
1787 let read = resolve(&toks(&["cat", path])).expect("cat");
1788 assert!(read_local().admits(&read), "reading package content {path} should be admitted");
1789 let write = resolve(&toks(&["rm", "-rf", path])).expect("rm");
1790 assert!(
1791 !read_local().admits(&write),
1792 "package content {path} must NOT be writable — this widens disclosure only"
1793 );
1794 }
1795 }
1796
1797 /// The credential shield outranks an admit prefix, whatever the specificity ordering says.
1798 ///
1799 /// Specificity ranks exact ≫ prefix ≫ segment, so every subtree admit outranked the shield's
1800 /// segment match: `/usr/share/.ssh/id_rsa` was APPROVED the moment package content became
1801 /// readable. A shield that a new admit node can widen is not a shield.
1802 #[test]
1803 fn an_admit_prefix_can_never_widen_the_credential_shield() {
1804 for path in [
1805 "/usr/share/.ssh/id_rsa",
1806 "/usr/local/lib/.aws/credentials",
1807 "/opt/homebrew/share/.gnupg/secring.gpg",
1808 "~/.cargo/registry/.ssh/id_ed25519",
1809 "/nix/store/x/.aws/credentials",
1810 ] {
1811 let p = resolve(&toks(&["cat", path])).expect("cat");
1812 assert!(!read_local().admits(&p), "an admit prefix widened the shield at {path}");
1813 }
1814 }
1815
1816 #[test]
1817 fn cat_stdin_is_process_scoped() {
1818 assert!(inert().admits(&resolve(&toks(&["cat"])).expect("cat")), "no operand → stdin");
1819 assert!(inert().admits(&resolve(&toks(&["cat", "-"])).expect("cat -")), "- → stdin");
1820 }
1821
1822 #[test]
1823 fn cat_reads_every_file_operand_and_one_home_read_sinks_it() {
1824 let p = resolve(&toks(&["cat", "-n", "a.txt", "src/b.rs"])).expect("cat");
1825 assert_eq!(p.capabilities.len(), 2, "-n is a flag; two files");
1826 assert!(read_local().admits(&p), "both worktree");
1827
1828 let mixed = resolve(&toks(&["cat", "a.txt", "~/.ssh/id_rsa"])).expect("cat");
1829 assert!(!read_local().admits(&mixed), "one home read sinks the whole profile");
1830 }
1831
1832 #[test]
1833 fn cat_double_dash_treats_the_rest_as_files() {
1834 let p = resolve(&toks(&["cat", "--", "-n"])).expect("cat");
1835 assert_eq!(p.capabilities.len(), 1, "-n after -- is a filename");
1836 assert!(read_local().admits(&p));
1837 }
1838
1839 #[test]
1840 fn head_tail_wc_read_like_cat_and_honor_numeric_shorthand() {
1841 use crate::engine::bridge::project;
1842 use crate::verdict::{SafetyLevel, Verdict};
1843 // worktree reads → read-local (SafeRead); home reads → denied by locus, same as cat.
1844 for cmd in [
1845 vec!["head", "README.md"],
1846 vec!["head", "-n", "5", "src/main.rs"],
1847 vec!["head", "-20", "src/main.rs"], // obsolete -NUM form must parse
1848 vec!["tail", "-f", "./log.txt"], // follow is still a bounded read
1849 vec!["tail", "-n", "100", "./log.txt"],
1850 vec!["wc", "-l", "./notes.md"],
1851 ] {
1852 assert_eq!(project(&resolve(&toks(&cmd)).expect("read")), Verdict::Allowed(SafetyLevel::SafeRead), "{cmd:?}");
1853 }
1854 // reading stdin (`-`) is process-scoped → inert, like `cat -`.
1855 assert_eq!(project(&resolve(&toks(&["wc", "-c", "-"])).expect("wc")), Verdict::Allowed(SafetyLevel::Inert), "wc stdin");
1856 for cmd in [vec!["head", "~/.ssh/id_rsa"], vec!["tail", "/etc/shadow"], vec!["wc", "-l", "$SECRET"]] {
1857 assert_eq!(project(&resolve(&toks(&cmd)).expect("read")), Verdict::Denied, "{cmd:?} beyond worktree");
1858 }
1859 // -NUM consumes no operand: `head -20 file` reads exactly `file`, not a phantom "20".
1860 let p = resolve(&toks(&["head", "-20", "src/main.rs"])).expect("head");
1861 assert_eq!(p.capabilities.len(), 1, "-20 is the count, not a file");
1862 // wc --files0-from reads an unpinnable set → worst-case → denied.
1863 assert_eq!(project(&resolve(&toks(&["wc", "--files0-from=list"])).expect("wc")), Verdict::Denied, "--files0-from");
1864 assert_eq!(project(&resolve(&toks(&["wc", "--files0-from", "-"])).expect("wc")), Verdict::Denied, "--files0-from -");
1865 // unknown flags fail closed.
1866 assert_eq!(project(&resolve(&toks(&["head", "-Z", "x"])).expect("head")), Verdict::Denied, "unknown flag");
1867 }
1868
1869 #[test]
1870 fn grep_reads_its_files_not_the_pattern() {
1871 let p = resolve(&toks(&["grep", "foo", "file.txt"])).expect("grep");
1872 assert_eq!(p.capabilities.len(), 1, "the pattern is not a file");
1873 assert!(read_local().admits(&p));
1874 }
1875
1876 #[test]
1877 fn grep_beyond_the_worktree_is_denied() {
1878 for args in [
1879 vec!["grep", "foo", "~/.ssh/config"],
1880 vec!["grep", "-r", "foo", "~"],
1881 vec!["grep", "foo", "$DIR"],
1882 ] {
1883 let p = resolve(&toks(&args)).expect("grep");
1884 assert!(!read_local().admits(&p), "{args:?}");
1885 }
1886 }
1887
1888 #[test]
1889 fn grep_recursive_is_unbounded_and_defaults_to_cwd() {
1890 let p = resolve(&toks(&["grep", "-r", "foo", "src/"])).expect("grep");
1891 assert!(p.capabilities.iter().all(|c| c.scale == Scale::Unbounded), "-r → unbounded");
1892 assert!(read_local().admits(&p), "recursive worktree search");
1893
1894 let cwd = resolve(&toks(&["grep", "-r", "foo"])).expect("grep");
1895 assert!(cwd.capabilities.iter().all(|c| c.locus.local == LocalLocus::Worktree), "cwd, not stdin");
1896 assert!(read_local().admits(&cwd));
1897 }
1898
1899 #[test]
1900 fn grep_e_and_f_supply_the_pattern_so_positionals_are_files() {
1901 // -e: pattern is the flag's value; file.txt is the only file
1902 let e = resolve(&toks(&["grep", "-e", "foo", "file.txt"])).expect("grep -e");
1903 assert_eq!(e.capabilities.len(), 1);
1904 assert!(read_local().admits(&e));
1905
1906 // -f: the pattern FILE is itself a read
1907 let f = resolve(&toks(&["grep", "-f", "patterns.txt", "file.txt"])).expect("grep -f");
1908 assert_eq!(f.capabilities.len(), 2, "patterns.txt + file.txt");
1909 assert!(read_local().admits(&f));
1910
1911 let home = resolve(&toks(&["grep", "-f", "~/.secret-patterns", "file.txt"])).expect("grep -f");
1912 assert!(!read_local().admits(&home), "a home pattern file is denied by locus");
1913
1914 // glued short value: -fpatterns.txt and -ifpatterns.txt both name a pattern file
1915 let glued = resolve(&toks(&["grep", "-fpatterns.txt", "file.txt"])).expect("grep -f glued");
1916 assert_eq!(glued.capabilities.len(), 2, "glued -f value is still a read");
1917 let glued_home = resolve(&toks(&["grep", "-if~/.secrets", "x"])).expect("grep -if glued");
1918 assert!(!read_local().admits(&glued_home), "glued home pattern file denied by locus");
1919 }
1920
1921 #[test]
1922 fn grep_long_flags() {
1923 // --file / --file= name a pattern file grep also reads (2 caps)
1924 assert_eq!(resolve(&toks(&["grep", "--file", "p.txt", "f.txt"])).expect("grep").capabilities.len(), 2);
1925 assert_eq!(resolve(&toks(&["grep", "--file=p.txt", "f.txt"])).expect("grep").capabilities.len(), 2);
1926
1927 // --regexp supplies the pattern; the positional is the file
1928 let r = resolve(&toks(&["grep", "--regexp", "foo", "f.txt"])).expect("grep");
1929 assert_eq!(r.capabilities.len(), 1);
1930 assert!(read_local().admits(&r));
1931
1932 // a space-separated long value (`--max-count 5`) is imprecise — `5` is read as a
1933 // phantom positional — but FAIL-SAFE: still worktree-bounded, admitted at
1934 // read-local, never looser. (Precise handling needs the TOML flag schema.)
1935 let m = resolve(&toks(&["grep", "--max-count", "5", "foo", "f.txt"])).expect("grep");
1936 assert!(read_local().admits(&m), "--max-count 5 is fail-safe (imprecise)");
1937
1938 // --perl-regexp (PCRE2) runs no code — benign like any regex-engine flag; reads read-local.
1939 let pcre = resolve(&toks(&["grep", "--perl-regexp", "foo", "f"])).expect("grep");
1940 assert!(read_local().admits(&pcre), "grep --perl-regexp reads a file, it does not exec");
1941 }
1942
1943 #[test]
1944 fn grep_dash_patterns_are_search_patterns_not_flags() {
1945 // A `--`-prefixed token that is not a recognized grep flag is a SEARCH PATTERN, not
1946 // an unknown flag — grep patterns commonly look like `-->`, `---`, `--foo`. The
1947 // engine must read the file operand at read-local, matching the legacy handler, not
1948 // worst-case it.
1949 for args in [
1950 vec!["grep", "-->", "file.txt"],
1951 vec!["grep", "---", "file.txt"],
1952 vec!["grep", "--some-pattern", "file.txt"],
1953 vec!["grep", "-rn", "-->", "src/"],
1954 vec!["grep", "-i", "-r", "-n", "-->", "src/"],
1955 ] {
1956 let p = resolve(&toks(&args)).expect("grep");
1957 assert!(read_local().admits(&p), "dash-pattern should read-local: {args:?}");
1958 assert!(!inert().admits(&p), "it still reads a file: {args:?}");
1959 }
1960 // but the genuinely-dangerous long (--dereference-recursive, symlink escape) worst-cases
1961 let args = vec!["grep", "--dereference-recursive", "foo", "dir"];
1962 let p = resolve(&toks(&args)).expect("grep");
1963 assert!(!read_local().admits(&p), "dangerous long must worst-case: {args:?}");
1964 // PCRE flags now read-local (PCRE2 execs no code): -P short, --perl-regexp long, -oP combined.
1965 for args in [
1966 vec!["grep", "-P", "foo", "f"],
1967 vec!["grep", "--perl-regexp", "foo", "f"],
1968 vec!["grep", "-oP", "foo", "f"],
1969 ] {
1970 let p = resolve(&toks(&args)).expect("grep");
1971 assert!(read_local().admits(&p), "grep PCRE flag should read-local: {args:?}");
1972 }
1973 }
1974
1975 #[test]
1976 fn grep_stdin_and_standalone_flags() {
1977 assert!(inert().admits(&resolve(&toks(&["grep", "foo"])).expect("grep")), "no file → stdin");
1978 let p = resolve(&toks(&["grep", "-i", "-n", "foo", "file.txt"])).expect("grep");
1979 assert_eq!(p.capabilities.len(), 1, "-i -n standalone; foo pattern; file.txt file");
1980 assert!(read_local().admits(&p));
1981 }
1982
1983 /// The complete resolved capability for a single-capability invocation, with
1984 /// `because` cleared so the assertion is over the **facets** (not the prose).
1985 fn one_cap(cmd: &[&str]) -> Capability {
1986 let p = resolve(&toks(cmd)).expect("resolves");
1987 assert_eq!(p.capabilities.len(), 1, "{cmd:?} is a single-capability invocation");
1988 let mut c = p.capabilities[0].clone();
1989 c.because = String::new();
1990 c
1991 }
1992
1993 /// A read the credential shield cannot clear must SAY so, on the secret axis.
1994 ///
1995 /// Enumerated over the shield's own region nodes plus the unpinnable spellings, because the
1996 /// claim has to survive a new store being declared and a new reader being written. Two halves,
1997 /// and the second is the one that is easy to lose:
1998 ///
1999 /// - a path that NAMES a store (`~/.ssh/id_rsa`) — the shield can check it and it fails;
2000 /// - a path the shield cannot check AT ALL (`$VAR`, an undeclared `$(…)`, an xargs item) —
2001 /// unknowable, so possibly a credential, so refused.
2002 ///
2003 /// Today both also deny by locus, which is exactly why this guard is worth having: the locus
2004 /// cap makes the secret claim invisible in the verdict, so nothing else would notice it going
2005 /// missing — and it is the only thing that keeps `find / | xargs -I{} cat {}` refused once
2006 /// local reads open up (TODO.md).
2007 #[test]
2008 fn a_read_the_shield_cannot_clear_claims_secret() {
2009 let secret_of = |cmd: &str| {
2010 let toks: Vec<Token> = shell_words::split(cmd)
2011 .expect("splits")
2012 .into_iter()
2013 .map(Token::from_raw)
2014 .collect();
2015 resolve(&toks).map(|p| {
2016 p.capabilities.iter().any(|c| c.secret.level == crate::engine::facet::SecretLevel::Reads)
2017 })
2018 };
2019
2020 // Every declared credential store, read by the plainest reader there is.
2021 let mut checked = 0usize;
2022 for path in crate::engine::resolve::regions::declared_region_paths() {
2023 if !crate::engine::resolve::names_credential_store(&path) {
2024 continue;
2025 }
2026 // A node is a SUBTREE (`~/.ssh/`), a SEGMENT (`.ssh`) or an EXACT file
2027 // (`/etc/master.passwd`). Only the first two have anything beneath them; appending to
2028 // the exact form names a path that is not the node and is not shielded.
2029 // QUOTED, because several stores have a space in them (`~/Library/Application
2030 // Support/Firefox/`) and an unquoted probe splits into two tokens, neither of which is
2031 // the node — the guard would pass by never testing them.
2032 let probe = if path.ends_with('/') || !path.contains('/') {
2033 format!("cat '{}/probe'", path.trim_end_matches('/'))
2034 } else {
2035 format!("cat '{path}'")
2036 };
2037 if let Some(claims) = secret_of(&probe) {
2038 checked += 1;
2039 assert!(claims, "`{probe}` reads a declared credential store without claiming secret");
2040 }
2041 }
2042 assert!(checked > 0, "no credential store was probed — the guard is vacuous");
2043
2044 // Paths the shield cannot be consulted about at all.
2045 for cmd in ["cat $SOMEVAR", "cat $(hostname)", "head -c 20 ${HOME}x/$Y"] {
2046 assert_eq!(
2047 secret_of(cmd),
2048 Some(true),
2049 "`{cmd}` names a path the shield cannot check, so it must claim secret"
2050 );
2051 }
2052
2053 // ...and an ordinary, checkable read does NOT — the claim has to discriminate, or it is
2054 // just a second way of spelling "deny everything".
2055 for cmd in ["cat ./README.md", "cat src/lib.rs"] {
2056 assert_eq!(secret_of(cmd), Some(false), "`{cmd}` must not claim a secret read");
2057 }
2058 }
2059
2060 /// Golden profiles: assert **every** facet of the resolved capability for
2061 /// representative invocations. This is the "all facets covered" check (§0) — struct
2062 /// equality means a facet the resolver forgot (left at a wrong default) or set wrong
2063 /// fails the test, per command. When commands carry TOML profiles, the expected
2064 /// profile is derived from the TOML instead of hand-built here.
2065 #[test]
2066 fn golden_profiles_cover_every_facet() {
2067 // echo — the reference `structural` profile: observe, process-scoped, output to
2068 // the model, and every other axis provably zero.
2069 let mut echo = Capability::new(Operation::Observe);
2070 echo.disclosure.audience = DisclosureAudience::LocalProcess;
2071 assert_eq!(one_cap(&["echo", "hi"]), echo, "echo");
2072
2073 // cat of a worktree file — observe · worktree · content-to-model.
2074 let mut cat = Capability::new(Operation::Observe);
2075 cat.locus.local = LocalLocus::Worktree;
2076 cat.disclosure.audience = DisclosureAudience::LocalProcess;
2077 assert_eq!(one_cap(&["cat", "./notes.md"]), cat, "cat ./notes.md");
2078
2079 // cat of a plain home file — home is no longer admitted, so locus rises to machine (deny).
2080 let mut cat_home = cat.clone();
2081 cat_home.locus.local = LocalLocus::Machine;
2082 assert_eq!(one_cap(&["cat", "~/notes.txt"]), cat_home, "cat ~/notes.txt");
2083
2084 // cat of a home CREDENTIAL store: machine locus AND — the part that was missing until
2085 // 2026-08-14 — a `secret · reads` claim. The region carried `reads_secret = true` all along,
2086 // but nothing put it on the capability, so this golden recorded "reading an SSH private key
2087 // claims no secret" and the denial rested entirely on the locus cap. Both facets now, which
2088 // is what lets the locus cap be relaxed without handing over the key.
2089 let mut cat_cred = cat.clone();
2090 cat_cred.locus.local = LocalLocus::Machine;
2091 cat_cred.secret.level = SecretLevel::Reads;
2092 assert_eq!(one_cap(&["cat", "~/.ssh/id_rsa"]), cat_cred, "cat ~/.ssh/id_rsa");
2093
2094 // grep of a worktree file — like cat, bounded to the single searched file.
2095 assert_eq!(one_cap(&["grep", "foo", "file.txt"]), cat, "grep foo file.txt");
2096
2097 // grep -r — the recursive search raises scale to unbounded and nothing else.
2098 let mut grep_r = cat.clone();
2099 grep_r.scale = Scale::Unbounded;
2100 assert_eq!(one_cap(&["grep", "-r", "foo", "src/"]), grep_r, "grep -r foo src/");
2101
2102 // rm — destroy · worktree · effortful; no net/exec/secret.
2103 let mut rm = Capability::new(Operation::Destroy);
2104 rm.locus.local = LocalLocus::Worktree;
2105 rm.reversibility = Reversibility::Effortful;
2106 assert_eq!(one_cap(&["rm", "./x"]), rm, "rm ./x");
2107
2108 // mkdir — create · worktree · trivial · leaves data. A fresh dir is rmdir-removable.
2109 let mut mkdir = Capability::new(Operation::Create);
2110 mkdir.locus.local = LocalLocus::Worktree;
2111 mkdir.reversibility = Reversibility::Trivial;
2112 mkdir.persistence.level = PersistenceLevel::Data;
2113 assert_eq!(one_cap(&["mkdir", "./build"]), mkdir, "mkdir ./build");
2114
2115 // touch — the same create · worktree · trivial · data shape as mkdir.
2116 assert_eq!(one_cap(&["touch", "./new.txt"]), mkdir, "touch ./new.txt");
2117
2118 // cp -n ./a ./b — a guaranteed-non-clobbering copy is TWO capabilities:
2119 // a source read (observe, worktree, NO model disclosure) and a trivial dest create.
2120 let cp = resolve(&toks(&["cp", "-n", "./a", "./b"])).expect("cp");
2121 assert_eq!(cp.capabilities.len(), 2, "cp = source read + dest write");
2122 let mut src = Capability::new(Operation::Observe);
2123 src.locus.local = LocalLocus::Worktree; // disclosure.audience stays `none`: file→file
2124 assert_eq!(clear_because(&cp.capabilities[0]), src, "cp source read");
2125 let mut dst = Capability::new(Operation::Create);
2126 dst.locus.local = LocalLocus::Worktree;
2127 dst.reversibility = Reversibility::Trivial; // -n → cannot overwrite
2128 dst.persistence.level = PersistenceLevel::Data;
2129 assert_eq!(clear_because(&cp.capabilities[1]), dst, "cp -n dest write");
2130
2131 // mv ./a ./b — a relocation: source MUTATE (trivial, transient — the entry leaves)
2132 // + dest CREATE (recoverable overwrite). Contrast cp's source, which is an observe.
2133 let mv = resolve(&toks(&["mv", "./a", "./b"])).expect("mv");
2134 let mut mv_src = Capability::new(Operation::Mutate);
2135 mv_src.locus.local = LocalLocus::Worktree;
2136 mv_src.reversibility = Reversibility::Trivial;
2137 assert_eq!(clear_because(&mv.capabilities[0]), mv_src, "mv source relocation");
2138 let mut mv_dst = Capability::new(Operation::Create);
2139 mv_dst.locus.local = LocalLocus::Worktree;
2140 mv_dst.reversibility = Reversibility::Recoverable;
2141 mv_dst.persistence.level = PersistenceLevel::Data;
2142 assert_eq!(clear_because(&mv.capabilities[1]), mv_dst, "mv dest write");
2143
2144 // ln ./a ./b — target bridged (observe, no model disclosure) + link create (trivial,
2145 // no -f). Same facet shapes as cp -n, the point being ln reuses `observes`.
2146 let ln = resolve(&toks(&["ln", "./a", "./b"])).expect("ln");
2147 let mut ln_tgt = Capability::new(Operation::Observe);
2148 ln_tgt.locus.local = LocalLocus::Worktree;
2149 assert_eq!(clear_because(&ln.capabilities[0]), ln_tgt, "ln target bridge");
2150 let mut ln_link = Capability::new(Operation::Create);
2151 ln_link.locus.local = LocalLocus::Worktree;
2152 ln_link.reversibility = Reversibility::Trivial;
2153 ln_link.persistence.level = PersistenceLevel::Data;
2154 assert_eq!(clear_because(&ln.capabilities[1]), ln_link, "ln link create");
2155 }
2156
2157 fn clear_because(c: &Capability) -> Capability {
2158 let mut c = c.clone();
2159 c.because = String::new();
2160 c
2161 }
2162
2163 #[test]
2164 fn mkdir_creates_in_the_worktree_but_not_beyond_it() {
2165 use crate::engine::bridge::project;
2166 use crate::verdict::{SafetyLevel, Verdict};
2167 // a fresh dir is a trivial-reversibility create → write-local (SafeWrite)
2168 for cmd in [vec!["mkdir", "./build"], vec!["mkdir", "-p", "a/b/c"], vec!["mkdir", "-m", "755", "./x"]] {
2169 assert_eq!(project(&resolve(&toks(&cmd)).expect("mkdir")), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
2170 }
2171 // outside the worktree → denied by locus
2172 for cmd in [vec!["mkdir", "/etc/evil"], vec!["mkdir", "~/newdir"], vec!["mkdir", "$HOME/x"]] {
2173 assert_eq!(project(&resolve(&toks(&cmd)).expect("mkdir")), Verdict::Denied, "{cmd:?}");
2174 }
2175 // a glued valued short (-m755) and its value must not be read as operands
2176 let g = resolve(&toks(&["mkdir", "-m755", "./x"])).expect("mkdir");
2177 assert_eq!(g.capabilities.len(), 1, "-m755 glued: only ./x is an operand");
2178 assert_eq!(g.capabilities[0].locus.local, LocalLocus::Worktree);
2179 // fail-closed on an unknown flag / no operand
2180 assert_eq!(project(&resolve(&toks(&["mkdir", "-Q", "x"])).expect("mkdir")), Verdict::Denied, "unknown flag");
2181 assert_eq!(project(&resolve(&toks(&["mkdir"])).expect("mkdir")), Verdict::Denied, "no operand");
2182 }
2183
2184 #[test]
2185 fn cp_splits_source_and_dest_loci_and_overwrite_gates_the_level() {
2186 use crate::engine::bridge::project;
2187 use crate::verdict::{SafetyLevel, Verdict};
2188
2189 // a copy is a create/overwrite, not a destroy → write-local (SafeWrite), matching
2190 // echo > config.json. Overwriting is recoverable; -n can't clobber (trivial). Both
2191 // write-local — the destroy-vs-create boundary keeps cp below rm.
2192 let plain = resolve(&toks(&["cp", "./a", "./b"])).expect("cp");
2193 assert_eq!(plain.capabilities.last().unwrap().reversibility, Reversibility::Recoverable, "dest overwrite");
2194 assert_eq!(project(&plain), Verdict::Allowed(SafetyLevel::SafeWrite), "cp ./a ./b");
2195 let nc = resolve(&toks(&["cp", "-n", "./a", "./b"])).expect("cp");
2196 assert_eq!(nc.capabilities.last().unwrap().reversibility, Reversibility::Trivial, "-n cannot clobber");
2197 assert_eq!(project(&nc), Verdict::Allowed(SafetyLevel::SafeWrite), "cp -n ./a ./b");
2198
2199 // reading a home/system SOURCE is denied by the source locus — no secret detector,
2200 // just the read locus (cp can't smuggle ~/.ssh/id_rsa into the worktree).
2201 assert_eq!(project(&resolve(&toks(&["cp", "~/.ssh/id_rsa", "./x"])).expect("cp")), Verdict::Denied, "home source");
2202 assert_eq!(project(&resolve(&toks(&["cp", "/etc/shadow", "./x"])).expect("cp")), Verdict::Denied, "system source");
2203 // writing a home/system DEST is denied by the dest locus.
2204 assert_eq!(project(&resolve(&toks(&["cp", "./x", "~/backdoor"])).expect("cp")), Verdict::Denied, "home dest");
2205 assert_eq!(project(&resolve(&toks(&["cp", "./x", "/etc/cron.d/x"])).expect("cp")), Verdict::Denied, "system dest");
2206
2207 // -t DIR makes every positional a source; the dir is the dest. All three spellings
2208 // (separate, --long=, and glued short) must parse the same way.
2209 for form in [
2210 vec!["cp", "-t", "./dest", "./a", "./b"],
2211 vec!["cp", "--target-directory=./dest", "./a", "./b"],
2212 vec!["cp", "-t./dest", "./a", "./b"], // glued short — previously worst-cased
2213 ] {
2214 let t = resolve(&toks(&form)).expect("cp -t");
2215 assert_eq!(t.capabilities.len(), 3, "{form:?}: 2 sources + 1 dest");
2216 assert_eq!(project(&t), Verdict::Allowed(SafetyLevel::SafeWrite), "{form:?}");
2217 }
2218 // a glued -t pointing outside the worktree is still denied by the dest locus.
2219 assert_eq!(project(&resolve(&toks(&["cp", "-t/etc", "./a"])).expect("cp")), Verdict::Denied, "cp -t/etc");
2220
2221 // optional-argument longs (--backup[=X], --preserve[=X]) must NOT swallow the
2222 // source operand: bare and glued forms both leave ./a a source and ./b the dest.
2223 for form in [
2224 vec!["cp", "--backup", "./a", "./b"],
2225 vec!["cp", "--preserve", "./a", "./b"],
2226 vec!["cp", "--preserve=mode", "./a", "./b"],
2227 ] {
2228 let c = resolve(&toks(&form)).expect("cp");
2229 assert_eq!(c.capabilities.len(), 2, "{form:?}: source read + dest write");
2230 assert_eq!(project(&c), Verdict::Allowed(SafetyLevel::SafeWrite), "{form:?}");
2231 }
2232
2233 // recursion raises scale to unbounded; a lone operand / unknown flag worst-cases.
2234 assert_eq!(resolve(&toks(&["cp", "-r", "./a", "./b"])).expect("cp").capabilities[0].scale, Scale::Unbounded);
2235 assert_eq!(project(&resolve(&toks(&["cp", "./only"])).expect("cp")), Verdict::Denied, "no dest");
2236 assert_eq!(project(&resolve(&toks(&["cp", "-Q", "./a", "./b"])).expect("cp")), Verdict::Denied, "unknown flag");
2237 // -t naming a dest with NO source operands is a usage error → fail closed (not a lone,
2238 // benign dest write).
2239 assert_eq!(project(&resolve(&toks(&["cp", "-t", "./dest"])).expect("cp")), Verdict::Denied, "-t no source");
2240 }
2241
2242 #[test]
2243 fn mv_relocates_within_the_worktree_and_gates_both_loci() {
2244 use crate::engine::bridge::project;
2245 use crate::verdict::{SafetyLevel, Verdict};
2246
2247 // a move within the worktree is a mutate (source) + create (dest), both trivial/
2248 // recoverable → write-local, NOT developer. Unlike rm, a move relocates, not destroys.
2249 let m = resolve(&toks(&["mv", "./a", "./b"])).expect("mv");
2250 assert_eq!(m.capabilities[0].operation, Operation::Mutate, "source is a relocation, not a destroy");
2251 assert_eq!(m.capabilities[0].reversibility, Reversibility::Trivial, "mv back");
2252 assert_eq!(project(&m), Verdict::Allowed(SafetyLevel::SafeWrite), "mv ./a ./b");
2253
2254 // both loci are gated as writes: source-out and dest-out both deny.
2255 assert_eq!(project(&resolve(&toks(&["mv", "~/.ssh/id_rsa", "./x"])).expect("mv")), Verdict::Denied, "source in home");
2256 assert_eq!(project(&resolve(&toks(&["mv", "./x", "~/exfil"])).expect("mv")), Verdict::Denied, "dest in home");
2257 // moving a worktree-TRUSTED file mutates .git → denied, even though cp of it is
2258 // allowed (cp only READS .git/config; the dest write puts cp at SafeWrite).
2259 assert_eq!(project(&resolve(&toks(&["mv", ".git/config", "./x"])).expect("mv")), Verdict::Denied, "mv .git/config");
2260 assert_eq!(project(&resolve(&toks(&["cp", ".git/config", "./x"])).expect("cp")), Verdict::Allowed(SafetyLevel::SafeWrite), "cp .git/config reads");
2261
2262 // The relocate source gates at its REBIND face, not its read face. safe-chains' own config
2263 // READS at worktree-trusted but rebinds at system-integrity (un-grantable, and above what
2264 // any level below yolo admits): `mv`ing it REMOVES it, so the removal must gate at the
2265 // rebind face; a `cp` of it only READS (worktree-trusted). Both deny by verdict, so assert
2266 // the source LOCUS to pin the face — this is the case a read-face relocate would fail open
2267 // on, and the value pins that the face is the strict one rather than plain `machine`.
2268 let cfg = "~/.config/safe-chains.toml";
2269 assert_eq!(
2270 resolve(&toks(&["mv", cfg, "./x"])).expect("mv").capabilities[0].locus.local,
2271 LocalLocus::SystemIntegrity,
2272 "mv source removal gates at the REBIND face",
2273 );
2274 assert_eq!(
2275 resolve(&toks(&["cp", cfg, "./x"])).expect("cp").capabilities[0].locus.local,
2276 LocalLocus::WorktreeTrusted,
2277 "cp source read gates at the READ face",
2278 );
2279
2280 // -t DIR and glued forms; fail-closed on unknown flag / lone operand.
2281 let t = resolve(&toks(&["mv", "-t", "./dest", "./a", "./b"])).expect("mv -t");
2282 assert_eq!(t.capabilities.len(), 3, "2 sources + 1 dest");
2283 assert_eq!(project(&resolve(&toks(&["mv", "./only"])).expect("mv")), Verdict::Denied, "no dest");
2284 assert_eq!(project(&resolve(&toks(&["mv", "-Q", "./a", "./b"])).expect("mv")), Verdict::Denied, "unknown flag");
2285 }
2286
2287 #[test]
2288 fn ln_is_cp_by_reference_and_gates_the_target_locus() {
2289 use crate::engine::bridge::project;
2290 use crate::verdict::{SafetyLevel, Verdict};
2291
2292 // a worktree link (hard or symbolic) is target-read + link-create → write-local.
2293 for cmd in [vec!["ln", "./a", "./b"], vec!["ln", "-s", "./target", "./link"]] {
2294 let p = resolve(&toks(&cmd)).expect("ln");
2295 assert_eq!(p.capabilities[0].operation, Operation::Observe, "target is a bridged read");
2296 assert_eq!(project(&p), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
2297 }
2298 // the cp-bypass is closed: linking a SECRET/unreadable TARGET denies on the target
2299 // locus, exactly as `cp` of it would (a link would otherwise alias the secret in).
2300 assert_eq!(project(&resolve(&toks(&["ln", "~/.ssh/id_rsa", "./x"])).expect("ln")), Verdict::Denied, "hard link to home credential");
2301 assert_eq!(project(&resolve(&toks(&["ln", "-s", "/etc/shadow", "./x"])).expect("ln")), Verdict::Denied, "symlink to secret");
2302 // the retreat: linking to a NON-workspace target denies on the target locus (as cp would).
2303 assert_eq!(project(&resolve(&toks(&["ln", "-s", "/etc/hosts", "./x"])).expect("ln")), Verdict::Denied, "symlink to system path");
2304 // writing the LINK outside the worktree denies on the link locus.
2305 assert_eq!(project(&resolve(&toks(&["ln", "-s", "./a", "~/evil"])).expect("ln")), Verdict::Denied, "link into home");
2306 // -t DIR, lone operand, unknown flag.
2307 assert_eq!(resolve(&toks(&["ln", "-t", "./dir", "./a", "./b"])).expect("ln -t").capabilities.len(), 3);
2308 assert_eq!(project(&resolve(&toks(&["ln", "./only"])).expect("ln")), Verdict::Denied, "no link name");
2309 assert_eq!(project(&resolve(&toks(&["ln", "-Q", "./a", "./b"])).expect("ln")), Verdict::Denied, "unknown flag");
2310 // -f (a clobber flag PRESENT) flips the link-create from the no-clobber default
2311 // (`trivial`) to `recoverable` — still write-local. Exercises the `clobber_flags`-present
2312 // branch of the transfer arm, the inverse of cp/mv's `no_clobber_flags`.
2313 let forced = resolve(&toks(&["ln", "-f", "./a", "./b"])).expect("ln -f");
2314 assert_eq!(project(&forced), Verdict::Allowed(SafetyLevel::SafeWrite), "ln -f worktree link");
2315 assert_eq!(forced.capabilities.last().unwrap().reversibility, Reversibility::Recoverable, "ln -f overwrites → recoverable");
2316 assert_eq!(
2317 resolve(&toks(&["ln", "./a", "./b"])).expect("ln").capabilities.last().unwrap().reversibility,
2318 Reversibility::Trivial,
2319 "ln default no-clobber → trivial",
2320 );
2321 }
2322
2323 #[test]
2324 fn dd_parses_key_value_operands_and_gates_both_sides() {
2325 use crate::engine::bridge::project;
2326 use crate::verdict::{SafetyLevel, Verdict};
2327
2328 // a worktree-to-worktree copy → write-local; params (bs/count/conv) are ignored.
2329 assert_eq!(
2330 project(&resolve(&toks(&["dd", "if=./a", "of=./b", "bs=1M", "count=10"])).expect("dd")),
2331 Verdict::Allowed(SafetyLevel::SafeWrite),
2332 "dd worktree copy",
2333 );
2334 // input from stdout (no of=) discloses the input content to the model, like cat.
2335 assert_eq!(project(&resolve(&toks(&["dd", "if=./notes"])).expect("dd")), Verdict::Allowed(SafetyLevel::SafeRead), "dd to stdout");
2336 assert_eq!(project(&resolve(&toks(&["dd"])).expect("dd")), Verdict::Allowed(SafetyLevel::Inert), "bare dd is stdin→stdout");
2337
2338 // both sides gated by locus: a home INPUT or a device/home OUTPUT denies.
2339 for cmd in [
2340 vec!["dd", "if=~/.ssh/id_rsa", "of=./x"], // read a home secret
2341 vec!["dd", "if=./x", "of=/dev/rdisk0"], // write a raw device (disk wipe)
2342 vec!["dd", "if=./x", "of=/dev/sda"],
2343 vec!["dd", "if=./x", "of=~/backup"], // write into home
2344 vec!["dd", "if=~/.ssh/id_rsa"], // home secret to stdout (→ model)
2345 ] {
2346 assert_eq!(project(&resolve(&toks(&cmd)).expect("dd")), Verdict::Denied, "{cmd:?}");
2347 }
2348 // fail-closed: a non key=value operand, or an unknown key, worst-cases.
2349 assert_eq!(project(&resolve(&toks(&["dd", "./file"])).expect("dd")), Verdict::Denied, "positional operand");
2350 assert_eq!(project(&resolve(&toks(&["dd", "exec=evil", "of=./x"])).expect("dd")), Verdict::Denied, "unknown key");
2351 }
2352
2353 #[test]
2354 fn tar_parses_dashless_bundles_and_splits_by_mode() {
2355 use crate::engine::bridge::project;
2356 use crate::verdict::{SafetyLevel, Verdict};
2357
2358 // dashless `czf` and dashed `-czf` and the long form all parse the same: a create is
2359 // members-read + archive-write → write-local for a worktree backup.
2360 for cmd in [
2361 vec!["tar", "czf", "backup.tar", "./src"],
2362 vec!["tar", "-czf", "backup.tar", "./src"],
2363 vec!["tar", "--create", "--file=backup.tar", "./src"],
2364 ] {
2365 assert_eq!(project(&resolve(&toks(&cmd)).expect("tar")), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
2366 }
2367 // list reads the archive → read-local.
2368 assert_eq!(project(&resolve(&toks(&["tar", "tzf", "backup.tar"])).expect("tar")), Verdict::Allowed(SafetyLevel::SafeRead), "list");
2369
2370 // the bundler-exfil case (golden-set): a home member denies on the member locus,
2371 // whether the archive goes to stdout or a file.
2372 assert_eq!(project(&resolve(&toks(&["tar", "czf", "-", "~/.ssh"])).expect("tar")), Verdict::Denied, "bundle secret to stdout");
2373 assert_eq!(project(&resolve(&toks(&["tar", "czf", "out.tar", "~/.aws"])).expect("tar")), Verdict::Denied, "bundle home member");
2374 // a home/system ARCHIVE denies on the archive write locus.
2375 assert_eq!(project(&resolve(&toks(&["tar", "cf", "~/backup.tar", "./src"])).expect("tar")), Verdict::Denied, "archive into home");
2376
2377 // extract is archive-controlled (..-escapable) → worst-case, even for a benign archive.
2378 assert_eq!(project(&resolve(&toks(&["tar", "xzf", "release.tar"])).expect("tar")), Verdict::Denied, "extract");
2379 // `tar cf backup.tar` with no members creates an empty archive — a benign worktree
2380 // write, so SafeWrite (not a fail-closed case).
2381 assert_eq!(project(&resolve(&toks(&["tar", "cf", "backup.tar"])).expect("tar")), Verdict::Allowed(SafetyLevel::SafeWrite), "empty archive");
2382 // fail-closed: an unmodeled value option (-C), no mode, an empty profile, a bad letter.
2383 assert_eq!(project(&resolve(&toks(&["tar", "-C", "/etc", "xf", "a.tar"])).expect("tar")), Verdict::Denied, "-C unmodeled");
2384 assert_eq!(project(&resolve(&toks(&["tar", "c"])).expect("tar")), Verdict::Denied, "create to stdout, no members");
2385 assert_eq!(project(&resolve(&toks(&["tar", "zf", "backup.tar"])).expect("tar")), Verdict::Denied, "no mode letter");
2386 }
2387
2388 /// perl's two gates are independent and BOTH are required: the identifier allowlist decides
2389 /// whether the one-liner is inert, locus decides whether the operands may be touched. The
2390 /// second was missing — `perl -pe 's/a/b/' /etc/shadow` auto-approved, because the handler
2391 /// judged only the code — so the read cases below are the regression, and the `-i` cases are
2392 /// the capability the missing gate had been standing in for.
2393 /// Parse `line` and ask what a `$( … )` around it would evaluate to.
2394 #[cfg(test)]
2395 fn sub_locus(line: &str) -> Option<LocalLocus> {
2396 let script = crate::cst::parse(line).expect("parses");
2397 match substitution_claim(&script)? {
2398 SubClaim::Locus(l) => Some(l),
2399 // An atom names no locus, so these callers — which ask "which rung does this value
2400 // point at" — correctly see nothing.
2401 SubClaim::Atom => None,
2402 }
2403 }
2404
2405 /// No output claim survives `--help` / `--version`, for EVERY command that declares one.
2406 ///
2407 /// Enumerated over the registry rather than spot-checked on seq, because the failure is a
2408 /// property of what those flags DO — replace the command's data output with prose — and so it
2409 /// applies to every claim, including ones added later. The prose routinely carries paths and
2410 /// URLs: GNU `seq --help` prints `<https://www.gnu.org/software/coreutils/>` under an `atom`
2411 /// claim asserting no word holds a separator.
2412 ///
2413 /// Missed by hand-probing because macOS ships BSD seq, whose help is terse and slash-free —
2414 /// the local install disagreed with the upstream the claim is written against.
2415 #[test]
2416 fn no_output_claim_survives_a_help_or_version_flag() {
2417 let mut probed = 0usize;
2418 for (scope, spec) in crate::registry::output_claims() {
2419 // A claim gated on a required flag is only ever live WITH it, so the probe has to carry
2420 // it — otherwise the assertion holds for the boring reason and guards nothing.
2421 let scope = match spec.requires.first() {
2422 Some(required) => format!("{scope} {required}"),
2423 None => scope,
2424 };
2425 for flag in ["--help", "--version"] {
2426 let line = format!("{scope} {flag}");
2427 let Some(script) = crate::cst::parse(&line) else { continue };
2428 probed += 1;
2429 assert!(
2430 substitution_claim(&script).is_none(),
2431 "`{line}` still carries an output claim, but --help/--version print prose \
2432 rather than the command's data, so the claim does not describe it"
2433 );
2434 }
2435 }
2436 assert!(probed > 0, "nothing declares an output claim; this guard would be vacuous");
2437 }
2438
2439 /// A sub-scoped claim must survive every TRUSTED spelling of its command, and no other.
2440 ///
2441 /// The walker keys on the registry name, so it has to be handed the CANONICALIZED one — the
2442 /// same key the command-level lookup gets. Given the raw first word instead, `/usr/bin/git diff
2443 /// --name-only` silently lost the claim that bare `git` kept: one operation, two spellings, two
2444 /// answers, which is the false-deny class the flag-form guards exist to kill.
2445 ///
2446 /// The other half is that this must NOT extend trust: `./git` is a worktree binary that may not
2447 /// be git at all, and `trusted_command_path` is what keeps it claimless.
2448 #[test]
2449 fn a_sub_claim_follows_every_trusted_spelling_of_its_command() {
2450 let bare = sub_locus("git diff --name-only");
2451 assert!(bare.is_some(), "precondition: bare `git diff --name-only` should carry a claim");
2452 for spelling in ["/usr/bin/git", "/opt/homebrew/bin/git"] {
2453 assert_eq!(
2454 sub_locus(&format!("{spelling} diff --name-only")),
2455 bare,
2456 "`{spelling} diff --name-only` disagrees with the bare spelling",
2457 );
2458 }
2459 for untrusted in ["./git", "/tmp/git", "../git"] {
2460 assert_eq!(
2461 sub_locus(&format!("{untrusted} diff --name-only")),
2462 None,
2463 "`{untrusted}` is not a trusted path to git and must earn no output claim",
2464 );
2465 }
2466 }
2467
2468 /// A claim gated on `requires` must be DEAD without its flag. `git diff` prints a patch and
2469 /// `jj diff` a diff; only `--name-only` turns either into a list of paths, so the ungated
2470 /// invocation must stay unpinnable. Without this, `requires` could be silently ignored and the
2471 /// claim would widen every invocation of the sub.
2472 #[test]
2473 fn a_required_flag_is_necessary_for_its_claim() {
2474 let mut probed = 0usize;
2475 for (scope, spec) in crate::registry::output_claims() {
2476 if spec.requires.is_empty() {
2477 continue;
2478 }
2479 probed += 1;
2480 let Some(script) = crate::cst::parse(&scope) else { continue };
2481 assert_eq!(
2482 substitution_claim(&script).map(|_| ()),
2483 None,
2484 "`{scope}` carries an output claim without any of {:?}, which the declaration says \
2485 are required for the output to be paths at all",
2486 spec.requires,
2487 );
2488 // ...and LIVE with it, or the declaration describes nothing.
2489 for required in &spec.requires {
2490 let line = format!("{scope} {required}");
2491 let Some(script) = crate::cst::parse(&line) else { continue };
2492 assert!(
2493 substitution_claim(&script).is_some(),
2494 "`{line}` carries no output claim, but `{required}` is declared as one of the \
2495 flags that makes the claim hold"
2496 );
2497 }
2498 }
2499 assert!(probed > 0, "nothing declares `requires`; this guard would be vacuous");
2500 }
2501
2502 /// Fail-closed, enumerated over the REGISTRY: every `[command.output]` claim is probed on a HOT
2503 /// root, and must never report a locus below what reading that root reports. This is the
2504 /// fail-open the whole feature risks — a missed search root means the substitution is admitted
2505 /// at worktree while the command actually reaches `/etc`. The `match` is EXHAUSTIVE, so a new
2506 /// `OutputLocus` variant must state how it is probed or the build breaks.
2507 ///
2508 /// Red→green: drop the glued-value branch from `candidate_roots` and
2509 /// `fd --search-path=/etc x` stops reporting machine.
2510 #[test]
2511 fn every_output_claim_is_bounded_by_its_roots() {
2512 use crate::registry::types::OutputLocus;
2513
2514 let mut probed = 0usize;
2515 for (scope, spec) in crate::registry::output_claims() {
2516 probed += 1;
2517 // A `requires`-gated claim is only live with its flag, so every probe below carries it.
2518 // `name` is therefore the invocation PREFIX, not just a command name.
2519 let name = match spec.requires.first() {
2520 Some(required) => format!("{scope} {required}"),
2521 None => scope.clone(),
2522 };
2523 let name = name.as_str();
2524 match spec.locus_from {
2525 // An `atom` claim is that no output word can contain a separator, so the check is
2526 // the claim: run the command's OWN examples and read what they would print. A
2527 // command whose examples emit a `/` is mis-declared, and the consequence is not
2528 // subtle — the confinement layer treats the value as unable to leave its
2529 // component, so a separator would let it walk anywhere the prefix can reach.
2530 //
2531 // Enumerated over the registry rather than spot-checked, because the next command
2532 // to declare `atom` gets this for free, which is the only way a data-driven claim
2533 // stays honest as the data grows.
2534 // An `atom` claim cannot be checked the way the others can. The rest are probed by
2535 // asking the resolver where a HOT root lands, but "no output word contains a
2536 // separator" is a fact about the TOOL, and the only mechanical way to confirm it
2537 // would be to run the command — which a unit test must not do for arbitrary
2538 // registry entries.
2539 //
2540 // So this is a REVIEW gate, not a proof: the claim has to be argued per command,
2541 // and a new declaration fails here until someone does that and adds it. What makes
2542 // it worth having is the failure mode it guards — an atom is treated as unable to
2543 // leave its path component, so a tool that CAN emit a `/` would let the value walk
2544 // anywhere its prefix reaches. `seq`'s argument is in its TOML: numbers only, with
2545 // the three flags that inject caller text (`-s`, `-t`, `-f`) in `invalidated_by`.
2546 //
2547 // The soundness of the confinement ITSELF — that a separator-free value beside
2548 // literal text cannot escape — is proved separately, by
2549 // `a_flanked_atom_never_moves_where_the_write_lands`.
2550 OutputLocus::Atom => {
2551 const ARGUED: &[&str] = &["seq"];
2552 assert!(
2553 ARGUED.contains(&name),
2554 "command '{name}' declares `locus_from = \"atom\"`, which asserts that no \
2555 word it prints can contain a separator. That cannot be checked here \
2556 without running the command, so it must be argued in the command's TOML \
2557 (what it prints, and which flags reshape it into `invalidated_by`) and \
2558 then listed in ARGUED."
2559 );
2560 }
2561 OutputLocus::Operands => {
2562 // `~` is here as a named case, not just inside HOT_PATHS, because it is the
2563 // spelling that actually got through: it carries neither `/` nor `.`, so the
2564 // path-SHAPE test skipped it and `cat $(fd pat ~)` swept the home directory
2565 // while reporting worktree.
2566 let hot_roots: Vec<&str> =
2567 HOT_PATHS.iter().copied().chain(["~", "~/.ssh"]).collect();
2568 for hot in hot_roots {
2569 // Every spelling a root can arrive in: bare operand, separated flag value,
2570 // glued long value, glued short value. Missing any is the fail-open.
2571 for line in [
2572 format!("{name} pat {hot}"),
2573 format!("{name} --base-directory {hot} pat"),
2574 format!("{name} --search-path={hot} pat"),
2575 format!("{name} -E{hot} pat"),
2576 ] {
2577 let got = sub_locus(&line);
2578 let want = read_locus(hot);
2579 assert!(
2580 got.is_none_or(|l| l >= want),
2581 "`{line}`: reported {got:?}, but reading {hot} is {want:?}",
2582 );
2583 }
2584 }
2585 // A substitution in a root slot is unknowable — no claim.
2586 assert_eq!(sub_locus(&format!("{name} pat $(hostname)")), None, "{name}: nested sub");
2587 }
2588 // Its output is the cwd, which takes no root operand; the guard that matters is
2589 // that it does not somehow report BELOW the cwd's own locus.
2590 OutputLocus::Cwd => {
2591 assert_eq!(sub_locus(name), Some(read_locus(".")), "{name}: bare");
2592 }
2593 // A filter only filters while it has no file operand — given one it prints that
2594 // file's CONTENTS, which are not paths and must void the claim.
2595 OutputLocus::Stdin => {
2596 for hot in HOT_PATHS {
2597 assert_eq!(
2598 sub_locus(&format!("{name} {hot}")),
2599 None,
2600 "{name}: a file operand makes it print contents, not paths",
2601 );
2602 }
2603 }
2604 }
2605 // Every flag the command declares as invalidating must actually void the claim.
2606 for flag in &spec.invalidated_by {
2607 let line = format!("{name} {flag} pat");
2608 assert_eq!(sub_locus(&line), None, "`{line}`: {flag} is declared invalidating");
2609 }
2610 }
2611 assert!(probed > 0, "no command declares [command.output] — the guard is vacuous");
2612 // The enumeration must reach SUB-scoped claims, not just command-scoped ones. Without this
2613 // the extension is silently self-defeating: a walker that stopped at the top level would
2614 // make every `[command.sub.output]` skip the probes above and the guard would still be
2615 // green, reporting coverage it does not have.
2616 assert!(
2617 crate::registry::output_claims().iter().any(|(scope, _)| scope.contains(' ')),
2618 "no sub-scoped output claim was enumerated, so `[command.sub.output]` is unprobed",
2619 );
2620 }
2621
2622 /// Enumerated over the REGISTRY: a flag declared `valued` on `[command.output]` means "this
2623 /// value is not a path", and BOTH spellings must agree. Handling only the separated form denied
2624 /// `head --lines=5` while `head -n 5` passed — one operation, two spellings, two answers, which
2625 /// is the false-deny class the flag-form equivalence guards exist to kill.
2626 #[test]
2627 fn output_valued_flags_agree_across_spellings() {
2628 use crate::registry::types::OutputLocus;
2629 let mut checked = 0usize;
2630 for (scope, spec) in crate::registry::output_claims() {
2631 // As above: a `requires`-gated claim is only live with its flag, so the probe carries it.
2632 let name = match spec.requires.first() {
2633 Some(required) => format!("{scope} {required}"),
2634 None => scope.clone(),
2635 };
2636 let name = name.as_str();
2637 for flag in &spec.valued {
2638 // An invalidating flag voids the claim by design, so it is not a spelling case.
2639 if spec.invalidated_by.contains(flag) {
2640 continue;
2641 }
2642 // Two things are load-bearing about the probe shape, and without EITHER the
2643 // guard silently passes a broken skip:
2644 // - a PRODUCER stage, because a lone `stdin` command walks back off the end of
2645 // the pipeline and reports `None` whether or not it saw a file operand, hiding
2646 // the difference entirely;
2647 // - a TRAILING OPERAND, because a glued form that over-skips (swallowing the
2648 // next argument as if it were a separated value) is indistinguishable from a
2649 // correct one until there is a next argument to lose.
2650 // Together they expose the over-skip as a file operand going missing — which for
2651 // a `stdin` claim is a fail-open: contents get classified as if they were paths.
2652 let producer = match spec.locus_from {
2653 OutputLocus::Stdin => "fd a app/ | ",
2654 _ => "",
2655 };
2656 for tail in ["", " /etc/hosts"] {
2657 let separated = sub_locus(&format!("{producer}{name} {flag} 5{tail}"));
2658 let glued = sub_locus(&format!("{producer}{name} {flag}=5{tail}"));
2659 assert_eq!(
2660 separated, glued,
2661 "{name} {flag} (tail {tail:?}): separated {separated:?}, glued {glued:?}",
2662 );
2663 checked += 1;
2664 }
2665 }
2666 }
2667 assert!(checked > 0, "no output claim declares a valued flag — the guard is vacuous");
2668 }
2669
2670 /// The default is unpinnable. A command that has NOT been researched for its output locus must
2671 /// keep the opaque sentinel, so the feature can only ever widen through a deliberate
2672 /// declaration — never by a command happening to look read-only.
2673 #[test]
2674 fn undeclared_commands_get_no_output_claim() {
2675 // `echo` is the load-bearing case: as safe as a command gets, and its output is whatever
2676 // the caller typed. If it ever acquires a claim, `cat $(echo /etc/shadow)` opens up.
2677 for line in ["echo /etc/shadow", "hostname", "cat ./f", "ls", "git rev-parse --show-toplevel"] {
2678 assert_eq!(sub_locus(line), None, "`{line}` must have no output claim");
2679 }
2680 assert!(!crate::is_safe_command("cat $(echo /etc/shadow)"), "echo must not bound its output");
2681 }
2682
2683 #[test]
2684 fn perl_i_worktree_vs_system() {
2685 use crate::engine::bridge::project;
2686 use crate::verdict::{SafetyLevel, Verdict};
2687
2688 // No -i: the operands are content reads, gated by READ locus.
2689 let read = resolve(&toks(&["perl", "-pe", "s/x/y/", "./foo"])).expect("perl");
2690 assert_eq!(read.capabilities[0].operation, Operation::Observe, "no -i → read");
2691 assert_eq!(project(&read), Verdict::Allowed(SafetyLevel::SafeRead), "perl read");
2692
2693 // -i flips them to in-place MUTATES, admitted only in the worktree.
2694 let edit = resolve(&toks(&["perl", "-pi", "-e", "s/x/y/", "./foo"])).expect("perl");
2695 assert_eq!(edit.capabilities[0].operation, Operation::Mutate, "-i → in-place write");
2696 assert_eq!(project(&edit), Verdict::Allowed(SafetyLevel::SafeWrite), "perl -i worktree");
2697 let glued = resolve(&toks(&["perl", "-i.bak", "-pe", "s/x/y/", "./foo"])).expect("perl");
2698 assert_eq!(glued.capabilities[0].operation, Operation::Mutate, "-i.bak is still in-place");
2699
2700 // THE REGRESSION: an inert one-liner does not license the operand. Reads above the
2701 // worktree deny, exactly as `cat` and `sed` already did.
2702 for cmd in [
2703 vec!["perl", "-pe", "s/a/b/", "/etc/shadow"],
2704 vec!["perl", "-ne", "print", "~/.ssh/id_rsa"],
2705 vec!["perl", "-pe", "s/a/b/", "/etc/passwd"],
2706 vec!["perl", "-pe", "s/a/b/", "$CONFIG"], // unpinnable
2707 vec!["perl", "-pi", "-e", "s/a/b/", "/etc/hosts"],
2708 vec!["perl", "-pi", "-e", "s/a/b/", "~/.bashrc"],
2709 vec!["perl", "-pi", "-e", "s/a/b/", "../outside"],
2710 ] {
2711 assert_eq!(project(&resolve(&toks(&cmd)).expect("perl")), Verdict::Denied, "{cmd:?} must deny");
2712 }
2713
2714 // Opaque code is refused whatever the operand: no `-e` means the first operand is a script
2715 // file we cannot read, and a failed identifier gate means the one-liner left the vocabulary.
2716 for cmd in [
2717 vec!["perl", "./script.pl"],
2718 vec!["perl", "-n", "./file.txt"],
2719 vec!["perl", "-e", "system(\"rm -rf /\")", "./foo"],
2720 vec!["perl", "-pie", "s/a/b/", "./foo"], // ambiguous suffix spelling — unmodeled
2721 ] {
2722 assert_eq!(project(&resolve(&toks(&cmd)).expect("perl")), Verdict::Denied, "{cmd:?} must deny");
2723 }
2724
2725 // A worktree-scoped sweep is bounded, not single — scored honestly, still admitted.
2726 let glob = resolve(&toks(&["perl", "-pi", "-e", "s/a/b/", "*"])).expect("perl");
2727 assert_eq!(glob.capabilities[0].scale, Scale::Bounded, "a glob is a bounded blast radius");
2728 assert_eq!(project(&glob), Verdict::Allowed(SafetyLevel::SafeWrite), "perl -i * (worktree)");
2729 }
2730
2731 #[test]
2732 fn sed_i_flips_read_to_write_and_locus_stops_system_wide_damage() {
2733 use crate::engine::bridge::project;
2734 use crate::verdict::{SafetyLevel, Verdict};
2735
2736 // -i turns the file operands from reads into in-place MUTATES.
2737 let read = resolve(&toks(&["sed", "s/x/y/", "./foo"])).expect("sed");
2738 assert_eq!(read.capabilities[0].operation, Operation::Observe, "no -i → read");
2739 assert_eq!(project(&read), Verdict::Allowed(SafetyLevel::SafeRead), "sed read");
2740 let edit = resolve(&toks(&["sed", "-i", "s/x/y/", "./foo"])).expect("sed");
2741 assert_eq!(edit.capabilities[0].operation, Operation::Mutate, "-i → in-place write");
2742 assert_eq!(project(&edit), Verdict::Allowed(SafetyLevel::SafeWrite), "sed -i worktree");
2743
2744 // THE CONCERN: a stray system-wide `sed -i` is stopped by LOCUS — a system, home, or
2745 // unpinnable target denies whatever the scale. Damage needs a target above the
2746 // worktree, and every such target is denied.
2747 for cmd in [
2748 vec!["sed", "-i", "s/a/b/", "/etc/passwd"],
2749 vec!["sed", "-i", "s/a/b/", "/etc/hosts"],
2750 vec!["sed", "-i", "s/a/b/", "~/.bashrc"],
2751 vec!["sed", "-i", "s/a/b/", "$CONFIG"], // unpinnable
2752 vec!["sed", "-i", "s/a/b/", "../outside"], // escapes the worktree
2753 vec!["sed", "-i", "-e", "s/a/b/", "/etc/x"], // -e script, system file
2754 ] {
2755 assert_eq!(project(&resolve(&toks(&cmd)).expect("sed")), Verdict::Denied, "{cmd:?} must deny");
2756 }
2757
2758 // A worktree-scoped sweep IS allowed — bounded, recoverable, your own project files.
2759 // The glob/multi-operand blast radius is scored as `bounded`, still write-local.
2760 let glob = resolve(&toks(&["sed", "-i", "s/a/b/", "*"])).expect("sed");
2761 assert_eq!(glob.capabilities[0].scale, Scale::Bounded, "a glob is a bounded blast radius");
2762 assert_eq!(project(&glob), Verdict::Allowed(SafetyLevel::SafeWrite), "sed -i * (worktree)");
2763 assert_eq!(project(&resolve(&toks(&["sed", "-i", "s/a/b/", "a", "b", "c"])).expect("sed")), Verdict::Allowed(SafetyLevel::SafeWrite), "multi-file");
2764
2765 // -i.bak (optional glued suffix) still parses as in-place.
2766 assert_eq!(project(&resolve(&toks(&["sed", "-i.bak", "s/a/b/", "./foo"])).expect("sed")), Verdict::Allowed(SafetyLevel::SafeWrite), "-i.bak");
2767 // -f runs a script file we can't inspect (its e/w/r commands are invisible) → denied, like
2768 // `awk -f`, `bash script.sh`, mlr `--load`.
2769 assert_eq!(project(&resolve(&toks(&["sed", "-f", "script.sed", "./foo"])).expect("sed")), Verdict::Denied, "-f script file unanalyzable");
2770 // a home file read (no -i) still denies by locus, like cat.
2771 assert_eq!(project(&resolve(&toks(&["sed", "s/a/b/", "~/.ssh/id_rsa"])).expect("sed")), Verdict::Denied, "read home secret");
2772 assert_eq!(project(&resolve(&toks(&["sed", "-Q", "./foo"])).expect("sed")), Verdict::Denied, "unknown flag");
2773 }
2774
2775 #[test]
2776 fn sed_exec_command_is_worst_cased_at_parity_with_legacy() {
2777 use crate::engine::bridge::project;
2778 use crate::verdict::Verdict;
2779 // The `e` command/modifier executes text as a shell command (RCE). The resolver must
2780 // worst-case it — flag parsing alone treated the script as opaque and let it through.
2781 for cmd in [
2782 vec!["sed", "s/test/touch tmp/e", "file"], // s///e modifier
2783 vec!["sed", "-e", "s/x/cmd/e", "file"], // via -e
2784 vec!["sed", "s/x/cmd/ew", "file"], // e flag BEFORE the greedy w flag
2785 vec!["sed", "1e", "file"], // address + e
2786 vec!["sed", "e"], // bare e
2787 vec!["sed", "-e", "e"],
2788 vec!["sed", "1e reboot", "file"], // address + e WITH a command argument
2789 vec!["sed", "p;e id", "file"], // e after a `;` separator
2790 ] {
2791 assert_eq!(project(&resolve(&toks(&cmd)).expect("sed")), Verdict::Denied, "{cmd:?}: exec must deny");
2792 }
2793 // `s/x/cmd/we` is NOT here: `w` is greedy-to-EOL, so `we` writes to a file named `e` (a
2794 // local SafeWrite), not w-then-e exec. `sed '1e reboot'` — the former residual gap — is now
2795 // caught by the sed sub-parser (`scan_sed`).
2796 }
2797
2798 /// HP-19 #1 (engine): `classify_locus` now resolves relative paths against the ambient
2799 /// cwd/root. With no context it falls back to relative-is-worktree (status quo); under a
2800 /// `cd /etc` context the same operands resolve to `/etc/*` and deny.
2801 #[test]
2802 fn classify_locus_resolves_relative_operands_against_the_cwd_context() {
2803 use crate::engine::bridge::project;
2804 use crate::pathctx::PathCtx;
2805 use crate::verdict::{SafetyLevel, Verdict};
2806
2807 // No context → relative is worktree (fallback), and a sweeping edit is write-local.
2808 for p in ["*", "passwd", "config"] {
2809 assert_eq!(classify_locus(p), LocalLocus::Worktree, "{p}: no ctx → worktree");
2810 }
2811 assert_eq!(project(&resolve(&toks(&["sed", "-i", "s/a/b/", "*"])).expect("sed")), Verdict::Allowed(SafetyLevel::SafeWrite), "no ctx: sed -i *");
2812
2813 // Context says the shell is in /etc → relative operands are /etc/* → machine → deny.
2814 let _g = crate::pathctx::enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
2815 for p in ["*", "hosts", "config", "cron.d"] {
2816 assert_eq!(classify_locus(p), LocalLocus::Machine, "{p}: cwd=/etc → machine");
2817 }
2818 // /etc/passwd is the identity substrate: its WRITE face worst-cases to system-integrity
2819 // (above machine → above local-admin), even reached as a relative operand from cwd=/etc.
2820 assert_eq!(classify_locus("passwd"), LocalLocus::SystemIntegrity, "passwd: cwd=/etc → system-integrity");
2821 assert_eq!(project(&resolve(&toks(&["sed", "-i", "s/a/b/", "*"])).expect("sed")), Verdict::Denied, "cwd=/etc: sed -i * denied");
2822 assert_eq!(project(&resolve(&toks(&["dd", "if=./x", "of=passwd"])).expect("dd")), Verdict::Denied, "cwd=/etc: dd of=passwd denied");
2823 assert_eq!(project(&resolve(&toks(&["cp", "./payload", "config"])).expect("cp")), Verdict::Denied, "cwd=/etc: cp denied");
2824 }
2825
2826 #[test]
2827 fn touch_creates_in_the_worktree_and_gates_the_reference_path() {
2828 use crate::engine::bridge::project;
2829 use crate::verdict::{SafetyLevel, Verdict};
2830 for cmd in [
2831 vec!["touch", "./new.txt"],
2832 vec!["touch", "-c", "existing"],
2833 vec!["touch", "-r", "ref.txt", "./out"], // worktree reference: a read + a create, both worktree
2834 vec!["touch", "-d", "-1 day", "./out"], // -d takes a DATE literal (not a path), dash-leading value
2835 ] {
2836 assert_eq!(project(&resolve(&toks(&cmd)).expect("touch")), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
2837 }
2838 // `-r REF` reads REF's timestamp — a path-flag gated by REF's locus. A worktree ref is a
2839 // worktree read (allowed, 2 caps), but an out-of-workspace reference DENIES (it would
2840 // otherwise be an mtime/existence oracle for arbitrary paths).
2841 let p = resolve(&toks(&["touch", "-r", "ref.txt", "./out"])).expect("touch");
2842 assert_eq!(p.capabilities.len(), 2, "./out create + ref.txt read");
2843 assert!(p.capabilities.iter().any(|c| c.operation == Operation::Observe), "the -r reference is a read");
2844 assert_eq!(project(&resolve(&toks(&["touch", "-r", "~/.bashrc", "./out"])).expect("touch")), Verdict::Denied, "home reference");
2845 assert_eq!(project(&resolve(&toks(&["touch", "-r", "/etc/shadow", "./out"])).expect("touch")), Verdict::Denied, "system reference");
2846 assert_eq!(project(&resolve(&toks(&["touch", "--reference=/etc/shadow", "./out"])).expect("touch")), Verdict::Denied, "long glued reference");
2847 assert_eq!(project(&resolve(&toks(&["touch", "--reference", "/etc/shadow", "./out"])).expect("touch")), Verdict::Denied, "long spaced reference");
2848 // -d's dash-leading date literal is NOT a path and is NOT gated.
2849 assert_eq!(project(&resolve(&toks(&["touch", "-d", "-1 day", "/tmp/../etc/x"])).expect("touch")), Verdict::Denied, "operand still gated");
2850 // beyond the worktree, and fail-closed cases
2851 assert_eq!(project(&resolve(&toks(&["touch", "/etc/x"])).expect("touch")), Verdict::Denied, "system path");
2852 assert_eq!(project(&resolve(&toks(&["touch", "-Z", "x"])).expect("touch")), Verdict::Denied, "unknown flag");
2853 assert_eq!(project(&resolve(&toks(&["touch"])).expect("touch")), Verdict::Denied, "no operand");
2854 }
2855
2856 #[test]
2857 fn worst_case_is_denied_even_by_a_permissive_yolo_shaped_level() {
2858 use crate::engine::level::{Clause, Level, OrdBound};
2859 // a yolo-shaped level: allow anything local up to `machine`, minus a destroy corner
2860 let yolo = Level::new("yolo-ish")
2861 .allowing(Clause {
2862 local_locus: Some(OrdBound::at_most(LocalLocus::Machine)),
2863 ..Default::default()
2864 })
2865 .denying(Clause {
2866 operation: Some(vec![Operation::Destroy]),
2867 reversibility: Some(OrdBound::at_least(Reversibility::Irreversible)),
2868 ..Default::default()
2869 });
2870 let wc = Profile::of(vec![Capability::worst("test")]);
2871 assert!(!yolo.admits(&wc), "worst_case (locus=kernel) exceeds even a machine-capped allow");
2872 }
2873
2874 #[test]
2875 fn rm_within_the_worktree_projects_to_developer_but_beyond_it_denies() {
2876 use crate::engine::bridge::project;
2877 use crate::verdict::{SafetyLevel, Verdict};
2878 // `developer` admits destroy WITHIN the worktree (golden-set decision 2), even
2879 // recursive/effortful; it maps to the legacy SafeWrite ceiling.
2880 for cmd in [
2881 vec!["rm", "./stale.log"],
2882 vec!["rm", "-rf", "./node_modules"],
2883 vec!["rm", "a", "b", "c"],
2884 vec!["rm", "--interactive=always", "./x"], // optional-arg long: must not worst-case
2885 ] {
2886 let p = resolve(&toks(&cmd)).expect("rm resolves");
2887 assert!(p.capabilities.iter().all(|c| c.operation == Operation::Destroy), "{cmd:?} destroys");
2888 assert_eq!(project(&p), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?} → developer");
2889 }
2890 // Deletion that reaches beyond the worktree (home/system) is above `developer`,
2891 // denied by locus — no clause admits a machine/user-scoped destroy.
2892 for cmd in [vec!["rm", "-rf", "/"], vec!["rm", "-rf", "~/notes"], vec!["rm", "/etc/hosts"]] {
2893 assert_eq!(project(&resolve(&toks(&cmd)).expect("rm")), Verdict::Denied, "{cmd:?} beyond worktree");
2894 }
2895 }
2896
2897 /// End-to-end: `rm -rf /` resolves to the `destroy · irreversible · unbounded` corner and
2898 /// is the one thing even a maximally-permissive yolo refuses — by facet, not by name.
2899 /// Everything one facet away stays yolo-admitted.
2900 #[test]
2901 fn rm_rf_root_is_the_one_thing_even_yolo_denies() {
2902 let yolo = level("yolo");
2903 let root = resolve(&toks(&["rm", "-rf", "/"])).expect("rm");
2904 assert_eq!(root.capabilities[0].reversibility, Reversibility::Irreversible, "rm -rf / is irreversible");
2905 assert_eq!(root.capabilities[0].scale, Scale::Unbounded);
2906 assert!(!yolo.admits(&root), "rm -rf / denied even at yolo");
2907 assert!(!yolo.admits(&resolve(&toks(&["rm", "-rf", "~/notes"])).expect("rm")), "rm -rf ~ likewise");
2908 // adjacent-by-one-facet stays yolo-allowed:
2909 assert!(yolo.admits(&resolve(&toks(&["rm", "-rf", "./node_modules"])).expect("rm")), "recoverable worktree");
2910 assert!(yolo.admits(&resolve(&toks(&["rm", "/etc/hosts"])).expect("rm")), "single (bounded) system delete");
2911 }
2912
2913 /// Phase 1 end-to-end: a subcommand tagged `profile = "<archetype>"` resolves (through the
2914 /// nested `<resource> <action>` grammar) to that archetype's exact static capability, so its
2915 /// verdict is DERIVED from facets, not hand-marked. Untagged sibling subs leave the engine
2916 /// abstaining (→ legacy).
2917 #[test]
2918 fn a_subcommand_profile_resolves_to_its_archetype() {
2919 let p = resolve(&toks(&["koyeb", "apps", "delete", "myapp"])).expect("koyeb apps delete resolves");
2920 assert_eq!(p.capabilities.len(), 1);
2921 assert_eq!(
2922 &p.capabilities[0],
2923 crate::engine::archetype::archetype("remote-destroy-recoverable").unwrap(),
2924 "the sub resolves to its declared archetype's capability",
2925 );
2926 // a differently-tagged action gets a different archetype
2927 let create = resolve(&toks(&["koyeb", "apps", "create", "myapp"])).expect("resolves");
2928 assert_eq!(create.capabilities[0].operation, Operation::Create);
2929 // an untagged read sub: no profile, no command behavior → the engine abstains (legacy decides)
2930 assert!(resolve(&toks(&["koyeb", "apps", "list"])).is_none(), "untagged sub → engine abstains");
2931 }
2932
2933 /// Per-flag escalation (Phase 1 layer): a dangerous flag ADDS a capability to the sub's profile,
2934 /// and the level algebra takes the max — so a benign base + a destructive flag lands at the
2935 /// flag's tier. `git push` is vcs-sync (network-admin); `git push --force` adds
2936 /// remote-destroy-irreversible and escalates past it, to yolo.
2937 #[test]
2938 fn an_escalating_flag_adds_a_capability_and_raises_the_tier() {
2939 let destroy = crate::engine::archetype::archetype("remote-destroy-irreversible").unwrap();
2940 // The vcs-sync base now carries the destination's provenance (exposure §4): `origin` and the
2941 // bare `--force` form (default remote) are both `established`.
2942 let vcs_sync = {
2943 let mut c = crate::engine::archetype::archetype("vcs-sync").unwrap().clone();
2944 c.locus.provenance = Provenance::Established;
2945 c
2946 };
2947
2948 let base = resolve(&toks(&["git", "push", "origin", "main"])).expect("git push resolves");
2949 assert_eq!(base.capabilities, vec![vcs_sync.clone()], "base is vcs-sync, established destination");
2950
2951 let forced = resolve(&toks(&["git", "push", "--force"])).expect("resolves");
2952 assert_eq!(forced.capabilities.len(), 2);
2953 assert!(forced.capabilities.contains(&vcs_sync) && forced.capabilities.contains(destroy),
2954 "--force ADDS remote-destroy-irreversible to the vcs-sync base");
2955
2956 // the escalation MATTERS at the level layer: network-admin admits the base but not the
2957 // forced push; the flag pushed it up to yolo.
2958 let network_admin = level("network-admin");
2959 assert!(network_admin.admits(&base), "git push is network-admin");
2960 assert!(!network_admin.admits(&forced), "git push --force escalated past network-admin");
2961 assert!(level("yolo").admits(&forced), "and lands at yolo");
2962
2963 // the -f short form escalates identically
2964 assert_eq!(resolve(&toks(&["git", "push", "-f"])).unwrap().capabilities.len(), 2);
2965 }
2966
2967 /// Destination-trust (exposure §4): `git push`'s send TARGET is classified onto
2968 /// `locus.provenance`, and an `ext::` command-transport worst-cases as RCE. The one resolver
2969 /// that makes the `locus.provenance` facet actually bind to a command.
2970 #[test]
2971 fn git_push_destination_provenance_is_classified() {
2972 use crate::engine::bridge::project;
2973 use crate::verdict::Verdict;
2974
2975 let prov = |cmd: &[&str]| resolve(&toks(cmd)).expect("push resolves").capabilities[0].locus.provenance;
2976
2977 // bare (configured default) and a bare remote NAME → established (a prior deliberate act).
2978 assert_eq!(prov(&["git", "push"]), Provenance::Established, "bare push = default remote");
2979 assert_eq!(prov(&["git", "push", "origin", "main"]), Provenance::Established, "remote name");
2980 // a flag before the target doesn't hide it.
2981 assert_eq!(prov(&["git", "push", "--force", "origin"]), Provenance::Established, "flag then name");
2982 // spelled inline → literal (visible but injectable): URL, scp-path, filesystem path.
2983 assert_eq!(prov(&["git", "push", "https://h/x.git", "main"]), Provenance::Literal, "url");
2984 assert_eq!(prov(&["git", "push", "git@h:x.git"]), Provenance::Literal, "scp-style");
2985 assert_eq!(prov(&["git", "push", "/srv/mirror.git"]), Provenance::Literal, "path");
2986 // a variable / substitution → opaque (unreviewable).
2987 assert_eq!(prov(&["git", "push", "$REMOTE"]), Provenance::Opaque, "variable");
2988
2989 // network-admin admits established + literal, refuses opaque; the ext:: transport is RCE.
2990 let net = level("network-admin");
2991 assert!(net.admits(&resolve(&toks(&["git", "push", "origin"])).unwrap()), "established at network-admin");
2992 assert!(net.admits(&resolve(&toks(&["git", "push", "https://h/x.git"])).unwrap()), "literal URL at network-admin");
2993 assert!(!net.admits(&resolve(&toks(&["git", "push", "$REMOTE"])).unwrap()), "opaque above network-admin");
2994 // ext::<cmd> runs a local command — worst-cased, denied below yolo.
2995 assert_eq!(project(&resolve(&toks(&["git", "push", "ext::sh"])).unwrap()), Verdict::Denied, "ext:: is RCE");
2996 assert!(!net.admits(&resolve(&toks(&["git", "push", "ext::sh"])).unwrap()), "ext:: not at network-admin");
2997
2998 // `--repo=<dest>` OVERRIDES the positional (the fail-open the review found: `--repo=ext::sh`
2999 // slipping past a benign `origin`). Glued and space forms; a bare remote name still allows.
3000 assert_eq!(project(&resolve(&toks(&["git", "push", "--repo=ext::sh", "origin"])).unwrap()), Verdict::Denied, "--repo=ext:: is RCE");
3001 assert!(!net.admits(&resolve(&toks(&["git", "push", "--repo", "$VAR", "origin"])).unwrap()), "--repo $VAR is opaque");
3002 assert_eq!(prov(&["git", "push", "--repo=https://h/x.git", "main"]), Provenance::Literal, "--repo URL is literal");
3003 assert!(net.admits(&resolve(&toks(&["git", "push", "--repo=upstream", "main"])).unwrap()), "--repo=<remote name> is established");
3004 }
3005
3006 /// The `data-export` resolver: a bulk remote export (`supabase db dump`) is a read that
3007 /// auto-approves to stdout, but its OUTPUT-FILE form (`-f path`) adds a SECOND, path-gated local
3008 /// write — a dump to the worktree stays local (SafeWrite) while one to a system path gates on
3009 /// locus (denied), and the glued short `-f/path` spelling can't slip that gate. The unbounded
3010 /// `scale` records the volume without itself gating the read. See `behavioral-taxonomy-exposure.md`.
3011 #[test]
3012 fn data_export_gates_its_output_file() {
3013 use crate::engine::bridge::project;
3014 use crate::verdict::{SafetyLevel, Verdict};
3015
3016 // to stdout: the bulk remote read alone — one capability, auto-approves as a read.
3017 let stdout = resolve(&toks(&["supabase", "db", "dump", "--data-only"])).expect("dump resolves");
3018 assert_eq!(stdout.capabilities.len(), 1, "stdout dump = the remote read only");
3019 assert_eq!(stdout.capabilities[0].scale, Scale::Unbounded, "a dump records its volume");
3020 assert_eq!(project(&stdout), Verdict::Allowed(SafetyLevel::SafeRead), "bulk read auto-approves");
3021
3022 // -f into the worktree: read + a worktree write → still auto-approves (SafeWrite).
3023 for cmd in [
3024 vec!["supabase", "db", "dump", "-f", "dump.sql"],
3025 vec!["supabase", "db", "dump", "--file=dump.sql", "--data-only"],
3026 ] {
3027 let p = resolve(&toks(&cmd)).expect("dump resolves");
3028 assert_eq!(p.capabilities.len(), 2, "{cmd:?}: the remote read + a local write");
3029 assert_eq!(project(&p), Verdict::Allowed(SafetyLevel::SafeWrite), "{cmd:?}");
3030 }
3031
3032 // -f onto a system path: the write gates on locus → denied, in every spelling — space,
3033 // glued `=`, AND the glued short `-f/path` that mustn't be a bypass.
3034 for cmd in [
3035 vec!["supabase", "db", "dump", "-f", "/etc/passwd"],
3036 vec!["supabase", "db", "dump", "--file=/etc/passwd"],
3037 vec!["supabase", "db", "dump", "-f/etc/passwd"],
3038 ] {
3039 assert_eq!(project(&resolve(&toks(&cmd)).expect("resolves")), Verdict::Denied, "{cmd:?} writes a system path");
3040 }
3041 }
3042
3043 /// `sudo`/`doas` elevate the wrapped command's AUTHORITY — the resolver that finally gives
3044 /// `local-admin` something to admit. `sudo <safe cmd>` = a root op (above every user-authority
3045 /// band); `sudo rm -rf /` stays the catastrophe corner; `-u`/`-i` and unknown options fail up.
3046 #[test]
3047 fn sudo_elevates_the_wrapped_commands_authority() {
3048 use crate::engine::bridge::project;
3049 use crate::verdict::Verdict;
3050 let (dev, local, net, yolo) = (level("developer"), level("local-admin"), level("network-admin"), level("yolo"));
3051
3052 // sudo cat ./notes — a ROOT read. Authority lifts to root; every band below local-admin pins
3053 // authority=user, so it lands at local-admin (and yolo), NOT developer/network-admin.
3054 let read = resolve(&toks(&["sudo", "cat", "./notes.md"])).expect("sudo cat resolves");
3055 assert_eq!(read.capabilities[0].authority, Authority::Root, "authority lifted to root");
3056 assert!(!dev.admits(&read) && !net.admits(&read), "a root op is above the user-authority bands");
3057 assert!(local.admits(&read) && yolo.admits(&read), "a root read is local-admin");
3058
3059 // benign flag clusters are skipped without losing the inner command (space + glued values too).
3060 assert_eq!(resolve(&toks(&["sudo", "-EH", "cat", "./x"])).unwrap().capabilities[0].authority, Authority::Root);
3061 assert_eq!(resolve(&toks(&["sudo", "-n", "-p", "pw", "cat", "./x"])).unwrap().capabilities[0].authority, Authority::Root);
3062
3063 // bumping authority does NOT rescue the catastrophe corner.
3064 assert_eq!(project(&resolve(&toks(&["sudo", "rm", "-rf", "/"])).unwrap()), Verdict::Denied, "sudo rm -rf / denied everywhere");
3065
3066 // -u (run as another user) → other-user authority → yolo-only (identity confusion tops the ladder).
3067 let other = resolve(&toks(&["sudo", "-u", "bob", "cat", "./x"])).expect("sudo -u resolves");
3068 assert_eq!(other.capabilities[0].authority, Authority::OtherUser, "-u = run as other user");
3069 assert!(!local.admits(&other) && yolo.admits(&other), "other-user is yolo-only");
3070 assert_eq!(resolve(&toks(&["sudo", "-ubob", "cat", "./x"])).unwrap().capabilities[0].authority, Authority::OtherUser, "glued -ubob");
3071
3072 // -i / -s / -e launch a root shell or editor → arbitrary code, worst-cased.
3073 assert_eq!(project(&resolve(&toks(&["sudo", "-i"])).unwrap()), Verdict::Denied, "sudo -i is a root shell");
3074 assert!(!local.admits(&resolve(&toks(&["sudo", "-s", "bash"])).unwrap()), "root shell not local-admin");
3075
3076 // an UNRECOGNIZED sudo option fails closed.
3077 assert_eq!(project(&resolve(&toks(&["sudo", "--nonsense", "cat", "./x"])).unwrap()), Verdict::Denied, "unknown option worst-cases");
3078
3079 // an UNRESOLVED inner → None, so the caller's legacy fallback denies (never looser than bare).
3080 assert!(resolve(&toks(&["sudo", "totallyunknowncmd", "x"])).is_none(), "unresolved inner → legacy denies");
3081 // `sudo` with no command → None (legacy decides).
3082 assert!(resolve(&toks(&["sudo", "-v"])).is_none(), "no inner command");
3083
3084 // doas is the same wrapper.
3085 assert_eq!(resolve(&toks(&["doas", "cat", "./x"])).unwrap().capabilities[0].authority, Authority::Root);
3086
3087 // A valued short flag at end-of-input has no next-token value: `i` overshot the slice and
3088 // PANICKED (fail-open hook crash, found by the parse fuzzer). Now clamps → no inner → None.
3089 assert!(resolve(&toks(&["doas", "-r"])).is_none(), "doas -r must not panic");
3090 assert!(resolve(&toks(&["sudo", "-u"])).is_none(), "sudo -u must not panic");
3091 assert_eq!(crate::command_verdict("doas -r"), Verdict::Denied, "doas -r denied, not crashed");
3092
3093 // NEVER LOOSER: at the default band every `sudo …` is denied (root authority is auto-approved
3094 // by NO level below local-admin), exactly like the legacy classifier, which denies sudo whole.
3095 for cmd in ["sudo cat ./notes.md", "sudo rm -rf ./build", "sudo -EH cat ./x", "sudo -u bob ls"] {
3096 assert_eq!(crate::command_verdict(cmd), Verdict::Denied, "`{cmd}` must not auto-approve at the default band");
3097 }
3098 }
3099
3100 /// systemctl — the first REAL command user of the `local-privileged` archetype. Read subs stay
3101 /// SafeRead (any band); service-management subs land at local-admin; and `sudo systemctl restart`
3102 /// (previously fail-closed, since systemctl's inner sub was unmodeled) now resolves to local-admin.
3103 #[test]
3104 fn systemctl_service_management_is_local_admin() {
3105 use crate::verdict::Verdict;
3106 let (dev, local, net, yolo) = (level("developer"), level("local-admin"), level("network-admin"), level("yolo"));
3107
3108 // service management → local-privileged: local-admin and yolo admit; developer/network-admin don't.
3109 for sub in ["restart", "start", "stop", "enable", "disable", "mask", "daemon-reload", "kill"] {
3110 let p = resolve(&toks(&["systemctl", sub, "nginx"])).unwrap_or_else(|| panic!("systemctl {sub} resolves"));
3111 assert!(!dev.admits(&p) && !net.admits(&p), "systemctl {sub} is above developer/network-admin");
3112 assert!(local.admits(&p) && yolo.admits(&p), "systemctl {sub} is local-admin");
3113 }
3114 // reads stay auto-approvable (SafeRead), a power-state sub denies by omission (not modeled).
3115 assert!(crate::command_verdict("systemctl status nginx").is_allowed(), "status reads");
3116 assert_eq!(crate::command_verdict("systemctl reboot"), Verdict::Denied, "reboot omitted → denied");
3117
3118 // the fail-closed case is fixed: `sudo systemctl restart` resolves the inner sub (already root).
3119 let sudo_restart = resolve(&toks(&["sudo", "systemctl", "restart", "nginx"])).expect("resolves");
3120 assert!(local.admits(&sudo_restart), "sudo systemctl restart is local-admin");
3121 assert_eq!(crate::command_verdict("sudo systemctl restart nginx"), Verdict::Denied, "still not auto-approved at default");
3122 }
3123
3124 /// The flag-conditional-archetype resolver (the `when_absent` mechanism, npm exemplar):
3125 /// `npm ci --ignore-scripts` is a PINNED, scripts-off install → `local-install-pinned`
3126 /// (developer). Dropping `--ignore-scripts` escalates it to `supply-chain-build` (yolo — runs
3127 /// fetched code at install). `npm install`/`i` are FLOATING → always `supply-chain-build`. This
3128 /// is the pattern the package-manager fan-out replicates.
3129 #[test]
3130 fn npm_install_is_classified_by_pinning_and_scripts_off() {
3131 let (dev, yolo) = (level("developer"), level("yolo"));
3132
3133 // pinned (ci) + scripts-off → developer.
3134 let safe = resolve(&toks(&["npm", "ci", "--ignore-scripts"])).expect("npm ci --ignore-scripts");
3135 assert!(dev.admits(&safe), "pinned, scripts-off ci is developer");
3136
3137 // pinned but scripts-ON → the --ignore-scripts ABSENCE escalates to supply-chain-build → yolo.
3138 let scripts_on = resolve(&toks(&["npm", "ci"])).expect("npm ci");
3139 assert!(!dev.admits(&scripts_on), "ci without --ignore-scripts runs fetched code → above developer");
3140 assert!(yolo.admits(&scripts_on), "and lands at yolo");
3141
3142 // floating installs → supply-chain-build regardless of flags.
3143 for c in [&["npm", "install"][..], &["npm", "install", "left-pad"], &["npm", "i", "react"], &["npm", "install", "--ignore-scripts"]] {
3144 let p = resolve(&toks(c)).unwrap_or_else(|| panic!("{c:?} resolves"));
3145 assert!(!dev.admits(&p) && yolo.admits(&p), "{c:?}: floating install → supply-chain (yolo)");
3146 }
3147 }
3148
3149 #[test]
3150 fn rm_flag_and_operand_fail_closed() {
3151 use crate::engine::bridge::project;
3152 use crate::verdict::Verdict;
3153 for cmd in [
3154 vec!["rm", "--no-preserve-root", "-rf", "/"], // enables rm -rf / → must worst-case
3155 vec!["rm", "-Z", "x"], // unknown flag
3156 vec!["rm"], // no operand (usage error)
3157 vec!["./rm", "x"], // basename spoof
3158 ] {
3159 assert_eq!(project(&resolve(&toks(&cmd)).expect("resolves")), Verdict::Denied, "{cmd:?}");
3160 }
3161 }
3162
3163 #[test]
3164 fn rm_scale_and_force_semantics() {
3165 let cap = |cmd: &[&str]| resolve(&toks(cmd)).expect("rm").capabilities[0].clone();
3166 assert_eq!(cap(&["rm", "./x"]).scale, Scale::Single);
3167 assert_eq!(cap(&["rm", "a", "b"]).scale, Scale::Bounded, "multiple operands");
3168 assert_eq!(cap(&["rm", "*.log"]).scale, Scale::Bounded, "a glob");
3169 assert_eq!(cap(&["rm", "-r", "./dir"]).scale, Scale::Unbounded, "recursive");
3170 // -f only suppresses prompts — it does NOT raise reversibility for rm
3171 assert_eq!(cap(&["rm", "./x"]).reversibility, Reversibility::Effortful);
3172 assert_eq!(cap(&["rm", "-f", "./x"]).reversibility, Reversibility::Effortful, "-f is not a raiser");
3173 }
3174
3175 #[test]
3176 fn a_resolvable_name_from_a_non_standard_path_worst_cases() {
3177 // ./cat, /tmp/cat, ~/bin/grep may be impostors → worst-case, not certified safe
3178 for cmd in [vec!["./cat", "x"], vec!["/tmp/cat", "x"], vec!["~/bin/grep", "foo", "f"]] {
3179 let p = resolve(&toks(&cmd)).expect("resolvable name");
3180 assert!(!read_local().admits(&p), "{cmd:?} from a non-standard path must worst-case");
3181 }
3182 // bare names and standard bin paths resolve normally
3183 assert!(read_local().admits(&resolve(&toks(&["cat", "./notes.md"])).expect("cat")));
3184 assert!(read_local().admits(&resolve(&toks(&["/usr/bin/cat", "./notes.md"])).expect("cat")));
3185 // a non-resolvable command from any path → None (the engine doesn't claim it)
3186 assert!(resolve(&toks(&["/tmp/mytool", "x"])).is_none());
3187 }
3188
3189 #[test]
3190 fn unrecognized_flags_worst_case_fail_closed() {
3191 for cmd in [
3192 vec!["cat", "-Z", "./x"],
3193 vec!["cat", "--wat", "./x"],
3194 vec!["grep", "-Q", "foo", "f"], // unknown grep short char (-Z is benign: --null)
3195 vec!["grep", "-R", "foo", "dir"], // -R follows symlinks → escapes locus (M2)
3196 ] {
3197 let p = resolve(&toks(&cmd)).expect("resolver");
3198 assert!(!inert().admits(&p) && !read_local().admits(&p), "{cmd:?} must worst-case");
3199 }
3200 // recognized-benign flags still resolve normally
3201 assert!(read_local().admits(&resolve(&toks(&["cat", "-nA", "./x"])).expect("cat")));
3202 assert!(read_local().admits(&resolve(&toks(&["grep", "-rin", "foo", "src/"])).expect("grep")));
3203 }
3204
3205 use proptest::prelude::*;
3206
3207 /// The content-transfer commands: every one moves/bridges content between a source and
3208 /// a destination operand, so BOTH roles must be locus-gated. Extend this list as
3209 /// `install`/`dd`/`rsync`/`tar` land — a resolver that forgets to gate a role then fails
3210 /// the property below (the `ln` cp-bypass class, §HP re: capability laundering).
3211 const TRANSFER_CMDS: &[&str] = &["cp", "mv", "ln"];
3212
3213 /// A sensitive path that must never be laundered through a transfer command, in any
3214 /// role. Covers each locus rung above the worktree AND the two unpinnable markers.
3215 const HOT_PATHS: &[&str] = &["/etc/shadow", "~/.ssh/id_rsa", "$SECRET", "../out", "~/.aws"];
3216
3217 proptest! {
3218 /// No capability laundering: a hot path in EITHER operand role of a transfer command
3219 /// denies — you can neither pull a secret in (`cp ~/.ssh/id_rsa ./x`) nor push one
3220 /// out (`cp ./x /etc/cron.d/y`). This is the STRICT property that catches an ignored
3221 /// operand; plain locus-monotonicity does not, because ignoring a role leaves the
3222 /// verdict unchanged, and unchanged is "not looser".
3223 #[test]
3224 fn transfer_commands_gate_both_operand_roles(
3225 cmd in prop::sample::select(TRANSFER_CMDS),
3226 hot in prop::sample::select(HOT_PATHS),
3227 ) {
3228 use crate::engine::bridge::project;
3229 use crate::verdict::Verdict;
3230 let hot_source = resolve(&toks(&[cmd, hot, "./safe"])).expect("resolves");
3231 prop_assert_eq!(project(&hot_source), Verdict::Denied, "{} hot SOURCE ({})", cmd, hot);
3232 let hot_dest = resolve(&toks(&[cmd, "./safe", hot])).expect("resolves");
3233 prop_assert_eq!(project(&hot_dest), Verdict::Denied, "{} hot DEST ({})", cmd, hot);
3234 }
3235
3236 /// The sudo/doas flag walk must never panic (a panic in the resolver is a fail-OPEN hook
3237 /// crash) nor depend on evaluation order, for ANY flag salad — crucially a valued short flag
3238 /// at end-of-input (`doas -r`, `sudo -u`), which consumes a "next token" that isn't there and
3239 /// pushed `i` one past the end. That `&tokens[i..]` out-of-range is what the parse fuzzer hit
3240 /// on `doas -r`; uniform command sampling never lands on this resolver often enough to find it.
3241 #[test]
3242 fn sudo_family_flag_walk_never_panics(
3243 head in prop::sample::select(vec!["sudo", "doas"]),
3244 args in prop::collection::vec(
3245 prop_oneof![
3246 Just("-u".to_string()), Just("-r".to_string()), Just("-g".to_string()),
3247 Just("-i".to_string()), Just("-EH".to_string()), Just("-uEH".to_string()),
3248 Just("-uroot".to_string()), Just("--".to_string()), Just("-".to_string()),
3249 Just("root".to_string()), Just("cat".to_string()), Just("./x".to_string()),
3250 "-[a-zA-Z]{1,4}",
3251 ],
3252 0..6,
3253 ),
3254 ) {
3255 let parts: Vec<&str> =
3256 std::iter::once(head).chain(args.iter().map(String::as_str)).collect();
3257 let a = resolve(&toks(&parts)).is_some();
3258 let b = resolve(&toks(&parts)).is_some();
3259 prop_assert_eq!(a, b, "nondeterministic verdict for {:?}", parts);
3260 }
3261 }
3262
3263 /// The exact roster of commands classified by `[command.behavior]`. Pinning it turns a
3264 /// DROPPED or typo'd behavior block into a test failure: `TomlCommand` deliberately lacks
3265 /// `deny_unknown_fields` (it must tolerate `[[trusted]]`), so a mistyped top-level key
3266 /// (`behaviour = …`) is silently dropped and the command reverts to its PERMISSIVE legacy
3267 /// fallback — a fail-open the enumeration guards can't see (they `continue` on `None`). This
3268 /// roster is that missing tripwire, and the guards below derive their non-vacuity floors from
3269 /// it so the floors track reality. Update deliberately when porting a command. `echo` is a
3270 /// none-role printer; `dd`/`tar`/`sed` are hook commands; `grep` is a hook + pattern-then-read;
3271 /// the other 10 are the plain positional coreutils.
3272 const EXPECTED_BEHAVIOR_COMMANDS: &[&str] = &[
3273 "cat", "cp", "dd", "echo", "grep", "head", "ln", "mkdir", "mv", "perl", "rm", "rmdir",
3274 "sed", "tail", "tar", "touch", "wc",
3275 ];
3276
3277 /// The behavior roster is exactly `EXPECTED_BEHAVIOR_COMMANDS` — no command silently lost its
3278 /// `[command.behavior]` (fail-open) and none was added without being pinned. Red→green: delete
3279 /// one command's behavior block and this fails.
3280 #[test]
3281 fn behavior_command_roster_is_pinned() {
3282 use std::collections::BTreeSet;
3283 let actual: BTreeSet<&str> = crate::registry::toml_command_names()
3284 .into_iter()
3285 .filter(|n| crate::registry::command_behavior(n).is_some())
3286 .collect();
3287 let expected: BTreeSet<&str> = EXPECTED_BEHAVIOR_COMMANDS.iter().copied().collect();
3288 assert_eq!(
3289 actual, expected,
3290 "behavior-command roster drifted — a [command.behavior] block was added, dropped, or \
3291 typo'd. A dropped block silently reverts the command to its fail-open legacy path."
3292 );
3293 }
3294
3295 /// Hot-path probes for a `[command.behavior]` command, keyed on its declared operand role
3296 /// (the parallel of `probes` for the `Operands` enum). A `@` in a slot is the hot path.
3297 fn behavior_probes(cmd: &str, role: crate::registry::types::PositionalRole, hot: &str) -> Vec<Vec<String>> {
3298 use crate::registry::types::PositionalRole;
3299 let inv = |slots: &[&str]| -> Vec<String> {
3300 std::iter::once(cmd.to_string()).chain(slots.iter().map(|s| s.replace('@', hot))).collect()
3301 };
3302 match role {
3303 PositionalRole::None => vec![],
3304 PositionalRole::Read | PositionalRole::Write => vec![inv(&["@"])],
3305 PositionalRole::PatternThenRead => vec![inv(&["PATTERN", "@"])],
3306 PositionalRole::Transfer => vec![inv(&["@", "./safe"]), inv(&["./safe", "@"])],
3307 }
3308 }
3309
3310 /// Hot-path probes for a HOOK command, whose irregular operand syntax `behavior_probes`
3311 /// (positional roles) can't express — dd's `key=value`, tar's dashless mode bundles, sed's
3312 /// script. The `match` is EXHAUSTIVE, so a new `BehaviorHook` variant must declare its probe
3313 /// rows here or the build breaks — restoring the "new entry covered automatically" property the
3314 /// deleted `every_touched_path_operand_is_gated` had via `Operands::Custom`. `@` = the hot slot.
3315 fn hook_probes(hook: crate::registry::types::BehaviorHook, cmd: &str, hot: &str) -> Vec<Vec<String>> {
3316 use crate::registry::types::BehaviorHook;
3317 let inv = |slots: &[&str]| -> Vec<String> {
3318 std::iter::once(cmd.to_string()).chain(slots.iter().map(|s| s.replace('@', hot))).collect()
3319 };
3320 match hook {
3321 // grep is pattern-then-read → already probed by `behavior_probes`; no extra rows.
3322 BehaviorHook::Grep => vec![],
3323 BehaviorHook::Dd => vec![inv(&["if=@", "of=./safe"]), inv(&["if=./safe", "of=@"])],
3324 BehaviorHook::Tar => vec![inv(&["cf", "./s.tar", "@"]), inv(&["cf", "@", "./s"]), inv(&["tf", "@"])],
3325 BehaviorHook::Sed => vec![inv(&["s/x/y/", "@"]), inv(&["-i", "s/x/y/", "@"])],
3326 BehaviorHook::Perl => {
3327 vec![inv(&["-pe", "s/x/y/", "@"]), inv(&["-pi", "-e", "s/x/y/", "@"])]
3328 }
3329 }
3330 }
3331
3332 /// Fail-closed, enumerated over the REGISTRY: every `[command.behavior]` command denies an
3333 /// operand on a hot path (a secret, home, system, or unpinnable locus), AND a write-role
3334 /// command denies a write into the worktree-trusted rung (`.git/config`). Restores and
3335 /// generalizes `every_touched_path_operand_is_gated` for the declarative path — a command
3336 /// ported off Rust is covered automatically. Red→green: make `resolve_behavior` skip
3337 /// `classify_locus` and this fails on the first probe.
3338 #[test]
3339 fn every_behavior_command_gates_hot_operands() {
3340 use crate::engine::bridge::project;
3341 use crate::registry::types::PositionalRole;
3342 use crate::verdict::Verdict;
3343
3344 let deny = |cmd: &[String], why: &str| {
3345 let refs: Vec<&str> = cmd.iter().map(String::as_str).collect();
3346 let profile = resolve(&toks(&refs)).expect("behavior command resolves");
3347 assert_eq!(project(&profile), Verdict::Denied, "{cmd:?}: {why}");
3348 };
3349
3350 let mut path_bearing = 0usize;
3351 let mut hook_bearing = 0usize;
3352 for name in crate::registry::toml_command_names() {
3353 let Some(b) = crate::registry::command_behavior(name) else { continue };
3354 if !matches!(b.positionals, PositionalRole::None) {
3355 path_bearing += 1;
3356 }
3357 if b.hook.is_some() {
3358 hook_bearing += 1;
3359 }
3360 for hot in HOT_PATHS {
3361 for cmd in behavior_probes(name, b.positionals, hot) {
3362 deny(&cmd, "touched hot path not gated");
3363 }
3364 // Hook commands (dd/tar/sed) have irregular operand syntax, so they are swept by
3365 // their own probe table — restoring the enumerated coverage the deleted RESOLVERS
3366 // sweep gave them.
3367 if let Some(hook) = b.hook {
3368 for cmd in hook_probes(hook, name, hot) {
3369 deny(&cmd, "hook: touched hot path not gated");
3370 }
3371 }
3372 }
3373 // Worktree-trusted is a WRITE boundary only: reading `.git/config` (cat/grep) is
3374 // legitimately allowed, but a write/destroy/relocate into it must deny. Probe the
3375 // write face — the destination slot for a transfer, the operand for a plain write.
3376 let inv = |slots: &[&str]| -> Vec<String> {
3377 std::iter::once(name.to_string()).chain(slots.iter().map(|s| s.to_string())).collect()
3378 };
3379 match b.positionals {
3380 PositionalRole::Write => deny(&inv(&[".git/config"]), "write into worktree-trusted not gated"),
3381 PositionalRole::Transfer => deny(&inv(&["./safe", ".git/config"]), "transfer dest into worktree-trusted not gated"),
3382 _ => {}
3383 }
3384 }
3385 // Non-vacuity: every path-bearing AND every hook command on the roster was reached and
3386 // probed. Derived from the roster (not a magic number) — none-role printers (echo) don't
3387 // positionally gate; hook commands (dd/tar/sed) gate via `hook_probes`.
3388 let count = |pred: fn(&crate::registry::types::BehaviorSpec) -> bool| {
3389 EXPECTED_BEHAVIOR_COMMANDS
3390 .iter()
3391 .filter(|n| crate::registry::command_behavior(n).is_some_and(pred))
3392 .count()
3393 };
3394 assert_eq!(
3395 path_bearing,
3396 count(|b| !matches!(b.positionals, PositionalRole::None)),
3397 "path-bearing behavior commands: saw {path_bearing}"
3398 );
3399 assert_eq!(hook_bearing, count(|b| b.hook.is_some()), "hook behavior commands: saw {hook_bearing}");
3400 }
3401
3402 /// Fail-closed on unknown flags, enumerated over the REGISTRY: every DECLARATIVE flag-walking
3403 /// behavior command (a Read/Write/Transfer role, hookless) worst-cases an unrecognized flag —
3404 /// the `walk_positionals` → `worst` path. Exempt: `grep` (its hook treats an unknown `--token`
3405 /// as a search pattern — keyed on `BehaviorHook::Grep` SPECIFICALLY, not `hook.is_some()`, so a
3406 /// future hook variant is not auto-exempted), and none-role commands (echo prints its args;
3407 /// dd/tar/sed parse their own irregular syntax — all covered by their own resolver tests, and
3408 /// none-role commands take no positional path operands, so an unknown flag can't unlock danger).
3409 #[test]
3410 fn every_hookless_behavior_command_worst_cases_unknown_flags() {
3411 use crate::engine::bridge::project;
3412 use crate::registry::types::{BehaviorHook, PositionalRole};
3413 use crate::verdict::Verdict;
3414
3415 let exempt = |b: &crate::registry::types::BehaviorSpec| {
3416 matches!(b.hook, Some(BehaviorHook::Grep)) || matches!(b.positionals, PositionalRole::None)
3417 };
3418 let mut checked = 0usize;
3419 for name in crate::registry::toml_command_names() {
3420 let Some(b) = crate::registry::command_behavior(name) else { continue };
3421 if exempt(b) {
3422 continue;
3423 }
3424 let profile = resolve(&toks(&[name, "--xyzzy-unknown-42", "./safe"])).expect("resolves");
3425 assert_eq!(project(&profile), Verdict::Denied, "{name}: unknown flag not worst-cased");
3426 checked += 1;
3427 }
3428 let expected = EXPECTED_BEHAVIOR_COMMANDS
3429 .iter()
3430 .filter(|n| crate::registry::command_behavior(n).is_some_and(|b| !exempt(b)))
3431 .count();
3432 assert_eq!(checked, expected, "declarative flag-walking behavior commands: saw {checked}");
3433 }
3434
3435 /// Fail-closed authoring guard: `path_flag_caps` (which gates a valued flag's path VALUE, e.g.
3436 /// `touch -r REF`) runs ONLY on the declarative Read/Write/Transfer path — the None arm (echo)
3437 /// and the hook arm (grep/dd/tar/sed) both return before it. So a `[command.behavior.flags]`
3438 /// path-role declared on a none-role or hook command would be SILENTLY UNGATED — a fail-open.
3439 /// Assert no command does that. Red→green: add `kind = "read"` to a hook command's flags.
3440 #[test]
3441 fn no_none_or_hook_command_declares_ungated_path_flags() {
3442 use crate::registry::types::PositionalRole;
3443 for name in crate::registry::toml_command_names() {
3444 let Some(b) = crate::registry::command_behavior(name) else { continue };
3445 if b.path_flags.is_empty() {
3446 continue;
3447 }
3448 assert!(
3449 b.hook.is_none() && !matches!(b.positionals, PositionalRole::None),
3450 "{name}: behavior path-flags are gated only on the Read/Write/Transfer path; on a \
3451 none-role or hook command they would be silently ungated (fail-open)"
3452 );
3453 }
3454 }
3455}