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
simplify changes
Matheus Nogueira6f39d0bdd55d
diff --git a/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-binding-fns.ts b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-binding-fns.tsnew file mode 100644index 0000000000..5aeb6de879--- /dev/null+++ b/backend/src/services/secret-sync/cloudflare-workers/cloudflare-workers-binding-fns.ts@@ -0,0 +1,139 @@+import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";+import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";+import { TSecretMap } from "@app/services/secret-sync/secret-sync-types";++import { CloudflareWorkersVariableType } from "./cloudflare-workers-constants";+import { TCloudflareWorkersSyncWithCredentials } from "./cloudflare-workers-types";++const VARIABLE_BINDING_TYPES = new Set<string>(Object.values(CloudflareWorkersVariableType));++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[] };++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.+export 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+ });+};++export 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+ });+ }+};++// The binding types a sync writes and deletes; the same split as $getManagedBindings in cloudflare-workers-fns.ts.+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.+export 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 };+};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 7f429ad9fc..134caaa205 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@@ -9,6 +9,7 @@ import { TSecretSyncPayload } from "@app/services/secret-sync/secret-sync-payloaimport { TSecretMap, TSyncSecretsResult } from "@app/services/secret-sync/secret-sync-types";import { SECRET_SYNC_NAME_MAP } from "../secret-sync-maps";+import { throwOnNonVariableConflicts, throwOnTypeConflicts } from "./cloudflare-workers-binding-fns";import { CloudflareWorkersVariableType } from "./cloudflare-workers-constants";import {CloudflareWorkersPendingVersionError,@@ -17,10 +18,9 @@ import {validateCloudflareResponse} from "./cloudflare-workers-errors";import { TCloudflareWorkersSyncWithCredentials } from "./cloudflare-workers-types";-import { applyBindingsWithVersionFallback, TBindingPlan, TWrittenBinding } from "./cloudflare-workers-version-fns";+import { applySecretsWithVersionFallback } from "./cloudflare-workers-version-fns";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;@@ -99,38 +99,6 @@ 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- });-};--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,@@ -202,9 +170,9 @@ const $syncVariableBindings = async (const existingBindings = settingsData.result.bindings ?? [];- $throwOnNonVariableConflicts(existingBindings, secretMapKeys);+ throwOnNonVariableConflicts(existingBindings, secretMapKeys);- $throwOnTypeConflicts(+ 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.");@@ -228,92 +196,6 @@ const $syncVariableBindings = async (}};-// 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 $inPlace = {syncSecrets: async (secretSync: TCloudflareWorkersSyncWithCredentials, payload: TSecretSyncPayload) => {const secretMap = payload.flatten();@@ -342,7 +224,7 @@ const $inPlace = {// Otherwise the sync fails rather than change their type, except a sync created before the type could be// chosen (no variableType), which keeps skipping them as it always has.if (!shouldSyncNonSecretBindings && variableType) {- $throwOnTypeConflicts(+ throwOnTypeConflicts(cloudflareBindings.nonSecretBindings.filter((binding) => secretMapKeys.has(binding.key)).map(({ key, type }) => ({ name: key, type })),@@ -628,10 +510,7 @@ export const CloudflareWorkersSyncFns = {} catch (err) {if (!(err instanceof CloudflareWorkersPendingVersionError)) throw err;- const secretMap = payload.flatten();- return applyBindingsWithVersionFallback(secretSync, keyStore, (baseBindings) =>- $planSyncBindings(secretSync, secretMap, baseBindings)- );+ return applySecretsWithVersionFallback(secretSync, payload.flatten(), keyStore);}},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.tsindex 6915698533..8b4367a773 100644--- 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.ts@@ -12,10 +12,10 @@ import { TCloudflareWorkersSyncWithCredentials } from "./cloudflare-workers-typevi.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() }));+const { get, patch, post, del } = vi.hoisted(() => ({ get: vi.fn(), patch: vi.fn(), post: vi.fn(), del: vi.fn() }));vi.mock("@app/lib/config/request", async (importOriginal) => ({...(await importOriginal<object>()),- request: { get, patch, post }+ request: { get, patch, post, delete: del }}));type TBinding = { type: string; name: string; text?: string; version_id?: string } & Record<string, unknown>;@@ -49,8 +49,10 @@ const pendingVersion = (extra: Record<string, unknown> = {}): TVersion => ({...extra});+// The latest version. Tests set it before installing the fake, which then keeps it pointing at the newest upload.let base: TVersion;-let created: Map<string, TVersion>;+let versions: Map<string, TVersion>;+let uploads: number;let uploadGate: Promise<void> | undefined;// Lets a test make Cloudflare store something other than what was uploaded.let alterStoredVersion: ((version: TVersion) => TVersion) | undefined;@@ -58,12 +60,17 @@ let alterStoredVersion: ((version: TVersion) => 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) => {+ versions = new Map([[base.id, base]]);+ uploads = 0;+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 = created.get(url.split("/versions/")[1]) ?? base;+ const ref = url.split("/versions/")[1];+ const version = ref === "latest" ? base : versions.get(ref);+ if (!version) throw cloudflareError(10007);return { data: { success: true, result: structuredClone(version) } };});@@ -77,18 +84,29 @@ const installFakeCloudflare = (secretsEndpointRefuses = true) => {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+ binding.type === "inherit"+ ? versions.get(binding.version_id!)!.bindings.find(({ name }) => name === binding.name)!+ : binding);// Holds only the upload that is in flight when the gate is set.const gate = uploadGate;uploadGate = undefined;await gate;- const uploaded = { ...body, id: `new-${created.size + 1}`, bindings };+ uploads += 1;+ const uploaded = { ...body, id: `new-${uploads}`, bindings };const version = alterStoredVersion ? alterStoredVersion(uploaded) : uploaded;- created.set(version.id, version);+ versions.set(version.id, version);base = version;return { data: { success: true, result: { id: version.id } } };});++ // Checked against the live API: neither the latest nor a deployed version can be deleted.+ del.mockImplementation(async (url: string) => {+ const id = url.split("/versions/")[1];+ if (id === base.id) throw cloudflareError(10339);+ versions.delete(id);+ return { data: { success: true } };+ });};const syncOf = (syncOptions: Record<string, unknown> = {}, id = "sync-id") =>@@ -133,7 +151,6 @@ describe("Cloudflare Workers version fallback", () => {beforeEach(() => {vi.clearAllMocks();base = pendingVersion();- created = new Map();uploadGate = undefined;alterStoredVersion = undefined;heldLocks.clear();@@ -203,7 +220,7 @@ describe("Cloudflare Workers version fallback", () => {const error = (await sync({ API_KEY: "new" }).catch((err: unknown) => err)) as SecretSyncError;expect(error).toBeInstanceOf(SecretSyncError);- expect(error.message).toContain("took longer than 5 minutes");+ expect(error.message).toContain("took longer than 60 seconds");expect(error.shouldRetry).toBe(false);});@@ -245,19 +262,69 @@ describe("Cloudflare Workers version fallback", () => {expect(heldLocks.size).toBe(0);});- it("fails, without exposing secret values, when the stored version doesn't match the upload", async () => {- installFakeCloudflare();- alterStoredVersion = (version) => ({+ describe("when Cloudflare stores a version different from the upload", () => {+ const tamper = (version: TVersion): TVersion => ({...version,bindings: version.bindings.filter(({ name }) => name !== "CACHE"),modules: [{ name: "index.js", content_type: "application/javascript+module", content_base64: "Y2hhbmdlZA==" }]});+ const tamperFirstUpload = () => {+ alterStoredVersion = (version) => {+ alterStoredVersion = undefined;+ return tamper(version);+ };+ };++ it("replaces it with an unchanged copy of the base and deletes it", async () => {+ installFakeCloudflare();+ tamperFirstUpload();++ const error = (await sync({ API_KEY: "s3cr3t-value" }).catch((err: unknown) => err)) as Error;++ expect(error).toBeInstanceOf(SecretSyncError);+ expect(error.message).toContain("CACHE");+ expect(error.message).toContain("index.js");+ expect(error.message).toContain("deleted that version");+ expect(error.message).not.toContain("s3cr3t-value");++ const [, [, restore]] = versionCreates();+ expect(restore.modules).toEqual(pendingVersion().modules);+ expect(+ restore.bindings.every(({ type, version_id: versionId }) => type === "inherit" && versionId === "v21")+ ).toBe(true);+ expect(versions.has("new-1")).toBe(false);+ expect(base.id).toBe("new-2");+ });++ it("tells the user not to deploy either version when the restored copy is also different", async () => {+ installFakeCloudflare();+ alterStoredVersion = tamper;++ await expect(sync({ API_KEY: "new" })).rejects.toThrow("Don't deploy either version");+ expect(del).not.toHaveBeenCalled();+ });++ it("tells the user not to deploy the rejected version when it can't be deleted", async () => {+ installFakeCloudflare();+ tamperFirstUpload();+ del.mockRejectedValueOnce(new AxiosError("socket hang up", "ECONNRESET"));++ await expect(sync({ API_KEY: "new" })).rejects.toThrow("couldn't delete the rejected version new-1");+ expect(base.id).toBe("new-2");+ });+ });++ it("doesn't retry the sync when reading back the uploaded version fails", async () => {+ installFakeCloudflare();+ const readVersion = get.getMockImplementation() as (url: string) => Promise<unknown>;+ get.mockImplementation(async (url: string) => {+ if (url.endsWith("/versions/new-1")) throw new AxiosError("timeout of 60000ms exceeded", "ECONNABORTED");+ return readVersion(url);+ });- const error = (await sync({ API_KEY: "s3cr3t-value" }).catch((err: unknown) => err)) as Error;+ const error = (await sync({ API_KEY: "new" }).catch((err: unknown) => err)) as SecretSyncError;expect(error).toBeInstanceOf(SecretSyncError);- expect(error.message).toContain("CACHE");- expect(error.message).toContain("index.js");- expect(error.message).not.toContain("s3cr3t-value");+ expect(error.shouldRetry).toBe(false);});});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.tsindex 8e7fe69795..6a005ab241 100644--- 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.ts@@ -1,5 +1,4 @@import { isAxiosError } from "axios";-import pLimit from "p-limit";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { request } from "@app/lib/config/request";@@ -7,17 +6,23 @@ 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 { TSecretMap, TSyncSecretsResult } from "@app/services/secret-sync/secret-sync-types";+import { planSyncBindings, TWrittenBinding } from "./cloudflare-workers-binding-fns";import { getCloudflareErrors, 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;+// A fallback moves the Worker's whole bundle each way (up to ~85 MB of base64), so only a few run at once. A job+// that finds them all busy is retried instead of waiting, since waiting counts against its lock.+const MAX_CONCURRENT_FALLBACKS = 2;+let activeFallbacks = 0;+// The three requests together stay well inside the sync job's 5-minute lock, so a second job for the same sync can't+// start while one is still uploading.+const VERSION_REQUEST_TIMEOUT_MS = 60 * 1000;const MAX_VERSION_PAYLOAD_BYTES = 128 * 1024 * 1024;-// Outlives the three version requests made under the lock (read, upload, read back) at their longest.-const WORKER_LOCK_DURATION_MS = 3 * VERSION_REQUEST_TIMEOUT_MS + 60 * 1000;+// Outlives the version requests made under the lock at their longest: read, upload and read back, then the same three+// again to restore the base and a delete if Cloudflare stored something other than what was uploaded.+const WORKER_LOCK_DURATION_MS = 7 * VERSION_REQUEST_TIMEOUT_MS + 60 * 1000;// Read as the reason in $fail's message, for the errors a copied version can run into.const CLOUDFLARE_ERROR_REASONS: Record<number, string> = {@@ -40,15 +45,8 @@ type TWorkerVersion = {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[] };+// The sync whose secrets a new version applies. Without one, the new version is an unchanged copy of its base.+type TSecretChanges = { secretSync: TCloudflareWorkersSyncWithCredentials; secretMap: TSecretMap };type TFallbackContext = {syncId: string;@@ -106,7 +104,7 @@ const $throwRequestError = (scriptId: string, err: unknown, { canRetry }: { canRthrow $fail(scriptId,isTimeout- ? `the request to Cloudflare took longer than ${VERSION_REQUEST_TIMEOUT_MS / 60000} minutes`+ ? `the request to Cloudflare took longer than ${VERSION_REQUEST_TIMEOUT_MS / 1000} seconds`: "Infisical couldn't reach Cloudflare","Sync again.",// A retried upload can't be told apart from a new one, so only reads are retried.@@ -127,7 +125,13 @@ const $hashModule = ({ content_type: contentType, content_base64: contentBase64const $hashModules = (modules: TVersionModule[]) =>new Map(modules.map((module) => [module.name, $hashModule(module)]));-const $getVersion = async ({ scriptId, accountUrl, headers }: TFallbackContext, versionRef: string) => {+// A read that follows an upload isn't retried: the job's retry would upload another version on top of the one+// that was never checked.+const $getVersion = async (+ { scriptId, accountUrl, headers }: TFallbackContext,+ versionRef: string,+ { canRetry = true }: { canRetry?: boolean } = {}+) => {try {const { data } = await request.get<{ result: TWorkerVersion }>(`${accountUrl}/workers/workers/${scriptId}/versions/${versionRef}`,@@ -140,7 +144,7 @@ const $getVersion = async ({ scriptId, accountUrl, headers }: TFallbackContext,);return data.result;} catch (err) {- return $throwRequestError(scriptId, err, { canRetry: true });+ return $throwRequestError(scriptId, err, { canRetry });}};@@ -168,7 +172,8 @@ const $validateBaseVersion = (scriptId: string, base: TWorkerVersion) => {const $createVersion = async (ctx: TFallbackContext,baseVersionRef: string,- planBindings: (baseBindings: TVersionBinding[]) => TBindingPlan+ changes: TSecretChanges | undefined,+ { message }: { message: (baseVersionId: string) => string }) => {const base = await $getVersion(ctx, baseVersionRef);$validateBaseVersion(ctx.scriptId, base);@@ -177,9 +182,11 @@ const $createVersion = async (// 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);+ const plan = changes+ ? planSyncBindings(changes.secretSync, changes.secretMap, baseBindings)+ : { written: [], dropped: [] };- if (!plan.written.length && !plan.dropped.length) return null;+ if (changes && !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);@@ -231,7 +238,7 @@ const $createVersion = async (bindings,annotations: {"workers/tag": "infisical-sync",- "workers/message": `Infisical secret sync (fallback, base ${baseVersionId})`+ "workers/message": message(baseVersionId)}},{@@ -268,8 +275,9 @@ const $createVersion = async (};};-const $verifyVersion = async (ctx: TFallbackContext, newVersionId: string, expected: TExpectedVersion) => {- const created = await $getVersion(ctx, newVersionId);+// Compares the version Cloudflare stored with what was uploaded: binding names and types, and every module's code.+const $findDifferences = async (ctx: TFallbackContext, newVersionId: string, expected: TExpectedVersion) => {+ const created = await $getVersion(ctx, newVersionId, { canRetry: false });const differences: string[] = [];const actualBindings = (created.bindings ?? []).map($bindingLabel);@@ -285,82 +293,175 @@ const $verifyVersion = async (ctx: TFallbackContext, newVersionId: string, expec);if (changedModules.length) differences.push(`different modules ${changedModules.join(", ")}`);+ return differences;+};++const $uploadCheckedVersion = async (+ ctx: TFallbackContext,+ baseVersionRef: string,+ changes: TSecretChanges | undefined,+ options: Parameters<typeof $createVersion>[3]+) => {+ const created = await $createVersion(ctx, baseVersionRef, changes, options);+ if (!created) return null;++ const differences = await $findDifferences(ctx, created.newVersionId, created.expected);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("; ")}]`+ `SecretSync Cloudflare Workers fallback version mismatch [syncId=${ctx.syncId}] [scriptId=${ctx.scriptId}] [baseVersionId=${created.expected.baseVersionId}] [newVersionId=${created.newVersionId}] [differences=${differences.join("; ")}]`+ );+ }++ return { ...created, differences };+};++const $deleteVersion = async ({ scriptId, accountUrl, headers }: TFallbackContext, versionId: string) => {+ try {+ const { data } = await request.delete<{ success?: boolean }>(+ `${accountUrl}/workers/workers/${scriptId}/versions/${versionId}`,+ { headers });+ validateCloudflareResponse(data);+ } catch (err) {+ if (err instanceof SecretSyncError) throw err;+ $throwRequestError(scriptId, err, { canRetry: false });+ }+};++// A rejected version is the latest, so the next sync would build on it, and Cloudflare refuses to delete the latest+// version. An unchanged copy of the base takes its place first, after which the rejected version can be deleted.+// Returns whether the rejected version was deleted.+const $replaceRejectedVersion = async (ctx: TFallbackContext, rejectedVersionId: string, baseVersionId: string) => {+ const restored = await $uploadCheckedVersion(ctx, baseVersionId, undefined, {+ message: () => `Infisical secret sync (restores ${baseVersionId} in place of rejected ${rejectedVersionId})`+ });++ if (restored?.differences.length) {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."+ `Cloudflare stored versions ${rejectedVersionId} and ${restored.newVersionId} differently from what Infisical uploaded (${restored.differences.join("; ")})`,+ "Don't deploy either version, and contact support."+ );+ }++ try {+ await $deleteVersion(ctx, rejectedVersionId);+ return true;+ } catch (err) {+ logger.warn(+ err,+ `SecretSync Cloudflare Workers failed to delete rejected version [syncId=${ctx.syncId}] [scriptId=${ctx.scriptId}] [versionId=${rejectedVersionId}]`);+ return false;}};// 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 = (+const $applySecretsWithVersionFallback = async (secretSync: TCloudflareWorkersSyncWithCredentials,- keyStore: Pick<TKeyStoreFactory, "acquireLock">,- planBindings: (baseBindings: TVersionBinding[]) => TBindingPlan-) =>- fallbackLimit(async (): Promise<TSyncSecretsResult | undefined> => {- const {- id: syncId,- connection: {- credentials: { apiToken, accountId }- },- destinationConfig: { scriptId }- } = secretSync;+ secretMap: TSecretMap,+ keyStore: Pick<TKeyStoreFactory, "acquireLock">+): 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"+ }+ };- 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}]`+ );- logger.info(- `SecretSync Cloudflare Workers latest version not deployed, using fallback [syncId=${syncId}] [scriptId=${scriptId}]`+ // Each sync builds on the latest version, so two syncs to one Worker reading it at once would each upload a+ // copy missing the other's changes. The lock is per Worker because syncs only lock themselves.+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;+ try {+ lock = await keyStore.acquireLock(+ [KeyStorePrefixes.CloudflareWorkerVersionLock(accountId, scriptId)],+ WORKER_LOCK_DURATION_MS);+ } catch {+ throw $fail(+ scriptId,+ "another sync was adding secrets to a new version of the same Worker",+ "Infisical retries the sync automatically. If it keeps failing, sync again later.",+ { shouldRetry: true }+ );+ }- // Each sync builds on the latest version, so two syncs to one Worker reading it at once would each upload a- // copy missing the other's changes. The lock is per Worker because syncs only lock themselves.- let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;- try {- lock = await keyStore.acquireLock(- [KeyStorePrefixes.CloudflareWorkerVersionLock(accountId, scriptId)],- WORKER_LOCK_DURATION_MS- );- } catch {+ try {+ const created = await $uploadCheckedVersion(+ ctx,+ "latest",+ { secretSync, secretMap },+ {+ message: (baseVersionId) => `Infisical secret sync (fallback, base ${baseVersionId})`+ }+ );+ if (!created) return undefined;++ if (created.differences.length) {+ const {+ newVersionId,+ expected: { baseVersionId }+ } = created;+ const deleted = await $replaceRejectedVersion(ctx, newVersionId, baseVersionId);throw $fail(scriptId,- "another sync was adding secrets to a new version of the same Worker",- "Infisical retries the sync automatically. If it keeps failing, sync again later.",- { shouldRetry: true }+ `Cloudflare stored the new version differently from what Infisical uploaded (${created.differences.join("; ")})`,+ deleted+ ? `Infisical deleted that version and made an unchanged copy of version ${baseVersionId} the latest. Sync again, and contact support if this keeps happening.`+ : `Infisical made an unchanged copy of version ${baseVersionId} the latest, but couldn't delete the rejected version ${newVersionId}. Don't deploy it. Sync again, and contact support if this keeps happening.`);}- try {- 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.`- };- } finally {- // A release that fails (the lock already expired) mustn't turn a finished sync into a failed one.- await lock.release().catch((err: unknown) => {- logger.warn(- err,- `SecretSync Cloudflare Workers failed to release Worker lock [syncId=${syncId}] [scriptId=${scriptId}]`- );- });- }- });+ return {+ ...created.result,+ message: `Worker has undeployed changes; created version ${created.newVersionId} with updated secrets. Deploy it for the secrets to take effect.`+ };+ } finally {+ // A release that fails (the lock already expired) mustn't turn a finished sync into a failed one.+ await lock.release().catch((err: unknown) => {+ logger.warn(+ err,+ `SecretSync Cloudflare Workers failed to release Worker lock [syncId=${syncId}] [scriptId=${scriptId}]`+ );+ });+ }+};++export const applySecretsWithVersionFallback = async (+ secretSync: TCloudflareWorkersSyncWithCredentials,+ secretMap: TSecretMap,+ keyStore: Pick<TKeyStoreFactory, "acquireLock">+) => {+ if (activeFallbacks >= MAX_CONCURRENT_FALLBACKS) {+ throw $fail(+ secretSync.destinationConfig.scriptId,+ "Infisical was already building as many Worker versions as it builds at once",+ "Infisical retries the sync automatically. If it keeps failing, sync again later.",+ { shouldRetry: true }+ );+ }++ activeFallbacks += 1;+ try {+ return await $applySecretsWithVersionFallback(secretSync, secretMap, keyStore);+ } finally {+ activeFallbacks -= 1;+ }+};