Skip to main content

codewhale_runtime/
child_env.rs

1//! Sanitized environment handling for child processes.
2
3use std::collections::HashMap;
4use std::ffi::{OsStr, OsString};
5
6#[cfg(windows)]
7use std::os::windows::ffi::{OsStrExt, OsStringExt};
8#[cfg(windows)]
9use windows::Win32::Foundation::{ERROR_MORE_DATA, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS};
10#[cfg(windows)]
11use windows::Win32::System::Environment::ExpandEnvironmentStringsW;
12#[cfg(windows)]
13use windows::Win32::System::Registry::{
14    HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, REG_EXPAND_SZ, REG_SZ, REG_VALUE_TYPE,
15    RegCloseKey, RegEnumValueW, RegOpenKeyExW,
16};
17#[cfg(windows)]
18use windows::core::{PCWSTR, PWSTR};
19
20/// Convert a string env map into owned OS strings for child env helpers.
21pub fn string_map_env(
22    env: &HashMap<String, String>,
23) -> impl Iterator<Item = (OsString, OsString)> + '_ {
24    env.iter()
25        .map(|(key, value)| (OsString::from(key), OsString::from(value)))
26}
27
28/// Return the environment for a child process after dropping parent secrets.
29///
30/// `overrides` are trusted call-site values, such as sandbox markers, hook
31/// variables, MCP server config, or RLM context path. They are applied after the
32/// parent allowlist so explicit values win.
33pub fn sanitized_child_env<I, K, V>(overrides: I) -> Vec<(OsString, OsString)>
34where
35    I: IntoIterator<Item = (K, V)>,
36    K: AsRef<OsStr>,
37    V: AsRef<OsStr>,
38{
39    let mut env = Vec::new();
40    #[cfg(windows)]
41    append_sanitized_child_env_candidates(&mut env, windows_registry_env_vars());
42    for (key, value) in std::env::vars_os() {
43        append_sanitized_child_env_candidate(&mut env, key, value);
44    }
45    for (key, value) in overrides {
46        upsert_env(
47            &mut env,
48            key.as_ref().to_os_string(),
49            value.as_ref().to_os_string(),
50        );
51    }
52    #[cfg(windows)]
53    fill_windows_common_program_files(&mut env);
54    // OS sandboxes set CODEWHALE_SANDBOX (seatbelt / bwrap / windows). sccache
55    // and other RUSTC_WRAPPER compilers need sockets or files those sandboxes
56    // deny, so nested `cargo` fails with "Operation not permitted" before any
57    // crate compiles (seen on macOS CI seatbelt). Drop the wrapper so rustc
58    // still runs under the sandbox; unsandboxed children keep it. A
59    // CARGO_BUILD_BUILD_DIR outside the sandbox's writable roots fails the
60    // same way when nested cargo creates that directory.
61    if env
62        .iter()
63        .any(|(key, _)| normalize_key(key) == "CODEWHALE_SANDBOX")
64    {
65        env.retain(|(key, _)| {
66            let key = normalize_key(key);
67            key != "RUSTC_WRAPPER" && key != "CARGO_BUILD_BUILD_DIR"
68        });
69    }
70    env
71}
72
73/// Environment for a Codewhale runtime child (a Fleet worker), built from a
74/// snapshot of the parent environment.
75///
76/// It uses the same allowlist as [`sanitized_child_env`], so provider keys and
77/// other secret-shaped variables are dropped, with one deliberate difference:
78/// proxy URLs keep their `user:password@` part. The runtime child is Codewhale
79/// itself, not a model-chosen program, and must reach its provider through the
80/// same authenticated proxy as the parent. Every tool it starts builds its own
81/// environment through [`sanitized_child_env`], which strips that userinfo at
82/// the model-facing boundary.
83pub fn sanitized_runtime_env_from<B, K, V>(base_environment: B) -> Vec<(OsString, OsString)>
84where
85    B: IntoIterator<Item = (K, V)>,
86    K: AsRef<OsStr>,
87    V: AsRef<OsStr>,
88{
89    let mut env = Vec::new();
90    for (key, value) in base_environment {
91        if is_allowed_parent_env_key(key.as_ref()) {
92            upsert_env(
93                &mut env,
94                key.as_ref().to_os_string(),
95                value.as_ref().to_os_string(),
96            );
97        }
98    }
99    env
100}
101
102pub fn apply_to_command<I, K, V>(cmd: &mut std::process::Command, overrides: I)
103where
104    I: IntoIterator<Item = (K, V)>,
105    K: AsRef<OsStr>,
106    V: AsRef<OsStr>,
107{
108    cmd.env_clear();
109    for (key, value) in sanitized_child_env(overrides) {
110        cmd.env(key, value);
111    }
112}
113
114pub fn apply_to_tokio_command<I, K, V>(cmd: &mut tokio::process::Command, overrides: I)
115where
116    I: IntoIterator<Item = (K, V)>,
117    K: AsRef<OsStr>,
118    V: AsRef<OsStr>,
119{
120    cmd.env_clear();
121    for (key, value) in sanitized_child_env(overrides) {
122        cmd.env(key, value);
123    }
124}
125
126/// Parent variables git needs beyond the base allowlist: the ssh agent for
127/// remote transports, where the user's global config lives, a pinned ssh
128/// transport, and author/committer identity. None of them is a secret value.
129const GIT_PASSTHROUGH_KEYS: &[&str] = &[
130    "SSH_AUTH_SOCK",
131    "SSH_AGENT_PID",
132    "GNUPGHOME",
133    "XDG_CONFIG_HOME",
134    "GIT_SSH",
135    "GIT_SSH_COMMAND",
136    "GIT_SSH_VARIANT",
137    "GIT_EXEC_PATH",
138    "GIT_CONFIG_GLOBAL",
139    "GIT_CONFIG_SYSTEM",
140    "GIT_CONFIG_NOSYSTEM",
141    "GIT_CEILING_DIRECTORIES",
142    "GIT_SSL_CAINFO",
143    "GIT_SSL_CAPATH",
144    "GIT_AUTHOR_NAME",
145    "GIT_AUTHOR_EMAIL",
146    "GIT_COMMITTER_NAME",
147    "GIT_COMMITTER_EMAIL",
148];
149
150/// Start a git child from the sanitized environment plus
151/// `GIT_PASSTHROUGH_KEYS`. Repository config (`core.fsmonitor`, hooks,
152/// filters, `core.sshCommand`) can make any git command run a program chosen
153/// by whoever wrote the workspace, so git must not hand that program the
154/// parent's credentials.
155pub fn apply_to_git_command(cmd: &mut std::process::Command) {
156    let passthrough: Vec<(OsString, OsString)> = std::env::vars_os()
157        .filter(|(key, _)| {
158            let normalized = normalize_key(key);
159            GIT_PASSTHROUGH_KEYS.contains(&normalized.as_str())
160        })
161        .collect();
162    apply_to_command(cmd, passthrough);
163}
164
165#[cfg(not(target_env = "ohos"))]
166pub fn apply_to_pty_command<I, K, V>(cmd: &mut portable_pty::CommandBuilder, overrides: I)
167where
168    I: IntoIterator<Item = (K, V)>,
169    K: AsRef<OsStr>,
170    V: AsRef<OsStr>,
171{
172    cmd.env_clear();
173    for (key, value) in sanitized_child_env(overrides) {
174        cmd.env(key, value);
175    }
176}
177
178/// Build the sanitized child environment used for MCP stdio servers.
179///
180/// MCP stdio servers are user-configured integrations declared in
181/// `~/.deepseek/mcp.json` (or equivalent). They are not arbitrary processes
182/// the agent decided to launch on its own. To avoid breaking common
183/// `npx ...` / `uvx ...` / `python -m mcp_server_*` setups (#1244), the
184/// MCP-launch allowlist is wider than the base shell-tool allowlist: it
185/// also passes through Node, npm, Python, Ruby, Java, proxy, and CA-bundle
186/// bootstrap variables, plus the non-secret AWS profile/region/config-path
187/// selectors. It still drops arbitrary parent env so secret-bearing vars
188/// (AWS keys and session tokens, `*_API_KEY`, `GITHUB_TOKEN`, …) are not
189/// silently exported.
190pub fn sanitized_mcp_env<I, K, V>(overrides: I) -> Vec<(OsString, OsString)>
191where
192    I: IntoIterator<Item = (K, V)>,
193    K: AsRef<OsStr>,
194    V: AsRef<OsStr>,
195{
196    let mut env = Vec::new();
197    for (key, value) in std::env::vars_os() {
198        if is_allowed_mcp_env_key(&key) {
199            upsert_env(&mut env, key, value);
200        }
201    }
202    for (key, value) in overrides {
203        upsert_env(
204            &mut env,
205            key.as_ref().to_os_string(),
206            value.as_ref().to_os_string(),
207        );
208    }
209    env
210}
211
212/// Build the environment for a reviewed plugin-contributed MCP child.
213///
214/// Unlike user-authored MCP configuration, a plugin must name every extra
215/// environment source during trust review. Start from the ordinary
216/// secret-scrubbed child environment, remove ambient proxy variables whose
217/// URLs may themselves contain credentials, then apply only reviewed
218/// overrides. `NO_PROXY` remains safe routing metadata.
219#[cfg(test)]
220pub fn sanitized_plugin_mcp_env<I, K, V>(overrides: I) -> Vec<(OsString, OsString)>
221where
222    I: IntoIterator<Item = (K, V)>,
223    K: AsRef<OsStr>,
224    V: AsRef<OsStr>,
225{
226    sanitized_plugin_mcp_env_from(std::env::vars_os(), overrides)
227}
228
229/// Build a reviewed plugin child environment from an immutable host snapshot.
230///
231/// This is separate from `sanitized_plugin_mcp_env` so a repository-local
232/// dotenv file loaded after startup cannot add or replace inherited values.
233pub fn sanitized_plugin_mcp_env_from<B, BK, BV, I, K, V>(
234    base_environment: B,
235    overrides: I,
236) -> Vec<(OsString, OsString)>
237where
238    B: IntoIterator<Item = (BK, BV)>,
239    BK: AsRef<OsStr>,
240    BV: AsRef<OsStr>,
241    I: IntoIterator<Item = (K, V)>,
242    K: AsRef<OsStr>,
243    V: AsRef<OsStr>,
244{
245    let mut env = Vec::new();
246    for (key, value) in base_environment {
247        if is_allowed_parent_env_key(key.as_ref()) {
248            upsert_env(
249                &mut env,
250                key.as_ref().to_os_string(),
251                value.as_ref().to_os_string(),
252            );
253        }
254    }
255    env.retain(|(key, _)| {
256        !matches!(
257            normalize_key(key).as_str(),
258            "HTTP_PROXY" | "HTTPS_PROXY" | "ALL_PROXY" | "FTP_PROXY"
259        )
260    });
261    for (key, value) in overrides {
262        upsert_env(
263            &mut env,
264            key.as_ref().to_os_string(),
265            value.as_ref().to_os_string(),
266        );
267    }
268    env
269}
270
271pub fn apply_to_tokio_command_mcp<I, K, V>(cmd: &mut tokio::process::Command, overrides: I)
272where
273    I: IntoIterator<Item = (K, V)>,
274    K: AsRef<OsStr>,
275    V: AsRef<OsStr>,
276{
277    cmd.env_clear();
278    for (key, value) in sanitized_mcp_env(overrides) {
279        cmd.env(key, value);
280    }
281}
282
283fn is_allowed_parent_env_key(key: &OsStr) -> bool {
284    let key = key.to_string_lossy();
285    let normalized = key.to_ascii_uppercase();
286    matches!(
287        normalized.as_str(),
288        "PATH"
289            // Desktop connection metadata. Computer-use tools must reach
290            // the existing X11/Wayland and accessibility bus sessions. Keep
291            // this list exact; never inherit arbitrary XDG/DBUS namespaces
292            // or read the Xauthority credential file into the environment.
293            | "DISPLAY"
294            | "WAYLAND_DISPLAY"
295            | "XDG_RUNTIME_DIR"
296            | "XDG_SESSION_TYPE"
297            | "DBUS_SESSION_BUS_ADDRESS"
298            | "XAUTHORITY"
299            | "HOME"
300            | "USER"
301            | "USERNAME"
302            | "LOGNAME"
303            | "LANG"
304            | "LANGUAGE"
305            | "LC_ALL"
306            | "LC_CTYPE"
307            | "LC_COLLATE"
308            | "LC_MESSAGES"
309            | "LC_MONETARY"
310            | "LC_NUMERIC"
311            | "LC_TIME"
312            | "LC_PAPER"
313            | "LC_NAME"
314            | "LC_ADDRESS"
315            | "LC_TELEPHONE"
316            | "LC_MEASUREMENT"
317            | "LC_IDENTIFICATION"
318            | "LC_TERMINAL"
319            | "LC_TERMINAL_VERSION"
320            | "TERM"
321            | "COLORTERM"
322            | "NO_COLOR"
323            | "FORCE_COLOR"
324            | "SHELL"
325            | "TMPDIR"
326            | "TMP"
327            | "TEMP"
328            | "__CF_USER_TEXT_ENCODING"
329            | "SYSTEMROOT"
330            | "WINDIR"
331            | "COMSPEC"
332            | "PATHEXT"
333            | "USERPROFILE"
334            | "HOMEDRIVE"
335            | "HOMEPATH"
336            // Preserve Windows toolchain context when the parent shell has
337            // already loaded VsDevCmd / vcvars. Without these, `exec_shell`
338            // can find `link.exe` via PATH but still fail to resolve
339            // SDK/CRT libraries like `kernel32.lib`, so any model-driven
340            // `cargo build` from inside the TUI silently breaks on
341            // Windows installs that don't run inside a Developer Command
342            // Prompt. Harvested from PR #1487.
343            | "LIB"
344            | "LIBPATH"
345            | "INCLUDE"
346            | "VSINSTALLDIR"
347            | "VCINSTALLDIR"
348            | "VCTOOLSINSTALLDIR"
349            | "WINDOWSSDKDIR"
350            | "WINDOWSSDKVERSION"
351            | "UNIVERSALCRTSDKDIR"
352            | "UCRTVERSION"
353            | "EXTENSIONSDKDIR"
354            | "DEVENVDIR"
355            | "VISUALSTUDIOVERSION"
356            // Windows app-data + .NET/NuGet paths. `dotnet restore` (and npm,
357            // pip, etc.) resolve their package caches, HTTP cache, and config
358            // under %APPDATA% / %LOCALAPPDATA% / %ProgramData% / %ProgramFiles%.
359            // The sanitized child env dropped these, so restore failed through
360            // `exec_shell` even though it worked in the user's own shell, where
361            // the full environment is present (#1857). `DOTNET_*` (below) covers
362            // DOTNET_ROOT and the CLI flags.
363            | "APPDATA"
364            | "LOCALAPPDATA"
365            | "PROGRAMDATA"
366            | "ALLUSERSPROFILE"
367            | "PROGRAMFILES"
368            | "PROGRAMFILES(X86)"
369            | "PROGRAMW6432"
370            | "COMMONPROGRAMFILES"
371            | "COMMONPROGRAMFILES(X86)"
372            | "COMMONPROGRAMW6432"
373            | "PROCESSOR_ARCHITECTURE"
374            | "NUGET_PACKAGES"
375            | "NUGET_HTTP_CACHE_PATH"
376            // Standard proxy variables are needed by shell tasks in
377            // corporate and WSL environments where direct internet egress is
378            // blocked. They intentionally exclude token/API-key-shaped vars.
379            | "HTTP_PROXY"
380            | "HTTPS_PROXY"
381            | "NO_PROXY"
382            | "ALL_PROXY"
383            | "FTP_PROXY"
384            // Python uses these to pick stdio/default encodings when stdout is
385            // piped instead of attached to a Windows console (#4202).
386            | "PYTHONIOENCODING"
387            | "PYTHONUTF8"
388            // Rustup installs `cargo`/`rustc` as shims and resolves the real
389            // toolchain through these non-secret bootstrap paths. Dropping
390            // them makes an otherwise working Rust toolchain unusable in
391            // official Rust containers and other non-default installations.
392            | "CARGO_HOME"
393            | "RUSTUP_HOME"
394            | "RUSTUP_TOOLCHAIN"
395            // Non-secret build and toolchain configuration. Model-run
396            // builds and tests (`run_tests`, verifier and task gates,
397            // language servers) must honour the same target dir, job limit,
398            // flags, active virtualenv and CA bundle as the user's own shell;
399            // dropping them caused full rebuilds, lost memory limits and TLS
400            // failures. `CARGO_*` is handled below without its secret-shaped
401            // and registry keys. Connection strings such as `DATABASE_URL`
402            // stay out: they usually embed a password. `RUSTC_WRAPPER` is
403            // kept for unsandboxed children only; see the CODEWHALE_SANDBOX
404            // scrub in `sanitized_child_env`.
405            | "RUSTFLAGS"
406            | "RUSTDOCFLAGS"
407            | "RUSTC_WRAPPER"
408            | "RUST_BACKTRACE"
409            | "RUST_LOG"
410            | "RUST_MIN_STACK"
411            | "RUST_TEST_THREADS"
412            | "VIRTUAL_ENV"
413            | "CONDA_PREFIX"
414            | "CONDA_DEFAULT_ENV"
415            | "PYTHONPATH"
416            | "JAVA_HOME"
417            | "GOPATH"
418            | "GOROOT"
419            | "GOBIN"
420            | "GOFLAGS"
421            | "GOCACHE"
422            | "GOMODCACHE"
423            | "GOTOOLCHAIN"
424            | "GO111MODULE"
425            | "NVM_DIR"
426            | "NVM_BIN"
427            | "NVM_INC"
428            | "VOLTA_HOME"
429            | "NODE_PATH"
430            | "NODE_OPTIONS"
431            | "NODE_EXTRA_CA_CERTS"
432            | "SSL_CERT_FILE"
433            | "SSL_CERT_DIR"
434            | "REQUESTS_CA_BUNDLE"
435            | "CURL_CA_BUNDLE"
436    ) || is_allowed_cargo_config_key(&normalized)
437        || is_allowed_dotnet_child_env_key(&normalized)
438        || is_allowed_platform_path_like_child_env_key(&normalized)
439}
440
441fn is_allowed_dotnet_child_env_key(normalized: &str) -> bool {
442    const SECRET_WORDS: [&str; 8] = [
443        "KEY", "CONNSTR", "PWD", "PASS", "DSN", "AUTH", "BEARER", "COOKIE",
444    ];
445    const SWITCHES: &[&str] = &[
446        "ROOT",
447        "ROOT(X86)",
448        "HOST_PATH",
449        "NOLOGO",
450        "SKIP_FIRST_TIME_EXPERIENCE",
451        "MULTILEVEL_LOOKUP",
452        "ENVIRONMENT",
453        "BUNDLE_EXTRACT_BASE_DIR",
454        "NUGET_SIGNATURE_VERIFICATION",
455        "ADD_GLOBAL_TOOLS_TO_PATH",
456        "USE_POLLING_FILE_WATCHER",
457        "RUNNING_IN_CONTAINER",
458        "GENERATE_ASPNET_CERTIFICATE",
459        "TOOLS_ALLOW_MANIFEST_IN_ROOT",
460        "ADDITIONAL_DEPS",
461        "SHARED_STORE",
462        "STARTUP_HOOKS",
463        "PROCESSOR_COUNT",
464        "HTTPREPL_PREFERRED_EDITOR",
465        "SDK_VERSION",
466        "VERSION",
467        "GCSERVER",
468        "GCCONCURRENT",
469        "GCGEN0SIZE",
470        "GCHEAPHARDLIMIT",
471        "GCHEAPHARDLIMITPERCENT",
472        "GCHEAPCOUNT",
473        "GCHEAPAFFINITIZEMASK",
474        "GCNOAFFINITIZE",
475        "GCCONSERVEMEMORY",
476        "GCCPUGROUP",
477        "TIEREDCOMPILATION",
478        "TIEREDPGO",
479        "TC_QUICKJIT",
480        "TC_QUICKJITFORLOOPS",
481        "TC_ONSTACKREPLACEMENT",
482        "READYTORUN",
483        "ENABLEDIAGNOSTICS",
484        "ENABLEDIAGNOSTICS_IPC",
485        "ENABLEDIAGNOSTICS_DEBUGGER",
486        "ENABLEDIAGNOSTICS_PROFILER",
487        "DBGENABLEMINIDUMP",
488        "DBGMINIDUMPTYPE",
489        "DBGMINIDUMPNAME",
490        "CREATEDUMPDIAGNOSTICS",
491        "DIAGNOSTICPORTS",
492        "ENABLEEVENTPIPE",
493        "EVENTPIPEOUTPUTPATH",
494        "EVENTPIPECONFIG",
495        "ENABLEWRITEXOREXECUTE",
496        "THREAD_USEALLCPUGROUPS",
497    ];
498    const FAMILIES: &[&str] = &[
499        "ROOT_",
500        "CLI_",
501        "SYSTEM_",
502        "ROLL_FORWARD",
503        "WATCH_",
504        "MSBUILD_SDK_RESOLVER_",
505    ];
506    let Some(name) = normalized.strip_prefix("DOTNET_") else {
507        return false;
508    };
509    if !SWITCHES.contains(&name) && !FAMILIES.iter().any(|family| name.starts_with(family)) {
510        return false;
511    }
512    if name.contains("__") || name.contains(':') {
513        return false;
514    }
515    let compact: String = name.chars().filter(|c| *c != '_').collect();
516    !SECRET_WORDS.iter().any(|word| compact.contains(word))
517        && !is_secret_like_child_env_key(normalized)
518}
519
520/// Cargo's `CARGO_*` configuration namespace (`CARGO_TARGET_DIR`,
521/// `CARGO_BUILD_JOBS`, `CARGO_INCREMENTAL`, ...) minus anything that can carry
522/// a credential: registry tokens and credential providers live under
523/// `CARGO_REGISTRY_` / `CARGO_REGISTRIES_`, and secret-shaped names are
524/// dropped wherever they appear. `CARGO_HTTP_PROXY` is passed with its
525/// userinfo removed, like the other proxy variables.
526fn is_allowed_cargo_config_key(normalized: &str) -> bool {
527    normalized.starts_with("CARGO_")
528        && !normalized.starts_with("CARGO_REGISTRY_")
529        && !normalized.starts_with("CARGO_REGISTRIES_")
530        && !is_secret_like_child_env_key(normalized)
531}
532
533/// Proxy variables whose URL may embed `user:password@`.
534fn is_proxy_url_key(normalized: &str) -> bool {
535    matches!(
536        normalized,
537        "HTTP_PROXY" | "HTTPS_PROXY" | "ALL_PROXY" | "FTP_PROXY" | "CARGO_HTTP_PROXY"
538    )
539}
540
541/// Remove the `user:password@` part of a proxy URL so a child keeps the route
542/// (`scheme://host:port`) but not the proxy credentials. Values that are not
543/// valid UTF-8 cannot be inspected and are dropped.
544fn strip_proxy_userinfo(value: &OsStr) -> Option<OsString> {
545    let value = value.to_str()?;
546    let (scheme, rest) = match value.find("://") {
547        Some(index) => value.split_at(index + 3),
548        None => ("", value),
549    };
550    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
551    let (authority, tail) = rest.split_at(authority_end);
552    let host = authority
553        .rsplit_once('@')
554        .map_or(authority, |(_, host)| host);
555    Some(OsString::from(format!("{scheme}{host}{tail}")))
556}
557
558#[cfg(windows)]
559fn is_allowed_platform_path_like_child_env_key(normalized: &str) -> bool {
560    is_allowed_path_like_child_env_key(normalized)
561}
562
563#[cfg(not(windows))]
564fn is_allowed_platform_path_like_child_env_key(_normalized: &str) -> bool {
565    false
566}
567
568#[cfg(windows)]
569fn is_allowed_path_like_child_env_key(normalized: &str) -> bool {
570    if is_secret_like_child_env_key(normalized) {
571        return false;
572    }
573    normalized.ends_with("_ROOT")
574        || normalized.ends_with("_DIR")
575        || normalized.ends_with("_HOME")
576        || normalized.ends_with("_PATH")
577        || normalized.ends_with("_PATHS")
578        || normalized.ends_with("SDKROOT")
579}
580
581fn is_secret_like_child_env_key(normalized: &str) -> bool {
582    normalized.contains("SECRET")
583        || normalized.contains("TOKEN")
584        || normalized.contains("PASSWORD")
585        || normalized.contains("PASSWD")
586        || normalized.contains("CREDENTIAL")
587        || normalized.contains("API_KEY")
588        || normalized.contains("ACCESS_KEY")
589        || normalized.contains("PRIVATE_KEY")
590        || normalized.contains("CONNECTIONSTRING")
591        || normalized.ends_with("_KEY")
592}
593
594/// Allowlist for MCP stdio launches. Strict superset of
595/// `is_allowed_parent_env_key`. See `sanitized_mcp_env` for rationale.
596fn is_allowed_mcp_env_key(key: &OsStr) -> bool {
597    if is_allowed_parent_env_key(key) {
598        return true;
599    }
600    let key_str = key.to_string_lossy();
601    let normalized = key_str.to_ascii_uppercase();
602    if matches!(
603        normalized.as_str(),
604        // Node.js / npm / npx / pnpm / yarn / volta / corepack
605        "NVM_DIR"
606            | "NVM_BIN"
607            | "NVM_INC"
608            | "VOLTA_HOME"
609            | "COREPACK_HOME"
610            | "NODE_PATH"
611            | "NODE_OPTIONS"
612            | "NODE_EXTRA_CA_CERTS"
613            // Python ecosystem
614            | "PYTHONPATH"
615            | "PYTHONHOME"
616            | "PYTHONDONTWRITEBYTECODE"
617            | "PYTHONUNBUFFERED"
618            | "VIRTUAL_ENV"
619            | "POETRY_HOME"
620            | "PIPX_HOME"
621            | "PIPX_BIN_DIR"
622            // Ruby ecosystem
623            | "GEM_HOME"
624            | "GEM_PATH"
625            | "BUNDLE_PATH"
626            | "BUNDLE_GEMFILE"
627            // Java
628            | "JAVA_HOME"
629            // Network proxies (uppercase form; lowercase handled below)
630            | "HTTP_PROXY"
631            | "HTTPS_PROXY"
632            | "NO_PROXY"
633            | "ALL_PROXY"
634            | "FTP_PROXY"
635            // Custom CA bundles for corporate TLS interception
636            | "SSL_CERT_FILE"
637            | "SSL_CERT_DIR"
638            | "REQUESTS_CA_BUNDLE"
639            | "CURL_CA_BUNDLE"
640            // AWS profile/region selection and config-file locations. These
641            // name *which* credentials to use, never the credentials
642            // themselves: an AWS MCP server launched with `--profile x`
643            // still needs the user's config file and region to resolve an
644            // SSO session. Keys, secrets and session tokens
645            // (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`,
646            // `AWS_SESSION_TOKEN`, …) stay dropped.
647            | "AWS_PROFILE"
648            | "AWS_REGION"
649            | "AWS_DEFAULT_REGION"
650            | "AWS_CONFIG_FILE"
651            | "AWS_SHARED_CREDENTIALS_FILE"
652    ) {
653        return true;
654    }
655    // npm config namespace (NPM_CONFIG_PREFIX, NPM_CONFIG_CACHE, …) and
656    // uv (UV_CACHE_DIR, UV_PYTHON, …) — both ecosystems use a stable prefix
657    // for their bootstrap configuration, so allow the whole namespace.
658    if normalized.starts_with("NPM_CONFIG_") || normalized.starts_with("UV_") {
659        return true;
660    }
661    false
662}
663
664#[cfg(windows)]
665fn append_sanitized_child_env_candidates<I, K, V>(
666    env: &mut Vec<(OsString, OsString)>,
667    candidates: I,
668) where
669    I: IntoIterator<Item = (K, V)>,
670    K: Into<OsString>,
671    V: Into<OsString>,
672{
673    for (key, value) in candidates {
674        append_sanitized_child_env_candidate(env, key.into(), value.into());
675    }
676}
677
678fn append_sanitized_child_env_candidate(
679    env: &mut Vec<(OsString, OsString)>,
680    key: OsString,
681    value: OsString,
682) {
683    if !is_allowed_parent_env_key(&key) {
684        return;
685    }
686    if is_proxy_url_key(&normalize_key(&key)) {
687        if let Some(value) = strip_proxy_userinfo(&value) {
688            upsert_env(env, key, value);
689        }
690        return;
691    }
692    upsert_env(env, key, value);
693}
694
695fn upsert_env(env: &mut Vec<(OsString, OsString)>, key: OsString, value: OsString) {
696    let normalized = normalize_key(&key);
697    env.retain(|(existing, _)| normalize_key(existing) != normalized);
698    env.push((key, value));
699}
700
701#[cfg(windows)]
702fn windows_registry_env_vars() -> Vec<(OsString, OsString)> {
703    let mut env = Vec::new();
704    append_windows_registry_env_key(
705        &mut env,
706        HKEY_LOCAL_MACHINE,
707        r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
708    );
709    append_windows_registry_env_key(&mut env, HKEY_CURRENT_USER, "Environment");
710    env
711}
712
713#[cfg(windows)]
714fn append_windows_registry_env_key(env: &mut Vec<(OsString, OsString)>, root: HKEY, subkey: &str) {
715    let mut key = HKEY::default();
716    let subkey_wide = windows_wide_null(OsStr::new(subkey));
717    // SAFETY: `subkey_wide` is NUL-terminated and live; `key` is live.
718    let open =
719        unsafe { RegOpenKeyExW(root, PCWSTR(subkey_wide.as_ptr()), None, KEY_READ, &mut key) };
720    if open != ERROR_SUCCESS {
721        return;
722    }
723
724    let mut index = 0;
725    loop {
726        match read_windows_registry_env_value(key, index) {
727            RegistryEnvValue::Value(name, value) => {
728                upsert_env(env, name, value);
729                index += 1;
730            }
731            RegistryEnvValue::Skip => {
732                index += 1;
733            }
734            RegistryEnvValue::Done => break,
735        }
736    }
737
738    // SAFETY: `key` was opened above and is not used after.
739    let _ = unsafe { RegCloseKey(key) };
740}
741
742#[cfg(windows)]
743enum RegistryEnvValue {
744    Value(OsString, OsString),
745    Skip,
746    Done,
747}
748
749#[cfg(windows)]
750fn read_windows_registry_env_value(key: HKEY, index: u32) -> RegistryEnvValue {
751    let mut name = vec![0u16; 32_767];
752    let mut data = vec![0u8; 65_536];
753
754    loop {
755        let mut name_len = name.len() as u32;
756        let mut data_len = data.len() as u32;
757        let mut value_type = 0u32;
758        // SAFETY: buffers are live with matching lengths passed.
759        let status = unsafe {
760            RegEnumValueW(
761                key,
762                index,
763                Some(PWSTR(name.as_mut_ptr())),
764                &mut name_len,
765                None,
766                Some(&mut value_type),
767                Some(data.as_mut_ptr()),
768                Some(&mut data_len),
769            )
770        };
771
772        if status == ERROR_NO_MORE_ITEMS {
773            return RegistryEnvValue::Done;
774        }
775        if status == ERROR_MORE_DATA && resize_registry_data_buffer(&mut data, data_len) {
776            continue;
777        }
778        if status != ERROR_SUCCESS {
779            return RegistryEnvValue::Skip;
780        }
781        if value_type != REG_SZ.0 && value_type != REG_EXPAND_SZ.0 {
782            return RegistryEnvValue::Skip;
783        }
784
785        let name = OsString::from_wide(&name[..name_len as usize]);
786        let value = registry_utf16_value_from_bytes(&data[..data_len as usize]);
787        let value = if REG_VALUE_TYPE(value_type) == REG_EXPAND_SZ {
788            expand_windows_env_string(&value).unwrap_or(value)
789        } else {
790            value
791        };
792        return RegistryEnvValue::Value(name, value);
793    }
794}
795
796#[cfg(windows)]
797fn resize_registry_data_buffer(data: &mut Vec<u8>, required_len: u32) -> bool {
798    let Ok(required_len) = usize::try_from(required_len) else {
799        return false;
800    };
801    if required_len <= data.len() {
802        return false;
803    }
804    data.resize(required_len, 0);
805    true
806}
807
808#[cfg(windows)]
809fn registry_utf16_value_from_bytes(data: &[u8]) -> OsString {
810    let mut wide = data
811        .chunks_exact(2)
812        .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
813        .collect::<Vec<_>>();
814    while wide.last() == Some(&0) {
815        wide.pop();
816    }
817    OsString::from_wide(&wide)
818}
819
820#[cfg(windows)]
821fn expand_windows_env_string(value: &OsStr) -> Option<OsString> {
822    let src = windows_wide_null(value);
823    // SAFETY: `src` is NUL-terminated and live.
824    let required_len = unsafe { ExpandEnvironmentStringsW(PCWSTR(src.as_ptr()), None) };
825    if required_len == 0 {
826        return None;
827    }
828
829    let mut expanded = vec![0u16; required_len as usize];
830    // SAFETY: `src` is NUL-terminated; `expanded` has the queried length.
831    let written = unsafe { ExpandEnvironmentStringsW(PCWSTR(src.as_ptr()), Some(&mut expanded)) };
832    if written == 0 || written > required_len {
833        return None;
834    }
835
836    let len = usize::try_from(written).ok()?.saturating_sub(1);
837    Some(OsString::from_wide(&expanded[..len]))
838}
839
840#[cfg(windows)]
841fn windows_wide_null(value: &OsStr) -> Vec<u16> {
842    value.encode_wide().chain(std::iter::once(0)).collect()
843}
844
845#[cfg(any(windows, test))]
846fn fill_windows_common_program_files(env: &mut Vec<(OsString, OsString)>) {
847    for (key, default) in [
848        ("CommonProgramFiles", r"C:\Program Files\Common Files"),
849        (
850            "CommonProgramFiles(x86)",
851            r"C:\Program Files (x86)\Common Files",
852        ),
853        ("CommonProgramW6432", r"C:\Program Files\Common Files"),
854    ] {
855        let existing = env
856            .iter()
857            .find(|(existing, _)| normalize_key(existing) == normalize_key(OsStr::new(key)))
858            .map(|(_, value)| value.to_string_lossy().trim().is_empty());
859        if existing.unwrap_or(true) {
860            upsert_env(env, OsString::from(key), OsString::from(default));
861        }
862    }
863}
864
865fn normalize_key(key: &OsStr) -> String {
866    key.to_string_lossy().to_ascii_uppercase()
867}
868
869#[cfg(test)]
870mod tests {
871    use super::*;
872    use crate::test_support::EnvVarGuard;
873
874    #[test]
875    fn mcp_env_allowlist_inherits_base_keys() {
876        for key in [
877            "PATH",
878            "HOME",
879            "USER",
880            "TERM",
881            "LANG",
882            "SHELL",
883            "LIB",
884            "LIBPATH",
885            "INCLUDE",
886            "VCTOOLSINSTALLDIR",
887            "WINDOWSSDKDIR",
888        ] {
889            assert!(
890                is_allowed_mcp_env_key(OsStr::new(key)),
891                "MCP allowlist should inherit base key {key}"
892            );
893        }
894    }
895
896    #[test]
897    fn mcp_env_allowlist_includes_node_bootstrap_keys() {
898        for key in [
899            "NVM_DIR",
900            "NVM_BIN",
901            "NVM_INC",
902            "NODE_PATH",
903            "NODE_OPTIONS",
904            "NODE_EXTRA_CA_CERTS",
905            "VOLTA_HOME",
906            "COREPACK_HOME",
907        ] {
908            assert!(
909                is_allowed_mcp_env_key(OsStr::new(key)),
910                "MCP allowlist should include {key}"
911            );
912        }
913    }
914
915    #[test]
916    fn mcp_env_allowlist_includes_npm_config_prefix() {
917        for key in [
918            "NPM_CONFIG_PREFIX",
919            "NPM_CONFIG_CACHE",
920            "NPM_CONFIG_REGISTRY",
921            "NPM_CONFIG_USERCONFIG",
922        ] {
923            assert!(
924                is_allowed_mcp_env_key(OsStr::new(key)),
925                "MCP allowlist should include npm config key {key}"
926            );
927        }
928    }
929
930    #[test]
931    fn mcp_env_allowlist_includes_proxy_keys_either_case() {
932        for key in [
933            "HTTP_PROXY",
934            "HTTPS_PROXY",
935            "NO_PROXY",
936            "ALL_PROXY",
937            "http_proxy",
938            "https_proxy",
939            "no_proxy",
940            "all_proxy",
941        ] {
942            assert!(
943                is_allowed_mcp_env_key(OsStr::new(key)),
944                "MCP allowlist should include proxy key {key}"
945            );
946        }
947    }
948
949    #[test]
950    fn child_env_allowlist_includes_proxy_keys_either_case() {
951        for key in [
952            "HTTP_PROXY",
953            "HTTPS_PROXY",
954            "NO_PROXY",
955            "ALL_PROXY",
956            "FTP_PROXY",
957            "http_proxy",
958            "https_proxy",
959            "no_proxy",
960            "all_proxy",
961            "ftp_proxy",
962        ] {
963            assert!(
964                is_allowed_parent_env_key(OsStr::new(key)),
965                "child env allowlist should include proxy key {key}"
966            );
967        }
968    }
969
970    #[test]
971    fn child_env_allowlist_includes_dotnet_and_windows_appdata_keys() {
972        // #1857: dotnet restore / NuGet need these to find caches and config.
973        for key in [
974            "APPDATA",
975            "LOCALAPPDATA",
976            "PROGRAMDATA",
977            "ALLUSERSPROFILE",
978            "PROGRAMFILES",
979            "PROGRAMFILES(X86)",
980            "PROGRAMW6432",
981            "COMMONPROGRAMFILES",
982            "COMMONPROGRAMFILES(X86)",
983            "COMMONPROGRAMW6432",
984            "PROCESSOR_ARCHITECTURE",
985            "NUGET_PACKAGES",
986            "DOTNET_ROOT",
987            "DOTNET_CLI_TELEMETRY_OPTOUT",
988            "DOTNET_NOLOGO",
989            // Case-insensitive: the real Windows var is `ProgramFiles`.
990            "ProgramFiles",
991            "dotnet_root",
992        ] {
993            assert!(
994                is_allowed_parent_env_key(OsStr::new(key)),
995                "child env allowlist should include {key}"
996            );
997        }
998        // Guard: NuGet credential env vars must still be dropped.
999        assert!(
1000            !is_allowed_parent_env_key(OsStr::new("NuGetPackageSourceCredentials_feed")),
1001            "NuGet credential vars must not be exported to child processes"
1002        );
1003    }
1004
1005    #[test]
1006    fn child_env_allowlist_includes_python_stdio_encoding_vars() {
1007        for key in ["PYTHONIOENCODING", "PYTHONUTF8", "pythonioencoding"] {
1008            assert!(
1009                is_allowed_parent_env_key(OsStr::new(key)),
1010                "child env allowlist should include Python stdio encoding key {key}"
1011            );
1012        }
1013    }
1014
1015    #[test]
1016    fn child_env_allowlist_includes_rust_toolchain_bootstrap_keys() {
1017        for key in [
1018            "CARGO_HOME",
1019            "RUSTUP_HOME",
1020            "RUSTUP_TOOLCHAIN",
1021            "cargo_home",
1022        ] {
1023            assert!(
1024                is_allowed_parent_env_key(OsStr::new(key)),
1025                "child env allowlist should include Rust bootstrap key {key}"
1026            );
1027        }
1028    }
1029
1030    #[cfg(windows)]
1031    #[test]
1032    fn child_env_allowlist_includes_custom_path_like_vars_without_secrets() {
1033        // #3572: SDK/toolchain roots created through Windows Environment
1034        // Variables are often project-specific and cannot be exhaustively
1035        // named in the static allowlist.
1036        for key in [
1037            "BIMRV_SDK_ROOT",
1038            "ACME_TOOLCHAIN_HOME",
1039            "PROJECT_SDK_DIR",
1040            "CMAKE_PREFIX_PATH",
1041            "ANDROID_SDKROOT",
1042        ] {
1043            assert!(
1044                is_allowed_parent_env_key(OsStr::new(key)),
1045                "child env allowlist should include path-like key {key}"
1046            );
1047        }
1048
1049        for key in [
1050            "OPENAI_API_KEY",
1051            "GITHUB_TOKEN",
1052            "MY_SECRET_ROOT",
1053            "SERVICE_PASSWORD_DIR",
1054            "AWS_ACCESS_KEY_ID",
1055            "PRIVATE_KEY_PATH",
1056            "NuGetPackageSourceCredentials_feed",
1057        ] {
1058            assert!(
1059                !is_allowed_parent_env_key(OsStr::new(key)),
1060                "secret-like key {key} must not be exported to child processes"
1061            );
1062        }
1063    }
1064
1065    #[cfg(windows)]
1066    #[test]
1067    fn sanitized_child_env_preserves_custom_sdk_root_vars() {
1068        let _guard = crate::test_support::lock_test_env();
1069        let _sdk = EnvVarGuard::set("BIMRV_SDK_ROOT", r"F:\Lib\BimRv27.5");
1070        let _secret = EnvVarGuard::set("MY_SECRET_ROOT", r"F:\Secrets");
1071
1072        let env = sanitized_child_env(std::iter::empty::<(OsString, OsString)>());
1073
1074        assert!(
1075            env.iter()
1076                .any(|(key, value)| key == "BIMRV_SDK_ROOT" && value == r"F:\Lib\BimRv27.5"),
1077            "child env should preserve custom SDK roots"
1078        );
1079        assert!(
1080            env.iter().all(|(key, _)| key != "MY_SECRET_ROOT"),
1081            "secret-like path vars must still be dropped"
1082        );
1083    }
1084
1085    #[cfg(windows)]
1086    #[test]
1087    fn windows_registry_env_candidates_preserve_custom_sdk_roots() {
1088        use windows::Win32::System::Registry::{
1089            HKEY_CURRENT_USER, REG_SZ, RegCreateKeyW, RegDeleteTreeW, RegSetValueExW,
1090        };
1091
1092        let subkey = format!(r"Software\CodeWhaleTest\child_env_{}", std::process::id());
1093        let subkey_wide = windows_wide_null(OsStr::new(&subkey));
1094        let mut key = HKEY::default();
1095        let created =
1096            unsafe { RegCreateKeyW(HKEY_CURRENT_USER, PCWSTR(subkey_wide.as_ptr()), &mut key) };
1097        assert_eq!(created, ERROR_SUCCESS);
1098
1099        set_registry_string_value(key, "BIMRV_SDK_ROOT", r"F:\Lib\BimRv27.5");
1100        set_registry_string_value(key, "MY_SECRET_ROOT", r"F:\Secrets");
1101        let _ = unsafe { RegCloseKey(key) };
1102
1103        let mut candidates = Vec::new();
1104        append_windows_registry_env_key(&mut candidates, HKEY_CURRENT_USER, &subkey);
1105        let mut env = Vec::new();
1106        append_sanitized_child_env_candidates(&mut env, candidates);
1107
1108        let _ = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, PCWSTR(subkey_wide.as_ptr())) };
1109
1110        assert!(
1111            env.iter()
1112                .any(|(key, value)| key == "BIMRV_SDK_ROOT" && value == r"F:\Lib\BimRv27.5"),
1113            "registry child env should preserve custom SDK roots"
1114        );
1115        assert!(
1116            env.iter().all(|(key, _)| key != "MY_SECRET_ROOT"),
1117            "secret-like registry vars must still be dropped"
1118        );
1119
1120        fn set_registry_string_value(key: HKEY, name: &str, value: &str) {
1121            let name_wide = windows_wide_null(OsStr::new(name));
1122            let data = value
1123                .encode_utf16()
1124                .chain(std::iter::once(0))
1125                .flat_map(u16::to_le_bytes)
1126                .collect::<Vec<_>>();
1127            let status = unsafe {
1128                RegSetValueExW(key, PCWSTR(name_wide.as_ptr()), None, REG_SZ, Some(&data))
1129            };
1130            assert_eq!(status, ERROR_SUCCESS);
1131        }
1132    }
1133
1134    #[test]
1135    fn windows_common_program_files_defaults_replace_empty_values() {
1136        let mut env = vec![
1137            (OsString::from("CommonProgramFiles"), OsString::new()),
1138            (
1139                OsString::from("CommonProgramFiles(x86)"),
1140                OsString::from(" "),
1141            ),
1142            (
1143                OsString::from("CommonProgramW6432"),
1144                OsString::from(r"D:\Common Files"),
1145            ),
1146        ];
1147
1148        fill_windows_common_program_files(&mut env);
1149
1150        let get = |name: &str| {
1151            env.iter()
1152                .find(|(key, _)| normalize_key(key) == normalize_key(OsStr::new(name)))
1153                .map(|(_, value)| value.to_string_lossy().into_owned())
1154        };
1155        assert_eq!(
1156            get("CommonProgramFiles").as_deref(),
1157            Some(r"C:\Program Files\Common Files")
1158        );
1159        assert_eq!(
1160            get("CommonProgramFiles(x86)").as_deref(),
1161            Some(r"C:\Program Files (x86)\Common Files")
1162        );
1163        assert_eq!(
1164            get("CommonProgramW6432").as_deref(),
1165            Some(r"D:\Common Files")
1166        );
1167    }
1168
1169    #[test]
1170    fn mcp_env_allowlist_includes_python_bootstrap_keys() {
1171        for key in [
1172            "PYTHONPATH",
1173            "PYTHONHOME",
1174            "VIRTUAL_ENV",
1175            "PIPX_HOME",
1176            "PIPX_BIN_DIR",
1177            "POETRY_HOME",
1178        ] {
1179            assert!(
1180                is_allowed_mcp_env_key(OsStr::new(key)),
1181                "MCP allowlist should include python bootstrap key {key}"
1182            );
1183        }
1184    }
1185
1186    #[test]
1187    fn mcp_env_allowlist_includes_uv_prefixed_keys() {
1188        for key in ["UV_CACHE_DIR", "UV_INDEX_URL", "UV_PYTHON"] {
1189            assert!(
1190                is_allowed_mcp_env_key(OsStr::new(key)),
1191                "MCP allowlist should include uv prefixed key {key}"
1192            );
1193        }
1194    }
1195
1196    #[test]
1197    fn mcp_env_allowlist_includes_ca_bundles() {
1198        for key in [
1199            "SSL_CERT_FILE",
1200            "SSL_CERT_DIR",
1201            "REQUESTS_CA_BUNDLE",
1202            "CURL_CA_BUNDLE",
1203        ] {
1204            assert!(
1205                is_allowed_mcp_env_key(OsStr::new(key)),
1206                "MCP allowlist should include CA bundle key {key}"
1207            );
1208        }
1209    }
1210
1211    #[test]
1212    fn mcp_env_allowlist_includes_aws_profile_and_region_selectors() {
1213        for key in [
1214            "AWS_PROFILE",
1215            "AWS_REGION",
1216            "AWS_DEFAULT_REGION",
1217            "AWS_CONFIG_FILE",
1218            "AWS_SHARED_CREDENTIALS_FILE",
1219        ] {
1220            assert!(
1221                is_allowed_mcp_env_key(OsStr::new(key)),
1222                "MCP allowlist should include non-secret AWS selector {key}"
1223            );
1224        }
1225    }
1226
1227    #[test]
1228    fn mcp_env_allowlist_excludes_secrets_and_creds() {
1229        for key in [
1230            "AWS_SECRET_ACCESS_KEY",
1231            "AWS_ACCESS_KEY_ID",
1232            "AWS_SESSION_TOKEN",
1233            "AWS_SECURITY_TOKEN",
1234            "GITHUB_TOKEN",
1235            "OPENAI_API_KEY",
1236            "ANTHROPIC_API_KEY",
1237            "DEEPSEEK_API_KEY",
1238            "SLACK_TOKEN",
1239            "MY_RANDOM_SECRET",
1240        ] {
1241            assert!(
1242                !is_allowed_mcp_env_key(OsStr::new(key)),
1243                "MCP allowlist must NOT include {key}"
1244            );
1245        }
1246    }
1247
1248    #[test]
1249    fn sanitized_mcp_env_passes_through_node_bootstrap() {
1250        let _guard = crate::test_support::lock_test_env();
1251        let _nvm_dir = EnvVarGuard::set("NVM_DIR", "/tmp/test-nvm");
1252
1253        let env = sanitized_mcp_env(std::iter::empty::<(OsString, OsString)>());
1254
1255        let nvm_dir = env
1256            .iter()
1257            .find(|(key, _)| normalize_key(key) == "NVM_DIR")
1258            .map(|(_, value)| value.clone());
1259        assert_eq!(nvm_dir, Some(OsString::from("/tmp/test-nvm")));
1260    }
1261
1262    #[test]
1263    fn sanitized_mcp_env_drops_unrelated_secret_like_values() {
1264        let _guard = crate::test_support::lock_test_env();
1265        let _secret = EnvVarGuard::set("DEEPSEEK_MCP_TEST_SECRET", "should-not-leak");
1266
1267        let env = sanitized_mcp_env(std::iter::empty::<(OsString, OsString)>());
1268
1269        assert!(
1270            env.iter().all(|(key, _)| key != "DEEPSEEK_MCP_TEST_SECRET"),
1271            "MCP env should not pass arbitrary parent vars"
1272        );
1273    }
1274
1275    #[test]
1276    fn reviewed_plugin_mcp_env_requires_explicit_proxy_provenance() {
1277        let _guard = crate::test_support::lock_test_env();
1278        let synthetic_proxy = format!(
1279            "{}://{}:{}@{}",
1280            "http", "fixture-user", "fixture-password", "127.0.0.1:9"
1281        );
1282        let _proxy = EnvVarGuard::set("HTTP_PROXY", synthetic_proxy);
1283
1284        let ambient = sanitized_plugin_mcp_env(std::iter::empty::<(OsString, OsString)>());
1285        let explicit = sanitized_plugin_mcp_env([("HTTP_PROXY", "http://proxy.invalid")]);
1286
1287        assert!(
1288            ambient
1289                .iter()
1290                .all(|(key, _)| normalize_key(key) != "HTTP_PROXY"),
1291            "reviewed plugins must not inherit a credential-capable proxy URL"
1292        );
1293        assert!(explicit.iter().any(|(key, value)| {
1294            normalize_key(key) == "HTTP_PROXY" && value == "http://proxy.invalid"
1295        }));
1296    }
1297
1298    #[test]
1299    fn reviewed_plugin_mcp_env_keeps_desktop_routing_without_secret_namespaces() {
1300        let desktop = [
1301            ("DISPLAY", ":1"),
1302            ("WAYLAND_DISPLAY", "wayland-0"),
1303            ("XDG_RUNTIME_DIR", "/run/user/1000"),
1304            ("XDG_SESSION_TYPE", "wayland"),
1305            ("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"),
1306            ("XAUTHORITY", "/run/user/1000/.Xauthority"),
1307        ];
1308        let unexpected = [
1309            ("OPENAI_API_KEY", "provider-fixture"),
1310            ("XDG_PRIVATE_TOKEN", "xdg-fixture"),
1311            ("DBUS_PRIVATE_TOKEN", "dbus-fixture"),
1312            ("CODEWHALE_CU_APP_BUNDLE", "/stale/helper.app"),
1313        ];
1314        let child = sanitized_plugin_mcp_env_from(
1315            desktop.into_iter().chain(unexpected),
1316            std::iter::empty::<(&str, &str)>(),
1317        );
1318        for (key, value) in desktop {
1319            assert!(
1320                child
1321                    .iter()
1322                    .any(|(found, content)| found == key && content == value)
1323            );
1324        }
1325        for (key, _) in unexpected {
1326            assert!(child.iter().all(|(found, _)| found != key));
1327        }
1328    }
1329
1330    #[test]
1331    fn child_env_allowlist_keeps_build_config_but_not_credentials() {
1332        for key in [
1333            "CARGO_TARGET_DIR",
1334            "CARGO_BUILD_JOBS",
1335            "CARGO_INCREMENTAL",
1336            "RUSTFLAGS",
1337            "RUST_BACKTRACE",
1338            "RUST_LOG",
1339            "VIRTUAL_ENV",
1340            "JAVA_HOME",
1341            "GOPATH",
1342            "NVM_DIR",
1343            "NODE_OPTIONS",
1344            "SSL_CERT_FILE",
1345            "REQUESTS_CA_BUNDLE",
1346        ] {
1347            assert!(
1348                is_allowed_parent_env_key(OsStr::new(key)),
1349                "child env should keep {key}"
1350            );
1351        }
1352        for key in [
1353            "CARGO_REGISTRY_TOKEN",
1354            "CARGO_REGISTRIES_PRIVATE_TOKEN",
1355            "CARGO_REGISTRIES_PRIVATE_CREDENTIAL_PROVIDER",
1356            "CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS",
1357            "CARGO_SOME_SECRET",
1358            "CARGO_SIGNING_KEY",
1359            "DATABASE_URL",
1360            "OPENAI_API_KEY",
1361        ] {
1362            assert!(
1363                !is_allowed_parent_env_key(OsStr::new(key)),
1364                "child env must not keep {key}"
1365            );
1366        }
1367    }
1368
1369    #[test]
1370    fn locale_and_dotnet_allowlists_drop_secret_shaped_names() {
1371        for key in [
1372            "LC_ALL",
1373            "LC_CTYPE",
1374            "LC_MESSAGES",
1375            "LC_TIME",
1376            "LC_COLLATE",
1377            "LC_NUMERIC",
1378            "LC_MONETARY",
1379            "LC_PAPER",
1380            "LC_NAME",
1381            "LC_ADDRESS",
1382            "LC_TELEPHONE",
1383            "LC_MEASUREMENT",
1384            "LC_IDENTIFICATION",
1385            "LC_TERMINAL",
1386            "LC_TERMINAL_VERSION",
1387            "lc_time",
1388            "DOTNET_ROOT",
1389            "DOTNET_ROOT(x86)",
1390            "DOTNET_ROOT_X64",
1391            "DOTNET_HOST_PATH",
1392            "DOTNET_CLI_HOME",
1393            "DOTNET_NOLOGO",
1394            "DOTNET_CLI_TELEMETRY_OPTOUT",
1395            "DOTNET_SKIP_FIRST_TIME_EXPERIENCE",
1396            "DOTNET_MULTILEVEL_LOOKUP",
1397            "DOTNET_ROLL_FORWARD",
1398            "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT",
1399            "DOTNET_CLI_UI_LANGUAGE",
1400            "DOTNET_ENVIRONMENT",
1401            "DOTNET_BUNDLE_EXTRACT_BASE_DIR",
1402            "DOTNET_NUGET_SIGNATURE_VERIFICATION",
1403            "DOTNET_ADD_GLOBAL_TOOLS_TO_PATH",
1404            "DOTNET_WATCH_SUPPRESS_LAUNCH_BROWSER",
1405            "DOTNET_USE_POLLING_FILE_WATCHER",
1406            "DOTNET_RUNNING_IN_CONTAINER",
1407            "DOTNET_TieredPGO",
1408            "DOTNET_TieredCompilation",
1409            "DOTNET_GCHeapHardLimit",
1410            "DOTNET_EnableDiagnostics",
1411            "dotnet_gcServer",
1412            "DOTNET_SDK_VERSION",
1413            "DOTNET_SYSTEM_NET_DISABLEIPV6",
1414            "DOTNET_CLI_WORKLOAD_UPDATE_NOTIFY_DISABLE",
1415            "DOTNET_CLI_TELEMETRY_SESSIONID",
1416            "DOTNET_WATCH_RESTART_ON_RUDE_EDIT",
1417            "DOTNET_STARTUP_HOOKS",
1418            "DOTNET_EventPipeOutputPath",
1419            "DOTNET_DbgMiniDumpName",
1420            "DOTNET_DiagnosticPorts",
1421        ] {
1422            assert!(
1423                is_allowed_parent_env_key(OsStr::new(key)),
1424                "child env should keep {key}"
1425            );
1426            assert!(
1427                is_allowed_mcp_env_key(OsStr::new(key)),
1428                "mcp env should keep {key}"
1429            );
1430        }
1431        for key in [
1432            "LC_X_TOKEN",
1433            "LC_PROBE_SECRET_TOKEN",
1434            "lc_probe_password",
1435            "LC_PROBE_API_KEY",
1436            "LC_PROBE_SIGNING_KEY",
1437            "LC_APIKEY",
1438            "LC_ApiKey",
1439            "LC_OPENAI_APIKEY",
1440            "LC_GH_PAT",
1441            "LC_PAT",
1442            "LC_PASS",
1443            "LC_X_PASS",
1444            "LC_PWD",
1445            "LC_AUTH",
1446            "LC_X_AUTH",
1447            "LC_BEARER",
1448            "LC_JWT",
1449            "LC_DB_URL",
1450            "LC_DSN",
1451            "LC_ACCESSKEY",
1452            "LC_PRIVATEKEY",
1453            "LC_SESSION_COOKIE",
1454            "LC_TIME_EXTRA",
1455            "DOTNET_X_API_KEY",
1456            "DOTNET_PROBE_API_KEY",
1457            "DOTNET_PROBE_ACCESS_KEY",
1458            "DOTNET_CONNECTIONSTRINGS__PROBE_PASSWORD",
1459            "DOTNET_ConnectionStrings__Default",
1460            "DOTNET_ConnectionStrings:Default",
1461            "DOTNET_Data__DefaultConnection__ConnectionString",
1462            "DOTNET_ConnStr",
1463            "DOTNET_ApiKey",
1464            "DOTNET_OpenAI__ApiKey",
1465            "DOTNET_OpenAI:ApiKey",
1466            "DOTNET_Stripe__ApiKey",
1467            "DOTNET_Jwt__SigningKey",
1468            "DOTNET_Jwt__Key",
1469            "DOTNET_Jwt__Keys__0",
1470            "DOTNET_Aws__AccessKey",
1471            "DOTNET_Signing__PrivateKey",
1472            "DOTNET_AzureStorage__AccountKey",
1473            "DOTNET_ApplicationInsights__InstrumentationKey",
1474            "DOTNET_Auth__ClientSecret",
1475            "DOTNET_Auth__Bearer",
1476            "DOTNET_Smtp__Pass",
1477            "DOTNET_Db__Pwd",
1478            "DOTNET_Database__ConnStr",
1479            "DOTNET_Database__Url",
1480            "DOTNET_Sentry__Dsn",
1481            "DOTNET_Redis__Configuration",
1482            "DOTNET_Azure__SasToken",
1483            "dotnet_probe_credential",
1484            "DOTNET_",
1485            "DOTNET__",
1486            "DOTNET_GH_PAT",
1487            "DOTNET_PAT",
1488            "DOTNET_NUGET_PAT",
1489            "DOTNET_AzureDevOpsPat",
1490            "DOTNET_JWT",
1491            "DOTNET_DATABASE_URL",
1492            "DOTNET_DB_URL",
1493            "DOTNET_DatabaseUrl",
1494            "DOTNET_DefaultConnection",
1495            "DOTNET_RedisConfiguration",
1496            "DOTNET_SentryUrl",
1497            "DOTNET_SlackWebhookUrl",
1498            "DOTNET_SasUrl",
1499            "DOTNET_Hmac",
1500            "DOTNET_Salt",
1501            "DOTNET_Signature",
1502            "DOTNET_Pfx",
1503            "DOTNET_Otp",
1504            "DOTNET_Creds",
1505            "DOTNET_Cred",
1506            "DOTNET_Pw",
1507            "DOTNET_Pin",
1508            "DOTNET_Mnemonic",
1509            "DOTNET_Seed",
1510            "DOTNET_SessionId",
1511            "DOTNET_Login",
1512            "DOTNET_License",
1513            "DOTNET_Api\u{212A}ey",
1514            "DOTNET_Api\u{FF2B}ey",
1515            "DOTNET_TieredPGO_X",
1516            "DOTNET_ROOT__X",
1517        ] {
1518            assert!(
1519                !is_allowed_parent_env_key(OsStr::new(key)),
1520                "child env must not keep {key}"
1521            );
1522            assert!(
1523                !is_allowed_mcp_env_key(OsStr::new(key)),
1524                "mcp env must not keep {key}"
1525            );
1526        }
1527    }
1528
1529    #[test]
1530    fn sanitized_envs_drop_secret_shaped_locale_and_dotnet_names() {
1531        let _guard = crate::test_support::lock_test_env();
1532        let secrets = [
1533            "LC_PROBE_SECRET_TOKEN",
1534            "LC_APIKEY",
1535            "LC_GH_PAT",
1536            "LC_PASS",
1537            "DOTNET_PROBE_API_KEY",
1538            "DOTNET_OpenAI__ApiKey",
1539            "DOTNET_Jwt__SigningKey",
1540            "DOTNET_Smtp__Pass",
1541            "DOTNET_Db__Pwd",
1542            "DOTNET_GH_PAT",
1543            "DOTNET_DATABASE_URL",
1544            "DOTNET_DefaultConnection",
1545            "DOTNET_SlackWebhookUrl",
1546        ];
1547        let _secret_guards: Vec<_> = secrets
1548            .iter()
1549            .map(|name| EnvVarGuard::set(name, "probe-fixture-value"))
1550            .collect();
1551        let _dotnet_root = EnvVarGuard::set("DOTNET_ROOT", "/opt/dotnet");
1552        let _lc_time = EnvVarGuard::set("LC_TIME", "C");
1553
1554        let parent: Vec<(OsString, OsString)> = std::env::vars_os().collect();
1555        for env in [
1556            sanitized_child_env(std::iter::empty::<(OsString, OsString)>()),
1557            sanitized_mcp_env(std::iter::empty::<(OsString, OsString)>()),
1558            sanitized_runtime_env_from(parent.clone()),
1559            sanitized_plugin_mcp_env_from(
1560                parent.clone(),
1561                std::iter::empty::<(OsString, OsString)>(),
1562            ),
1563        ] {
1564            let has = |name: &str| env.iter().any(|(key, _)| normalize_key(key) == name);
1565            for name in secrets {
1566                assert!(!has(name), "{name} reached the child env");
1567            }
1568            assert!(
1569                env.iter()
1570                    .all(|(_, value)| !value.to_string_lossy().contains("probe-fixture"))
1571            );
1572            assert!(has("DOTNET_ROOT"));
1573            assert!(has("LC_TIME"));
1574        }
1575    }
1576
1577    #[test]
1578    fn proxy_userinfo_is_removed_before_reaching_a_child() {
1579        for (input, expected) in [
1580            ("http://user:secret@proxy:3128", "http://proxy:3128"),
1581            (
1582                "http://user:secret@proxy:3128/path?x=1",
1583                "http://proxy:3128/path?x=1",
1584            ),
1585            ("socks5h://u:p@w@10.0.0.1:1080", "socks5h://10.0.0.1:1080"),
1586            ("user:secret@proxy:3128", "proxy:3128"),
1587            ("http://proxy:3128", "http://proxy:3128"),
1588            ("http://proxy:3128/a@b", "http://proxy:3128/a@b"),
1589        ] {
1590            assert_eq!(
1591                strip_proxy_userinfo(OsStr::new(input)),
1592                Some(OsString::from(expected)),
1593                "{input}"
1594            );
1595        }
1596    }
1597
1598    #[test]
1599    fn sanitized_child_env_strips_proxy_credentials() {
1600        let _guard = crate::test_support::lock_test_env();
1601        let _https = EnvVarGuard::set(
1602            "HTTPS_PROXY",
1603            "http://fixture-user:fixture-pass@proxy.invalid:3128",
1604        );
1605        let _cargo = EnvVarGuard::set(
1606            "CARGO_HTTP_PROXY",
1607            "http://fixture-user:fixture-pass@proxy.invalid:3128",
1608        );
1609        let _no_proxy = EnvVarGuard::set("NO_PROXY", "localhost");
1610
1611        let env = sanitized_child_env(std::iter::empty::<(OsString, OsString)>());
1612        let get = |name: &str| {
1613            env.iter()
1614                .find(|(key, _)| normalize_key(key) == name)
1615                .map(|(_, value)| value.clone())
1616        };
1617        assert_eq!(
1618            get("HTTPS_PROXY"),
1619            Some(OsString::from("http://proxy.invalid:3128"))
1620        );
1621        assert_eq!(
1622            get("CARGO_HTTP_PROXY"),
1623            Some(OsString::from("http://proxy.invalid:3128"))
1624        );
1625        assert_eq!(get("NO_PROXY"), Some(OsString::from("localhost")));
1626        assert!(
1627            env.iter()
1628                .all(|(_, value)| !value.to_string_lossy().contains("fixture-pass"))
1629        );
1630        // Explicit call-site overrides are trusted and kept as given.
1631        let explicit = sanitized_child_env([("HTTPS_PROXY", "http://a:b@proxy.invalid:1")]);
1632        assert!(explicit.iter().any(|(key, value)| {
1633            normalize_key(key) == "HTTPS_PROXY" && value == "http://a:b@proxy.invalid:1"
1634        }));
1635    }
1636
1637    #[test]
1638    fn sanitized_child_env_drops_parent_secret_like_values() {
1639        let _guard = crate::test_support::lock_test_env();
1640        let _secret = EnvVarGuard::set("DEEPSEEK_CHILD_ENV_TEST_SECRET", "parent-secret");
1641
1642        let env = sanitized_child_env(std::iter::empty::<(OsString, OsString)>());
1643
1644        assert!(
1645            env.iter()
1646                .all(|(key, _)| key != "DEEPSEEK_CHILD_ENV_TEST_SECRET")
1647        );
1648    }
1649
1650    #[test]
1651    fn sanitized_child_env_drops_rustc_wrapper_under_os_sandbox() {
1652        let _guard = crate::test_support::lock_test_env();
1653        let _wrapper = EnvVarGuard::set("RUSTC_WRAPPER", "sccache");
1654
1655        let unsandboxed = sanitized_child_env(std::iter::empty::<(OsString, OsString)>());
1656        assert!(
1657            unsandboxed
1658                .iter()
1659                .any(|(key, value)| normalize_key(key) == "RUSTC_WRAPPER" && value == "sccache"),
1660            "unsandboxed children keep RUSTC_WRAPPER"
1661        );
1662
1663        let sandboxed = sanitized_child_env([(
1664            OsString::from("CODEWHALE_SANDBOX"),
1665            OsString::from("seatbelt"),
1666        )]);
1667        assert!(
1668            sandboxed.iter().any(
1669                |(key, value)| normalize_key(key) == "CODEWHALE_SANDBOX" && value == "seatbelt"
1670            ),
1671            "sandbox marker must survive"
1672        );
1673        assert!(
1674            sandboxed
1675                .iter()
1676                .all(|(key, _)| normalize_key(key) != "RUSTC_WRAPPER"),
1677            "OS sandbox children must not keep RUSTC_WRAPPER"
1678        );
1679    }
1680
1681    #[test]
1682    fn explicit_child_env_values_win_over_parent_allowlist() {
1683        // The real parent PATH is enough to prove the override wins; setting
1684        // PATH here would break every concurrent test that spawns a program.
1685        assert_ne!(
1686            std::env::var_os("PATH"),
1687            Some(OsString::from("/explicit/bin"))
1688        );
1689
1690        let env = sanitized_child_env([(OsString::from("PATH"), OsString::from("/explicit/bin"))]);
1691
1692        let path = env
1693            .iter()
1694            .find(|(key, _)| normalize_key(key) == "PATH")
1695            .map(|(_, value)| value);
1696        assert_eq!(path, Some(&OsString::from("/explicit/bin")));
1697    }
1698
1699    #[test]
1700    fn sanitized_child_env_preserves_windows_toolchain_vars() {
1701        let _guard = crate::test_support::lock_test_env();
1702        let _lib = EnvVarGuard::set("LIB", r"C:\sdk\lib");
1703        let _include = EnvVarGuard::set("INCLUDE", r"C:\sdk\include");
1704        let _sdk = EnvVarGuard::set("WINDOWSSDKDIR", r"C:\sdk");
1705
1706        let env = sanitized_child_env(std::iter::empty::<(OsString, OsString)>());
1707
1708        assert!(
1709            env.iter()
1710                .any(|(key, value)| key == "LIB" && value == r"C:\sdk\lib"),
1711            "child env should preserve LIB"
1712        );
1713        assert!(
1714            env.iter()
1715                .any(|(key, value)| key == "INCLUDE" && value == r"C:\sdk\include"),
1716            "child env should preserve INCLUDE"
1717        );
1718        assert!(
1719            env.iter()
1720                .any(|(key, value)| key == "WINDOWSSDKDIR" && value == r"C:\sdk"),
1721            "child env should preserve WINDOWSSDKDIR"
1722        );
1723    }
1724}