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
//! 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 ;
use crateglob_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.
/// 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).
/// 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).
/// 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).
/// 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`).
/// 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.
/// 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).
/// BP-10 (catalog row "Additional working directories"): [`evaluate_path_safe`]
/// over EVERY granted root — `cwd` plus each `core.additional_dirs`/
/// `--add-dir` entry — folded to the strictest [`Decision`] any of them
/// reaches.
///
/// Why a fold rather than "pick the containing root": a root-relative
/// protected-path floor (`write(.git/**)`, from
/// [`protected_path_deny_rules`]) is written relative to A workspace root,
/// and once an extra root is granted there is more than one. Evaluating
/// against only `cwd` — what this crate did before BP-10 — meant a write to
/// `<extra_root>/.git/config` matched NO root-relative pattern at all and
/// fell through to `default`, i.e. the grant silently also removed the
/// floor inside the granted directory. Folding every root keeps the floor
/// on all of them; and because [`evaluate_path_subject_safe`] already
/// treats "resolves entirely outside this root" as a non-match (never an
/// over-block), a root a path has nothing to do with contributes nothing.
///
/// `roots` empty is impossible in practice (callers pass
/// [`crate::tools::ToolContext::write_roots`]-shaped lists that always
/// start with `cwd`); an empty slice returns `default` unchanged.
/// BP-10: [`evaluate_path_subject_safe`] over every granted root — see
/// [`evaluate_path_safe_roots`]'s doc comment for the fold's rationale.
/// 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.
/// BP-10 (catalog row "Allow/ask/deny rule language", semantics "Pattern
/// rules per tool/path/**domain**/command"): the FOURTH rule subject —
/// evaluate a network HOST against `rules` as the `domain` pseudo-tool,
/// exactly the way [`evaluate_path`] evaluates a path as the `read`/`write`
/// pseudo-tools. A rule is written `"domain(evil.example)"` /
/// `"domain(*.evil.example)"`, or bare `"domain"` to name every host at
/// once; the glob syntax, the tier priority, and the first-match order are
/// the engine's, not a second matcher's.
///
/// `host: None` (a URL with no parseable host) is [`Decision::Deny`],
/// fail-closed — an unresolvable host cannot be proven to satisfy an
/// allowlist. `host` is lowercased before matching (hostnames are
/// case-insensitive; patterns are expected lowercase).
/// BP-10: does the DENY tier alone match `host`? Used only to tell the two
/// refusal REASONS apart ("denied by" vs "not on the allowlist") — the
/// decision itself is always [`evaluate_domain`]'s.
/// Which access [`evaluate_path`] is checking — matches module 11's
/// `read(...)`/`write(...)` pseudo-tool rule pattern names.
/// 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).