Skip to content

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

fix(secrets): check duplicate secret names server-side in quick add and inline rename (#9001)

Andrew Huang76646c959bc0
diff --git a/backend/src/server/routes/v1/dashboard-router.ts b/backend/src/server/routes/v1/dashboard-router.ts
index 83ab0722db..543e5a186a 100644
--- a/backend/src/server/routes/v1/dashboard-router.ts
+++ b/backend/src/server/routes/v1/dashboard-router.ts
@@ -12,7 +12,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";
import { OrderByDirection } from "@app/lib/types";
import { readLimit, secretsLimit } from "@app/server/config/rateLimiter";
-import { slugSchema } from "@app/server/lib/schemas";
+import { SecretNameSchema, slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { getUserAgentType } from "@app/server/plugins/audit-log";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -1943,6 +1943,57 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/secrets/key-exists",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: true,
+ operationId: "getSecretKeyExists",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ querystring: z.object({
+ projectId: z.string().trim().min(1).max(64),
+ environments: z
+ .string()
+ .trim()
+ .max(4000)
+ .transform(decodeURIComponent)
+ .transform((value) => value.split(",").filter(Boolean))
+ .pipe(slugSchema({ field: "Environment" }).array().min(1).max(100)),
+ secretPath: z.string().trim().max(1000).default("/").transform(removeTrailingSlash),
+ secretKey: z.string().trim().max(500).pipe(SecretNameSchema)
+ }),
+ response: {
+ 200: z.object({
+ existingEnvironments: z.string().array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { projectId, environments, secretPath, secretKey } = req.query;
+
+ const existingEnvironments = await server.services.secret.getSecretKeyEnvironments({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ projectId,
+ environments,
+ path: secretPath,
+ secretKey
+ });
+
+ return { existingEnvironments };
+ }
+ });
+
server.route({
method: "GET",
url: "/secret-value",
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
index 4875b592b2..4ae6338f87 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
@@ -940,6 +940,38 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
+ const findSharedKeyInFolders = async ({ folderIds, key }: { folderIds: string[]; key: string }) => {
+ try {
+ const rows = await db
+ .replicaNode()(TableName.SecretV2)
+ .where(`${TableName.SecretV2}.key`, key)
+ .where(`${TableName.SecretV2}.type`, SecretType.Shared)
+ .whereIn(`${TableName.SecretV2}.folderId`, folderIds)
+ .leftJoin(
+ TableName.SecretV2JnTag,
+ `${TableName.SecretV2}.id`,
+ `${TableName.SecretV2JnTag}.${TableName.SecretV2}Id`
+ )
+ .leftJoin(
+ TableName.SecretTag,
+ `${TableName.SecretV2JnTag}.${TableName.SecretTag}Id`,
+ `${TableName.SecretTag}.id`
+ )
+ .select(db.ref("folderId").withSchema(TableName.SecretV2))
+ .select(db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"));
+
+ const tagSlugsByFolderId = new Map<string, string[]>();
+ rows.forEach(({ folderId, tagSlug }) => {
+ const tagSlugs = tagSlugsByFolderId.get(folderId) ?? [];
+ if (tagSlug) tagSlugs.push(tagSlug);
+ tagSlugsByFolderId.set(folderId, tagSlugs);
+ });
+ return Array.from(tagSlugsByFolderId, ([folderId, tagSlugs]) => ({ folderId, tagSlugs }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find shared secret key in folders" });
+ }
+ };
+
const findBySecretKeys = async (
folderId: string,
query: Array<{ key: string; type: SecretType.Shared } | { key: string; type: SecretType.Personal; userId: string }>,
@@ -1856,6 +1888,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
findByFolderIds,
findMetadataByFolderIds,
findBySecretKeys,
+ findSharedKeyInFolders,
upsertSecretReferences,
findReferencedSecretReferences,
findSecretReferencesByProjectId,
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
index c7eeae6920..0e70a5d275 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
@@ -107,6 +107,7 @@ import {
TDispatchSecretCreateSideEffectsDTO,
TDispatchSecretMoveSideEffectsDTO,
TGetASecretDTO,
+ TGetSecretKeyEnvironmentsDTO,
TGetSecretReferencesTreeDTO,
TGetSecretsDTO,
TGetSecretsMultiEnvDTO,
@@ -1336,6 +1337,55 @@ export const secretV2BridgeServiceFactory = ({
return secrets;
};
+ const getSecretKeyEnvironments = async ({
+ actorId,
+ actor,
+ actorOrgId,
+ actorAuthMethod,
+ projectId,
+ environments,
+ path,
+ secretKey
+ }: TGetSecretKeyEnvironmentsDTO) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+
+ // the folder lookup ignores empty segments, so check permissions against the same canonical path
+ const secretPath = `/${path.split("/").filter(Boolean).join("/")}`;
+ const folders = await folderDAL.findBySecretPathMultiEnv(projectId, environments, secretPath);
+ if (!folders.length) return [];
+
+ const folderEnvironments = new Map(folders.map((folder) => [folder.id, folder.environment.slug]));
+ const matches = await secretDAL.findSharedKeyInFolders({
+ folderIds: folders.map((folder) => folder.id),
+ key: secretKey
+ });
+
+ const existingEnvironments = new Set<string>();
+ matches.forEach(({ folderId, tagSlugs }) => {
+ const environment = folderEnvironments.get(folderId);
+ if (
+ environment &&
+ hasSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {
+ environment,
+ secretPath,
+ secretName: secretKey,
+ secretTags: tagSlugs
+ })
+ ) {
+ existingEnvironments.add(environment);
+ }
+ });
+
+ return environments.filter((environment) => existingEnvironments.has(environment));
+ };
+
const getSecrets = async (dto: TGetSecretsDTO) => {
const {
actorId,
@@ -3961,6 +4011,7 @@ export const secretV2BridgeServiceFactory = ({
deleteManySecret: withSecretMetrics(deleteManySecret, { duration: "write", write: "delete" }),
getSecrets: withSecretMetrics(getSecrets, { duration: "read" }),
getSecretByName,
+ getSecretKeyEnvironments,
getSecretVersions,
backfillSecretReferences,
moveSecrets,
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
index 1d52d565bc..2cb3834c27 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
@@ -536,6 +536,13 @@ export type TGetSecretsMultiEnvDTO = Pick<
isInternal?: boolean;
};
+export type TGetSecretKeyEnvironmentsDTO = Pick<
+ TGetSecretsMultiEnvDTO,
+ "actorId" | "actor" | "path" | "projectId" | "actorOrgId" | "actorAuthMethod" | "environments"
+> & {
+ secretKey: string;
+};
+
export type TGetSecretsRawByFolderMappingsDTO = {
projectId: string;
folderMappings: { folderId: string; path: string; environment: string }[];
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index 0136450401..1b5af3d580 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -65,7 +65,7 @@ import { TSecretTagDALFactory } from "../secret-tag/secret-tag-dal";
import { getAllSecretReferences } from "../secret-v2-bridge/secret-reference-fns";
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TSecretV2BridgeServiceFactory } from "../secret-v2-bridge/secret-v2-bridge-service";
-import { TGetSecretReferencesTreeDTO } from "../secret-v2-bridge/secret-v2-bridge-types";
+import { TGetSecretKeyEnvironmentsDTO, TGetSecretReferencesTreeDTO } from "../secret-v2-bridge/secret-v2-bridge-types";
import { TSecretVersionV2DALFactory } from "../secret-v2-bridge/secret-version-dal";
import { TSecretDALFactory } from "./secret-dal";
import {
@@ -1329,6 +1329,16 @@ export const secretServiceFactory = ({
return secrets;
};
+ const getSecretKeyEnvironments = async (dto: TGetSecretKeyEnvironmentsDTO) => {
+ const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);
+ if (!shouldUseSecretV2Bridge)
+ throw new BadRequestError({
+ message: "Project version does not support checking secret names"
+ });
+
+ return secretV2BridgeService.getSecretKeyEnvironments(dto);
+ };
+
const getSecretReferenceTree = async (dto: TGetSecretReferencesTreeDTO) => {
const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);
@@ -4027,6 +4037,7 @@ export const secretServiceFactory = ({
getSecretsCount,
getSecretsCountMultiEnv,
getSecretsRawMultiEnv,
+ getSecretKeyEnvironments,
getSecretReferenceTree,
getSecretsRawByFolderMappings,
getSecretAccessList,
diff --git a/frontend/src/hooks/api/dashboard/queries.tsx b/frontend/src/hooks/api/dashboard/queries.tsx
index 8d2bc79316..b119d8b902 100644
--- a/frontend/src/hooks/api/dashboard/queries.tsx
+++ b/frontend/src/hooks/api/dashboard/queries.tsx
@@ -1,5 +1,11 @@
import { useCallback } from "react";
-import { useQueries, useQuery, useQueryClient, UseQueryOptions } from "@tanstack/react-query";
+import {
+ queryOptions,
+ useQueries,
+ useQuery,
+ useQueryClient,
+ UseQueryOptions
+} from "@tanstack/react-query";
import { AxiosError } from "axios";
import { apiRequest } from "@app/config/request";
@@ -20,6 +26,7 @@ import {
TGetDashboardProjectSecretsDetailsDTO,
TGetDashboardProjectSecretsOverviewDTO,
TGetDashboardProjectSecretsQuickSearchDTO,
+ TGetSecretKeyExistsDTO,
TGetSecretMetadataDTO,
TGetSecretValueDTO,
TSearchSecretsByMetadataDTO,
@@ -73,6 +80,17 @@ export const dashboardKeys = {
] as const,
searchSecretsByMetadata: ({ projectId, ...params }: TSearchSecretsByMetadataDTO) =>
[...dashboardKeys.all(), "secrets-by-metadata", projectId, params] as const,
+ getSecretKeyExists: ({
+ projectId,
+ secretPath,
+ environments,
+ secretKey
+ }: TGetSecretKeyExistsDTO) =>
+ [
+ ...dashboardKeys.getDashboardSecrets({ projectId, secretPath }),
+ "secret-key-exists",
+ { environments, secretKey }
+ ] as const,
getSecretValuesRoot: () => [...dashboardKeys.all(), "secrets-values"] as const,
getSecretValue: ({
projectId,
@@ -113,6 +131,30 @@ export const fetchSecretMetadata = async (params: TGetSecretMetadataDTO, signal?
return data;
};
+export const secretKeyExistsQueryOptions = (params: TGetSecretKeyExistsDTO) =>
+ queryOptions({
+ queryKey: dashboardKeys.getSecretKeyExists(params),
+ queryFn: async () => {
+ const { environments, ...rest } = params;
+ const { data } = await apiRequest.get<{ existingEnvironments: string[] }>(
+ "/api/v1/dashboard/secrets/key-exists",
+ { params: { ...rest, environments: encodeURIComponent(environments.join(",")) } }
+ );
+ return data.existingEnvironments;
+ },
+ staleTime: 60 * 1000,
+ retry: false
+ });
+
+export const useGetSecretKeyExistingEnvironments = (
+ params: TGetSecretKeyExistsDTO,
+ { enabled = true }: { enabled?: boolean } = {}
+) =>
+ useQuery({
+ ...secretKeyExistsQueryOptions(params),
+ enabled: enabled && Boolean(params.secretKey) && params.environments.length > 0
+ });
+
export const fetchProjectSecretsOverview = async ({
environments,
tags,
diff --git a/frontend/src/hooks/api/dashboard/types.ts b/frontend/src/hooks/api/dashboard/types.ts
index 31c61e0004..ebedb0243c 100644
--- a/frontend/src/hooks/api/dashboard/types.ts
+++ b/frontend/src/hooks/api/dashboard/types.ts
@@ -236,6 +236,13 @@ export type TSearchSecretsByMetadataResponse = {
searchLimit: number;
};
+export type TGetSecretKeyExistsDTO = {
+ projectId: string;
+ environments: string[];
+ secretPath: string;
+ secretKey: string;
+};
+
export type TGetDashboardProjectSecretsByKeys = {
projectId: string;
secretPath: string;
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index c2b1197cb6..3aa169d861 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -4618,6 +4618,24 @@ const OverviewPageContent = () => {
isDirectSave
);
}}
+ onQueuedSecretConflict={(draft) => {
+ const pendingCreate = batchStoreApi
+ .getState()
+ .pendingChanges.secrets.find(
+ (change) =>
+ change.type === PendingAction.Create &&
+ change.secretKey === draft.key &&
+ change.secretValue === draft.value &&
+ (change.secretComment ?? "") === draft.comment
+ );
+ if (!pendingCreate || !singleVisibleEnv) return false;
+ removePendingChange(pendingCreate.id, "secret", {
+ projectId,
+ environment: singleVisibleEnv.slug,
+ secretPath
+ });
+ return true;
+ }}
onPasteSecrets={(env) => {
overviewTelemetry.flow({
action: "import",
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/QuickAddSecretRow/QuickAddSecretRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/QuickAddSecretRow/QuickAddSecretRow.tsx
index d36a736d11..4274ed82a9 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/QuickAddSecretRow/QuickAddSecretRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/QuickAddSecretRow/QuickAddSecretRow.tsx
@@ -7,7 +7,9 @@ import {
useRef,
useState
} from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { createNotification } from "@app/components/notifications";
import { parsePastedEnv } from "@app/components/utilities/parseSecrets";
import {
InfisicalSecretInput,
@@ -15,9 +17,17 @@ import {
SecretInputActions,
TableCell,
TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
useSecretInputActionShortcuts
} from "@app/components/v3";
import { useProject } from "@app/context";
+import { useDebounce } from "@app/hooks";
+import {
+ secretKeyExistsQueryOptions,
+ useGetSecretKeyExistingEnvironments
+} from "@app/hooks/api/dashboard/queries";
import { overviewCountBucket, useOverviewTelemetry } from "../../OverviewTelemetry";
import { TABLE_ROW_ACTIVE_FILTER_CLASS_NAME } from "../tableRowActionStyles";
@@ -25,6 +35,36 @@ import type { TableRowActivityChangeHandler, TableRowActivityId } from "../table
type TParsedEnv = Record<string, { value: string; comments: string[] }>;
+const getDuplicateKeyError = (environmentsWithKey: string[], isMultiEnvironmentView: boolean) =>
+ isMultiEnvironmentView
+ ? `A secret with this name already exists in ${environmentsWithKey.join(", ")}`
+ : "A secret with this name already exists";
+
+const LISTED_ENVIRONMENT_COUNT = 2;
+
+const DuplicateEnvironmentsMessage = ({ environments }: { environments: string[] }) => {
+ const listedEnvironments = environments.slice(0, LISTED_ENVIRONMENT_COUNT).join(", ");
+ const hiddenEnvironments = environments.slice(LISTED_ENVIRONMENT_COUNT);
+ if (!hiddenEnvironments.length) return <>Already exists in {listedEnvironments}</>;
+
+ return (
+ <>
+ Already exists in {listedEnvironments} and{" "}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ className="cursor-default rounded-sm underline decoration-dotted underline-offset-2 outline-hidden focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ {hiddenEnvironments.length} more
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{hiddenEnvironments.join(", ")}</TooltipContent>
+ </Tooltip>
+ </>
+ );
+};
+
type Props = {
autoQueueOnBlur?: boolean;
environments: string[];
@@ -37,6 +77,7 @@ type Props = {
isDirectSave?: boolean
) => Promise<void>;
onPasteSecrets: (env: TParsedEnv) => void;
+ onQueuedSecretConflict?: (draft: { key: string; value: string; comment: string }) => boolean;
renderResourceTypeTrigger: (isDisabled: boolean) => ReactNode;
saveLabel?: string;
secretPath: string;
@@ -50,6 +91,7 @@ export const QuickAddSecretRow = ({
existingSecretKeys,
onCreateSecret,
onPasteSecrets,
+ onQueuedSecretConflict,
renderResourceTypeTrigger,
saveLabel,
secretPath,
@@ -70,6 +112,30 @@ export const QuickAddSecretRow = ({
const [isSubmitting, setIsSubmitting] = useState(false);
const [valueEditorStyle, setValueEditorStyle] = useState<CSSProperties>();
const isMultiEnvironmentView = environments.length > 1;
+ const queryClient = useQueryClient();
+ const latestDraftRef = useRef({ key, value, comment });
+ latestDraftRef.current = { key, value, comment };
+ const trimmedKey = key.trim();
+ const [debouncedKey] = useDebounce(trimmedKey, 500);
+ const isLocalDuplicate = existingSecretKeys.includes(trimmedKey);
+ const { data: environmentsWithKey } = useGetSecretKeyExistingEnvironments(
+ { projectId: currentProject.id, environments, secretPath, secretKey: debouncedKey },
+ { enabled: !existingSecretKeys.includes(debouncedKey) }
+ );
+ const isCheckForCurrentKey = Boolean(trimmedKey) && debouncedKey === trimmedKey;
+ let duplicateError: string | undefined;
+ if (isLocalDuplicate) duplicateError = "A secret with this name already exists";
+ else if (isCheckForCurrentKey && environmentsWithKey?.length)
+ duplicateError = getDuplicateKeyError(environmentsWithKey, isMultiEnvironmentView);
+ const isKeyConfirmedFree = isCheckForCurrentKey && environmentsWithKey?.length === 0;
+ const duplicateEnvironments =
+ isMultiEnvironmentView &&
+ !isLocalDuplicate &&
+ isCheckForCurrentKey &&
+ environmentsWithKey?.length
+ ? environmentsWithKey
+ : undefined;
+ const displayedError = error ?? duplicateError;
useEffect(() => {
if (!isMultiEnvironmentView) {
@@ -124,8 +190,7 @@ export const QuickAddSecretRow = ({
return;
}
- if (existingSecretKeys.includes(normalizedKey)) {
- setError("A secret with this name already exists");
+ if (duplicateError) {
if (refocus) keyInputRef.current?.focus();
return;
}
@@ -134,14 +199,61 @@ export const QuickAddSecretRow = ({
setError(undefined);
try {
+ if (isDirectSave) {
+ const takenEnvironments = await queryClient
+ .fetchQuery(
+ secretKeyExistsQueryOptions({
+ projectId: currentProject.id,
+ environments,
+ secretPath,
+ secretKey: normalizedKey
+ })
+ )
+ .catch(() => []);
+ if (takenEnvironments.length) {
+ if (refocus) setTimeout(() => keyInputRef.current?.focus(), 0);
+ return;
+ }
+ }
+
await Promise.all(
environments.map((environment) =>
onCreateSecret(environment, normalizedKey, value, comment, isDirectSave)
)
);
+ if (!isDirectSave && !isKeyConfirmedFree) {
+ const queuedDraft = { key: normalizedKey, value, comment };
+ queryClient
+ .fetchQuery(
+ secretKeyExistsQueryOptions({
+ projectId: currentProject.id,
+ environments,
+ secretPath,
+ secretKey: normalizedKey
+ })
+ )
+ .catch(() => [])
+ .then((takenEnvironments) => {
+ if (!takenEnvironments.length || !onQueuedSecretConflict?.(queuedDraft)) return;
+ const duplicateKeyError = getDuplicateKeyError(
+ takenEnvironments,
+ isMultiEnvironmentView
+ );
+ createNotification({
+ type: "error",
+ text: `${duplicateKeyError}, so '${queuedDraft.key}' was removed from your pending changes`
+ });
+ const latestDraft = latestDraftRef.current;
+ if (latestDraft.key || latestDraft.value || latestDraft.comment) return;
+ setKey(queuedDraft.key);
+ setValue(queuedDraft.value);
+ setComment(queuedDraft.comment);
+ });
+ }
setKey("");
setValue("");
setComment("");
+ setError(undefined);
const { activeElement } = document;
if (activeElement instanceof HTMLElement && rowRef.current?.contains(activeElement)) {
activeElement.blur();
@@ -255,12 +367,12 @@ export const QuickAddSecretRow = ({
<form ref={formRef} id="quick-add-secret-form" onSubmit={handleSubmit}>
<Input
ref={keyInputRef}
- aria-describedby={error ? "quick-add-secret-error" : undefined}
+ aria-describedby={displayedError ? "quick-add-secret-error" : undefined}
aria-label="New secret name"
autoComplete="off"
className="h-auto w-full rounded-none border-0 bg-transparent px-0 py-0 shadow-none focus-visible:border-transparent focus-visible:ring-0"
disabled={isSubmitting}
- isError={Boolean(error)}
+ isError={Boolean(displayedError)}
placeholder="Add a secret name or paste a .env"
spellCheck={false}
value={key}
@@ -280,9 +392,16 @@ export const QuickAddSecretRow = ({
}
}}
/>
- {error && (
- <span id="quick-add-secret-error" className="mt-1 block text-2xs text-danger">
- {error}
+ {displayedError && (
+ <span
+ id="quick-add-secret-error"
+ className="mt-1 block text-2xs break-words whitespace-normal text-danger"
+ >
+ {!error && duplicateEnvironments ? (
+ <DuplicateEnvironmentsMessage environments={duplicateEnvironments} />
+ ) : (
+ displayedError
+ )}
</span>
)}
</form>
@@ -321,7 +440,7 @@ export const QuickAddSecretRow = ({
{isDraftActive && (
<SecretInputActions
className="absolute right-0"
- isSaveDisabled={isSubmitting}
+ isSaveDisabled={isSubmitting || Boolean(duplicateError)}
isUndoDisabled={isSubmitting}
saveLabel={saveLabel}
onSave={requestSave}
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
index 128e9c7d4b..abec38cad1 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
@@ -10,6 +10,7 @@ import {
} from "react";
import { Controller, useForm } from "react-hook-form";
import { subject } from "@casl/ability";
+import { useQueryClient } from "@tanstack/react-query";
import {
BanIcon,
BellIcon,
@@ -96,9 +97,19 @@ import {
useSubscription
} from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
-import { useDiscardChangesGuard, usePopUp, useTimedReset, useToggle } from "@app/hooks";
+import {
+ useDebounce,
+ useDiscardChangesGuard,
+ usePopUp,
+ useTimedReset,
+ useToggle
+} from "@app/hooks";
import { useUpdateSecretV3 } from "@app/hooks/api";
-import { useGetSecretValue } from "@app/hooks/api/dashboard/queries";
+import {
+ secretKeyExistsQueryOptions,
+ useGetSecretKeyExistingEnvironments,
+ useGetSecretValue
+} from "@app/hooks/api/dashboard/queries";
import { Reminder } from "@app/hooks/api/reminders/types";
import { PendingAction } from "@app/hooks/api/secretFolders/types";
import { ProjectEnv, SecretType, SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
@@ -309,6 +320,7 @@ export const SecretEditTableRow = ({
setValue,
setFocus,
getFieldState,
+ getValues,
watch,
formState: { isDirty, dirtyFields, isSubmitting }
} = useForm({
@@ -517,6 +529,34 @@ export const SecretEditTableRow = ({
const serializedMetadata = JSON.stringify(watchedMetadata);
const batchAutoApplyTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
const applyBatchEditsRef = useRef<() => void>(undefined);
+ const queryClient = useQueryClient();
+ const isSavingPendingChangeRef = useRef(false);
+ const getKeyCheckParams = (secretKey: string) => ({
+ projectId: currentProject.id,
+ environments: [environment],
+ secretPath,
+ secretKey
+ });
+ const getCheckedKeyEnvironments = (secretKey: string) => {
+ const state = queryClient.getQueryState<string[]>(
+ secretKeyExistsQueryOptions(getKeyCheckParams(secretKey)).queryKey
+ );
+ if (state?.status === "error" && state.fetchStatus === "idle") return [];
+ if (!state || state.isInvalidated) return undefined;
+ return state.data;
+ };
+ const getRenameKey = () => {
+ const key = getValues("key") as string | undefined;
+ return isSingleEnvView && key && key !== secretName ? key : undefined;
+ };
+ const [debouncedKey] = useDebounce((watchedKey as string | undefined) ?? "", 500);
+ const keyCheck = useGetSecretKeyExistingEnvironments(getKeyCheckParams(debouncedKey), {
+ enabled: isSingleEnvView && debouncedKey !== secretName
+ });
+
+ useEffect(() => {
+ if (keyCheck.dataUpdatedAt || keyCheck.errorUpdatedAt) applyBatchEditsRef.current?.();
+ }, [keyCheck.dataUpdatedAt, keyCheck.errorUpdatedAt]);
const lastAppliedRef = useRef<{
value: unknown;
key: unknown;
@@ -628,6 +668,7 @@ export const SecretEditTableRow = ({
// Check for key rename conflicts before applying (read store snapshot, no subscription)
let effectiveKeyDirty = isKeyDirty;
+ let isKeyCheckPending = false;
if (isKeyDirty) {
const { existingSecretKeys, pendingChanges: pc } = batchStore.getState();
const newKey = watchedKey as string;
@@ -642,6 +683,9 @@ export const SecretEditTableRow = ({
s.newSecretName !== key
);
+ const checkedKeyEnvironments = getCheckedKeyEnvironments(newKey);
+ isKeyCheckPending = checkedKeyEnvironments === undefined;
+
const isTaken =
(existingSecretKeys.has(newKey) && !isServerKeyFreed(newKey)) ||
pc.secrets.some(
@@ -653,13 +697,17 @@ export const SecretEditTableRow = ({
: s.secretKey === newKey) ||
// Also check if a create uses this key
(s.type === PendingAction.Create && s.secretKey === newKey))
- );
+ ) ||
+ (Boolean(checkedKeyEnvironments?.length) && !isServerKeyFreed(newKey));
if (isTaken) {
createNotification({
type: "error",
text: "A secret with this name already exists"
});
effectiveKeyDirty = false;
+ isKeyCheckPending = false;
+ } else if (isKeyCheckPending) {
+ effectiveKeyDirty = false;
}
}
@@ -672,7 +720,7 @@ export const SecretEditTableRow = ({
!isTagsDirty &&
!isMetadataDirty
) {
- if (isKeyDirty) {
+ if (isKeyDirty && !isKeyCheckPending) {
// Key conflicted — reset form key back to original so the input updates.
// Update lastAppliedRef first so the effect doesn't re-trigger on the reset.
lastAppliedRef.current = {
@@ -726,7 +774,8 @@ export const SecretEditTableRow = ({
}
// Reset form to mark as clean (like SecretDashboardPage's auto-save)
- const resetKey = effectiveKeyDirty ? watchedKey || secretName : secretName;
+ const resetKey =
+ effectiveKeyDirty || isKeyCheckPending ? watchedKey || secretName : secretName;
reset({
value: watchedValue,
...(isSingleEnvView
@@ -752,16 +801,29 @@ export const SecretEditTableRow = ({
batchStore.getState().pendingChanges.secrets.find((c) => c.secretKey === secretName)?.id;
const savePendingRow = async (knownPendingChangeId?: string) => {
- if (!onPendingSave) return;
- const pendingChangeId = knownPendingChangeId ?? findPendingChangeId();
- if (batchAutoApplyTimer.current) {
- clearTimeout(batchAutoApplyTimer.current);
- if (!knownPendingChangeId) applyBatchEditsRef.current?.();
- }
+ if (!onPendingSave || isSavingPendingChangeRef.current) return;
+ isSavingPendingChangeRef.current = true;
setIsSavingPendingChange.on();
try {
+ let renameKey = getRenameKey();
+ while (renameKey && getCheckedKeyEnvironments(renameKey) === undefined) {
+ // eslint-disable-next-line no-await-in-loop
+ await queryClient
+ .fetchQuery(secretKeyExistsQueryOptions(getKeyCheckParams(renameKey)))
+ .catch(() => []);
+ const latestRenameKey = getRenameKey();
+ if (latestRenameKey === renameKey) break;
+ renameKey = latestRenameKey;
+ }
+ if (renameKey && !knownPendingChangeId) applyBatchEditsRef.current?.();
+ const pendingChangeId = knownPendingChangeId ?? findPendingChangeId();
+ if (batchAutoApplyTimer.current) {
+ clearTimeout(batchAutoApplyTimer.current);
+ if (!knownPendingChangeId) applyBatchEditsRef.current?.();
+ }
await onPendingSave(environment, secretName, pendingChangeId);
} finally {
+ isSavingPendingChangeRef.current = false;
setIsSavingPendingChange.off();
}
};