Skip to main content

aidaemon_tools/
path_class.rs

1//! Which paths hold secrets or must not be touched by the file tools.
2
3use std::path::{Path, PathBuf};
4
5/// Sensitive path patterns that should not be exposed through file tools.
6pub 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
34/// Entries that hold secrets; a file read refuses these. Narrower than
35/// [`SENSITIVE_PATTERNS`], which also guards non-secret writes such as
36/// `.git`.
37pub const SECRET_READ_PATTERNS: &[&str] = &[
38    ".ssh",
39    ".gnupg",
40    ".aws",
41    ".azure",
42    ".kube",
43    ".env",
44    ".envrc",
45    ".dev.vars",
46    ".key",
47    ".pem",
48    ".aws/credentials",
49    ".netrc",
50    ".docker/config.json",
51    "credentials",
52    "id_rsa",
53    "id_ed25519",
54    ".npmrc",
55    ".pypirc",
56    ".htpasswd",
57    ".git-credentials",
58    "secrets",
59];
60
61/// Classifies paths for the file tools: secrets a read refuses, and the
62/// wider set of sensitive paths a write refuses. Beyond the built-in
63/// patterns, an app adds its own files (its config, its env file) as
64/// `protected`; they count as both.
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct PathClassifier {
67    protected: Vec<PathBuf>,
68}
69
70impl PathClassifier {
71    pub fn new(protected: Vec<PathBuf>) -> Self {
72        Self { protected }
73    }
74
75    /// A classifier with no app files protected (usable in a `static`).
76    pub const fn empty() -> Self {
77        Self {
78            protected: Vec::new(),
79        }
80    }
81
82    /// The app's own files, as given.
83    pub fn protected_paths(&self) -> &[PathBuf] {
84        &self.protected
85    }
86
87    /// One of the app's own files (compared after resolving symlinks).
88    pub fn is_protected(&self, path: &Path) -> bool {
89        self.protected.iter().any(|own| same_file(own, path))
90    }
91
92    /// A file that holds secrets: keys, credentials, env files, the app's
93    /// own files.
94    pub fn is_secret(&self, path: &Path) -> bool {
95        self.is_secret_ignoring_name_shape(path) || has_secret_name_shape(path)
96    }
97
98    /// [`PathClassifier::is_secret`] without the `.env.*` / `*.key`
99    /// name-shape rules, so a template file is judged by where it lives.
100    pub fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
101        matches_patterns(path, SECRET_READ_PATTERNS) || self.is_protected(path)
102    }
103
104    /// A path the file tools must not write: everything secret, plus
105    /// repository internals and infrastructure state.
106    pub fn is_sensitive(&self, path: &Path) -> bool {
107        matches_patterns(path, SENSITIVE_PATTERNS)
108            || self.is_protected(path)
109            || has_secret_name_shape(path)
110    }
111}
112
113/// Whether two paths name the same file, directly or after resolving
114/// symlinks.
115pub fn same_file(a: &Path, b: &Path) -> bool {
116    a == b
117        || matches!(
118            (dunce::canonicalize(a), dunce::canonicalize(b)),
119            (Ok(x), Ok(y)) if x == y
120        )
121}
122
123fn matches_patterns(path: &Path, patterns: &[&str]) -> bool {
124    let path_lower = path.to_string_lossy().to_ascii_lowercase();
125    patterns.iter().any(|pattern| {
126        if pattern.contains('/') {
127            // A multi-component pattern (".aws/credentials") is specific
128            // enough to match as a substring.
129            path_lower.contains(&pattern.to_ascii_lowercase())
130        } else {
131            // A single component matches a whole path component or the
132            // file name, never part of one.
133            path.components().any(|c| {
134                c.as_os_str()
135                    .to_string_lossy()
136                    .eq_ignore_ascii_case(pattern)
137            }) || path
138                .file_name()
139                .is_some_and(|f| f.to_string_lossy().eq_ignore_ascii_case(pattern))
140        }
141    })
142}
143
144/// Secret-shaped names: env variants, key and keystore extensions, and
145/// Terraform state.
146fn has_secret_name_shape(path: &Path) -> bool {
147    path.components().any(|component| {
148        let component = component.as_os_str().to_string_lossy().to_ascii_lowercase();
149        component.starts_with(".env.")
150            || component.starts_with(".dev.vars.")
151            || component.ends_with(".key")
152            || component.ends_with(".pem")
153            || component.ends_with(".p12")
154            || component.ends_with(".pfx")
155            || component.ends_with(".jks")
156            || component.ends_with(".keystore")
157            || component == "terraform.tfstate"
158            || component.starts_with("terraform.tfstate.")
159    })
160}
161
162/// How the daemon classifies paths: the SDK's patterns, its own config and
163/// env files (fixed at startup), and any env file its environment names.
164///
165/// The default protects no daemon files; only tests use it.
166#[derive(Debug, Clone, Default)]
167pub struct DaemonPaths {
168    classifier: std::sync::Arc<PathClassifier>,
169}
170
171impl DaemonPaths {
172    /// `protected` holds the daemon's own config and env files. They change
173    /// only through `manage_config`, never through the file tools.
174    pub fn new(protected: Vec<PathBuf>) -> Self {
175        Self {
176            classifier: std::sync::Arc::new(PathClassifier::new(protected)),
177        }
178    }
179
180    /// True for files that hold secrets (keys, credentials, env files, the
181    /// daemon's own config). Used by `read_file`.
182    pub fn is_secret(&self, path: &Path) -> bool {
183        self.classifier.is_secret(path) || is_configured_env_file(path)
184    }
185
186    /// Like [`DaemonPaths::is_secret`] but without the `.env.*` / `*.key`
187    /// name-shape rules, so a template file is judged by where it lives alone.
188    pub fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
189        self.classifier.is_secret_ignoring_name_shape(path) || is_configured_env_file(path)
190    }
191
192    /// True for paths the file tools must not write.
193    pub fn is_sensitive(&self, path: &Path) -> bool {
194        self.classifier.is_sensitive(path) || is_configured_env_file(path)
195    }
196
197    /// True for the daemon's own config and env files given at startup.
198    pub fn is_own_file(&self, path: &Path) -> bool {
199        self.classifier.is_protected(path)
200    }
201}
202
203/// Env files named by the daemon's own environment variables
204/// (`AIDAEMON_ENV_FILE`, `AIDAEMON_RUNTIME_ENV_FILE`), wherever they live.
205fn is_configured_env_file(path: &Path) -> bool {
206    ["AIDAEMON_ENV_FILE", "AIDAEMON_RUNTIME_ENV_FILE"]
207        .iter()
208        .filter_map(std::env::var_os)
209        .filter(|value| !value.is_empty())
210        .any(|value| same_file(Path::new(&value), path))
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    fn path(p: &str) -> &Path {
218        Path::new(p)
219    }
220
221    #[test]
222    fn secrets_and_sensitive_paths() {
223        let classifier = PathClassifier::default();
224        for secret in [
225            "/home/synthetic/.ssh/id_ed25519",
226            "/srv/app/.env",
227            "/srv/app/.env.production",
228            "/srv/app/server.key",
229            "/home/synthetic/.aws/credentials",
230        ] {
231            assert!(classifier.is_secret(path(secret)), "{secret}");
232            assert!(classifier.is_sensitive(path(secret)), "{secret}");
233        }
234        // Sensitive to write, but not a secret to read.
235        assert!(classifier.is_sensitive(path("/srv/app/.git/config")));
236        assert!(!classifier.is_secret(path("/srv/app/.git/config")));
237        assert!(classifier.is_sensitive(path("/srv/infra/terraform.tfstate")));
238        // Ordinary files.
239        assert!(!classifier.is_sensitive(path("/srv/app/src/main.rs")));
240        // A component name, not a substring: "monkey" is not ".key".
241        assert!(!classifier.is_sensitive(path("/srv/app/monkey.txt")));
242    }
243
244    #[test]
245    fn name_shape_rules_can_be_ignored_for_templates() {
246        let classifier = PathClassifier::default();
247        let template = path("/srv/app/config/.env.example");
248        assert!(classifier.is_secret(template));
249        assert!(!classifier.is_secret_ignoring_name_shape(template));
250    }
251
252    #[test]
253    fn the_apps_own_files_are_protected() {
254        let own = PathBuf::from("/srv/synthetic-app/app.toml");
255        let classifier = PathClassifier::new(vec![own.clone()]);
256        assert!(classifier.is_protected(&own));
257        assert!(classifier.is_secret(&own));
258        assert!(classifier.is_sensitive(&own));
259        assert!(!PathClassifier::default().is_sensitive(&own));
260    }
261}