返回 CodeWhale
read_guard.rs
根目录 / crates / sandbox / src / read_guard.rs
1 //! Read deny-list (S1, #5568 follow-up).
2 //!
3 //! # What this is
4 //!
5 //! Every sandbox posture Codewhale ships — including `read-only` — grants the
6 //! sandboxed process read access to the entire filesystem
7 //! (`policy.rs`). #5568 added the *plumbing* for an
8 //! opt-in deny-list (Seatbelt last-match-wins `deny file-read*` rules;
9 //! bubblewrap masks), but the list shipped empty, so in practice nothing was
10 //! denied. This module supplies (a) a curated default set covering the obvious
11 //! credential stores and (b) the in-process matcher that Codewhale's own
12 //! file-reading tools consult — those tools call `std::fs` directly inside the
13 //! harness process and are never wrapped by `sandbox-exec` or `bwrap` at all,
14 //! so the OS-level rules alone left the largest hole wide open.
15 //!
16 //! # Two scopes
17 //!
18 //! Every rule denies the model's own file tools. Only `DenyScope::Process`
19 //! rules are also handed to the OS wrappers, so a subprocess cannot read them.
20 //! A tool's own auth config (`~/.config/gh/hosts.yml`, `~/.npmrc`) is
21 //! `DenyScope::ModelContext`: refusing that file to the process does not hide
22 //! the token, because the tool prints it on request; it only stops the tool
23 //! from starting at all.
24 //!
25 //! # What this is NOT
26 //!
27 //! **This is defense-in-depth, not a security boundary.** It raises the cost of
28 //! a confused or prompt-injected agent stumbling into `~/.ssh/id_ed25519`; it
29 //! does not contain a deliberate attacker. Specifically it does NOT stop:
30 //!
31 //! - **Hardlinks.** A hardlink is a second *name* for the same inode with no
32 //! trace of the first. `foo` hardlinked to `~/.ssh/id_rsa` canonicalizes to
33 //! `foo`, matches nothing, and is read. No path-based deny-list can fix this;
34 //! only an inode-level or MAC-label check could.
35 //! - **Content already elsewhere.** A key copied into the workspace before the
36 //! agent ran, or pasted into the conversation, is readable.
37 //! - **Indirect reads.** `ssh-agent`, `security find-generic-password`,
38 //! `aws sts get-session-token`, a helper the user installed — a process that
39 //! *hands over* a secret without the agent reading the file. On macOS
40 //! `~/Library/Keychains` is denied but the keychain *daemon* is not.
41 //! - **`danger-full-access`.** That posture bypasses the OS wrapper entirely
42 //! (`should_sandbox() == false`). The in-process tool checks still apply, but
43 //! a shell command does not.
44 //! - **Anything on the network side.** A denied read does not stop exfiltration
45 //! of what *was* read.
46 //! - **Reads by MCP servers and other child processes** that Codewhale did not
47 //! itself wrap.
48 //!
49 //! Treat it as a seatbelt, and keep the real controls (least-privilege
50 //! credentials, short-lived tokens, approval prompts) doing the real work.
51 //!
52 //! # Matching rules
53 //!
54 //! - **Deny wins.** A path matching any deny rule is refused; there is no allow
55 //! rule that can override one. Exemptions (`sandbox_read_denylist_exempt`)
56 //! subtract from the *built-in defaults* only, before matching — a path the
57 //! user explicitly listed in `sandbox_denied_read_paths` can never be
58 //! exempted back open.
59 //! - **Symlinks.** Both the literal path and its `canonicalize()`d target are
60 //! tested, so a symlink pointing into `~/.ssh` is denied by its target even
61 //! though its own name is innocuous. The *rules* are resolved the same way
62 //! when they are built: a rule spelled `/etc/ssh` also denies
63 //! `/private/etc/ssh` on macOS, where `/etc` is itself a symlink, and a rule
64 //! written against a `/var/...` directory fires for the `/private/var/...`
65 //! spelling that `canonicalize` and `current_dir` hand back. Without that,
66 //! the resolved candidate never matched a literal rule, which is exactly the
67 //! shape hosted macOS CI runs in (`$TMPDIR` under `/var/folders`).
68 //! Exemptions are matched the same way, so exempting `/private/etc/sudoers`
69 //! — the spelling a denial message may name — reopens the `/etc/sudoers`
70 //! rule it resolves from. Rules are resolved when the list is built
71 //! (startup and config reload); a symlink retargeted afterwards is seen
72 //! through the literal candidate only until the list is rebuilt, which is
73 //! within the defense-in-depth posture above.
74 //! - **`..` and relative paths.** Two candidates are tested. The literal one is
75 //! lexically normalized (`.`/`..` folded without touching the disk), which
76 //! catches traversal into a denied tree even when nothing on the path exists
77 //! yet. The resolved one keeps `..` components raw and lets the OS apply
78 //! them *after* resolving each symlink component — the secure order — because
79 //! with `pub/link -> denied/sub`, the path `pub/link/../secret` really reads
80 //! `denied/secret`; folding `..` first would hide that. When the path does
81 //! not exist, the deepest existing ancestor is canonicalized (with the same
82 //! raw order) and the remainder re-appended.
83 //! - **Case.** On macOS and Windows — where the default filesystem is
84 //! case-insensitive — comparison is case-folded, so `~/.SSH/ID_RSA` is denied.
85 //! On Linux comparison is exact, matching the filesystem's own semantics.
86 //! - **Boundaries are component-wise.** `~/.awsome/notes.md` is not under
87 //! `~/.aws`; a plain string `starts_with` would have said it was.
88
89 use std::ffi::OsString;
90 use std::path::{Component, Path, PathBuf};
91 use std::sync::{Arc, OnceLock, RwLock};
92
93 /// Why a read was refused, so callers can render one clear message.
94 ///
95 /// A denial is always an explicit error. It is never rendered as an empty file,
96 /// a zero-length result, or a "not found" — a silent empty read teaches an agent
97 /// that the file is empty and invites it to try a dozen sibling paths.
98 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub struct ReadDenial {
100 /// The path the caller asked for, as written.
101 pub requested: PathBuf,
102 /// The deny rule that matched.
103 pub rule: DenyRule,
104 /// True when the match was on the symlink target rather than the literal
105 /// path — worth saying out loud, or the refusal looks arbitrary.
106 pub via_symlink: bool,
107 }
108
109 impl ReadDenial {
110 /// One-line, non-leaky refusal message.
111 ///
112 /// Names the *rule*, not the resolved secret path: telling the model that
113 /// `notes.txt` really points at `/Users/x/.ssh/id_ed25519` hands it the
114 /// location it was looking for.
115 #[must_use]
116 pub fn message(&self, tool: &str) -> String {
117 let via = if self.via_symlink {
118 " (reached through a symlink)"
119 } else {
120 ""
121 };
122 format!(
123 "{tool} refused to read {}{via}: the sandbox read deny-list blocks {}. \
124 This path is treated as a credential store. If it is genuinely needed, \
125 add it to `sandbox_read_denylist_exempt` in your Codewhale config.",
126 self.requested.display(),
127 self.rule.describe(),
128 )
129 }
130 }
131
132 /// Which reads a rule applies to.
133 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
134 pub enum DenyScope {
135 /// Every read the sandbox controls: the model's file tools and any
136 /// subprocess. For key material, system policy, and stores that belong to
137 /// a different principal.
138 Process,
139 /// Only the reads the model performs through its own file tools. For a
140 /// tool's own auth config, which the tool must open to work at all.
141 ModelContext,
142 }
143
144 /// A single deny rule. Kept as an enum rather than a bare path so the refusal
145 /// message can name the rule ("SSH keys") instead of echoing a secret path.
146 #[derive(Debug, Clone, PartialEq, Eq)]
147 pub enum DenyRule {
148 /// Everything at or below a directory (or a single file at that path).
149 Subtree {
150 /// Normalized absolute path, as configured.
151 path: PathBuf,
152 /// `path` with symlinks resolved, kept only when it differs. A read is
153 /// matched against both spellings: the literal one catches
154 /// `/etc/sudoers` as written, this one catches `/private/etc/sudoers`
155 /// — the same file, reached by the name the OS actually uses.
156 resolved: Option<PathBuf>,
157 /// Human label, e.g. "SSH keys (~/.ssh)".
158 label: &'static str,
159 /// Whether this rule also denies subprocess reads.
160 scope: DenyScope,
161 },
162 /// Any file whose *name* matches, anywhere on disk. Used for `.env`, which
163 /// has no fixed location.
164 FileName {
165 /// Human label.
166 label: &'static str,
167 },
168 }
169
170 impl DenyRule {
171 /// A subtree rule that also remembers where its path really leads.
172 fn subtree(path: PathBuf, label: &'static str, scope: DenyScope) -> Self {
173 let resolved = canonicalize_best_effort(&path);
174 DenyRule::Subtree {
175 resolved: (resolved != path).then_some(resolved),
176 path,
177 label,
178 scope,
179 }
180 }
181
182 /// True when this rule, under either spelling, lies at or below one of
183 /// `roots`. Exemptions subtract whole rules, so both spellings count.
184 fn is_within_any(&self, roots: &[PathBuf]) -> bool {
185 let DenyRule::Subtree { path, resolved, .. } = self else {
186 return false;
187 };
188 roots.iter().any(|root| {
189 path_is_within(path, root)
190 || resolved
191 .as_deref()
192 .is_some_and(|real| path_is_within(real, root))
193 })
194 }
195
196 #[must_use]
197 fn describe(&self) -> String {
198 match self {
199 DenyRule::Subtree { label, .. } => (*label).to_string(),
200 DenyRule::FileName { label } => (*label).to_string(),
201 }
202 }
203 }
204
205 /// The compiled deny-list.
206 #[derive(Debug, Clone, Default)]
207 pub struct ReadDenylist {
208 subtrees: Vec<DenyRule>,
209 deny_env_files: bool,
210 }
211
212 impl ReadDenylist {
213 /// An empty deny-list: denies nothing. Used when the user turns defaults
214 /// off and configures no paths of their own.
215 #[must_use]
216 pub fn empty() -> Self {
217 Self::default()
218 }
219
220 /// The read deny-list in force for a config (S1).
221 ///
222 /// Unions the built-in credential-store defaults (unless
223 /// `sandbox_read_denylist_defaults = false`) with
224 /// `sandbox_denied_read_paths`, minus `sandbox_read_denylist_exempt`.
225 /// Feeds both the in-process file-reading tools and the OS sandbox
226 /// wrappers. A `read_file` call refuses every rule; a shell `cat` refuses
227 /// only the rules scoped to the process, which excludes a tool's own auth
228 /// config.
229 #[must_use]
230 pub fn from_config(config: &codewhale_runtime::config::Config) -> Self {
231 Self::build(
232 config.sandbox_read_denylist_defaults.unwrap_or(true),
233 &config.sandbox_denied_read_paths,
234 &config.sandbox_read_denylist_exempt,
235 )
236 }
237
238 /// Build the effective deny-list.
239 ///
240 /// * `include_defaults` — apply the built-in credential-store set.
241 /// * `extra` — user-configured `sandbox_denied_read_paths`; these are
242 /// absolute (or `~`-prefixed) paths and are never exemptable.
243 /// * `exempt` — user-configured `sandbox_read_denylist_exempt`; subtracts
244 /// from the built-in defaults only.
245 #[must_use]
246 pub fn build(include_defaults: bool, extra: &[PathBuf], exempt: &[PathBuf]) -> Self {
247 // Each exemption is kept in both spellings too, so exempting the path a
248 // denial named (`/private/etc/sudoers` on macOS) reopens the rule it
249 // resolved from (`/etc/sudoers`), and vice versa.
250 let exempt_normalized: Vec<PathBuf> = exempt
251 .iter()
252 .cloned()
253 .map(expand_home_prefix)
254 .map(|p| normalize_lexically(&p))
255 .flat_map(|p| {
256 let resolved = canonicalize_best_effort(&p);
257 let real = (resolved != p).then_some(resolved);
258 std::iter::once(p).chain(real)
259 })
260 .collect();
261
262 let mut subtrees = Vec::new();
263 let mut deny_env_files = false;
264
265 if include_defaults {
266 // The `.env` rule has no fixed location, so its exemption is
267 // name-shaped: any exempt entry whose FILE NAME is `.env` — bare
268 // `.env`, `~/.env`, `some/project/.env` — disables the whole
269 // filename rule. Comparing the raw string could never match: the
270 // entries above were normalized to absolute paths.
271 deny_env_files = !exempt_normalized.iter().any(|p| {
272 p.file_name()
273 .is_some_and(|name| name == std::ffi::OsStr::new(".env"))
274 });
275 for (raw, label, scope) in default_denied_subtrees() {
276 let rule = DenyRule::subtree(normalize_lexically(&raw), label, scope);
277 if rule.is_within_any(&exempt_normalized) {
278 continue;
279 }
280 subtrees.push(rule);
281 }
282 }
283
284 // User-listed denies are appended last and are NOT filtered by the
285 // exempt list: deny wins over allow, without exception.
286 for raw in extra {
287 let path = normalize_lexically(&expand_home_prefix(raw.clone()));
288 if path.as_os_str().is_empty() {
289 continue;
290 }
291 subtrees.push(DenyRule::subtree(
292 path,
293 "a path in `sandbox_denied_read_paths`",
294 DenyScope::Process,
295 ));
296 }
297
298 Self {
299 subtrees,
300 deny_env_files,
301 }
302 }
303
304 /// True when nothing is denied — i.e. the posture really does grant read of
305 /// every file on disk.
306 #[must_use]
307 pub fn is_empty(&self) -> bool {
308 self.subtrees.is_empty() && !self.deny_env_files
309 }
310
311 /// Every literal subtree path that must also be denied to subprocesses,
312 /// for handing to the OS wrappers (`SandboxManager::set_denied_read_subpaths`).
313 /// Rules scoped to [`DenyScope::ModelContext`] are omitted: refusing a
314 /// program the config it needs to start disables the program without
315 /// keeping its bytes out of the model. The filename rule (`.env`) has no
316 /// fixed path and therefore cannot be expressed to Seatbelt or bubblewrap
317 /// as a subpath — it is enforced in-process only, which is a real gap for
318 /// shell commands and is documented as such.
319 #[must_use]
320 pub fn subtree_paths(&self) -> Vec<PathBuf> {
321 self.subtrees
322 .iter()
323 .filter_map(|rule| match rule {
324 DenyRule::Subtree {
325 path,
326 scope: DenyScope::Process,
327 ..
328 } => Some(path.clone()),
329 DenyRule::Subtree { .. } | DenyRule::FileName { .. } => None,
330 })
331 .collect()
332 }
333
334 /// Check a path a tool is about to read.
335 ///
336 /// `requested` may be relative, may contain `..`, may be a symlink, and may
337 /// not exist. Both the lexically normalized path and the canonicalized
338 /// target are tested; either matching is a denial.
339 pub fn check(&self, requested: &Path) -> Result<(), ReadDenial> {
340 if self.is_empty() {
341 return Ok(());
342 }
343
344 let literal = absolutize(requested);
345 let resolved = canonicalize_best_effort(requested);
346 let via_symlink = resolved != literal;
347
348 for candidate in [&literal, &resolved] {
349 if self.deny_env_files && is_env_file(candidate) {
350 return Err(ReadDenial {
351 requested: requested.to_path_buf(),
352 rule: DenyRule::FileName {
353 label: "environment files (`.env`, `.env.<name>`)",
354 },
355 via_symlink: via_symlink && candidate == &resolved,
356 });
357 }
358 for rule in &self.subtrees {
359 let DenyRule::Subtree {
360 path,
361 resolved: rule_resolved,
362 ..
363 } = rule
364 else {
365 continue;
366 };
367 let hit = path_is_within(candidate, path)
368 || rule_resolved
369 .as_deref()
370 .is_some_and(|real| path_is_within(candidate, real));
371 if hit {
372 return Err(ReadDenial {
373 requested: requested.to_path_buf(),
374 rule: rule.clone(),
375 via_symlink: via_symlink && candidate == &resolved,
376 });
377 }
378 }
379 }
380
381 Ok(())
382 }
383 }
384
385 // ---------------------------------------------------------------------------
386 // Process-wide active deny-list
387 //
388 // Codewhale's file-reading tools (`read_file`, `read`, `read_media`, …) run
389 // in-process and are never wrapped by `sandbox-exec` or `bwrap`, so they have
390 // to consult the deny-list themselves. Threading config through every tool
391 // signature would touch dozens of call sites for one read; a process-global
392 // set once at startup keeps the blast radius to the tools that actually read
393 // files.
394 // ---------------------------------------------------------------------------
395
396 static ACTIVE: RwLock<Option<Arc<ReadDenylist>>> = RwLock::new(None);
397 static FALLBACK: OnceLock<Arc<ReadDenylist>> = OnceLock::new();
398
399 /// Install the deny-list resolved from user config. Called once during startup.
400 pub fn set_active(list: ReadDenylist) {
401 if let Ok(mut slot) = ACTIVE.write() {
402 *slot = Some(Arc::new(list));
403 }
404 }
405
406 /// The deny-list in force for this process.
407 ///
408 /// Falls back to the built-in defaults when startup has not installed one, so
409 /// a code path that runs before config load is protected rather than open.
410 #[must_use]
411 pub fn active() -> Arc<ReadDenylist> {
412 if let Ok(slot) = ACTIVE.read()
413 && let Some(list) = slot.as_ref()
414 {
415 return Arc::clone(list);
416 }
417 Arc::clone(FALLBACK.get_or_init(|| Arc::new(ReadDenylist::build(true, &[], &[]))))
418 }
419
420 #[cfg(any(test, feature = "test-support"))]
421 pub fn with_test_active_denylist<R>(list: ReadDenylist, callback: impl FnOnce() -> R) -> R {
422 struct RestoreActive(Option<Arc<ReadDenylist>>);
423 impl Drop for RestoreActive {
424 fn drop(&mut self) {
425 *ACTIVE.write().unwrap() = self.0.take();
426 }
427 }
428 let previous = (*ACTIVE.write().unwrap()).replace(Arc::new(list));
429 let _restore = RestoreActive(previous);
430 callback()
431 }
432
433 /// `.env`, `.env.local`, `.env.production` — but deliberately NOT
434 /// `.env.example`, `.env.sample`, `.env.template`, `.env.defaults`, or
435 /// `.env.dist`. Those are committed placeholders that a coding agent has a
436 /// legitimate, routine reason to read (they document which variables a project
437 /// needs), and denying them would break ordinary development for no security
438 /// gain — they contain no secrets by construction.
439 fn is_env_file(path: &Path) -> bool {
440 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
441 return false;
442 };
443 let name = fold_case_str(name);
444 if name == ".env" {
445 return true;
446 }
447 let Some(suffix) = name.strip_prefix(".env.") else {
448 return false;
449 };
450 const PLACEHOLDER_SUFFIXES: &[&str] = &[
451 "example", "sample", "template", "defaults", "dist", "schema",
452 ];
453 !PLACEHOLDER_SUFFIXES.contains(&suffix)
454 }
455
456 /// The built-in default deny set.
457 ///
458 /// Every rule here denies a read to the model's own file tools. A rule also
459 /// denies subprocess reads (DenyScope::Process) only when the item is key
460 /// material, system policy, or another principal's store: something no
461 /// ordinary program opens in order to work. A tool's own auth config is
462 /// scoped to the model instead (DenyScope::ModelContext), because `gh`
463 /// cannot start without `~/.config/gh/hosts.yml`, so denying that file to the
464 /// process disables the CLI without putting its token any further out of
465 /// reach, since the CLI will still print it on request. Deliberately
466 /// excluded, despite containing or neighbouring secrets:
467 ///
468 /// - `~/.gitconfig` — read constantly by tooling; holds config, not secrets.
469 /// (`~/.git-credentials`, which holds the secrets, IS denied.)
470 /// - `~/.cargo`, `~/.npm`, `~/.m2` as a whole — the seatbelt profile already
471 /// grants these read+write because `cargo build` and `npx` fail without
472 /// them. Only the credential *files* inside them are denied.
473 /// - `~/.docker` as a whole — `docker build` reads it. Only
474 /// `~/.docker/config.json` (registry auth) is denied.
475 /// - `~/.config` as a whole — far too broad; individual credential dirs inside
476 /// it are listed instead.
477 /// - The user's source tree, `~/Documents`, `~/Downloads` — a coding agent must
478 /// still be able to read the user's code, which is the entire point.
479 fn default_denied_subtrees() -> Vec<(PathBuf, &'static str, DenyScope)> {
480 use DenyScope::{ModelContext, Process};
481 let mut out = machine_wide_denied_subtrees();
482 if let Ok(Some(active)) = codewhale_paths::codewhale_home() {
483 out.push((
484 active.join("secrets"),
485 "Codewhale secret store (active home)",
486 Process,
487 ));
488 out.push((
489 active.join("credentials"),
490 "Codewhale OAuth credentials (active home)",
491 Process,
492 ));
493 }
494 if let Some(legacy) = codewhale_paths::legacy_deepseek_home() {
495 out.push((
496 legacy.join("secrets"),
497 "Codewhale secret store (legacy home)",
498 Process,
499 ));
500 out.push((
501 legacy.join("credentials"),
502 "Codewhale OAuth credentials (legacy home)",
503 Process,
504 ));
505 }
506 out.push((
507 codewhale_runtime::oauth::auth_file_path(),
508 "Codex CLI login (resolved auth file)",
509 Process,
510 ));
511 out.extend(runtime_daemon_socket_dirs());
512 let Some(home) = dirs::home_dir() else {
513 return out;
514 };
515 let h = |rel: &str| home.join(rel);
516
517 let mut ambient: Vec<(PathBuf, &'static str, DenyScope)> = vec![
518 // --- SSH / GPG ---
519 (h(".ssh"), "SSH keys and known-hosts (~/.ssh)", Process),
520 (h(".gnupg"), "GnuPG keyring (~/.gnupg)", Process),
521 // --- Cloud provider credentials ---
522 (h(".aws"), "AWS credentials (~/.aws)", ModelContext),
523 (
524 h(".config/gcloud"),
525 "Google Cloud credentials (~/.config/gcloud)",
526 ModelContext,
527 ),
528 (h(".azure"), "Azure credentials (~/.azure)", ModelContext),
529 (h(".kube"), "Kubernetes credentials (~/.kube)", ModelContext),
530 (h(".oci"), "Oracle Cloud credentials (~/.oci)", ModelContext),
531 (
532 h(".config/doctl"),
533 "DigitalOcean credentials (~/.config/doctl)",
534 ModelContext,
535 ),
536 (
537 h(".config/fly"),
538 "Fly.io credentials (~/.config/fly)",
539 ModelContext,
540 ),
541 (h(".vercel"), "Vercel credentials (~/.vercel)", ModelContext),
542 (
543 h(".wrangler/config"),
544 "Cloudflare credentials (~/.wrangler/config)",
545 ModelContext,
546 ),
547 (
548 h(".config/gh/hosts.yml"),
549 "GitHub CLI tokens (~/.config/gh/hosts.yml)",
550 ModelContext,
551 ),
552 (
553 h(".config/glab-cli"),
554 "GitLab CLI tokens (~/.config/glab-cli)",
555 ModelContext,
556 ),
557 // --- Package-registry and network credential files ---
558 (h(".netrc"), "netrc credentials (~/.netrc)", ModelContext),
559 (h("_netrc"), "netrc credentials (~/_netrc)", ModelContext),
560 (
561 h(".pgpass"),
562 "PostgreSQL password file (~/.pgpass)",
563 ModelContext,
564 ),
565 (h(".my.cnf"), "MySQL credentials (~/.my.cnf)", ModelContext),
566 (h(".npmrc"), "npm auth tokens (~/.npmrc)", ModelContext),
567 (h(".pypirc"), "PyPI auth tokens (~/.pypirc)", ModelContext),
568 (
569 h(".git-credentials"),
570 "stored git credentials (~/.git-credentials)",
571 ModelContext,
572 ),
573 (
574 h(".cargo/credentials"),
575 "crates.io token (~/.cargo/credentials)",
576 ModelContext,
577 ),
578 (
579 h(".cargo/credentials.toml"),
580 "crates.io token (~/.cargo/credentials.toml)",
581 ModelContext,
582 ),
583 (
584 h(".docker/config.json"),
585 "Docker registry auth (~/.docker/config.json)",
586 ModelContext,
587 ),
588 (
589 h(".m2/settings-security.xml"),
590 "Maven master password (~/.m2)",
591 ModelContext,
592 ),
593 (
594 h(".gradle/gradle.properties"),
595 "Gradle credentials (~/.gradle/gradle.properties)",
596 ModelContext,
597 ),
598 // --- Codewhale's own credential stores ---
599 // Duplicated with `tools::file::is_codewhale_credential_path` on
600 // purpose: that guard is scoped to the *active* config, this one is
601 // unconditional, and neither should depend on the other still existing.
602 (
603 h(".codewhale/secrets"),
604 "Codewhale secret store (~/.codewhale/secrets)",
605 Process,
606 ),
607 (
608 h(".deepseek/secrets"),
609 "Codewhale secret store (~/.deepseek/secrets)",
610 Process,
611 ),
612 (
613 h(".codewhale/credentials"),
614 "Codewhale OAuth credentials (ambient home)",
615 Process,
616 ),
617 (
618 h(".deepseek/credentials"),
619 "Codewhale OAuth credentials (ambient legacy home)",
620 Process,
621 ),
622 (h(".kimi/credentials"), "Kimi CLI credentials", Process),
623 (
624 h(".claude/.credentials.json"),
625 "Claude Code credentials",
626 Process,
627 ),
628 (
629 h(".codewhale-cu/recordings"),
630 "Computer Use recordings and trajectories",
631 Process,
632 ),
633 // --- Browser profiles (cookies, saved passwords, session tokens) ---
634 (h(".mozilla"), "Firefox profile (~/.mozilla)", Process),
635 (
636 h(".config/google-chrome"),
637 "Chrome profile (~/.config/google-chrome)",
638 Process,
639 ),
640 (
641 h(".config/chromium"),
642 "Chromium profile (~/.config/chromium)",
643 Process,
644 ),
645 (
646 h(".config/BraveSoftware"),
647 "Brave profile (~/.config/BraveSoftware)",
648 Process,
649 ),
650 ];
651
652 if cfg!(target_os = "macos") {
653 ambient.extend([
654 (
655 h("Library/Keychains"),
656 "macOS keychain (~/Library/Keychains)",
657 Process,
658 ),
659 (
660 h("Library/Application Support/Google/Chrome"),
661 "Chrome profile (~/Library/Application Support/Google/Chrome)",
662 Process,
663 ),
664 (
665 h("Library/Application Support/Firefox"),
666 "Firefox profile (~/Library/Application Support/Firefox)",
667 Process,
668 ),
669 (
670 h("Library/Application Support/BraveSoftware"),
671 "Brave profile (~/Library/Application Support/BraveSoftware)",
672 Process,
673 ),
674 (
675 h("Library/Safari"),
676 "Safari profile (~/Library/Safari)",
677 Process,
678 ),
679 (
680 h("Library/Cookies"),
681 "macOS cookie store (~/Library/Cookies)",
682 Process,
683 ),
684 ]);
685 }
686
687 out.extend(ambient);
688 out
689 }
690
691 fn runtime_daemon_socket_dirs() -> Vec<(PathBuf, &'static str, DenyScope)> {
692 use codewhale_paths::daemon_socket::{SocketPathInputs, resolve_socket_path};
693 let live = SocketPathInputs::from_environment(None).unwrap_or_else(|_| SocketPathInputs {
694 xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR")
695 .filter(|value| !value.is_empty())
696 .map(PathBuf::from),
697 user_home: codewhale_paths::user_home(),
698 macos: cfg!(target_os = "macos"),
699 ..SocketPathInputs::default()
700 });
701 let layouts = [
702 live.clone(),
703 SocketPathInputs {
704 codewhale_home_override: None,
705 ..live.clone()
706 },
707 SocketPathInputs {
708 codewhale_home_override: None,
709 xdg_runtime_dir: None,
710 ..live.clone()
711 },
712 SocketPathInputs {
713 codewhale_home_override: None,
714 xdg_runtime_dir: None,
715 macos: false,
716 ..live
717 },
718 ];
719 let mut dirs: Vec<PathBuf> = Vec::new();
720 for layout in &layouts {
721 if let Ok(socket) = resolve_socket_path(layout)
722 && let Some(dir) = socket.parent()
723 && !dirs.iter().any(|seen| seen == dir)
724 {
725 dirs.push(dir.to_path_buf());
726 }
727 }
728 dirs.into_iter()
729 .map(|dir| {
730 (
731 dir,
732 "Codewhale runtime daemon socket and owner receipt",
733 DenyScope::Process,
734 )
735 })
736 .collect()
737 }
738
739 fn machine_wide_denied_subtrees() -> Vec<(PathBuf, &'static str, DenyScope)> {
740 use DenyScope::Process;
741 let mut out: Vec<(PathBuf, &'static str, DenyScope)> = vec![
742 (
743 PathBuf::from("/etc/shadow"),
744 "system password hashes (/etc/shadow)",
745 Process,
746 ),
747 (
748 PathBuf::from("/etc/sudoers"),
749 "sudoers policy (/etc/sudoers)",
750 Process,
751 ),
752 (
753 PathBuf::from("/etc/ssh"),
754 "system SSH host keys (/etc/ssh)",
755 Process,
756 ),
757 ];
758 if cfg!(target_os = "macos") {
759 out.push((
760 PathBuf::from("/Library/Keychains"),
761 "system keychain (/Library/Keychains)",
762 Process,
763 ));
764 }
765 out
766 }
767
768 // ---------------------------------------------------------------------------
769 // Path handling
770 //
771 // The evasion cases this has to survive are the whole reason the module exists;
772 // a deny-list a symlink walks around is theater.
773 // ---------------------------------------------------------------------------
774
775 /// Expand a leading `~` to the user's home directory.
776 fn expand_home_prefix(path: PathBuf) -> PathBuf {
777 let Some(text) = path.to_str() else {
778 return path;
779 };
780 if text == "~" {
781 return dirs::home_dir().unwrap_or(path);
782 }
783 if let Some(rest) = text.strip_prefix("~/")
784 && let Some(home) = dirs::home_dir()
785 {
786 return home.join(rest);
787 }
788 path
789 }
790
791 /// Fold `.` and `..` without touching the disk, and make the path absolute
792 /// against the current directory when it is relative.
793 ///
794 /// Purely lexical on purpose: this is the check that catches
795 /// `workspace/../../../.ssh/id_rsa` even when nothing on that path exists yet.
796 /// It is paired with — never a substitute for — `canonicalize_best_effort`,
797 /// which is what catches symlinks.
798 fn normalize_lexically(path: &Path) -> PathBuf {
799 let absolute = if path.is_absolute() {
800 path.to_path_buf()
801 } else {
802 std::env::current_dir()
803 .unwrap_or_else(|_| PathBuf::from("/"))
804 .join(path)
805 };
806
807 let mut out = PathBuf::new();
808 for component in absolute.components() {
809 match component {
810 Component::CurDir => {}
811 Component::ParentDir => {
812 // Never pop past the root: `/..` is `/`.
813 if out
814 .components()
815 .next_back()
816 .is_some_and(|c| !matches!(c, Component::RootDir | Component::Prefix(_)))
817 {
818 out.pop();
819 }
820 }
821 other => out.push(other.as_os_str()),
822 }
823 }
824 out
825 }
826
827 fn absolutize(path: &Path) -> PathBuf {
828 normalize_lexically(path)
829 }
830
831 /// Make a path absolute against the current directory WITHOUT folding `.` or
832 /// `..` components.
833 ///
834 /// Folding first is unsound: with `pub/link -> denied/sub`, the path
835 /// `pub/link/../secret` lexically becomes `pub/secret`, but the OS resolves the
836 /// symlink *before* applying `..` and really reads `denied/secret`. Keeping the
837 /// raw `..` components lets `fs::canonicalize` apply the secure order —
838 /// resolve each component, then let `..` pop the resolved result.
839 fn absolutize_raw(path: &Path) -> PathBuf {
840 if path.is_absolute() {
841 path.to_path_buf()
842 } else {
843 std::env::current_dir()
844 .unwrap_or_else(|_| PathBuf::from("/"))
845 .join(path)
846 }
847 }
848
849 /// Resolve symlinks as far as the filesystem allows.
850 ///
851 /// `canonicalize` fails on a path that does not exist, which is exactly the
852 /// case for a read of a file that is about to be created — and also the case an
853 /// evader would reach for. So on failure we walk up the RAW ancestor chain
854 /// (each surviving `..` included) to the deepest ancestor that *does* exist,
855 /// canonicalize that — resolving any symlinks, with the OS applying any `..`
856 /// components above it in the secure order — and re-append the remaining
857 /// components verbatim. A dropped `..` can only leave the candidate *deeper*
858 /// inside an already-resolved ancestor, which subtree matching still denies;
859 /// the old lexical-first fold popped symlinks out of existence instead.
860 fn canonicalize_best_effort(path: &Path) -> PathBuf {
861 let absolute = absolutize_raw(path);
862 if let Ok(resolved) = std::fs::canonicalize(&absolute) {
863 return resolved;
864 }
865
866 let mut suffix: Vec<OsString> = Vec::new();
867 let mut cursor = absolute.as_path();
868 loop {
869 let Some(parent) = cursor.parent() else {
870 return absolute;
871 };
872 if let Some(name) = cursor.file_name() {
873 suffix.push(name.to_os_string());
874 }
875 if let Ok(resolved) = std::fs::canonicalize(parent) {
876 let mut out = resolved;
877 for name in suffix.iter().rev() {
878 out.push(name);
879 }
880 return out;
881 }
882 cursor = parent;
883 }
884 }
885
886 /// Case-fold when — and only when — the platform's default filesystem is
887 /// case-insensitive. Folding on Linux would deny `~/.SSH` on a system where
888 /// that is a genuinely different directory.
889 fn fold_case_str(text: &str) -> String {
890 if cfg!(any(target_os = "macos", target_os = "windows")) {
891 text.to_lowercase()
892 } else {
893 text.to_string()
894 }
895 }
896
897 fn normalize_windows_verbatim_prefix(text: &str) -> std::borrow::Cow<'_, str> {
898 if text
899 .get(..8)
900 .is_some_and(|prefix| prefix.eq_ignore_ascii_case(r"\\?\unc\"))
901 {
902 return std::borrow::Cow::Owned(format!(r"\\{}", &text[8..]));
903 }
904 if let Some(rest) = text.strip_prefix(r"\\?\")
905 && rest.len() >= 2
906 && rest.as_bytes()[0].is_ascii_alphabetic()
907 && rest.as_bytes()[1] == b':'
908 {
909 return std::borrow::Cow::Owned(rest.to_string());
910 }
911 std::borrow::Cow::Borrowed(text)
912 }
913
914 fn fold_component(component: &std::ffi::OsStr) -> OsString {
915 match component.to_str() {
916 Some(text) => {
917 let normalized = if cfg!(windows) {
918 normalize_windows_verbatim_prefix(text)
919 } else {
920 std::borrow::Cow::Borrowed(text)
921 };
922 OsString::from(fold_case_str(normalized.as_ref()))
923 }
924 None => component.to_os_string(),
925 }
926 }
927
928 /// True when `candidate` is `root` itself or lives beneath it.
929 ///
930 /// Compared component by component, not by string prefix: `~/.awsome` must not
931 /// match the `~/.aws` rule, and `starts_with` on the raw strings says it does.
932 /// (`Path::starts_with` is already component-wise; the case folding is what
933 /// forces the manual walk.)
934 pub fn path_is_within(candidate: &Path, root: &Path) -> bool {
935 let mut root_components = root.components().map(|c| fold_component(c.as_os_str()));
936 let mut candidate_components = candidate
937 .components()
938 .map(|c| fold_component(c.as_os_str()));
939
940 loop {
941 match (root_components.next(), candidate_components.next()) {
942 (None, _) => return true,
943 (Some(_), None) => return false,
944 (Some(r), Some(c)) if r == c => {}
945 (Some(_), Some(_)) => return false,
946 }
947 }
948 }
949
950 pub fn paths_match(left: &Path, right: &Path) -> bool {
951 let mut left_components = left.components().map(|c| fold_component(c.as_os_str()));
952 let mut right_components = right.components().map(|c| fold_component(c.as_os_str()));
953
954 loop {
955 match (left_components.next(), right_components.next()) {
956 (None, None) => return true,
957 (Some(l), Some(r)) if l == r => {}
958 _ => return false,
959 }
960 }
961 }
962
963 #[cfg(test)]
964 mod tests {
965 use super::*;
966
967 fn denylist_for(paths: &[PathBuf]) -> ReadDenylist {
968 ReadDenylist::build(false, paths, &[])
969 }
970
971 // Two tests below move the process-wide cwd. libtest runs tests as
972 // parallel threads of one process, so they take this lock; nextest runs
973 // each test in its own process and never contends for it.
974 static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
975
976 fn lock_cwd() -> std::sync::MutexGuard<'static, ()> {
977 CWD_LOCK
978 .lock()
979 .unwrap_or_else(|poisoned| poisoned.into_inner())
980 }
981
982 #[test]
983 fn empty_denylist_denies_nothing_and_reports_full_disk_read() {
984 let list = ReadDenylist::empty();
985 assert!(list.is_empty());
986 assert!(list.check(Path::new("/etc/hosts")).is_ok());
987 }
988
989 #[test]
990 fn direct_path_under_a_denied_root_is_refused() {
991 let secret = tempfile::tempdir().expect("tempdir");
992 let file = secret.path().join("id_ed25519");
993 std::fs::write(&file, "KEY").expect("write");
994
995 let list = denylist_for(&[secret.path().to_path_buf()]);
996 let denial = list.check(&file).expect_err("must deny");
997 assert_eq!(denial.requested, file);
998 assert!(!denial.via_symlink);
999 }
1000
1001 #[test]
1002 fn sibling_with_a_shared_string_prefix_is_not_denied() {
1003 // `~/.awsome` must not be caught by the `~/.aws` rule. This is the bug
1004 // a naive string `starts_with` ships with.
1005 let tmp = tempfile::tempdir().expect("tempdir");
1006 let denied = tmp.path().join("aws");
1007 let innocent = tmp.path().join("awsome");
1008 std::fs::create_dir_all(&denied).expect("mkdir");
1009 std::fs::create_dir_all(&innocent).expect("mkdir");
1010 let note = innocent.join("notes.md");
1011 std::fs::write(&note, "notes").expect("write");
1012
1013 let list = denylist_for(std::slice::from_ref(&denied));
1014 assert!(
1015 list.check(&note).is_ok(),
1016 "sibling prefix must stay readable"
1017 );
1018 }
1019
1020 #[test]
1021 fn dot_dot_traversal_out_of_the_workspace_is_refused() {
1022 let tmp = tempfile::tempdir().expect("tempdir");
1023 let secret_dir = tmp.path().join("secrets");
1024 let workspace = tmp.path().join("workspace");
1025 std::fs::create_dir_all(&secret_dir).expect("mkdir");
1026 std::fs::create_dir_all(&workspace).expect("mkdir");
1027 let secret = secret_dir.join("token");
1028 std::fs::write(&secret, "TOKEN").expect("write");
1029
1030 let list = denylist_for(std::slice::from_ref(&secret_dir));
1031 let sneaky = workspace.join("..").join("secrets").join("token");
1032 list.check(&sneaky)
1033 .expect_err("`..` must not walk around the deny-list");
1034 }
1035
1036 #[test]
1037 #[cfg(unix)]
1038 fn symlink_pointing_into_a_denied_tree_is_refused_by_its_target() {
1039 let tmp = tempfile::tempdir().expect("tempdir");
1040 let secret_dir = tmp.path().join("secrets");
1041 let workspace = tmp.path().join("workspace");
1042 std::fs::create_dir_all(&secret_dir).expect("mkdir");
1043 std::fs::create_dir_all(&workspace).expect("mkdir");
1044 let secret = secret_dir.join("id_rsa");
1045 std::fs::write(&secret, "KEY").expect("write");
1046
1047 let link = workspace.join("harmless.txt");
1048 std::os::unix::fs::symlink(&secret, &link).expect("symlink");
1049
1050 let list = denylist_for(std::slice::from_ref(&secret_dir));
1051 let denial = list.check(&link).expect_err("symlink must not walk around");
1052 assert!(denial.via_symlink, "denial should report the symlink hop");
1053 assert!(denial.message("read_file").contains("symlink"));
1054 }
1055
1056 #[test]
1057 #[cfg(unix)]
1058 fn symlinked_parent_directory_is_refused() {
1059 // The link is on a *directory* in the middle of the path, not the leaf.
1060 let tmp = tempfile::tempdir().expect("tempdir");
1061 let secret_dir = tmp.path().join("secrets");
1062 let workspace = tmp.path().join("workspace");
1063 std::fs::create_dir_all(&secret_dir).expect("mkdir");
1064 std::fs::create_dir_all(&workspace).expect("mkdir");
1065 std::fs::write(secret_dir.join("token"), "TOKEN").expect("write");
1066
1067 let link_dir = workspace.join("data");
1068 std::os::unix::fs::symlink(&secret_dir, &link_dir).expect("symlink");
1069
1070 let list = denylist_for(std::slice::from_ref(&secret_dir));
1071 list.check(&link_dir.join("token"))
1072 .expect_err("symlinked parent must not walk around");
1073 }
1074
1075 /// F5 regression: `..` must be applied by the OS *after* resolving each
1076 /// symlink component, never folded lexically first. With
1077 /// `pub/link -> denied/sub`, the path `pub/link/../secret` really reads
1078 /// `denied/secret`; the old lexical-first fold produced `pub/secret` and
1079 /// the check returned Ok while the read sailed through.
1080 #[test]
1081 #[cfg(unix)]
1082 fn dot_dot_through_a_symlink_is_applied_after_symlink_resolution() {
1083 let tmp = tempfile::tempdir().expect("tempdir");
1084 let denied = tmp.path().join("denied");
1085 std::fs::create_dir_all(denied.join("sub")).expect("mkdir");
1086 std::fs::write(denied.join("sub").join("secret"), "TOKEN").expect("write");
1087 let pub_dir = tmp.path().join("pub");
1088 std::fs::create_dir_all(&pub_dir).expect("mkdir");
1089 std::os::unix::fs::symlink(denied.join("sub"), pub_dir.join("link")).expect("symlink");
1090
1091 let list = denylist_for(std::slice::from_ref(&denied));
1092 list.check(&pub_dir.join("link").join("..").join("secret"))
1093 .expect_err("`..` through a symlink must not walk around the deny-list");
1094
1095 // Same evasion with a not-yet-existing leaf: the direct canonicalize
1096 // fails, so the raw-ancestor walk has to carry the check.
1097 list.check(&pub_dir.join("link").join("..").join("not-yet"))
1098 .expect_err("the raw-ancestor walk must resolve the symlink before `..`");
1099 }
1100
1101 /// A chain of symlinks (link → link → secret) must be followed to the
1102 /// final target, not just one hop. Integrator defeat attempt: indirection
1103 /// depth is not a bypass.
1104 #[test]
1105 #[cfg(unix)]
1106 fn symlink_chains_resolve_to_the_denied_target() {
1107 let tmp = tempfile::tempdir().expect("tempdir");
1108 let denied = tmp.path().join("denied");
1109 std::fs::create_dir_all(&denied).expect("mkdir");
1110 std::fs::write(denied.join("id_ed25519"), "KEY").expect("write");
1111 std::os::unix::fs::symlink(denied.join("id_ed25519"), tmp.path().join("hop2"))
1112 .expect("symlink");
1113 std::os::unix::fs::symlink(tmp.path().join("hop2"), tmp.path().join("hop1"))
1114 .expect("symlink");
1115 let list = denylist_for(std::slice::from_ref(&denied));
1116 list.check(&tmp.path().join("hop1"))
1117 .expect_err("a symlink chain must resolve to the denied target");
1118 }
1119
1120 /// A relative read issued with the process cwd INSIDE a denied subtree
1121 /// must be refused: the absolutization against cwd lands under the rule.
1122 /// (Serialized with the other cwd-moving test; restores cwd regardless.)
1123 #[test]
1124 fn relative_read_from_inside_a_denied_tree_is_refused() {
1125 let _cwd = lock_cwd();
1126 let tmp = tempfile::tempdir().expect("tempdir");
1127 let denied = tmp.path().join("denied");
1128 std::fs::create_dir_all(&denied).expect("mkdir");
1129 std::fs::write(denied.join("id_ed25519"), "KEY").expect("write");
1130 let prior = std::env::current_dir().expect("cwd");
1131 struct Restore(std::path::PathBuf);
1132 impl Drop for Restore {
1133 fn drop(&mut self) {
1134 let _ = std::env::set_current_dir(&self.0);
1135 }
1136 }
1137 let _restore = Restore(prior);
1138 std::env::set_current_dir(&denied).expect("chdir into the denied tree");
1139
1140 let list = denylist_for(std::slice::from_ref(&denied));
1141 list.check(Path::new("id_ed25519"))
1142 .expect_err("a relative read from inside the denied tree must be refused");
1143 list.check(Path::new("./id_ed25519"))
1144 .expect_err("the dotted spelling must not differ from the bare one");
1145 }
1146
1147 /// Separator noise must not dodge matching: repeated slashes collapse and a
1148 /// trailing slash never changes which subtree a path belongs to.
1149 #[test]
1150 fn double_slash_and_trailing_slash_variants_are_refused() {
1151 let tmp = tempfile::tempdir().expect("tempdir");
1152 let secret_dir = tmp.path().join("secrets");
1153 std::fs::create_dir_all(&secret_dir).expect("mkdir");
1154 std::fs::write(secret_dir.join("token"), "TOKEN").expect("write");
1155
1156 let list = denylist_for(std::slice::from_ref(&secret_dir));
1157 let root = secret_dir.parent().expect("parent");
1158 let double = PathBuf::from(format!("{}/secrets//token", root.display()));
1159 list.check(&double)
1160 .expect_err("double slashes must not walk around the deny-list");
1161 let trailing = PathBuf::from(format!("{}/secrets/", root.display()));
1162 list.check(&trailing)
1163 .expect_err("a trailing slash must not walk around the deny-list");
1164 // And the `.env` filename rule is name-based, so a trailing slash on it
1165 // still leaves the file name intact.
1166 let list = ReadDenylist::build(true, &[], &[]);
1167 let env_dir = tmp.path().join("nested");
1168 std::fs::create_dir_all(&env_dir).expect("mkdir");
1169 list.check(&env_dir.join(".env"))
1170 .unwrap_err_or_panic("`.env` under any directory is denied by name");
1171 }
1172
1173 /// The real attack spelling on macOS: `~/.SSH/ID_RSA` on a case-insensitive
1174 /// filesystem is `~/.ssh/id_rsa`. (The tempdir sibling above covers the
1175 /// mechanism; this one pins the default rule itself.)
1176 #[cfg(target_os = "macos")]
1177 #[test]
1178 fn macos_case_variation_of_the_default_ssh_rule_is_refused() {
1179 let Some(home) = dirs::home_dir() else {
1180 return;
1181 };
1182 if !home.join(".ssh").is_dir() {
1183 // Nothing to match against; skip rather than fake a pass.
1184 return;
1185 }
1186 let list = ReadDenylist::build(true, &[], &[]);
1187 list.check(&home.join(".SSH").join("ID_RSA"))
1188 .expect_err("~/.SSH/ID_RSA is ~/.ssh/id_rsa on a case-insensitive filesystem");
1189 }
1190
1191 #[cfg(any(target_os = "macos", target_os = "windows"))]
1192 #[test]
1193 fn case_variation_is_refused_on_case_insensitive_filesystems() {
1194 let tmp = tempfile::tempdir().expect("tempdir");
1195 let secret_dir = tmp.path().join("Secrets");
1196 std::fs::create_dir_all(&secret_dir).expect("mkdir");
1197 std::fs::write(secret_dir.join("id_rsa"), "KEY").expect("write");
1198
1199 let list = denylist_for(std::slice::from_ref(&secret_dir));
1200 let shouted = tmp.path().join("SECRETS").join("ID_RSA");
1201 list.check(&shouted)
1202 .expect_err("case variation must not walk around on a case-insensitive FS");
1203 }
1204
1205 #[test]
1206 fn nonexistent_path_under_a_denied_root_is_still_refused() {
1207 // canonicalize() fails here; the deepest-existing-ancestor walk is what
1208 // has to carry the check.
1209 let tmp = tempfile::tempdir().expect("tempdir");
1210 let secret_dir = tmp.path().join("secrets");
1211 std::fs::create_dir_all(&secret_dir).expect("mkdir");
1212
1213 let list = denylist_for(std::slice::from_ref(&secret_dir));
1214 list.check(&secret_dir.join("not-created-yet").join("key"))
1215 .expect_err("a not-yet-existing path under a denied root must still be denied");
1216 }
1217
1218 #[test]
1219 fn env_files_are_denied_but_committed_placeholders_are_not() {
1220 let list = ReadDenylist::build(true, &[], &[]);
1221 let tmp = tempfile::tempdir().expect("tempdir");
1222
1223 for denied in [".env", ".env.local", ".env.production"] {
1224 let path = tmp.path().join(denied);
1225 list.check(&path)
1226 .unwrap_err_or_panic(&format!("{denied} should be denied"));
1227 }
1228 for allowed in [".env.example", ".env.sample", ".env.template", ".env.dist"] {
1229 let path = tmp.path().join(allowed);
1230 assert!(
1231 list.check(&path).is_ok(),
1232 "{allowed} is a committed placeholder and must stay readable"
1233 );
1234 }
1235 }
1236
1237 /// F3 regression: exempting `.env` used to compare a *normalized absolute*
1238 /// path against the bare string `.env`, which could never match — the
1239 /// exemption was dead code. The rule is name-shaped, so any exempt entry
1240 /// whose file name is `.env` must disable it.
1241 #[test]
1242 fn exempting_env_by_name_disables_the_env_file_rule() {
1243 let tmp = tempfile::tempdir().expect("tempdir");
1244 let env_file = tmp.path().join(".env");
1245 std::fs::write(&env_file, "SECRET=1\n").expect("write");
1246
1247 // Bare `.env` — the spelling the docs advertise.
1248 let list = ReadDenylist::build(true, &[], &[PathBuf::from(".env")]);
1249 assert!(
1250 list.check(&env_file).is_ok(),
1251 "exempting `.env` must disable the env-file rule everywhere"
1252 );
1253
1254 // Any path ending in `/.env` — e.g. `~/.env` or `project/.env`.
1255 let home_spelled = dirs::home_dir().map(|h| h.join(".env"));
1256 let exempt_path = home_spelled.as_deref().unwrap_or(env_file.as_path());
1257 let list = ReadDenylist::build(true, &[], &[exempt_path.to_path_buf()]);
1258 assert!(
1259 list.check(&env_file).is_ok(),
1260 "an exempt entry named `.env` must disable the whole env-file rule"
1261 );
1262
1263 // An exemption for anything else must leave the rule armed.
1264 let unrelated = tmp.path().join("notes");
1265 let list = ReadDenylist::build(true, &[], std::slice::from_ref(&unrelated));
1266 list.check(&env_file)
1267 .unwrap_err_or_panic("an unrelated exemption must not reopen `.env` files");
1268 }
1269
1270 #[test]
1271 fn ordinary_source_files_stay_readable_under_the_defaults() {
1272 let list = ReadDenylist::build(true, &[], &[]);
1273 let tmp = tempfile::tempdir().expect("tempdir");
1274 for ordinary in [
1275 "main.rs",
1276 "Cargo.toml",
1277 "README.md",
1278 ".gitignore",
1279 ".env.example",
1280 ] {
1281 let path = tmp.path().join(ordinary);
1282 assert!(
1283 list.check(&path).is_ok(),
1284 "{ordinary} must stay readable — a coding agent has to read the source tree"
1285 );
1286 }
1287 }
1288
1289 #[test]
1290 fn defaults_cover_ssh_and_cloud_credential_stores() {
1291 let Some(home) = dirs::home_dir() else {
1292 return;
1293 };
1294 let list = ReadDenylist::build(true, &[], &[]);
1295 for rel in [
1296 ".ssh/id_ed25519",
1297 ".aws/credentials",
1298 ".config/gcloud/x",
1299 ".netrc",
1300 ] {
1301 list.check(&home.join(rel))
1302 .unwrap_err_or_panic(&format!("~/{rel} should be denied by default"));
1303 }
1304 }
1305
1306 #[test]
1307 fn exempt_narrows_the_defaults_but_never_an_explicit_deny() {
1308 let Some(home) = dirs::home_dir() else {
1309 return;
1310 };
1311 let ssh = home.join(".ssh");
1312
1313 // Exempting the default rule reopens it.
1314 let exempted = ReadDenylist::build(true, &[], std::slice::from_ref(&ssh));
1315 assert!(
1316 exempted.check(&ssh.join("id_rsa")).is_ok(),
1317 "an exempted default must be readable again"
1318 );
1319
1320 // The same exemption must NOT reopen a path the user explicitly denied.
1321 let both =
1322 ReadDenylist::build(true, std::slice::from_ref(&ssh), std::slice::from_ref(&ssh));
1323 both.check(&ssh.join("id_rsa"))
1324 .unwrap_err_or_panic("deny must win over allow");
1325 }
1326
1327 #[test]
1328 fn defaults_can_be_turned_off_entirely() {
1329 let Some(home) = dirs::home_dir() else {
1330 return;
1331 };
1332 let list = ReadDenylist::build(false, &[], &[]);
1333 assert!(list.is_empty());
1334 assert!(list.check(&home.join(".ssh/id_rsa")).is_ok());
1335 }
1336
1337 #[test]
1338 fn subtree_paths_feed_the_os_wrappers_and_omit_the_filename_rule() {
1339 let tmp = tempfile::tempdir().expect("tempdir");
1340 let list = ReadDenylist::build(false, &[tmp.path().to_path_buf()], &[]);
1341 let paths = list.subtree_paths();
1342 assert_eq!(paths.len(), 1);
1343 assert_eq!(paths[0], normalize_lexically(tmp.path()));
1344 }
1345
1346 #[test]
1347 #[cfg(unix)]
1348 fn denial_message_names_the_rule_without_echoing_the_resolved_secret_path() {
1349 let tmp = tempfile::tempdir().expect("tempdir");
1350 let secret_dir = tmp.path().join("secrets");
1351 let workspace = tmp.path().join("workspace");
1352 std::fs::create_dir_all(&secret_dir).expect("mkdir");
1353 std::fs::create_dir_all(&workspace).expect("mkdir");
1354 std::fs::write(secret_dir.join("id_rsa"), "KEY").expect("write");
1355
1356 let link = workspace.join("notes.txt");
1357 std::os::unix::fs::symlink(secret_dir.join("id_rsa"), &link).expect("symlink");
1358
1359 let list = denylist_for(std::slice::from_ref(&secret_dir));
1360 let message = list.check(&link).expect_err("deny").message("read_file");
1361 assert!(message.contains("notes.txt"), "{message}");
1362 assert!(
1363 !message.contains("id_rsa"),
1364 "the refusal must not hand back the secret's real location: {message}"
1365 );
1366 assert!(
1367 message.contains("sandbox_read_denylist_exempt"),
1368 "{message}"
1369 );
1370 }
1371
1372 #[test]
1373 fn root_parent_traversal_does_not_escape_above_root() {
1374 // Spell the traversal from the current drive/root so the assertion
1375 // holds on Windows too: there `/../../etc` resolves against the cwd's
1376 // drive and normalizes to `D:\etc`, not a bare `/etc`.
1377 let cwd = std::env::current_dir().expect("cwd");
1378 let root: PathBuf = cwd
1379 .components()
1380 .take_while(|c| matches!(c, Component::Prefix(_) | Component::RootDir))
1381 .collect();
1382 let traversal = root.join("..").join("..").join("etc");
1383 assert_eq!(normalize_lexically(&traversal), root.join("etc"));
1384 if cfg!(unix) {
1385 assert_eq!(
1386 normalize_lexically(Path::new("/../../etc")),
1387 PathBuf::from("/etc")
1388 );
1389 }
1390 }
1391
1392 /// Hosted macOS CI hands `tempfile` a `/var/folders/...` directory that is
1393 /// really `/private/var/folders/...`; `canonicalize` and `current_dir`
1394 /// return the resolved spelling while the rule was written against the
1395 /// literal one, and no symlink test above fired. Build that shape
1396 /// explicitly so the regression is caught on every host, not only where
1397 /// `$TMPDIR` happens to be a symlink.
1398 #[test]
1399 #[cfg(unix)]
1400 fn rule_spelled_through_a_symlinked_root_matches_the_resolved_spelling() {
1401 let _cwd = lock_cwd();
1402 let tmp = tempfile::tempdir().expect("tempdir");
1403 let real_root = tmp.path().join("real");
1404 let denied = real_root.join("secrets");
1405 std::fs::create_dir_all(&denied).expect("mkdir");
1406 std::fs::write(denied.join("id_rsa"), "KEY").expect("write");
1407 let alias_root = tmp.path().join("alias");
1408 std::os::unix::fs::symlink(&real_root, &alias_root).expect("symlink");
1409
1410 // The rule names the alias, the way a `/var/...` tempdir rule does.
1411 let list = denylist_for(&[alias_root.join("secrets")]);
1412
1413 // A read spelled through the real directory is the same file.
1414 list.check(&denied.join("id_rsa"))
1415 .expect_err("the resolved spelling of a denied tree must be refused");
1416 // An innocuous symlink resolves to the real spelling, never the alias.
1417 let link = tmp.path().join("notes.txt");
1418 std::os::unix::fs::symlink(denied.join("id_rsa"), &link).expect("symlink");
1419 list.check(&link)
1420 .expect_err("a symlink into the denied tree must be refused by its target");
1421 // A relative read from inside it absolutizes against the real cwd.
1422 let prior = std::env::current_dir().expect("cwd");
1423 struct Restore(std::path::PathBuf);
1424 impl Drop for Restore {
1425 fn drop(&mut self) {
1426 let _ = std::env::set_current_dir(&self.0);
1427 }
1428 }
1429 let _restore = Restore(prior);
1430 std::env::set_current_dir(&denied).expect("chdir into the denied tree");
1431 list.check(Path::new("id_rsa"))
1432 .expect_err("a relative read from inside the denied tree must be refused");
1433 // And the innocent sibling of the real directory stays readable.
1434 let sibling = real_root.join("notes.md");
1435 std::fs::write(&sibling, "notes").expect("write");
1436 assert!(list.check(&sibling).is_ok(), "sibling must stay readable");
1437 }
1438
1439 /// A denial names the path as requested, so on macOS it may say
1440 /// `/private/etc/sudoers`; exempting that spelling must reopen the
1441 /// `/etc/sudoers` rule it resolves from, and the literal spelling must
1442 /// keep working too. Unrelated defaults stay armed either way.
1443 #[cfg(target_os = "macos")]
1444 #[test]
1445 fn exempting_either_spelling_of_a_symlinked_default_rule_reopens_it() {
1446 for exempt in ["/private/etc/sudoers", "/etc/sudoers"] {
1447 let list = ReadDenylist::build(true, &[], &[PathBuf::from(exempt)]);
1448 assert!(
1449 list.check(Path::new("/etc/sudoers")).is_ok(),
1450 "exempting {exempt} must reopen the literal spelling"
1451 );
1452 assert!(
1453 list.check(Path::new("/private/etc/sudoers")).is_ok(),
1454 "exempting {exempt} must reopen the resolved spelling"
1455 );
1456 list.check(Path::new("/private/etc/ssh/ssh_host_ed25519_key"))
1457 .unwrap_err_or_panic("an unrelated default rule stays armed");
1458 }
1459 }
1460
1461 /// On macOS `/etc` is a symlink to `/private/etc`, so the machine-wide
1462 /// default rules were readable under their real names.
1463 #[cfg(target_os = "macos")]
1464 #[test]
1465 fn macos_private_spelling_of_a_machine_wide_rule_is_refused() {
1466 let list = ReadDenylist::build(true, &[], &[]);
1467 list.check(Path::new("/private/etc/sudoers"))
1468 .unwrap_err_or_panic("/private/etc/sudoers is /etc/sudoers");
1469 list.check(Path::new("/private/etc/ssh/ssh_host_ed25519_key"))
1470 .unwrap_err_or_panic("/private/etc/ssh is /etc/ssh");
1471 assert!(
1472 list.check(Path::new("/private/etc/hosts")).is_ok(),
1473 "/etc/hosts is not a credential store"
1474 );
1475 }
1476
1477 #[test]
1478 fn normalize_windows_verbatim_prefix_handles_drive_and_unc() {
1479 assert_eq!(normalize_windows_verbatim_prefix(r"\\?\C:"), "C:");
1480 assert_eq!(normalize_windows_verbatim_prefix(r"\\?\d:"), "d:");
1481 assert_eq!(
1482 normalize_windows_verbatim_prefix(r"\\?\UNC\server\share"),
1483 r"\\server\share"
1484 );
1485 assert_eq!(
1486 normalize_windows_verbatim_prefix(r"\\?\unc\server\share"),
1487 r"\\server\share"
1488 );
1489 assert_eq!(
1490 normalize_windows_verbatim_prefix(r"\\?\Unc\server\share"),
1491 r"\\server\share"
1492 );
1493 assert_eq!(normalize_windows_verbatim_prefix("C:"), "C:");
1494 assert_eq!(
1495 normalize_windows_verbatim_prefix(r"\\?\Pipe\demo"),
1496 r"\\?\Pipe\demo"
1497 );
1498 }
1499
1500 #[cfg(windows)]
1501 #[test]
1502 fn windows_verbatim_prefix_matches_dos_drive_and_unc_deny_rules() {
1503 assert!(path_is_within(
1504 Path::new(r"\\?\C:\Work\Secret\id_rsa"),
1505 Path::new(r"c:\work\secret"),
1506 ));
1507 assert!(paths_match(
1508 Path::new(r"\\?\C:\Work\Secret\id_rsa"),
1509 Path::new(r"c:\work\secret\id_rsa"),
1510 ));
1511 assert!(path_is_within(
1512 Path::new(r"\\?\UNC\Server\Share\Secret\token"),
1513 Path::new(r"\\server\share\secret"),
1514 ));
1515 let list = denylist_for(&[PathBuf::from(r"Z:\nonexistent-secret-root")]);
1516 list.check(Path::new(r"\\?\z:\nonexistent-secret-root\key.pem"))
1517 .unwrap_err_or_panic("verbatim Windows path must match non-verbatim deny rule");
1518 }
1519
1520 // Small helper so the intent of a "must be denied" assertion reads clearly.
1521 trait ExpectDenied {
1522 fn unwrap_err_or_panic(self, message: &str);
1523 }
1524 impl ExpectDenied for Result<(), ReadDenial> {
1525 fn unwrap_err_or_panic(self, message: &str) {
1526 assert!(self.is_err(), "{message}");
1527 }
1528 }
1529 }
1530
1530 lines RUST