safe-chains 0.241.4

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! The capability builders: small constructors that each stamp out one `Capability`
//! (or fail-closed `Profile`) with the facet pairing its operation warrants. Resolvers
//! name the intent (`creates`/`overwrites`/`relocates`/`destroys`/`reads_*`/`worst`); the
//! enum choices and `because` strings live here, in one place.

use super::locus::{read_is_unshieldable, read_locus};
use crate::engine::facet::*;

/// A read capability for `path`: its read locus AND, when the path cannot be cleared by the
/// credential shield, the `secret · reads` claim.
///
/// **Use this rather than `reads_content(read_locus(p), …)` anywhere a PATH becomes a read.**
///
/// The shield has never actually reached the level algebra. `reads_secret` sits on the region nodes,
/// but it is consumed only by `apply_grant` (stopping a grant widening a store) and the case-folding
/// test — no capability ever carried it, so `cat ~/.ssh/id_rsa` denied purely because `.ssh`
/// classifies `machine` and the reader level caps local reads at `worktree-trusted`. That made the
/// reader level's own comment — `secret <= uses-ambient` "excludes credential EXTRACTION" — true
/// only of commands that DECLARE a secret read (`security find-generic-password`), never of `cat` on
/// a secret path.
///
/// So the verdict is unchanged today and the REASON is now correct, which is what makes the locus
/// cap safe to relax later. Both halves matter: a path that names a store, and a path that cannot be
/// checked at all.
pub(super) fn reads_path(path: &str, scale: Scale, because: &str) -> Capability {
    let mut c = reads_content(read_locus(path), scale, because);
    if unclearable_read(path, scale) {
        claims_secret_read(&mut c);
    }
    c
}

pub(super) fn claims_secret_read(c: &mut Capability) {
    c.secret.level = SecretLevel::Reads;
    if c.operation == Operation::Observe {
        c.reversibility = c.reversibility.max(Reversibility::Exposed);
    }
}

/// The ONE test for "this read cannot be cleared by the shield" — either the path names a store,
/// or it does not name the files it reads at all.
///
/// One function because the previous two copies fell out of step the moment the second condition
/// was added: `reads_path` learned about sweeps and `transfer_profile` did not, so `tar -cf x.tar ~`
/// was refused while `cp -r ~ ./stolen` copied the same keys into the worktree, where reading them
/// is ordinary. Every read-shaped capability has to ask the same question.
pub(super) fn unclearable_read(path: &str, scale: Scale) -> bool {
    unshieldable(path) || sweeps_unnameable(path, scale)
}

/// An UNBOUNDED read rooted at `user` or above cannot be cleared, whatever its root is named.
///
/// The shield is a test on a name, so it can only answer about a path someone actually wrote.
/// `grep -r foo ~` writes one path, `~`, which is not a credential store — and then reads
/// `~/.ssh/id_rsa`, `~/.aws/credentials` and everything else underneath it. Same laundering as
/// `find ~ -exec cat {}`, arriving through scale instead of through a placeholder.
///
/// Bounded reads on those rungs are untouched: `cat /etc/hosts` names the one file it reads, and
/// the shield genuinely can clear it. Below `user` the sweep is bounded by the workspace, where
/// there is nothing for the shield to protect.
fn sweeps_unnameable(path: &str, scale: Scale) -> bool {
    let sweeps = scale == Scale::Unbounded || names_many(path);
    sweeps && read_locus(path) >= crate::engine::facet::LocalLocus::User
}

/// A glob stands for every file it expands to, none of which is written down. `for f in /etc/*;
/// do cat $f; done` reads `/etc/shadow` while the only string the shield ever sees is `/etc/*`,
/// so the scale is unbounded no matter what the caller declared it to be.
fn names_many(path: &str) -> bool {
    path.contains(['*', '?', '['])
}

/// As [`reads_path`], for the metadata-only observers (`find`, a `-f` script file, a tar member)
/// that place a path without pulling its content into the model.
pub(super) fn observes_path(path: &str, scale: Scale, because: &str) -> Capability {
    let mut c = observes(read_locus(path), scale, because);
    if unclearable_read(path, scale) {
        claims_secret_read(&mut c);
    }
    c
}

