Skip to content

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

feat(secret-sync): preview recursive-sync name conflicts before create

Calvin118df109e633
diff --git a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-endpoints.ts b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-endpoints.ts
index b6dd90a9f3..2556a8eb0d 100644
--- a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-endpoints.ts
+++ b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-endpoints.ts
@@ -2,8 +2,9 @@ import { z } from "zod";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, SecretSyncs } from "@app/lib/api-docs";
-import { startsWithVowel } from "@app/lib/fn";
+import { removeTrailingSlash, startsWithVowel } from "@app/lib/fn";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -541,4 +542,45 @@ export const registerSyncSecretsEndpoints = <T extends TSecretSync, I extends TS
return result;
}
});
+
+ // Destination-agnostic: flatten() never uses the destination or source folder path to build a
+ // key, so this is safe to call from the Source step before a destination is even chosen.
+ server.route({
+ method: "POST",
+ url: "/recursive-conflicts",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: `check${destinationNameForOpId}SecretSyncRecursiveConflicts`,
+ tags: [ApiDocsTags.SecretSyncs],
+ body: z.object({
+ projectId: z.string().uuid(),
+ environment: slugSchema({ field: "environment", max: 64 }),
+ secretPath: z.string().trim().min(1, "Secret path required").transform(removeTrailingSlash),
+ keySchema: z.string().trim().max(255).optional()
+ }),
+ response: {
+ 200: z.object({
+ conflicts: z.array(
+ z.object({
+ key: z.string(),
+ paths: z.array(z.string())
+ })
+ )
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { projectId, environment, secretPath, keySchema } = req.body;
+
+ const result = await server.services.secretSync.findRecursiveConflicts(
+ { projectId, environment, secretPath, keySchema },
+ req.permission
+ );
+
+ return result;
+ }
+ });
};
diff --git a/backend/src/services/secret-sync/secret-sync-payload.test.ts b/backend/src/services/secret-sync/secret-sync-payload.test.ts
index 3ac2d28068..8bef7e12b0 100644
--- a/backend/src/services/secret-sync/secret-sync-payload.test.ts
+++ b/backend/src/services/secret-sync/secret-sync-payload.test.ts
@@ -1,4 +1,9 @@
-import { createSecretSyncPayload, dedupeEntriesByDestinationKey, TSecretPayload } from "./secret-sync-payload";
+import {
+ createSecretSyncPayload,
+ dedupeEntriesByDestinationKey,
+ findFlattenConflicts,
+ TSecretPayload
+} from "./secret-sync-payload";
const secret = (key: string, path: string, value = "v"): TSecretPayload => ({ key, path, value });
@@ -84,6 +89,43 @@ describe("createSecretSyncPayload", () => {
});
});
+describe("findFlattenConflicts", () => {
+ test("returns every conflict, uncapped, unlike flatten()'s thrown message", () => {
+ const secrets = Array.from({ length: 7 }, (_, i) => [secret(`K${i}`, "/"), secret(`K${i}`, "/api")]).flat();
+
+ const conflicts = findFlattenConflicts({ secrets, environment: "dev" });
+
+ expect(conflicts).toHaveLength(7);
+ expect(conflicts.map((c) => c.key).sort()).toEqual(["K0", "K1", "K2", "K3", "K4", "K5", "K6"]);
+ });
+
+ test("reports the destination key and every path it appears in", () => {
+ const conflicts = findFlattenConflicts({
+ secrets: [secret("DB_URL", "/backend"), secret("DB_URL", "/backend/api")],
+ environment: "dev"
+ });
+
+ expect(conflicts).toEqual([{ key: "DB_URL", paths: ["/backend", "/backend/api"] }]);
+ });
+
+ test("returns an empty array when there are no conflicts", () => {
+ expect(findFlattenConflicts({ secrets: [secret("DB_URL", "/")], environment: "dev" })).toEqual([]);
+ });
+
+ test("applySchema: false reports raw-key collisions instead of schema-applied ones", () => {
+ const conflicts = findFlattenConflicts(
+ {
+ secrets: [secret("DB_URL", "/backend"), secret("DB_URL", "/backend/api")],
+ environment: "dev",
+ keySchema: "{{environment}}_{{secretKey}}"
+ },
+ { applySchema: false }
+ );
+
+ expect(conflicts).toEqual([{ key: "DB_URL", paths: ["/backend", "/backend/api"] }]);
+ });
+});
+
describe("dedupeEntriesByDestinationKey", () => {
test("keeps one entry per destination key when two folders share a name", () => {
const deduped = dedupeEntriesByDestinationKey([secret("DB_URL", "/backend"), secret("DB_URL", "/backend/api")], {
diff --git a/backend/src/services/secret-sync/secret-sync-payload.ts b/backend/src/services/secret-sync/secret-sync-payload.ts
index 67f705ad7a..00684d68b0 100644
--- a/backend/src/services/secret-sync/secret-sync-payload.ts
+++ b/backend/src/services/secret-sync/secret-sync-payload.ts
@@ -17,9 +17,15 @@ export type TSecretPayload = {
export type TSecretSyncPayload = {
secrets: TSecretPayload[];
environment: string;
+ keySchema?: string;
flatten: (opts?: { applySchema?: boolean }) => TSecretMap;
};
+export type TSecretSyncConflict = {
+ key: string;
+ paths: string[];
+};
+
export const getKeyWithSchema = ({
key,
environment,
@@ -37,19 +43,43 @@ export const getKeyWithSchema = ({
});
};
-const buildConflictError = (conflicts: [string, TSecretPayload[]][]) => {
+const groupByDestinationKey = (
+ { secrets, environment }: Pick<TSecretSyncPayload, "secrets" | "environment">,
+ schema?: string
+): Map<string, TSecretPayload[]> => {
+ const grouped = new Map<string, TSecretPayload[]>();
+
+ for (const entry of secrets) {
+ const destinationKey = getKeyWithSchema({ key: entry.key, environment, schema });
+ const group = grouped.get(destinationKey);
+
+ if (group) group.push(entry);
+ else grouped.set(destinationKey, [entry]);
+ }
+
+ return grouped;
+};
+
+// 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.
+export const findFlattenConflicts = (
+ payload: Pick<TSecretSyncPayload, "secrets" | "environment" | "keySchema">,
+ { applySchema = true }: { applySchema?: boolean } = {}
+): TSecretSyncConflict[] => {
+ const schema = applySchema ? payload.keySchema : undefined;
+ const grouped = groupByDestinationKey(payload, schema);
+
+ return [...grouped.entries()]
+ .filter(([, group]) => group.length > 1)
+ .map(([key, group]) => ({ key, paths: group.map((entry) => entry.path).sort() }));
+};
+
+const buildConflictError = (conflicts: TSecretSyncConflict[]) => {
const shown = conflicts.slice(0, MAX_REPORTED_KEY_CONFLICTS);
const remainder = conflicts.length - shown.length;
- const detail = shown
- .map(
- ([key, group]) =>
- `"${key}" in ${group
- .map((entry) => entry.path)
- .sort()
- .join(" and ")}`
- )
- .join("; ");
+ const detail = shown.map(({ key, paths }) => `"${key}" in ${paths.join(" and ")}`).join("; ");
return new SecretSyncError({
message: `This destination stores secrets in a single flat list, so each name can be used only once. These names are used in more than one folder: ${detail}${
@@ -91,6 +121,7 @@ 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
@@ -98,21 +129,12 @@ export const createSecretSyncPayload = (
// groups by the resulting destination key and rejects collisions, so duplicate-name detection
// never depends on whether the schema was applied.
flatten: ({ applySchema = true }: { applySchema?: boolean } = {}) => {
- const schema = applySchema ? keySchema : undefined;
- const grouped = new Map<string, TSecretPayload[]>();
-
- for (const entry of secrets) {
- const destinationKey = getKeyWithSchema({ key: entry.key, environment, schema });
- const group = grouped.get(destinationKey);
-
- if (group) group.push(entry);
- else grouped.set(destinationKey, [entry]);
- }
-
- const conflicts = [...grouped.entries()].filter(([, group]) => group.length > 1);
+ const conflicts = findFlattenConflicts({ secrets, environment, keySchema }, { applySchema });
if (conflicts.length) throw buildConflictError(conflicts);
+ const schema = applySchema ? keySchema : undefined;
+ const grouped = groupByDestinationKey({ secrets, environment }, schema);
const map: TSecretMap = {};
for (const [destinationKey, [entry]] of grouped) {
diff --git a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts b/backend/src/services/secret-sync/secret-sync-recursive-fns.ts
index 409fb6bd92..8b6960925f 100644
--- a/backend/src/services/secret-sync/secret-sync-recursive-fns.ts
+++ b/backend/src/services/secret-sync/secret-sync-recursive-fns.ts
@@ -36,7 +36,10 @@ export const getAncestorPaths = (path: string): string[] => {
return segments.map((_, index) => (index === 0 ? "/" : `/${segments.slice(0, index).join("/")}`));
};
-export const SECRET_SYNC_MAX_SECRETS = 10_000;
+// buildSyncPayload expands secret references for every secret concurrently
+// (Promise.allSettled below), and expansion can hit the DB per secret. Kept low against a
+// 10-connection pool; raise it if customers need more room and the concurrency is bounded first.
+export const SECRET_SYNC_MAX_SECRETS = 100;
export const assertWithinSecretLimit = (count: number) => {
if (count <= SECRET_SYNC_MAX_SECRETS) return;
diff --git a/backend/src/services/secret-sync/secret-sync-service.ts b/backend/src/services/secret-sync/secret-sync-service.ts
index f98cd82e1f..0aaf0109da 100644
--- a/backend/src/services/secret-sync/secret-sync-service.ts
+++ b/backend/src/services/secret-sync/secret-sync-service.ts
@@ -35,12 +35,14 @@ 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,
TCheckDuplicateDestinationDTO,
TCreateSecretSyncDTO,
TDeleteSecretSyncDTO,
+ TFindRecursiveSyncConflictsDTO,
TFindSecretSyncByIdDTO,
TFindSecretSyncByNameDTO,
TListSecretSyncsByFolderId,
@@ -271,6 +273,103 @@ export const secretSyncServiceFactory = ({
}
};
+ // Lets the frontend check for duplicate-name conflicts while the user is still on the Source
+ // step, before a provider or destination is even chosen: the check is destination-agnostic
+ // (flatten() never uses the destination or the source folder path to build a key), so nothing
+ // downstream can change the answer. Returns every conflict, untruncated, unlike the
+ // BadRequestError $assertSyncableAtDestination throws at create/update time.
+ const findRecursiveConflicts = async (
+ { projectId, environment, secretPath, keySchema }: TFindRecursiveSyncConflictsDTO,
+ actor: OrgServiceActor
+ ) => {
+ const { permission: projectPermission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.SecretManager,
+ projectId
+ });
+
+ ForbiddenError.from(projectPermission).throwUnlessCan(
+ ProjectPermissionSecretSyncActions.Read,
+ ProjectPermissionSub.SecretSyncs
+ );
+
+ const folder = await folderDAL.findBySecretPath(projectId, environment, secretPath);
+
+ if (!folder)
+ throw new BadRequestError({
+ message: `Could not find folder with path "${secretPath}" in environment "${environment}" for project with ID "${projectId}"`
+ });
+
+ await $assertCanReadSyncedFolders(projectPermission, {
+ projectId,
+ environment,
+ sourcePath: secretPath,
+ sourceFolderId: folder.id,
+ 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,
+ projectId,
+ canExpandValue: () => true,
+ actorOrgId: actor.orgId,
+ orgDAL,
+ licenseService,
+ projectFolderGrantDAL,
+ projectDAL,
+ kmsService
+ });
+
+ 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;
+ }
+ };
+
const listSecretSyncsByProjectId = async (
{ projectId, destination }: TListSecretSyncsByProjectId,
actor: OrgServiceActor
@@ -1130,6 +1229,7 @@ export const secretSyncServiceFactory = ({
triggerSecretSyncSyncSecretsById,
triggerSecretSyncImportSecretsById,
triggerSecretSyncRemoveSecretsById,
- checkDuplicateDestination
+ checkDuplicateDestination,
+ findRecursiveConflicts
};
};
diff --git a/backend/src/services/secret-sync/secret-sync-types.ts b/backend/src/services/secret-sync/secret-sync-types.ts
index cadb9505a3..a878de7147 100644
--- a/backend/src/services/secret-sync/secret-sync-types.ts
+++ b/backend/src/services/secret-sync/secret-sync-types.ts
@@ -499,6 +499,13 @@ export type TCheckDuplicateDestinationDTO = {
projectId: string;
};
+export type TFindRecursiveSyncConflictsDTO = {
+ projectId: string;
+ environment: string;
+ secretPath: string;
+ keySchema?: string;
+};
+
export enum SecretSyncStatus {
Pending = "pending",
Running = "running",
diff --git a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx
index 16f9467ebe..d7631ac5f2 100644
--- a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx
+++ b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx
@@ -34,6 +34,7 @@ import {
TSecretSync,
useCreateSecretSync,
useDuplicateDestinationCheck,
+ useRecursiveConflictsCheck,
useSecretSyncOption
} from "@app/hooks/api/secretSyncs";
@@ -226,12 +227,26 @@ export const CreateSecretSyncForm = ({
initialSyncBehavior === SecretSyncInitialSyncBehavior.OverwriteDestination &&
!disableSecretDeletion &&
!keySchema;
+ const importsFromDestination =
+ initialSyncBehavior === SecretSyncInitialSyncBehavior.ImportPrioritizeSource ||
+ initialSyncBehavior === SecretSyncInitialSyncBehavior.ImportPrioritizeDestination;
+
+ const { conflicts: recursiveConflicts } = useRecursiveConflictsCheck({
+ destination,
+ projectId: currentProject?.id || "",
+ environment: watch("environment")?.slug,
+ secretPath: watch("secretPath"),
+ keySchema,
+ recursive: Boolean(watch("syncOptions.recursive")) && !importsFromDestination
+ });
const isStepValid = async (index: number) => trigger(formTabs[index].fields);
const isFinalStep = selectedTabIndex === formTabs.length - 1;
- const isCreateButtonDisabled =
- isFinalStep && hasDuplicate && currentOrg?.blockDuplicateSecretSyncDestinations;
+ const isSourceStep = selectedTabIndex === 0;
+ const isNextButtonDisabled =
+ (isFinalStep && hasDuplicate && currentOrg?.blockDuplicateSecretSyncDestinations) ||
+ (isSourceStep && recursiveConflicts.length > 0);
const handleNext = async () => {
if (isFinalStep) {
@@ -239,6 +254,8 @@ export const CreateSecretSyncForm = ({
return;
}
+ if (isSourceStep && recursiveConflicts.length > 0) return;
+
const isValid = await isStepValid(selectedTabIndex);
if (!isValid) return;
@@ -267,6 +284,10 @@ export const CreateSecretSyncForm = ({
return;
}
+ // The Source step (index 0) is always behind a forward jump, since targetTab > selectedTabIndex
+ // here, so a conflict there must block the jump the same way it blocks handleNext.
+ if (recursiveConflicts.length > 0) return;
+
let canJump = true;
for (let i = selectedTabIndex; i < targetTab; i += 1) {
// eslint-disable-next-line no-await-in-loop
@@ -390,7 +411,7 @@ export const CreateSecretSyncForm = ({
<Button variant="outline" onClick={handlePrev}>
Back
</Button>
- <Button variant="project" onClick={handleNext} isDisabled={isCreateButtonDisabled}>
+ <Button variant="project" onClick={handleNext} isDisabled={isNextButtonDisabled}>
{isFinalStep ? "Create Sync" : "Continue"}
</Button>
</div>
diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx
index 05c21cc167..cf6bb628a4 100644
--- a/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx
+++ b/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx
@@ -1,8 +1,12 @@
import { useEffect } from "react";
import { Controller, useFormContext, useWatch } from "react-hook-form";
import { subject } from "@casl/ability";
+import { CheckCircle2, TriangleAlert } from "lucide-react";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Field,
FieldContent,
FieldDescription,
@@ -19,26 +23,45 @@ import {
ProjectPermissionSecretSyncActions,
ProjectPermissionSub
} from "@app/context/ProjectPermissionContext/types";
-import { SecretSync, SecretSyncInitialSyncBehavior } from "@app/hooks/api/secretSyncs";
+import {
+ SecretSync,
+ SecretSyncInitialSyncBehavior,
+ useRecursiveConflictsCheck
+} from "@app/hooks/api/secretSyncs";
import { AzureEntraIdScimSyncSourceFields } from "./AzureEntraIdScimSyncSourceFields";
import { TSecretSyncForm } from "./schemas";
+// Mirrors SECRET_SYNC_MAX_SECRETS in backend/src/services/secret-sync/secret-sync-recursive-fns.ts.
+const SECRET_SYNC_MAX_SECRETS = 100;
+const MAX_DISPLAYED_CONFLICTS = 5;
+
const DefaultSecretSyncSourceFields = () => {
const { control, watch, setValue, setError, clearErrors } = useFormContext<TSecretSyncForm>();
const { permission } = useProjectPermission();
const { currentProject } = useProject();
+ const destination = watch("destination");
const selectedEnvironment = watch("environment");
const selectedSecretPath = watch("secretPath");
const initialSyncBehavior = watch("syncOptions.initialSyncBehavior");
const recursive = watch("syncOptions.recursive");
+ const keySchema = watch("syncOptions.keySchema");
const importsFromDestination =
initialSyncBehavior === SecretSyncInitialSyncBehavior.ImportPrioritizeSource ||
initialSyncBehavior === SecretSyncInitialSyncBehavior.ImportPrioritizeDestination;
+ const { conflicts, isChecking, isClear } = useRecursiveConflictsCheck({
+ destination,
+ projectId: currentProject.id,
+ environment: selectedEnvironment?.slug,
+ secretPath: selectedSecretPath,
+ keySchema,
+ recursive: Boolean(recursive) && !importsFromDestination
+ });
+
useEffect(() => {
if (!selectedEnvironment) {
clearErrors("secretPath");
@@ -118,11 +141,11 @@ const DefaultSecretSyncSourceFields = () => {
<Field>
<Field orientation="horizontal">
<FieldContent>
- <Label htmlFor="recursive">Include subfolders</Label>
+ <Label htmlFor="recursive">Recursively sync secrets</Label>
<FieldDescription>
{importsFromDestination
? "Not available when the initial sync imports secrets from the destination. There is no single folder to import them back into."
- : "Also sync secrets from every folder beneath this path. Secret names must be unique across those folders."}
+ : `Also sync secrets from every folder beneath this path, however deep. Secret names must be unique across all of them, and the combined total can't exceed ${SECRET_SYNC_MAX_SECRETS} secrets.`}
</FieldDescription>
</FieldContent>
<Switch
@@ -134,6 +157,50 @@ const DefaultSecretSyncSourceFields = () => {
/>
</Field>
<FieldError errors={[error]} />
+ {isChecking && (
+ <p className="text-sm text-muted">Checking for naming conflicts across folders...</p>
+ )}
+ {isClear && (
+ <p className="flex items-center gap-1.5 text-sm text-success">
+ <CheckCircle2 className="size-4" />
+ No naming collisions detected
+ </p>
+ )}
+ {!isChecking && conflicts.length > 0 && (
+ <Alert variant="danger">
+ <TriangleAlert />
+ <AlertTitle>
+ {conflicts.length === 1
+ ? "1 secret name conflicts across folders"
+ : `${conflicts.length} secret names conflict across folders`}
+ </AlertTitle>
+ <AlertDescription>
+ <p>
+ This destination stores secrets in a single flat list, so each name can be used
+ only once. Rename or move one secret in each pair, or point the sync at a
+ narrower secret path.
+ </p>
+ <ul className="mt-1 space-y-2">
+ {conflicts.slice(0, MAX_DISPLAYED_CONFLICTS).map((conflict) => (
+ <li key={conflict.key}>
+ <span className="font-mono font-semibold">&quot;{conflict.key}&quot;</span>{" "}
+ is used in {conflict.paths.length} folders:
+ <ul className="mt-0.5 list-inside list-disc">
+ {conflict.paths.map((path) => (
+ <li key={path} className="font-mono">
+ {path}
+ </li>
+ ))}
+ </ul>
+ </li>
+ ))}
+ </ul>
+ {conflicts.length > MAX_DISPLAYED_CONFLICTS && (
+ <p>and {conflicts.length - MAX_DISPLAYED_CONFLICTS} more</p>
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
</Field>
)}
/>
diff --git a/frontend/src/hooks/api/secretSyncs/index.ts b/frontend/src/hooks/api/secretSyncs/index.ts
index 0050bad8de..96f40b81d4 100644
--- a/frontend/src/hooks/api/secretSyncs/index.ts
+++ b/frontend/src/hooks/api/secretSyncs/index.ts
@@ -3,3 +3,4 @@ export * from "./mutations";
export * from "./queries";
export * from "./types";
export * from "./useDuplicateDestinationCheck";
+export * from "./useRecursiveConflictsCheck";
diff --git a/frontend/src/hooks/api/secretSyncs/queries.tsx b/frontend/src/hooks/api/secretSyncs/queries.tsx
index 2019902a69..445b37320b 100644
--- a/frontend/src/hooks/api/secretSyncs/queries.tsx
+++ b/frontend/src/hooks/api/secretSyncs/queries.tsx
@@ -28,9 +28,30 @@ export const secretSyncKeys = {
destinationConfig,
connectionId,
excludeSyncId
+ ] as const,
+ recursiveConflicts: (
+ destination: SecretSync,
+ projectId: string,
+ environment?: string,
+ secretPath?: string,
+ keySchema?: string
+ ) =>
+ [
+ ...secretSyncKeys.all,
+ destination,
+ "recursive-conflicts",
+ projectId,
+ environment,
+ secretPath,
+ keySchema
] as const
};
+export type TSecretSyncRecursiveConflict = {
+ key: string;
+ paths: string[];
+};
+
export const useSecretSyncOptions = (
options?: Omit<
UseQueryOptions<
@@ -143,3 +164,40 @@ export const useCheckDuplicateDestination = (
...options
});
};
+
+export const useCheckRecursiveConflicts = (
+ destination: SecretSync,
+ projectId: string,
+ environment?: string,
+ secretPath?: string,
+ keySchema?: string,
+ options?: Omit<
+ UseQueryOptions<
+ { conflicts: TSecretSyncRecursiveConflict[] },
+ unknown,
+ { conflicts: TSecretSyncRecursiveConflict[] },
+ ReturnType<typeof secretSyncKeys.recursiveConflicts>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: secretSyncKeys.recursiveConflicts(
+ destination,
+ projectId,
+ environment,
+ secretPath,
+ keySchema
+ ),
+ queryFn: async () => {
+ const { data } = await apiRequest.post<{ conflicts: TSecretSyncRecursiveConflict[] }>(
+ `/api/v1/secret-syncs/${destination}/recursive-conflicts`,
+ { projectId, environment, secretPath, keySchema }
+ );
+
+ return data;
+ },
+ enabled: Boolean(environment) && Boolean(secretPath),
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/secretSyncs/useRecursiveConflictsCheck.ts b/frontend/src/hooks/api/secretSyncs/useRecursiveConflictsCheck.ts
new file mode 100644
index 0000000000..58c9740c15
--- /dev/null
+++ b/frontend/src/hooks/api/secretSyncs/useRecursiveConflictsCheck.ts
@@ -0,0 +1,45 @@
+import { SecretSync, useCheckRecursiveConflicts } from "@app/hooks/api/secretSyncs";
+
+type UseRecursiveConflictsCheckProps = {
+ destination: SecretSync;
+ projectId: string;
+ environment?: string;
+ secretPath?: string;
+ keySchema?: string;
+ recursive: boolean;
+};
+
+export const useRecursiveConflictsCheck = ({
+ destination,
+ projectId,
+ environment,
+ secretPath,
+ keySchema,
+ recursive
+}: UseRecursiveConflictsCheckProps) => {
+ const shouldCheck = recursive && Boolean(environment) && Boolean(secretPath);
+
+ const { data, isLoading, isSuccess, error } = useCheckRecursiveConflicts(
+ destination,
+ projectId,
+ shouldCheck ? environment : undefined,
+ shouldCheck ? secretPath : undefined,
+ keySchema,
+ {
+ enabled: shouldCheck,
+ staleTime: 0,
+ gcTime: 0
+ }
+ );
+
+ const conflicts = shouldCheck ? (data?.conflicts ?? []) : [];
+
+ return {
+ conflicts,
+ isChecking: shouldCheck && isLoading,
+ // True once a check has actually completed and found nothing, so the caller can render a
+ // "no conflicts" success state distinct from "no check has run yet".
+ isClear: shouldCheck && isSuccess && conflicts.length === 0,
+ hasError: Boolean(error)
+ };
+};