Skip to content

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

add new endpoint to perform the duplication between environment operation

adilson70046c1f1342
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 42e28007ab..b07db4dfec 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -53,6 +53,7 @@ import {
TSecretSyncRaw,
TUpdateSecretSyncDTO
} from "@app/services/secret-sync/secret-sync-types";
+import { TDuplicateSecretAttributes } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
import { TWebhookPayloads } from "@app/services/webhook/webhook-types";
import { WorkflowIntegration } from "@app/services/workflow-integration/workflow-integration-types";
@@ -166,6 +167,7 @@ export enum EventType {
UPDATE_SECRET = "update-secret",
UPDATE_SECRETS = "update-secrets",
MOVE_SECRETS = "move-secrets",
+ DUPLICATE_SECRET = "duplicate-secret",
DELETE_SECRET = "delete-secret",
DELETE_SECRETS = "delete-secrets",
REDACT_SECRET_VERSION_VALUE = "redact-secret-version-value",
@@ -1091,6 +1093,22 @@ interface MoveSecretsEvent {
};
}
+interface DuplicateSecretEvent {
+ type: EventType.DUPLICATE_SECRET;
+ metadata: {
+ sourceEnvironment: string;
+ sourceSecretPath: string;
+ sourceSecretId: string;
+ sourceSecretKey: string;
+ destinationEnvironment: string;
+ destinationSecretPath: string;
+ destinationSecretId?: string;
+ approvalRequestId?: string;
+ shouldOverwrite: boolean;
+ attributesCopied: TDuplicateSecretAttributes;
+ };
+}
+
interface DeleteSecretEvent {
type: EventType.DELETE_SECRET;
metadata: {
@@ -6417,6 +6435,7 @@ export type Event =
| UpdateSecretEvent
| UpdateSecretBatchEvent
| MoveSecretsEvent
+ | DuplicateSecretEvent
| DeleteSecretEvent
| DeleteSecretBatchEvent
| RedactSecretVersionValueEvent
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index ecf161488d..9fddfe7ee5 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1343,6 +1343,18 @@ export const RAW_SECRETS = {
secretPath: "The folder path where the secret is located.",
includeAllEntities:
"When true, includes all project users, identities, and groups in the response, even those without any access to the secret."
+ },
+ DUPLICATE_SECRET: {
+ projectId: "The ID of the project containing the secret.",
+ sourceEnvironment: "The slug of the source environment.",
+ sourceSecretPath: "The folder path of the source secret.",
+ destinationEnvironment: "The slug of the destination environment.",
+ destinationSecretPath: "The folder path where the secret will be duplicated to.",
+ secretId: "The ID of the source secret to duplicate. Rotation and honey-token secrets cannot be duplicated.",
+ shouldOverwrite:
+ "When true, overwrite an existing secret with the same key at the destination. When false (default), the request fails if the destination already has a secret with that key.",
+ attributesToCopy:
+ "Object specifying which attributes of the source secret to copy to the destination. Each key is optional and defaults to false. Available keys: value, comment, tags, metadata, skipMultilineEncoding."
}
} as const;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index bbe53d35bf..59db3e262a 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1783,6 +1783,7 @@ export const registerRoutes = async (
reminderService,
secretVersionV2DAL: secretVersionV2BridgeDAL,
secretV2BridgeDAL,
+ kmsService,
userGroupMembershipDAL,
identityGroupMembershipDAL
});
diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.ts
index 32e7358159..9730be93d9 100644
--- a/backend/src/server/routes/v4/secret-router.ts
+++ b/backend/src/server/routes/v4/secret-router.ts
@@ -31,6 +31,16 @@ const SecretReferenceNode = z.object({
secretPath: z.string()
});
+const DuplicateSecretAttributesSchema = z
+ .object({
+ value: z.boolean().default(false),
+ comment: z.boolean().default(false),
+ tags: z.boolean().default(false),
+ metadata: z.boolean().default(false),
+ skipMultilineEncoding: z.boolean().default(false)
+ })
+ .default({});
+
const convertStringBoolean = (defaultValue: boolean = false) => {
return z
.enum(["true", "false"])
@@ -898,6 +908,102 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/duplicate",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "duplicateSecretV4",
+ tags: [ApiDocsTags.Secrets],
+ description: "Duplicate a static secret into another environment",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.DUPLICATE_SECRET.projectId),
+ sourceEnvironment: z.string().trim().describe(RAW_SECRETS.DUPLICATE_SECRET.sourceEnvironment),
+ sourceSecretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.DUPLICATE_SECRET.sourceSecretPath),
+ destinationEnvironment: z.string().trim().describe(RAW_SECRETS.DUPLICATE_SECRET.destinationEnvironment),
+ destinationSecretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.DUPLICATE_SECRET.destinationSecretPath),
+ secretId: z.string().trim().uuid().describe(RAW_SECRETS.DUPLICATE_SECRET.secretId),
+ shouldOverwrite: z.boolean().default(false).describe(RAW_SECRETS.DUPLICATE_SECRET.shouldOverwrite),
+ attributesToCopy: DuplicateSecretAttributesSchema.describe(RAW_SECRETS.DUPLICATE_SECRET.attributesToCopy)
+ }),
+ response: {
+ 200: z.union([
+ z.object({
+ destinationSecretId: z.string(),
+ sourceSecretKey: z.string()
+ }),
+ z
+ .object({ approval: SecretApprovalRequestsSchema })
+ .describe("Returned when the destination has an active secret-approval policy.")
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { destinationSecretId, approval, sourceSecretKey, projectId } =
+ await server.services.secret.duplicateSecret({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.DUPLICATE_SECRET,
+ metadata: {
+ sourceEnvironment: req.body.sourceEnvironment,
+ sourceSecretPath: req.body.sourceSecretPath,
+ sourceSecretId: req.body.secretId,
+ sourceSecretKey,
+ destinationEnvironment: req.body.destinationEnvironment,
+ destinationSecretPath: req.body.destinationSecretPath,
+ destinationSecretId,
+ approvalRequestId: approval?.id,
+ shouldOverwrite: req.body.shouldOverwrite,
+ attributesCopied: {
+ value: req.body.attributesToCopy.value,
+ comment: req.body.attributesToCopy.comment,
+ tags: req.body.attributesToCopy.tags,
+ metadata: req.body.attributesToCopy.metadata,
+ skipMultilineEncoding: req.body.attributesToCopy.skipMultilineEncoding
+ }
+ }
+ }
+ });
+
+ if (approval) {
+ return { approval };
+ }
+
+ return {
+ destinationSecretId,
+ sourceSecretKey
+ };
+ }
+ });
+
server.route({
method: "POST",
url: "/batch",
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 9bb0e81e78..b121216119 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
@@ -351,6 +351,25 @@ export type TMoveSecretsDTO = {
shouldOverwrite: boolean;
} & Omit<TProjectPermission, "projectId">;
+export type TDuplicateSecretAttributes = {
+ value?: boolean;
+ comment?: boolean;
+ tags?: boolean;
+ metadata?: boolean;
+ skipMultilineEncoding?: boolean;
+};
+
+export type TDuplicateSecretDTO = {
+ projectId: string;
+ sourceEnvironment: string;
+ sourceSecretPath: string;
+ destinationEnvironment: string;
+ destinationSecretPath: string;
+ secretId: string;
+ shouldOverwrite: boolean;
+ attributesToCopy: TDuplicateSecretAttributes;
+} & Omit<TProjectPermission, "projectId">;
+
export type TAttachSecretTagsDTO = {
projectId: string;
secretName: string;
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index a8c4580ad7..cb1869e8df 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -10,7 +10,8 @@ import {
SecretEncryptionAlgo,
SecretKeyEncoding,
SecretsSchema,
- SecretType
+ SecretType,
+ TableName
} from "@app/db/schemas";
import { TIdentityGroupMembershipDALFactory } from "@app/ee/services/group/identity-group-membership-dal";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
@@ -42,12 +43,15 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { OrgServiceActor } from "@app/lib/types";
import {
SecretUpdateMode,
+ TDuplicateSecretDTO,
TGetSecretReferencesDTO,
TGetSecretsRawByFolderMappingsDTO
} from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
import { ChangeType } from "../folder-commit/folder-commit-service";
+import { TKmsServiceFactory } from "../kms/kms-service";
+import { KmsDataKey } from "../kms/kms-types";
import { TProjectDALFactory } from "../project/project-dal";
import { TProjectBotServiceFactory } from "../project-bot/project-bot-service";
import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
@@ -140,7 +144,8 @@ type TSecretServiceFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
reminderService: Pick<TReminderServiceFactory, "createReminder">;
secretVersionV2DAL: Pick<TSecretVersionV2DALFactory, "findOne">;
- secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "invalidateSecretCacheByProjectId">;
+ secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "invalidateSecretCacheByProjectId" | "find">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
};
@@ -169,6 +174,7 @@ export const secretServiceFactory = ({
reminderService,
secretVersionV2DAL,
secretV2BridgeDAL,
+ kmsService,
userGroupMembershipDAL,
identityGroupMembershipDAL
}: TSecretServiceFactoryDep) => {
@@ -3485,6 +3491,212 @@ export const secretServiceFactory = ({
};
};
+ const duplicateSecret = async ({
+ projectId: inputProjectId,
+ sourceEnvironment,
+ sourceSecretPath,
+ destinationEnvironment,
+ destinationSecretPath,
+ secretId,
+ shouldOverwrite,
+ attributesToCopy,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TDuplicateSecretDTO) => {
+ const project = await requestMemoize(requestMemoKeys.projectFindById(inputProjectId), () =>
+ projectDAL.findById(inputProjectId)
+ );
+ if (!project) {
+ throw new NotFoundError({ message: `Project with ID '${inputProjectId}' not found` });
+ }
+ if (project.version !== ProjectVersion.V3) {
+ throw new BadRequestError({
+ message: "Duplicating secrets is only supported on v3 projects. Please upgrade your project."
+ });
+ }
+ const projectId = project.id;
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+
+ const [sourceFolder, destinationFolder] = await Promise.all([
+ folderDAL.findBySecretPath(projectId, sourceEnvironment, sourceSecretPath),
+ folderDAL.findBySecretPath(projectId, destinationEnvironment, destinationSecretPath)
+ ]);
+ if (!sourceFolder) {
+ throw new NotFoundError({
+ message: `Source folder with path '${sourceSecretPath}' in environment with slug '${sourceEnvironment}' not found`
+ });
+ }
+ if (!destinationFolder) {
+ throw new NotFoundError({
+ message: `Destination folder with path '${destinationSecretPath}' in environment with slug '${destinationEnvironment}' not found`
+ });
+ }
+
+ const [sourceSecret] = await secretV2BridgeDAL.find({
+ type: SecretType.Shared,
+ folderId: sourceFolder.id,
+ [`${TableName.SecretV2}.id` as "id"]: secretId
+ });
+ if (!sourceSecret) {
+ throw new NotFoundError({
+ message: `Secret with ID '${secretId}' not found in source folder with path '${sourceSecretPath}' and environment slug '${sourceEnvironment}'`
+ });
+ }
+ if (sourceSecret.isRotatedSecret) {
+ throw new BadRequestError({ message: `Cannot duplicate rotated secret: ${sourceSecret.key}` });
+ }
+ if (sourceSecret.isHoneyTokenSecret) {
+ throw new BadRequestError({ message: `Cannot duplicate honey token secret: ${sourceSecret.key}` });
+ }
+
+ const sourceTagSlugs = sourceSecret.tags?.map((t) => t.slug) ?? [];
+ throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {
+ environment: sourceEnvironment,
+ secretPath: sourceSecretPath,
+ secretName: sourceSecret.key,
+ secretTags: sourceTagSlugs
+ });
+ if (attributesToCopy.value) {
+ throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.ReadValue, {
+ environment: sourceEnvironment,
+ secretPath: sourceSecretPath,
+ secretName: sourceSecret.key,
+ secretTags: sourceTagSlugs
+ });
+ }
+
+ const [existingAtDest] = await secretV2BridgeDAL.find({
+ folderId: destinationFolder.id,
+ type: SecretType.Shared,
+ [`${TableName.SecretV2}.key` as "key"]: sourceSecret.key
+ });
+
+ if (existingAtDest && !shouldOverwrite) {
+ throw new BadRequestError({
+ message: `Secret with key '${sourceSecret.key}' already exists at destination. Set shouldOverwrite to true to replace it.`
+ });
+ }
+ if (existingAtDest?.isRotatedSecret) {
+ throw new BadRequestError({
+ message: `Cannot duplicate to '${destinationFolder.path}' because the destination key '${sourceSecret.key}' is managed by a secret rotation.`
+ });
+ }
+ if (existingAtDest?.isHoneyTokenSecret) {
+ throw new BadRequestError({
+ message: `Cannot duplicate to '${destinationFolder.path}' because the destination key '${sourceSecret.key}' is a honey token secret.`
+ });
+ }
+
+ const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ const valueToCopy =
+ attributesToCopy.value && sourceSecret.encryptedValue
+ ? secretManagerDecryptor({ cipherTextBlob: sourceSecret.encryptedValue }).toString()
+ : "";
+ let commentToCopy: string | undefined;
+ if (attributesToCopy.comment) {
+ commentToCopy = sourceSecret.encryptedComment
+ ? secretManagerDecryptor({ cipherTextBlob: sourceSecret.encryptedComment }).toString()
+ : "";
+ }
+ const secretMetadataToCopy = attributesToCopy.metadata
+ ? (sourceSecret.secretMetadata?.map((el) => ({
+ key: el.key,
+ value: el.encryptedValue
+ ? secretManagerDecryptor({ cipherTextBlob: el.encryptedValue }).toString()
+ : (el.value ?? ""),
+ isEncrypted: Boolean(el.encryptedValue)
+ })) ?? [])
+ : undefined;
+ const tagIdsToCopy = attributesToCopy.tags ? (sourceSecret.tags?.map((t) => t.id) ?? []) : undefined;
+ const skipMultilineEncodingToCopy = attributesToCopy.skipMultilineEncoding
+ ? Boolean(sourceSecret.skipMultilineEncoding)
+ : false;
+
+ const secretPayload = {
+ secretValue: valueToCopy,
+ secretComment: commentToCopy,
+ skipMultilineEncoding: skipMultilineEncodingToCopy,
+ tagIds: tagIdsToCopy,
+ secretMetadata: secretMetadataToCopy
+ };
+
+ const destFolderPolicy = await secretApprovalPolicyService.getSecretApprovalPolicy(
+ projectId,
+ destinationEnvironment,
+ destinationSecretPath
+ );
+
+ if (destFolderPolicy && actor === ActorType.USER) {
+ const op = existingAtDest ? SecretOperations.Update : SecretOperations.Create;
+ const approval = await secretApprovalRequestService.generateSecretApprovalRequestV2Bridge({
+ projectId,
+ environment: destinationEnvironment,
+ secretPath: destinationSecretPath,
+ policy: destFolderPolicy,
+ data: {
+ [op]: [{ secretKey: sourceSecret.key, ...secretPayload }]
+ },
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ });
+
+ return {
+ projectId,
+ approval,
+ sourceSecretKey: sourceSecret.key
+ };
+ }
+
+ const baseSecretArgs = {
+ projectId,
+ environment: destinationEnvironment,
+ secretPath: destinationSecretPath,
+ secretName: sourceSecret.key,
+ type: SecretType.Shared,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ ...secretPayload
+ };
+
+ const destinationSecret = existingAtDest
+ ? await secretV2BridgeService.updateSecret(baseSecretArgs)
+ : await secretV2BridgeService.createSecret(baseSecretArgs);
+
+ await snapshotService.performSnapshot(destinationFolder.id);
+ await secretQueueService.syncSecrets({
+ projectId: project.id,
+ orgId: project.orgId,
+ secretPath: destinationFolder.path,
+ environmentSlug: destinationFolder.environment.slug,
+ actorId,
+ actor
+ });
+
+ return {
+ projectId,
+ destinationSecretId: destinationSecret.id,
+ sourceSecretKey: sourceSecret.key
+ };
+ };
+
const startSecretV2Migration = async ({
projectId,
actor,
@@ -3627,6 +3839,7 @@ export const secretServiceFactory = ({
getSecretVersions,
backfillSecretReferences,
moveSecrets,
+ duplicateSecret,
startSecretV2Migration,
getSecretsCount,
getSecretsCountMultiEnv,
diff --git a/frontend/src/hooks/api/secrets/index.ts b/frontend/src/hooks/api/secrets/index.ts
index 6bbd156d4a..3f5596e378 100644
--- a/frontend/src/hooks/api/secrets/index.ts
+++ b/frontend/src/hooks/api/secrets/index.ts
@@ -4,6 +4,7 @@ export {
useCreateSecretV3,
useDeleteSecretBatch,
useDeleteSecretV3,
+ useDuplicateSecret,
useMoveSecrets,
useRedactSecretValue,
useUpdateSecretBatch,
diff --git a/frontend/src/hooks/api/secrets/mutations.tsx b/frontend/src/hooks/api/secrets/mutations.tsx
index c54ba599b3..c064b4bd58 100644
--- a/frontend/src/hooks/api/secrets/mutations.tsx
+++ b/frontend/src/hooks/api/secrets/mutations.tsx
@@ -17,6 +17,8 @@ import {
TCreateSecretsV3DTO,
TDeleteSecretBatchDTO,
TDeleteSecretsV3DTO,
+ TDuplicateSecretDTO,
+ TDuplicateSecretResponse,
TMoveSecretsDTO,
TUpdateSecretBatchDTO,
TUpdateSecretsV3DTO
@@ -483,6 +485,77 @@ export const useMoveSecrets = ({
});
};
+export const useDuplicateSecret = ({
+ options
+}: {
+ options?: Omit<
+ MutationOptions<TDuplicateSecretResponse, object, TDuplicateSecretDTO>,
+ "mutationFn"
+ >;
+} = {}) => {
+ const queryClient = useQueryClient();
+
+ return useMutation<TDuplicateSecretResponse, object, TDuplicateSecretDTO>({
+ mutationFn: async (dto) => {
+ const { data } = await apiRequest.post<TDuplicateSecretResponse>(
+ "/api/v4/secrets/duplicate",
+ dto
+ );
+ return data;
+ },
+ onSuccess: (data, { projectId, destinationEnvironment, destinationSecretPath }) => {
+ queryClient.invalidateQueries({
+ queryKey: dashboardKeys.getDashboardSecrets({
+ projectId,
+ secretPath: destinationSecretPath
+ })
+ });
+ queryClient.invalidateQueries({
+ queryKey: secretKeys.getProjectSecret({
+ projectId,
+ environment: destinationEnvironment,
+ secretPath: destinationSecretPath
+ })
+ });
+ queryClient.invalidateQueries({
+ queryKey: secretSnapshotKeys.list({
+ environment: destinationEnvironment,
+ projectId,
+ directory: destinationSecretPath
+ })
+ });
+ queryClient.invalidateQueries({
+ queryKey: secretSnapshotKeys.count({
+ environment: destinationEnvironment,
+ projectId,
+ directory: destinationSecretPath
+ })
+ });
+ queryClient.invalidateQueries({
+ queryKey: commitKeys.count({
+ projectId,
+ environment: destinationEnvironment,
+ directory: destinationSecretPath
+ })
+ });
+ queryClient.invalidateQueries({
+ queryKey: commitKeys.history({
+ projectId,
+ environment: destinationEnvironment,
+ directory: destinationSecretPath
+ })
+ });
+ if ("approval" in data) {
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
+ queryClient.invalidateQueries({
+ queryKey: secretApprovalRequestKeys.listAllForProject({ projectId })
+ });
+ }
+ },
+ ...options
+ });
+};
+
export const createSecret = async (dto: TCreateSecretsV3DTO) => {
const { data } = await apiRequest.post(`/api/v4/secrets/${dto.secretKey}`, dto);
return data;
diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.ts
index 76f6b0731a..159523aa38 100644
--- a/frontend/src/hooks/api/secrets/types.ts
+++ b/frontend/src/hooks/api/secrets/types.ts
@@ -265,6 +265,39 @@ export type TMoveSecretsDTO = {
shouldOverwrite: boolean;
};
+export type TDuplicateSecretAttributes = {
+ value?: boolean;
+ comment?: boolean;
+ tags?: boolean;
+ metadata?: boolean;
+ skipMultilineEncoding?: boolean;
+};
+
+export type TDuplicateSecretDTO = {
+ projectId: string;
+ sourceEnvironment: string;
+ sourceSecretPath: string;
+ destinationEnvironment: string;
+ destinationSecretPath: string;
+ secretId: string;
+ shouldOverwrite: boolean;
+ attributesToCopy: TDuplicateSecretAttributes;
+};
+
+export type TDuplicateSecretResponse =
+ | {
+ destinationSecretId: string;
+ sourceSecretKey: string;
+ }
+ | {
+ approval: {
+ id: string;
+ slug: string;
+ status: string;
+ committerUserId: string;
+ };
+ };
+
export type TGetSecretReferenceTreeDTO = {
secretKey: string;
secretPath: string;
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/DuplicateSecretModal.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/DuplicateSecretModal.tsx
index d0db11c8f8..d0ab6d9248 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/DuplicateSecretModal.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/DuplicateSecretModal.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { CheckIcon, ChevronsUpDownIcon, CopyIcon, KeyIcon } from "lucide-react";
+import { createNotification } from "@app/components/notifications";
import {
Badge,
Button,
@@ -24,6 +25,7 @@ import {
} from "@app/components/v3";
import { cn } from "@app/components/v3/utils";
import { useProject } from "@app/context";
+import { useDuplicateSecret } from "@app/hooks/api/secrets";
type IncludeKey = "value" | "comment" | "tags" | "metadata" | "skipMultilineEncoding";
@@ -50,6 +52,7 @@ const DEFAULT_INCLUDE: Record<IncludeKey, boolean> = {
type Props = {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
+ secretId?: string;
secretName: string;
secretPath: string;
sourceEnvironment: { slug: string; name: string };
@@ -58,17 +61,20 @@ type Props = {
export const DuplicateSecretModal = ({
isOpen,
onOpenChange,
+ secretId,
secretName,
secretPath,
sourceEnvironment
}: Props) => {
const {
- currentProject: { environments }
+ currentProject: { id: projectId, environments }
} = useProject();
+ const duplicateSecret = useDuplicateSecret();
const [selectedEnvIds, setSelectedEnvIds] = useState<string[]>([]);
const [includeOptions, setIncludeOptions] =
useState<Record<IncludeKey, boolean>>(DEFAULT_INCLUDE);
+ const [shouldOverwrite, setShouldOverwrite] = useState(false);
const [popoverOpen, setPopoverOpen] = useState(false);
const [searchValue, setSearchValue] = useState("");
@@ -76,6 +82,7 @@ export const DuplicateSecretModal = ({
if (!isOpen) {
setSelectedEnvIds([]);
setIncludeOptions(DEFAULT_INCLUDE);
+ setShouldOverwrite(false);
setSearchValue("");
setPopoverOpen(false);
}
@@ -93,24 +100,98 @@ export const DuplicateSecretModal = ({
setIncludeOptions((prev) => ({ ...prev, [key]: !prev[key] }));
};
+ const handleDuplicate = async () => {
+ if (!secretId || selectedEnvIds.length === 0) return;
+
+ const targets = selectedEnvIds
+ .map((id) => availableEnvs.find((env) => env.id === id))
+ .filter((env): env is (typeof availableEnvs)[number] => Boolean(env));
+
+ const results = await Promise.allSettled(
+ targets.map((env) =>
+ duplicateSecret.mutateAsync({
+ projectId,
+ sourceEnvironment: sourceEnvironment.slug,
+ sourceSecretPath: secretPath,
+ destinationEnvironment: env.slug,
+ destinationSecretPath: secretPath,
+ secretId,
+ shouldOverwrite,
+ attributesToCopy: includeOptions
+ })
+ )
+ );
+
+ let successCount = 0;
+ let approvalCount = 0;
+ const failures: { env: string; message: string }[] = [];
+
+ results.forEach((result, idx) => {
+ const envName = targets[idx].name;
+ if (result.status === "fulfilled") {
+ if ("approval" in result.value) {
+ approvalCount += 1;
+ } else {
+ successCount += 1;
+ }
+ } else {
+ const reason = result.reason as {
+ response?: { data?: { message?: string } };
+ message?: string;
+ };
+ failures.push({
+ env: envName,
+ message: reason?.response?.data?.message ?? reason?.message ?? "Unknown error"
+ });
+ }
+ });
+
+ if (successCount > 0) {
+ createNotification({
+ type: "success",
+ text: `Duplicated '${secretName}' to ${successCount} environment${successCount === 1 ? "" : "s"}`
+ });
+ }
+ if (approvalCount > 0) {
+ createNotification({
+ type: "info",
+ text: `${approvalCount} environment${approvalCount === 1 ? "" : "s"} require approval before the secret is created`
+ });
+ }
+ failures.forEach(({ env, message }) => {
+ createNotification({
+ type: "error",
+ text: `Failed to duplicate to ${env}: ${message}`
+ });
+ });
+
+ if (failures.length === 0) {
+ onOpenChange(false);
+ }
+ };
+
+ const selectedEnvCount = selectedEnvIds.length;
+ const singleSelectedEnvName =
+ selectedEnvCount === 1
+ ? (availableEnvs.find((e) => e.id === selectedEnvIds[0])?.name ?? null)
+ : null;
+
let triggerLabel: string;
- if (selectedEnvIds.length === 0) {
+ if (selectedEnvCount === 0) {
triggerLabel = "Search environments...";
- } else if (selectedEnvIds.length === 1) {
- const env = availableEnvs.find((e) => e.id === selectedEnvIds[0]);
- triggerLabel = env?.name ?? "1 environment";
+ } else if (selectedEnvCount === 1) {
+ triggerLabel = singleSelectedEnvName ?? "1 environment";
} else {
- triggerLabel = `${selectedEnvIds.length} environments`;
+ triggerLabel = `${selectedEnvCount} environments`;
}
let actionLabel: string;
- if (selectedEnvIds.length === 0) {
+ if (selectedEnvCount === 0) {
actionLabel = "Duplicate to ...";
- } else if (selectedEnvIds.length === 1) {
- const env = availableEnvs.find((e) => e.id === selectedEnvIds[0]);
- actionLabel = `Duplicate to ${env?.name ?? "environment"}`;
+ } else if (selectedEnvCount === 1) {
+ actionLabel = `Duplicate to ${singleSelectedEnvName ?? "environment"}`;
} else {
- actionLabel = `Duplicate to ${selectedEnvIds.length} environments`;
+ actionLabel = `Duplicate to ${selectedEnvCount} environments`;
}
return (
@@ -229,14 +310,42 @@ export const DuplicateSecretModal = ({
</div>
</div>
+ <div className="flex flex-col gap-1.5">
+ <p className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
+ If a secret with the same key already exists
+ </p>
+ {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
+ <label
+ htmlFor="duplicate-overwrite"
+ className="flex cursor-pointer items-start gap-3 rounded-md border border-border p-3"
+ >
+ <Checkbox
+ id="duplicate-overwrite"
+ variant="project"
+ isChecked={shouldOverwrite}
+ onCheckedChange={(checked) => setShouldOverwrite(Boolean(checked))}
+ className="mt-0.5"
+ />
+ <div className="flex flex-col gap-0.5">
+ <span className="text-sm text-foreground">Overwrite existing secret</span>
+ <span className="text-muted-foreground text-xs">
+ Replace the destination secret&apos;s selected fields with the values from the
+ source. Without this, duplication fails for environments that already have a secret
+ with this key.
+ </span>
+ </div>
+ </label>
+ </div>
+
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<Button
variant="project"
- isDisabled={selectedEnvIds.length === 0}
- onClick={() => onOpenChange(false)}
+ isDisabled={selectedEnvIds.length === 0 || !secretId}
+ isPending={duplicateSecret.isPending}
+ onClick={handleDuplicate}
>
<CopyIcon />
{actionLabel}
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 13dada2aac..5eff96e207 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx
@@ -1876,6 +1876,7 @@ export const SecretEditTableRow = ({
<DuplicateSecretModal
isOpen={popUp.duplicateSecret.isOpen}
onOpenChange={(open) => handlePopUpToggle("duplicateSecret", open)}
+ secretId={secretId}
secretName={secretName}
secretPath={secretPath}
sourceEnvironment={{ slug: environment, name: environmentName }}