/// A read of `path` must be treated as a credential read when it either NAMES a known store or
/// cannot be checked against the shield at all. See [`read_is_unshieldable`] for why the second half
/// is not redundant with the locus.
fn unshieldable(path: &str) -> bool {
    // Delegates entirely: `read_is_unshieldable` owns both halves (names-a-store, cannot-be-pinned)
    // AND the IFS word split they must each run under. Keeping a separate named-store test here ran
    // it on the whole operand, so `VAR="x /etc/shadow"; cat $VAR` reached it as one word that names
    // nothing. Kept as a named seam because the call sites read better for it.
    read_is_unshieldable(path)
}

/// One `observe · content-to-model` capability per path (empty list = reads stdin). A
/// `-` operand is stdin (process-scoped); every other path is placed by `classify_locus`.
pub(super) fn reads_to_model(paths: &[&str], scale: Scale) -> Vec<Capability> {
    if paths.is_empty() {
        return vec![reads_content(LocalLocus::Process, scale, "reads stdin")];
    }
    paths
        .iter()
        .map(|p| {
            if *p == "-" {
                reads_content(LocalLocus::Process, scale, "reads stdin (-)")
            } else {
                reads_path(p, scale, "reads file content to the model")
            }
        })
        .collect()
}

pub(super) fn reads_content(locus: LocalLocus, scale: Scale, because: &str) -> Capability {
    let mut c = Capability::new(Operation::Observe);
    c.locus.local = locus;
    c.scale = scale;
    c.disclosure.audience = DisclosureAudience::LocalProcess; // content → the model
    c.because = because.to_string();
    c
}

pub(super) fn destroys(locus: LocalLocus, scale: Scale) -> Capability {
    // Worktree/temp data is recoverable with effort (VCS, reinstall, regenerate). But an
    // UNBOUNDED destroy reaching home or the system (locus >= user) has no such recovery path
    // — `rm -rf /`, `rm -rf ~` wipe irreplaceable data — so it worst-cases to irreversible
    // (HP-8). That `destroy · irreversible · unbounded` signature is the one corner even yolo
    // refuses; a single or bounded system delete (rm /etc/hosts) stays effortful.
    let reversibility =
        if locus >= LocalLocus::User && scale == Scale::Unbounded { Reversibility::Irreversible } else { Reversibility::Effortful };
    writes(
        Operation::Destroy,
        locus,
        scale,
        reversibility,
        PersistenceLevel::Transient, // a delete leaves nothing behind
        "rm deletes files (recoverable only from out-of-band backups; irreversible when it mass-deletes home/system)",
    )
}

/// The private builder behind the write-family capability constructors (`creates`,
/// `overwrites`, `relocates`, `destroys`): a write at `locus` with the reversibility and
/// persistence the operation warrants. Resolvers call the named constructors, never this —
/// the intent (and the enum pairing) then lives in exactly one place.
fn writes(
    op: Operation,
    locus: LocalLocus,
    scale: Scale,
    reversibility: Reversibility,
    persistence: PersistenceLevel,
    because: &str,
) -> Capability {
    let mut c = Capability::new(op);
    c.locus.local = locus;
    c.scale = scale;
    c.reversibility = reversibility;
    c.persistence.level = persistence;
    c.because = because.to_string();
    c
}

/// A fresh file or directory (`mkdir`, `touch`): `create` at `locus`, `trivial` to undo
/// (`rmdir`/`rm` the new entry), leaving ordinary data.
pub(super) fn creates(locus: LocalLocus, scale: Scale) -> Capability {
    writes(Operation::Create, locus, scale, Reversibility::Trivial, PersistenceLevel::Data, "creates a file or directory")
}

/// A destination write that may clobber existing content (`cp`/`mv` dest): `create` at
/// `locus`, `recoverable` (the repo-recoverable assumption, HP-8) — or `trivial` when
/// `--no-clobber` guarantees no overwrite.
pub(super) fn overwrites(locus: LocalLocus, scale: Scale, no_clobber: bool) -> Capability {
    let reversibility = if no_clobber { Reversibility::Trivial } else { Reversibility::Recoverable };
    writes(
        Operation::Create,
        locus,
        scale,
        reversibility,
        PersistenceLevel::Data,
        "writes the destination; may overwrite existing content unless --no-clobber",
    )
}

