diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ae3d41..a8adee6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ All notable changes to cloudpin are listed here. The format follows ### Fixed +- Variables an agent sets earlier in its command line now count (#86). `export AWS_PROFILE=other; aws ...` and + PowerShell `$env:AWS_PROFILE = 'other'; aws ...` were checked against the default account and ran on another; and + `GH_TOKEN=$(cat other.token) gh ...` read the token as empty. cloudpin now follows `export`, `unset` and `$env:` + through the line, and stops a command whose account depends on a value only known when it runs, saying why. Found + in the threat-model review. + - Cursor: a command on your Cursor allowlist runs again when the account matches (#2). cloudpin answered `ask`, which stopped even allowlisted commands; it now answers `allow`, which Cursor treats exactly like having no hook (measured in Cursor CLI 2026.10.01: commands not on the allowlist still need your approval). Wrong accounts are still blocked. diff --git a/README.md b/README.md index c48175e..5a2e374 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,10 @@ serves paid API keys and enterprise licenses, so both are supported. cloudpin reads the whole command line the agent is about to run, so it also catches `cd ../other && npx vercel deploy`, `bash -c "..."`, pipelines, `$( )`, `xargs`, `find -exec`, heredocs fed to a shell (`bash < (n.endsWith("*") ? key.startsWith(n.slice(0, -1)) : key === n)); +} + function relevantEnv(names: string[], env: NodeJS.ProcessEnv): [string, string][] { return Object.entries(env) - .filter(([key, value]) => - value !== undefined && names.some((n) => (n.endsWith("*") ? key.startsWith(n.slice(0, -1)) : key === n)), - ) + .filter(([key, value]) => value !== undefined && envNameMatches(names, key)) .map(([key, value]) => [key, value as string] as [string, string]) .sort(([a], [b]) => a.localeCompare(b)); } diff --git a/src/explain.ts b/src/explain.ts index f13e34b..3fd8ce2 100644 --- a/src/explain.ts +++ b/src/explain.ts @@ -1,8 +1,8 @@ import type { ActiveEnvironment } from "./config.js"; import { commandName, guard, type GuardDeps, type Trace, type Verdict } from "./guard.js"; -import { AGENTS, type AgentName, withoutUserOnlyVars } from "./hooks/agents.js"; +import { AGENTS, type AgentName } from "./hooks/agents.js"; import { home } from "./paths.js"; -import { findInvocations, type Invocation } from "./shellwords.js"; +import { envFor, findInvocations, type Invocation } from "./shellwords.js"; import { describe } from "./status.js"; import type { Identity } from "./types.js"; @@ -109,10 +109,9 @@ export async function explain(command: string | string[], opts: ExplainOptions, if (wrapped.length === 0) continue; call = { ...call, bin: wrapped[0]!, args: wrapped.slice(1) }; } - const own = opts.mode === "agent" ? withoutUserOnlyVars(call.env) : call.env; const cwd = call.cwd ?? opts.cwd; const trace: Trace = {}; - const verdict = await guard({ bin: call.bin, args: call.args, env: { ...opts.env, ...own }, cwd, mode: opts.mode }, deps, trace); + const verdict = await guard({ bin: call.bin, args: call.args, env: envFor(opts.env, call, { agent: opts.mode === "agent" }), cwd, mode: opts.mode }, deps, trace); const res = trace.resolution; out.push({ argv: [call.bin, ...call.args], diff --git a/src/guard.ts b/src/guard.ts index e687f6b..de87d9a 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -1,7 +1,8 @@ import { basename } from "node:path"; import { type ActiveEnvironment, ConfigError, findConfig, type FoundConfig, type Provider } from "./config.js"; +import { envNameMatches } from "./cache.js"; import { isReadOnly } from "./readonly.js"; -import type { Exec, ProviderDef, Resolution } from "./types.js"; +import { type Exec, type ProviderDef, type Resolution, UNKNOWN_VALUE } from "./types.js"; export interface GuardRequest { /** The executable as typed or resolved, e.g. "az" or "C:\\...\\gh.exe". */ @@ -126,7 +127,23 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { if (result.notFound) cliMissing = true; return result; }; - const res = await provider.resolve({ args: req.args, env: req.env, cwd: req.cwd, bin: name }, exec); + // A variable the line sets from something only known when it runs (#86): if it + // decides this CLI's account, cloudpin can't tell which account will be used. + const identityVars = provider.cacheInputs(req.env).env; + const unknown = Object.keys(req.env).filter((k) => req.env[k] === UNKNOWN_VALUE && envNameMatches(identityVars, k)); + if (unknown.length > 0) { + return { + ...base, + uncertain: true, + problems: [ + `${unknown.join(", ")} ${unknown.length > 1 ? "are" : "is"} set by the command line from something cloudpin can't read in advance ($(...), backticks or another variable), so it can't tell which account this command would use`, + ], + fix: `set ${unknown[0]} to a literal value, or run the command yourself`, + }; + } + // Other unknown values don't decide the account; the CLI's identity check runs without them. + const env = Object.fromEntries(Object.entries(req.env).filter(([, v]) => v !== UNKNOWN_VALUE)); + const res = await provider.resolve({ args: req.args, env, cwd: req.cwd, bin: name }, exec); trace.resolution = res; if (res.kind === "error" && cliMissing) return { action: "allow", reason: "not-installed" }; switch (res.kind) { diff --git a/src/hooks/agents.ts b/src/hooks/agents.ts index 6decae2..a04da66 100644 --- a/src/hooks/agents.ts +++ b/src/hooks/agents.ts @@ -1,7 +1,7 @@ import { resolve } from "node:path"; import { formatBlock, formatConfirm } from "../format.js"; import { commandName, guard, type GuardDeps } from "../guard.js"; -import { findInvocations } from "../shellwords.js"; +import { envFor, findInvocations } from "../shellwords.js"; /** How one agent hands a shell command to its hook and reads the answer. */ export interface AgentHook { @@ -144,15 +144,6 @@ export const AGENTS = { }, } satisfies Record; -// Set by the user before starting the agent, these count; set by the agent -// inside its own command, they would let it pick a laxer environment, confirm -// for the user or skip the check, so they are dropped. -const USER_ONLY_VARS = ["CLOUDPIN_ENV", "CLOUDPIN_CONFIRM", "CLOUDPIN_SKIP"]; - -export function withoutUserOnlyVars(vars: Record): Record { - return Object.fromEntries(Object.entries(vars).filter(([k]) => !USER_ONLY_VARS.includes(k))); -} - /** A request for the user's OK: the text an agent asks with, or the one it is denied with. */ interface Confirmation { ask: string; @@ -247,7 +238,7 @@ async function checkCommand( { bin: inv.bin, args: inv.args, - env: { ...env, ...withoutUserOnlyVars(inv.env) }, + env: envFor(env, inv, { agent: true }), cwd: inv.cwd ?? call.cwd, mode: "agent", }, diff --git a/src/shellwords.ts b/src/shellwords.ts index c56cda1..0b79b41 100644 --- a/src/shellwords.ts +++ b/src/shellwords.ts @@ -1,20 +1,54 @@ import { homedir } from "node:os"; import { resolve } from "node:path"; import { commandName } from "./guard.js"; +import { UNKNOWN_VALUE } from "./types.js"; export interface Invocation { /** Executable as written, e.g. "gh" or "/usr/bin/gh". */ bin: string; args: string[]; - /** VAR=value assignments written before the command. */ + /** + * Variables the CLI receives from the line: exported earlier in it (`export X=1;`, + * PowerShell `$env:X = 1`) or assigned before the command (`X=1 cli`) (#86). + */ env: Record; + /** Plain `X=1;` assignments earlier in the line: they reach the CLI only if X is already exported. */ + ifExported?: Record; + /** Names `unset` earlier in the line. */ + unset?: string[]; /** Folder the call runs in, when a `cd` earlier in the line changed it. */ cwd?: string; } +export { UNKNOWN_VALUE }; + +/** + * Variables only the user may set. Set before starting the agent, they count; set by the agent inside its own command, + * they would let it pick a laxer environment, confirm for the user or skip the check, so they are ignored there. + */ +export const USER_ONLY_VARS = ["CLOUDPIN_ENV", "CLOUDPIN_CONFIRM", "CLOUDPIN_SKIP"]; + +/** + * The environment a call runs with: `base` (the environment the line starts + * in), then the line's plain assignments to names already exported, its + * `unset`s, and its exported and prefix variables. With `agent`, the line can't + * set or unset the user-only variables. + */ +export function envFor(base: NodeJS.ProcessEnv, inv: Invocation, opts: { agent?: boolean } = {}): NodeJS.ProcessEnv { + const allowed = (name: string) => !(opts.agent && USER_ONLY_VARS.includes(name)); + const out: NodeJS.ProcessEnv = { ...base }; + for (const [name, value] of Object.entries(inv.ifExported ?? {})) if (name in base && allowed(name)) out[name] = value; + for (const name of inv.unset ?? []) if (allowed(name)) delete out[name]; + for (const [name, value] of Object.entries(inv.env)) if (allowed(name)) out[name] = value; + return out; +} + type Token = - /** `quoted`: some of it was in quotes, so `"vercel"` is a string, not a command. */ - | { kind: "word"; value: string; quoted: boolean } + /** + * `quoted`: some of it was in quotes, so `"vercel"` is a string, not a command. + * `dynamic`: it contains `$(...)`, backticks or a `$NAME` expansion, so its value is only known when it runs. + */ + | { kind: "word"; value: string; quoted: boolean; dynamic: boolean } /** A control operator: ; & | newline, or ( and ) which open and close a subshell. */ | { kind: "op"; op: string } /** $( ... ) or backticks: a command line run in a subshell. */ @@ -31,17 +65,21 @@ function tokenize(input: string): Token[] { let word = ""; let inWord = false; let quoted = false; + let dynamic = false; // The next word is a here-string (`<<< word`), not an argument. let hereString = false; // Heredocs whose bodies start after the next newline. const pending: { token: { kind: "stdin"; body: string }; delimiter: string; stripTabs: boolean }[] = []; const flush = () => { - if (inWord) tokens.push(hereString ? { kind: "stdin", body: word } : { kind: "word", value: word, quoted }); + if (inWord) tokens.push(hereString ? { kind: "stdin", body: word } : { kind: "word", value: word, quoted, dynamic }); if (inWord) hereString = false; word = ""; inWord = false; quoted = false; + dynamic = false; }; + // `$NAME` or `${NAME}` (not `$` alone or `$1`): an expansion outside single quotes. + const expands = (at: number) => /[A-Za-z_{]/.test(input[at + 1] ?? ""); // Reads $( ... ) starting after "$(", honouring nesting and quotes. const readParen = (start: number): number => { @@ -125,9 +163,14 @@ function tokenize(input: string): Token[] { if (d === "\\" && i + 1 < input.length && '"\\$`\n'.includes(input[i + 1]!)) { word += input[i + 1]; i += 2; - } else if (d === "$" && input[i + 1] === "(") i = readParen(i + 2); - else if (d === "`") i = readBacktick(i + 1); - else { + } else if (d === "$" && input[i + 1] === "(") { + dynamic = true; + i = readParen(i + 2); + } else if (d === "`") { + dynamic = true; + i = readBacktick(i + 1); + } else { + if (d === "$" && expands(i)) dynamic = true; word += d; i++; } @@ -141,9 +184,11 @@ function tokenize(input: string): Token[] { i += 2; } else if (c === "$" && input[i + 1] === "(") { inWord = true; + dynamic = true; i = readParen(i + 2); } else if (c === "`") { inWord = true; + dynamic = true; i = readBacktick(i + 1); } else if (c === "#" && !inWord) { // A comment runs to the end of the line. @@ -172,6 +217,7 @@ function tokenize(input: string): Token[] { i++; if (c === "\n" && pending.length > 0) i = readBodies(i); } else { + if (c === "$" && expands(i)) dynamic = true; word += c; inWord = true; i++; @@ -213,30 +259,78 @@ interface State { base?: string; /** Variables set by plain `NAME=value` commands earlier in the line. */ vars: Record; + /** Of those, the ones the shell passes to the commands it runs: `export`ed, or PowerShell `$env:` (#86). */ + exported: Record; + /** Plain `NAME=value` assignments not exported here: they reach a command only if NAME was already exported. */ + plain: Record; + /** Names `unset` and not set again since. */ + unset: Set; /** The whole command line, to spot CLI names behind an unknown `$VAR` command. */ line: string; guarded: Set; } /** A copy for code that runs in a child shell, whose `cd` and variables do not come back. */ -const child = (state: State): State => ({ ...state, vars: { ...state.vars } }); +const child = (state: State): State => ({ + ...state, + vars: { ...state.vars }, + exported: { ...state.exported }, + plain: { ...state.plain }, + unset: new Set(state.unset), +}); // PowerShell assignment: `$name = ` or `$name=`. const PS_ASSIGNMENT = /^\$([A-Za-z_][A-Za-z0-9_]*)(?:=(.*))?$/s; +// PowerShell environment variable: `$env:NAME = ` or `$env:NAME=` (#86). +const PS_ENV = /^\$env:([A-Za-z_][A-Za-z0-9_]*)(?:=(.*))?$/is; +// Builtins that export: `export`, and `declare`/`typeset` with -x. +const EXPORTERS = new Set(["export", "declare", "typeset"]); -function analyse(words: string[], stdin: string[], out: Invocation[], state: State, quoted: boolean[] = []): void { +/** Sets NAME for the rest of the line, exported or not. */ +function assign(state: State, name: string, value: string, exported: boolean): void { + state.vars[name] = value; + state.unset.delete(name); + // Assigning to an exported variable updates what commands receive. + if (exported || name in state.exported) { + state.exported[name] = value; + delete state.plain[name]; + } else state.plain[name] = value; +} + +function analyse( + words: string[], + stdin: string[], + out: Invocation[], + state: State, + quoted: boolean[] = [], + dynamic: boolean[] = [], +): void { + const psEnv = PS_ENV.exec(words[0] ?? ""); + if (psEnv && (psEnv[2] !== undefined || words[1] === "=")) { + // A single literal (`'other'`, `other`) is known; anything else (an expression, + // a command, `(Get-Content f)`, `$x`) is only known when it runs. + const inline = psEnv[2] !== undefined && psEnv[2] !== ""; + const from = inline ? 1 : psEnv[2] !== undefined ? 1 : 2; + const value = inline ? psEnv[2]! : words[from]; + // Inline, the word's own `$env:` counts as an expansion, so look at the value part alone. + const expandsValue = inline ? /\$[A-Za-z_{(]/.test(value!) : dynamic[from]; + const known = value !== undefined && words.length === (inline ? 1 : from + 1) && !expandsValue; + assign(state, psEnv[1]!, known ? value : UNKNOWN_VALUE, true); + return; + } const ps = PS_ASSIGNMENT.exec(words[0] ?? ""); if (ps && (ps[2] !== undefined || words[1] === "=")) { // `$x = "vercel"` stores a string; `$x = vercel ls` runs vercel and stores its output. const inline = ps[2] !== undefined && ps[2] !== ""; const rest = inline ? [ps[2]!, ...words.slice(1)] : words.slice(ps[2] !== undefined ? 1 : 2); const restQuoted = inline ? quoted : quoted.slice(ps[2] !== undefined ? 1 : 2); + const restDynamic = inline ? dynamic : dynamic.slice(ps[2] !== undefined ? 1 : 2); if (rest.length === 1 && restQuoted[0]) { state.vars[ps[1]!] = rest[0]!; return; } delete state.vars[ps[1]!]; - if (rest.length > 0) analyse(rest, stdin, out, state, restQuoted); + if (rest.length > 0) analyse(rest, stdin, out, state, restQuoted, restDynamic); return; } const env: Record = {}; @@ -245,14 +339,14 @@ function analyse(words: string[], stdin: string[], out: Invocation[], state: Sta const word = words[i]; if (word === undefined) { // Only assignments: they set shell variables for the rest of the line. - Object.assign(state.vars, env); + for (const [name, value] of Object.entries(env)) assign(state, name, value, false); return; } const assignment = ASSIGNMENT.exec(word); const name = commandName(word); const wrapper = VALUE_WRAPPERS[name]; if (assignment) { - env[assignment[1]!] = assignment[2]!; + env[assignment[1]!] = dynamic[i] ? UNKNOWN_VALUE : assignment[2]!; i++; } else if (wrapper) { i++; @@ -278,7 +372,8 @@ function analyse(words: string[], stdin: string[], out: Invocation[], state: Sta // A command held in a variable: `CLI=vercel; $CLI deploy`. const variable = VARIABLE.exec(bin); if (variable) { - const value = state.vars[variable[1] ?? variable[2]!]; + const held = state.vars[variable[1] ?? variable[2]!]; + const value = held === UNKNOWN_VALUE ? undefined : held; if (value === undefined) { // Unknown here (set elsewhere): check every guarded CLI the line names. // A bare `$files` is most likely a value (PowerShell pipes it), not a command. @@ -293,6 +388,31 @@ function analyse(words: string[], stdin: string[], out: Invocation[], state: Sta } const name = commandName(bin); + if (EXPORTERS.has(name)) { + // `declare`/`typeset` export only with -x; `export -n` un-exports (left alone: it never adds a variable). + const flags = args.filter((a) => a.startsWith("-")); + if (name !== "export" && !flags.some((f) => /^-[a-zA-Z]*x/.test(f))) return; + if (flags.includes("-n")) return; + const offset = i + 1; + args.forEach((arg, k) => { + if (arg.startsWith("-")) return; + const set = ASSIGNMENT.exec(arg); + if (set) assign(state, set[1]!, dynamic[offset + k] ? UNKNOWN_VALUE : set[2]!, true); + else if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(arg) && arg in state.vars) assign(state, arg, state.vars[arg]!, true); + }); + return; + } + if (name === "unset") { + if (args.includes("-f")) return; + for (const arg of args) { + if (arg.startsWith("-")) continue; + delete state.vars[arg]; + delete state.exported[arg]; + delete state.plain[arg]; + state.unset.add(arg); + } + return; + } if (name === "cd") { const target = args[0]; if (target !== undefined && target !== "-") { @@ -331,7 +451,11 @@ function analyse(words: string[], stdin: string[], out: Invocation[], state: Sta } function invocation(bin: string, args: string[], env: Record, state: State): Invocation { - return state.cwd === undefined ? { bin, args, env } : { bin, args, env, cwd: state.cwd }; + const inv: Invocation = { bin, args, env: { ...state.exported, ...env } }; + if (Object.keys(state.plain).length > 0) inv.ifExported = { ...state.plain }; + if (state.unset.size > 0) inv.unset = [...state.unset]; + if (state.cwd !== undefined) inv.cwd = state.cwd; + return inv; } /** Guarded CLI names that appear as whole words anywhere in the line. */ @@ -344,27 +468,37 @@ function namedClis(state: State): string[] { function collect(input: string, out: Invocation[], state: State): void { let segment: string[] = []; let quoted: boolean[] = []; + let dynamic: boolean[] = []; let stdin: string[] = []; - // Folders to go back to when a ( ) subshell ends. - const saved: (string | undefined)[] = []; + // What to go back to when a ( ) subshell ends: its `cd` and variables don't come back (#86). + const saved: State[] = []; const end = () => { - if (segment.length > 0) analyse(segment, stdin, out, state, quoted); + if (segment.length > 0) analyse(segment, stdin, out, state, quoted, dynamic); segment = []; quoted = []; + dynamic = []; stdin = []; }; for (const token of tokenize(input)) { if (token.kind === "word") { segment.push(token.value); quoted.push(token.quoted); + dynamic.push(token.dynamic); } else if (token.kind === "stdin") stdin.push(token.body); // Runs where it appears, in a child shell, so a `cd` inside does not leak. else if (token.kind === "subst") collect(token.inner, out, child(state)); else { end(); - if (token.op === "(") saved.push(state.cwd); - else if (token.op === ")" && saved.length > 0) state.cwd = saved.pop(); + if (token.op === "(") saved.push(child(state)); + else if (token.op === ")" && saved.length > 0) { + const outer = saved.pop()!; + state.cwd = outer.cwd; + state.vars = outer.vars; + state.exported = outer.exported; + state.plain = outer.plain; + state.unset = outer.unset; + } } } end(); @@ -381,6 +515,14 @@ function collect(input: string, out: Invocation[], state: State): void { */ export function findInvocations(command: string, guardedBins: string[], baseCwd?: string): Invocation[] { const out: Invocation[] = []; - collect(command, out, { base: baseCwd, vars: {}, line: command, guarded: new Set(guardedBins) }); + collect(command, out, { + base: baseCwd, + vars: {}, + exported: {}, + plain: {}, + unset: new Set(), + line: command, + guarded: new Set(guardedBins), + }); return out; } diff --git a/src/types.ts b/src/types.ts index d630af3..47059de 100644 --- a/src/types.ts +++ b/src/types.ts @@ -57,3 +57,9 @@ export interface ProviderDef

