From 519bf91f614bbe1f22573dcc6edf6faa1e858f34 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:34:12 -0400 Subject: [PATCH 01/21] Cloudflare: account variables with unknown values block as can't tell (#119) `CLOUDFLARE_ACCOUNT_ID=$(cat id) wrangler deploy` dropped the variable, since guard only stops on an unknown value in a provider's identity variables (cacheInputs().env, #86), and the account variables weren't in Cloudflare's list. cloudpin then resolved the account without them while Wrangler used the unknown value. Cloudflare's identity variables are now every name in DOTENV_VARS (the account variables, CLOUDFLARE_ENV, WRANGLER_CACHE_DIR, the credentials) plus DOTENV_KEY, which makes Wrangler decrypt a .env.vault instead of .env. whoami's cache key gains names it ignores, which can only make it miss. Co-Authored-By: Claude Opus 5.5 --- src/providers/cloudflare.ts | 8 ++- test/cloudflare-account-vars.test.ts | 84 ++++++++++++++++++++++++++++ test/wrangler-dotenv.test.ts | 3 +- 3 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 test/cloudflare-account-vars.test.ts diff --git a/src/providers/cloudflare.ts b/src/providers/cloudflare.ts index a9a6266..16e35b3 100644 --- a/src/providers/cloudflare.ts +++ b/src/providers/cloudflare.ts @@ -3,7 +3,7 @@ import { basename, dirname, join, resolve as resolvePath } from "node:path"; import { commandWords, flagValue, hasAnyFlag } from "../args.js"; import { home } from "../paths.js"; import type { ProviderDef, Resolution } from "../types.js"; -import { envFileArgs, wranglerDotenv } from "./wrangler-dotenv.js"; +import { DOTENV_VARS, envFileArgs, wranglerDotenv } from "./wrangler-dotenv.js"; // Sources: github.com/cloudflare/workers-sdk (packages/workers-auth/src/core/factory.ts // getActiveAccountId and getOrSelectAccountId; packages/workers-utils/src/config/ @@ -175,7 +175,11 @@ export const cloudflare: ProviderDef<"cloudflare"> = { // Wrangler config folder (~/.wrangler if it exists, else the XDG one). const dirs = [join(home(env), ".wrangler"), join(env.XDG_CONFIG_HOME ?? join(home(env), ".config"), ".wrangler")]; return { - env: [...TOKEN_VARS, "CLOUDFLARE_EMAIL", "CF_EMAIL", "CLOUDFLARE_AUTH_USE_KEYRING"], + // Every variable that decides the account, not only whoami's credentials: + // guard blocks when a command line sets one to a value it can't know (#86, + // #119). DOTENV_KEY picks a .env.vault over .env (wrangler-dotenv.ts). Names + // whoami ignores can only make its cache miss, never hit wrongly. + env: [...DOTENV_VARS, "DOTENV_KEY"], files: dirs.map((d) => join(d, "config", "default.toml")), dirs: [], }; diff --git a/test/cloudflare-account-vars.test.ts b/test/cloudflare-account-vars.test.ts new file mode 100644 index 0000000..52cf05a --- /dev/null +++ b/test/cloudflare-account-vars.test.ts @@ -0,0 +1,84 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import type { FoundConfig } from "../src/config.js"; +import { guard, type Verdict } from "../src/guard.js"; +import { cloudflare } from "../src/providers/cloudflare.js"; +import { envFor, findInvocations } from "../src/shellwords.js"; +import type { Exec } from "../src/types.js"; +import { tempDir } from "./tmp.js"; + +// #119, part 1: a variable that decides Wrangler's account, set by an agent's +// line from something cloudpin can't read in advance ($(...), backticks, +// $OTHER), must block as "can't tell" (the #86 mechanism), not be dropped +// while Wrangler goes on to use it. + +const A = "0123456789abcdef0123456789abcdef"; +const B = "fedcba9876543210fedcba9876543210"; +const pinnedToA: FoundConfig = { path: "/repo/.cloudpin.yml", pins: { cloudflare: { account: A } } }; + +function folder(files: Record = {}) { + const root = tempDir("cloudpin-cf-account-vars-"); + for (const [name, content] of Object.entries(files)) { + mkdirSync(join(root, name, ".."), { recursive: true }); + writeFileSync(join(root, name), content); + } + return root; +} + +/** A fake `wrangler whoami` whose credentials see only account A, the pinned one. */ +const onlyA: Exec = async () => ({ code: 0, stdout: JSON.stringify({ loggedIn: true, accounts: [{ id: A, name: "Acme" }] }), stderr: "" }); + +/** The verdict for an agent's command line, as the hook builds it (findInvocations, then envFor). */ +async function agentLine(line: string, cwd: string, base: NodeJS.ProcessEnv = {}): Promise { + const [inv] = findInvocations(line, cloudflare.bins, cwd); + return guard( + { bin: inv!.bin, args: inv!.args, env: envFor(base, inv!, { agent: true }), cwd, mode: "agent" }, + { providers: [cloudflare], exec: onlyA, findConfig: () => pinnedToA }, + ); +} + +describe("guard: Cloudflare account variables with unknown values (#119)", () => { + it.each(["CLOUDFLARE_ACCOUNT_ID", "CF_ACCOUNT_ID"])("blocks %s=$(...) as can't tell", async (name) => { + // Without the variable cloudpin would reach whoami, whose only account is the pinned one. + for (const value of ["$(cat id)", "`cat id`", "$OTHER"]) { + const v = await agentLine(`${name}=${value} wrangler deploy`, folder()); + expect(v).toMatchObject({ action: "block", uncertain: true, problems: [expect.stringContaining(`${name} is set by the command line`)] }); + } + }); + + it("blocks CLOUDFLARE_ENV=$(...) when the config file's sections name different accounts", async () => { + const root = folder({ "wrangler.toml": `account_id = "${A}"\n[env.staging]\naccount_id = "${B}"\n` }); + expect(await agentLine("CLOUDFLARE_ENV=$(cat e) wrangler deploy", root)).toMatchObject({ action: "block", uncertain: true }); + }); + + it("blocks WRANGLER_CACHE_DIR=$(...), which picks the account cache Wrangler reads", async () => { + const root = folder({ ".wrangler/cache/wrangler-account.json": JSON.stringify({ account: { id: A } }) }); + expect(await agentLine("WRANGLER_CACHE_DIR=$(cat d) wrangler deploy", root)).toMatchObject({ action: "block", uncertain: true }); + }); + + it("blocks DOTENV_KEY=$(...) when a .env.vault exists, since Wrangler would decrypt it instead of .env", async () => { + const root = folder({ ".env": `CLOUDFLARE_ACCOUNT_ID=${A}\n`, ".env.vault": "DOTENV_VAULT_PRODUCTION=x\n" }); + expect(await agentLine("DOTENV_KEY=$(cat k) wrangler deploy", root)).toMatchObject({ action: "block", uncertain: true }); + }); + + it("still resolves known values: the pinned account passes, another one blocks", async () => { + expect(await agentLine(`CLOUDFLARE_ACCOUNT_ID=${A} wrangler deploy`, folder())).toEqual({ action: "allow", reason: "match" }); + const blocked = await agentLine(`CF_ACCOUNT_ID=${B} wrangler deploy`, folder()); + expect(blocked).toMatchObject({ action: "block", problems: [expect.stringContaining(B)] }); + expect(blocked).not.toHaveProperty("uncertain"); + }); + + it("controls: an unknown value in a variable Wrangler doesn't read is still dropped", async () => { + expect(await agentLine(`BUILD_ID=$(date) CLOUDFLARE_ACCOUNT_ID=${A} wrangler deploy`, folder())).toEqual({ action: "allow", reason: "match" }); + expect(await agentLine("BUILD_ID=$(date) wrangler deploy", folder())).toEqual({ action: "allow", reason: "match" }); + }); + + it("every variable the provider follows from .env counts as an identity variable", () => { + // DOTENV_VARS (wrangler-dotenv.ts) lists what decides the account or the credentials. + const identity = cloudflare.cacheInputs({}).env; + for (const name of ["CLOUDFLARE_ACCOUNT_ID", "CF_ACCOUNT_ID", "CLOUDFLARE_ENV", "WRANGLER_CACHE_DIR", "DOTENV_KEY"]) { + expect(identity).toContain(name); + } + }); +}); diff --git a/test/wrangler-dotenv.test.ts b/test/wrangler-dotenv.test.ts index f62a5a6..4d16864 100644 --- a/test/wrangler-dotenv.test.ts +++ b/test/wrangler-dotenv.test.ts @@ -210,7 +210,8 @@ describe("wranglerDotenv: the environment Wrangler gives itself", () => { }); it("covers every variable the identity cache keys on", () => { - for (const name of cloudflare.cacheInputs({}).env) expect(DOTENV_VARS).toContain(name); + // DOTENV_KEY is read from the process only (dotenv's _dotenvKey), never from a .env file. + for (const name of cloudflare.cacheInputs({}).env) if (name !== "DOTENV_KEY") expect(DOTENV_VARS).toContain(name); for (const name of ["CLOUDFLARE_ACCOUNT_ID", "CF_ACCOUNT_ID", "CLOUDFLARE_ENV", "WRANGLER_CACHE_DIR"]) expect(DOTENV_VARS).toContain(name); }); }); From 64e29d45a33d9d3edf6181c32357fc4c92286b89 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:36:27 -0400 Subject: [PATCH 02/21] Windows: providers read variable names case-insensitively (#119) Windows variable names ignore case, and so does every guarded CLI there: Node's process.env, Wrangler's caseInsensitiveEnv proxy over its merged environment (wrangler@4.151.3, config/case-insensitive-env.ts, used by config/dot-env.ts loadDotEnv on Windows only, installed as process.env in index.ts), Go's os.Getenv and Python's upper-cased os.environ. guard handed providers a plain object, so `cloudflare_account_id=B` from the shell or an agent's line was missed by env.CLOUDFLARE_ACCOUNT_ID, as were gh_host and the rest, and the identity cache keyed on AWS_* missed aws_profile and reused another profile's identity. On win32 guard now gives the provider one upper-case key per name. When two spellings of a variable that decides the account hold different values, which one a CLI sees depends on the shell and the CLI, so the command blocks as can't tell, naming the spellings, never the values. Other variables keep the value of the first key in code-unit order, the one Node keeps when it spawns. An unknown value in either spelling blocks as before (#86). Linux and macOS are unchanged. The platform is injectable through GuardDeps for tests. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 52 +++++++++++- test/guard-env-case.test.ts | 159 ++++++++++++++++++++++++++++++++++++ 2 files changed, 209 insertions(+), 2 deletions(-) create mode 100644 test/guard-env-case.test.ts diff --git a/src/guard.ts b/src/guard.ts index de87d9a..f2a3bb7 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -26,6 +26,41 @@ export interface GuardDeps { * not installed when none of its commands is found, since some providers never spawn it (#75). */ onPath?: (bin: string, env: NodeJS.ProcessEnv) => string | null; + /** The platform the command runs on; on win32 variable names are case-insensitive. Defaults to this process's. */ + platform?: NodeJS.Platform; +} + +/** + * The command's environment as a Windows program reads it: one upper-case key + * per name, since Windows and every guarded CLI there ignore case (Node's + * process.env, Wrangler's caseInsensitiveEnv, Go's os.Getenv, Python's + * os.environ) (#119). When two spellings differ, the value is the one of the + * first key in code-unit order, the one Node keeps when it spawns + * (child_process normalizeSpawnArguments), except that an unknown value wins; + * `conflicts` names those variables, as which value a CLI sees then depends + * on the shell and the CLI. Other platforms get `env` unchanged. + */ +export function foldEnvNames(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): { env: NodeJS.ProcessEnv; conflicts: Map } { + const conflicts = new Map(); + if (platform !== "win32") return { env, conflicts }; + const out: NodeJS.ProcessEnv = {}; + const spellings = new Map(); + for (const key of Object.keys(env).sort()) { + const value = env[key]; + if (value === undefined) continue; + const name = key.toUpperCase(); + const seen = spellings.get(name); + if (seen === undefined) { + spellings.set(name, [key]); + out[name] = value; + continue; + } + seen.push(key); + if (value === out[name]) continue; + if (value === UNKNOWN_VALUE || out[name] === UNKNOWN_VALUE) out[name] = UNKNOWN_VALUE; + else conflicts.set(name, seen); + } + return { env: out, conflicts }; } /** False only when `onPath` is given and finds none of the provider's commands. */ @@ -127,10 +162,12 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { if (result.notFound) cliMissing = true; return result; }; + // On Windows the provider reads names the way the CLI does, case-insensitively (#119). + const folded = foldEnvNames(req.env, deps.platform ?? process.platform); // 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)); + const unknown = Object.keys(folded.env).filter((k) => folded.env[k] === UNKNOWN_VALUE && envNameMatches(identityVars, k)); if (unknown.length > 0) { return { ...base, @@ -141,8 +178,19 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { fix: `set ${unknown[0]} to a literal value, or run the command yourself`, }; } + const conflict = [...folded.conflicts].find(([k]) => envNameMatches(identityVars, k)); + if (conflict) { + return { + ...base, + uncertain: true, + problems: [ + `${conflict[1].join(" and ")} are set to different values; on Windows they are one variable, so cloudpin can't tell which value this command would use`, + ], + fix: `set ${conflict[0]} in one spelling only`, + }; + } // 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 env = Object.fromEntries(Object.entries(folded.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" }; diff --git a/test/guard-env-case.test.ts b/test/guard-env-case.test.ts new file mode 100644 index 0000000..b8097d7 --- /dev/null +++ b/test/guard-env-case.test.ts @@ -0,0 +1,159 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { cachedExec } from "../src/cache.js"; +import type { FoundConfig } from "../src/config.js"; +import { guard, type GuardDeps, type Verdict } from "../src/guard.js"; +import { aws } from "../src/providers/aws.js"; +import { cloudflare } from "../src/providers/cloudflare.js"; +import { github } from "../src/providers/github.js"; +import { envFor, findInvocations } from "../src/shellwords.js"; +import type { Exec, ProviderDef } from "../src/types.js"; +import { tempDir } from "./tmp.js"; + +// #119, part 2: Windows variable names are case-insensitive, and so is every +// guarded CLI there (Node's process.env, Wrangler's caseInsensitiveEnv proxy, +// Go's os.Getenv, Python's upper-cased os.environ), so `cloudflare_account_id` +// is CLOUDFLARE_ACCOUNT_ID. On Linux they are different variables. guard hands +// providers a plain object, so it folds the names itself on Windows. + +const A = "0123456789abcdef0123456789abcdef"; +const B = "fedcba9876543210fedcba9876543210"; + +function folder(files: Record = {}) { + const root = tempDir("cloudpin-env-case-"); + for (const [name, content] of Object.entries(files)) { + mkdirSync(join(root, name, ".."), { recursive: true }); + writeFileSync(join(root, name), content); + } + return root; +} + +/** A fake `wrangler whoami` whose credentials see one account. */ +const whoamiSees = (id: string): Exec => async () => ({ code: 0, stdout: JSON.stringify({ loggedIn: true, accounts: [{ id }] }), stderr: "" }); + +function cfDeps(platform: NodeJS.Platform, exec: Exec): GuardDeps { + const pinnedToA: FoundConfig = { path: "/repo/.cloudpin.yml", pins: { cloudflare: { account: A } } }; + return { providers: [cloudflare], exec, findConfig: () => pinnedToA, platform }; +} + +const shell = (env: NodeJS.ProcessEnv, cwd: string, deps: GuardDeps, bin = "wrangler", args = ["deploy"]) => + guard({ bin, args, env, cwd, mode: "shell" }, deps); + +/** An agent's line, as the hook builds it (findInvocations, then envFor). */ +async function agentLine(line: string, cwd: string, deps: GuardDeps, base: NodeJS.ProcessEnv = {}): Promise { + const [inv] = findInvocations(line, deps.providers.flatMap((p) => p.bins), cwd); + return guard({ bin: inv!.bin, args: inv!.args, env: envFor(base, inv!, { agent: true }), cwd, mode: "agent" }, deps); +} + +const mismatch = (other: string) => ({ action: "block", problems: [expect.stringContaining(other)] }); +const allowed = { action: "allow", reason: "match" }; + +describe("guard: lowercase Cloudflare variables count on Windows only (#119)", () => { + it("reads a lowercase account variable from the shell's environment on win32", async () => { + // whoami sees only the pinned account, so a missed variable would pass. + const root = folder(); + expect(await shell({ cloudflare_account_id: B }, root, cfDeps("win32", whoamiSees(A)))).toMatchObject(mismatch(B)); + expect(await shell({ cf_account_id: B }, root, cfDeps("win32", whoamiSees(A)))).toMatchObject(mismatch(B)); + // Control: the right account passes, though whoami alone would block. + expect(await shell({ Cloudflare_Account_Id: A }, root, cfDeps("win32", whoamiSees(B)))).toEqual(allowed); + }); + + it("ignores the same lowercase name on linux, where it is another variable", async () => { + const root = folder(); + expect(await shell({ cloudflare_account_id: B }, root, cfDeps("linux", whoamiSees(A)))).toEqual(allowed); + expect(await shell({ cloudflare_account_id: A }, root, cfDeps("linux", whoamiSees(B)))).toMatchObject(mismatch(B)); + }); + + it("reads a lowercase assignment in an agent's line on win32, and not on linux", async () => { + const root = folder(); + expect(await agentLine(`cloudflare_account_id=${B} wrangler deploy`, root, cfDeps("win32", whoamiSees(A)))).toMatchObject(mismatch(B)); + expect(await agentLine(`cloudflare_account_id=${A} wrangler deploy`, root, cfDeps("win32", whoamiSees(B)))).toEqual(allowed); + expect(await agentLine(`cloudflare_account_id=${B} wrangler deploy`, root, cfDeps("linux", whoamiSees(A)))).toEqual(allowed); + }); + + it("blocks a lowercase account variable with an unknown value on win32 only", async () => { + const root = folder(); + const line = "cloudflare_account_id=$(cat id) wrangler deploy"; + expect(await agentLine(line, root, cfDeps("win32", whoamiSees(A)))).toMatchObject({ + action: "block", + uncertain: true, + problems: [expect.stringContaining("CLOUDFLARE_ACCOUNT_ID is set by the command line")], + }); + expect(await agentLine(line, root, cfDeps("linux", whoamiSees(A)))).toEqual(allowed); + }); + + it("follows a lowercase cloudflare_env to its config section on win32", async () => { + const root = folder({ "wrangler.toml": `account_id = "${A}"\n[env.staging]\naccount_id = "${B}"\n` }); + expect(await shell({ cloudflare_env: "staging" }, root, cfDeps("win32", whoamiSees(A)))).toMatchObject(mismatch(B)); + expect(await shell({ cloudflare_env: "staging" }, root, cfDeps("linux", whoamiSees(A)))).toEqual(allowed); + }); + + it("can't tell when two spellings of an account variable hold different values on win32", async () => { + // Which one a Windows program sees depends on the shell and the program, + // so cloudpin blocks, naming the spellings but never the values. + const root = folder(); + const v = await agentLine(`cloudflare_account_id=${B} wrangler deploy`, root, cfDeps("win32", whoamiSees(A)), { CLOUDFLARE_ACCOUNT_ID: A }); + expect(v).toMatchObject({ action: "block", uncertain: true, problems: [expect.stringMatching(/CLOUDFLARE_ACCOUNT_ID.*cloudflare_account_id/)] }); + expect(JSON.stringify(v)).not.toContain(B); + // The same value twice is no conflict; on linux they are two variables anyway. + expect(await agentLine(`cloudflare_account_id=${A} wrangler deploy`, root, cfDeps("win32", whoamiSees(B)), { CLOUDFLARE_ACCOUNT_ID: A })).toEqual(allowed); + expect(await agentLine(`cloudflare_account_id=${B} wrangler deploy`, root, cfDeps("linux", whoamiSees(B)), { CLOUDFLARE_ACCOUNT_ID: A })).toEqual(allowed); + }); + + it("keeps one spelling of a variable that doesn't decide the account, as Node does when it spawns", async () => { + const seen: NodeJS.ProcessEnv[] = []; + const exec: Exec = async (_bin, _args, env) => { + seen.push(env); + return whoamiSees(A)(_bin, _args, env); + }; + expect(await shell({ Path: "C:\\b", PATH: "C:\\a" }, folder(), cfDeps("win32", exec))).toEqual(allowed); + expect(seen[0]).toEqual({ PATH: "C:\\a" }); + }); +}); + +describe("guard: lowercase variables of other providers on Windows (#119)", () => { + it("GitHub: a lowercase gh_host sends cloudpin's question to that host on win32 only", async () => { + const hosts: string[] = []; + const exec: Exec = async (_bin, args) => { + hosts.push(args[args.indexOf("--hostname") + 1]!); + return { code: 0, stdout: "octocat\n", stderr: "" }; + }; + const deps = (platform: NodeJS.Platform): GuardDeps => ({ + providers: [github], + exec, + findConfig: () => ({ path: "/repo/.cloudpin.yml", pins: { github: { user: "octocat" } } }), + platform, + }); + expect(await shell({ gh_host: "ghe.example.com" }, "/repo", deps("win32"), "gh", ["repo", "list"])).toMatchObject(mismatch("ghe.example.com")); + expect(await shell({ gh_host: "ghe.example.com" }, "/repo", deps("linux"), "gh", ["repo", "list"])).toEqual(allowed); + expect(hosts).toEqual(["ghe.example.com", "github.com"]); + // An unknown value in a lowercase token variable can't be told on win32. + expect(await agentLine("gh_token=$(cat t) gh repo list", "/repo", deps("win32"))).toMatchObject({ action: "block", uncertain: true }); + expect(await agentLine("gh_token=$(cat t) gh repo list", "/repo", deps("linux"))).toEqual(allowed); + }); + + it("AWS: a lowercase aws_profile misses the identity cache on win32, so the other account is seen", async () => { + const run = async (platform: NodeJS.Platform) => { + const cacheDir = tempDir("cloudpin-env-case-cache-"); + const exec: Exec = async (_bin, _args, env) => { + const account = env.AWS_PROFILE === "other" ? "999999999999" : "111111111111"; + return { code: 0, stdout: JSON.stringify({ Account: account, Arn: `arn:aws:iam::${account}:user/me` }), stderr: "" }; + }; + const deps: GuardDeps = { + providers: [aws], + exec, + findConfig: () => ({ path: "/repo/.cloudpin.yml", pins: { aws: { account: "111111111111" } } }), + wrapExec: (p: ProviderDef, env, inner) => cachedExec(inner, p.cacheInputs(env), { cacheDir, env: {} }), + platform, + }; + const home = tempDir("cloudpin-env-case-home-"); + const first = await shell({ HOME: home }, "/repo", deps, "aws", ["s3", "ls"]); + const second = await shell({ HOME: home, aws_profile: "other" }, "/repo", deps, "aws", ["s3", "ls"]); + return [first, second]; + }; + expect(await run("win32")).toEqual([allowed, expect.objectContaining(mismatch("999999999999"))]); + // On linux aws ignores aws_profile, so the cached identity is the right one. + expect(await run("linux")).toEqual([allowed, allowed]); + }); +}); From 85648c0210e728ff8a701d56def9761fe87da446 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:36:51 -0400 Subject: [PATCH 03/21] Test: an unknown value in one spelling gives the unknown reason (#119) Co-Authored-By: Claude Opus 5.5 --- test/guard-env-case.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/guard-env-case.test.ts b/test/guard-env-case.test.ts index b8097d7..a819dd8 100644 --- a/test/guard-env-case.test.ts +++ b/test/guard-env-case.test.ts @@ -96,6 +96,12 @@ describe("guard: lowercase Cloudflare variables count on Windows only (#119)", ( const v = await agentLine(`cloudflare_account_id=${B} wrangler deploy`, root, cfDeps("win32", whoamiSees(A)), { CLOUDFLARE_ACCOUNT_ID: A }); expect(v).toMatchObject({ action: "block", uncertain: true, problems: [expect.stringMatching(/CLOUDFLARE_ACCOUNT_ID.*cloudflare_account_id/)] }); expect(JSON.stringify(v)).not.toContain(B); + // When one spelling's value is unknown, that is the reason given. + expect(await agentLine("cloudflare_account_id=$(cat id) wrangler deploy", root, cfDeps("win32", whoamiSees(A)), { CLOUDFLARE_ACCOUNT_ID: A })).toMatchObject({ + action: "block", + uncertain: true, + problems: [expect.stringContaining("CLOUDFLARE_ACCOUNT_ID is set by the command line")], + }); // The same value twice is no conflict; on linux they are two variables anyway. expect(await agentLine(`cloudflare_account_id=${A} wrangler deploy`, root, cfDeps("win32", whoamiSees(B)), { CLOUDFLARE_ACCOUNT_ID: A })).toEqual(allowed); expect(await agentLine(`cloudflare_account_id=${B} wrangler deploy`, root, cfDeps("linux", whoamiSees(B)), { CLOUDFLARE_ACCOUNT_ID: A })).toEqual(allowed); From 9b58b6d8d5a5ffedbf85128e1820b2e2d4e8c011 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:37:37 -0400 Subject: [PATCH 04/21] CONTRIBUTING: what cacheInputs().env must list, and Windows names (#119) Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 26584a1..c4ffb8f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -62,7 +62,10 @@ What to pin: a stable ID (subscription ID, account ID, project ref), never a dis `resolve` must return the identity *the specific command* would use, so flags such as `--profile` and environment variables count. When it can't tell, it returns an error, and cloudpin stops the command with that -reason. `cacheInputs` must list every variable and file that can change the answer of a CLI call that `resolve` makes. +reason. `cacheInputs` must list every variable and file that can change the answer of a CLI call that `resolve` makes, +and its `env` every variable that can change `resolve`'s own answer: when a command line sets one of those from +something cloudpin can't read in advance (`$(...)`), the command is stopped. On Windows, `resolve` gets every +variable name in upper case, as the CLIs read them there. ## Pull requests From 3f884f3a25582f74e1b4aa32a673bfe0a8a32680 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:39:03 -0400 Subject: [PATCH 05/21] Windows: the identity cache gets the folded names too (#119) The cache wrapper computed its watched files from the unfolded environment, so with a lowercase azure_config_dir it watched the default ~/.azure folder, and an `az account set` in the named folder kept reusing the old identity for up to five minutes. It now gets the same folded environment as resolve. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 8 ++++---- test/guard-env-case.test.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/guard.ts b/src/guard.ts index f2a3bb7..504a98c 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -156,17 +156,17 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { // Track whether the CLI itself is missing: then the command would fail on // its own, so there is no account to protect (DESIGN.md, edge cases). let cliMissing = false; - const inner = deps.wrapExec ? deps.wrapExec(provider, req.env, deps.exec) : deps.exec; + // On Windows the provider reads names the way the CLI does, case-insensitively (#119). + const folded = foldEnvNames(req.env, deps.platform ?? process.platform); + const inner = deps.wrapExec ? deps.wrapExec(provider, folded.env, deps.exec) : deps.exec; const exec: Exec = async (bin, args, env) => { const result = await inner(bin, args, env); if (result.notFound) cliMissing = true; return result; }; - // On Windows the provider reads names the way the CLI does, case-insensitively (#119). - const folded = foldEnvNames(req.env, deps.platform ?? process.platform); // 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 identityVars = provider.cacheInputs(folded.env).env; const unknown = Object.keys(folded.env).filter((k) => folded.env[k] === UNKNOWN_VALUE && envNameMatches(identityVars, k)); if (unknown.length > 0) { return { diff --git a/test/guard-env-case.test.ts b/test/guard-env-case.test.ts index a819dd8..fa98f20 100644 --- a/test/guard-env-case.test.ts +++ b/test/guard-env-case.test.ts @@ -5,6 +5,7 @@ import { cachedExec } from "../src/cache.js"; import type { FoundConfig } from "../src/config.js"; import { guard, type GuardDeps, type Verdict } from "../src/guard.js"; import { aws } from "../src/providers/aws.js"; +import { azure } from "../src/providers/azure.js"; import { cloudflare } from "../src/providers/cloudflare.js"; import { github } from "../src/providers/github.js"; import { envFor, findInvocations } from "../src/shellwords.js"; @@ -162,4 +163,30 @@ describe("guard: lowercase variables of other providers on Windows (#119)", () = // On linux aws ignores aws_profile, so the cached identity is the right one. expect(await run("linux")).toEqual([allowed, allowed]); }); + + it("Azure: the identity cache watches the folder a lowercase azure_config_dir names, on win32", async () => { + const run = async (platform: NodeJS.Platform) => { + const cacheDir = tempDir("cloudpin-env-case-cache-"); + const configDir = folder({ "azureProfile.json": "{}" }); + let active = "11111111-1111-1111-1111-111111111111"; + const exec: Exec = async () => ({ code: 0, stdout: JSON.stringify({ id: active, tenantId: "t" }), stderr: "" }); + const deps: GuardDeps = { + providers: [azure], + exec, + findConfig: () => ({ path: "/repo/.cloudpin.yml", pins: { azure: { subscription: "11111111-1111-1111-1111-111111111111" } } }), + wrapExec: (p: ProviderDef, env, inner) => cachedExec(inner, p.cacheInputs(env), { cacheDir, env: {} }), + platform, + }; + const env = { HOME: tempDir("cloudpin-env-case-home-"), azure_config_dir: configDir }; + const first = await shell(env, "/repo", deps, "az", ["vm", "list"]); + // `az account set` in that folder rewrites azureProfile.json. + active = "22222222-2222-2222-2222-222222222222"; + writeFileSync(join(configDir, "azureProfile.json"), '{"subscriptions": []}'); + const second = await shell(env, "/repo", deps, "az", ["vm", "list"]); + return [first, second]; + }; + expect(await run("win32")).toEqual([allowed, expect.objectContaining(mismatch("22222222"))]); + // On linux az ignores azure_config_dir, and the default folder didn't change. + expect(await run("linux")).toEqual([allowed, allowed]); + }); }); From 5c3d3a51685c763f78ca2b5b1abf429ac452fcf3 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:22:35 -0400 Subject: [PATCH 06/21] Test: Windows case and folder gaps, failing before the fix (#136) New tests for what the Windows variable-name fold (#119) left out, each with a Linux control and the platform given to guard, so both sides run on any OS: - the user's lowercase cloudpin_env and cloudpin_branch pick the environment in the agent hook on win32, while the agent's own assignment, export or unset of them in any spelling still doesn't count; - a lowercase cloudpin_confirm or cloudpin_skip in a terminal on win32; - a lowercase aws_config_file next to an alias file makes a protected environment ask on win32; - a lowercase name inside Wrangler's .env folds by the given platform; - the identity cache watches Wrangler's login file where Wrangler writes it on each platform (%APPDATA%\xdg.config on Windows). Before the fix, 11 fail and the 2 Linux-only tests pass. Co-Authored-By: Claude Opus 5.5 --- test/windows-case-gaps.test.ts | 193 +++++++++++++++++++++++++++++ test/wrangler-login-folder.test.ts | 65 ++++++++++ 2 files changed, 258 insertions(+) create mode 100644 test/windows-case-gaps.test.ts create mode 100644 test/wrangler-login-folder.test.ts diff --git a/test/windows-case-gaps.test.ts b/test/windows-case-gaps.test.ts new file mode 100644 index 0000000..809f2be --- /dev/null +++ b/test/windows-case-gaps.test.ts @@ -0,0 +1,193 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { findConfig, type FoundConfig } from "../src/config.js"; +import { guard, type GuardDeps } from "../src/guard.js"; +import { AGENTS, runHook } from "../src/hooks/agents.js"; +import { cloudflare } from "../src/providers/cloudflare.js"; +import type { Exec, ProviderDef } from "../src/types.js"; +import { tempDir } from "./tmp.js"; + +// #136: what #119's fold of Windows variable names left out. Windows names are +// case-insensitive, so a user's `cloudpin_env` is CLOUDPIN_ENV there; on Linux +// they are different variables. Every test sets the platform guard is given, +// so both sides run on any OS. + +function folder(files: Record = {}) { + const root = tempDir("cloudpin-case-gaps-"); + for (const [name, content] of Object.entries(files)) { + mkdirSync(join(root, name, ".."), { recursive: true }); + writeFileSync(join(root, name), content); + } + return root; +} + +// A fake gh, always on the pinned user, so only the environment decides. +const gh: ProviderDef<"github"> = { + name: "github", + bins: ["gh"], + isExempt: (args) => args[0] === "auth", + resolve: async () => ({ kind: "identity", identity: { user: "octocat" }, source: "t" }), + 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: [] }), +}; + +// Production is listed first and protected; staging is not. +const ENVIRONMENTS = [ + "environments:", + " production:", + " protected: true", + " github:", + " user: octocat", + " staging:", + " github:", + " user: octocat", + "branches:", + " release: staging", + "", +].join("\n"); + +describe("hook: cloudpin's own variables are case-insensitive on Windows only (#136)", () => { + const root = folder({ ".cloudpin.yml": ENVIRONMENTS }); + const deps = (platform: NodeJS.Platform): GuardDeps => ({ + providers: [gh as ProviderDef], + exec: async () => ({ code: 0, stdout: "", stderr: "" }), + findConfig, + platform, + }); + /** The hook's decision for an agent's command: "ask" on production, "none" on staging. */ + const decision = async (command: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => { + const stdin = JSON.stringify({ hook_event_name: "PreToolUse", tool_name: "Bash", tool_input: { command }, cwd: root }); + const out = await runHook(AGENTS.claude, stdin, deps(platform), env); + return out === "" ? "none" : JSON.parse(out).hookSpecificOutput.permissionDecision; + }; + + it("honours the user's lowercase cloudpin_env on win32, and not on linux", async () => { + expect(await decision("gh pr merge 12", { cloudpin_env: "staging" }, "win32")).toBe("none"); + expect(await decision("gh pr merge 12", { Cloudpin_Env: "staging" }, "win32")).toBe("none"); + expect(await decision("gh pr merge 12", { cloudpin_env: "staging" }, "linux")).toBe("ask"); + // Controls: the exact name counts everywhere, and no variable means production. + expect(await decision("gh pr merge 12", { CLOUDPIN_ENV: "staging" }, "linux")).toBe("none"); + expect(await decision("gh pr merge 12", {}, "win32")).toBe("ask"); + }); + + it("honours the user's lowercase cloudpin_branch on win32, and not on linux", async () => { + expect(await decision("gh pr merge 12", { cloudpin_branch: "release" }, "win32")).toBe("none"); + expect(await decision("gh pr merge 12", { cloudpin_branch: "release" }, "linux")).toBe("ask"); + expect(await decision("gh pr merge 12", { CLOUDPIN_BRANCH: "release" }, "linux")).toBe("none"); + }); + + it("still ignores the agent's own cloudpin_env or cloudpin_branch in any spelling on win32", async () => { + for (const line of [ + "CLOUDPIN_ENV=staging gh pr merge 12", + "cloudpin_env=staging gh pr merge 12", + "Cloudpin_Env=staging gh pr merge 12", + "export cloudpin_env=staging; gh pr merge 12", + "$env:cloudpin_env = 'staging'; gh pr merge 12", + "cloudpin_branch=release gh pr merge 12", + ]) { + expect(await decision(line, {}, "win32"), line).toBe("ask"); + expect(await decision(line, {}, "linux"), line).toBe("ask"); + } + }); + + it("doesn't let the agent override or unset the user's variable in another spelling on win32", async () => { + // The user chose production; the agent's lowercase assignment must not win. + expect(await decision("cloudpin_env=staging gh pr merge 12", { CLOUDPIN_ENV: "production" }, "win32")).toBe("ask"); + // A plain assignment counts only for a name already exported: here, the user's own. + expect(await decision("cloudpin_env=staging; gh pr merge 12", { cloudpin_env: "production" }, "win32")).toBe("ask"); + // The user chose staging; the agent can't unset it to fall back to production. + expect(await decision("unset cloudpin_env; gh pr merge 12", { cloudpin_env: "staging" }, "win32")).toBe("none"); + expect(await decision("unset CLOUDPIN_ENV; gh pr merge 12", { cloudpin_env: "staging" }, "win32")).toBe("none"); + }); +}); + +describe("guard: CLOUDPIN_CONFIRM and CLOUDPIN_SKIP are case-insensitive on Windows only (#136)", () => { + const production: FoundConfig = { + path: "/repo/.cloudpin.yml", + pins: { github: { user: "octocat" } }, + environment: { name: "production", protected: true, source: "first listed" }, + }; + const deps = (platform: NodeJS.Platform): GuardDeps => ({ + providers: [gh as ProviderDef], + exec: async () => ({ code: 0, stdout: "", stderr: "" }), + findConfig: () => production, + platform, + }); + const run = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform, mode: "shell" | "agent" = "shell") => + guard({ bin: "gh", args: ["pr", "merge", "12"], env, cwd: "/repo", mode }, deps(platform)); + + it("confirms with a lowercase cloudpin_confirm in a terminal on win32, and not on linux", async () => { + expect(await run({ cloudpin_confirm: "production" }, "win32")).toEqual({ action: "allow", reason: "confirmed" }); + expect(await run({ cloudpin_confirm: "production" }, "linux")).toMatchObject({ action: "confirm" }); + expect(await run({ CLOUDPIN_CONFIRM: "production" }, "linux")).toEqual({ action: "allow", reason: "confirmed" }); + // An agent can't confirm, in any spelling. + expect(await run({ cloudpin_confirm: "production" }, "win32", "agent")).toMatchObject({ action: "confirm" }); + }); + + it("skips with a lowercase cloudpin_skip in a terminal on win32, and not on linux", async () => { + expect(await run({ cloudpin_skip: "1" }, "win32")).toEqual({ action: "allow", reason: "skipped" }); + expect(await run({ cloudpin_skip: "1" }, "linux")).toMatchObject({ action: "confirm" }); + expect(await run({ cloudpin_skip: "1" }, "win32", "agent")).toMatchObject({ action: "confirm" }); + }); +}); + +describe("guard: the read-only check sees a lowercase aws_config_file on Windows only (#136)", () => { + // An AWS CLI alias file next to the config file means no aws command is + // trusted as read-only (readonly.ts awsAliasFiles), so a protected + // environment asks even for `aws s3 ls`. + const fakeAws: ProviderDef<"aws"> = { + name: "aws", + bins: ["aws"], + isExempt: () => false, + resolve: async () => ({ kind: "identity", identity: { account: "111122223333" }, source: "t" }), + compare: (pin, id) => (pin.account === id.account ? [] : ["account differs"]), + switchHint: () => "aws sso login", + statusCommand: "aws sts get-caller-identity", + cacheInputs: () => ({ env: [], files: [], dirs: [] }), + }; + const production: FoundConfig = { + path: "/repo/.cloudpin.yml", + pins: { aws: { account: "111122223333" } }, + environment: { name: "production", protected: true, source: "first listed" }, + }; + const awsDir = folder({ "cli/alias": "[toplevel]\n" }); + const home = folder(); + const run = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => + guard( + { bin: "aws", args: ["s3", "ls"], env: { HOME: home, ...env }, cwd: "/repo", mode: "agent" }, + { providers: [fakeAws as ProviderDef], exec: async () => ({ code: 0, stdout: "", stderr: "" }), findConfig: () => production, platform }, + ); + + it("asks on win32 when a lowercase aws_config_file points next to an alias file", async () => { + expect(await run({ aws_config_file: join(awsDir, "config") }, "win32")).toMatchObject({ action: "confirm" }); + // linux: a different variable, so the AWS CLI reads its default config and `s3 ls` only reads. + expect(await run({ aws_config_file: join(awsDir, "config") }, "linux")).toEqual({ action: "allow", reason: "match" }); + // Control: the exact name asks everywhere. + expect(await run({ AWS_CONFIG_FILE: join(awsDir, "config") }, "linux")).toMatchObject({ action: "confirm" }); + }); +}); + +describe("guard: names inside Wrangler's .env files fold by the platform guard is given (#136)", () => { + const A = "0123456789abcdef0123456789abcdef"; + const B = "fedcba9876543210fedcba9876543210"; + const whoamiSeesA: Exec = async () => ({ code: 0, stdout: JSON.stringify({ loggedIn: true, accounts: [{ id: A }] }), stderr: "" }); + const pinnedToA: FoundConfig = { path: "/repo/.cloudpin.yml", pins: { cloudflare: { account: A } } }; + const run = (cwd: string, platform: NodeJS.Platform) => + guard( + { bin: "wrangler", args: ["deploy"], env: {}, cwd, mode: "agent" }, + { providers: [cloudflare], exec: whoamiSeesA, findConfig: () => pinnedToA, platform }, + ); + + it("reads a lowercase cloudflare_account_id in .env on win32, and not on linux", async () => { + const root = folder({ ".env": `cloudflare_account_id=${B}\n` }); + expect(await run(root, "win32")).toMatchObject({ action: "block", problems: [expect.stringContaining(B)] }); + // Wrangler folds .env names on Windows only (config/dot-env.ts), so on linux whoami decides. + expect(await run(root, "linux")).toEqual({ action: "allow", reason: "match" }); + // Control: the exact name counts everywhere. + const exact = folder({ ".env": `CLOUDFLARE_ACCOUNT_ID=${B}\n` }); + expect(await run(exact, "linux")).toMatchObject({ action: "block", problems: [expect.stringContaining(B)] }); + }); +}); diff --git a/test/wrangler-login-folder.test.ts b/test/wrangler-login-folder.test.ts new file mode 100644 index 0000000..fa21d0f --- /dev/null +++ b/test/wrangler-login-folder.test.ts @@ -0,0 +1,65 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { cachedExec } from "../src/cache.js"; +import { cloudflare } from "../src/providers/cloudflare.js"; +import type { Exec } from "../src/types.js"; +import { tempDir } from "./tmp.js"; + +// #136: the identity cache keys `wrangler whoami` on Wrangler's login file, +// /config/default.toml. The folder is ~/.wrangler if it +// exists, else the XDG one, which differs per platform (workers-sdk +// packages/workers-utils/src/global-wrangler-config-path.ts getGlobalConfigPath +// and xdg-app-paths.ts xdgConfig): XDG_CONFIG_HOME when non-empty, else +// %APPDATA%\xdg.config on Windows, ~/Library/Preferences on macOS, ~/.config elsewhere. + +const login = (dir: string) => join(dir, ".wrangler", "config", "default.toml"); +const files = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => cloudflare.cacheInputs(env, platform).files; + +describe("cloudflare.cacheInputs: the login file Wrangler writes, per platform (#136)", () => { + const home = "/home/u"; + + it("watches %APPDATA%\\xdg.config\\.wrangler on win32", () => { + const appData = join("C:", "Users", "u", "AppData", "Roaming"); + expect(files({ USERPROFILE: home, APPDATA: appData }, "win32")).toEqual([login(home), login(join(appData, "xdg.config"))]); + // Without APPDATA, Wrangler falls back to \AppData\Roaming (windowsAppData). + expect(files({ USERPROFILE: home }, "win32")).toEqual([login(home), login(join(home, "AppData", "Roaming", "xdg.config"))]); + }); + + it("watches ~/Library/Preferences/.wrangler on darwin", () => { + expect(files({ HOME: home }, "darwin")).toEqual([login(home), login(join(home, "Library", "Preferences"))]); + }); + + it("watches ~/.config/.wrangler on linux", () => { + expect(files({ HOME: home }, "linux")).toEqual([login(home), login(join(home, ".config"))]); + }); + + it("follows a non-empty XDG_CONFIG_HOME on every platform, and ignores an empty one", () => { + const xdg = "/x/config"; + for (const platform of ["win32", "darwin", "linux"] as const) { + expect(files({ HOME: home, APPDATA: "/a", XDG_CONFIG_HOME: xdg }, platform), platform).toEqual([login(home), login(xdg)]); + } + // xdg-portable's valOrPath: an empty value counts as unset. + expect(files({ HOME: home, XDG_CONFIG_HOME: "" }, "linux")).toEqual([login(home), login(join(home, ".config"))]); + }); +}); + +describe("identity cache: a re-login in the Windows folder drops the cached whoami (#136)", () => { + it("asks whoami again after %APPDATA%\\xdg.config\\.wrangler\\config\\default.toml changes", async () => { + const appData = tempDir("cloudpin-wrangler-appdata-"); + const env = { USERPROFILE: tempDir("cloudpin-wrangler-home-"), APPDATA: appData }; + const file = login(join(appData, "xdg.config")); + mkdirSync(join(file, ".."), { recursive: true }); + writeFileSync(file, "oauth_token = \"first\"\n"); + let calls = 0; + const exec: Exec = async () => ({ code: 0, stdout: String(++calls), stderr: "" }); + const cached = cachedExec(exec, cloudflare.cacheInputs(env, "win32"), { cacheDir: tempDir("cloudpin-wrangler-cache-"), env: {} }); + await cached("wrangler", ["whoami", "--json"], env); + await cached("wrangler", ["whoami", "--json"], env); + expect(calls).toBe(1); + // `wrangler login` rewrites the file, with a different size, so the stamp changes. + writeFileSync(file, "oauth_token = \"second, longer\"\n"); + await cached("wrangler", ["whoami", "--json"], env); + expect(calls).toBe(2); + }); +}); From f78f566b57ffa6c0b0d53a2cbd1a423dc0e28ea6 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:24:13 -0400 Subject: [PATCH 07/21] Windows: CLOUDPIN_CONFIRM and CLOUDPIN_SKIP read case-insensitively (#136) guard folds the command's variable names before it reads CLOUDPIN_SKIP and CLOUDPIN_CONFIRM, so a user's lowercase cloudpin_confirm or cloudpin_skip counts in a terminal on Windows, as Windows itself reads them. Both still count in shell mode only, so an agent can't use either in any spelling. Linux and macOS are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/guard.ts b/src/guard.ts index 504a98c..c624540 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -145,7 +145,11 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { if (!pin) return { action: "allow", reason: "not-pinned" }; trace.pin = pin as Record; if (provider.isExempt(req.args, name)) return { action: "allow", reason: "exempt" }; - if (req.mode === "shell" && req.env.CLOUDPIN_SKIP === "1") return { action: "allow", reason: "skipped" }; + // On Windows the provider reads names the way the CLI does, case-insensitively + // (#119), and so does cloudpin for its own variables (#136). + const platform = deps.platform ?? process.platform; + const folded = foldEnvNames(req.env, platform); + if (req.mode === "shell" && folded.env.CLOUDPIN_SKIP === "1") return { action: "allow", reason: "skipped" }; const base = { action: "block" as const, @@ -156,8 +160,6 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { // Track whether the CLI itself is missing: then the command would fail on // its own, so there is no account to protect (DESIGN.md, edge cases). let cliMissing = false; - // On Windows the provider reads names the way the CLI does, case-insensitively (#119). - const folded = foldEnvNames(req.env, deps.platform ?? process.platform); const inner = deps.wrapExec ? deps.wrapExec(provider, folded.env, deps.exec) : deps.exec; const exec: Exec = async (bin, args, env) => { const result = await inner(bin, args, env); @@ -206,7 +208,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { const p = provider as ProviderDef; const problems = p.compare(pin as never, res.identity); if (problems.length > 0) return { ...base, problems, fix: p.switchHint(pin as never) }; - return protectedEnvironment(req, provider.name, config, trace); + return protectedEnvironment(req, folded.env, provider.name, config, trace); } } } @@ -214,14 +216,15 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { /** * The account is right; on a protected environment a command that may change * something still needs the user's yes (issue #12). Only a human can give it - * ahead of time, with CLOUDPIN_CONFIRM=. + * ahead of time, with CLOUDPIN_CONFIRM=. `env` is the command's + * environment with Windows names folded (#136). */ -function protectedEnvironment(req: GuardRequest, provider: Provider, config: FoundConfig, trace: Trace): Verdict { +function protectedEnvironment(req: GuardRequest, env: NodeJS.ProcessEnv, provider: Provider, config: FoundConfig, trace: Trace): Verdict { const environment = config.environment; if (!environment?.protected) return { action: "allow", reason: "match" }; trace.readOnly = isReadOnly(provider, req.args, req.env, config.readOnly ?? {}, commandName(req.bin)); if (trace.readOnly) return { action: "allow", reason: "match" }; - if (req.mode === "shell" && req.env.CLOUDPIN_CONFIRM === environment.name) { + if (req.mode === "shell" && env.CLOUDPIN_CONFIRM === environment.name) { return { action: "allow", reason: "confirmed" }; } return { action: "confirm", provider, configPath: config.path, environment }; From 60ffb08db27f85cf1f82da186d42aa128086cc15 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:24:32 -0400 Subject: [PATCH 08/21] Windows: the read-only check gets the folded variable names (#136) isReadOnly decides whether a protected environment asks for confirmation, and for aws it looks for an alias file next to AWS_CONFIG_FILE. It got the unfolded environment, so on Windows a lowercase aws_config_file was missed and an aliased `aws s3 ls` skipped the question. guard now passes the environment with Windows names folded. Linux and macOS are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/guard.ts b/src/guard.ts index c624540..a4e4332 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -222,7 +222,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { function protectedEnvironment(req: GuardRequest, env: NodeJS.ProcessEnv, provider: Provider, config: FoundConfig, trace: Trace): Verdict { const environment = config.environment; if (!environment?.protected) return { action: "allow", reason: "match" }; - trace.readOnly = isReadOnly(provider, req.args, req.env, config.readOnly ?? {}, commandName(req.bin)); + trace.readOnly = isReadOnly(provider, req.args, env, config.readOnly ?? {}, commandName(req.bin)); if (trace.readOnly) return { action: "allow", reason: "match" }; if (req.mode === "shell" && env.CLOUDPIN_CONFIRM === environment.name) { return { action: "allow", reason: "confirmed" }; From 546f1d253327279c963d2bbe294e49ffcec20320 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:25:04 -0400 Subject: [PATCH 09/21] Providers get the platform guard is given (#136) The command context now carries the platform the command runs on, and guard passes its own. The Cloudflare provider hands it to wranglerDotenv, which folds the names inside .env files on Windows only, as Wrangler does; it used to fold by process.platform, so the Windows behaviour was tested only on a Windows run and the Linux one only elsewhere. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 2 +- src/providers/cloudflare.ts | 4 ++-- src/types.ts | 2 ++ 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/guard.ts b/src/guard.ts index a4e4332..0f25b08 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -193,7 +193,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { } // Other unknown values don't decide the account; the CLI's identity check runs without them. const env = Object.fromEntries(Object.entries(folded.env).filter(([, v]) => v !== UNKNOWN_VALUE)); - const res = await provider.resolve({ args: req.args, env, cwd: req.cwd, bin: name }, exec); + const res = await provider.resolve({ args: req.args, env, cwd: req.cwd, bin: name, platform }, exec); trace.resolution = res; if (res.kind === "error" && cliMissing) return { action: "allow", reason: "not-installed" }; switch (res.kind) { diff --git a/src/providers/cloudflare.ts b/src/providers/cloudflare.ts index 16e35b3..75145da 100644 --- a/src/providers/cloudflare.ts +++ b/src/providers/cloudflare.ts @@ -195,14 +195,14 @@ export const cloudflare: ProviderDef<"cloudflare"> = { return false; }, - async resolve({ args, env: commandEnv, cwd }, exec): Promise { + async resolve({ args, env: commandEnv, cwd, platform }, exec): Promise { if (hasAnyFlag(args, ["--temporary"])) { return { kind: "error", message: "deploy --temporary uploads to a temporary preview account, not a pinned one" }; } const start = resolvePath(cwd, flagValue(args, ["--cwd"]) ?? "."); // Wrangler adds what its .env files set to its own environment (#116); from // here on, env is that environment, and whoami below is asked with it. - const dotenv = wranglerDotenv(args, commandEnv, start); + const dotenv = wranglerDotenv(args, commandEnv, start, platform); if ("error" in dotenv) return { kind: "error", message: dotenv.error }; const { env } = dotenv; const inFile = (name: string) => (dotenv.from[name] ? ` in ${dotenv.from[name]}` : ""); diff --git a/src/types.ts b/src/types.ts index 47059de..8c55d53 100644 --- a/src/types.ts +++ b/src/types.ts @@ -21,6 +21,8 @@ export interface CommandContext { cwd: string; /** The command name, e.g. "kubectl" or "helm", for providers that guard several CLIs. */ bin?: string; + /** The platform the command runs on; providers read it, never process.platform, so tests can set it (#136). */ + platform?: NodeJS.Platform; } /** The identity a command will act as, keyed like the provider's pin section. */ From 40869eda535ab34da12b3c64aeedbc6bbf5a683d Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:25:30 -0400 Subject: [PATCH 10/21] Wrangler: the identity cache watches the login file on Windows and macOS (#136) The cached `wrangler whoami` is keyed on Wrangler's login file, but cloudpin watched ~/.config/.wrangler on every platform. Wrangler's XDG config folder is %APPDATA%\xdg.config on Windows and ~/Library/Preferences on macOS (workers-utils getGlobalConfigPath and xdgConfig, unchanged from wrangler@4.151.3 to the current main), so a re-login there didn't drop the 5-minute cache. cacheInputs now takes the platform (guard passes its own; it defaults to this process's), and an empty XDG_CONFIG_HOME counts as unset, as in Wrangler. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 2 +- src/providers/cloudflare.ts | 18 +++++++++++++++--- src/types.ts | 4 ++-- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/guard.ts b/src/guard.ts index 0f25b08..b051266 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -168,7 +168,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { }; // 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(folded.env).env; + const identityVars = provider.cacheInputs(folded.env, platform).env; const unknown = Object.keys(folded.env).filter((k) => folded.env[k] === UNKNOWN_VALUE && envNameMatches(identityVars, k)); if (unknown.length > 0) { return { diff --git a/src/providers/cloudflare.ts b/src/providers/cloudflare.ts index 75145da..7c7262a 100644 --- a/src/providers/cloudflare.ts +++ b/src/providers/cloudflare.ts @@ -170,10 +170,22 @@ export const cloudflare: ProviderDef<"cloudflare"> = { bins: ["wrangler", "wrangler2", "cf-wrangler"], statusCommand: "wrangler whoami", - cacheInputs(env) { + cacheInputs(env, platform = process.platform) { // Only `wrangler whoami` is cached. Its OAuth login lives in the global - // Wrangler config folder (~/.wrangler if it exists, else the XDG one). - const dirs = [join(home(env), ".wrangler"), join(env.XDG_CONFIG_HOME ?? join(home(env), ".config"), ".wrangler")]; + // Wrangler config folder: ~/.wrangler if it exists, else the XDG one, which is + // XDG_CONFIG_HOME when non-empty, else %APPDATA%\xdg.config on Windows, + // ~/Library/Preferences on macOS and ~/.config elsewhere (#136; workers-sdk + // wrangler@4.151.3, packages/workers-utils/src/global-wrangler-config-path.ts + // getGlobalConfigPath and xdg-app-paths.ts xdgConfig and windowsAppData). + const h = home(env); + const xdg = + env.XDG_CONFIG_HOME || + (platform === "win32" + ? join(env.APPDATA || join(h, "AppData", "Roaming"), "xdg.config") + : platform === "darwin" + ? join(h, "Library", "Preferences") + : join(h, ".config")); + const dirs = [join(h, ".wrangler"), join(xdg, ".wrangler")]; return { // Every variable that decides the account, not only whoami's credentials: // guard blocks when a command line sets one to a value it can't know (#86, diff --git a/src/types.ts b/src/types.ts index 8c55d53..2d160eb 100644 --- a/src/types.ts +++ b/src/types.ts @@ -56,8 +56,8 @@ export interface ProviderDef

{ switchHint(pin: NonNullable): string; /** Command that shows the CLI's login state, suggested when resolving fails. */ statusCommand: string; - /** Environment variables and files that decide the identity (cache invalidation). */ - cacheInputs(env: NodeJS.ProcessEnv): CacheInputs; + /** Environment variables and files that decide the identity (cache invalidation), on `platform` (default: this process's). */ + cacheInputs(env: NodeJS.ProcessEnv, platform?: NodeJS.Platform): CacheInputs; } /** From 2306d4d05cc76585c4ac40f26bb5155c571a8cd1 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:25:53 -0400 Subject: [PATCH 11/21] CONTRIBUTING: providers read the platform they are given (#136) Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c4ffb8f..e2f9c65 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -65,7 +65,8 @@ environment variables count. When it can't tell, it returns an error, and cloudp reason. `cacheInputs` must list every variable and file that can change the answer of a CLI call that `resolve` makes, and its `env` every variable that can change `resolve`'s own answer: when a command line sets one of those from something cloudpin can't read in advance (`$(...)`), the command is stopped. On Windows, `resolve` gets every -variable name in upper case, as the CLIs read them there. +variable name in upper case, as the CLIs read them there. Both get the platform the command runs on (`platform` in +`resolve`'s context, `cacheInputs`' second argument): read it there, never `process.platform`, so tests can set it. ## Pull requests From 53223072ab4dea09eecc92f811822fb5a8152f6b Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:29:29 -0400 Subject: [PATCH 12/21] Move envFor and the user-only variables into user-env.ts (#136) A pure move, no behaviour change: USER_ONLY_VARS and envFor, with their doc comments, go verbatim from src/shellwords.ts (over its size limit) into the new src/user-env.ts, which imports only the Invocation type from shellwords.ts. The importers (hooks/agents.ts, explain.ts and three tests) import envFor from user-env.ts directly; nothing else used it. Co-Authored-By: Claude Opus 5.5 --- src/explain.ts | 3 ++- src/hooks/agents.ts | 3 ++- src/shellwords.ts | 21 --------------------- src/user-env.ts | 22 ++++++++++++++++++++++ test/cloudflare-account-vars.test.ts | 3 ++- test/guard-env-case.test.ts | 3 ++- test/shellwords.test.ts | 3 ++- 7 files changed, 32 insertions(+), 26 deletions(-) create mode 100644 src/user-env.ts diff --git a/src/explain.ts b/src/explain.ts index 3fd8ce2..8e6cdf8 100644 --- a/src/explain.ts +++ b/src/explain.ts @@ -2,7 +2,8 @@ import type { ActiveEnvironment } from "./config.js"; import { commandName, guard, type GuardDeps, type Trace, type Verdict } from "./guard.js"; import { AGENTS, type AgentName } from "./hooks/agents.js"; import { home } from "./paths.js"; -import { envFor, findInvocations, type Invocation } from "./shellwords.js"; +import { findInvocations, type Invocation } from "./shellwords.js"; +import { envFor } from "./user-env.js"; import { describe } from "./status.js"; import type { Identity } from "./types.js"; diff --git a/src/hooks/agents.ts b/src/hooks/agents.ts index a04da66..55e86a6 100644 --- a/src/hooks/agents.ts +++ b/src/hooks/agents.ts @@ -1,7 +1,8 @@ import { resolve } from "node:path"; import { formatBlock, formatConfirm } from "../format.js"; import { commandName, guard, type GuardDeps } from "../guard.js"; -import { envFor, findInvocations } from "../shellwords.js"; +import { findInvocations } from "../shellwords.js"; +import { envFor } from "../user-env.js"; /** How one agent hands a shell command to its hook and reads the answer. */ export interface AgentHook { diff --git a/src/shellwords.ts b/src/shellwords.ts index 9800c21..ba252ec 100644 --- a/src/shellwords.ts +++ b/src/shellwords.ts @@ -22,27 +22,6 @@ export interface Invocation { 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_BRANCH", "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. diff --git a/src/user-env.ts b/src/user-env.ts new file mode 100644 index 0000000..e443de4 --- /dev/null +++ b/src/user-env.ts @@ -0,0 +1,22 @@ +import type { Invocation } from "./shellwords.js"; + +/** + * 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_BRANCH", "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; +} diff --git a/test/cloudflare-account-vars.test.ts b/test/cloudflare-account-vars.test.ts index 52cf05a..d8ea2b1 100644 --- a/test/cloudflare-account-vars.test.ts +++ b/test/cloudflare-account-vars.test.ts @@ -4,7 +4,8 @@ import { describe, expect, it } from "vitest"; import type { FoundConfig } from "../src/config.js"; import { guard, type Verdict } from "../src/guard.js"; import { cloudflare } from "../src/providers/cloudflare.js"; -import { envFor, findInvocations } from "../src/shellwords.js"; +import { findInvocations } from "../src/shellwords.js"; +import { envFor } from "../src/user-env.js"; import type { Exec } from "../src/types.js"; import { tempDir } from "./tmp.js"; diff --git a/test/guard-env-case.test.ts b/test/guard-env-case.test.ts index fa98f20..4a25efc 100644 --- a/test/guard-env-case.test.ts +++ b/test/guard-env-case.test.ts @@ -8,7 +8,8 @@ import { aws } from "../src/providers/aws.js"; import { azure } from "../src/providers/azure.js"; import { cloudflare } from "../src/providers/cloudflare.js"; import { github } from "../src/providers/github.js"; -import { envFor, findInvocations } from "../src/shellwords.js"; +import { findInvocations } from "../src/shellwords.js"; +import { envFor } from "../src/user-env.js"; import type { Exec, ProviderDef } from "../src/types.js"; import { tempDir } from "./tmp.js"; diff --git a/test/shellwords.test.ts b/test/shellwords.test.ts index 26b1f61..d897082 100644 --- a/test/shellwords.test.ts +++ b/test/shellwords.test.ts @@ -1,7 +1,8 @@ import { resolve } from "node:path"; import { describe, expect, it } from "vitest"; import { commandName } from "../src/guard.js"; -import { envFor, findInvocations, UNKNOWN_VALUE } from "../src/shellwords.js"; +import { findInvocations, UNKNOWN_VALUE } from "../src/shellwords.js"; +import { envFor } from "../src/user-env.js"; const GUARDED = ["az", "aws", "gcloud", "vercel", "gh"]; const find = (cmd: string) => findInvocations(cmd, GUARDED); From 2c4e82aa5d9591ae779b6158a9af7b07fad1466c Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:30:22 -0400 Subject: [PATCH 13/21] Windows: CLOUDPIN_ENV and CLOUDPIN_BRANCH read case-insensitively, agents still can't set them (#136) guard folds the command's variable names before findConfig, so a user's lowercase cloudpin_env or cloudpin_branch picks the environment in the agent hook on Windows, as the real process reads it there. In the same change envFor's user-only check folds the names on Windows, so an agent's inline, exported, plain or unset cloudpin_env (any spelling) is still ignored, as CLOUDPIN_ENV=... is today. The hook and explain pass the platform guard is given. Linux and macOS are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/explain.ts | 2 +- src/guard.ts | 11 ++++++----- src/hooks/agents.ts | 2 +- src/user-env.ts | 12 +++++++++--- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/explain.ts b/src/explain.ts index 8e6cdf8..2992ddf 100644 --- a/src/explain.ts +++ b/src/explain.ts @@ -112,7 +112,7 @@ export async function explain(command: string | string[], opts: ExplainOptions, } const cwd = call.cwd ?? opts.cwd; const trace: 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 verdict = await guard({ bin: call.bin, args: call.args, env: envFor(opts.env, call, { agent: opts.mode === "agent", platform: deps.platform }), 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 b051266..063e9d3 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -124,10 +124,15 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { const provider = deps.providers.find((p) => p.bins.includes(name)); if (!provider) return { action: "allow", reason: "not-guarded" }; trace.provider = provider.name; + // On Windows the provider reads names the way the CLI does, case-insensitively + // (#119), and so does cloudpin for its own variables, CLOUDPIN_ENV included + // (#136; envFor keeps an agent from setting those in any spelling). + const platform = deps.platform ?? process.platform; + const folded = foldEnvNames(req.env, platform); let config: FoundConfig | null; try { - config = deps.findConfig(req.cwd, req.env); + config = deps.findConfig(req.cwd, folded.env); } catch (err) { // A broken pin file must not silently switch protection off. Exempt // commands (login, whoami, help, ...) never act on an account, and are @@ -145,10 +150,6 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { if (!pin) return { action: "allow", reason: "not-pinned" }; trace.pin = pin as Record; if (provider.isExempt(req.args, name)) return { action: "allow", reason: "exempt" }; - // On Windows the provider reads names the way the CLI does, case-insensitively - // (#119), and so does cloudpin for its own variables (#136). - const platform = deps.platform ?? process.platform; - const folded = foldEnvNames(req.env, platform); if (req.mode === "shell" && folded.env.CLOUDPIN_SKIP === "1") return { action: "allow", reason: "skipped" }; const base = { diff --git a/src/hooks/agents.ts b/src/hooks/agents.ts index 55e86a6..3d67fb1 100644 --- a/src/hooks/agents.ts +++ b/src/hooks/agents.ts @@ -239,7 +239,7 @@ async function checkCommand( { bin: inv.bin, args: inv.args, - env: envFor(env, inv, { agent: true }), + env: envFor(env, inv, { agent: true, platform: deps.platform }), cwd: inv.cwd ?? call.cwd, mode: "agent", }, diff --git a/src/user-env.ts b/src/user-env.ts index e443de4..5fb7809 100644 --- a/src/user-env.ts +++ b/src/user-env.ts @@ -10,10 +10,16 @@ export const USER_ONLY_VARS = ["CLOUDPIN_ENV", "CLOUDPIN_BRANCH", "CLOUDPIN_CONF * 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. + * set or unset the user-only variables, in any spelling on Windows (`platform`, + * default this process's), where guard reads `cloudpin_env` as CLOUDPIN_ENV (#136). */ -export function envFor(base: NodeJS.ProcessEnv, inv: Invocation, opts: { agent?: boolean } = {}): NodeJS.ProcessEnv { - const allowed = (name: string) => !(opts.agent && USER_ONLY_VARS.includes(name)); +export function envFor( + base: NodeJS.ProcessEnv, + inv: Invocation, + opts: { agent?: boolean; platform?: NodeJS.Platform } = {}, +): NodeJS.ProcessEnv { + const win = (opts.platform ?? process.platform) === "win32"; + const allowed = (name: string) => !(opts.agent && USER_ONLY_VARS.includes(win ? name.toUpperCase() : 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]; From 3b41717c9d0010ee423890dd7fccf1d37d82ea9c Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:34:01 -0400 Subject: [PATCH 14/21] AGENTS: list src/user-env.ts in the source layout (#136) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index 58a26b9..68facce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,7 @@ Run the type-check and the tests as separate commands and read each exit code. | `src/mcp.ts`, `src/mcp-tools.ts` | `cloudpin mcp`: the JSON-RPC stdio server, and its two read-only tools | | `plugin/`, `.claude-plugin/marketplace.json` | The Claude Code plugin (hook, MCP server, skill) and its marketplace | | `src/shellwords.ts` | Finds CLI calls inside a full shell command line | +| `src/user-env.ts` | The environment a found call runs with; an agent can't set cloudpin's own variables | | `src/hooks/agents.ts` | One adapter per AI agent's hook format | | `src/cache.ts` | The identity cache | | `src/update.ts`, `src/install-method.ts` | The daily update notice, and how cloudpin was installed (npm, Homebrew, Scoop, pnpm, Volta, Yarn, Bun) so upgrade advice names the right command | From 92f6460cc12c810b2f212e90e9732548e815feb5 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:55:40 -0500 Subject: [PATCH 15/21] Test: the Wrangler login folder test checks main's cache inputs (#136) Main's cacheInputs (#103) watches each Wrangler folder's config/ directory, which holds every profile's login, and its profile bindings file, rather than config/default.toml alone, so the test expects those per platform. On win32 Wrangler's home is USERPROFILE (os.homedir), so the XDG_CONFIG_HOME case sets it next to HOME. The folders expected per platform are unchanged. Still failing: cacheInputs ignores the platform it is given. Co-Authored-By: Claude Opus 5.5 --- test/wrangler-login-folder.test.ts | 37 +++++++++++++++++++----------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/test/wrangler-login-folder.test.ts b/test/wrangler-login-folder.test.ts index fa21d0f..066dd28 100644 --- a/test/wrangler-login-folder.test.ts +++ b/test/wrangler-login-folder.test.ts @@ -6,41 +6,52 @@ import { cloudflare } from "../src/providers/cloudflare.js"; import type { Exec } from "../src/types.js"; import { tempDir } from "./tmp.js"; -// #136: the identity cache keys `wrangler whoami` on Wrangler's login file, -// /config/default.toml. The folder is ~/.wrangler if it -// exists, else the XDG one, which differs per platform (workers-sdk +// #136: the identity cache keys `wrangler whoami` on Wrangler's logins, in +// /config (default.toml, one file per profile) and the +// profile bindings next to it (#103). The folder is ~/.wrangler if it exists, +// else the XDG one, which differs per platform (workers-sdk // packages/workers-utils/src/global-wrangler-config-path.ts getGlobalConfigPath // and xdg-app-paths.ts xdgConfig): XDG_CONFIG_HOME when non-empty, else // %APPDATA%\xdg.config on Windows, ~/Library/Preferences on macOS, ~/.config elsewhere. -const login = (dir: string) => join(dir, ".wrangler", "config", "default.toml"); -const files = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => cloudflare.cacheInputs(env, platform).files; +/** What the cache watches for the Wrangler folders under `bases` (legacy home first, then XDG). */ +const watching = (...bases: string[]) => ({ + files: bases.map((b) => join(b, ".wrangler", "profiles", "directory-bindings.json")), + dirs: bases.map((b) => join(b, ".wrangler", "config")), +}); +const watched = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => { + const { files, dirs } = cloudflare.cacheInputs(env, platform); + return { files, dirs }; +}; +const loginFile = (base: string) => join(base, ".wrangler", "config", "default.toml"); -describe("cloudflare.cacheInputs: the login file Wrangler writes, per platform (#136)", () => { +describe("cloudflare.cacheInputs: the login folder Wrangler writes, per platform (#136)", () => { const home = "/home/u"; it("watches %APPDATA%\\xdg.config\\.wrangler on win32", () => { const appData = join("C:", "Users", "u", "AppData", "Roaming"); - expect(files({ USERPROFILE: home, APPDATA: appData }, "win32")).toEqual([login(home), login(join(appData, "xdg.config"))]); + expect(watched({ USERPROFILE: home, APPDATA: appData }, "win32")).toEqual(watching(home, join(appData, "xdg.config"))); // Without APPDATA, Wrangler falls back to \AppData\Roaming (windowsAppData). - expect(files({ USERPROFILE: home }, "win32")).toEqual([login(home), login(join(home, "AppData", "Roaming", "xdg.config"))]); + expect(watched({ USERPROFILE: home }, "win32")).toEqual(watching(home, join(home, "AppData", "Roaming", "xdg.config"))); }); it("watches ~/Library/Preferences/.wrangler on darwin", () => { - expect(files({ HOME: home }, "darwin")).toEqual([login(home), login(join(home, "Library", "Preferences"))]); + expect(watched({ HOME: home }, "darwin")).toEqual(watching(home, join(home, "Library", "Preferences"))); }); it("watches ~/.config/.wrangler on linux", () => { - expect(files({ HOME: home }, "linux")).toEqual([login(home), login(join(home, ".config"))]); + expect(watched({ HOME: home }, "linux")).toEqual(watching(home, join(home, ".config"))); }); it("follows a non-empty XDG_CONFIG_HOME on every platform, and ignores an empty one", () => { const xdg = "/x/config"; for (const platform of ["win32", "darwin", "linux"] as const) { - expect(files({ HOME: home, APPDATA: "/a", XDG_CONFIG_HOME: xdg }, platform), platform).toEqual([login(home), login(xdg)]); + // Wrangler's home is USERPROFILE on Windows and HOME elsewhere (os.homedir), so both are set. + const env = { HOME: home, USERPROFILE: home, APPDATA: "/a", XDG_CONFIG_HOME: xdg }; + expect(watched(env, platform), platform).toEqual(watching(home, xdg)); } // xdg-portable's valOrPath: an empty value counts as unset. - expect(files({ HOME: home, XDG_CONFIG_HOME: "" }, "linux")).toEqual([login(home), login(join(home, ".config"))]); + expect(watched({ HOME: home, XDG_CONFIG_HOME: "" }, "linux")).toEqual(watching(home, join(home, ".config"))); }); }); @@ -48,7 +59,7 @@ describe("identity cache: a re-login in the Windows folder drops the cached whoa it("asks whoami again after %APPDATA%\\xdg.config\\.wrangler\\config\\default.toml changes", async () => { const appData = tempDir("cloudpin-wrangler-appdata-"); const env = { USERPROFILE: tempDir("cloudpin-wrangler-home-"), APPDATA: appData }; - const file = login(join(appData, "xdg.config")); + const file = loginFile(join(appData, "xdg.config")); mkdirSync(join(file, ".."), { recursive: true }); writeFileSync(file, "oauth_token = \"first\"\n"); let calls = 0; From f8b5b369d758cd63169065e4a31158219c7e5220 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:56:13 -0500 Subject: [PATCH 16/21] Windows: CLOUDPIN_CONFIRM and CLOUDPIN_SKIP read case-insensitively (#136) guard folds the command's variable names once, before anything reads them, and the terminal's CLOUDPIN_SKIP and CLOUDPIN_CONFIRM come from that folded environment, so a lowercase cloudpin_confirm counts on win32 as it does for the shell. Agents still can't confirm or skip in any spelling; other platforms are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/guard.ts b/src/guard.ts index 37beff9..f624878 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -125,6 +125,10 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { const provider = deps.providers.find((p) => p.bins.includes(name)); if (!provider) return { action: "allow", reason: "not-guarded" }; trace.provider = provider.name; + // On Windows the provider reads names the way the CLI does, case-insensitively + // (#119), and so does cloudpin for its own variables (#136). + const platform = deps.platform ?? process.platform; + const folded = foldEnvNames(req.env, platform); let config: FoundConfig | null; try { @@ -146,7 +150,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { if (!pin) return { action: "allow", reason: "not-pinned" }; trace.pin = pin as Record; if (provider.isExempt(req.args, name)) return { action: "allow", reason: "exempt" }; - if (req.mode === "shell" && req.env.CLOUDPIN_SKIP === "1") return { action: "allow", reason: "skipped" }; + if (req.mode === "shell" && folded.env.CLOUDPIN_SKIP === "1") return { action: "allow", reason: "skipped" }; const base = { action: "block" as const, @@ -157,8 +161,6 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { // Track whether the CLI itself is missing: then the command would fail on // its own, so there is no account to protect (DESIGN.md, edge cases). let cliMissing = false; - // On Windows the provider reads names the way the CLI does, case-insensitively (#119). - const folded = foldEnvNames(req.env, deps.platform ?? process.platform); const inner = deps.wrapExec ? deps.wrapExec(provider, folded.env, deps.exec) : deps.exec; const exec: Exec = async (bin, args, env) => { const result = await inner(bin, args, env); @@ -215,7 +217,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { const p = provider as ProviderDef; const problems = p.compare(pin as never, res.identity); if (problems.length > 0) return { ...base, problems, fix: p.switchHint(pin as never) }; - return protectedEnvironment(req, provider.name, config, trace); + return protectedEnvironment(req, folded.env, provider.name, config, trace); } } } @@ -223,14 +225,15 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { /** * The account is right; on a protected environment a command that may change * something still needs the user's yes (issue #12). Only a human can give it - * ahead of time, with CLOUDPIN_CONFIRM=. + * ahead of time, with CLOUDPIN_CONFIRM=. `env` is the command's + * environment with Windows names folded (#136). */ -function protectedEnvironment(req: GuardRequest, provider: Provider, config: FoundConfig, trace: Trace): Verdict { +function protectedEnvironment(req: GuardRequest, env: NodeJS.ProcessEnv, provider: Provider, config: FoundConfig, trace: Trace): Verdict { const environment = config.environment; if (!environment?.protected) return { action: "allow", reason: "match" }; trace.readOnly = isReadOnly(provider, req.args, req.env, config.readOnly ?? {}, commandName(req.bin)); if (trace.readOnly) return { action: "allow", reason: "match" }; - if (req.mode === "shell" && req.env.CLOUDPIN_CONFIRM === environment.name) { + if (req.mode === "shell" && env.CLOUDPIN_CONFIRM === environment.name) { return { action: "allow", reason: "confirmed" }; } return { action: "confirm", provider, configPath: config.path, environment }; From e1055f021c2ac9234e13798b53a5427211a26b1b Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:56:27 -0500 Subject: [PATCH 17/21] Windows: the read-only check gets the folded variable names (#136) isReadOnly reads AWS_CONFIG_FILE to find an AWS CLI alias file; on win32 a lowercase aws_config_file is the same variable for the AWS CLI, so a protected `aws s3 ls` next to an alias file now asks there too. Co-Authored-By: Claude Opus 5.5 --- src/guard.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/guard.ts b/src/guard.ts index f624878..c21b224 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -231,7 +231,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { function protectedEnvironment(req: GuardRequest, env: NodeJS.ProcessEnv, provider: Provider, config: FoundConfig, trace: Trace): Verdict { const environment = config.environment; if (!environment?.protected) return { action: "allow", reason: "match" }; - trace.readOnly = isReadOnly(provider, req.args, req.env, config.readOnly ?? {}, commandName(req.bin)); + trace.readOnly = isReadOnly(provider, req.args, env, config.readOnly ?? {}, commandName(req.bin)); if (trace.readOnly) return { action: "allow", reason: "match" }; if (req.mode === "shell" && env.CLOUDPIN_CONFIRM === environment.name) { return { action: "allow", reason: "confirmed" }; From f9aa4037ea9092cd10ef6c056c04ca95375c209d Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:57:01 -0500 Subject: [PATCH 18/21] Providers get the platform guard is given (#136) CommandContext carries the platform the command runs on and cacheInputs takes it as a second argument, both from guard's deps.platform, so a provider's per-platform behaviour can be tested on any host. Without it they default to this process's platform, as before. CONTRIBUTING says to read it there, never process.platform. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 3 ++- src/guard.ts | 4 ++-- src/types.ts | 6 ++++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e6be6b3..dbe39bd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -67,7 +67,8 @@ environment variables count. When it can't tell, it returns an error, and cloudp reason. `cacheInputs` must list every variable and file that can change the answer of a CLI call that `resolve` makes, and its `env` every variable that can change `resolve`'s own answer: when a command line sets one of those from something cloudpin can't read in advance (`$(...)`), the command is stopped. On Windows, `resolve` gets every -variable name in upper case, as the CLIs read them there. +variable name in upper case, as the CLIs read them there. Both get the platform the command runs on (`platform` in +`resolve`'s context, `cacheInputs`' second argument): read it there, never `process.platform`, so tests can set it. ## Pull requests diff --git a/src/guard.ts b/src/guard.ts index c21b224..a7c52ad 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -172,7 +172,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { if (dynamic) return { ...base, uncertain: true, problems: [dynamic.problem], fix: dynamic.fix }; // 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(folded.env).env; + const identityVars = provider.cacheInputs(folded.env, platform).env; const unknown = Object.keys(folded.env).filter((k) => folded.env[k] === UNKNOWN_VALUE && envNameMatches(identityVars, k)); if (unknown.length > 0) { return { @@ -197,7 +197,7 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { } // Other unknown values don't decide the account; the CLI's identity check runs without them. const env = Object.fromEntries(Object.entries(folded.env).filter(([, v]) => v !== UNKNOWN_VALUE)); - const res = await provider.resolve({ args: req.args, env, cwd: req.cwd, bin: name }, exec); + const res = await provider.resolve({ args: req.args, env, cwd: req.cwd, bin: name, platform }, exec); trace.resolution = res; if (res.kind === "error" && cliMissing) return { action: "allow", reason: "not-installed" }; switch (res.kind) { diff --git a/src/types.ts b/src/types.ts index de28606..645f146 100644 --- a/src/types.ts +++ b/src/types.ts @@ -21,6 +21,8 @@ export interface CommandContext { cwd: string; /** The command name, e.g. "kubectl" or "helm", for providers that guard several CLIs. */ bin?: string; + /** The platform the command runs on; providers read it, never process.platform, so tests can set it (#136). */ + platform?: NodeJS.Platform; } /** The identity a command will act as, keyed like the provider's pin section. */ @@ -63,8 +65,8 @@ export interface ProviderDef

{ switchHint(pin: NonNullable): string; /** Command that shows the CLI's login state, suggested when resolving fails. */ statusCommand: string; - /** Environment variables and files that decide the identity (cache invalidation). */ - cacheInputs(env: NodeJS.ProcessEnv): CacheInputs; + /** Environment variables and files that decide the identity (cache invalidation), on `platform` (default: this process's). */ + cacheInputs(env: NodeJS.ProcessEnv, platform?: NodeJS.Platform): CacheInputs; /** * Every flag `resolve` reads (the ones that pick the account, project, scope, context, ...). A value * cloudpin can't read in advance in one of them means it can't tell which account the command uses, From 900776ea4901854ce7b28363466108c4985a367d Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:57:25 -0500 Subject: [PATCH 19/21] Wrangler: its folders and .env names follow the platform guard is given (#136) wranglerConfigDirs (#103) already knows Wrangler's per-platform login folder: %APPDATA%\xdg.config\.wrangler on Windows, ~/Library/Preferences/.wrangler on macOS, ~/.config/.wrangler elsewhere, XDG_CONFIG_HOME first when non-empty. cacheInputs and resolve now hand it, the .env reader and the profile lookup the platform they are given instead of this process's, so the identity cache and .env name folding are right for the command and testable on any host. Co-Authored-By: Claude Opus 5.5 --- src/providers/cloudflare.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/providers/cloudflare.ts b/src/providers/cloudflare.ts index e48aff4..3cafaf7 100644 --- a/src/providers/cloudflare.ts +++ b/src/providers/cloudflare.ts @@ -185,19 +185,20 @@ export const cloudflare: ProviderDef<"cloudflare"> = { // The flags resolve reads (#160). targetFlags: ["--cwd", "--config", "-c", "--env", "-e", "--env-file", "--envFile", "--profile"], - cacheInputs(env) { + cacheInputs(env, platform) { // Only `wrangler whoami` is cached. Its OAuth logins live in the global // Wrangler config folder (~/.wrangler if it exists, else the XDG one): // config/.toml or .enc, and the folder bindings that pick one. // WRANGLER_API_ENVIRONMENT renames the default profile's file. XDG_CONFIG_HOME - // and APPDATA move the folder, also when a .env file sets them. + // and APPDATA move the folder, also when a .env file sets them. The XDG + // folder differs per platform (wranglerConfigDirs), so it is `platform`'s (#136). return { // Every variable that decides the account, not only whoami's credentials: // guard blocks when a command line sets one to a value it can't know (#86, // #119). DOTENV_KEY picks a .env.vault over .env (wrangler-dotenv.ts). Names // whoami ignores can only make its cache miss, never hit wrongly. env: [...DOTENV_VARS, "DOTENV_KEY"], - ...profileCacheInputs(env), + ...profileCacheInputs(env, platform), }; }, @@ -214,14 +215,14 @@ export const cloudflare: ProviderDef<"cloudflare"> = { return false; }, - async resolve({ args, env: commandEnv, cwd }, exec): Promise { + async resolve({ args, env: commandEnv, cwd, platform }, exec): Promise { if (hasAnyFlag(args, ["--temporary"])) { return { kind: "error", message: "deploy --temporary uploads to a temporary preview account, not a pinned one" }; } const start = resolvePath(cwd, flagValue(args, ["--cwd"]) ?? "."); // Wrangler adds what its .env files set to its own environment (#116); from // here on, env is that environment, and whoami below is asked with it. - const dotenv = wranglerDotenv(args, commandEnv, start); + const dotenv = wranglerDotenv(args, commandEnv, start, platform); if ("error" in dotenv) return { kind: "error", message: dotenv.error }; const { env } = dotenv; const inFile = (name: string) => (dotenv.from[name] ? ` in ${dotenv.from[name]}` : ""); @@ -229,10 +230,10 @@ export const cloudflare: ProviderDef<"cloudflare"> = { const configPath = given !== undefined ? resolvePath(start, given) : CONFIG_NAMES.map((n) => findUp(n, start)).find(Boolean); const envName = flagValue(args, ["--env", "-e"]) ?? (env.CLOUDFLARE_ENV || undefined); // The folder whose binding picks the profile: the --config file's, else the command's. - const folder = bindingFolder(start); + const folder = bindingFolder(start, platform); const lookup = given !== undefined ? dirname(resolvePath(folder, given)) : folder; let known: ReturnType | undefined; - const profile = () => (known ??= commandProfile(args, env, lookup)); + const profile = () => (known ??= commandProfile(args, env, lookup, platform)); if (configPath !== undefined) { if (!existsSync(configPath)) return { kind: "error", message: `the Wrangler config file ${basename(configPath)} does not exist` }; From 931f27ff03d3232037483fbcbbc785913a971c2b Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:57:55 -0500 Subject: [PATCH 20/21] Windows: CLOUDPIN_ENV and CLOUDPIN_BRANCH read case-insensitively, agents still can't set them (#136) guard hands findConfig the folded environment, so a user's lowercase cloudpin_env or cloudpin_branch picks the environment on win32, as Windows reads it. In the same change envFor's user-only check folds the name on win32 (the platform guard is given, passed by the hook and explain), so an agent's cloudpin_env=..., export, $env: assignment or unset, in any spelling, still doesn't count and can't undo the user's choice. Linux and macOS are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/explain.ts | 2 +- src/guard.ts | 5 +++-- src/hooks/agents.ts | 2 +- src/user-env.ts | 13 ++++++++++--- 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/explain.ts b/src/explain.ts index 5dcea45..472d4ce 100644 --- a/src/explain.ts +++ b/src/explain.ts @@ -114,7 +114,7 @@ export async function explain(command: string | string[], opts: ExplainOptions, } const cwd = call.cwd ?? opts.cwd; const trace: 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 verdict = await guard({ bin: call.bin, args: call.args, env: envFor(opts.env, call, { agent: opts.mode === "agent", platform: deps.platform }), 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 a7c52ad..06bfe67 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -126,13 +126,14 @@ export async function guard(req: GuardRequest, deps: GuardDeps, trace: Trace = { if (!provider) return { action: "allow", reason: "not-guarded" }; trace.provider = provider.name; // On Windows the provider reads names the way the CLI does, case-insensitively - // (#119), and so does cloudpin for its own variables (#136). + // (#119), and so does cloudpin for its own variables, CLOUDPIN_ENV included + // (#136; envFor keeps an agent from setting those in any spelling). const platform = deps.platform ?? process.platform; const folded = foldEnvNames(req.env, platform); let config: FoundConfig | null; try { - config = deps.findConfig(req.cwd, req.env); + config = deps.findConfig(req.cwd, folded.env); } catch (err) { // A broken pin file must not silently switch protection off. Exempt // commands (login, whoami, help, ...) never act on an account, and are diff --git a/src/hooks/agents.ts b/src/hooks/agents.ts index 73c1bfa..1d34130 100644 --- a/src/hooks/agents.ts +++ b/src/hooks/agents.ts @@ -272,7 +272,7 @@ async function checkCommand( { bin: inv.bin, args: inv.args, - env: envFor(env, inv, { agent: true }), + env: envFor(env, inv, { agent: true, platform: deps.platform }), cwd: inv.cwd ?? call.cwd, mode: "agent", }, diff --git a/src/user-env.ts b/src/user-env.ts index 692d1f7..3e1d102 100644 --- a/src/user-env.ts +++ b/src/user-env.ts @@ -15,10 +15,17 @@ const KEPT_BY_ENV_I = ["PATH", "SYSTEMROOT", "WINDIR"]; * The environment a call runs with: `base` (the environment the line starts * in, or almost nothing after `env -i`), 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. + * With `agent`, the line can't set or unset the user-only variables, in any + * spelling on Windows (`platform`, default this process's), where guard reads + * `cloudpin_env` as CLOUDPIN_ENV (#136). */ -export function envFor(base: NodeJS.ProcessEnv, inv: Invocation, opts: { agent?: boolean } = {}): NodeJS.ProcessEnv { - const allowed = (name: string) => !(opts.agent && USER_ONLY_VARS.includes(name)); +export function envFor( + base: NodeJS.ProcessEnv, + inv: Invocation, + opts: { agent?: boolean; platform?: NodeJS.Platform } = {}, +): NodeJS.ProcessEnv { + const win = (opts.platform ?? process.platform) === "win32"; + const allowed = (name: string) => !(opts.agent && USER_ONLY_VARS.includes(win ? name.toUpperCase() : name)); const kept = ([name]: [string, unknown]) => !allowed(name) || KEPT_BY_ENV_I.includes(name.toUpperCase()); const out: NodeJS.ProcessEnv = inv.clearEnv ? Object.fromEntries(Object.entries(base).filter(kept)) : { ...base }; for (const [name, value] of Object.entries(inv.ifExported ?? {})) if (name in base && allowed(name)) out[name] = value; From 5b386942a1039cf9081e6980522071a45ad9a9e9 Mon Sep 17 00:00:00 2001 From: Alvaro Reis <133926455+paureis@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:00:14 -0500 Subject: [PATCH 21/21] CHANGELOG and ROADMAP: Windows case gaps (#136) Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ ROADMAP.md | 2 ++ 2 files changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 277395c..291ef26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ Versions 0.1.0 to 0.4.2 (2026-10-08 to 2026-10-10) are in [docs/changelog-0.x.md - Windows: variable names are read without regard to case, as Windows and the CLIs do (#119), so a lowercase `gh_token`, `aws_profile`, `azure_config_dir` or `cloudflare_account_id` counts. One variable set in two spellings to different values stops as "can't tell". +- Windows: cloudpin's own variables are read without regard to case too (#136): a lowercase `cloudpin_env`, + `cloudpin_branch`, `cloudpin_confirm` or `cloudpin_skip` you set counts, and an agent still can't set or unset + `CLOUDPIN_ENV` or `CLOUDPIN_BRANCH` in any spelling. The read-only check on a protected environment reads folded + names, so a lowercase `aws_config_file` counts there as well. ## [1.2.1] - 2026-10-29 diff --git a/ROADMAP.md b/ROADMAP.md index 956cc1f..62b54c0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -37,6 +37,8 @@ issues it ships. Open an [issue](https://github.com/paureis/cloudpin/issues) to the way each CLI does, in every provider. - **Cloudflare account variables** ([#119](https://github.com/paureis/cloudpin/issues/119)): done. An account variable whose value cloudpin can't know blocks, and Windows reads variable names without regard to case. +- **Windows case gaps** ([#136](https://github.com/paureis/cloudpin/issues/136)): done. cloudpin's own variables + and the read-only check read names without regard to case (Wrangler's per-platform login folder came with #103). ## Ideas (not scheduled yet)