/// A dump/export command's OUTPUT FILE (`supabase db dump -f`, `pg_dump --file`): `create` at
/// `locus`, `recoverable` (it may clobber an existing file; worktree content is repo-recoverable,
/// HP-8), leaving data. `single` scale (one file), gated at the file's locus exactly like a
/// redirect — `-f ./out.sql` is a worktree write, `-f /etc/cron.d/job` a system write. The bulk
/// REMOTE read is a separate capability (the `data-export` archetype); this is only the local sink.
pub(super) fn writes_export_file(locus: LocalLocus) -> Capability {
    writes(
        Operation::Create,
        locus,
        Scale::Single,
        Reversibility::Recoverable,
        PersistenceLevel::Data,
        "writes the export/dump output file (may overwrite existing content)",
    )
}

/// An in-place edit of an existing file (`sed -i`): `mutate` at `locus`, `recoverable` (the
/// old content is gone unless a backup was kept, but worktree content is repo-recoverable,
/// HP-8), leaving data. Distinct from `overwrites` (a fresh dest) — the file is edited, not
/// replaced wholesale.
pub(super) fn mutates(locus: LocalLocus, scale: Scale, because: &str) -> Capability {
    writes(Operation::Mutate, locus, scale, Reversibility::Recoverable, PersistenceLevel::Data, because)
}

/// A moved-from source (`mv` src): `mutate` at `locus` — the entry leaves that directory —
/// `trivial` to undo (`mv` back), leaving nothing behind. NOT a destroy: the content
/// survives at the destination, which is why `mv` stays at write-local and `rm` does not.
pub(super) fn relocates(locus: LocalLocus, scale: Scale) -> Capability {
    writes(
        Operation::Mutate,
        locus,
        scale,
        Reversibility::Trivial,
        PersistenceLevel::Transient,
        "mv removes the source from its old location (trivially reversible: mv back)",
    )
}

/// Running code: `execute` at the EXECUTOR's `locus`, with the supplied `trust` (`SelfCode`
/// for the project's own build artifact, `CallerFile` for a named script file). The code's
/// downstream effects are deliberately NOT modeled here — bounding them is the sandbox's job
/// (`Isolation`), not a static string classifier's. This capability is the act of invoking an
/// executor, gated by WHERE that executor lives: a worktree-local one is the dev loop (the
/// `developer` level admits it), a foreign one (`/tmp`, `~`, `/usr/local/bin`) or an
/// unpinnable path (`$VAR`/glob → `machine`) denies on locus. Modest facets (no forced
/// worst-case) so a worktree executor projects to `developer`. See
/// docs/design/behavioral-taxonomy-execution-origin.md.
pub(super) fn executes(locus: LocalLocus, trust: ExecutionTrust, because: &str) -> Capability {
    let mut c = Capability::new(Operation::Execute);
    c.locus.local = locus;
    c.execution.trust = trust;
    c.because = because.to_string();
    c
}

/// The fail-closed profile (§0): a single worst-case capability citing `because` — the
/// standard return when a resolver cannot certify an invocation (unknown flag, missing
/// operand, spoofed path).
pub(super) fn worst(because: &str) -> Profile {
    Profile::of(vec![Capability::worst(because)])
}

/// Breadth of a filesystem effect: `unbounded` when recursing, `bounded` for a glob or
/// several operands, else `single`. Shared by rm/mkdir/touch/cp.
pub(super) fn breadth_scale(operands: &[&str], recursive: bool) -> Scale {
    if recursive {
        Scale::Unbounded
    } else if operands.len() > 1 || operands.iter().any(|p| p.contains(['*', '?', '['])) {
        Scale::Bounded
    } else {
        Scale::Single
    }
}

/// A non-disclosing read: `observe` at `locus` with NO `local-process` disclosure — the
/// content flows to a file or link, not to the model. Used by `cp` (its source) and `ln`
/// (its target, whose content becomes reachable *through* the link — cp-by-reference), so
/// a home/system operand denies on the read locus just as it would for `cat`.
pub(super) fn observes(locus: LocalLocus, scale: Scale, because: &str) -> Capability {
    let mut c = Capability::new(Operation::Observe);
    c.locus.local = locus;
    c.scale = scale;
    c.because = because.to_string();
    c
}

