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/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/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) 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 37beff9..06bfe67 100644 --- a/src/guard.ts +++ b/src/guard.ts @@ -125,10 +125,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 @@ -146,7 +151,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 +162,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); @@ -170,7 +173,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 { @@ -195,7 +198,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) { @@ -215,7 +218,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 +226,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)); + trace.readOnly = isReadOnly(provider, req.args, 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 }; 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/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` }; 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, 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; 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..066dd28 --- /dev/null +++ b/test/wrangler-login-folder.test.ts @@ -0,0 +1,76 @@ +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 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. + +/** 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 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(watched({ USERPROFILE: home, APPDATA: appData }, "win32")).toEqual(watching(home, join(appData, "xdg.config"))); + // Without APPDATA, Wrangler falls back to \AppData\Roaming (windowsAppData). + expect(watched({ USERPROFILE: home }, "win32")).toEqual(watching(home, join(home, "AppData", "Roaming", "xdg.config"))); + }); + + it("watches ~/Library/Preferences/.wrangler on darwin", () => { + expect(watched({ HOME: home }, "darwin")).toEqual(watching(home, join(home, "Library", "Preferences"))); + }); + + it("watches ~/.config/.wrangler on linux", () => { + 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) { + // 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(watched({ HOME: home, XDG_CONFIG_HOME: "" }, "linux")).toEqual(watching(home, 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 = loginFile(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); + }); +});