Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: fallback to worker version API in worker sync
Matheus Nogueira02dd89ce71cb
diff --git a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-errors.ts b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-errors.tsnew file mode 100644index 0000000000..e8b796fbea--- /dev/null+++ b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-errors.ts@@ -0,0 +1,79 @@+import { AxiosError } from "axios";++import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";++// The script secrets (10215) and settings (10214) endpoints clone the latest uploaded version, and refuse when+// it isn't the deployed one.+const CLOUDFLARE_PENDING_VERSION_ERROR_CODES = new Set([10214, 10215]);++const CLOUDFLARE_ERROR_MESSAGES: Record<number, string> = {+ 10021: "Cloudflare rejected the Worker code in the new version",+ 10068: "Cloudflare rejected the Worker code in the new version",+ 10057: "a binding the new version keeps from its base version no longer exists there",+ 10027: "the Worker is over Cloudflare's 64 MiB size limit",+ 10339: "Cloudflare doesn't allow deleting the latest Worker version"+};++export type TCloudflareApiResponse = {+ result?: unknown;+ success?: boolean;+ errors?: Array<{ code: number; message: string }>;+ messages?: string[];+};++export class CloudflareWorkersPendingVersionError extends SecretSyncError {}++const $getCloudflareErrors = (data: unknown): Array<{ code: number; message: string }> => {+ if (typeof data !== "object" || data === null) return [];+ const { errors } = data as TCloudflareApiResponse;+ if (!Array.isArray(errors)) return [];+ return errors.filter((error) => typeof error?.message === "string");+};++const $throwCloudflareError = (+ errors: Array<{ code: number; message: string }>,+ cause: unknown,+ secretKey?: string+): never => {+ if (errors.some((e) => CLOUDFLARE_PENDING_VERSION_ERROR_CODES.has(e.code))) {+ throw new CloudflareWorkersPendingVersionError({+ message:+ "Cloudflare rejected the secret update because the latest Worker version is not deployed; deploy the latest Worker version, then retry the secret sync.",+ error: cause,+ secretKey,+ shouldRetry: false+ });+ }++ throw new SecretSyncError({+ message: errors.map((e) => CLOUDFLARE_ERROR_MESSAGES[e.code] ?? e.message).join(". "),+ error: cause,+ secretKey,+ shouldRetry: false+ });+};++export const throwOnCloudflareRequestError = (err: unknown, secretKey?: string): never => {+ if (err instanceof AxiosError) {+ const errors = $getCloudflareErrors(err.response?.data);+ if (errors.length > 0) {+ $throwCloudflareError(errors, err, secretKey);+ }+ }++ throw err;+};++export const validateCloudflareResponse = (data: unknown) => {+ if (typeof data !== "object" || data === null) return;+ if ((data as TCloudflareApiResponse).success === false) {+ const errors = $getCloudflareErrors(data);+ if (errors.length > 0) {+ $throwCloudflareError(errors, undefined);+ }+ throw new SecretSyncError({+ message: "Cloudflare returned an unsuccessful response without error details.",+ shouldRetry: false+ });+ }+};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.tsindex 132ed9c115..aecc96220d 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@@ -1,5 +1,3 @@-import { AxiosError } from "axios";-import { request } from "@app/lib/config/request";import { BadRequestError } from "@app/lib/errors";import { chunkArray } from "@app/lib/fn";@@ -7,25 +5,24 @@ import { IntegrationUrls } from "@app/services/integration-auth/integration-listimport { 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";+import { TSecretMap, TSyncSecretsResult } from "@app/services/secret-sync/secret-sync-types";import { SECRET_SYNC_NAME_MAP } from "../secret-sync-maps";import { CloudflareWorkersVariableType } from "./cloudflare-workers-constants";+import {+ CloudflareWorkersPendingVersionError,+ TCloudflareApiResponse,+ throwOnCloudflareRequestError,+ validateCloudflareResponse+} from "./cloudflare-workers-errors";import { TCloudflareWorkersSyncWithCredentials } from "./cloudflare-workers-types";+import { applyBindingsWithVersionFallback, TBindingPlan, TWrittenBinding } from "./cloudflare-workers-version-fns";-const CLOUDFLARE_UNDEPLOYED_VERSION_ERROR_CODE = 10215;const CLOUDFLARE_SECRET_TYPE = "secret_text";const VARIABLE_BINDING_TYPES = new Set<string>(Object.values(CloudflareWorkersVariableType));// Cloudflare rejects secrets-bulk requests carrying more than 100 secrets (error code 100160).const CLOUDFLARE_BULK_SECRETS_LIMIT = 100;-type TCloudflareApiResponse = {- result?: unknown;- success?: boolean;- errors?: Array<{ code: number; message: string }>;- messages?: string[];-};-type TCloudflareSecretMetadata = {key: string;type: string;@@ -52,55 +49,6 @@ const $validateJsonBindings = (}};-const $getCloudflareErrors = (data: unknown): Array<{ code: number; message: string }> => {- if (typeof data !== "object" || data === null) return [];- const { errors } = data as TCloudflareApiResponse;- if (!Array.isArray(errors)) return [];- return errors.filter((error) => typeof error?.message === "string");-};--const $throwCloudflareError = (- errors: Array<{ code: number; message: string }>,- cause: unknown,- secretKey?: string-): never => {- const message = errors.some((e) => e.code === CLOUDFLARE_UNDEPLOYED_VERSION_ERROR_CODE)- ? "Cloudflare rejected the secret update because the latest Worker version is not deployed; deploy the latest Worker version, then retry the secret sync."- : errors.map((e) => e.message).join(". ");-- throw new SecretSyncError({- message,- error: cause,- secretKey,- shouldRetry: false- });-};--const throwOnCloudflareRequestError = (err: unknown, secretKey?: string): never => {- if (err instanceof AxiosError) {- const errors = $getCloudflareErrors(err.response?.data);- if (errors.length > 0) {- $throwCloudflareError(errors, err, secretKey);- }- }-- throw err;-};--const $validateCloudflareResponse = (data: unknown) => {- if (typeof data !== "object" || data === null) return;- if ((data as TCloudflareApiResponse).success === false) {- const errors = $getCloudflareErrors(data);- if (errors.length > 0) {- $throwCloudflareError(errors, undefined);- }- throw new SecretSyncError({- message: "Cloudflare returned an unsuccessful response without error details.",- shouldRetry: false- });- }-};-type TCloudflareBindings = {secrets: TCloudflareSecretMetadata[];nonSecretBindings: TCloudflareSecretMetadata[];@@ -169,6 +117,19 @@ const $throwOnTypeConflicts = (conflicts: Array<{ name: string; type: string }>,});};+const $throwOnNonVariableConflicts = (bindings: Array<{ type: string; name: string }>, secretMapKeys: Set<string>) => {+ const conflictingKeys = bindings+ .filter((binding) => secretMapKeys.has(binding.name) && !VARIABLE_BINDING_TYPES.has(binding.type))+ .map((binding) => binding.name);++ if (conflictingKeys.length > 0) {+ throw new SecretSyncError({+ message: `The following secrets have the same name as another binding on the Cloudflare Worker, such as a KV namespace or a service: ${conflictingKeys.join(", ")}. Rename the secrets in Infisical, or use a key schema to change their names in Cloudflare.`,+ 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,@@ -240,16 +201,7 @@ const $syncVariableBindings = async (const existingBindings = settingsData.result.bindings ?? [];- const conflictingKeys = existingBindings- .filter((binding) => secretMapKeys.has(binding.name) && !VARIABLE_BINDING_TYPES.has(binding.type))- .map((binding) => binding.name);-- if (conflictingKeys.length > 0) {- throw new SecretSyncError({- message: `The following secrets have the same name as another binding on the Cloudflare Worker, such as a KV namespace or a service: ${conflictingKeys.join(", ")}. Rename the secrets in Infisical, or use a key schema to change their names in Cloudflare.`,- shouldRetry: false- });- }+ $throwOnNonVariableConflicts(existingBindings, secretMapKeys);$throwOnTypeConflicts(existingBindings.filter((binding) => secretMapKeys.has(binding.name) && binding.type !== variableType),@@ -269,13 +221,119 @@ const $syncVariableBindings = async (Authorization: `Bearer ${apiToken}`}});- $validateCloudflareResponse(settingsPatchData);+ validateCloudflareResponse(settingsPatchData);} catch (err) {throwOnCloudflareRequestError(err);}};-export const CloudflareWorkersSyncFns = {+// The binding types a sync writes and deletes; the same split as $getManagedBindings.+const $getManagedTypes = (secretSync: TCloudflareWorkersSyncWithCredentials) => {+ const { variableType = CloudflareWorkersVariableType.Secret } = secretSync.destinationConfig;++ if (variableType !== CloudflareWorkersVariableType.Secret) return new Set<string>([variableType]);++ return secretSync.syncOptions.syncNonSecretBindings+ ? new Set<string>(VARIABLE_BINDING_TYPES)+ : new Set<string>([CloudflareWorkersVariableType.Secret]);+};++const $isManagedBySchema = (secretSync: TCloudflareWorkersSyncWithCredentials, name: string) =>+ matchesSchema(name, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema);++// The full set of changes a sync makes, applied to a version's bindings by the version fallback. It follows the+// in-place sync's rules for each variable type, the toggle, and deletion.+const $planSyncBindings = (+ secretSync: TCloudflareWorkersSyncWithCredentials,+ secretMap: TSecretMap,+ baseBindings: Array<{ type: string; name: string }>+): TBindingPlan => {+ const {+ destinationConfig: { variableType },+ syncOptions: { disableSecretDeletion }+ } = secretSync;+ const syncType = variableType ?? CloudflareWorkersVariableType.Secret;+ const managedTypes = $getManagedTypes(secretSync);+ const secretMapKeys = new Set(Object.keys(secretMap));+ const baseTypes = new Map(baseBindings.map(({ name, type }) => [name, type]));++ $throwOnNonVariableConflicts(baseBindings, secretMapKeys);++ const typeConflicts = baseBindings.filter(+ (binding) => secretMapKeys.has(binding.name) && !managedTypes.has(binding.type)+ );++ // A sync created before the type could be chosen skips same-name variables of another type.+ if (variableType) {+ $throwOnTypeConflicts(+ typeConflicts,+ syncType === CloudflareWorkersVariableType.Secret+ ? 'Delete them in Cloudflare, change the sync\'s variable type, or turn on "Sync plaintext and JSON variables" to update them as they are.'+ : "Delete them in Cloudflare or change the sync's variable type, then sync again."+ );+ }++ const written: TWrittenBinding[] = [];+ const invalidJsonKeys: string[] = [];++ for (const [name, { value }] of Object.entries(secretMap)) {+ const baseType = baseTypes.get(name);+ if (baseType === undefined || managedTypes.has(baseType)) {+ const type = baseType ?? syncType;+ if (type === CloudflareWorkersVariableType.Json) {+ try {+ written.push({ type, name, json: JSON.parse(value) as unknown });+ } catch {+ invalidJsonKeys.push(name);+ }+ } else {+ written.push({ type, name, text: value });+ }+ }+ }++ if (invalidJsonKeys.length > 0) {+ throw new SecretSyncError({+ message: `The following secrets are not valid JSON, so they cannot be synced as Cloudflare Workers JSON variables: ${invalidJsonKeys.join(", ")}. Fix their values in Infisical or change the sync's variable type.`,+ shouldRetry: false+ });+ }++ const dropped = disableSecretDeletion+ ? []+ : baseBindings+ .filter(+ (binding) =>+ managedTypes.has(binding.type) &&+ !secretMapKeys.has(binding.name) &&+ $isManagedBySchema(secretSync, binding.name)+ )+ .map(({ name }) => name);++ return { written, dropped };+};++const $planRemoveBindings = (+ secretSync: TCloudflareWorkersSyncWithCredentials,+ secretMap: TSecretMap,+ baseBindings: Array<{ type: string; name: string }>+): TBindingPlan => {+ const managedTypes = $getManagedTypes(secretSync);++ return {+ written: [],+ dropped: baseBindings+ .filter(+ (binding) =>+ managedTypes.has(binding.type) &&+ secretMap[binding.name] !== undefined &&+ $isManagedBySchema(secretSync, binding.name)+ )+ .map(({ name }) => name)+ };+};++const $inPlace = {syncSecrets: async (secretSync: TCloudflareWorkersSyncWithCredentials, payload: TSecretSyncPayload) => {const secretMap = payload.flatten();const {@@ -372,7 +430,7 @@ export const CloudflareWorkersSyncFns = {}});- $validateCloudflareResponse(settingsPatchData);+ validateCloudflareResponse(settingsPatchData);}// Build the bulk secrets payload using JSON Merge Patch (RFC 7396):@@ -422,7 +480,7 @@ export const CloudflareWorkersSyncFns = {}});- $validateCloudflareResponse(data);+ validateCloudflareResponse(data);} catch (err) {throwOnCloudflareRequestError(err, firstSecretKey);}@@ -484,10 +542,6 @@ export const CloudflareWorkersSyncFns = {}},- getSecrets: async (secretSync: TCloudflareWorkersSyncWithCredentials): Promise<TSecretMap> => {- throw new Error(`${SECRET_SYNC_NAME_MAP[secretSync.destination]} does not support importing secrets.`);- },-removeSecrets: async (secretSync: TCloudflareWorkersSyncWithCredentials, payload: TSecretSyncPayload) => {const secretMap = payload.flatten();const {@@ -533,7 +587,7 @@ export const CloudflareWorkersSyncFns = {}});- $validateCloudflareResponse(data);+ validateCloudflareResponse(data);} catch (err) {throwOnCloudflareRequestError(err, firstSecretKey);}@@ -573,10 +627,46 @@ export const CloudflareWorkersSyncFns = {}});- $validateCloudflareResponse(settingsPatchData);+ validateCloudflareResponse(settingsPatchData);}} catch (err) {throwOnCloudflareRequestError(err);}}};++export const CloudflareWorkersSyncFns = {+ syncSecrets: async (+ secretSync: TCloudflareWorkersSyncWithCredentials,+ payload: TSecretSyncPayload+ ): Promise<TSyncSecretsResult | undefined> => {+ try {+ await $inPlace.syncSecrets(secretSync, payload);+ return undefined;+ } catch (err) {+ if (!(err instanceof CloudflareWorkersPendingVersionError)) throw err;++ const secretMap = payload.flatten();+ return applyBindingsWithVersionFallback(secretSync, (baseBindings) =>+ $planSyncBindings(secretSync, secretMap, baseBindings)+ );+ }+ },++ getSecrets: async (secretSync: TCloudflareWorkersSyncWithCredentials): Promise<TSecretMap> => {+ throw new Error(`${SECRET_SYNC_NAME_MAP[secretSync.destination]} does not support importing secrets.`);+ },++ removeSecrets: async (secretSync: TCloudflareWorkersSyncWithCredentials, payload: TSecretSyncPayload) => {+ try {+ await $inPlace.removeSecrets(secretSync, payload);+ } catch (err) {+ if (!(err instanceof CloudflareWorkersPendingVersionError)) throw err;++ const secretMap = payload.flatten();+ await applyBindingsWithVersionFallback(secretSync, (baseBindings) =>+ $planRemoveBindings(secretSync, secretMap, baseBindings)+ );+ }+ }+};diff --git a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-version-fns.test.ts b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-version-fns.test.tsnew file mode 100644index 0000000000..7ec0b02452--- /dev/null+++ b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-version-fns.test.ts@@ -0,0 +1,155 @@+import { AxiosError, AxiosResponse } from "axios";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { TSecretSyncPayload } from "../secret-sync-payload";+import { CloudflareWorkersVariableType } from "./cloudflare-workers-constants";+import { CloudflareWorkersSyncFns } from "./cloudflare-workers-fns";+import { TCloudflareWorkersSyncWithCredentials } from "./cloudflare-workers-types";++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({}) }));+vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() } }));++const { get, patch, post } = vi.hoisted(() => ({ get: vi.fn(), patch: vi.fn(), post: vi.fn() }));+vi.mock("@app/lib/config/request", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ request: { get, patch, post }+}));++type TBinding = { type: string; name: string; text?: string; version_id?: string } & Record<string, unknown>;+type TVersion = { id: string; bindings: TBinding[] } & Record<string, unknown>;+type TCreateBody = { bindings: TBinding[] } & Record<string, unknown>;++const cloudflareError = (code: number) =>+ new AxiosError("Request failed with status code 400", "ERR_BAD_REQUEST", undefined, undefined, {+ status: 400,+ data: { success: false, errors: [{ code, message: `error ${code}` }] }+ } as AxiosResponse);++// Shaped like a real read of a pending version: besides its configuration, Cloudflare returns fields that describe+// the version itself, and the bindings a second time as `env`.+const pendingVersion = (extra: Record<string, unknown> = {}): TVersion => ({+ id: "v21",+ number: 21,+ created_on: "2026-01-01T00:00:00Z",+ source: "wrangler",+ urls: ["https://my-worker.example.workers.dev"],+ env: { API_KEY: { type: "secret_text" } },+ main_module: "index.js",+ modules: [{ name: "index.js", content_type: "application/javascript+module", content_base64: "djIx" }],+ bindings: [+ { type: "secret_text", name: "API_KEY" },+ { type: "secret_text", name: "STALE" },+ { type: "kv_namespace", name: "CACHE", namespace_id: "ns" }+ ],+ compatibility_date: "2026-01-01",+ annotations: { "workers/triggered_by": "upload" },+ ...extra+});++let base: TVersion;+let created: TVersion | undefined;++// The secrets endpoint refuses because v21 isn't deployed. Version reads and creates behave like Cloudflare's,+// including the two rejections seen against the live API.+const installFakeCloudflare = (secretsEndpointRefuses = true) => {+ get.mockImplementation(async (url: string) => {+ if (url.endsWith("/secrets")) {+ return { data: { result: base.bindings.filter(({ type }) => type === "secret_text") } };+ }+ if (url.endsWith("/settings")) return { data: { result: { bindings: base.bindings } } };+ const version = url.endsWith(`/versions/${created?.id}`) ? created : base;+ return { data: { success: true, result: structuredClone(version) } };+ });++ patch.mockImplementation(async () => {+ if (secretsEndpointRefuses) throw cloudflareError(10215);+ return { data: { success: true } };+ });++ post.mockImplementation(async (url: string, body: TCreateBody) => {+ if (body.env && body.bindings) throw cloudflareError(10021);+ if (body.bindings.some(({ type }) => type === "assets") && !body.assets) throw cloudflareError(10305);++ const bindings = body.bindings.map((binding) =>+ binding.type === "inherit" ? base.bindings.find(({ name }) => name === binding.name)! : binding+ );+ created = { ...body, id: "new-1", bindings };+ return { data: { success: true, result: { id: created.id } } };+ });+};++const sync = (secrets: Record<string, string>) =>+ CloudflareWorkersSyncFns.syncSecrets(+ {+ id: "sync-id",+ destination: "cloudflare-workers",+ destinationConfig: { scriptId: "my-worker", variableType: CloudflareWorkersVariableType.Secret },+ environment: { slug: "prod" },+ syncOptions: { disableSecretDeletion: false },+ connection: { credentials: { apiToken: "token", accountId: "account-id" } }+ } as unknown as TCloudflareWorkersSyncWithCredentials,+ {+ flatten: () => Object.fromEntries(Object.entries(secrets).map(([key, value]) => [key, { value }]))+ } as unknown as TSecretSyncPayload+ );++const versionCreates = () =>+ post.mock.calls.filter(([url]) => (url as string).endsWith("/versions")) as Array<+ [string, TCreateBody, { params?: unknown }]+ >;++describe("Cloudflare Workers version fallback", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ base = pendingVersion();+ created = undefined;+ });++ it("doesn't create a version when the secrets endpoint succeeds", async () => {+ installFakeCloudflare(false);++ await sync({ API_KEY: "new" });++ expect(versionCreates()).toEqual([]);+ });++ it("adds the secrets to a new version built on the latest one, and never deploys it", async () => {+ installFakeCloudflare();++ const result = await sync({ API_KEY: "new", ADDED: "a" });++ const [[, body, config]] = versionCreates();+ expect(config.params).toEqual({ deploy: false });+ expect(Object.fromEntries(body.bindings.map((binding) => [binding.name, binding]))).toEqual({+ API_KEY: { type: "secret_text", name: "API_KEY", text: "new" },+ CACHE: { type: "inherit", name: "CACHE", version_id: "v21" },+ ADDED: { type: "secret_text", name: "ADDED", text: "a" }+ });+ expect(post.mock.calls.some(([url]) => (url as string).endsWith("/deployments"))).toBe(false);+ expect(result?.message).toContain("new-1");+ });++ it("sends back every field of the base version except its id and env", async () => {+ const extra = { tail_consumers: [{ service: "logger" }], exports: { Room: { type: "durable-object" } } };+ base = pendingVersion(extra);+ installFakeCloudflare();++ await sync({ API_KEY: "new" });++ const [[, body]] = versionCreates();+ expect(body).not.toHaveProperty("id");+ expect(body).not.toHaveProperty("env");+ expect(body).toMatchObject({ number: 21, main_module: "index.js", modules: base.modules, ...extra });+ });++ it.each([+ ["assets", { assets: { config: { html_handling: "auto-trailing-slash" } } }],+ ["an assets binding", { bindings: [...pendingVersion().bindings, { type: "assets", name: "ASSETS" }] }]+ ])("refuses a Worker with %s, which a copy would lose", async (label, extra) => {+ base = pendingVersion(extra);+ installFakeCloudflare();++ await expect(sync({ API_KEY: "new" })).rejects.toThrow("static assets");+ expect(versionCreates()).toEqual([]);+ });+});diff --git a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-version-fns.ts b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-version-fns.tsnew file mode 100644index 0000000000..100d512faf--- /dev/null+++ b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-version-fns.ts@@ -0,0 +1,284 @@+import pLimit from "p-limit";++import { request } from "@app/lib/config/request";+import { crypto } from "@app/lib/crypto/cryptography";+import { logger } from "@app/lib/logger";+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";+import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";+import { TSyncSecretsResult } from "@app/services/secret-sync/secret-sync-types";++import { throwOnCloudflareRequestError, validateCloudflareResponse } from "./cloudflare-workers-errors";+import { TCloudflareWorkersSyncWithCredentials } from "./cloudflare-workers-types";++// A fallback moves the Worker's whole bundle each way (up to ~85 MB of base64), so only a few run at once.+const fallbackLimit = pLimit(2);+const VERSION_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;+const MAX_VERSION_PAYLOAD_BYTES = 128 * 1024 * 1024;++type TVersionModule = {+ name: string;+ content_type?: string;+ content_base64: string;+};+type TVersionBinding = { type: string; name: string };+type TWorkerVersion = {+ id: string;+ main_module?: string;+ modules?: TVersionModule[];+ bindings?: TVersionBinding[];+} & Record<string, unknown>;++export type TWrittenBinding = {+ type: string;+ name: string;+ text?: string;+ json?: unknown;+};++// Every base binding that is neither written nor dropped is inherited from the base version unchanged.+export type TBindingPlan = { written: TWrittenBinding[]; dropped: string[] };++type TFallbackContext = {+ syncId: string;+ scriptId: string;+ accountUrl: string;+ headers: Record<string, string>;+};++type TExpectedVersion = {+ baseVersionId: string;+ bindings: string[];+ moduleHashes: Map<string, string>;+};++const $fail = (+ scriptId: string,+ reason: string,+ fix = "Deploy the latest version of the Worker in Cloudflare, then sync again."+) =>+ new SecretSyncError({+ message: `The latest version of Cloudflare Worker '${scriptId}' is not deployed, so Infisical tried to add the secrets to a new version of the Worker instead, but ${reason}. ${fix}`,+ shouldRetry: false+ });++const $bindingLabel = ({ name, type }: { name: string; type: string }) => `${name} (${type})`;++const $hashModule = ({ content_type: contentType, content_base64: contentBase64 }: TVersionModule) =>+ crypto.nativeCrypto+ .createHash("sha256")+ .update(contentType ?? "")+ .update("\0")+ .update(contentBase64)+ .digest("hex");++const $hashModules = (modules: TVersionModule[]) =>+ new Map(modules.map((module) => [module.name, $hashModule(module)]));++const $getVersion = async ({ scriptId, accountUrl, headers }: TFallbackContext, versionRef: string) => {+ try {+ const { data } = await request.get<{ result: TWorkerVersion }>(+ `${accountUrl}/workers/workers/${scriptId}/versions/${versionRef}`,+ {+ headers,+ params: { include: "modules" },+ timeout: VERSION_REQUEST_TIMEOUT_MS,+ maxContentLength: MAX_VERSION_PAYLOAD_BYTES+ }+ );+ return data.result;+ } catch (err) {+ return throwOnCloudflareRequestError(err);+ }+};++const $validateBaseVersion = (scriptId: string, base: TWorkerVersion) => {+ if (+ !base.main_module ||+ !base.modules?.length ||+ base.modules.some((module) => typeof module.content_base64 !== "string" || !module.content_base64)+ ) {+ throw $fail(scriptId, `Cloudflare didn't return the code of version ${base.id}`);+ }++ if (!Array.isArray(base.bindings)) {+ throw $fail(scriptId, `Cloudflare didn't return the bindings of version ${base.id}`);+ }++ // A read returns only the assets config, not the upload token, so a copy is created without the static files and+ // serves 404 for them once deployed. Cloudflare accepts it unless the Worker also has an assets binding.+ if ((base.assets !== null && base.assets !== undefined) || base.bindings.some(({ type }) => type === "assets")) {+ throw $fail(scriptId, `version ${base.id} serves static assets, which Infisical can't copy into a new version`);+ }+};++// Kept apart from verification so the base version's modules can be freed before the new version is read back.+const $createVersion = async (+ ctx: TFallbackContext,+ baseVersionRef: string,+ planBindings: (baseBindings: TVersionBinding[]) => TBindingPlan+) => {+ const base = await $getVersion(ctx, baseVersionRef);+ $validateBaseVersion(ctx.scriptId, base);++ // Everything else is sent back, so configuration Cloudflare adds later carries over to the new version. A read+ // returns the bindings as both `env` and `bindings`, and Cloudflare rejects an upload with both (10021).+ const { id: baseVersionId, env: omittedEnv, ...config } = base;+ const baseBindings = base.bindings as TVersionBinding[];+ const plan = planBindings(baseBindings);++ if (!plan.written.length && !plan.dropped.length) return null;++ const writtenByName = new Map(plan.written.map((binding) => [binding.name, binding]));+ const dropped = new Set(plan.dropped);+ const baseNames = new Set(baseBindings.map(({ name }) => name));++ const bindings: Array<TWrittenBinding | { type: "inherit"; name: string; version_id: string }> = [];+ const expectedBindings: string[] = [];++ for (const binding of baseBindings) {+ const written = writtenByName.get(binding.name);+ if (written) {+ bindings.push(written);+ expectedBindings.push($bindingLabel(written));+ } else if (!dropped.has(binding.name)) {+ // Pinned to the base's id, since another upload can replace the latest version while this one is built.+ bindings.push({+ type: "inherit",+ name: binding.name,+ version_id: baseVersionId+ });+ expectedBindings.push($bindingLabel(binding));+ }+ }++ const createdSecretKeys: string[] = [];+ for (const written of plan.written) {+ if (!baseNames.has(written.name)) {+ bindings.push(written);+ expectedBindings.push($bindingLabel(written));+ createdSecretKeys.push(written.name);+ }+ }++ const expected: TExpectedVersion = {+ baseVersionId,+ bindings: expectedBindings.sort(),+ moduleHashes: $hashModules(base.modules as TVersionModule[])+ };++ let newVersionId: string;+ try {+ const { data } = await request.post<{+ result?: { id?: string };+ success?: boolean;+ }>(+ `${ctx.accountUrl}/workers/workers/${ctx.scriptId}/versions`,+ {+ ...config,+ bindings,+ annotations: {+ "workers/tag": "infisical-sync",+ "workers/message": `Infisical secret sync (fallback, base ${baseVersionId})`+ }+ },+ {+ headers: { ...ctx.headers, "Content-Type": "application/json" },+ params: { deploy: false },+ timeout: VERSION_REQUEST_TIMEOUT_MS,+ maxBodyLength: MAX_VERSION_PAYLOAD_BYTES,+ // A retried upload can't be told apart from a new one, and each one becomes the latest version.+ "axios-retry": { retries: 0 }+ }+ );+ validateCloudflareResponse(data);+ if (!data.result?.id) {+ throw $fail(ctx.scriptId, "Cloudflare didn't return the id of the version it created");+ }+ newVersionId = data.result.id;+ } catch (err) {+ return throwOnCloudflareRequestError(err);+ }++ logger.info(+ `SecretSync Cloudflare Workers fallback created version [syncId=${ctx.syncId}] [scriptId=${ctx.scriptId}] [baseVersionId=${baseVersionId}] [newVersionId=${newVersionId}] [bindings=${expectedBindings.join(", ")}]`+ );++ return {+ newVersionId,+ expected,+ result: {+ createdSecretKeys,+ updatedSecretKeys: [...writtenByName.keys()].filter((name) => baseNames.has(name)),+ deletedSecretKeys: baseBindings.filter(({ name }) => dropped.has(name)).map(({ name }) => name)+ }+ };+};++const $verifyVersion = async (ctx: TFallbackContext, newVersionId: string, expected: TExpectedVersion) => {+ const created = await $getVersion(ctx, newVersionId);+ const differences: string[] = [];++ const actualBindings = (created.bindings ?? []).map($bindingLabel);+ const missingBindings = expected.bindings.filter((binding) => !actualBindings.includes(binding));+ const unexpectedBindings = actualBindings.filter((binding) => !expected.bindings.includes(binding));+ if (missingBindings.length) differences.push(`missing bindings ${missingBindings.join(", ")}`);+ if (unexpectedBindings.length) differences.push(`unexpected bindings ${unexpectedBindings.join(", ")}`);++ const actualModuleHashes = $hashModules(created.modules ?? []);+ const moduleNames = new Set([...expected.moduleHashes.keys(), ...actualModuleHashes.keys()]);+ const changedModules = [...moduleNames].filter(+ (name) => expected.moduleHashes.get(name) !== actualModuleHashes.get(name)+ );+ if (changedModules.length) differences.push(`different modules ${changedModules.join(", ")}`);++ if (differences.length) {+ logger.error(+ `SecretSync Cloudflare Workers fallback version mismatch [syncId=${ctx.syncId}] [scriptId=${ctx.scriptId}] [baseVersionId=${expected.baseVersionId}] [newVersionId=${newVersionId}] [differences=${differences.join("; ")}]`+ );+ throw $fail(+ ctx.scriptId,+ `the version it created (${newVersionId}, tagged infisical-sync) doesn't match version ${expected.baseVersionId}: ${differences.join("; ")}`,+ "Don't deploy it. Sync again, and contact support if this keeps happening."+ );+ }+};++// The secrets and settings endpoints refuse to write while the latest version is not the deployed one. This builds+// a new version from the latest one's code and bindings with the secrets changed, uploads it without deploying it,+// and checks it. Deploying it is left to the user, because it also ships the pending changes it was built on.+export const applyBindingsWithVersionFallback = (+ secretSync: TCloudflareWorkersSyncWithCredentials,+ planBindings: (baseBindings: TVersionBinding[]) => TBindingPlan+) =>+ fallbackLimit(async (): Promise<TSyncSecretsResult | undefined> => {+ const {+ id: syncId,+ connection: {+ credentials: { apiToken, accountId }+ },+ destinationConfig: { scriptId }+ } = secretSync;++ const ctx: TFallbackContext = {+ syncId,+ scriptId,+ accountUrl: `${IntegrationUrls.CLOUDFLARE_WORKERS_API_URL}/client/v4/accounts/${accountId}`,+ headers: {+ Authorization: `Bearer ${apiToken}`,+ Accept: "application/json"+ }+ };++ logger.info(+ `SecretSync Cloudflare Workers latest version not deployed, using fallback [syncId=${syncId}] [scriptId=${scriptId}]`+ );++ const created = await $createVersion(ctx, "latest", planBindings);+ if (!created) return undefined;++ await $verifyVersion(ctx, created.newVersionId, created.expected);+ return {+ ...created.result,+ message: `Worker has undeployed changes; created version ${created.newVersionId} with updated secrets. Deploy it for the secrets to take effect.`+ };+ });diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.tsindex c0c771a0d7..bc064ca516 100644--- a/backend/src/services/secret-sync/secret-sync-queue.ts+++ b/backend/src/services/secret-sync/secret-sync-queue.ts@@ -585,6 +585,7 @@ export const secretSyncQueueFactory = ({});syncResult = result ?? undefined;+ syncMessage = syncResult?.message ?? null;isSynced = true;} catch (err) {diff --git a/backend/src/services/secret-sync/secret-sync-types.ts b/backend/src/services/secret-sync/secret-sync-types.tsindex 91fd10269e..7e381c2d43 100644--- a/backend/src/services/secret-sync/secret-sync-types.ts+++ b/backend/src/services/secret-sync/secret-sync-types.ts@@ -553,6 +553,8 @@ export type TSyncSecretsResult = {createdSecretKeys: string[];updatedSecretKeys: string[];deletedSecretKeys: string[];+ // Something the user has to act on although the sync succeeded; saved as the sync's last message.+ message?: string;};// ReturnType<> resolves findById's includeFolderPath generic to boolean, a union whose members maydiff --git a/docs/integrations/secret-syncs/cloudflare-workers.mdx b/docs/integrations/secret-syncs/cloudflare-workers.mdxindex 1886c35066..cf0f603329 100644--- a/docs/integrations/secret-syncs/cloudflare-workers.mdx+++ b/docs/integrations/secret-syncs/cloudflare-workers.mdx@@ -133,3 +133,13 @@ description: "Learn how to configure a Cloudflare Workers Sync for Infisical."</Tab></Tabs>++## Syncing while a version is pending++If someone uploads a version of the Worker without deploying it, for example with `wrangler versions upload`, that version is pending, and Cloudflare doesn't let Infisical change the Worker's secrets directly. Instead, Infisical uploads a new version with the pending version's code and settings and the updated secrets, and labels the new version with the `infisical-sync` tag in Cloudflare.++Infisical doesn't deploy the new version, because deploying it also deploys the pending changes. The sync's status shows the ID of the new version, and the secrets take effect when you deploy that version in Cloudflare.++### When Infisical can't upload a new version++If the pending version serves static assets, the sync fails without changing the Worker. To sync the secrets, deploy the pending version in Cloudflare, then sync again.diff --git a/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsx b/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsxindex 303dba5f82..413bbfe25a 100644--- a/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsx+++ b/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsx@@ -5,6 +5,7 @@ import {CalendarCheckIcon,CheckIcon,HourglassIcon,+ InfoIcon,LucideIcon,RefreshCwIcon,XIcon@@ -68,6 +69,9 @@ export const SecretSyncStatusBadge = ({ status, lastSyncedAt, lastSyncMessage }:return null;}, [status, lastSyncMessage]);+ // A sync can succeed and still leave something to do, such as deploying a Cloudflare Worker version.+ const successNote = status === SecretSyncStatus.Succeeded ? lastSyncMessage : null;+const badge = (<Badge variant={variant}><Icon className={[SecretSyncStatus.Running].includes(status) ? "animate-spin" : ""} />@@ -77,7 +81,7 @@ export const SecretSyncStatusBadge = ({ status, lastSyncedAt, lastSyncMessage }:if (![SecretSyncStatus.Succeeded, SecretSyncStatus.Failed].includes(status) ||- (!lastSyncedAt && !failureMessage)+ (!lastSyncedAt && !failureMessage && !successNote)) {return badge;}@@ -111,6 +115,17 @@ export const SecretSyncStatusBadge = ({ status, lastSyncedAt, lastSyncMessage }:</div></div>)}+ {successNote && (+ <div>+ <div className="mb-2 flex items-center gap-1.5 self-start text-info">+ <InfoIcon className="size-3" />+ <div className="text-xs">Note</div>+ </div>+ <div className="rounded-sm bg-surface-active p-2 text-xs break-words">+ {successNote}+ </div>+ </div>+ )}</div></HoverCardContent></HoverCard>