bash-subprocess-env.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /**
  2. * Bash subprocess environment sanitizer — two independent layers applied
  3. * before every bash tool child spawn (foreground LocalBashTool, background
  4. * bash executor, and the pi-turn-runner builtin fallback).
  5. *
  6. * Layer A — MCode runtime boundary strip. ALWAYS on, no escape hatch.
  7. * Reuses the env-builder boundary key lists verbatim (import, never fork):
  8. * runtime/parent identity, session ids, profile/dataDir/port keys, safety
  9. * switches, and ASR proxy auth. Leaking these is not a "secret exfil"
  10. * problem but a boundary-correctness one: a child could impersonate the
  11. * parent session against the runtime API, or a nested `mavis` CLI inside
  12. * bash would silently bind to the parent runtime's profile.
  13. *
  14. * Layer B — provider and integration secret scrub. GATED, mirroring the
  15. * reference CLI's `subprocessEnv()` design (src/utils/subprocessEnv.ts):
  16. * - `off` (interactive default): do not strip user secrets. CC parity —
  17. * interactive users rely on env credentials (gh, npm, ...).
  18. * - `scrub` (auto in CI / non-interactive): precise blocklist of
  19. * credentials the *parent* process needs but subprocesses never
  20. * do. GH_TOKEN / GITHUB_TOKEN / NPM_TOKEN are intentionally NOT
  21. * on the list (CC parity: subprocesses have legitimate uses).
  22. * - `strict` (opt-in): pattern-based strip of credential-looking names,
  23. * with a protected-system-vars floor and an allowlist hatch.
  24. *
  25. * @module
  26. */
  27. import { isAbsolute } from 'node:path';
  28. import { stripRuntimeBoundaryKeysFrom } from '@mavis/shared/runtime-boundary-env';
  29. export type BashEnvSanitizeMode = 'off' | 'scrub' | 'strict';
  30. export interface BashEnvPolicy {
  31. mode: BashEnvSanitizeMode;
  32. /** Names exempt from the `strict` pattern strip. Never applies to Layer A. */
  33. allowlist?: readonly string[];
  34. /**
  35. * Absolute directories prepended to `PATH` for every bash subprocess.
  36. *
  37. * Used by the desktop runtime to install command shims (currently the
  38. * recoverable-delete `rm` shim) so the EXECUTION layer decides how a verb is
  39. * carried out, without any caller having to parse or rewrite command text.
  40. * agent-core stays agnostic about what the directories contain.
  41. */
  42. prependPath?: readonly string[];
  43. /**
  44. * Host-injected gate that runs before every bash subprocess launch; throwing
  45. * blocks the spawn. The desktop runtime uses it to verify — and re-seed when
  46. * possible — the recoverable-delete `rm` shim, so a lost shim fails the
  47. * spawn loudly instead of silently resolving `/bin/rm` (fail-closed). It is
  48. * a callback rather than data because agent-core must stay free of
  49. * filesystem imports (host boundary): only the host knows what the shim
  50. * directories are supposed to contain and how to repair them.
  51. */
  52. spawnPreflight?: () => void;
  53. }
  54. export interface BashEnvSanitizeResult {
  55. /** New env object; the input is never mutated. */
  56. env: NodeJS.ProcessEnv;
  57. /** Names (never values) of removed vars, sorted, for tool-result hints. */
  58. removed: string[];
  59. }
  60. /**
  61. * Precise `scrub` blocklist. Selection rule (reference CLI GHA_SUBPROCESS_SCRUB
  62. * parity): the parent process needs these for API calls / lazy SDK reads, but
  63. * bash subprocesses never legitimately do. Each entry also strips its
  64. * `INPUT_<NAME>` alias (GitHub Actions duplicates `with:` inputs that way).
  65. *
  66. * Deliberately NOT listed (CC parity — legitimate subprocess uses):
  67. * GH_TOKEN, GITHUB_TOKEN (gh CLI), NPM_TOKEN (private registry installs).
  68. */
  69. export const BASH_SUBPROCESS_SCRUB: readonly string[] = [
  70. // Provider / LLM auth — the runtime re-reads these per-request itself
  71. 'MCODE_PROVIDER_API_KEY',
  72. 'ANTHROPIC_API_KEY',
  73. 'ANTHROPIC_AUTH_TOKEN',
  74. 'CLAUDE_CODE_OAUTH_TOKEN',
  75. 'ANTHROPIC_FOUNDRY_API_KEY',
  76. 'ANTHROPIC_CUSTOM_HEADERS',
  77. 'OPENAI_API_KEY',
  78. // OTLP exporter headers — documented to carry Authorization bearer tokens
  79. 'OTEL_EXPORTER_OTLP_HEADERS',
  80. 'OTEL_EXPORTER_OTLP_LOGS_HEADERS',
  81. 'OTEL_EXPORTER_OTLP_METRICS_HEADERS',
  82. 'OTEL_EXPORTER_OTLP_TRACES_HEADERS',
  83. // Cloud provider creds — lazy SDK reads in the parent only
  84. 'AWS_SECRET_ACCESS_KEY',
  85. 'AWS_SESSION_TOKEN',
  86. 'AWS_BEARER_TOKEN_BEDROCK',
  87. 'GOOGLE_APPLICATION_CREDENTIALS',
  88. 'AZURE_CLIENT_SECRET',
  89. 'AZURE_CLIENT_CERTIFICATE_PATH',
  90. // GitHub Actions OIDC + artifact/cache API — repo-takeover / supply-chain pivots
  91. 'ACTIONS_ID_TOKEN_REQUEST_TOKEN',
  92. 'ACTIONS_ID_TOKEN_REQUEST_URL',
  93. 'ACTIONS_RUNTIME_TOKEN',
  94. 'ACTIONS_RUNTIME_URL',
  95. // MCode-side additions — runtime-only integration tokens, no subprocess use
  96. 'FIGMA_API_TOKEN',
  97. 'FIGMA_TOKEN',
  98. 'E2E_AUTH_TOKEN',
  99. ];
  100. /**
  101. * Credential keyword core (regex source fragment, no anchors/flags) shared by
  102. * {@link SENSITIVE_ENV_NAME_RE} here and the permission layer's secret-read
  103. * command patterns (`echo $X`, `printenv X`). Single source so the two stay
  104. * aligned — a sync-guard test asserts the permission side imports this.
  105. */
  106. export const SENSITIVE_ENV_KEYWORD_CORE =
  107. 'API_?KEY|KEY|SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIALS?|PRIVATE_?KEY';
  108. /**
  109. * Credential-looking env var names for the `strict` mode and for the
  110. * permission layer's secret-read command rules (`echo $X`, `printenv X`).
  111. * Segment-bounded on `_`/start/end so MONKEY / TOKENIZER / KEYBOARD survive.
  112. */
  113. export const SENSITIVE_ENV_NAME_RE = new RegExp(
  114. `(?:^|_)(?:${SENSITIVE_ENV_KEYWORD_CORE})S?(?:_|$)`,
  115. 'i',
  116. );
  117. /** System vars the `strict` pattern must never strip (POSIX + Windows). */
  118. const PROTECTED_ENV_NAMES: ReadonlySet<string> = new Set([
  119. 'PATH',
  120. 'HOME',
  121. 'SHELL',
  122. 'LANG',
  123. 'LOGNAME',
  124. 'USER',
  125. 'TERM',
  126. 'TMPDIR',
  127. // Windows
  128. 'SYSTEMROOT',
  129. 'COMSPEC',
  130. 'TEMP',
  131. 'TMP',
  132. 'USERPROFILE',
  133. 'APPDATA',
  134. 'LOCALAPPDATA',
  135. ]);
  136. function isProtectedName(name: string): boolean {
  137. const upper = name.toUpperCase();
  138. return PROTECTED_ENV_NAMES.has(upper) || upper.startsWith('LC_');
  139. }
  140. function isEnvTruthy(value: string | undefined): boolean {
  141. if (!value) return false;
  142. return !['0', 'false', 'no', 'off'].includes(value.toLowerCase());
  143. }
  144. const VALID_MODES: ReadonlySet<string> = new Set(['off', 'scrub', 'strict']);
  145. /**
  146. * Resolve the effective Layer B policy. Precedence: explicit override >
  147. * `MAVIS_BASH_ENV_SANITIZE` env switch > auto (CI markers → `scrub`,
  148. * otherwise `off` — interactive default, reference CLI parity).
  149. */
  150. export function resolveBashEnvPolicy(
  151. overrides?: Partial<BashEnvPolicy>,
  152. envSource: NodeJS.ProcessEnv = process.env,
  153. ): BashEnvPolicy {
  154. let mode: BashEnvSanitizeMode | undefined = overrides?.mode;
  155. if (mode === undefined) {
  156. const explicit = envSource.MAVIS_BASH_ENV_SANITIZE?.trim().toLowerCase();
  157. if (explicit && VALID_MODES.has(explicit)) {
  158. mode = explicit as BashEnvSanitizeMode;
  159. } else if (isEnvTruthy(envSource.CI) || isEnvTruthy(envSource.GITHUB_ACTIONS)) {
  160. mode = 'scrub';
  161. } else {
  162. mode = 'off';
  163. }
  164. }
  165. return {
  166. mode,
  167. ...(overrides?.allowlist ? { allowlist: overrides.allowlist } : {}),
  168. ...(overrides?.prependPath ? { prependPath: overrides.prependPath } : {}),
  169. ...(overrides?.spawnPreflight ? { spawnPreflight: overrides.spawnPreflight } : {}),
  170. };
  171. }
  172. export function sanitizeBashSubprocessEnv(
  173. env: NodeJS.ProcessEnv,
  174. policy: BashEnvPolicy,
  175. ): BashEnvSanitizeResult {
  176. policy.spawnPreflight?.();
  177. const out: NodeJS.ProcessEnv = { ...env };
  178. const removed: string[] = [];
  179. // Layer A — MCode boundary strip. Always on; allowlist deliberately ignored.
  180. removed.push(...stripRuntimeBoundaryKeysFrom(out, 'agent-runtime'));
  181. // Layer B — provider and integration secret scrub, gated by mode.
  182. if (policy.mode === 'scrub') {
  183. for (const key of BASH_SUBPROCESS_SCRUB) {
  184. for (const name of [key, `INPUT_${key}`]) {
  185. if (out[name] !== undefined) removed.push(name);
  186. delete out[name];
  187. }
  188. }
  189. } else if (policy.mode === 'strict') {
  190. const allow = new Set((policy.allowlist ?? []).map((name) => name.toUpperCase()));
  191. for (const name of Object.keys(out)) {
  192. if (isProtectedName(name)) continue;
  193. if (allow.has(name.toUpperCase())) continue;
  194. if (!SENSITIVE_ENV_NAME_RE.test(name)) continue;
  195. if (out[name] !== undefined) removed.push(name);
  196. delete out[name];
  197. }
  198. }
  199. removed.sort();
  200. applyPathPrefix(out, policy.prependPath);
  201. return { env: out, removed };
  202. }
  203. /**
  204. * Prepend runtime-managed shim directories to PATH, de-duplicating so repeated
  205. * spawns cannot grow the variable without bound. Relative entries are ignored:
  206. * a relative shim directory would resolve against the command's cwd and could
  207. * be shadowed by repository content.
  208. */
  209. function applyPathPrefix(env: NodeJS.ProcessEnv, prependPath?: readonly string[]): void {
  210. if (!prependPath?.length) return;
  211. const separator = process.platform === 'win32' ? ';' : ':';
  212. const existing = env.PATH ?? env.Path ?? '';
  213. const current = existing.split(separator).filter((entry) => entry !== '');
  214. const additions = prependPath.filter(
  215. (dir) => isAbsolute(dir) && !current.includes(dir),
  216. );
  217. if (additions.length === 0) return;
  218. const nextPath = [...additions, ...current].join(separator);
  219. // Windows env lookups are case-insensitive but the object keys are not:
  220. // overwrite whichever casing the inherited environment actually used.
  221. if (env.PATH === undefined && env.Path !== undefined) env.Path = nextPath;
  222. else env.PATH = nextPath;
  223. }
  224. /**
  225. * Minimal structural type of pi's `BashSpawnContext` — kept structural so
  226. * this module needs no dependency on the vendored pi packages.
  227. */
  228. export interface BashSpawnContextLike {
  229. command: string;
  230. cwd: string;
  231. env: NodeJS.ProcessEnv;
  232. }
  233. /**
  234. * Factory for a pi `createBashTool` spawnHook applying this sanitizer.
  235. * Used by the non-interactive bash spawn sites (background executor and
  236. * pi-turn-runner builtin fallback). The interactive LocalBashTool uses an
  237. * equivalent inline hook instead so it can also capture the removed variable
  238. * names for a one-time UX hint (`details.envSanitized`); the sanitizer applied
  239. * is identical — only the removed-name capture differs.
  240. */
  241. export function createBashEnvSpawnHook(
  242. policy: BashEnvPolicy,
  243. onSanitized?: (removed: string[]) => void,
  244. ): <T extends BashSpawnContextLike>(ctx: T) => T {
  245. return (ctx) => {
  246. const { env, removed } = sanitizeBashSubprocessEnv(ctx.env, policy);
  247. onSanitized?.(removed);
  248. return { ...ctx, env };
  249. };
  250. }