trusty_code/paths/mod.rs
1//! Trusty Code's own configuration and state layout (#5426, epic #2892).
2//!
3//! Why: every discovery site in this crate hard-coded `.claude/` — the agents
4//! directory, the skills directory, the plugin tree, `settings.json`, and the
5//! project context file each joined that literal themselves. That made
6//! Claude Code's directory the source of truth for a product that is not Claude
7//! Code: a clean project could not install or run without a `.claude/` tree, and
8//! nothing stopped Trusty Code writing INTO another product's directory. #5426
9//! inverts the relationship. `<project>/.trusty-code/` is where Trusty Code
10//! reads and — critically — the ONLY place it writes; `.claude/` (and the older
11//! `.open-mpm/`) stay readable as compatibility INPUTS, never as write targets.
12//!
13//! What: one resolver, [`resolve_project_entry`], that every discovery site
14//! calls instead of joining a literal. It walks [`SEARCH_ROOTS`] in order and
15//! reports the winning source ([`ConfigSource`]) alongside the path, so
16//! diagnostics can answer "which directory won, and what else was tried?"
17//! without re-deriving the rule. [`native_config_dir`] and
18//! [`check_native_write_target`] are the write half: a path that is not beneath
19//! `<project>/.trusty-code/` — including one that reaches outside it through a
20//! symlink — is refused rather than written. [`private_state`] owns the private
21//! mutable half (`~/.trusty-code/`, mode `0700`), and [`import`] owns the
22//! deterministic, non-overwriting legacy import from `.claude/`.
23//!
24//! **Precedence, and where it is documented.** The order is
25//! `.trusty-code/` → `.claude/` → `.open-mpm/`, then a default that names
26//! `.trusty-code/` even when nothing exists yet. The operator-facing statement
27//! of that rule, including the fallback and warning behaviour, lives in
28//! [the crate README](../../README.md#configuration-layout-trusty-code) — this
29//! module is its implementation, not a second specification.
30//!
31//! Test: `paths::tests::*`, `paths::private_state_tests::*`,
32//! `paths::import_tests::*`.
33//!
34//! Every link below is written as a `crate::paths::…` reference definition
35//! rather than a bare `[`name`]`. This module carries outer `///` docs at its
36//! `pub mod paths;` declaration in `lib.rs` as well as these inner `//!` docs,
37//! and rustdoc resolves the merged block in the scope of its first fragment —
38//! the crate root — where none of these names exist. See #7001.
39//!
40//! [`resolve_project_entry`]: crate::paths::resolve_project_entry
41//! [`SEARCH_ROOTS`]: crate::paths::SEARCH_ROOTS
42//! [`ConfigSource`]: crate::paths::ConfigSource
43//! [`native_config_dir`]: crate::paths::native_config_dir
44//! [`check_native_write_target`]: crate::paths::check_native_write_target
45//! [`private_state`]: crate::paths::private_state
46//! [`import`]: crate::paths::import
47
48use std::path::{Path, PathBuf};
49
50pub mod import;
51pub mod private_state;
52pub mod write_dir;
53
54/// Trusty Code's own project configuration directory name.
55///
56/// Why: named once so the convention cannot drift to `.trusty_code` /
57/// `.trustycode` at a second call site.
58/// What: `".trusty-code"` — both the project-config directory under a project
59/// root and (via [`private_state`]) the private state directory under `$HOME`,
60/// mirroring trusty-mpm's `.trusty-mpm` precedent.
61/// Test: `paths::tests::native_config_dir_is_always_trusty_code`.
62pub const TRUSTY_CODE_DIRNAME: &str = ".trusty-code";
63
64/// Claude Code's project configuration directory name.
65///
66/// Why: a compatibility INPUT — read when Trusty Code's own directory has not
67/// been created yet, never written to. See [`check_native_write_target`].
68/// What: `".claude"`.
69/// Test: `paths::tests::falls_back_to_claude_when_trusty_code_absent`.
70pub const CLAUDE_COMPAT_DIRNAME: &str = ".claude";
71
72/// The pre-Claude-Code open-mpm configuration directory name.
73///
74/// Why: `agents::locate_agents_dir` already honoured it; dropping it here would
75/// silently break a project that still uses it.
76/// What: `".open-mpm"`.
77/// Test: `paths::tests::falls_back_to_open_mpm_when_neither_native_nor_claude`.
78pub const OPEN_MPM_LEGACY_DIRNAME: &str = ".open-mpm";
79
80/// The search order every project-scoped lookup walks, highest precedence first.
81///
82/// Why: one ordered table rather than a chain of `if exists` blocks repeated per
83/// call site — the bug #5426 exists to remove.
84/// What: `.trusty-code` (native) → `.claude` (compatibility) → `.open-mpm`
85/// (legacy), each paired with the [`ConfigSource`] it resolves to.
86/// Test: `paths::tests::precedence_prefers_trusty_code_over_claude`.
87pub const SEARCH_ROOTS: &[(&str, ConfigSource)] = &[
88 (TRUSTY_CODE_DIRNAME, ConfigSource::TrustyCode),
89 (CLAUDE_COMPAT_DIRNAME, ConfigSource::ClaudeCompat),
90 (OPEN_MPM_LEGACY_DIRNAME, ConfigSource::OpenMpmLegacy),
91];
92
93/// Which configuration root a resolved path came from.
94///
95/// Why: "the winning source" is a diagnostic every CLI and log line needs, and
96/// deriving it back out of a `PathBuf` by string-matching would be a second,
97/// drifting implementation of [`SEARCH_ROOTS`].
98/// What: one variant per search root, plus [`ConfigSource::Default`] for the
99/// case where nothing exists yet and the resolver names the native path anyway.
100/// Test: `paths::tests::precedence_prefers_trusty_code_over_claude`,
101/// `paths::tests::default_source_when_nothing_exists`.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum ConfigSource {
104 /// `<project>/.trusty-code/…` — Trusty Code's own directory.
105 TrustyCode,
106 /// `<project>/.claude/…` — Claude Code compatibility input.
107 ClaudeCompat,
108 /// `<project>/.open-mpm/…` — pre-Claude-Code legacy input.
109 OpenMpmLegacy,
110 /// Nothing exists yet; the path names the native location regardless.
111 Default,
112}
113
114impl ConfigSource {
115 /// A stable lowercase token for logs, JSON diagnostics, and CLI output.
116 ///
117 /// Why: the CLI and the log field must agree, and a `Debug` rendering is not
118 /// a wire contract.
119 /// What: `"trusty-code"`, `"claude"`, `"open-mpm"`, `"default"`.
120 /// Test: `paths::tests::source_tokens_are_stable`.
121 pub fn as_str(self) -> &'static str {
122 match self {
123 Self::TrustyCode => "trusty-code",
124 Self::ClaudeCompat => "claude",
125 Self::OpenMpmLegacy => "open-mpm",
126 Self::Default => "default",
127 }
128 }
129
130 /// Whether this source is Trusty Code's own directory.
131 ///
132 /// Why: a caller deciding whether to suggest `tcode config import` needs the
133 /// question answered once, here.
134 /// What: `true` for [`ConfigSource::TrustyCode`] and [`ConfigSource::Default`]
135 /// — both name a path beneath `.trusty-code/`.
136 /// Test: `paths::tests::source_tokens_are_stable`.
137 pub fn is_native(self) -> bool {
138 matches!(self, Self::TrustyCode | Self::Default)
139 }
140}
141
142/// What a project-scoped lookup resolved to, and what it had to skip to get there.
143///
144/// Why: a bare `PathBuf` cannot answer "did the native directory lose, and why?"
145/// — the exact question the fail-open warning and the `tcode config paths`
146/// diagnostic both need. Carrying `unreadable` as data (not only as a log line)
147/// is what makes the fail-open branch assertable in a test.
148/// What: the winning `path`, its [`ConfigSource`], and every candidate that
149/// existed but could not be read (each already logged at `warn`).
150/// Test: `paths::tests::unreadable_native_dir_falls_back_and_is_reported`.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct ResolvedConfig {
153 /// The resolved path. Exists unless `source` is [`ConfigSource::Default`].
154 pub path: PathBuf,
155 /// Which root won.
156 pub source: ConfigSource,
157 /// Candidates that existed but could not be read, in search order.
158 pub unreadable: Vec<PathBuf>,
159}
160
161/// Whether a lookup targets a directory or a single file.
162///
163/// Why: "unreadable" means different syscalls for the two — a directory is
164/// unreadable when `read_dir` fails, a file when `File::open` fails — and the
165/// fail-open warning must not fire merely because a file candidate is a
166/// directory or vice versa.
167/// What: the two shapes [`resolve_project_entry`] accepts.
168/// Test: `paths::tests::unreadable_native_dir_falls_back_and_is_reported`,
169/// `paths::tests::unreadable_settings_file_falls_back_and_is_reported`.
170#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub enum EntryKind {
172 /// A directory, e.g. `agents/`.
173 Dir,
174 /// A regular file, e.g. `settings.json`.
175 File,
176}
177
178/// Resolve one project-scoped configuration entry across [`SEARCH_ROOTS`].
179///
180/// Why: the single entry point #5426 replaces every hard-coded `.claude/` join
181/// with. Centralising it is what makes the precedence testable in one place and
182/// makes "a clean project with only `.trusty-code/` works" true everywhere at
183/// once rather than per call site.
184/// What: walks [`SEARCH_ROOTS`] in order and returns the first candidate that
185/// exists AND can be opened. A candidate that exists but cannot be opened is
186/// SKIPPED, recorded in [`ResolvedConfig::unreadable`], and logged at `warn`
187/// with the path tried — falling through to the next root rather than failing
188/// the run, because a harness that refuses to start over an unreadable optional
189/// config is worse than one that starts with less config and says so. When no
190/// candidate is usable, the returned path is `<project_root>/.trusty-code/<rel>`
191/// with source [`ConfigSource::Default`]: callers that need existence check for
192/// it themselves, and every WRITE goes to the native path regardless.
193/// Test: `paths::tests::precedence_prefers_trusty_code_over_claude`,
194/// `paths::tests::falls_back_to_claude_when_trusty_code_absent`,
195/// `paths::tests::default_source_when_nothing_exists`,
196/// `paths::tests::unreadable_native_dir_falls_back_and_is_reported`.
197pub fn resolve_project_entry(
198 project_root: &Path,
199 relative: &str,
200 kind: EntryKind,
201) -> ResolvedConfig {
202 let mut unreadable = Vec::new();
203 for (dirname, source) in SEARCH_ROOTS {
204 let candidate = project_root.join(dirname).join(relative);
205 match probe(&candidate, kind) {
206 Probe::Missing => continue,
207 Probe::Usable => {
208 return ResolvedConfig {
209 path: candidate,
210 source: *source,
211 unreadable,
212 };
213 }
214 Probe::Unreadable(err) => {
215 // #5426: fail open — an unreadable candidate must never abort the
216 // run, but it must never be silent either.
217 tracing::warn!(
218 path = %candidate.display(),
219 source = source.as_str(),
220 error = %err,
221 "trusty-code config path exists but could not be read; \
222 skipping it and falling back to the next configuration root"
223 );
224 unreadable.push(candidate);
225 }
226 }
227 }
228 ResolvedConfig {
229 path: native_child(project_root, relative),
230 source: ConfigSource::Default,
231 unreadable,
232 }
233}
234
235/// The outcome of testing one candidate path.
236enum Probe {
237 /// Nothing of the requested kind is there.
238 Missing,
239 /// Present and openable.
240 Usable,
241 /// Present but the open failed (permissions, a broken mount, a race).
242 Unreadable(std::io::Error),
243}
244
245/// Test one candidate path for existence and readability.
246///
247/// Why: `Path::exists` alone cannot distinguish "absent" from "present but
248/// unreadable", and only the second deserves a warning.
249/// What: for [`EntryKind::Dir`], a non-directory is `Missing` and a `read_dir`
250/// failure is `Unreadable`; for [`EntryKind::File`], a non-file is `Missing` and
251/// a `File::open` failure is `Unreadable`.
252/// Test: `paths::tests::unreadable_native_dir_falls_back_and_is_reported`,
253/// `paths::tests::unreadable_settings_file_falls_back_and_is_reported`.
254fn probe(candidate: &Path, kind: EntryKind) -> Probe {
255 match kind {
256 EntryKind::Dir => {
257 if !candidate.is_dir() {
258 return Probe::Missing;
259 }
260 match std::fs::read_dir(candidate) {
261 Ok(_) => Probe::Usable,
262 Err(e) => Probe::Unreadable(e),
263 }
264 }
265 EntryKind::File => {
266 if !candidate.is_file() {
267 return Probe::Missing;
268 }
269 match std::fs::File::open(candidate) {
270 Ok(_) => Probe::Usable,
271 Err(e) => Probe::Unreadable(e),
272 }
273 }
274 }
275}
276
277/// The agents directory for a project root.
278///
279/// Why: `agents::locate_agents_dir`'s two-way `.claude`/`.open-mpm` check
280/// predates `.trusty-code/` and is now one instance of the general rule.
281/// What: [`resolve_project_entry`] for `agents`, as a directory.
282/// Test: `paths::tests::agents_dir_prefers_trusty_code`.
283pub fn agents_dir(project_root: &Path) -> ResolvedConfig {
284 resolve_project_entry(project_root, "agents", EntryKind::Dir)
285}
286
287/// The skills directory for a project root.
288///
289/// Why: see [`agents_dir`] — `skills::locate_skills_dir` was pinned to
290/// `.claude/skills` exactly, which is precisely what #5426 unpins.
291/// What: [`resolve_project_entry`] for `skills`, as a directory.
292/// Test: `paths::tests::skills_dir_prefers_trusty_code`.
293pub fn skills_dir(project_root: &Path) -> ResolvedConfig {
294 resolve_project_entry(project_root, "skills", EntryKind::Dir)
295}
296
297/// The plugins directory for a project root.
298///
299/// Why: `plugins::discover_plugin_roots` joined `.claude/plugins` directly.
300/// What: [`resolve_project_entry`] for `plugins`, as a directory.
301/// Test: `paths::tests::plugins_dir_prefers_trusty_code`.
302pub fn plugins_dir(project_root: &Path) -> ResolvedConfig {
303 resolve_project_entry(project_root, "plugins", EntryKind::Dir)
304}
305
306/// The `settings.json` file for a project root.
307///
308/// Why: `mode::read_settings_json_mode` read `.claude/settings.json` directly,
309/// so a project with only `.trusty-code/` could not set `code_harness.mode`.
310/// What: [`resolve_project_entry`] for `settings.json`, as a file.
311/// Test: `paths::tests::settings_file_prefers_trusty_code`.
312pub fn settings_file(project_root: &Path) -> ResolvedConfig {
313 resolve_project_entry(project_root, SETTINGS_FILENAME, EntryKind::File)
314}
315
316/// The project-settings filename, shared by both configuration roots.
317///
318/// Why: `.trusty-code/settings.json` deliberately keeps Claude Code's filename
319/// and schema so an imported file needs no rewriting — the directory moves, the
320/// format does not.
321/// What: `"settings.json"`.
322/// Test: `paths::tests::settings_file_prefers_trusty_code`.
323pub const SETTINGS_FILENAME: &str = "settings.json";
324
325/// Trusty Code's own project configuration directory — the ONLY write target.
326///
327/// Why: [`resolve_project_entry`] may legitimately RESOLVE into `.claude/`, but
328/// a write there would make Trusty Code mutate another product's directory. The
329/// read path and the write path are therefore deliberately different functions.
330/// What: `<project_root>/.trusty-code`, unconditionally — never probed, never
331/// falling back.
332/// Test: `paths::tests::native_config_dir_is_always_trusty_code`.
333pub fn native_config_dir(project_root: &Path) -> PathBuf {
334 project_root.join(TRUSTY_CODE_DIRNAME)
335}
336
337/// A path beneath [`native_config_dir`].
338///
339/// Why: the write-side counterpart of [`resolve_project_entry`]'s `relative`.
340/// What: `<project_root>/.trusty-code/<relative>`.
341/// Test: `paths::tests::native_config_dir_is_always_trusty_code`.
342pub fn native_child(project_root: &Path, relative: &str) -> PathBuf {
343 native_config_dir(project_root).join(relative)
344}
345
346/// Why a candidate write target was refused.
347///
348/// Why: each refusal has a different fix — "you aimed at the wrong product's
349/// directory", "something on this path is a symlink out of the tree", "the
350/// directory you validated was swapped out from under the write" — and
351/// collapsing them into one string would hide which.
352/// What: [`WriteTargetError::CrossProduct`] for a path outside
353/// `<project>/.trusty-code/`; [`WriteTargetError::SymlinkEscape`] for a path
354/// whose nearest existing ancestor resolves outside it;
355/// [`WriteTargetError::Unpinned`] and [`WriteTargetError::Unpinnable`] for the
356/// handle-based writes in [`write_dir`] (#7779).
357/// Test: `paths::tests::write_to_claude_dir_is_refused`,
358/// `paths::tests::symlinked_native_subdir_escape_is_refused`,
359/// `paths::write_dir_tests::symlinked_component_is_refused_at_open`.
360#[derive(Debug, thiserror::Error, PartialEq, Eq)]
361pub enum WriteTargetError {
362 /// The path is not beneath the project's own `.trusty-code/` directory.
363 #[error(
364 "refusing to write to {path}: trusty-code writes only beneath {native_root} \
365 (another product's configuration directory is a read-only compatibility input)"
366 )]
367 CrossProduct {
368 /// The refused path.
369 path: PathBuf,
370 /// The only permitted write root.
371 native_root: PathBuf,
372 },
373 /// A component was a symlink, or stopped being the directory the handle was
374 /// opened on, at write time (#7779).
375 #[error(
376 "refusing to write to {path}: `{component}` is not the directory this write was \
377 validated against — a symlink or rename was swapped in. Nothing was written through it."
378 )]
379 Unpinned {
380 /// The refused path, as supplied.
381 path: PathBuf,
382 /// The component that is no longer the validated directory.
383 component: String,
384 },
385 /// The write target could not be pinned to a directory handle at all.
386 #[error("refusing to write to {path}: {detail}")]
387 Unpinnable {
388 /// The refused path, as supplied.
389 path: PathBuf,
390 /// The underlying reason the handle could not be established.
391 detail: String,
392 },
393 /// A symlink on the path resolves outside `.trusty-code/`.
394 #[error("refusing to write to {path}: it resolves to {resolved}, outside {native_root}")]
395 SymlinkEscape {
396 /// The refused path, as supplied.
397 path: PathBuf,
398 /// Where its nearest existing ancestor actually points.
399 resolved: PathBuf,
400 /// The only permitted write root.
401 native_root: PathBuf,
402 },
403}
404
405/// The one resolution of `<project>/.trusty-code` a pinned write is anchored on.
406///
407/// Why: #7779 round 2. `check_native_write_target` resolved `.trusty-code` and
408/// `write_dir::pin_native_root` resolved it AGAIN, and the descriptor came from
409/// the second resolution — so a swap between them pinned a directory the
410/// membership rule had never approved. Handing the resolved root back to the
411/// caller is what makes "the path validated is the path pinned" literal: there
412/// is no second resolution to disagree with the first.
413/// What: `Existing` carries the canonical `.trusty-code`, already proven to sit
414/// inside the canonical project root; `Absent` means nothing resolves there yet,
415/// so the caller creates it under the project root it canonicalises itself.
416/// Test: `paths::write_dir_tests::native_root_swapped_between_check_and_pin_never_reaches_victim`.
417pub(crate) enum AnchoredRoot {
418 /// `.trusty-code` resolves, and resolves inside the project. Pin THIS path.
419 Existing(PathBuf),
420 /// `.trusty-code` does not resolve; it has to be created.
421 Absent,
422}
423
424/// Decide membership and resolve the config root, in one pass.
425///
426/// Why: the anchoring rule ("a `.trusty-code` that is itself a symlink must
427/// still land inside the project", PR #6980's code-critic BLOCK) has exactly one
428/// implementation, and both the plan-only [`check_native_write_target`] and the
429/// pinning [`write_dir::NativeWriteDir::open`] read it from here.
430/// What: the lexical [`WriteTargetError::CrossProduct`] test, then a SINGLE
431/// `canonicalize` of `.trusty-code` whose result is both compared against the
432/// canonical project root and returned for the caller to pin. A `project_root`
433/// that cannot be canonicalised while `.trusty-code` does resolve fails CLOSED
434/// as [`WriteTargetError::SymlinkEscape`] — containment cannot be established.
435/// Test: `paths::tests::write_to_claude_dir_is_refused`,
436/// `paths::tests::symlinked_native_root_escape_is_refused`,
437/// `paths::write_dir_tests::symlinked_native_root_escape_is_refused_at_open`.
438pub(crate) fn anchor_native_root(
439 project_root: &Path,
440 path: &Path,
441) -> Result<AnchoredRoot, WriteTargetError> {
442 let native_root = native_config_dir(project_root);
443 if !path.starts_with(&native_root) {
444 return Err(WriteTargetError::CrossProduct {
445 path: path.to_path_buf(),
446 native_root,
447 });
448 }
449
450 let escape = |resolved: PathBuf| WriteTargetError::SymlinkEscape {
451 path: path.to_path_buf(),
452 resolved,
453 native_root: native_root.clone(),
454 };
455
456 // #5426: anchor the config root to the project before trusting it. Without
457 // this, a symlinked `.trusty-code` makes every later comparison vacuous.
458 // #7779: this is the ONLY place `.trusty-code` is resolved on the write
459 // path, so nothing can swap it between the check and the pin.
460 let Ok(canon_root) = native_root.canonicalize() else {
461 return Ok(AnchoredRoot::Absent);
462 };
463 let canon_project = project_root
464 .canonicalize()
465 .map_err(|_| escape(canon_root.clone()))?;
466 if !canon_root.starts_with(&canon_project) {
467 return Err(escape(canon_root));
468 }
469 Ok(AnchoredRoot::Existing(canon_root))
470}
471
472/// Refuse any write target that is not genuinely beneath `<project>/.trusty-code/`.
473///
474/// Why: "native project writes stay beneath `<project>/.trusty-code/`" is only a
475/// property if something enforces it, and a lexical `starts_with` does not: a
476/// symlink at `.trusty-code/agents -> ../../elsewhere` satisfies it while every
477/// write lands outside the tree.
478///
479/// Resolving the target alone is not enough either. The first version of this
480/// guard resolved the target AND the config root the same way and compared them
481/// to each other, so a `.trusty-code` that was ITSELF a symlink out of the
482/// project moved the goalposts with the target and approved every write
483/// (code-critic BLOCK, PR #6980). The root is therefore anchored to the project
484/// FIRST, and only then does the target get compared against it.
485///
486/// What: three checks, in order.
487/// 1. Lexical — `path` must start with [`native_config_dir`], else
488/// [`WriteTargetError::CrossProduct`].
489/// 2. Root anchoring — when `<project>/.trusty-code` resolves, it must
490/// canonicalise to somewhere inside the canonicalised `project_root`, else
491/// [`WriteTargetError::SymlinkEscape`]. A `project_root` that cannot itself be
492/// canonicalised fails CLOSED here: containment cannot be established, so the
493/// write is refused rather than assumed safe. Checks 1 and 2 live in
494/// [`anchor_native_root`], shared with the pinning path.
495/// 3. Target containment — the target's nearest EXISTING ancestor (the target
496/// itself is usually absent, since we are about to create it) must resolve
497/// inside that same anchored root.
498///
499/// With nothing on the path existing yet, no symlink can be redirecting it and
500/// check 1 is the whole answer.
501///
502/// **This decides MEMBERSHIP, and it is not how a write is authorised.** Its
503/// answer describes the tree as it was when it ran, so a caller that then writes
504/// through the same path string can be overtaken by a rename (#7779). Writers do
505/// not call this at all: [`write_dir::NativeWriteDir::open`] goes to
506/// [`anchor_native_root`] directly and pins the very path it returned, so there
507/// is no second resolution to be raced. Call this function only to classify a
508/// path without writing to it — the import PLAN does.
509/// Test: `paths::tests::write_to_native_dir_is_allowed`,
510/// `paths::tests::write_to_claude_dir_is_refused`,
511/// `paths::tests::write_outside_project_is_refused`,
512/// `paths::tests::symlinked_native_subdir_escape_is_refused`,
513/// `paths::tests::symlinked_native_root_escape_is_refused`.
514pub fn check_native_write_target(
515 project_root: &Path,
516 path: &Path,
517) -> Result<PathBuf, WriteTargetError> {
518 // #7779: checks 1 and 2 are `anchor_native_root`'s, so the plan and the pin
519 // cannot drift apart on what "inside the project" means.
520 let canon_root = match anchor_native_root(project_root, path)? {
521 AnchoredRoot::Existing(canon_root) => canon_root,
522 // Nothing resolves on this path yet, so no symlink can be escaping
523 // through it; the lexical check is the whole answer.
524 AnchoredRoot::Absent => return Ok(path.to_path_buf()),
525 };
526
527 // The target itself is typically absent, so containment is judged on the
528 // deepest ancestor that DOES exist.
529 match canonicalize_existing(path) {
530 Some(resolved) if !resolved.starts_with(&canon_root) => {
531 Err(WriteTargetError::SymlinkEscape {
532 path: path.to_path_buf(),
533 resolved,
534 native_root: native_config_dir(project_root),
535 })
536 }
537 _ => Ok(path.to_path_buf()),
538 }
539}
540
541/// Canonicalise the deepest existing ancestor of `path` (including `path`).
542///
543/// Why: `Path::canonicalize` fails outright on a path that does not exist yet,
544/// which is the normal case for a write target. Resolving the nearest existing
545/// ancestor still catches every symlink ON the path, which is what the guard
546/// needs.
547/// What: walks up from `path` until `canonicalize` succeeds; `None` when even
548/// the root fails (a path with no existing ancestor at all).
549/// Test: `paths::tests::symlinked_native_subdir_escape_is_refused`.
550fn canonicalize_existing(path: &Path) -> Option<PathBuf> {
551 let mut current = Some(path);
552 while let Some(p) = current {
553 if let Ok(canon) = p.canonicalize() {
554 return Some(canon);
555 }
556 current = p.parent();
557 }
558 None
559}
560
561/// Normalised key words whose presence marks a value as secret-bearing.
562///
563/// Why: project configuration under `.trusty-code/` is committed to the
564/// project's repository by convention, so a credential landing there is a leak
565/// with a long tail. The import path checks against this list before copying a
566/// settings file rather than after.
567/// What: lowercase, separator-free, SINGULAR word forms — not substrings. A key
568/// is split into words first ([`key_segments`]) and each word is de-pluralised
569/// before matching, so one entry covers every spelling of it: `api_key`,
570/// `API-KEY`, `x-api-key`, `xApiKey`, `APIKEY` and `apiKeys` all reduce to the
571/// `apikey` form. Multi-word entries (`apikey`, `accesskey`, `privatekey`) are
572/// matched against adjacent word PAIRS as well as against a single unseparated
573/// word.
574/// Test: `paths::tests::secret_keys_match_across_separator_and_case_spellings`,
575/// `paths::tests::secret_keys_match_plural_spellings`,
576/// `paths::tests::benign_keys_containing_a_hint_are_not_flagged`.
577pub const SECRET_KEY_HINTS: &[&str] = &[
578 "accesskey",
579 "apikey",
580 "authorization",
581 "credential",
582 "passphrase",
583 "password",
584 "privatekey",
585 "secret",
586 "token",
587];
588
589/// Whole keys that name a COUNT rather than a credential.
590///
591/// Why: de-pluralising makes `tokens` a hit, and `max_tokens` is an LLM sampling
592/// parameter this crate's own `code_harness` settings carry — refusing to import
593/// the very file the feature exists to migrate is a worse outcome than the leak
594/// risk of a key that holds an integer (code-critic round 2, PR #6980). The
595/// exemption is deliberately a short, closed list rather than a heuristic.
596/// What: normalised whole-key forms. The comparison is against the ENTIRE key,
597/// not a window of it, so appending a credential to an exempt name
598/// (`max_tokens_api_key`) does not inherit the exemption.
599/// Test: `paths::tests::max_tokens_stays_benign_as_a_count_not_a_credential`.
600pub const SECRET_KEY_EXEMPTIONS: &[&str] = &[
601 "maxtokens",
602 "mintokens",
603 "numtokens",
604 "tokenbudget",
605 "tokencount",
606 "tokenlimit",
607 "tokenusage",
608 "totaltokens",
609];
610
611/// Split a key into lowercase word segments.
612///
613/// Why: matching raw substrings both missed spellings and invented matches —
614/// `x-api-key` contained no hint while `tokenizer` contained `token`
615/// (code-critic HIGH, PR #6980). Splitting into words first makes the rule
616/// spelling-insensitive and word-exact at the same time.
617/// What: breaks on any non-alphanumeric character and on a lower-to-upper
618/// transition (so `xApiKey` yields three words), lowercasing each. An
619/// all-uppercase run stays one word, which is why the unseparated forms
620/// (`apikey`) are listed in [`SECRET_KEY_HINTS`] too.
621/// Test: `paths::tests::secret_keys_match_across_separator_and_case_spellings`,
622/// `paths::tests::benign_keys_containing_a_hint_are_not_flagged`.
623fn key_segments(key: &str) -> Vec<String> {
624 let mut segments = Vec::new();
625 let mut current = String::new();
626 let mut prev_was_lower = false;
627 for ch in key.chars() {
628 if !ch.is_ascii_alphanumeric() {
629 if !current.is_empty() {
630 segments.push(std::mem::take(&mut current));
631 }
632 prev_was_lower = false;
633 continue;
634 }
635 if ch.is_ascii_uppercase() && prev_was_lower && !current.is_empty() {
636 segments.push(std::mem::take(&mut current));
637 }
638 prev_was_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
639 current.push(ch.to_ascii_lowercase());
640 }
641 if !current.is_empty() {
642 segments.push(current);
643 }
644 segments
645}
646
647/// Whether one JSON key names a credential.
648///
649/// Why: the single rule both the import refusal and its tests apply, so the
650/// spelling coverage cannot drift between them.
651/// What: `false` outright when the whole key is a [`SECRET_KEY_EXEMPTIONS`]
652/// entry. Otherwise `true` when any single word of the key, or any two ADJACENT
653/// words joined, matches [`SECRET_KEY_HINTS`] under [`matches_hint`]'s
654/// de-pluralising comparison. Word-exact, so `tokenizer` and `secretary` are
655/// clean while `token`, `tokens` and `x-api-key` are not.
656/// Test: `paths::tests::secret_keys_match_across_separator_and_case_spellings`,
657/// `paths::tests::secret_keys_match_plural_spellings`,
658/// `paths::tests::max_tokens_stays_benign_as_a_count_not_a_credential`,
659/// `paths::tests::benign_keys_containing_a_hint_are_not_flagged`.
660pub fn is_secret_key(key: &str) -> bool {
661 let segments = key_segments(key);
662 // #5426: the exemption matches the WHOLE key, never a window of it, so a
663 // credential appended to an exempt name still trips the check below.
664 if SECRET_KEY_EXEMPTIONS.contains(&segments.concat().as_str()) {
665 return false;
666 }
667 (1..=2).any(|width| {
668 segments
669 .windows(width)
670 .any(|window| matches_hint(&window.concat()))
671 })
672}
673
674/// Whether one normalised word (or word pair) is a hint, singular or plural.
675///
676/// Why: the hint list carried `credential` and `credentials` but left `secret`,
677/// `token`, `apikey`, `accesskey` and `privatekey` singular-only, so `tokens`,
678/// `secretsFile`, `apiKeys` and four more plural spellings walked past the
679/// matcher (code-critic round 2 HIGH, PR #6980). De-pluralising at the
680/// comparison keeps the list singular and closes every plural at once, instead
681/// of doubling the list and inviting the same omission again.
682/// What: matches `joined` against [`SECRET_KEY_HINTS`] as given, then again with
683/// one trailing `s` removed. Stripping only a trailing `s` is deliberately
684/// narrow: `passwordless` becomes `passwordles`, not `password`, and
685/// `secretary` has no trailing `s` to strip at all.
686/// Test: `paths::tests::secret_keys_match_plural_spellings`,
687/// `paths::tests::benign_keys_containing_a_hint_are_not_flagged`.
688fn matches_hint(joined: &str) -> bool {
689 if SECRET_KEY_HINTS.contains(&joined) {
690 return true;
691 }
692 joined
693 .strip_suffix('s')
694 .is_some_and(|singular| SECRET_KEY_HINTS.contains(&singular))
695}
696
697/// Find the first secret-bearing key path in a JSON value, if any.
698///
699/// Why: a boolean would tell an operator that their import was refused without
700/// telling them which key to remove.
701/// What: a depth-first walk returning the dotted key path of the first key
702/// [`is_secret_key`] accepts; `None` when clean. Array elements are indexed
703/// (`mcp.0.token`). Keys only — a bare credential under an unrelated key is out
704/// of scope, as the README states.
705/// Test: `paths::tests::secret_bearing_keys_are_detected`,
706/// `paths::tests::nested_kebab_secret_is_reported_by_path`,
707/// `paths::tests::ordinary_settings_carry_no_secret`.
708pub fn find_secret_key(value: &serde_json::Value) -> Option<String> {
709 fn walk(value: &serde_json::Value, prefix: &str, out: &mut Option<String>) {
710 if out.is_some() {
711 return;
712 }
713 match value {
714 serde_json::Value::Object(map) => {
715 for (key, child) in map {
716 let path = if prefix.is_empty() {
717 key.clone()
718 } else {
719 format!("{prefix}.{key}")
720 };
721 if is_secret_key(key) {
722 *out = Some(path);
723 return;
724 }
725 walk(child, &path, out);
726 if out.is_some() {
727 return;
728 }
729 }
730 }
731 serde_json::Value::Array(items) => {
732 for (i, child) in items.iter().enumerate() {
733 walk(child, &format!("{prefix}.{i}"), out);
734 if out.is_some() {
735 return;
736 }
737 }
738 }
739 _ => {}
740 }
741 }
742 let mut out = None;
743 walk(value, "", &mut out);
744 out
745}
746
747#[cfg(test)]
748#[path = "tests.rs"]
749mod tests;