{ /** Environment variables and files that decide the identity (cache invalidation). */ cacheInputs(env: NodeJS.ProcessEnv): CacheInputs; } + +/** + * A variable's value when the line sets it from something only known when it + * runs: `$(...)`, backticks, `$OTHER`, a PowerShell expression (#86). + */ +export const UNKNOWN_VALUE = ""; diff --git a/test/hook-agents.test.ts b/test/hook-agents.test.ts index bbf89bb..b5b19b8 100644 --- a/test/hook-agents.test.ts +++ b/test/hook-agents.test.ts @@ -13,7 +13,7 @@ const gh: ProviderDef<"github"> = { compare: (pin, id) => (pin.user === id.user ? [] : [`user: expected "${pin.user}", active is "${id.user}"`]), switchHint: (pin) => `gh auth switch --user ${pin.user}`, statusCommand: "gh auth status", - cacheInputs: () => ({ env: [], files: [], dirs: [] }), + cacheInputs: () => ({ env: ["FAKE_GH_USER", "GH_TOKEN"], files: [], dirs: [] }), }; const config: FoundConfig = { path: "/repo/.cloudpin.yml", pins: { github: { user: "paureis" } } }; const deps: GuardDeps = { @@ -50,6 +50,38 @@ const inputs = { }), }; +// #86: variables set earlier in the agent's line decide the account the CLI uses. +describe("runHook: environment set earlier in the line", () => { + const decision = async (command: string, env: NodeJS.ProcessEnv = {}) => + JSON.parse((await runHook(AGENTS.codex, inputs.codex(command), deps, env)) || "{}").hookSpecificOutput?.permissionDecision ?? "none"; + + it("denies when an export earlier in the line switches to the wrong account", async () => { + expect(await decision("export FAKE_GH_USER=someone; gh pr list")).toBe("deny"); + expect(await decision("$env:FAKE_GH_USER = 'someone'; gh pr list")).toBe("deny"); + expect(await decision("export FAKE_GH_USER=paureis; gh pr list")).toBe("none"); + }); + + it("counts a plain assignment only when the variable is already exported", async () => { + expect(await decision("FAKE_GH_USER=someone; gh pr list")).toBe("none"); + expect(await decision("FAKE_GH_USER=someone; gh pr list", { FAKE_GH_USER: "paureis" })).toBe("deny"); + }); + + it("follows unset", async () => { + expect(await decision("unset FAKE_GH_USER; gh pr list", { FAKE_GH_USER: "someone" })).toBe("none"); + }); + + it("denies, saying why, when a variable that decides the account is set from something unknown in advance", async () => { + const out = JSON.parse(await runHook(AGENTS.codex, inputs.codex("GH_TOKEN=$(cat other.token) gh repo list"), deps, {})); + expect(out.hookSpecificOutput.permissionDecision).toBe("deny"); + expect(out.hookSpecificOutput.permissionDecisionReason).toContain("GH_TOKEN"); + expect(await decision("export GH_TOKEN=$(cat other.token); gh repo list")).toBe("deny"); + }); + + it("ignores an unknown value for a variable that doesn't decide the account", async () => { + expect(await decision("export PAGER=$(which less); gh pr list")).toBe("none"); + }); +}); + describe("runHook: codex (same protocol as Claude Code)", () => { it("denies through hookSpecificOutput", async () => { const out = JSON.parse(await runHook(AGENTS.codex, inputs.codex("gh pr list"), deps, wrong)); diff --git a/test/shellwords.test.ts b/test/shellwords.test.ts index 520bb42..ee22363 100644 --- a/test/shellwords.test.ts +++ b/test/shellwords.test.ts @@ -1,7 +1,7 @@ import { resolve } from "node:path"; import { describe, expect, it } from "vitest"; import { commandName } from "../src/guard.js"; -import { findInvocations } from "../src/shellwords.js"; +import { envFor, findInvocations, UNKNOWN_VALUE } from "../src/shellwords.js"; const GUARDED = ["az", "aws", "gcloud", "vercel", "gh"]; const find = (cmd: string) => findInvocations(cmd, GUARDED); @@ -115,3 +115,82 @@ describe("findInvocations with cd", () => { expect(findInvocations("gh pr list", GUARDED, base)[0]?.cwd).toBeUndefined(); }); }); + +// #86: a variable set by an earlier statement in the line reaches the CLI. +describe("findInvocations: environment set earlier in the line", () => { + const one = (cmd: string) => find(cmd)[0]!; + + it.each([ + ["export AWS_PROFILE=other; aws s3 ls"], + ["export AWS_PROFILE=other && aws s3 ls"], + ["export AWS_PROFILE='other'\naws s3 ls"], + ["declare -x AWS_PROFILE=other; aws s3 ls"], + ["typeset -x AWS_PROFILE=other; aws s3 ls"], + ["$env:AWS_PROFILE='other'; aws s3 ls"], + ['$env:AWS_PROFILE = "other"; aws s3 ls'], + ])("applies %j to the later call", (cmd) => { + expect(one(cmd).env).toEqual({ AWS_PROFILE: "other" }); + }); + + it("exports a variable assigned before `export NAME`", () => { + expect(one("AWS_PROFILE=other; export AWS_PROFILE; aws s3 ls").env).toEqual({ AWS_PROFILE: "other" }); + }); + + it("lets a prefix assignment win over an earlier export, for that call only", () => { + const calls = find("export AWS_PROFILE=a; AWS_PROFILE=b aws s3 ls; aws ec2 describe-instances"); + expect(calls.map((c) => c.env.AWS_PROFILE)).toEqual(["b", "a"]); + }); + + it("keeps an export inside a subshell or bash -c from leaking out", () => { + expect(one("(export AWS_PROFILE=other); aws s3 ls").env).toEqual({}); + expect(one("bash -c 'export AWS_PROFILE=other'; aws s3 ls").env).toEqual({}); + expect(one("(export AWS_PROFILE=other; aws s3 ls)").env).toEqual({ AWS_PROFILE: "other" }); + }); + + it("reports a plain assignment separately: it only reaches the CLI if the name is already exported", () => { + const call = one("AWS_PROFILE=other; aws s3 ls"); + expect(call.env).toEqual({}); + expect(call.ifExported).toEqual({ AWS_PROFILE: "other" }); + }); + + it("reports unset names", () => { + expect(one("unset AWS_PROFILE; aws s3 ls").unset).toEqual(["AWS_PROFILE"]); + expect(one("export AWS_PROFILE=x; unset AWS_PROFILE; aws s3 ls").env).toEqual({}); + }); + + it.each([ + ["GH_TOKEN=$(cat other.token) gh repo list"], + ["GH_TOKEN=`cat other.token` gh repo list"], + ['GH_TOKEN="$OTHER" gh repo list'], + ["GH_TOKEN=${OTHER} gh repo list"], + ["export GH_TOKEN=$(cat other.token); gh repo list"], + ["$env:GH_TOKEN = (Get-Content other.token); gh repo list"], + ])("marks a value it can't know in advance as unknown: %j", (cmd) => { + expect(find(cmd).find((c) => c.bin === "gh")!.env).toEqual({ GH_TOKEN: UNKNOWN_VALUE }); + }); + + it("keeps a single-quoted $ literal", () => { + expect(one("GH_HOST='$literal' gh repo list").env).toEqual({ GH_HOST: "$literal" }); + }); +}); + +describe("envFor (#86)", () => { + const base = { AWS_PROFILE: "default", HOME: "/h" }; + + it("applies plain assignments only to names already exported, then unsets, then exports", () => { + expect(envFor(base, { bin: "aws", args: [], env: {}, ifExported: { AWS_PROFILE: "x", NOT_EXPORTED: "y" } })).toEqual({ + AWS_PROFILE: "x", + HOME: "/h", + }); + expect(envFor(base, { bin: "aws", args: [], env: {}, unset: ["AWS_PROFILE"] })).toEqual({ HOME: "/h" }); + expect(envFor(base, { bin: "aws", args: [], env: { AWS_PROFILE: "z" }, unset: ["AWS_PROFILE"] })).toEqual({ + AWS_PROFILE: "z", + HOME: "/h", + }); + }); + + it("never lets the line set CLOUDPIN_SKIP, CLOUDPIN_CONFIRM or CLOUDPIN_ENV for an agent", () => { + const inv = { bin: "aws", args: [], env: { CLOUDPIN_SKIP: "1" }, ifExported: { CLOUDPIN_ENV: "dev" }, unset: ["CLOUDPIN_ENV"] }; + expect(envFor({ CLOUDPIN_ENV: "prod" }, inv, { agent: true })).toEqual({ CLOUDPIN_ENV: "prod" }); + }); +});