Skip to main content

aft_base/
bash_env.rs

1//! The fixed deny list for `bash.env` and per-call `env` names.
2//!
3//! Two strengths, both case-insensitive at config load:
4//!
5//! - refused at every tier: the names can hijack process startup, redirect
6//!   where tools (and AFT's own nested processes) find configuration and
7//!   storage, inject code into an interpreter, corrupt or redirect Git, or
8//!   drive AFT, the sandbox, or a build worker;
9//! - refused at the project tier only: user configuration may set them, but a
10//!   repository must not swap the user's credentials, identity, or the trust
11//!   chain of its network traffic.
12//!
13//! The list is fixed in code and changes only through review; a config-time
14//! extension could only ever tighten it, which nobody has asked for.
15
16use std::collections::HashMap;
17
18/// Names refused at every tier, matched case-insensitively.
19pub(crate) const BLOCKED_ENV_VARS: &[&str] = &[
20    // Loader injection (existing list).
21    "LD_PRELOAD",
22    "LD_LIBRARY_PATH",
23    "LD_AUDIT",
24    "DYLD_INSERT_LIBRARIES",
25    "DYLD_LIBRARY_PATH",
26    "DYLD_FALLBACK_LIBRARY_PATH",
27    // Shell startup.
28    "BASH_ENV",
29    "ENV",
30    "IFS",
31    "PATH",
32    "SHELLOPTS",
33    "BASHOPTS",
34    "PROMPT_COMMAND",
35    "PS4",
36    // Interpreter startup.
37    "PYTHONSTARTUP",
38    "PYTHONPATH",
39    "PYTHONHOME",
40    "PERL5OPT",
41    "PERL5LIB",
42    "PERLLIB",
43    "PERL5DB",
44    "RUBYOPT",
45    "RUBYLIB",
46    "NODE_OPTIONS",
47    "GCONV_PATH",
48    "LOCPATH",
49    "NLSPATH",
50    "HOSTALIASES",
51    "RESOLV_HOST_CONF",
52    // Lookup roots: where tools and AFT's own nested processes find config and
53    // storage. The sandbox overwrites the temp names and pins the cargo names,
54    // so a configured value would apply unsandboxed and silently vanish
55    // sandboxed.
56    "HOME",
57    "SHELL",
58    "TMPDIR",
59    "TMP",
60    "TEMP",
61    "XDG_CONFIG_HOME",
62    "XDG_DATA_HOME",
63    "XDG_CACHE_HOME",
64    "XDG_STATE_HOME",
65    "XDG_RUNTIME_DIR",
66    "CARGO_HOME",
67    "RUSTUP_HOME",
68    "USERPROFILE",
69    "APPDATA",
70    "LOCALAPPDATA",
71    "COMSPEC",
72    "PATHEXT",
73    "SYSTEMROOT",
74    "PSMODULEPATH",
75    // Further interpreter injectors.
76    "NODE_PATH",
77    "JAVA_TOOL_OPTIONS",
78    "_JAVA_OPTIONS",
79    "JDK_JAVA_OPTIONS",
80    "PYTHONUSERBASE",
81    // Git: AFT appends its hooks path through GIT_CONFIG_COUNT/KEY/VALUE, so a
82    // configured count corrupts it; the rest redirect the repository or run a
83    // program. Harmless knobs (GIT_TERMINAL_PROMPT, GIT_PAGER, GIT_AUTHOR_*)
84    // stay allowed.
85    "GIT_DIR",
86    "GIT_WORK_TREE",
87    "GIT_COMMON_DIR",
88    "GIT_INDEX_FILE",
89    "GIT_OBJECT_DIRECTORY",
90    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
91    "GIT_CEILING_DIRECTORIES",
92    "GIT_EXEC_PATH",
93    "GIT_TEMPLATE_DIR",
94    "GIT_SSH",
95    "GIT_SSH_COMMAND",
96    "GIT_ASKPASS",
97    "SSH_ASKPASS",
98    "GIT_EXTERNAL_DIFF",
99    "GIT_PROXY_COMMAND",
100    // AFT and module control: AFT carries its own controls in the same map.
101    // The runner request already strips these prefixes.
102    // (prefixes: AFT_, SUBC_, CORTEXKIT_, CORTEX_, CK_)
103    // Sandbox and build-slot control: strict workers clear the compile-server
104    // wrappers but relaxed mode only fills them when absent, the worker
105    // test-thread budget keeps any caller value, and workers drop the session
106    // bus.
107    "RUSTC_WRAPPER",
108    "CARGO_BUILD_RUSTC_WRAPPER",
109    "RUSTC_WORKSPACE_WRAPPER",
110    "RUST_TEST_THREADS",
111    "NEXTEST_TEST_THREADS",
112    "DBUS_SESSION_BUS_ADDRESS",
113];
114
115/// Prefixes refused at every tier, matched case-insensitively.
116pub(crate) const BLOCKED_ENV_PREFIXES: &[&str] = &[
117    "LD_",
118    "DYLD_",
119    "BASH_FUNC_",
120    "GIT_CONFIG",
121    "AFT_",
122    "SUBC_",
123    "CORTEXKIT_",
124    "CORTEX_",
125    "CK_",
126    "SCCACHE_",
127];
128
129/// The subset of [`BLOCKED_ENV_PREFIXES`] that belongs to AFT and its module
130/// transport. User configuration must not set these, but a per-call `env` may:
131/// the request is the agent's explicit choice for one command, and the product
132/// strips these names from the child environment anyway, so refusing them only
133/// breaks callers that pass them on purpose.
134const MODULE_CONTROL_PREFIXES: &[&str] = &["AFT_", "SUBC_", "CORTEXKIT_", "CORTEX_", "CK_"];
135
136/// Names refused at the project tier only. User configuration is the user's own
137/// file and may set them.
138pub(crate) const PROJECT_ONLY_BLOCKED_ENV_VARS: &[&str] = &[
139    // Credentials and identity: a repository must not swap the user's identity
140    // or point tools at its own endpoints.
141    "SSH_AUTH_SOCK",
142    "GOOGLE_APPLICATION_CREDENTIALS",
143    "KUBECONFIG",
144    "DOCKER_HOST",
145    "DOCKER_CONFIG",
146    // Network and TLS trust: a user sets these for a corporate proxy; a
147    // repository must not.
148    "HTTP_PROXY",
149    "HTTPS_PROXY",
150    "ALL_PROXY",
151    "NO_PROXY",
152    "SSL_CERT_FILE",
153    "SSL_CERT_DIR",
154    "NODE_EXTRA_CA_CERTS",
155    "REQUESTS_CA_BUNDLE",
156    "CURL_CA_BUNDLE",
157    "GIT_SSL_NO_VERIFY",
158    "NODE_TLS_REJECT_UNAUTHORIZED",
159];
160
161/// Substrings refused at the project tier only, mirroring
162/// `exec_remote::request::denied_environment_name` so one credential vocabulary
163/// governs both the remote filter and project values.
164pub(crate) const PROJECT_ONLY_BLOCKED_ENV_SUBSTRINGS: &[&str] = &[
165    "TOKEN",
166    "SECRET",
167    "PASSWORD",
168    "PASSWD",
169    "PRIVATE_KEY",
170    "API_KEY",
171    "CREDENTIAL",
172];
173
174/// Prefixes refused at the project tier only (credentials and identity).
175pub(crate) const PROJECT_ONLY_BLOCKED_ENV_PREFIXES: &[&str] = &["AWS_", "GH_", "GITHUB_"];
176
177/// Which tier a `bash.env` map came from. The strength of the deny list and
178/// the disclosure wording both depend on it.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum BashEnvTier {
181    User,
182    Project,
183}
184
185impl BashEnvTier {
186    pub fn label(self) -> &'static str {
187        match self {
188            Self::User => "user",
189            Self::Project => "project",
190        }
191    }
192}
193
194fn matches_name(key: &str, name: &str) -> bool {
195    key.eq_ignore_ascii_case(name)
196}
197
198fn starts_with_prefix(key: &str, prefix: &str) -> bool {
199    // Compare bytes rather than slicing at a byte index: a configured name may
200    // be non-ASCII, and a cut inside a multi-byte character would panic.
201    let key = key.as_bytes();
202    let prefix = prefix.as_bytes();
203    key.len() >= prefix.len() && key[..prefix.len()].eq_ignore_ascii_case(prefix)
204}
205
206/// Whether `key` is refused at every tier.
207pub(crate) fn is_blocked_env_key(key: &str) -> bool {
208    BLOCKED_ENV_VARS
209        .iter()
210        .any(|blocked| matches_name(key, blocked))
211        || BLOCKED_ENV_PREFIXES
212            .iter()
213            .any(|prefix| starts_with_prefix(key, prefix))
214        || is_preexec_hijack_env_key(key)
215}
216
217// A provider's purpose is to replace PATH. Every other name uses the fixed deny
218// list for user configuration, which refuses module-control and startup names.
219const PROVIDER_PATH_EXCEPTION: &str = "PATH";
220
221pub fn is_blocked_provider_env_key(key: &str) -> bool {
222    !key.eq_ignore_ascii_case(PROVIDER_PATH_EXCEPTION) && is_blocked_env_key(key)
223}
224
225/// Whether `key` may not be set from project configuration. Names refused at
226/// every tier are also refused here: a single reason is reported per key.
227pub(crate) fn is_project_blocked_env_key(key: &str) -> bool {
228    if is_blocked_env_key(key) {
229        return true;
230    }
231    PROJECT_ONLY_BLOCKED_ENV_VARS
232        .iter()
233        .any(|blocked| matches_name(key, blocked))
234        || PROJECT_ONLY_BLOCKED_ENV_PREFIXES
235            .iter()
236            .any(|prefix| starts_with_prefix(key, prefix))
237        || {
238            let upper = key.to_ascii_uppercase();
239            PROJECT_ONLY_BLOCKED_ENV_SUBSTRINGS
240                .iter()
241                .any(|part| upper.contains(part))
242        }
243}
244
245/// The first name in `env` that `tier` may not set, if any.
246pub(crate) fn first_refused_env_key(
247    env: &std::collections::BTreeMap<String, String>,
248    tier: BashEnvTier,
249) -> Option<&str> {
250    env.keys()
251        .find(|key| match tier {
252            BashEnvTier::User => is_blocked_env_key(key),
253            BashEnvTier::Project => is_project_blocked_env_key(key),
254        })
255        .map(String::as_str)
256}
257
258/// Whether `key` is refused on a per-call `env` map. This is the config rule
259/// minus the module-control prefixes: those names never reach a child (AFT
260/// strips them), and a call that passes one explicitly is asking for it.
261pub(crate) fn is_blocked_request_env_key(key: &str) -> bool {
262    if MODULE_CONTROL_PREFIXES
263        .iter()
264        .any(|prefix| starts_with_prefix(key, prefix))
265    {
266        return BLOCKED_ENV_VARS
267            .iter()
268            .any(|blocked| matches_name(key, blocked));
269    }
270    is_blocked_env_key(key)
271}
272
273pub fn first_blocked_env_key(env: &HashMap<String, String>) -> Option<&str> {
274    env.keys()
275        .find(|key| is_blocked_request_env_key(key))
276        .map(String::as_str)
277}
278
279/// Startup hooks that execute code before a command can enter its sandbox.
280/// These names must be rejected for user-configured and per-call environments.
281pub fn is_preexec_hijack_env_key(key: &str) -> bool {
282    if starts_with_prefix(key, "LD_")
283        || starts_with_prefix(key, "DYLD_")
284        || starts_with_prefix(key, "BASH_FUNC_")
285    {
286        return true;
287    }
288    matches!(
289        key,
290        // The match is case-sensitive because every name here is uppercase;
291        // fold first so `pythonpath` cannot slip past on Unix, where the name
292        // still reaches an interpreter that reads it.
293        _ if [
294            "BASH_ENV",
295            "ENV",
296            "SHELLOPTS",
297            "BASHOPTS",
298            "PROMPT_COMMAND",
299            "PS4",
300            "IFS",
301            "PYTHONSTARTUP",
302            "PYTHONPATH",
303            "PYTHONHOME",
304            "PERL5OPT",
305            "PERL5LIB",
306            "PERLLIB",
307            "PERL5DB",
308            "RUBYOPT",
309            "RUBYLIB",
310            "NODE_OPTIONS",
311            "GCONV_PATH",
312            "LOCPATH",
313            "NLSPATH",
314            "HOSTALIASES",
315            "RESOLV_HOST_CONF",
316        ]
317        .iter()
318        .any(|name| matches_name(key, name))
319    )
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn request_environment_rejects_both_blocklists() {
328        for key in ["PATH", "LD_CUSTOM", "BASH_FUNC_echo%%", "NODE_OPTIONS"] {
329            assert!(is_blocked_env_key(key), "{key}");
330        }
331        assert!(!is_blocked_env_key("TZ"));
332    }
333
334    #[test]
335    fn blocked_names_fold_case_on_every_platform() {
336        for key in [
337            "path",
338            "Path",
339            "ld_preload",
340            "aft_internal_linux_scope",
341            "Git_Config_Count",
342            "sccache_dir",
343            "home",
344        ] {
345            assert!(is_blocked_env_key(key), "{key}");
346        }
347    }
348
349    #[test]
350    fn a_non_ascii_name_is_refused_instead_of_panicking() {
351        // A byte-index prefix check panics when it cuts inside a multi-byte
352        // character. Each name below starts with a refused prefix ("LD_",
353        // "AFT_", "SCCACHE_") and continues with one, so the check must reach
354        // a decision instead of slicing mid-character.
355        assert!(
356            is_blocked_env_key("LD_é"),
357            "LD_-prefixed name must be refused"
358        );
359        assert!(
360            is_blocked_env_key("AFT_é"),
361            "AFT_-prefixed name must be refused"
362        );
363        assert!(is_blocked_env_key("SCCACHE_日本"));
364        // A name sharing no refused prefix stays allowed.
365        assert!(!is_blocked_env_key("é"));
366        assert!(!is_blocked_env_key("IBToolNeverDequeé"));
367        assert!(!is_project_blocked_env_key("é"));
368    }
369
370    #[test]
371    fn module_control_names_are_refused_in_config_and_allowed_per_call() {
372        // Configuration must never set these, but a call may pass one: AFT
373        // strips them from the child anyway, and refusing them only breaks a
374        // caller that asks for them explicitly.
375        for key in ["AFT_INTERNAL_LINUX_SCOPE", "SUBC_MODULE_ID", "CORTEX_X"] {
376            let request_env = std::collections::HashMap::from([(key.to_string(), "1".to_string())]);
377            assert!(
378                first_blocked_env_key(&request_env).is_none(),
379                "{key} must be allowed on a per-call env"
380            );
381            let config_env = std::collections::BTreeMap::from([(key.to_string(), "1".to_string())]);
382            assert_eq!(
383                first_refused_env_key(&config_env, BashEnvTier::User),
384                Some(key),
385                "{key} must still be refused in configuration"
386            );
387        }
388        // Names outside the module prefixes keep the full per-call rule.
389        for key in ["PATH", "GIT_CONFIG_COUNT", "NODE_OPTIONS", "LD_PRELOAD"] {
390            let request_env = std::collections::HashMap::from([(key.to_string(), "1".to_string())]);
391            assert_eq!(first_blocked_env_key(&request_env), Some(key), "{key}");
392        }
393    }
394
395    #[test]
396    fn request_environment_keeps_harmless_git_and_project_names() {
397        for key in [
398            "TZ",
399            "IBToolNeverDeque",
400            "GIT_TERMINAL_PROMPT",
401            "GIT_PAGER",
402            "GIT_AUTHOR_NAME",
403        ] {
404            assert!(!is_blocked_env_key(key), "{key}");
405            assert!(!is_project_blocked_env_key(key), "{key}");
406        }
407    }
408
409    #[test]
410    fn credentials_and_proxy_settings_are_project_tier_only() {
411        for key in [
412            "API_KEY",
413            "NPM_TOKEN",
414            "GITHUB_TOKEN",
415            "AWS_PROFILE",
416            "GH_HOST",
417            "SSH_AUTH_SOCK",
418            "HTTPS_PROXY",
419            "NO_PROXY",
420            "NODE_EXTRA_CA_CERTS",
421        ] {
422            assert!(!is_blocked_env_key(key), "user tier must keep {key}");
423            assert!(
424                is_project_blocked_env_key(key),
425                "project tier must refuse {key}"
426            );
427        }
428    }
429}