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
refactor(secret-sync): dedupe the recursive-payload build path, keep keySchema private
Calvin3906488546af
diff --git a/backend/src/services/secret-sync/secret-sync-payload.test.ts b/backend/src/services/secret-sync/secret-sync-payload.test.tsindex 8bef7e12b0..ee86fb691a 100644--- a/backend/src/services/secret-sync/secret-sync-payload.test.ts+++ b/backend/src/services/secret-sync/secret-sync-payload.test.ts@@ -87,6 +87,31 @@ describe("createSecretSyncPayload", () => {expect(() => payload.flatten()).not.toThrow();});++ test("findConflicts() reports the same collisions as flatten() throws, without throwing", () => {+ const payload = createSecretSyncPayload([secret("DB_URL", "/backend"), secret("DB_URL", "/backend/api")], {+ environment: "dev"+ });++ expect(payload.findConflicts()).toEqual([{ key: "DB_URL", paths: ["/backend", "/backend/api"] }]);+ });++ test("findConflicts() returns an empty array when there are no conflicts", () => {+ const payload = createSecretSyncPayload([secret("DB_URL", "/")], { environment: "dev" });++ expect(payload.findConflicts()).toEqual([]);+ });++ test("findConflicts({ applySchema: false }) reports raw-key collisions instead of schema-applied ones", () => {+ const payload = createSecretSyncPayload([secret("DB_URL", "/backend"), secret("DB_URL", "/backend/api")], {+ environment: "dev",+ keySchema: "{{environment}}_{{secretKey}}"+ });++ expect(payload.findConflicts({ applySchema: false })).toEqual([+ { key: "DB_URL", paths: ["/backend", "/backend/api"] }+ ]);+ });});describe("findFlattenConflicts", () => {diff --git a/backend/src/services/secret-sync/secret-sync-payload.ts b/backend/src/services/secret-sync/secret-sync-payload.tsindex 00684d68b0..64e5efd61d 100644--- a/backend/src/services/secret-sync/secret-sync-payload.ts+++ b/backend/src/services/secret-sync/secret-sync-payload.ts@@ -17,8 +17,8 @@ export type TSecretPayload = {export type TSecretSyncPayload = {secrets: TSecretPayload[];environment: string;- keySchema?: string;flatten: (opts?: { applySchema?: boolean }) => TSecretMap;+ findConflicts: (opts?: { applySchema?: boolean }) => TSecretSyncConflict[];};export type TSecretSyncConflict = {@@ -61,10 +61,11 @@ const groupByDestinationKey = (};// Returns every destination-key collision, unordered and untruncated: the caller decides how much-// of this to show. The recursive-conflicts preview endpoint sends the full list so the UI can-// paginate/truncate it; flatten() below caps what it puts in a thrown error message.+// of this to show. findConflicts() below is the public way to reach this on a built payload; the+// recursive-conflicts preview endpoint calls that method, not this function directly, so+// keySchema never has to be a field the payload object exposes to its own callers.export const findFlattenConflicts = (- payload: Pick<TSecretSyncPayload, "secrets" | "environment" | "keySchema">,+ payload: { secrets: TSecretPayload[]; environment: string; keySchema?: string },{ applySchema = true }: { applySchema?: boolean } = {}): TSecretSyncConflict[] => {const schema = applySchema ? payload.keySchema : undefined;@@ -121,7 +122,6 @@ export const createSecretSyncPayload = (): TSecretSyncPayload => ({secrets,environment,- keySchema,// A destination whose sync targets can't carry the configured key schema (eg a many-to-one// JSON body whose fields are app-facing variable names, or an Infisical-to-Infisical sync,// where a schema-renamed key would look like a new secret and retrigger a sync cycle) calls@@ -147,5 +147,9 @@ export const createSecretSyncPayload = (}return map;- }+ },+ // keySchema itself is deliberately not a field on this object: nothing outside this module+ // needs to read it directly, and findConflicts() is how an external caller (the+ // recursive-conflicts preview endpoint) reaches the same check flatten() runs, without it.+ findConflicts: (opts) => findFlattenConflicts({ secrets, environment, keySchema }, opts)});diff --git a/backend/src/services/secret-sync/secret-sync-service.ts b/backend/src/services/secret-sync/secret-sync-service.tsindex 0aaf0109da..339cb9acdc 100644--- a/backend/src/services/secret-sync/secret-sync-service.ts+++ b/backend/src/services/secret-sync/secret-sync-service.ts@@ -35,7 +35,6 @@ import {preSaveTransformDestinationConfig,preSaveTransformSyncOptions} from "@app/services/secret-sync/secret-sync-fns";-import { findFlattenConflicts } from "@app/services/secret-sync/secret-sync-payload";import { buildSyncPayload, resolveSyncFolders } from "@app/services/secret-sync/secret-sync-recursive-fns";import {SecretSyncStatus,@@ -191,17 +190,27 @@ export const secretSyncServiceFactory = ({}};- // Flattening a subtree onto a destination that holds one flat list can produce two secrets with- // the same destination key. flatten() is what detects that, and the job runs it on every sync, so- // calling it here means a user reads the same sentence at save time and when the sync later drifts- // into the same state.- const $assertSyncableAtDestination = async ({+ // A SecretSyncError is written for the end user already (see secret-sync-payload.ts); every+ // caller that can surface one directly just needs it translated to the house error envelope.+ const $rethrowSecretSyncErrorsAsBadRequest = async <T>(fn: () => T | Promise<T>): Promise<T> => {+ try {+ return await fn();+ } catch (error) {+ if (error instanceof SecretSyncError) throw new BadRequestError({ message: error.message });++ throw error;+ }+ };++ // Shared by $assertSyncableAtDestination and findRecursiveConflicts: both need the same+ // decrypt-and-expand payload for the full recursive subtree, and differ only in what they do+ // with it once built (throw on the first conflict vs. report every conflict back).+ const $buildRecursiveSyncPayload = ({projectId,actorOrgId,environment,sourcePath,sourceFolderId,- recursive,keySchema}: {projectId: string;@@ -209,35 +218,32 @@ export const secretSyncServiceFactory = ({environment: string;sourcePath: string;sourceFolderId: string;- recursive: boolean;keySchema?: string;- }) => {- if (!recursive) return;-- const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });-- const decryptSecretValue = (value?: Buffer | null) =>- value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : "";+ }) =>+ $rethrowSecretSyncErrorsAsBadRequest(async () => {+ const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId+ });- const { expandSecretReferences } = expandSecretReferencesFactory({- decryptSecretValue,- secretDAL: secretV2BridgeDAL,- folderDAL,- projectId,- canExpandValue: () => true,- actorOrgId,- orgDAL,- licenseService,- projectFolderGrantDAL,- projectDAL,- kmsService- });+ const decryptSecretValue = (value?: Buffer | null) =>+ value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : "";++ const { expandSecretReferences } = expandSecretReferencesFactory({+ decryptSecretValue,+ secretDAL: secretV2BridgeDAL,+ folderDAL,+ projectId,+ canExpandValue: () => true,+ actorOrgId,+ orgDAL,+ licenseService,+ projectFolderGrantDAL,+ projectDAL,+ kmsService+ });- try {- const payload = await buildSyncPayload(+ return buildSyncPayload({folderDAL,projectEnvDAL,@@ -258,19 +264,47 @@ export const secretSyncServiceFactory = ({environment,sourcePath,sourceFolderId,- recursive,+ recursive: true,keySchema,includeImports: true,dedupeForRemoval: false});+ });- payload.flatten();- } catch (error) {- if (error instanceof SecretSyncError) throw new BadRequestError({ message: error.message });+ // Flattening a subtree onto a destination that holds one flat list can produce two secrets with+ // the same destination key. flatten() is what detects that, and the job runs it on every sync, so+ // calling it here means a user reads the same sentence at save time and when the sync later drifts+ // into the same state.+ const $assertSyncableAtDestination = async ({+ projectId,+ actorOrgId,+ environment,+ sourcePath,+ sourceFolderId,+ recursive,+ keySchema+ }: {+ projectId: string;+ actorOrgId: string;+ environment: string;+ sourcePath: string;+ sourceFolderId: string;+ recursive: boolean;+ keySchema?: string;+ }) => {+ if (!recursive) return;- throw error;- }+ const payload = await $buildRecursiveSyncPayload({+ projectId,+ actorOrgId,+ environment,+ sourcePath,+ sourceFolderId,+ keySchema+ });++ await $rethrowSecretSyncErrorsAsBadRequest(() => payload.flatten());};// Lets the frontend check for duplicate-name conflicts while the user is still on the Source@@ -311,63 +345,16 @@ export const secretSyncServiceFactory = ({recursive: true});- const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.SecretManager,- projectId- });-- const decryptSecretValue = (value?: Buffer | null) =>- value ? secretManagerDecryptor({ cipherTextBlob: value }).toString() : "";-- const { expandSecretReferences } = expandSecretReferencesFactory({- decryptSecretValue,- secretDAL: secretV2BridgeDAL,- folderDAL,+ const payload = await $buildRecursiveSyncPayload({projectId,- canExpandValue: () => true,actorOrgId: actor.orgId,- orgDAL,- licenseService,- projectFolderGrantDAL,- projectDAL,- kmsService+ environment,+ sourcePath: secretPath,+ sourceFolderId: folder.id,+ keySchema});- try {- const payload = await buildSyncPayload(- {- folderDAL,- projectEnvDAL,- secretV2BridgeDAL,- secretImportDAL,- expandSecretReferences,- decryptSecretValue,- fnSecretsV2FromImportsDeps: {- projectFolderGrantDAL,- actorOrgId: actor.orgId,- orgDAL,- licenseService,- kmsService- }- },- {- projectId,- environment,- sourcePath: secretPath,- sourceFolderId: folder.id,- recursive: true,- keySchema,- includeImports: true,- dedupeForRemoval: false- }- );-- return { conflicts: findFlattenConflicts(payload) };- } catch (error) {- if (error instanceof SecretSyncError) throw new BadRequestError({ message: error.message });-- throw error;- }+ return { conflicts: payload.findConflicts() };};const listSecretSyncsByProjectId = async (