Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(secret-sync): fail instead of changing a cloudflare variable's type

DimitrisStaratzis907153324b85
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index d5fe3d959d..0490462591 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3520,12 +3520,12 @@ export const SecretSyncs = {
projectName: "The name of the Cloudflare Pages project to sync secrets to.",
environment: "The environment of the Cloudflare Pages project to sync secrets to.",
variableType:
- "The type of environment variable to sync secrets as: secret_text (default) or plain_text. Infisical only deletes variables of this type."
+ "The type of environment variable to sync secrets as: secret_text (default) or plain_text. If a secret already exists in the environment as the other type, the sync fails and nothing is changed. Infisical only deletes variables of this type."
},
CLOUDFLARE_WORKERS: {
scriptId: "The ID of the Cloudflare Workers script to sync secrets to.",
variableType:
- "The type of variable to sync secrets as: secret_text (the default for new syncs), plain_text or json. Infisical converts a secret or variable of the same name to this type, except that with syncNonSecretBindings on, existing plaintext and JSON variables keep their type. Infisical only deletes variables of this type. Syncs created before this option existed have no type and skip keys that already exist as plaintext or JSON variables."
+ "The type of variable to sync secrets as: secret_text (default), plain_text or json. If a secret already exists on the Worker as a different type, the sync fails and nothing is changed, except that with syncNonSecretBindings on, a secret_text sync updates existing plaintext and JSON variables as they are. Infisical only deletes variables of this type."
},
CLOUDFLARE_SECRETS_STORE: {
storeId: "The ID of the Cloudflare Secrets Store to sync secrets to.",
diff --git a/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.test.ts b/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.test.ts
index ba7796ef84..a8b2977990 100644
--- a/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.test.ts
+++ b/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.test.ts
@@ -71,4 +71,18 @@ describe("CloudflarePagesSyncFns", () => {
expect.anything()
);
});
+
+ it("fails before writing when a key exists as the other type", async () => {
+ get.mockResolvedValue({
+ data: {
+ result: { deployment_configs: { production: { env_vars: { API_KEY: { type: "secret_text", value: "" } } } } }
+ }
+ });
+
+ await expect(
+ CloudflarePagesSyncFns.syncSecrets(syncWith(CloudflarePagesVariableType.Text), payloadOf({ API_KEY: "key" }))
+ ).rejects.toThrow("already exist in the Cloudflare Pages environment as a different type: API_KEY (secret).");
+
+ expect(patch).not.toHaveBeenCalled();
+ });
});
diff --git a/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.ts b/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.ts
index 92ab9082cd..1c4e42efd5 100644
--- a/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.ts
+++ b/backend/src/services/secret-sync/cloudflare-pages/cloudflare-pages-fns.ts
@@ -1,5 +1,6 @@
import { request } from "@app/lib/config/request";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";
import { TSecretSyncPayload } from "@app/services/secret-sync/secret-sync-payload";
import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";
@@ -15,7 +16,6 @@ const getProjectEnvironmentSecrets = async (secretSync: TCloudflarePagesSyncWith
credentials: { apiToken, accountId }
}
} = secretSync;
- const { variableType = CloudflarePagesVariableType.Secret } = destinationConfig;
const secrets = (
await request.get<{
@@ -38,13 +38,12 @@ const getProjectEnvironmentSecrets = async (secretSync: TCloudflarePagesSyncWith
)
).data.result.deployment_configs[destinationConfig.environment].env_vars;
- // A sync only owns variables of the type it writes, so syncs of different types can share an environment.
- return Object.entries(secrets ?? {})
- .filter(([, envVar]) => envVar.type === variableType)
- .map(([key, envVar]) => ({
- key,
- value: envVar.value
- }));
+ return Object.entries(secrets ?? {}).map(([key, envVar]) => ({ key, type: envVar.type }));
+};
+
+const VARIABLE_TYPE_LABELS: Record<CloudflarePagesVariableType, string> = {
+ [CloudflarePagesVariableType.Secret]: "secret",
+ [CloudflarePagesVariableType.Text]: "text"
};
export const CloudflarePagesSyncFns = {
@@ -58,18 +57,36 @@ export const CloudflarePagesSyncFns = {
} = secretSync;
const { variableType = CloudflarePagesVariableType.Secret } = destinationConfig;
+ const existingSecrets = await getProjectEnvironmentSecrets(secretSync);
+
+ // Changing a variable's type would expose a secret's value or hide a readable one, so a sync never changes
+ // one; it fails before writing anything.
+ const secretMapKeys = new Set(Object.keys(secretMap));
+ const conflicts = existingSecrets.filter((secret) => secretMapKeys.has(secret.key) && secret.type !== variableType);
+ if (conflicts.length > 0) {
+ throw new SecretSyncError({
+ message: `The following secrets already exist in the Cloudflare Pages environment as a different type: ${conflicts
+ .map(({ key, type }) => `${key} (${VARIABLE_TYPE_LABELS[type]})`)
+ .join(
+ ", "
+ )}. Infisical doesn't change a variable's type, so nothing was synced. Delete them in Cloudflare or change the sync's variable type, then sync again.`,
+ shouldRetry: false
+ });
+ }
+
// Create/update secret entries
let secretEntries: [string, object | null][] = Object.entries(secretMap).map(([key, val]) => [
key,
{ type: variableType, value: val.value }
]);
- // Handle deletions if not disabled
+ // Handle deletions if not disabled. A sync only owns variables of its type, so syncs of different types can
+ // share an environment.
if (!secretSync.syncOptions.disableSecretDeletion) {
- const existingSecrets = await getProjectEnvironmentSecrets(secretSync);
const toDeleteKeys = existingSecrets
.filter(
(secret) =>
+ secret.type === variableType &&
matchesSchema(secret.key, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema) &&
!secretMap[secret.key]
)
@@ -111,11 +128,13 @@ export const CloudflarePagesSyncFns = {
credentials: { apiToken, accountId }
}
} = secretSync;
+ const { variableType = CloudflarePagesVariableType.Secret } = destinationConfig;
const secrets = await getProjectEnvironmentSecrets(secretSync);
const toDeleteKeys = secrets
.filter(
(secret) =>
+ secret.type === variableType &&
matchesSchema(secret.key, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema) &&
secret.key in secretMap
)
diff --git a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.test.ts b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.test.ts
index e0f6ff4782..866f016881 100644
--- a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.test.ts
+++ b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.test.ts
@@ -18,12 +18,12 @@ vi.mock("@app/lib/config/request", async (importOriginal) => ({
type TBinding = { type: string; name: string; text?: string; json?: unknown };
-const syncWith = (variableType?: CloudflareWorkersVariableType) =>
+const syncWith = (variableType?: CloudflareWorkersVariableType, syncOptions: Record<string, unknown> = {}) =>
({
destination: "cloudflare-workers",
destinationConfig: { scriptId: "my-worker", variableType },
environment: { slug: "prod" },
- syncOptions: { disableSecretDeletion: false },
+ syncOptions: { disableSecretDeletion: false, ...syncOptions },
connection: { credentials: { apiToken: "token", accountId: "account-id" } }
}) as unknown as TCloudflareWorkersSyncWithCredentials;
@@ -49,9 +49,9 @@ describe("CloudflareWorkersSyncFns", () => {
vi.clearAllMocks();
});
- it("writes text variables in one settings update, replacing a same-name secret and deleting only stale text variables", async () => {
+ it("writes text variables in one settings update and deletes only stale text variables", async () => {
stubWorker([
- { type: "secret_text", name: "API_KEY" },
+ { type: "plain_text", name: "API_KEY", text: "old" },
{ type: "plain_text", name: "STALE", text: "old" },
{ type: "json", name: "CONFIG", json: { a: 1 } },
{ type: "kv_namespace", name: "CACHE" }
@@ -95,30 +95,31 @@ describe("CloudflareWorkersSyncFns", () => {
expect(patch).not.toHaveBeenCalled();
});
- it("converts a same-name text variable into a secret when Secret is chosen", async () => {
- stubWorker([
- { type: "plain_text", name: "API_URL", text: "old" },
- { type: "kv_namespace", name: "CACHE" }
- ]);
+ it.each([
+ [CloudflareWorkersVariableType.Secret, { type: "json", name: "CONFIG", json: { a: 1 } }, "CONFIG (JSON)"],
+ [undefined, { type: "plain_text", name: "CONFIG", text: "old" }, "CONFIG (text)"],
+ [CloudflareWorkersVariableType.Text, { type: "secret_text", name: "CONFIG" }, "CONFIG (secret)"],
+ [CloudflareWorkersVariableType.Json, { type: "plain_text", name: "CONFIG", text: "{}" }, "CONFIG (text)"]
+ ])("fails a %s sync before writing when a key exists as another type", async (variableType, binding, listed) => {
+ stubWorker([binding]);
- await CloudflareWorkersSyncFns.syncSecrets(
- syncWith(CloudflareWorkersVariableType.Secret),
- payloadOf({ API_URL: "new" })
- );
+ await expect(
+ CloudflareWorkersSyncFns.syncSecrets(syncWith(variableType), payloadOf({ CONFIG: '{"a":2}', NEW_KEY: "{}" }))
+ ).rejects.toThrow(`already exist on the Cloudflare Worker as a different type: ${listed}.`);
- expect(patch).toHaveBeenCalledTimes(1);
- expect(await patchedBindings()).toEqual([
- { type: "secret_text", name: "API_URL", text: "new" },
- { type: "kv_namespace", name: "CACHE" }
- ]);
+ expect(patch).not.toHaveBeenCalled();
});
- it("keeps skipping same-name text variables for syncs saved without a type", async () => {
+ it("updates same-name text variables as they are when the toggle is on", async () => {
stubWorker([{ type: "plain_text", name: "API_URL", text: "old" }]);
- await CloudflareWorkersSyncFns.syncSecrets(syncWith(), payloadOf({ API_URL: "new" }));
+ await CloudflareWorkersSyncFns.syncSecrets(
+ syncWith(CloudflareWorkersVariableType.Secret, { syncNonSecretBindings: true }),
+ payloadOf({ API_URL: "new" })
+ );
- expect(patch).not.toHaveBeenCalled();
+ expect(patch).toHaveBeenCalledTimes(1);
+ expect(await patchedBindings()).toEqual([{ type: "plain_text", name: "API_URL", text: "new" }]);
});
it("removes only variables of the sync's type", async () => {
diff --git a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.ts b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.ts
index 7d71bd6d5e..1187e3904d 100644
--- a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.ts
+++ b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-fns.ts
@@ -150,6 +150,25 @@ const getCloudflareBindings = async (
return { secrets, nonSecretBindings };
};
+const VARIABLE_TYPE_LABELS: Record<string, string> = {
+ [CloudflareWorkersVariableType.Secret]: "secret",
+ [CloudflareWorkersVariableType.Text]: "text",
+ [CloudflareWorkersVariableType.Json]: "JSON"
+};
+
+// Changing a variable's type can break the Worker, since a JSON variable reaches it as a parsed object, or
+// expose a secret's value in the dashboard. A sync never changes one; it fails before writing anything.
+const $throwOnTypeConflicts = (conflicts: Array<{ name: string; type: string }>, fix: string) => {
+ if (conflicts.length === 0) return;
+
+ throw new SecretSyncError({
+ message: `The following secrets already exist on the Cloudflare Worker as a different type: ${conflicts
+ .map(({ name, type }) => `${name} (${VARIABLE_TYPE_LABELS[type]})`)
+ .join(", ")}. Infisical doesn't change a variable's type, so nothing was synced. ${fix}`,
+ shouldRetry: false
+ });
+};
+
// A text or JSON sync only owns variables of its type, so syncs of different types can share a Worker.
const $getManagedBindings = (
secretSync: TCloudflareWorkersSyncWithCredentials,
@@ -165,8 +184,7 @@ const $getManagedBindings = (
};
// Text and JSON variables are bindings in the Worker's settings, which take the full binding list. One
-// PATCH therefore creates and updates them, replaces a secret or variable of another type with the same
-// name, and deletes the ones no longer in Infisical.
+// PATCH therefore creates and updates them and deletes the ones no longer in Infisical.
const $syncVariableBindings = async (
secretSync: TCloudflareWorkersSyncWithCredentials,
secretMap: TSecretMap,
@@ -233,6 +251,11 @@ const $syncVariableBindings = async (
});
}
+ $throwOnTypeConflicts(
+ existingBindings.filter((binding) => secretMapKeys.has(binding.name) && binding.type !== variableType),
+ "Delete them in Cloudflare or change the sync's variable type, then sync again."
+ );
+
const bindings = [
...existingBindings.filter((binding) => !secretMapKeys.has(binding.name) && !isDeleted(binding)),
...variableBindings
@@ -267,33 +290,27 @@ export const CloudflareWorkersSyncFns = {
return;
}
- const shouldSyncNonSecretBindings = Boolean(secretSync.syncOptions.syncNonSecretBindings);
const cloudflareBindings = await getCloudflareBindings(secretSync);
const existingSecrets = $getManagedBindings(secretSync, cloudflareBindings);
- const nonSecretBindingKeys = new Set(cloudflareBindings.nonSecretBindings.map((b) => b.key));
const existingSecretsMap = Object.fromEntries(existingSecrets.map(({ key, type }) => [key, type]));
const secretMapKeys = new Set(Object.keys(secretMap));
- // Cloudflare rejects a secret with the same name as a plaintext or JSON variable, so those keys can't go
- // through secrets-bulk. A sync with Secret chosen explicitly turns them into secrets in the settings
- // update below, in one step so a failure can't leave them missing. Syncs saved before the type could be
- // chosen skip them, unless shouldSyncNonSecretBindings updates them in place.
- const bindingKeysToConvert = new Set(
- variableType === CloudflareWorkersVariableType.Secret && !shouldSyncNonSecretBindings
- ? Object.keys(secretMap).filter((key) => nonSecretBindingKeys.has(key))
- : []
- );
-
- const syncableEntries = Object.entries(secretMap).filter(
- ([key]) => shouldSyncNonSecretBindings || !nonSecretBindingKeys.has(key)
- );
+ // With shouldSyncNonSecretBindings on, same-name plaintext and JSON variables are updated as they are.
+ if (!secretSync.syncOptions.syncNonSecretBindings) {
+ $throwOnTypeConflicts(
+ cloudflareBindings.nonSecretBindings
+ .filter((binding) => secretMapKeys.has(binding.key))
+ .map(({ key, type }) => ({ name: key, type })),
+ 'Delete them in Cloudflare, change the sync\'s variable type, or turn on "Sync plaintext and JSON variables" to update them as they are.'
+ );
+ }
const bindingEntries: Array<[string, { value: string }]> = [];
const secretEntries: Array<[string, { value: string }]> = [];
- for (const [key, val] of syncableEntries) {
+ for (const [key, val] of Object.entries(secretMap)) {
const existingType = existingSecretsMap[key];
if (existingType && existingType !== CLOUDFLARE_SECRET_TYPE) {
bindingEntries.push([key, val]);
@@ -303,7 +320,7 @@ export const CloudflareWorkersSyncFns = {
}
try {
- if (bindingEntries.length > 0 || bindingKeysToConvert.size > 0) {
+ if (bindingEntries.length > 0) {
const { data: settingsData } = await request.get<{
result: { bindings: Array<{ type: string; name: string; text?: string; json?: string }> };
}>(
@@ -321,9 +338,6 @@ export const CloudflareWorkersSyncFns = {
$validateJsonBindings(settingsData.result.bindings, updatedBindingMap);
const updatedBindings = settingsData.result.bindings.map((binding) => {
- if (bindingKeysToConvert.has(binding.name)) {
- return { type: CLOUDFLARE_SECRET_TYPE, name: binding.name, text: secretMap[binding.name].value };
- }
if (binding.type !== CLOUDFLARE_SECRET_TYPE && updatedBindingMap[binding.name] !== undefined) {
const newValue = updatedBindingMap[binding.name].value;
if (binding.type === "json") {
diff --git a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-schemas.ts b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-schemas.ts
index f962f462b7..da9e2a94a9 100644
--- a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-schemas.ts
+++ b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-schemas.ts
@@ -55,14 +55,7 @@ export const CreateCloudflareWorkersSyncSchema = GenericCreateSecretSyncFieldsSc
CloudflareWorkersSyncOptionsConfig,
CloudflareWorkersSyncAdditionalOptionsSchema
).extend({
- // New syncs default to Secret. The type stays optional elsewhere because syncs created before it existed
- // have none, and they keep skipping same-name plaintext and JSON variables.
- destinationConfig: CloudflareWorkersSyncDestinationConfigSchema.extend({
- variableType: z
- .nativeEnum(CloudflareWorkersVariableType)
- .default(CloudflareWorkersVariableType.Secret)
- .describe(SecretSyncs.DESTINATION_CONFIG.CLOUDFLARE_WORKERS.variableType)
- })
+ destinationConfig: CloudflareWorkersSyncDestinationConfigSchema
});
export const UpdateCloudflareWorkersSyncSchema = GenericUpdateSecretSyncFieldsSchema(
diff --git a/docs/integrations/secret-syncs/cloudflare-pages.mdx b/docs/integrations/secret-syncs/cloudflare-pages.mdx
index 422e8eb177..4bc993b7be 100644
--- a/docs/integrations/secret-syncs/cloudflare-pages.mdx
+++ b/docs/integrations/secret-syncs/cloudflare-pages.mdx
@@ -46,6 +46,8 @@ description: "Learn how to configure a Cloudflare Pages Sync for Infisical."
- **Secret**: Encrypted, so you can't read the value in the Cloudflare dashboard
- **Text**: Plain text that you can read in the Cloudflare dashboard
+ If a secret already exists in the environment as the other type, the sync fails with an error that names it, and nothing in Cloudflare changes. To sync it, delete the variable in Cloudflare or change the sync's variable type.
+
<Tip>
To sync both secrets and text variables to one environment, create one sync of each type from different folders. Each sync only deletes variables of its own type. When you create the second sync, Infisical warns that the destination is already in use. If your organization blocks duplicate destinations, you can't create the second sync.
</Tip>
diff --git a/docs/integrations/secret-syncs/cloudflare-workers.mdx b/docs/integrations/secret-syncs/cloudflare-workers.mdx
index 4970e68f6f..6ec135b720 100644
--- a/docs/integrations/secret-syncs/cloudflare-workers.mdx
+++ b/docs/integrations/secret-syncs/cloudflare-workers.mdx
@@ -46,6 +46,8 @@ description: "Learn how to configure a Cloudflare Workers Sync for Infisical."
- **Text**: Plain text that you can read in the Cloudflare dashboard
- **JSON**: A JSON value that your Worker receives already parsed (each secret value must be valid JSON)
+ If a secret already exists on the Worker as a different type, the sync fails with an error that names it, and nothing on the Worker changes. To sync it, delete the variable in Cloudflare or change the sync's variable type. With **Sync plaintext and JSON variables** turned on, a Secret sync updates existing text and JSON variables as they are instead.
+
6. Configure the **Details** of your Cloudflare Workers Sync, then click **Next**.
![Configure Details](/images/secret-syncs/cloudflare-workers/cloudflare-workers-sync-details.png)
diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/CloudflareWorkersSyncOptionsFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/CloudflareWorkersSyncOptionsFields.tsx
index 635592e38f..f89e408a42 100644
--- a/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/CloudflareWorkersSyncOptionsFields.tsx
+++ b/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/CloudflareWorkersSyncOptionsFields.tsx
@@ -45,19 +45,18 @@ export const CloudflareWorkersSyncOptionsFields = () => {
<Field className="mb-4">
<FieldLabel htmlFor="cloudflare-workers-variable-type">Variable type</FieldLabel>
<FieldContent>
- {/* Unset shows Secret as a placeholder, so picking Secret still saves it, while editing an
- older sync without picking a type keeps its behavior */}
- <Select value={value} onValueChange={onChange}>
+ {/* Unset means Secret. It isn't filled in, so editing an older sync doesn't look like a
+ destination change. */}
+ <Select
+ value={value ?? CloudflareWorkersVariableType.Secret}
+ onValueChange={onChange}
+ >
<SelectTrigger
id="cloudflare-workers-variable-type"
className="w-full"
isError={Boolean(error)}
>
- <SelectValue
- placeholder={
- CLOUDFLARE_WORKERS_VARIABLE_TYPE_LABELS[CloudflareWorkersVariableType.Secret]
- }
- />
+ <SelectValue />
</SelectTrigger>
<SelectContent position="popper">
{Object.entries(CLOUDFLARE_WORKERS_VARIABLE_TYPE_LABELS).map(([type, label]) => (
@@ -88,8 +87,8 @@ export const CloudflareWorkersSyncOptionsFields = () => {
Sync plaintext and JSON variables
</Label>
<FieldDescription>
- Keep existing plaintext and JSON variables as their type and update their
- values, instead of converting them to secrets.
+ Update existing plaintext and JSON variables as they are, instead of failing
+ the sync on them.
</FieldDescription>
</FieldContent>
<Toggle