Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/prefer-env-account-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"@cloudflare/workers-auth": minor
"@cloudflare/vite-plugin": patch
"@cloudflare/vitest-plugin": patch
"wrangler": patch
---

Prefer `CLOUDFLARE_ACCOUNT_ID` to the configured `accountId` in the Cloudflare Vite and Vitest plugins and in `cf dev`

When resolving an account for remote bindings, and for tunnels in the Vite plugin, the plugins and `cf dev` used the `accountId` in `cloudflare.config.ts` even when `CLOUDFLARE_ACCOUNT_ID` was set to a different account. This was the reverse of other `cf` commands, where the environment variable takes precedence. `CLOUDFLARE_ACCOUNT_ID` now takes precedence there too.

`wrangler` commands, and Vitest plugin projects that use a Wrangler configuration file, are unchanged: the configured `account_id` still takes precedence.
7 changes: 7 additions & 0 deletions .changeset/vite-reload-cloudflare-env.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@cloudflare/vite-plugin": patch
---

Apply changes to `CLOUDFLARE_*` variables in `.env` files when Vite restarts

The plugin copies `CLOUDFLARE_*` variables from `.env` files into `process.env`. When a `.env` file changes, Vite restarts in the same process. The values copied before the restart then took precedence over the edited file, as if they had been set in the shell. A variable changed in or removed from a `.env` file now takes effect after the restart. Variables set in the shell still take precedence.
52 changes: 52 additions & 0 deletions packages/vite-plugin-cloudflare/src/__tests__/auth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,32 @@ test("plugin contexts share auth until the Vite project is disposed", async ({
expect(createCfAuth).toHaveBeenCalledTimes(2);
});

test("plugin contexts create new auth when CLOUDFLARE_API_TOKEN changes", ({
expect,
onTestFinished,
}) => {
onTestFinished(() => {
vi.unstubAllEnvs();
});
vi.mocked(createCfAuth).mockClear();
const context = new PluginContext({
restartingDevServerCount: 0,
tunnelHostnames: new Set<string>(),
});
const logger = createLogger(createViteLogger("silent"));
vi.stubEnv("CLOUDFLARE_API_TOKEN", "first-token");
context.getCloudflareAuth("/project", logger);
// The same token reuses the auth
context.getCloudflareAuth("/project", logger);
Comment thread
petebacondarwin marked this conversation as resolved.
Resolved
expect(createCfAuth).toHaveBeenCalledOnce();

// The token changes, such as when Vite restarts after an edit to a `.env`
// file, so the new auth selects an account the new token can reach
vi.stubEnv("CLOUDFLARE_API_TOKEN", "second-token");
context.getCloudflareAuth("/project", logger);
expect(createCfAuth).toHaveBeenCalledTimes(2);
});

test("remote bindings auth uses the cf profile for the project", async ({
expect,
}) => {
Expand All @@ -84,6 +110,32 @@ test("remote bindings auth uses the cf profile for the project", async ({
).not.toBe(auth.key);
});

test("remote bindings auth changes its key when the account or token variable changes", ({
expect,
onTestFinished,
}) => {
onTestFinished(() => {
vi.unstubAllEnvs();
});
const logger = createLogger(createViteLogger("silent"));
const getAuth = () => createAuth("/project", logger);
const getKey = () =>
getRemoteBindingsAuth("/project", "account-id", getAuth).key;
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "first-account");
vi.stubEnv("CLOUDFLARE_API_TOKEN", "first-token");
const firstKey = getKey();

// Vite restarts with new values after an edit to a `.env` file
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "second-account");
const accountKey = getKey();
vi.stubEnv("CLOUDFLARE_API_TOKEN", "second-token");
const tokenKey = getKey();

expect(accountKey).not.toBe(firstKey);
expect(tokenKey).not.toBe(accountKey);
expect(tokenKey).not.toContain("second-token");
Comment thread
jamesopstad marked this conversation as resolved.
Resolved
});

test("account selection explains how to configure the account", async ({
expect,
}) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -853,6 +853,50 @@ describe("resolvePluginConfig", () => {
expect(result.localEnv.values.CLOUDFLARE_ACCOUNT_ID).toBeUndefined();
});

test("updates Cloudflare-prefixed values in process.env when the config is reloaded", async ({
expect,
}) => {
writeEntryConfig();
const envFile = path.join(root, ".env.production");
fs.writeFileSync(
envFile,
"CLOUDFLARE_ACCOUNT_ID=first-account\nCLOUDFLARE_API_TOKEN=first-token"
);
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined);
vi.stubEnv("CLOUDFLARE_API_TOKEN", undefined);
await resolvePluginConfig({}, { root }, buildEnv);

// Vite reloads the config in the same process when an environment file changes
fs.writeFileSync(envFile, "CLOUDFLARE_ACCOUNT_ID=second-account");
const result = await resolvePluginConfig({}, { root }, buildEnv);

expect(result.localEnv.values.CLOUDFLARE_ACCOUNT_ID).toBe("second-account");
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBe("second-account");
expect(process.env.CLOUDFLARE_API_TOKEN).toBeUndefined();
});

test("keeps Cloudflare-prefixed values not copied from environment files when the config is reloaded", async ({
expect,
}) => {
writeEntryConfig();
const envFile = path.join(root, ".env.production");
fs.writeFileSync(
envFile,
"CLOUDFLARE_ACCOUNT_ID=file-account\nCLOUDFLARE_API_TOKEN=file-token"
);
vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", "shell-account");
vi.stubEnv("CLOUDFLARE_API_TOKEN", undefined);
await resolvePluginConfig({}, { root }, buildEnv);

vi.stubEnv("CLOUDFLARE_API_TOKEN", "later-token");
fs.writeFileSync(envFile, "");
const result = await resolvePluginConfig({}, { root }, buildEnv);

expect(result.localEnv.values.CLOUDFLARE_ACCOUNT_ID).toBe("shell-account");
expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBe("shell-account");
expect(process.env.CLOUDFLARE_API_TOKEN).toBe("later-token");
});

test("rejects duplicate Vite environment names", async ({ expect }) => {
writeEntryConfig();
writeSource("src/aux.ts");
Expand Down
19 changes: 16 additions & 3 deletions packages/vite-plugin-cloudflare/src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { format } from "node:util";
import { inputPrompt } from "@cloudflare/cli-shared-helpers/interactive";
import {
Expand Down Expand Up @@ -90,8 +91,10 @@ export function createAuthForProfile(
/**
* Get the cf credentials for remote bindings sessions.
*
* The key includes the resolved profile so a profile change restarts the
* session with the newly selected credentials.
* The key includes the resolved profile, `CLOUDFLARE_ACCOUNT_ID` and
* `CLOUDFLARE_API_TOKEN`, so a change to any of them restarts the session with
* the new credentials. The variables can change when Vite restarts after an
* edit to a `.env` file. The key is hashed so it holds no secret.
*
* @param profileDir - Directory used to resolve the cf auth profile.
* @param accountId - The configured account ID, if any.
Expand All @@ -114,7 +117,17 @@ export function getRemoteBindingsAuth(
apiToken: auth.requireApiToken(),
};
},
key: JSON.stringify([profileDir, accountId, auth.getActiveProfile()]),
key: createHash("sha256")
.update(
JSON.stringify([
profileDir,
accountId,
process.env.CLOUDFLARE_ACCOUNT_ID,
process.env.CLOUDFLARE_API_TOKEN,
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
Comment thread
jamesopstad marked this conversation as resolved.
Resolved
auth.getActiveProfile(),
])
)
.digest("hex"),
};
}

Expand Down
25 changes: 21 additions & 4 deletions packages/vite-plugin-cloudflare/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,15 @@ export interface SharedContext {
/** Allowed hostnames for tunnel connections */
tunnelHostnames: Set<string>;
/** Auth instance shared by features within the same Vite project. */
auth?: CloudflareAuth;
auth?: {
instance: CloudflareAuth;
/**
* `CLOUDFLARE_API_TOKEN` when `instance` was created, to detect a change.
* `instance.getAPIToken()` can't, because it returns the current token,
* or the stored OAuth token when the variable isn't set.
*/
apiToken: string | undefined;
};
}

/** An explicitly typed additional module emitted by a Vite environment. */
Expand Down Expand Up @@ -67,10 +75,19 @@ export class PluginContext {

getCloudflareAuth(profileDir: string, logger: Logger): CloudflareAuth {
const profile = resolveAuthProfile(profileDir, logger);
if (this.#sharedContext.auth?.getActiveProfile() !== profile) {
this.#sharedContext.auth = createAuthForProfile(profile, logger);
// The token can change when Vite restarts after an edit to a `.env` file.
// The new token may not reach the account selected with the old one, so
// replace the auth instead of keeping its selection.
const apiToken = process.env.CLOUDFLARE_API_TOKEN;
let auth = this.#sharedContext.auth;
if (
auth?.instance.getActiveProfile() !== profile ||
auth.apiToken !== apiToken
) {
auth = { instance: createAuthForProfile(profile, logger), apiToken };
this.#sharedContext.auth = auth;
}
return this.#sharedContext.auth;
return auth.instance;
}

/** Creates a new Miniflare instance or updates the existing instance */
Expand Down
57 changes: 46 additions & 11 deletions packages/vite-plugin-cloudflare/src/plugin-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,51 @@ function resolveWorkerType(options: {
};
}

// `CLOUDFLARE_*` values copied from environment files into `process.env`, by
// name, so the next load can tell them apart from values set in the shell.
const copiedCloudflareEnv = new Map<string, string>();
Comment thread
jamesopstad marked this conversation as resolved.
Resolved

/**
* Load the environment files and copy their `CLOUDFLARE_*` values into
* `process.env`, where Cloudflare tooling reads them.
*
* Vite reloads the config in the same process when an environment file
* changes. `loadEnv` gives `process.env` precedence over the files, so values
* copied by the previous load are removed first. Otherwise a value removed from
* or changed in a file would keep its old value. A value that has since changed
* in `process.env` is left alone.
*
* TODO: Replace this process-global compatibility bridge by explicitly passing
* typed Cloudflare tool settings to the services that consume them.
*
* @param envDir - The resolved environment directory, or `false` to skip files.
* @param mode - The mode whose environment files are loaded, if any.
* @returns The loaded values and their sources.
*/
async function loadLocalEnv(
envDir: string | false,
mode?: string
): Promise<LoadedEnv> {
for (const [name, value] of copiedCloudflareEnv) {
if (process.env[name] === value) {
delete process.env[name];
}
}
copiedCloudflareEnv.clear();

const localEnv = await loadEnv(envDir, mode);
for (const [name, value] of Object.entries(localEnv.values)) {
if (
name.startsWith("CLOUDFLARE_") &&
localEnv.sources[name]?.type === "file"
) {
process.env[name] = value;
copiedCloudflareEnv.set(name, value);
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
}
}
return localEnv;
}

export async function resolvePluginConfig(
pluginConfig: PluginConfig,
userConfig: vite.UserConfig,
Expand All @@ -290,19 +335,9 @@ export async function resolvePluginConfig(
: undefined;
const localEnvMode = preview ? preview.rootConfig.buildContext.mode : mode;
const [localEnv, devVars] = await Promise.all([
loadEnv(envDir, localEnvMode),
loadLocalEnv(envDir, localEnvMode),
loadDevVars(envDir, localEnvMode),
]);
// TODO: Replace this process-global compatibility bridge by explicitly
// passing typed Cloudflare tool settings to the services that consume them.
Object.assign(
process.env,
Object.fromEntries(
Object.entries(localEnv.values).filter(([name]) =>
name.startsWith("CLOUDFLARE_")
)
)
);
const types = normalizeTypes(pluginConfig.types);
const shared = {
persistState: pluginConfig.persistState ?? true,
Expand Down
8 changes: 6 additions & 2 deletions packages/workers-auth/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,10 @@ Cloudflare CLI built on this package. It lives in `src/core/`:
credential storage, config cache (`@cloudflare/workers-utils`'
`createConfigCache`), account selection (`fetchInternalBase` with the token
the flow already holds), login / logout / refresh, and `requireAuth`. Imports
only `@cloudflare/workers-utils`.
only `@cloudflare/workers-utils`. The active account is the temporary
account, then `CLOUDFLARE_ACCOUNT_ID` and the configured `account_id`, then
the retained selection. The environment variable comes first unless the
descriptor sets `preferConfiguredAccountId`, as Wrangler's does.
- `types.ts` — `AuthContext` (the injected primitives: `logger`, optional
`temporaryAccountLogger` for temporary-account notices, `userAgent`, interactive
`prompt` / `select`, `isNoDefaultValueProvidedError`) and
Expand All @@ -114,7 +117,8 @@ Cloudflare CLI built on this package. It lives in `src/core/`:
`keyringServiceName`,
`clientId`, `consent`, `redirectUri`, `useDeviceFlowByDefault`,
`getConfigPath`, `fileFormat`,
`persistAccountSelection`, `accountCachePrefix`, `cacheNamespace`, `getConfigFileLabel`,
`persistAccountSelection`, `preferConfiguredAccountId`, `accountCachePrefix`,
`cacheNamespace`, `getConfigFileLabel`,
`getDefaultScopeKeys`, …).
- `file-storage.ts` (`createFileStorage(format, getPath)`), `auth-config-file.ts`
(`createAuthConfigFileHelpers({getConfigPath, format})`), `preferences.ts`
Expand Down
37 changes: 26 additions & 11 deletions packages/workers-auth/src/core/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ export function createCloudflareAuth(

const preferences = createPreferences(descriptor.getConfigPath);
const persistAccountSelection = descriptor.persistAccountSelection ?? false;
const preferConfiguredAccountId =
descriptor.preferConfiguredAccountId ?? false;

// The config cache is generic file-backed storage owned by
// `@cloudflare/workers-utils`; build our own instance bound to the injected
Expand Down Expand Up @@ -561,17 +563,32 @@ Alternatively, try running \`${descriptor.commands.login}\` to re-authenticate.`
return temporaryAccount.account.id;
}

if (config.account_id) {
return validateAccountId(
config.account_id,
`set in your ${descriptor.getConfigFileLabel()} file`
if (preferConfiguredAccountId) {
// The variable is validated, so it is read only when no account is
// configured. Otherwise an invalid value would fail commands that use
// their configured account.
return (
getConfiguredAccountId(config) ??
getAccountIdFromEnv() ??
resolveAccountSelection()?.id
);
}
const envAccountId = getAccountIdFromEnv();
if (envAccountId) {
return envAccountId;
}
return resolveAccountSelection()?.id;
return (
getAccountIdFromEnv() ??
Comment thread
jamesopstad marked this conversation as resolved.
Resolved
getConfiguredAccountId(config) ??
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
resolveAccountSelection()?.id
Comment thread
jamesopstad marked this conversation as resolved.
Resolved
);
}

function getConfiguredAccountId(config: {
account_id?: string;
}): string | undefined {
return config.account_id
? validateAccountId(
config.account_id,
`set in your ${descriptor.getConfigFileLabel()} file`
)
: undefined;
}

async function selectAccountId(config: RequireAuthConfig): Promise<string> {
Expand Down Expand Up @@ -624,8 +641,6 @@ ${accounts
async function getOrSelectAccountId(
config: RequireAuthConfig
): Promise<string> {
// TODO: v5 we should prioritise the env var instead of the config value here,
// for consistency with other env vars.
const activeAccountId = getActiveAccountId(config);
if (activeAccountId) {
return activeAccountId;
Expand Down
7 changes: 7 additions & 0 deletions packages/workers-auth/src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,13 @@ export interface CliDescriptor {
*/
persistAccountSelection?: boolean;

/**
* Whether a configured `account_id` takes precedence over
* `CLOUDFLARE_ACCOUNT_ID`. When disabled, the environment variable wins, as
* other `CLOUDFLARE_*` variables do. Defaults to `false`.
*/
preferConfiguredAccountId?: boolean;

/**
* Filename prefix for the cached account selection in the config cache
* (e.g. `"wrangler-account"` → `wrangler-account.json`). Always JSON.
Expand Down
3 changes: 3 additions & 0 deletions packages/workers-auth/src/wrangler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ export const WRANGLER_CLI: CliDescriptor = {
fileFormat: "toml",
// Preserve Wrangler's cross-invocation account selection.
persistAccountSelection: true,
// Preserve Wrangler's account order, where a configured `account_id`
// overrides `CLOUDFLARE_ACCOUNT_ID`.
preferConfiguredAccountId: true,
accountCachePrefix: "wrangler-account",
getConfigFileLabel: () => configFileName(undefined),
// A getter so any reassignment of the live `DefaultScopeKeys` binding is
Expand Down
Loading
Loading