trusty_code/paths/private_state.rs
1//! Private mutable state beneath `~/.trusty-code/` (#5426, epic #2892).
2//!
3//! Why: transcripts, logs, compression telemetry, daemon discovery files, and
4//! channel cursors are per-user runtime state, not project configuration. They
5//! were already landing in `~/.trusty-code` via `workstreams::default_data_dir`,
6//! but nothing named that directory as PRIVATE and nothing set its mode, so a
7//! default-umask machine left `0755` — world-readable transcripts of whatever
8//! the harness was asked to work on.
9//!
10//! What: [`private_state_dir_at`] is the hermetic resolver (an explicit `$HOME`,
11//! so tests never touch a real home directory and never mutate the environment);
12//! [`private_state_dir`] is the production wrapper.
13//! [`ensure_private_state_dir_at`] creates the tree and TIGHTENS the mode to
14//! `0700` on Unix — including on a directory that already existed with a
15//! permissive mode, since the common case is an upgrade over an existing
16//! `~/.trusty-code`. [`is_restrictive`] is the predicate the tests and the
17//! `tcode config paths` diagnostic both assert on.
18//!
19//! Test: `paths::private_state_tests::*`.
20
21use std::io;
22use std::path::{Path, PathBuf};
23
24use super::TRUSTY_CODE_DIRNAME;
25
26/// The Unix mode private state is held at: owner-only, no group, no other.
27///
28/// Why: `0700` is the same bar `~/.ssh` sets, and the state here (transcripts,
29/// daemon tokens' neighbours, logs) is comparably sensitive.
30/// What: `0o700`.
31/// Test: `paths::private_state_tests::ensure_tightens_a_permissive_existing_dir`.
32#[cfg(unix)]
33pub const PRIVATE_DIR_MODE: u32 = 0o700;
34
35/// The permission bits that must be clear for a directory to count as private.
36///
37/// Why: comparing the full mode would fail on a directory that is `0700` plus a
38/// sticky or setgid bit, which is not a privacy problem.
39/// What: `0o077` — every group and other bit.
40/// Test: `paths::private_state_tests::permissive_mode_is_not_restrictive`.
41#[cfg(unix)]
42pub const NON_OWNER_BITS: u32 = 0o077;
43
44/// Resolve the private state directory beneath an explicit home directory.
45///
46/// Why: the hermetic core. Every test points `home` at a temp dir, so none of
47/// them reads or writes the developer's real `~/.trusty-code` and none needs to
48/// mutate `$HOME` (an env mutation would race every other test in the binary).
49/// What: `<home>/.trusty-code`.
50/// Test: `paths::private_state_tests::private_state_dir_at_is_dot_trusty_code`.
51pub fn private_state_dir_at(home: &Path) -> PathBuf {
52 home.join(TRUSTY_CODE_DIRNAME)
53}
54
55/// Resolve the production private state directory, `~/.trusty-code`.
56///
57/// Why: the one place `dirs::home_dir()` is consulted for this purpose, so the
58/// no-home fallback is decided once instead of per call site.
59/// What: [`private_state_dir_at`] on `dirs::home_dir()`. With no resolvable home
60/// — a stripped container, a daemon launched with no `$HOME` — it falls back to
61/// a process-relative `.trusty-code` and logs at `warn` with the path used,
62/// rather than panicking a harness that is otherwise fine.
63/// Test: `paths::private_state_tests::private_state_dir_matches_home_when_available`.
64pub fn private_state_dir() -> PathBuf {
65 match dirs::home_dir() {
66 Some(home) => private_state_dir_at(&home),
67 None => {
68 let fallback = PathBuf::from(TRUSTY_CODE_DIRNAME);
69 // #5426: fail open, but never silently — a relative state directory
70 // follows the process's working directory, which is rarely intended.
71 tracing::warn!(
72 path = %fallback.display(),
73 "no home directory could be resolved; falling back to a \
74 working-directory-relative trusty-code state directory"
75 );
76 fallback
77 }
78 }
79}
80
81/// Create the private state directory and tighten it to owner-only.
82///
83/// Why: creating it with `create_dir_all` alone applies the process umask, which
84/// on a default `022` machine yields `0755`. An upgrade path matters as much as
85/// a fresh install: `~/.trusty-code` already exists on every machine that has
86/// run `tcode`, so this tightens an EXISTING permissive directory rather than
87/// only getting new ones right.
88/// What: `create_dir_all`, then on Unix `set_permissions` to
89/// [`PRIVATE_DIR_MODE`] whenever any of [`NON_OWNER_BITS`] is set. A failure to
90/// tighten is logged at `warn` with the path and the mode observed, and the
91/// directory is still returned — the harness must run on a filesystem that
92/// cannot represent Unix modes. Non-Unix targets create the directory and rely
93/// on the platform's own per-user home ACLs.
94/// Test: `paths::private_state_tests::ensure_creates_restrictive_dir`,
95/// `paths::private_state_tests::ensure_tightens_a_permissive_existing_dir`.
96pub fn ensure_private_state_dir_at(home: &Path) -> io::Result<PathBuf> {
97 let dir = private_state_dir_at(home);
98 ensure_dir(&dir)?;
99 Ok(dir)
100}
101
102/// Create `dir` and tighten it, on an already-resolved path.
103///
104/// Why: #6999 — the create-and-tighten body was written twice, once per
105/// `ensure_*` wrapper, and [`crate::workstreams::default_data_dir`] needs a
106/// third caller that already holds the resolved path (its home resolution is
107/// [`private_state_dir`]'s job, including the no-home fallback). One body, three
108/// callers, rather than a copy per entry point.
109/// What: `create_dir_all` then [`harden`]. Errors only on the create — a
110/// failure to chmod is logged by [`harden`] and does not fail the call.
111/// Test: `paths::private_state_tests::ensure_creates_restrictive_dir`,
112/// `workstreams::path_tests::ensure_or_report_falls_back_when_the_path_is_a_file`.
113pub(crate) fn ensure_dir(dir: &Path) -> io::Result<()> {
114 std::fs::create_dir_all(dir)?;
115 harden(dir);
116 Ok(())
117}
118
119/// Create and tighten the production `~/.trusty-code`.
120///
121/// Why: the production wrapper over [`ensure_private_state_dir_at`], so callers
122/// never resolve the home directory themselves. #6999: `tcode paths import` was
123/// its only caller, so the mode guarantee applied to exactly one subcommand;
124/// [`crate::workstreams::default_data_dir`] now calls it too, which is the
125/// resolver every private-state writer already routes through.
126/// What: [`private_state_dir`] then the same create-and-tighten sequence.
127/// Test: covered hermetically by `ensure_private_state_dir_at`'s tests; the
128/// wrapper adds only home resolution.
129/// `tests/cli_e2e.rs::a_non_import_command_tightens_a_permissive_private_state_dir`
130/// covers the call from `default_data_dir`.
131pub fn ensure_private_state_dir() -> io::Result<PathBuf> {
132 let dir = private_state_dir();
133 ensure_dir(&dir)?;
134 Ok(dir)
135}
136
137/// Tighten `dir` to [`PRIVATE_DIR_MODE`] when any non-owner bit is set.
138///
139/// Why: separated from [`ensure_private_state_dir_at`] so the "already private"
140/// case does a single `metadata` call and no write at all.
141/// What: no-op when [`is_restrictive`] already holds; otherwise
142/// `set_permissions`, logging a `warn` if that fails.
143/// Test: `paths::private_state_tests::ensure_tightens_a_permissive_existing_dir`.
144#[cfg(unix)]
145fn harden(dir: &Path) {
146 use std::os::unix::fs::PermissionsExt;
147 let Ok(meta) = std::fs::metadata(dir) else {
148 return;
149 };
150 let mode = meta.permissions().mode();
151 if mode & NON_OWNER_BITS == 0 {
152 return;
153 }
154 if let Err(e) = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(PRIVATE_DIR_MODE))
155 {
156 tracing::warn!(
157 path = %dir.display(),
158 mode = format!("{:o}", mode & 0o777),
159 error = %e,
160 "could not tighten the trusty-code private state directory to 0700; \
161 its contents may be readable by other users on this machine"
162 );
163 }
164}
165
166/// Non-Unix targets have no mode bits to tighten.
167#[cfg(not(unix))]
168fn harden(_dir: &Path) {}
169
170/// Whether a directory's permissions keep it private to its owner.
171///
172/// Why: the assertion the permissive-permissions test makes, and the field the
173/// `tcode config paths` diagnostic reports, must come from ONE rule.
174/// What: on Unix, `true` when none of [`NON_OWNER_BITS`] is set; `Err` when the
175/// directory cannot be stat'd. On non-Unix targets, always `true` — the platform
176/// has no comparable bits and the home directory's ACL governs.
177/// Test: `paths::private_state_tests::permissive_mode_is_not_restrictive`,
178/// `paths::private_state_tests::ensure_creates_restrictive_dir`.
179#[cfg(unix)]
180pub fn is_restrictive(dir: &Path) -> io::Result<bool> {
181 use std::os::unix::fs::PermissionsExt;
182 let mode = std::fs::metadata(dir)?.permissions().mode();
183 Ok(mode & NON_OWNER_BITS == 0)
184}
185
186/// See the Unix variant — non-Unix targets have no mode bits to inspect.
187#[cfg(not(unix))]
188pub fn is_restrictive(dir: &Path) -> io::Result<bool> {
189 std::fs::metadata(dir)?;
190 Ok(true)
191}
192
193#[cfg(test)]
194#[path = "private_state_tests.rs"]
195mod private_state_tests;