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
fix(secrets): show and resolve existing-key conflicts when uploading secrets (#9038)
Andrew Huangb2ddfabd14bb
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsxindex 12e3f95e7d..3f15b175fe 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/CopySecretsSheet.tsx@@ -15,14 +15,6 @@ import {import {Alert,AlertDescription,- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,AlertTitle,Button,Combobox,@@ -61,6 +53,7 @@ import {overviewResponsePhase,useOverviewTelemetry} from "../../OverviewTelemetry";+import { SecretConflictsDialog } from "../SecretConflictsDialog";import { type CopySecretsErrorKind, getCopySecretsErrorKind } from "./copySecrets.data";import type {CopySecretsAttributes,@@ -899,44 +892,19 @@ const CopySecretsSession = ({</SheetContent></Sheet>- <AlertDialog open={isConflictDialogOpen} onOpenChange={setIsConflictDialogOpen}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Resolve Secret Conflicts</AlertDialogTitle>- <AlertDialogDescription>- These secrets already exist at the destination. Overwrite them or copy only secrets- without conflicts.- </AlertDialogDescription>- </AlertDialogHeader>- <ul className="max-h-64 overflow-y-auto rounded-md border border-border bg-container">- {conflictingSecrets.map(- ({ sourceSecretId, name, destinationPath: conflictDestinationPath }) => (- <li- key={sourceSecretId}- className="flex min-w-0 flex-col gap-1 border-b border-border px-3 py-2 last:border-b-0 sm:flex-row sm:items-center sm:justify-between sm:gap-4"- >- <span className="font-mono text-sm break-all text-foreground">{name}</span>- <span className="font-mono text-xs break-all text-muted">- {conflictDestinationPath}- </span>- </li>- )- )}- </ul>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="outline" onClick={() => handleConflictResolution("skip")}>- Skip conflicts- </AlertDialogAction>- <AlertDialogAction- variant="danger"- onClick={() => handleConflictResolution("overwrite")}- >- Overwrite conflicts- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>+ <SecretConflictsDialog+ isOpen={isConflictDialogOpen}+ onOpenChange={setIsConflictDialogOpen}+ conflicts={conflictingSecrets.map(+ ({ sourceSecretId, name, destinationPath: location }) => ({+ id: sourceSecretId,+ name,+ location+ })+ )}+ description="These secrets already exist at the destination. Overwrite them or copy only secrets without conflicts."+ onResolve={handleConflictResolution}+ /></>);};diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/useCopySecretsQuery.ts b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/useCopySecretsQuery.tsindex a2ba981a36..134c323133 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/useCopySecretsQuery.ts+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CopySecretsSheet/useCopySecretsQuery.ts@@ -1,4 +1,4 @@-import { useQuery } from "@tanstack/react-query";+import { queryOptions, useQuery } from "@tanstack/react-query";import { fetchSecretMetadata } from "@app/hooks/api/dashboard/queries";@@ -16,7 +16,7 @@ export const copySecretsQueryKeys = {}) => ["copy-secrets-preview", { projectId, environment, secretPath }] as const};-export const useCopySecretsQuery = ({+export const getCopySecretsQueryOptions = ({projectId,environment,secretPath,@@ -27,7 +27,7 @@ export const useCopySecretsQuery = ({secretPath: string;enabled: boolean;}) =>- useQuery({+ queryOptions({queryKey: copySecretsQueryKeys.preview({ projectId, environment, secretPath }),enabled: enabled && Boolean(projectId && environment),staleTime: 0,@@ -49,3 +49,6 @@ export const useCopySecretsQuery = ({signal)});++export const useCopySecretsQuery = (params: Parameters<typeof getCopySecretsQueryOptions>[0]) =>+ useQuery(getCopySecretsQueryOptions(params));diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretConflictsDialog/SecretConflictsDialog.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretConflictsDialog/SecretConflictsDialog.tsxnew file mode 100644index 0000000000..88048a7223--- /dev/null+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretConflictsDialog/SecretConflictsDialog.tsx@@ -0,0 +1,61 @@+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle+} from "@app/components/v3";++export type SecretConflict = {+ id: string;+ name: string;+ location: string;+};++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ conflicts: SecretConflict[];+ description: string;+ onResolve: (resolution: "overwrite" | "skip") => void;+};++export const SecretConflictsDialog = ({+ isOpen,+ onOpenChange,+ conflicts,+ description,+ onResolve+}: Props) => (+ <AlertDialog open={isOpen} onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Resolve Secret Conflicts</AlertDialogTitle>+ <AlertDialogDescription>{description}</AlertDialogDescription>+ </AlertDialogHeader>+ <ul className="max-h-64 overflow-y-auto rounded-md border border-border bg-container">+ {conflicts.map(({ id, name, location }) => (+ <li+ key={id}+ className="flex min-w-0 flex-col gap-1 border-b border-border px-3 py-2 last:border-b-0 sm:flex-row sm:items-center sm:justify-between sm:gap-4"+ >+ <span className="font-mono text-sm break-all text-foreground">{name}</span>+ <span className="font-mono text-xs break-all text-muted">{location}</span>+ </li>+ ))}+ </ul>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction variant="outline" onClick={() => onResolve("skip")}>+ Skip conflicts+ </AlertDialogAction>+ <AlertDialogAction variant="danger" onClick={() => onResolve("overwrite")}>+ Overwrite conflicts+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+);diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretConflictsDialog/index.ts b/frontend/src/pages/secret-manager/OverviewPage/components/SecretConflictsDialog/index.tsnew file mode 100644index 0000000000..193acf2bc8--- /dev/null+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretConflictsDialog/index.ts@@ -0,0 +1,2 @@+export type { SecretConflict } from "./SecretConflictsDialog";+export { SecretConflictsDialog } from "./SecretConflictsDialog";diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsxindex 42da38b7b0..e0d1678a04 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsx@@ -1,5 +1,6 @@import { ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";import { subject } from "@casl/ability";+import { useQueries } from "@tanstack/react-query";import axios from "axios";import {ChevronRightIcon,@@ -24,6 +25,7 @@ import {Alert,AlertDescription,AlertTitle,+ Badge,Button,Combobox,Field,@@ -73,6 +75,9 @@ import {overviewResponsePhase,useOverviewTelemetry} from "../../OverviewTelemetry";+import { normalizeCopyPath } from "../CopySecretsSheet/copySecrets.utils";+import { getCopySecretsQueryOptions } from "../CopySecretsSheet/useCopySecretsQuery";+import { SecretConflictsDialog } from "../SecretConflictsDialog";import { CsvColumnMapContent } from "./CsvColumnMapDialog";import {buildFolderTree,@@ -164,6 +169,7 @@ const ImportSecretsContent = ({const [csvData, setCsvData] = useState<CsvData | null>(null);const [visibleSecretKeys, setVisibleSecretKeys] = useState<Set<string>>(new Set());const [shouldOverwrite, setShouldOverwrite] = useState(false);+ const [isConflictDialogOpen, setIsConflictDialogOpen] = useState(false);const [keyOverrides, setKeyOverrides] = useState<Record<string, string>>({});const [nestedJson, setNestedJson] = useState<Record<string, unknown> | null>(null);const [shouldImportNested, setShouldImportNested] = useState(false);@@ -268,6 +274,88 @@ const ImportSecretsContent = ({nestedImport.folderPaths.every((path) => collapsedFolders.has(path)));+ const existingSecretQueries = useQueries({+ queries: selectedEnvs.map((env) =>+ nestedImport+ ? getCopySecretsQueryOptions({+ projectId,+ environment: env.slug,+ secretPath,+ enabled: Boolean(activeSecrets)+ })+ : {+ queryKey: ["upload-existing-secrets", { projectId, environment: env.slug, secretPath }],+ enabled: Boolean(activeSecrets),+ staleTime: 0,+ gcTime: 0,+ queryFn: async () => {+ try {+ const { secrets } = await fetchProjectSecrets({+ projectId,+ environment: env.slug,+ secretPath,+ viewSecretValue: false+ });+ return mergePersonalSecrets(secrets).map(({ id, key }) => ({+ id,+ name: key,+ path: secretPath+ }));+ } catch (error) {+ // The upload creates a missing destination folder, so it has no existing secrets+ if (axios.isAxiosError(error) && error.response?.status === 404) return [];+ throw error;+ }+ }+ }+ )+ });+ const isCheckingExistingSecrets = existingSecretQueries.some(+ (query) => query.isFetching || (query.isPending && query.fetchStatus !== "idle")+ );+ const hasExistingSecretsError = existingSecretQueries.some((query) => query.isError);+ const incomingSecrets = (+ nestedImport+ ? Object.entries(nestedImport.secretsByPath).flatMap(([path, secrets]) =>+ Object.entries(secrets).map(([key, secretData]) => ({+ rowId: `${path}:${key}`,+ key,+ secretData,+ path: joinSecretPath(secretPath, path)+ }))+ )+ : Object.entries(activeSecrets ?? {}).map(([key, secretData]) => ({+ rowId: key,+ key,+ secretData,+ path: secretPath+ }))+ ).map(({ rowId, key, secretData, path }) => ({+ rowId,+ path: normalizeCopyPath(path),+ finalKey: (secretData.isFileSecret ? (keyOverrides[key] ?? key) : key).trim()+ }));+ const secretConflicts = selectedEnvs.flatMap((env, index) => {+ const existingLocations = new Set(+ (existingSecretQueries[index]?.data ?? []).map(+ ({ path, name }) => `${normalizeCopyPath(path)}\u0000${name}`+ )+ );+ return incomingSecrets+ .filter(({ path, finalKey }) => existingLocations.has(`${path}\u0000${finalKey}`))+ .map(({ rowId, path, finalKey }) => ({+ id: `${env.slug}\u0000${rowId}`,+ rowId,+ environmentName: env.name,+ name: finalKey,+ location: `${env.name}: ${path}`+ }));+ });+ const conflictEnvironmentsByRowId = secretConflicts.reduce((map, { rowId, environmentName }) => {+ map.set(rowId, [...(map.get(rowId) ?? []), environmentName]);+ return map;+ }, new Map<string, string[]>());+const toggleFolder = (path: string) => {setCollapsedFolders((prev) => {const next = new Set(prev);@@ -362,7 +450,7 @@ const ImportSecretsContent = ({if (initialFile) parseFile(initialFile);}, [initialFile, parseFile]);- const handleImport = async () => {+ const handleImport = async (overwriteExisting: boolean) => {if (!activeSecrets || !selectedEnvs.length) return;if (isImportRunningRef.current) return;@@ -422,6 +510,8 @@ const ImportSecretsContent = ({});}+ const skippedCountByEnv = new Map<string, number>();+const resolveTagIds = (slugs?: string[]): string[] | undefined => {if (!slugs?.length) return undefined;const ids = slugs.map((s) => slugToTagId.get(s)).filter((id): id is string => Boolean(id));@@ -514,6 +604,13 @@ const ImportSecretsContent = ({skipMultilineEncoding: secretData.skipMultilineEncoding}));+ if (!overwriteExisting) {+ skippedCountByEnv.set(+ environment,+ (skippedCountByEnv.get(environment) ?? 0) + secretsToUpdate.length+ );+ }+if (!enqueue) {return {oversizedKeys: [] as string[],@@ -528,7 +625,7 @@ const ImportSecretsContent = ({})]: []),- ...(shouldOverwrite && secretsToUpdate.length+ ...(overwriteExisting && secretsToUpdate.length? [updateSecretBatch({projectId,@@ -549,7 +646,7 @@ const ImportSecretsContent = ({secretsToCreate,MAX_BATCH_REQUEST_BYTES);- const updates = shouldOverwrite+ const updates = overwriteExisting? chunkSecretsByRequestSize(envelope, secretsToUpdate, MAX_BATCH_REQUEST_BYTES): { chunks: [], oversized: [] };const oversizedKeys = [...creates.oversized, ...updates.oversized].map(@@ -722,10 +819,16 @@ const ImportSecretsContent = ({}});+ const skippedCount = successEnvSlugs.reduce(+ (count, slug) => count + (skippedCountByEnv.get(slug) ?? 0),+ 0+ );if (successEnvs.length) {createNotification({type: "success",- text: `Successfully uploaded ${secretCount} secret${secretCount > 1 ? "s" : ""}${folderSummary} into ${successEnvs.join(", ")}`+ text: skippedCount+ ? `Uploaded secrets${folderSummary} into ${successEnvs.join(", ")}; ${skippedCount} existing ${skippedCount === 1 ? "secret" : "secrets"} skipped`+ : `Successfully uploaded ${secretCount} secret${secretCount > 1 ? "s" : ""}${folderSummary} into ${successEnvs.join(", ")}`});}@@ -782,6 +885,19 @@ const ImportSecretsContent = ({}};+ const handleUpload = () => {+ if (secretConflicts.length && !shouldOverwrite) {+ setIsConflictDialogOpen(true);+ return;+ }+ handleImport(shouldOverwrite);+ };++ const handleConflictResolution = (resolution: "overwrite" | "skip") => {+ setIsConflictDialogOpen(false);+ handleImport(resolution === "overwrite");+ };+const handleBack = () => {setParsedSecrets(null);setNestedJson(null);@@ -1049,6 +1165,8 @@ const ImportSecretsContent = ({const hasSkipMl = secretData.skipMultilineEncoding === true;const editableKey = secretData.isFileSecret === true;const editedKey = keyOverrides[key] ?? key;+ const conflictEnvironments = conflictEnvironmentsByRowId.get(id);+ const conflictLabel = shouldOverwrite ? "Overwrite" : "Conflict";return (<TableRow key={id} {...rowProps}><TableCell isTruncatable className="w-1/2 overflow-hidden font-mono text-xs">@@ -1125,6 +1243,24 @@ const ImportSecretsContent = ({<TooltipContent>Multi-line encoding enabled</TooltipContent></Tooltip>)}+ {conflictEnvironments && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ className="ml-auto shrink-0 rounded-sm focus-visible:ring-2 focus-visible:ring-ring"+ aria-label={`${editedKey}: ${conflictLabel}`}+ >+ <Badge variant="warning">{conflictLabel}</Badge>+ </button>+ </TooltipTrigger>+ <TooltipContent className="max-w-72">+ {shouldOverwrite+ ? `This key already exists in ${conflictEnvironments.join(", ")} and will be overwritten.`+ : `This key already exists in ${conflictEnvironments.join(", ")}. Choose whether to overwrite or skip it when you upload.`}+ </TooltipContent>+ </Tooltip>+ )}</ImportKeyContent></TableCell><TableCell isTruncatable className="w-1/2 font-mono text-xs whitespace-pre">@@ -1187,8 +1323,8 @@ const ImportSecretsContent = ({</TooltipTrigger><TooltipContent className="max-w-md text-center">When enabled, secrets that already exist in the target environment will be updated- with the imported values. When disabled, existing secrets will be skipped and only- new secrets will be created.+ with the imported values. When disabled, you choose whether to overwrite or skip+ them when you upload.</TooltipContent></Tooltip></FieldLabel>@@ -1198,6 +1334,20 @@ const ImportSecretsContent = ({onCheckedChange={setShouldOverwrite}/></Field>+ {secretConflicts.length > 0 && (+ <p className="-mt-2 text-xs text-muted" aria-live="polite">+ {`${secretConflicts.length} ${secretConflicts.length === 1 ? "key already exists" : "keys already exist"} in the target environments. `}+ {shouldOverwrite+ ? "They will be overwritten."+ : "Choose whether to overwrite or skip them when you upload."}+ </p>+ )}+ {hasExistingSecretsError && (+ <p className="-mt-2 text-xs text-muted" aria-live="polite">+ Existing secrets couldn't be checked. Keys that already exist are skipped unless+ you turn on overwrite.+ </p>+ )}{nestedJson && (<Field orientation="horizontal" className="w-fit"><FieldLabel htmlFor="import-nested-as-folders">@@ -1246,20 +1396,28 @@ const ImportSecretsContent = ({</Button><Buttonvariant="project"- onClick={handleImport}+ onClick={handleUpload}isDisabled={!selectedEnvs.length ||isImporting ||+ isCheckingExistingSecrets ||isWaitingForTags ||hasInvalidKey ||isOverRequestLimit ||hasNestedErrors}- isPending={isImporting || isWaitingForTags}+ isPending={isImporting || isWaitingForTags || isCheckingExistingSecrets}>Upload {secretCount} Secret{secretCount !== 1 ? "s" : ""}</Button></SheetFooter>+ <SecretConflictsDialog+ isOpen={isConflictDialogOpen}+ onOpenChange={setIsConflictDialogOpen}+ conflicts={secretConflicts}+ description="These secrets already exist in the target environments. Overwrite them or upload only secrets without conflicts."+ onResolve={handleConflictResolution}+ /></>);};