1use std::path::{Path, PathBuf};
4
5pub const SENSITIVE_PATTERNS: &[&str] = &[
7 ".git",
8 ".ssh",
9 ".gnupg",
10 ".aws",
11 ".azure",
12 ".docker",
13 ".kube",
14 ".pulumi",
15 ".terraform",
16 ".env",
17 ".envrc",
18 ".dev.vars",
19 ".key",
20 ".pem",
21 ".aws/credentials",
22 ".netrc",
23 ".docker/config.json",
24 "credentials",
25 "id_rsa",
26 "id_ed25519",
27 ".npmrc",
28 ".pypirc",
29 ".htpasswd",
30 ".git-credentials",
31 "secrets",
32];
33
34pub const SECRET_READ_PATTERNS: &[&str] = &[
39 ".config/gh/hosts.yml",
40 ".codex/auth.json",
41 ".claude/.credentials.json",
42 ".config/gcloud/credentials.db",
43 ".config/gcloud/access_tokens.db",
44 ".config/gcloud/application_default_credentials.json",
45 ".docker/config.json",
46 ".kube/config",
47 ".bash_history",
48 ".zsh_history",
49 ".python_history",
50 ".node_repl_history",
51 ".psql_history",
52 ".mysql_history",
53 ".sqlite_history",
54 ".lesshst",
55 ".local/share/fish/fish_history",
56 "Library/Application Support/Google/Chrome",
57 "Library/Application Support/Firefox",
58 "Library/Application Support/Microsoft Edge",
59 "Library/Application Support/BraveSoftware",
60 "Library/Safari",
61 "Library/Cookies",
62 "Library/Keychains",
63 ".mozilla/firefox",
64 ".config/google-chrome",
65 ".config/chromium",
66 ".config/BraveSoftware",
67 ".password-store",
68 ".ssh",
69 ".gnupg",
70 ".aws",
71 ".azure",
72 ".kube",
73 ".env",
74 ".envrc",
75 ".dev.vars",
76 ".key",
77 ".pem",
78 ".aws/credentials",
79 ".netrc",
80 ".docker/config.json",
81 "credentials",
82 "id_rsa",
83 "id_ed25519",
84 ".npmrc",
85 ".pypirc",
86 ".htpasswd",
87 ".git-credentials",
88 "secrets",
89];
90
91const SHELL_STARTUP_FILES: &[&str] = &[
93 ".bashrc",
94 ".bash_profile",
95 ".bash_login",
96 ".bash_logout",
97 ".profile",
98 ".zshrc",
99 ".zshenv",
100 ".zprofile",
101 ".zlogin",
102 ".zlogout",
103 ".cshrc",
104 ".tcshrc",
105 ".kshrc",
106 ".mkshrc",
107 ".xprofile",
108 ".xinitrc",
109 ".xsessionrc",
110 "microsoft.powershell_profile.ps1",
111 "profile.ps1",
112];
113
114const STARTUP_FOLDERS: &[&[&str]] = &[
117 &["Library", "LaunchAgents"],
118 &["Library", "LaunchDaemons"],
119 &["Library", "StartupItems"],
120 &["systemd", "user"],
121 &["systemd", "system"],
122 &[".config", "autostart"],
123 &[".config", "environment.d"],
124 &[".config", "fish", "conf.d"],
125 &["etc", "cron.d"],
126 &["etc", "cron.daily"],
127 &["etc", "cron.hourly"],
128 &["etc", "cron.weekly"],
129 &["etc", "cron.monthly"],
130 &["var", "spool", "cron"],
131 &["etc", "profile.d"],
132 &["Start Menu", "Programs", "Startup"],
133 &[".git", "hooks"],
134 &[".husky"],
135];
136
137const DAEMON_INSTRUCTION_ENTRIES: &[&str] =
141 &["AGENTS.md", "AGENTS.override.md", "specialists", "skills"];
142
143const DAEMON_DIR_NAME: &str = ".aidaemon";
145
146pub fn is_persistence_path(path: &Path, daemon_dirs: &[PathBuf]) -> bool {
153 let components: Vec<String> = path
154 .components()
155 .map(|c| c.as_os_str().to_string_lossy().into_owned())
156 .collect();
157 let eq = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
158 if path.file_name().is_some_and(|name| {
159 let name = name.to_string_lossy();
160 SHELL_STARTUP_FILES.iter().any(|file| eq(&name, file))
161 || eq(&name, "crontab")
162 || (eq(&name, "config.fish")
163 && components
164 .iter()
165 .rev()
166 .nth(1)
167 .is_some_and(|dir| eq(dir, "fish")))
168 }) {
169 return true;
170 }
171 let holds_run = |run: &[&str]| {
172 components
173 .windows(run.len())
174 .any(|window| window.iter().zip(run).all(|(c, r)| eq(c, r)))
175 };
176 if STARTUP_FOLDERS.iter().any(|run| holds_run(run)) {
177 return true;
178 }
179 let under_entry = |dir_len: usize| {
181 components
182 .get(dir_len)
183 .is_some_and(|entry| DAEMON_INSTRUCTION_ENTRIES.iter().any(|e| eq(entry, e)))
184 };
185 if components
186 .iter()
187 .enumerate()
188 .any(|(i, c)| eq(c, DAEMON_DIR_NAME) && under_entry(i + 1))
189 {
190 return true;
191 }
192 daemon_dirs.iter().any(|dir| {
193 let dir_len = dir.components().count();
194 (path.starts_with(dir)
195 || dunce::canonicalize(dir)
196 .ok()
197 .is_some_and(|dir| path.starts_with(&dir)))
198 && under_entry(dir_len)
199 })
200}
201
202#[derive(Debug, Clone, Default, PartialEq, Eq)]
207pub struct PathClassifier {
208 protected: Vec<PathBuf>,
209}
210
211impl PathClassifier {
212 pub fn new(protected: Vec<PathBuf>) -> Self {
213 Self { protected }
214 }
215
216 pub const fn empty() -> Self {
218 Self {
219 protected: Vec::new(),
220 }
221 }
222
223 pub fn protected_paths(&self) -> &[PathBuf] {
225 &self.protected
226 }
227
228 pub fn is_protected(&self, path: &Path) -> bool {
230 self.protected.iter().any(|own| same_file(own, path))
231 }
232
233 pub fn is_secret(&self, path: &Path) -> bool {
236 self.is_secret_ignoring_name_shape(path) || has_secret_name_shape(path)
237 }
238
239 pub fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
242 matches_patterns(path, SECRET_READ_PATTERNS) || self.is_protected(path)
243 }
244
245 pub fn is_sensitive(&self, path: &Path) -> bool {
248 matches_patterns(path, SENSITIVE_PATTERNS)
249 || self.is_protected(path)
250 || has_secret_name_shape(path)
251 }
252}
253
254pub fn same_file(a: &Path, b: &Path) -> bool {
257 a == b
258 || matches!(
259 (dunce::canonicalize(a), dunce::canonicalize(b)),
260 (Ok(x), Ok(y)) if x == y
261 )
262}
263
264fn matches_patterns(path: &Path, patterns: &[&str]) -> bool {
265 let path_lower = path.to_string_lossy().to_ascii_lowercase();
266 patterns.iter().any(|pattern| {
267 if pattern.contains('/') {
268 path_lower.contains(&pattern.to_ascii_lowercase())
271 } else {
272 path.components().any(|c| {
275 c.as_os_str()
276 .to_string_lossy()
277 .eq_ignore_ascii_case(pattern)
278 }) || path
279 .file_name()
280 .is_some_and(|f| f.to_string_lossy().eq_ignore_ascii_case(pattern))
281 }
282 })
283}
284
285fn has_secret_name_shape(path: &Path) -> bool {
288 path.components().any(|component| {
289 let component = component.as_os_str().to_string_lossy().to_ascii_lowercase();
290 component.starts_with(".env.")
291 || component.starts_with(".dev.vars.")
292 || component.ends_with(".key")
293 || component.ends_with(".pem")
294 || component.ends_with(".p12")
295 || component.ends_with(".pfx")
296 || component.ends_with(".jks")
297 || component.ends_with(".keystore")
298 || component == "terraform.tfstate"
299 || component.starts_with("terraform.tfstate.")
300 })
301}
302
303#[derive(Debug, Clone, Default)]
308pub struct DaemonPaths {
309 classifier: std::sync::Arc<PathClassifier>,
310}
311
312impl DaemonPaths {
313 pub fn new(protected: Vec<PathBuf>) -> Self {
316 Self {
317 classifier: std::sync::Arc::new(PathClassifier::new(protected)),
318 }
319 }
320
321 pub fn is_secret(&self, path: &Path) -> bool {
324 self.classifier.is_secret(path) || is_configured_env_file(path)
325 }
326
327 pub fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
330 self.classifier.is_secret_ignoring_name_shape(path) || is_configured_env_file(path)
331 }
332
333 pub fn is_sensitive(&self, path: &Path) -> bool {
335 self.classifier.is_sensitive(path) || is_configured_env_file(path)
336 }
337
338 pub fn is_own_file(&self, path: &Path) -> bool {
340 self.classifier.is_protected(path)
341 }
342
343 pub fn is_persistence(&self, path: &Path) -> bool {
347 let dirs = self
348 .classifier
349 .protected_paths()
350 .iter()
351 .filter_map(|file| file.parent().map(Path::to_path_buf))
352 .collect::<Vec<_>>();
353 is_persistence_path(path, &dirs)
354 }
355}
356
357fn is_configured_env_file(path: &Path) -> bool {
360 ["AIDAEMON_ENV_FILE", "AIDAEMON_RUNTIME_ENV_FILE"]
361 .iter()
362 .filter_map(std::env::var_os)
363 .filter(|value| !value.is_empty())
364 .any(|value| same_file(Path::new(&value), path))
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 fn path(p: &str) -> &Path {
372 Path::new(p)
373 }
374
375 #[test]
376 fn secrets_and_sensitive_paths() {
377 let classifier = PathClassifier::default();
378 for secret in [
379 "/home/synthetic/.ssh/id_ed25519",
380 "/srv/app/.env",
381 "/srv/app/.env.production",
382 "/srv/app/server.key",
383 "/home/synthetic/.aws/credentials",
384 ] {
385 assert!(classifier.is_secret(path(secret)), "{secret}");
386 assert!(classifier.is_sensitive(path(secret)), "{secret}");
387 }
388 assert!(classifier.is_sensitive(path("/srv/app/.git/config")));
390 assert!(!classifier.is_secret(path("/srv/app/.git/config")));
391 assert!(classifier.is_sensitive(path("/srv/infra/terraform.tfstate")));
392 assert!(!classifier.is_sensitive(path("/srv/app/src/main.rs")));
394 assert!(!classifier.is_sensitive(path("/srv/app/monkey.txt")));
396 }
397
398 #[test]
399 fn token_stores_and_histories_are_secrets() {
400 let classifier = PathClassifier::default();
401 for secret in [
402 "/home/synthetic/.config/gh/hosts.yml",
403 "/home/synthetic/.codex/auth.json",
404 "/home/synthetic/.claude/.credentials.json",
405 "/home/synthetic/.zsh_history",
406 "/home/synthetic/.bash_history",
407 "/home/synthetic/.netrc",
408 "/home/synthetic/.docker/config.json",
409 "/home/synthetic/.kube/config",
410 "/Users/synthetic/Library/Application Support/Google/Chrome/Default/Cookies",
411 "/home/synthetic/.mozilla/firefox/abc.default/logins.json",
412 ] {
413 assert!(classifier.is_secret(path(secret)), "{secret}");
414 }
415 assert!(!classifier.is_secret(path("/srv/app/.config/settings.yml")));
416 }
417
418 #[test]
419 fn name_shape_rules_can_be_ignored_for_templates() {
420 let classifier = PathClassifier::default();
421 let template = path("/srv/app/config/.env.example");
422 assert!(classifier.is_secret(template));
423 assert!(!classifier.is_secret_ignoring_name_shape(template));
424 }
425
426 #[test]
427 fn the_apps_own_files_are_protected() {
428 let own = PathBuf::from("/srv/synthetic-app/app.toml");
429 let classifier = PathClassifier::new(vec![own.clone()]);
430 assert!(classifier.is_protected(&own));
431 assert!(classifier.is_secret(&own));
432 assert!(classifier.is_sensitive(&own));
433 assert!(!PathClassifier::default().is_sensitive(&own));
434 }
435
436 #[test]
439 fn sensitive_paths_are_classified() {
440 let paths = DaemonPaths::default();
441 for sensitive in [
442 "/home/user/.ssh/id_rsa",
443 "/home/user/.env",
444 "/repo/.env.production/value",
445 "/repo/.dev.vars.local",
446 "/repo/.git/config",
447 "/repo/certificates/app.PEM",
448 "/repo/terraform.tfstate.backup",
449 "/home/user/.gnupg/key",
450 ] {
451 assert!(paths.is_sensitive(Path::new(sensitive)), "{sensitive}");
452 }
453 assert!(!paths.is_sensitive(Path::new("/home/user/code/main.rs")));
454 assert!(!paths.is_sensitive(Path::new("/repo/src/environment.rs")));
455 }
456
457 #[test]
458 fn persistence_paths_are_classified() {
459 let daemon = PathBuf::from("/srv/synthetic-daemon");
460 let paths = DaemonPaths::new(vec![daemon.join("config.toml")]);
461 for persistent in [
462 "/home/synthetic/.zshrc",
463 "/home/synthetic/.bash_profile",
464 "/Users/synthetic/Library/LaunchAgents/com.example.agent.plist",
465 "/Library/LaunchDaemons/com.example.plist",
466 "/home/synthetic/.config/systemd/user/example.service",
467 "/home/synthetic/.config/autostart/example.desktop",
468 "/home/synthetic/.config/fish/config.fish",
469 "/etc/cron.d/example",
470 "/var/spool/cron/crontabs/synthetic",
471 "/srv/app/.git/hooks/pre-commit",
472 "/srv/app/.husky/pre-push",
473 "/home/synthetic/.aidaemon/AGENTS.md",
474 "/home/synthetic/.aidaemon/specialists/coder.md",
475 "/home/synthetic/.aidaemon/skills/example/SKILL.md",
476 "/srv/synthetic-daemon/AGENTS.md",
477 "/srv/synthetic-daemon/specialists/x.md",
478 ] {
479 assert!(paths.is_persistence(Path::new(persistent)), "{persistent}");
480 }
481 for ordinary in [
482 "/srv/app/src/main.rs",
483 "/srv/app/AGENTS.md",
484 "/home/synthetic/.aidaemon/files/inbox/report.pdf",
485 "/srv/app/profile.rs",
486 "/srv/app/docs/launchagents.md",
487 ] {
488 assert!(!paths.is_persistence(Path::new(ordinary)), "{ordinary}");
489 }
490 }
491
492 #[test]
493 fn the_daemons_own_files_are_protected_only_when_given() {
494 let own = Path::new("/synthetic/daemon/config.toml");
495 assert!(!DaemonPaths::default().is_sensitive(own));
496 let paths = DaemonPaths::new(vec![own.to_path_buf()]);
497 assert!(paths.is_sensitive(own));
498 assert!(paths.is_secret(own));
499 }
500}