/// How a transfer places its operands: the face its sources are judged at, whether the command acts
/// on a link named as a source rather than on what it leads to (`cp -R link x`), and whether the
/// destination is the entry made.
pub(super) struct Placing {
    pub face: super::locus::Face,
    pub on_link: bool,
    /// The destination is the entry made, never a folder a source lands in: `ln -sf a link` over an
    /// existing link to a file replaces it.
    pub dest_is_entry: bool,
}

/// The profile of a content-transfer command (`cp`/`mv`/`ln`): one capability per SOURCE
/// operand plus one for the DEST, each gated at its own locus. Assembling it here — rather
/// than by hand in each resolver — makes a *dropped operand role* unrepresentable: every
/// source flows through `per_source` and the dest through `per_dest`, by construction, so
/// the omission that made `ln` a `cp`-bypass (HP-18) cannot recur. Callers close over any
/// extra parameters (the `because` string, the `--no-clobber` flag) to fit the uniform
/// `Fn(locus, scale) -> Capability` shape.
///
/// `source_writes` selects the source locus FACE: `mv` REMOVES its source (a write — the entry
/// leaves that directory), so its source must gate at `write_locus`, not `read_locus`. `cp`/`ln`
/// only READ their source. The two faces diverge for roles where read and write policy differ
/// (a copy-OK-but-don't-delete location), so gating a relocate at the read face would be a
/// fail-open there; this closes it by construction rather than relying on the locus ladder.
pub(super) fn transfer_profile(
    sources: &[&str],
    dest: &str,
    scale: Scale,
    source: Placing,
    dest_face: super::locus::Face,
    per_source: impl Fn(LocalLocus, Scale) -> Capability,
    per_dest: impl Fn(LocalLocus, Scale) -> Capability,
) -> Profile {
    // Faces rather than a `source_writes` bool: `mv` REBINDS its source (the name stops referring
    // to anything) and `ln` rebinds its destination, and neither is expressible as read-or-write.
    let at = super::locus::face;
    // A SOURCE the shield cannot clear carries the same `secret · reads` claim a plain reader gets.
    // `per_source` takes only a locus, so it could never make this claim itself, and every transfer
    // command routes through here — `cp`, `mv`, `ln`, `scp`, `rsync`. Without it `cp ~/.ssh/id_rsa
    // ./stolen` rested entirely on the locus cap, and `xargs -I{} cp {} /tmp/dest` (whose source is
    // an unknowable stdin item) claimed nothing at all.
    //
    // Sources only. An unshieldable DESTINATION is a write-placement question, answered by the write
    // face — `secret` is about what is READ, and stamping it on a dest would deny `cp ./a $OUT` for
    // the wrong reason.
    let mut caps: Vec<Capability> = sources
        .iter()
        .map(|s| {
            let judge = || {
                let mut c = per_source(at(s, source.face), scale);
                if unclearable_read(s, scale) {
                    claims_secret_read(&mut c);
                }
                c
            };
            if source.on_link { crate::pathctx::on_the_link(judge) } else { judge() }
        })
        .collect();
    // The destination is judged at its worst landing: itself, or the name a source arrives under.
    let landing = sources
        .iter()
        .filter(|_| !source.dest_is_entry)
        .filter_map(|s| received_name(s))
        .map(|name| at(&format!("{}/{name}", dest.trim_end_matches('/')), dest_face))
        .fold(at(dest, dest_face), LocalLocus::max);
    caps.push(per_dest(landing, scale));
    Profile::of(caps)
}

/// The name a source arrives under when the destination is a directory: `cp /tmp/.envrc .` writes
/// `./.envrc`, which the destination `.` alone never shows. A source copied by its CONTENTS
/// (`rsync -a src/ dest`, `cp -r src/. dest`) brings names nobody wrote down; they stand in as a
/// hidden name, which only an unknown folder treats as sensitive. Unpinnable sources name nothing.
fn received_name(source: &str) -> Option<String> {
    const UNNAMED: &str = ".names-the-copy-brings";
    let trimmed = source.trim_end_matches('/');
    if source.ends_with('/') || trimmed.is_empty() || trimmed == "." || trimmed.ends_with("/.") {
        return Some(UNNAMED.to_string());
    }
    let name = trimmed.rsplit('/').next()?;
    (name != ".." && !super::locus::is_unpinnable(name)).then(|| name.to_string())
}

