Skip to content

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

fix(secret-sync): block copies that duplicate secret names in a sync

Calvin2afa48fdf86a
diff --git a/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsx b/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsx
index 609c53c73e..3767d618da 100644
--- a/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsx
+++ b/frontend/src/components/secret-syncs/SecretSyncMoveWarning.tsx
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { Link } from "@tanstack/react-router";
-import { ExternalLinkIcon, TriangleAlertIcon } from "lucide-react";
+import { CircleAlertIcon, ExternalLinkIcon, TriangleAlertIcon } from "lucide-react";
import { Alert, AlertDescription, AlertTitle, Checkbox, Label } from "@app/components/v3";
import { ROUTE_PATHS } from "@app/const/routes";
@@ -10,19 +10,24 @@ import { TItemMove } from "@app/helpers/secretSyncCoverage";
import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs";
import { TSecretSync, useListSecretSyncsCoveringMove } from "@app/hooks/api/secretSyncs";
+type TAcknowledgement = {
+ isRequired: boolean;
+ isAcknowledged: boolean;
+ setIsAcknowledged: (value: boolean) => void;
+};
+
export type TSecretSyncMoveWarning = {
secretSyncs: TSecretSync[];
+ duplicatedSecretSyncs: TSecretSync[];
isChecking: boolean;
hasError: boolean;
- needsAcknowledgement: boolean;
- isAcknowledged: boolean;
- setIsAcknowledged: (value: boolean) => void;
+ coverageAcknowledgement: TAcknowledgement;
isBlockingSubmit: boolean;
};
// remembers the warning the user ticked. it is cleared on any change, so returning to a warning ticked
// earlier asks again rather than carrying a yes over to syncs the user has not seen.
-const useAcknowledgement = (warningKey: string) => {
+const useAcknowledgement = (isRequired: boolean, warningKey: string): TAcknowledgement => {
const [acknowledgedWarningKey, setAcknowledgedWarningKey] = useState<string | null>(null);
useEffect(() => {
@@ -30,6 +35,7 @@ const useAcknowledgement = (warningKey: string) => {
}, [warningKey]);
return {
+ isRequired,
isAcknowledged: acknowledgedWarningKey === warningKey,
setIsAcknowledged: (value: boolean) => setAcknowledgedWarningKey(value ? warningKey : null)
};
@@ -38,7 +44,8 @@ const useAcknowledgement = (warningKey: string) => {
// intentionally warns only about syncs the user can read
export const useSecretSyncMoveWarning = (
projectId: string,
- moves: TItemMove[]
+ moves: TItemMove[],
+ { isCopy = false }: { isCopy?: boolean } = {}
): TSecretSyncMoveWarning => {
const { permission } = useProjectPermission();
const canReadSecretSyncs = permission.can(
@@ -47,30 +54,35 @@ export const useSecretSyncMoveWarning = (
);
const {
- data: fetchedSecretSyncs = [],
+ data,
isLoading: isChecking,
isError
} = useListSecretSyncsCoveringMove(projectId, moves, {
- enabled: canReadSecretSyncs && moves.length > 0
+ enabled: canReadSecretSyncs && moves.length > 0,
+ isCopy
});
// a disabled query keeps its last result, so a user whose read access is revoked mid-dialog must not
// keep seeing the syncs it listed
- const secretSyncs = canReadSecretSyncs ? fetchedSecretSyncs : [];
+ const secretSyncs = (canReadSecretSyncs && data?.newSecretSyncs) || [];
+ const duplicatedSecretSyncs = (canReadSecretSyncs && data?.duplicatedSecretSyncs) || [];
const hasError = canReadSecretSyncs && isError;
- const needsAcknowledgement = hasError || secretSyncs.length > 0;
- const { isAcknowledged, setIsAcknowledged } = useAcknowledgement(
+
+ const coverageAcknowledgement = useAcknowledgement(
+ hasError || secretSyncs.length > 0,
JSON.stringify({ moves, syncIds: secretSyncs.map(({ id }) => id), hasError })
);
return {
secretSyncs,
+ duplicatedSecretSyncs,
isChecking,
hasError,
- needsAcknowledgement,
- isAcknowledged,
- setIsAcknowledged,
- isBlockingSubmit: isChecking || (needsAcknowledgement && !isAcknowledged)
+ coverageAcknowledgement,
+ isBlockingSubmit:
+ isChecking ||
+ duplicatedSecretSyncs.length > 0 ||
+ (coverageAcknowledgement.isRequired && !coverageAcknowledgement.isAcknowledged)
};
};
@@ -101,18 +113,20 @@ const getTitle = ({
const SecretSyncMoveWarningItem = ({
sync,
orgId,
- projectId
+ projectId,
+ manualSyncNote
}: {
sync: TSecretSync;
orgId: string;
projectId: string;
+ manualSyncNote?: string;
}) => (
<li>
<span className="font-medium text-foreground">{sync.name}</span>
{` (${SECRET_SYNC_MAP[sync.destination].name}) syncs `}
<code>{sync.folder?.path ?? "/"}</code>
{sync.syncOptions.includeAllSubFolders ? " and all its subfolders." : "."}
- {!sync.isAutoSyncEnabled && " Auto-sync is off, so it sends them on its next manual sync."}{" "}
+ {manualSyncNote && !sync.isAutoSyncEnabled && ` Auto-sync is off, so ${manualSyncNote}.`}{" "}
<Link
to={ROUTE_PATHS.SecretManager.SecretSyncDetailsByIDPage.path}
params={{
@@ -131,42 +145,94 @@ const SecretSyncMoveWarningItem = ({
</li>
);
-export const SecretSyncMoveWarning = ({ warning, projectId, noun, verb }: Props) => {
+const SecretSyncMoveWarningList = ({
+ syncs,
+ projectId,
+ manualSyncNote
+}: {
+ syncs: TSecretSync[];
+ projectId: string;
+ manualSyncNote?: string;
+}) => {
const { currentOrg } = useOrganization();
- const { needsAcknowledgement, isChecking, hasError, secretSyncs } = warning;
- if (isChecking || !needsAcknowledgement) return null;
+ return (
+ <ul className="max-h-40 list-disc overflow-y-auto pl-4">
+ {syncs.map((sync) => (
+ <SecretSyncMoveWarningItem
+ key={sync.id}
+ sync={sync}
+ orgId={currentOrg.id}
+ projectId={projectId}
+ manualSyncNote={manualSyncNote}
+ />
+ ))}
+ </ul>
+ );
+};
+
+const AcknowledgementCheckbox = ({
+ id,
+ acknowledgement,
+ label
+}: {
+ id: string;
+ acknowledgement: TAcknowledgement;
+ label: string;
+}) => (
+ <div className="mt-2 flex items-center gap-2">
+ <Checkbox
+ id={id}
+ variant="warning"
+ isChecked={acknowledgement.isAcknowledged}
+ onCheckedChange={(checked) => acknowledgement.setIsAcknowledged(checked === true)}
+ />
+ <Label htmlFor={id}>{label}</Label>
+ </div>
+);
+
+export const SecretSyncMoveWarning = ({ warning, projectId, noun, verb }: Props) => {
+ const { isChecking, hasError, secretSyncs, duplicatedSecretSyncs, coverageAcknowledgement } =
+ warning;
+
+ if (isChecking) return null;
return (
- <Alert variant="warning">
- <TriangleAlertIcon />
- <AlertTitle>{getTitle({ noun, verb, count: secretSyncs.length, hasError })}</AlertTitle>
- <AlertDescription>
- {hasError && <p>Secret syncs may send these {noun} to external destinations.</p>}
- {secretSyncs.length > 0 && (
- <ul className="max-h-40 list-disc overflow-y-auto pl-4">
- {secretSyncs.map((sync) => (
- <SecretSyncMoveWarningItem
- key={sync.id}
- sync={sync}
- orgId={currentOrg.id}
+ <>
+ {coverageAcknowledgement.isRequired && (
+ <Alert variant="warning">
+ <TriangleAlertIcon />
+ <AlertTitle>{getTitle({ noun, verb, count: secretSyncs.length, hasError })}</AlertTitle>
+ <AlertDescription>
+ {hasError && <p>Secret syncs may send these {noun} to external destinations.</p>}
+ {secretSyncs.length > 0 && (
+ <SecretSyncMoveWarningList
+ syncs={secretSyncs}
projectId={projectId}
+ manualSyncNote="it sends them on its next manual sync"
/>
- ))}
- </ul>
- )}
- <div className="mt-2 flex items-center gap-2">
- <Checkbox
- id="secret-sync-move-warning-acknowledgement"
- variant="warning"
- isChecked={warning.isAcknowledged}
- onCheckedChange={(checked) => warning.setIsAcknowledged(checked === true)}
- />
- <Label htmlFor="secret-sync-move-warning-acknowledgement">
- I understand these {noun} {hasError ? "may" : "will"} be synced to external destinations
- </Label>
- </div>
- </AlertDescription>
- </Alert>
+ )}
+ <AcknowledgementCheckbox
+ id="secret-sync-move-warning-acknowledgement"
+ acknowledgement={coverageAcknowledgement}
+ label={`I understand these ${noun} ${hasError ? "may" : "will"} be synced to external destinations`}
+ />
+ </AlertDescription>
+ </Alert>
+ )}
+ {duplicatedSecretSyncs.length > 0 && (
+ <Alert variant="danger">
+ <CircleAlertIcon />
+ <AlertTitle>Cannot copy these secrets here</AlertTitle>
+ <AlertDescription>
+ <p>
+ The following secret syncs cover both folders and cannot send two secrets with the
+ same name. Choose a destination outside them:
+ </p>
+ <SecretSyncMoveWarningList syncs={duplicatedSecretSyncs} projectId={projectId} />
+ </AlertDescription>
+ </Alert>
+ )}
+ </>
);
};
diff --git a/frontend/src/helpers/secretSyncCoverage.test.ts b/frontend/src/helpers/secretSyncCoverage.test.ts
index 17c00afa90..da241f3091 100644
--- a/frontend/src/helpers/secretSyncCoverage.test.ts
+++ b/frontend/src/helpers/secretSyncCoverage.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, test } from "vitest";
-import { getSecretSyncsNewlyCoveringPaths, isPathCoveredBySecretSync } from "./secretSyncCoverage";
+import {
+ getSecretSyncsDuplicatedByCopies,
+ getSecretSyncsNewlyCoveringPaths,
+ isPathCoveredBySecretSync
+} from "./secretSyncCoverage";
describe("isPathCoveredBySecretSync", () => {
const sync = (path: string, includeAllSubFolders?: boolean, environment = "dev") => ({
@@ -105,3 +109,75 @@ describe("getSecretSyncsNewlyCoveringPaths", () => {
).toEqual(["alpha", "zeta"]);
});
});
+
+describe("getSecretSyncsDuplicatedByCopies", () => {
+ const sync = (id: string, overrides: Record<string, unknown> = {}) => ({
+ id,
+ name: id,
+ environment: { slug: "dev" },
+ folder: { path: "/" },
+ syncOptions: { includeAllSubFolders: true },
+ ...overrides
+ });
+
+ const copy = (
+ sourceSecretPath: string,
+ destinationSecretPath: string,
+ sourceEnvironment = "dev",
+ destinationEnvironment = sourceEnvironment
+ ) => ({
+ source: { environment: sourceEnvironment, secretPath: sourceSecretPath },
+ destination: { environment: destinationEnvironment, secretPath: destinationSecretPath }
+ });
+
+ const ids = (syncs: { id: string }[]) => syncs.map(({ id }) => id);
+
+ test("returns a sync that covers both the source and the destination", () => {
+ expect(ids(getSecretSyncsDuplicatedByCopies([sync("a")], [copy("/", "/bench")]))).toEqual([
+ "a"
+ ]);
+ expect(
+ ids(getSecretSyncsDuplicatedByCopies([sync("a")], [copy("/apps/x", "/apps/y")]))
+ ).toEqual(["a"]);
+ });
+
+ test("leaves out a sync that covers only one side", () => {
+ const syncs = [sync("a", { folder: { path: "/apps" } })];
+
+ expect(getSecretSyncsDuplicatedByCopies(syncs, [copy("/other", "/apps")])).toEqual([]);
+ expect(getSecretSyncsDuplicatedByCopies(syncs, [copy("/apps", "/other")])).toEqual([]);
+ });
+
+ test("leaves out a sync that does not include subfolders", () => {
+ const syncs = [sync("a", { syncOptions: { includeAllSubFolders: false } })];
+
+ expect(getSecretSyncsDuplicatedByCopies(syncs, [copy("/", "/bench")])).toEqual([]);
+ });
+
+ test("leaves out a copy onto its own path", () => {
+ expect(getSecretSyncsDuplicatedByCopies([sync("a")], [copy("/bench", "/bench/")])).toEqual([]);
+ });
+
+ test("leaves out a copy into another environment", () => {
+ expect(
+ getSecretSyncsDuplicatedByCopies([sync("a")], [copy("/", "/bench", "prod", "dev")])
+ ).toEqual([]);
+ expect(getSecretSyncsDuplicatedByCopies([sync("a")], [copy("/", "/", "dev", "prod")])).toEqual(
+ []
+ );
+ });
+
+ test("returns a sync once even when several copies duplicate into it", () => {
+ const copies = [copy("/", "/a"), copy("/x", "/b")];
+
+ expect(ids(getSecretSyncsDuplicatedByCopies([sync("a")], copies))).toEqual(["a"]);
+ });
+
+ test("orders syncs by name", () => {
+ const syncs = [sync("b", { name: "zeta" }), sync("a", { name: "alpha" })];
+
+ expect(
+ getSecretSyncsDuplicatedByCopies(syncs, [copy("/", "/bench")]).map(({ name }) => name)
+ ).toEqual(["alpha", "zeta"]);
+ });
+});
diff --git a/frontend/src/helpers/secretSyncCoverage.ts b/frontend/src/helpers/secretSyncCoverage.ts
index fb01e42d0d..93b75a0e5e 100644
--- a/frontend/src/helpers/secretSyncCoverage.ts
+++ b/frontend/src/helpers/secretSyncCoverage.ts
@@ -35,6 +35,12 @@ export const isPathCoveredBySecretSync = (
);
};
+const isSamePath = (a: string, b: string) =>
+ toPathSegments(a).join("/") === toPathSegments(b).join("/");
+
+const sortByName = <T extends { name: string }>(syncs: T[]) =>
+ [...syncs].sort((a, b) => a.name.localeCompare(b.name));
+
// The syncs that would start sending items to their destination if they were moved or copied as described.
// A sync that already covers a move's source is left out for that move, since the items already reach it.
export const getSecretSyncsNewlyCoveringPaths = <
@@ -43,12 +49,36 @@ export const getSecretSyncsNewlyCoveringPaths = <
syncs: T[],
moves: TItemMove[]
) =>
- syncs
- .filter((sync) =>
+ sortByName(
+ syncs.filter((sync) =>
moves.some(
(move) =>
isPathCoveredBySecretSync(sync, move.destination) &&
!isPathCoveredBySecretSync(sync, move.source)
)
)
- .sort((a, b) => a.name.localeCompare(b.name));
+ );
+
+// The syncs a copy would give two secrets with the same name. A copy leaves the original in place, so
+// copying between two folders of one sync puts both in it, and since a sync's key schema cannot include
+// the folder, both map to one key in the destination and the sync fails on it. Two different folders can
+// only share a sync that includes subfolders, so a sync without them never matches.
+export const getSecretSyncsDuplicatedByCopies = <
+ T extends TCoverageSync & { id: string; name: string }
+>(
+ syncs: T[],
+ copies: TItemMove[]
+) =>
+ sortByName(
+ syncs.filter((sync) =>
+ copies.some(
+ (copy) =>
+ !(
+ copy.source.environment === copy.destination.environment &&
+ isSamePath(copy.source.secretPath, copy.destination.secretPath)
+ ) &&
+ isPathCoveredBySecretSync(sync, copy.source) &&
+ isPathCoveredBySecretSync(sync, copy.destination)
+ )
+ )
+ );
diff --git a/frontend/src/hooks/api/secretSyncs/queries.tsx b/frontend/src/hooks/api/secretSyncs/queries.tsx
index 3baa580010..79b5734919 100644
--- a/frontend/src/hooks/api/secretSyncs/queries.tsx
+++ b/frontend/src/hooks/api/secretSyncs/queries.tsx
@@ -1,7 +1,11 @@
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { getSecretSyncsNewlyCoveringPaths, TItemMove } from "@app/helpers/secretSyncCoverage";
+import {
+ getSecretSyncsDuplicatedByCopies,
+ getSecretSyncsNewlyCoveringPaths,
+ TItemMove
+} from "@app/helpers/secretSyncCoverage";
import { SecretSync, TSecretSyncOption } from "@app/hooks/api/secretSyncs";
import {
TListSecretSyncOptions,
@@ -111,12 +115,15 @@ export const useListSecretSyncs = (
export const useListSecretSyncsCoveringMove = (
projectId: string,
moves: TItemMove[],
- { enabled }: { enabled: boolean }
+ { enabled, isCopy }: { enabled: boolean; isCopy: boolean }
) =>
useQuery({
queryKey: secretSyncKeys.coveringMove(projectId, moves),
queryFn: () => fetchSecretSyncsByProjectId(projectId),
- select: (secretSyncs) => getSecretSyncsNewlyCoveringPaths(secretSyncs, moves),
+ select: (secretSyncs) => ({
+ newSecretSyncs: getSecretSyncsNewlyCoveringPaths(secretSyncs, moves),
+ duplicatedSecretSyncs: isCopy ? getSecretSyncsDuplicatedByCopies(secretSyncs, moves) : []
+ }),
enabled,
staleTime: 0,
gcTime: 0
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx
index 17d2cb2173..5e79879b41 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx
@@ -210,7 +210,8 @@ const CopySecretsSession = ({
secretPath: group.destinationPath
}
}))
- : []
+ : [],
+ { isCopy: true }
);
const destinationFolderPaths = getCopyDestinationFolderPaths({
folderPaths: selectedFolderPaths,
@@ -346,6 +347,8 @@ const CopySecretsSession = ({
if (isDestinationLoading) return "Loading destination secrets";
if (!selectedItemCount) return "Select at least one secret or folder";
if (secretSyncWarning.isChecking) return "Checking the destination for secret syncs";
+ if (secretSyncWarning.duplicatedSecretSyncs.length)
+ return "Choose a destination outside the source's secret syncs";
if (secretSyncWarning.isBlockingSubmit) return "Confirm the secret sync warning to copy";
if (
destinationFolderSteps.some(