返回 CodeWhale
test_support.rs
根目录 / crates / tui / src / test_support.rs
1 pub(crate) use codewhale_engine::test_support::*;
2
3 #[cfg(unix)]
4 mod tests {
5 use std::path::Path;
6 use std::time::UNIX_EPOCH;
7
8 /// Tripwire for the leak this module exists to prevent: run a sample of
9 /// the tests that once wrote `~/.codewhale` in a child process whose
10 /// *ambient* `HOME` and `CODEWHALE_HOME` are a seeded, read-only sentinel,
11 /// then require both that they pass and that the sentinel is byte-for-byte
12 /// as it was. A test that writes the ambient home without sealing its own
13 /// fails here by name, instead of silently rewriting a developer's profile.
14 ///
15 /// The sample covers one test per resolver class that leaked
16 /// (`App::new`, command dispatch, sessions, snapshots, plugin bundles,
17 /// credentials, the `/import-claude` report). To sweep a whole family,
18 /// set `CODEWHALE_TEST_AMBIENT_HOME_FILTER` to a libtest filter such as
19 /// `commands::`; that takes minutes, which is why it is not the default.
20 #[test]
21 fn ambient_home_survives_a_sample_of_state_touching_tests() {
22 use std::os::unix::fs::PermissionsExt;
23
24 const PROBE_ENV: &str = "CODEWHALE_TEST_AMBIENT_HOME_PROBE";
25 const FILTER_ENV: &str = "CODEWHALE_TEST_AMBIENT_HOME_FILTER";
26 const SAMPLE: &[&str] = &[
27 "commands::contract::tests::bundle_construction_performs_no_eager_work",
28 "commands::contract::tests::skill_group_snapshot_list_and_restore_roundtrip",
29 "commands::debug_diagnostics_host_tests::test_context_report_subcommands_return_source_map",
30 "commands::debug_mutation_host_tests::test_patch_undo_requests_durable_rewind_after_restore",
31 "commands::groups::core::core::tests::test_clear_resets_all_state",
32 "commands::groups::plugins::tests::kimi_managed_import_refuses_linked_children",
33 "commands::session_lifecycle_regression_tests::fork_saves_parent_and_switches_to_child_session",
34 "commands::session_lifecycle_regression_tests::test_save_creates_file_and_sets_session_id",
35 "commands::tests::every_registered_command_dispatches_to_a_handler",
36 "commands::tests::every_command_alias_dispatches_to_a_handler",
37 "commands::tests::feat020_plugin_dispatches_through_public_seam",
38 ];
39
40 // The child runs the sample; it must not recurse into this probe.
41 if std::env::var_os(PROBE_ENV).is_some() {
42 return;
43 }
44
45 fn walk(dir: &Path, visit: &mut dyn FnMut(&Path, &std::fs::Metadata)) {
46 let mut entries: Vec<_> = std::fs::read_dir(dir)
47 .expect("read sentinel dir")
48 .map(|entry| entry.expect("sentinel entry").path())
49 .collect();
50 entries.sort();
51 for path in entries {
52 let metadata = std::fs::symlink_metadata(&path).expect("sentinel metadata");
53 visit(&path, &metadata);
54 if metadata.is_dir() {
55 walk(&path, visit);
56 }
57 }
58 }
59 fn listing(root: &Path) -> Vec<String> {
60 let mut out = Vec::new();
61 walk(root, &mut |path, metadata| {
62 let mtime = metadata
63 .modified()
64 .ok()
65 .and_then(|time| time.duration_since(UNIX_EPOCH).ok())
66 .map_or(0, |elapsed| elapsed.as_nanos());
67 out.push(format!(
68 "{} dir={} len={} mtime={mtime} contents={:?}",
69 path.strip_prefix(root).unwrap_or(path).display(),
70 metadata.is_dir(),
71 metadata.len(),
72 metadata
73 .is_file()
74 .then(|| std::fs::read(path).expect("read sentinel file"))
75 ));
76 });
77 out
78 }
79 fn set_readonly(root: &Path, readonly: bool) {
80 let mode = |dir: bool| match (dir, readonly) {
81 (true, true) => 0o500,
82 (true, false) => 0o700,
83 (false, true) => 0o400,
84 (false, false) => 0o600,
85 };
86 let apply = |path: &Path, dir: bool| {
87 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode(dir)))
88 .expect("set sentinel permissions");
89 };
90 walk(root, &mut |path, metadata| {
91 if !metadata.file_type().is_symlink() {
92 apply(path, metadata.is_dir());
93 }
94 });
95 apply(root, true);
96 }
97
98 let sentinel = tempfile::tempdir().expect("sentinel tempdir");
99 let home = sentinel.path().join("home");
100 let codewhale_home = sentinel.path().join("codewhale-home");
101 // Content a leaking test would read, rewrite or migrate.
102 for (relative, body) in [
103 (
104 "home/.claude/CLAUDE.md",
105 "# someone's Claude instructions\n",
106 ),
107 ("home/.claude.json", "{\"mcpServers\":{}}\n"),
108 ("home/.codewhale/instructions.md", "# real instructions\n"),
109 ("home/.deepseek/config.toml", "model = \"keep-me\"\n"),
110 ("home/.deepseek/sessions/legacy.json", "{}\n"),
111 ("codewhale-home/instructions.md", "# real instructions\n"),
112 ("codewhale-home/sessions/keep.json", "{}\n"),
113 ] {
114 let path = sentinel.path().join(relative);
115 std::fs::create_dir_all(path.parent().expect("sentinel parent")).expect("seed dir");
116 std::fs::write(path, body).expect("seed file");
117 }
118 assert!(home.is_dir() && codewhale_home.is_dir());
119 let before = listing(sentinel.path());
120 set_readonly(sentinel.path(), true);
121
122 let filter = std::env::var(FILTER_ENV).ok().filter(|f| !f.is_empty());
123 let mut child = std::process::Command::new(std::env::current_exe().expect("test binary"));
124 child.arg("--test-threads=4");
125 match &filter {
126 Some(filter) => child.arg(filter),
127 None => child.arg("--exact").args(SAMPLE),
128 };
129 let output = child
130 .env(PROBE_ENV, "1")
131 .env("HOME", &home)
132 .env("USERPROFILE", &home)
133 .env("CODEWHALE_HOME", &codewhale_home)
134 .env_remove("HOMEDRIVE")
135 .env_remove("HOMEPATH")
136 .env_remove("CODEWHALE_CONFIG_PATH")
137 .env_remove("DEEPSEEK_CONFIG_PATH")
138 .env_remove("DEEPSEEK_HOME")
139 .output();
140
141 // Restore write access first so a failure still cleans up after itself.
142 set_readonly(sentinel.path(), false);
143 let output = output.expect("run the sample under a read-only ambient home");
144 let stdout = String::from_utf8_lossy(&output.stdout);
145 let stderr = String::from_utf8_lossy(&output.stderr);
146 let report = format!("stdout:\n{stdout}\nstderr:\n{stderr}");
147
148 assert!(
149 output.status.success(),
150 "a test failed under a read-only ambient home — it reaches the user's \
151 state without sealing it (use SealedHome, or fence the resolver):\n{report}"
152 );
153 if filter.is_none() {
154 assert!(
155 stdout.contains(&format!("running {} tests", SAMPLE.len())),
156 "the sample names drifted from real tests; update SAMPLE:\n{report}"
157 );
158 }
159 assert_eq!(
160 listing(sentinel.path()),
161 before,
162 "a test wrote the ambient home:\n{report}"
163 );
164 }
165 }
166
166 lines RUST