/// A mutating command is refused when one of its own operands is still a shell glob. Paths the
/// walk derives (`operand/.git/f`, the name a copy lands under) are not operands: only a path
/// that is a current command word is recorded.
pub(super) fn with_operands(
    tokens: &[crate::parse::Token],
    resolve: impl FnOnce(&[crate::parse::Token]) -> Option<Profile>,
) -> Option<Profile> {
    let _tokens = crate::cst::opaque::glob::enter_tokens(tokens.iter().map(|token| token.as_str().to_string()).collect());
    let _unresolved = crate::cst::opaque::glob::enter_unresolved();
    resolve(tokens).map(|mut profile| {
        if crate::cst::opaque::glob::take_unresolved() {
            profile
                .capabilities
                .push(mutates(LocalLocus::Machine, Scale::Unbounded, "behavior: an operand still names a glob"));
        }
        profile
    })
}

#[cfg(test)]
mod secret_read_tests {
    use super::*;
    use crate::engine::authoring::default_levels;
    use crate::engine::testgen::arb_capability;
    use proptest::prelude::*;

    fn admitted_by(cap: &Capability) -> Vec<bool> {
        default_levels().iter().map(|l| l.admits(&Profile::of(vec![cap.clone()]))).collect()
    }

    proptest! {
        #[test]
        fn a_secret_read_is_exposed_and_nothing_else_moves(cap in arb_capability()) {
            let mut marked = cap.clone();
            claims_secret_read(&mut marked);
            prop_assert_eq!(marked.secret.level, SecretLevel::Reads);
            prop_assert_eq!(marked.reversibility >= Reversibility::Exposed, cap.operation == Operation::Observe || cap.reversibility >= Reversibility::Exposed);
            prop_assert!(marked.reversibility >= cap.reversibility);
            let mut rest = cap.clone();
            rest.secret.level = marked.secret.level;
            rest.reversibility = marked.reversibility;
            prop_assert_eq!(rest, marked);
        }

        #[test]
        fn marking_a_secret_read_exposed_changes_no_default_level(cap in arb_capability()) {
            let mut before = cap.clone();
            before.secret.level = SecretLevel::Reads;
            let mut after = cap;
            claims_secret_read(&mut after);
            prop_assert_eq!(admitted_by(&before), admitted_by(&after));
        }

        #[test]
        fn a_read_is_exposed_exactly_when_it_claims_a_secret(
            root in proptest::sample::select(vec!["", "./", "../", "~/", "~/.ssh/", "~/.aws/", "/etc/", "/tmp/", "$X/", "/usr/lib/"]),
            name in "[a-z_.*]{1,10}",
            scale in proptest::sample::select(Scale::all().to_vec()),
        ) {
            let path = format!("{root}{name}");
            for c in [reads_path(&path, scale, "probe"), observes_path(&path, scale, "probe")] {
                prop_assert_eq!(c.secret.level == SecretLevel::Reads, c.reversibility == Reversibility::Exposed, "{}", path);
            }
        }
    }

    #[test]
    fn a_credential_store_read_is_exposed() {
        let c = reads_path("~/.ssh/id_rsa", Scale::Single, "probe");
        assert_eq!(c.secret.level, SecretLevel::Reads);
        assert_eq!(c.reversibility, Reversibility::Exposed);
        let plain = reads_path("./src/main.rs", Scale::Single, "probe");
        assert_eq!(plain.reversibility, Reversibility::None);
    }

    #[test]
    fn a_threshold_at_effortful_refuses_a_secret_read_on_reversibility_alone() {
        let levels = crate::engine::authoring::build_level_set(
            "[level.old]\n[[level.old.allow]]\noperation = [\"observe\"]\nreversibility = \"<= effortful\"\n",
        )
        .expect("compiles");
        let old = &levels[0];
        let read = reads_path("~/.ssh/id_rsa", Scale::Single, "probe");
        assert!(!old.admits(&Profile::of(vec![read])), "a ceiling at effortful must refuse a secret read");
        let plain = reads_path("./notes", Scale::Single, "probe");
        assert!(old.admits(&Profile::of(vec![plain])));
    }
}