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
allow bulk duplication of secrets
adilsone7f5f7c4144a
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 9fddfe7ee5..185edde96f 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -1350,7 +1350,8 @@ export const RAW_SECRETS = {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.",+ secretIds:+ "Array of source secret IDs to duplicate. All secrets must belong to the source environment and path. Rotation and honey-token secrets cannot be duplicated. Maximum 50 secrets per request.",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:diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.tsindex 9730be93d9..0603666307 100644--- a/backend/src/server/routes/v4/secret-router.ts+++ b/backend/src/server/routes/v4/secret-router.ts@@ -918,7 +918,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {hide: false,operationId: "duplicateSecretV4",tags: [ApiDocsTags.Secrets],- description: "Duplicate a static secret into another environment",+ description: "Duplicate one or more static secrets into another environment",security: [{bearerAuth: []@@ -940,67 +940,74 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {.default("/").transform(removeTrailingSlash).describe(RAW_SECRETS.DUPLICATE_SECRET.destinationSecretPath),- secretId: z.string().trim().uuid().describe(RAW_SECRETS.DUPLICATE_SECRET.secretId),+ secretIds: z.array(z.string().trim().uuid()).min(1).max(50).describe(RAW_SECRETS.DUPLICATE_SECRET.secretIds),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.")- ])+ 200: z.object({+ results: z.array(+ z.union([+ z.object({+ sourceSecretId: z.string(),+ sourceSecretKey: z.string(),+ destinationSecretId: z.string()+ }),+ z+ .object({+ sourceSecretId: z.string(),+ sourceSecretKey: z.string(),+ 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- }- }- }+ const { projectId, results } = await server.services.secret.duplicateSecrets({+ actorId: req.permission.id,+ actor: req.permission.type,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId,+ ...req.body});- if (approval) {- return { approval };- }-- return {- destinationSecretId,- sourceSecretKey+ const 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};++ await Promise.all(+ results.map((result) =>+ server.services.auditLog.createAuditLog({+ projectId,+ ...req.auditLogInfo,+ event: {+ type: EventType.DUPLICATE_SECRET,+ metadata: {+ sourceEnvironment: req.body.sourceEnvironment,+ sourceSecretPath: req.body.sourceSecretPath,+ sourceSecretId: result.sourceSecretId,+ sourceSecretKey: result.sourceSecretKey,+ destinationEnvironment: req.body.destinationEnvironment,+ destinationSecretPath: req.body.destinationSecretPath,+ destinationSecretId: "destinationSecretId" in result ? result.destinationSecretId : undefined,+ approvalRequestId: "approval" in result ? result.approval.id : undefined,+ shouldOverwrite: req.body.shouldOverwrite,+ attributesCopied+ }+ }+ })+ )+ );++ return { results };}});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.tsindex b121216119..5951adf654 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@@ -365,7 +365,7 @@ export type TDuplicateSecretDTO = {sourceSecretPath: string;destinationEnvironment: string;destinationSecretPath: string;- secretId: string;+ secretIds: string[];shouldOverwrite: boolean;attributesToCopy: TDuplicateSecretAttributes;} & Omit<TProjectPermission, "projectId">;diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.tsindex e3ee648ed0..fb04abb64d 100644--- a/backend/src/services/secret/secret-service.ts+++ b/backend/src/services/secret/secret-service.ts@@ -3491,13 +3491,13 @@ export const secretServiceFactory = ({};};- const duplicateSecret = async ({+ const duplicateSecrets = async ({projectId: inputProjectId,sourceEnvironment,sourceSecretPath,destinationEnvironment,destinationSecretPath,- secretId,+ secretIds,shouldOverwrite,attributesToCopy,actor,@@ -3518,6 +3518,10 @@ export const secretServiceFactory = ({}const projectId = project.id;+ if (sourceSecretPath === destinationSecretPath && sourceEnvironment === destinationEnvironment) {+ throw new BadRequestError({ message: "Cannot duplicate secrets to the same path" });+ }+const { permission } = await permissionService.getProjectPermission({actor,actorId,@@ -3542,63 +3546,75 @@ export const secretServiceFactory = ({});}- const [sourceSecret] = await secretV2BridgeDAL.find({- type: SecretType.Shared,- folderId: sourceFolder.id,- [`${TableName.SecretV2}.id` as "id"]: secretId+ const uniqueSecretIds = Array.from(new Set(secretIds));+ const sourceSecrets = await secretV2BridgeDAL.find({+ $in: {+ [`${TableName.SecretV2}.id` as "id"]: uniqueSecretIds+ },+ [`${TableName.SecretV2}.type` as "type"]: SecretType.Shared,+ [`${TableName.SecretV2}.folderId` as "folderId"]: sourceFolder.id});- if (!sourceSecret) {+ if (sourceSecrets.length !== uniqueSecretIds.length) {+ const foundIds = new Set(sourceSecrets.map((s) => s.id));+ const missingId = uniqueSecretIds.find((id) => !foundIds.has(id));throw new NotFoundError({- message: `Secret with ID '${secretId}' not found in source folder with path '${sourceSecretPath}' and environment slug '${sourceEnvironment}'`+ message: `Secret with ID '${missingId}' 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}` });- }- if (sourceSecretPath === destinationSecretPath && sourceEnvironment === destinationEnvironment) {- throw new BadRequestError({ message: `Cannot duplicate secret to the same path: ${sourceSecret.key}` });- }+ for (const sourceSecret of sourceSecrets) {+ 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, {+ 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+ const existingAtDestRows = await secretV2BridgeDAL.find({+ $in: {+ [`${TableName.SecretV2}.key` as "key"]: sourceSecrets.map((s) => s.key)+ },+ [`${TableName.SecretV2}.folderId` as "folderId"]: destinationFolder.id,+ [`${TableName.SecretV2}.type` as "type"]: SecretType.Shared});+ const existingByKey = new Map(existingAtDestRows.map((row) => [row.key, row]));- 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.`- });+ for (const sourceSecret of sourceSecrets) {+ const existingAtDest = existingByKey.get(sourceSecret.key);+ if (existingAtDest) {+ if (!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({@@ -3606,37 +3622,33 @@ export const secretServiceFactory = ({projectId});- const valueToCopy =- attributesToCopy.value && sourceSecret.encryptedValue- ? secretManagerDecryptor({ cipherTextBlob: sourceSecret.encryptedValue }).toString()- : undefined;- let commentToCopy: string | undefined;- if (attributesToCopy.comment) {- commentToCopy = sourceSecret.encryptedComment- ? secretManagerDecryptor({ cipherTextBlob: sourceSecret.encryptedComment }).toString()- : undefined;- }- 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)- : undefined;-- const secretPayload = {- secretValue: valueToCopy,- secretComment: commentToCopy,- skipMultilineEncoding: skipMultilineEncodingToCopy,- tagIds: tagIdsToCopy,- secretMetadata: secretMetadataToCopy- };+ const buildSecretPayload = (sourceSecret: (typeof sourceSecrets)[number]) => ({+ secretKey: sourceSecret.key,+ secretValue:+ attributesToCopy.value && sourceSecret.encryptedValue+ ? secretManagerDecryptor({ cipherTextBlob: sourceSecret.encryptedValue }).toString()+ : undefined,+ secretComment:+ attributesToCopy.comment && sourceSecret.encryptedComment+ ? secretManagerDecryptor({ cipherTextBlob: sourceSecret.encryptedComment }).toString()+ : undefined,+ skipMultilineEncoding: attributesToCopy.skipMultilineEncoding+ ? Boolean(sourceSecret.skipMultilineEncoding)+ : undefined,+ tagIds: attributesToCopy.tags ? (sourceSecret.tags?.map((t) => t.id) ?? []) : undefined,+ secretMetadata: 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 sourcesToUpdate = sourceSecrets.filter((s) => existingByKey.has(s.key));+ const sourcesToCreate = sourceSecrets.filter((s) => !existingByKey.has(s.key));const destFolderPolicy = await secretApprovalPolicyService.getSecretApprovalPolicy(projectId,@@ -3645,14 +3657,14 @@ export const secretServiceFactory = ({);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 }]+ [SecretOperations.Create]: sourcesToCreate.map(buildSecretPayload),+ [SecretOperations.Update]: sourcesToUpdate.map(buildSecretPayload)},actor,actorId,@@ -3662,30 +3674,47 @@ export const secretServiceFactory = ({return {projectId,- approval,- sourceSecretKey: sourceSecret.key+ results: sourceSecrets.map((sourceSecret) => ({+ sourceSecretId: sourceSecret.id,+ sourceSecretKey: sourceSecret.key,+ approval+ }))};}- const baseSecretArgs = {+ const baseManyArgs = {projectId,environment: destinationEnvironment,secretPath: destinationSecretPath,- secretName: sourceSecret.key,- type: SecretType.Shared,actor,actorId,actorAuthMethod,- actorOrgId,- ...secretPayload- };+ actorOrgId+ } as const;++ const [createdSecrets, updatedSecrets] = await Promise.all([+ sourcesToCreate.length+ ? secretV2BridgeService.createManySecret({+ ...baseManyArgs,+ secrets: sourcesToCreate.map((sourceSecret) => {+ const { secretKey, secretValue, ...rest } = buildSecretPayload(sourceSecret);+ return { secretKey, secretValue: secretValue ?? "", ...rest };+ })+ })+ : Promise.resolve([] as Awaited<ReturnType<typeof secretV2BridgeService.createManySecret>>),+ sourcesToUpdate.length+ ? secretV2BridgeService.updateManySecret({+ ...baseManyArgs,+ mode: SecretUpdateMode.FailOnNotFound,+ secrets: sourcesToUpdate.map(buildSecretPayload)+ })+ : Promise.resolve([] as Awaited<ReturnType<typeof secretV2BridgeService.updateManySecret>>)+ ]);- const destinationSecret = existingAtDest- ? await secretV2BridgeService.updateSecret(baseSecretArgs)- : await secretV2BridgeService.createSecret({- ...baseSecretArgs,- secretValue: baseSecretArgs.secretValue ?? ""- });+ const destinationIdByKey = new Map<string, string>([+ ...createdSecrets.map((s): [string, string] => [s.secretKey, s.id]),+ ...updatedSecrets.map((s): [string, string] => [s.secretKey, s.id])+ ]);await snapshotService.performSnapshot(destinationFolder.id);await secretQueueService.syncSecrets({@@ -3699,8 +3728,11 @@ export const secretServiceFactory = ({return {projectId,- destinationSecretId: destinationSecret.id,- sourceSecretKey: sourceSecret.key+ results: sourceSecrets.map((sourceSecret) => ({+ sourceSecretId: sourceSecret.id,+ sourceSecretKey: sourceSecret.key,+ destinationSecretId: destinationIdByKey.get(sourceSecret.key) as string+ }))};};@@ -3846,7 +3878,7 @@ export const secretServiceFactory = ({getSecretVersions,backfillSecretReferences,moveSecrets,- duplicateSecret,+ duplicateSecrets,startSecretV2Migration,getSecretsCount,getSecretsCountMultiEnv,diff --git a/docs/api-reference/endpoints/secrets/duplicate.mdx b/docs/api-reference/endpoints/secrets/duplicate.mdxnew file mode 100644index 0000000000..e7c0d5e90d--- /dev/null+++ b/docs/api-reference/endpoints/secrets/duplicate.mdx@@ -0,0 +1,4 @@+---+title: "Duplicate"+openapi: "POST /api/v4/secrets/duplicate"+---diff --git a/docs/docs.json b/docs/docs.jsonindex 24fcbd3879..001e332442 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -2146,6 +2146,7 @@"api-reference/endpoints/secrets/create-many","api-reference/endpoints/secrets/update-many","api-reference/endpoints/secrets/delete-many",+ "api-reference/endpoints/secrets/duplicate",{"group": "Legacy","pages": [diff --git a/frontend/src/hooks/api/secrets/mutations.tsx b/frontend/src/hooks/api/secrets/mutations.tsxindex c064b4bd58..0d24e95d90 100644--- a/frontend/src/hooks/api/secrets/mutations.tsx+++ b/frontend/src/hooks/api/secrets/mutations.tsx@@ -545,7 +545,7 @@ export const useDuplicateSecret = ({directory: destinationSecretPath})});- if ("approval" in data) {+ if (data.results.some((result) => "approval" in result)) {queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });queryClient.invalidateQueries({queryKey: secretApprovalRequestKeys.listAllForProject({ projectId })diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.tsindex 159523aa38..76bedc6028 100644--- a/frontend/src/hooks/api/secrets/types.ts+++ b/frontend/src/hooks/api/secrets/types.ts@@ -279,17 +279,20 @@ export type TDuplicateSecretDTO = {sourceSecretPath: string;destinationEnvironment: string;destinationSecretPath: string;- secretId: string;+ secretIds: string[];shouldOverwrite: boolean;attributesToCopy: TDuplicateSecretAttributes;};-export type TDuplicateSecretResponse =+export type TDuplicateSecretResult =| {- destinationSecretId: string;+ sourceSecretId: string;sourceSecretKey: string;+ destinationSecretId: string;}| {+ sourceSecretId: string;+ sourceSecretKey: string;approval: {id: string;slug: string;@@ -298,6 +301,10 @@ export type TDuplicateSecretResponse =};};+export type TDuplicateSecretResponse = {+ results: TDuplicateSecretResult[];+};+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.tsxindex b9377949e6..2fa12fc7e5 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/DuplicateSecretModal.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/DuplicateSecretModal.tsx@@ -61,11 +61,12 @@ const formSchema = z.object({type FormValues = z.infer<typeof formSchema>;+export type DuplicateSecretTarget = { id: string; name: string };+type Props = {isOpen: boolean;onOpenChange: (open: boolean) => void;- secretId?: string;- secretName: string;+ secrets: DuplicateSecretTarget[];secretPath: string;sourceEnvironment: { slug: string; name: string };};@@ -81,8 +82,7 @@ type EnvironmentOption = {};const DuplicateSecretContent = ({- secretId,- secretName,+ secrets,secretPath,sourceEnvironment,onClose@@ -110,14 +110,17 @@ const DuplicateSecretContent = ({const includeSelection = watch("include");const hasSelectedIncludeOption = Object.values(includeSelection).some(Boolean);const availableEnvs = environments.filter((env) => env.slug !== sourceEnvironment.slug);+ const hasSecretsToDuplicate = secrets.length > 0;const handleFormSubmit = async (data: FormValues) => {- if (!secretId || data.environmentIds.length === 0) return;+ if (!hasSecretsToDuplicate || data.environmentIds.length === 0) return;const targets = data.environmentIds.map((id) => availableEnvs.find((env) => env.id === id)).filter((env): env is (typeof availableEnvs)[number] => Boolean(env));+ const secretIds = secrets.map((s) => s.id);+const settled = await Promise.allSettled(targets.map((env) =>duplicateSecret.mutateAsync({@@ -126,7 +129,7 @@ const DuplicateSecretContent = ({sourceSecretPath: secretPath,destinationEnvironment: env.slug,destinationSecretPath: secretPath,- secretId,+ secretIds,shouldOverwrite: data.shouldOverwrite,attributesToCopy: data.include})@@ -141,7 +144,8 @@ const DuplicateSecretContent = ({const env = targets[idx];if (result.status === "fulfilled") {- if ("approval" in result.value) {+ const hasApproval = result.value.results.some((entry) => "approval" in entry);+ if (hasApproval) {approvalEnvs.push({ name: env.name });} else {successEnvs.push({ name: env.name });@@ -160,10 +164,11 @@ const DuplicateSecretContent = ({});if (successEnvs.length > 0) {+ const secretLabel = secrets.length === 1 ? "secret" : `${secrets.length} secrets`;const text =successEnvs.length === 1- ? `Successfully duplicated secret to ${successEnvs[0].name}`- : `Successfully duplicated secret to ${successEnvs.length} environments`;+ ? `Successfully duplicated ${secretLabel} to ${successEnvs[0].name}`+ : `Successfully duplicated ${secretLabel} to ${successEnvs.length} environments`;createNotification({ type: "success", text });}@@ -171,7 +176,7 @@ const DuplicateSecretContent = ({const text =approvalEnvs.length === 1? `Secret approval request generated for ${approvalEnvs[0].name}`- : `Secret approval request generated for ${approvalEnvs.length} environments`;+ : `Secret approval requests generated for ${approvalEnvs.length} environments`;createNotification({ type: "info", text });}@@ -192,23 +197,35 @@ const DuplicateSecretContent = ({<Field><FieldLabel>Source</FieldLabel><FieldContent>- <div className="grid min-w-0 grid-cols-[minmax(0,1fr)_minmax(0,40%)] items-center gap-2 overflow-hidden rounded-md border border-border bg-container px-3 py-2">- <div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden text-sm text-foreground">- <KeyIcon className="text-muted-foreground size-3.5 shrink-0" />- {secretPath !== "/" && (- <span className="text-muted-foreground/60 truncate">{secretPath}</span>- )}- <span className="truncate">{secretName}</span>- </div>- <Badge- variant="info"- className="max-w-full min-w-0 justify-self-end"- isTruncatable- title={sourceEnvironment.name}- >- <span className="block max-w-full">{sourceEnvironment.name}</span>- </Badge>+ <div className="max-h-48 thin-scrollbar divide-y divide-border overflow-y-auto rounded-md border border-border bg-container">+ {secrets.map((s) => (+ <div+ key={s.id}+ className="grid min-w-0 grid-cols-[minmax(0,1fr)_minmax(0,40%)] items-center gap-2 px-3 py-2"+ >+ <div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden text-sm text-foreground">+ <KeyIcon className="text-muted-foreground size-3.5 shrink-0" />+ {secretPath !== "/" && (+ <span className="text-muted-foreground/60 truncate">{secretPath}</span>+ )}+ <span className="truncate">{s.name}</span>+ </div>+ <Badge+ variant="info"+ className="max-w-full min-w-0 justify-self-end"+ isTruncatable+ title={sourceEnvironment.name}+ >+ <span className="block max-w-full">{sourceEnvironment.name}</span>+ </Badge>+ </div>+ ))}</div>+ {secrets.length > 1 && (+ <FieldDescription>+ {secrets.length} secrets will be duplicated into each selected destination.+ </FieldDescription>+ )}</FieldContent></Field>@@ -326,7 +343,10 @@ const DuplicateSecretContent = ({type="submit"variant="project"isDisabled={- selectedEnvIds.length === 0 || !secretId || isSubmitting || !hasSelectedIncludeOption+ selectedEnvIds.length === 0 ||+ !hasSecretsToDuplicate ||+ isSubmitting ||+ !hasSelectedIncludeOption}isPending={isSubmitting}>@@ -345,7 +365,8 @@ export const DuplicateSecretModal = ({ isOpen, onOpenChange, ...props }: Props)<DialogTitle>Duplicate Secret</DialogTitle></div><DialogDescription>- Copy this secret and its metadata into one or more environments.+ Copy the selected secret{props.secrets.length > 1 ? "s" : ""} and their metadata into one+ or more environments.</DialogDescription></DialogHeader><DuplicateSecretContent {...props} onClose={() => onOpenChange(false)} />diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsxindex 5481a230ce..cee25358cd 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretTableRow/SecretEditTableRow.tsx@@ -1877,8 +1877,7 @@ export const SecretEditTableRow = ({<DuplicateSecretModalisOpen={popUp.duplicateSecret.isOpen}onOpenChange={(open) => handlePopUpToggle("duplicateSecret", open)}- secretId={secretId}- secretName={secretName}+ secrets={secretId ? [{ id: secretId, name: secretName }] : []}secretPath={secretPath}sourceEnvironment={{ slug: environment, name: environmentName }}/>diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsxindex 7d234b642d..3621855f5d 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx@@ -1,6 +1,6 @@import { useMemo } from "react";import { subject } from "@casl/ability";-import { FolderInputIcon, TagsIcon, TrashIcon } from "lucide-react";+import { CopyPlus, FolderInputIcon, TagsIcon, TrashIcon } from "lucide-react";import { twMerge } from "tailwind-merge";import { createNotification } from "@app/components/notifications";@@ -27,6 +27,7 @@ import {TDeleteSecretBatchDTO,TSecretFolder} from "@app/hooks/api/types";+import { DuplicateSecretModal } from "@app/pages/secret-manager/OverviewPage/components/SecretTableRow/DuplicateSecretModal";import {BulkDeleteDialog,BulkTagDialog,@@ -70,7 +71,8 @@ export const SelectionPanel = ({const { handlePopUpOpen, handlePopUpToggle, handlePopUpClose, popUp } = usePopUp(["bulkDeleteEntries","bulkMoveSecrets",- "bulkTagSecrets"+ "bulkTagSecrets",+ "bulkDuplicateSecrets"] as const);const selectedFolderCount = Object.keys(selectedEntries.folder).length;@@ -314,6 +316,37 @@ export const SelectionPanel = ({"Rotations cannot be deleted from this view. Use the delete action on the rotation row instead.";}+ const selectedSecretEntries = Object.values(selectedEntries[EntryType.SECRET]).flatMap((perEnv) =>+ Object.entries(perEnv)+ );+ const duplicateSourceEnvSlugs = new Set(selectedSecretEntries.map(([envSlug]) => envSlug));++ const isDuplicateDisabled =+ areFoldersSelected ||+ isHoneyTokenSelected ||+ Boolean(selectedHoneyTokenCount) ||+ areRotationsSelected ||+ isManagedSecretSelected ||+ duplicateSourceEnvSlugs.size > 1;++ let duplicateDisabledReason = "Folders cannot be duplicated";+ if (isHoneyTokenSelected || Boolean(selectedHoneyTokenCount)) {+ duplicateDisabledReason = "Honey token secrets cannot be duplicated";+ } else if (areRotationsSelected || isManagedSecretSelected) {+ duplicateDisabledReason = "Rotated secrets cannot be duplicated";+ } else if (duplicateSourceEnvSlugs.size > 1) {+ duplicateDisabledReason = "Selected secrets must all be from the same source environment";+ }++ const duplicateSourceEnv =+ duplicateSourceEnvSlugs.size === 1+ ? userAvailableEnvs.find((env) => env.slug === selectedSecretEntries[0][0])+ : undefined;+ const duplicateSecrets = selectedSecretEntries.map(([, secret]) => ({+ id: secret.id,+ name: secret.key+ }));+return (<><div@@ -365,6 +398,23 @@ export const SelectionPanel = ({</TooltipTrigger><TooltipContent>{moveDisabledReason}</TooltipContent></Tooltip>+ {selectedKeysCount > 0 && (+ <Tooltip open={isDuplicateDisabled ? undefined : false}>+ <TooltipTrigger>+ <Button+ isDisabled={isDuplicateDisabled}+ variant="project"+ className="ml-2"+ onClick={() => handlePopUpOpen("bulkDuplicateSecrets")}+ size="xs"+ >+ <CopyPlus />+ Duplicate+ </Button>+ </TooltipTrigger>+ <TooltipContent>{duplicateDisabledReason}</TooltipContent>+ </Tooltip>+ )}<Tooltip open={isDeleteDisabled ? undefined : false}><TooltipTrigger><Button@@ -418,6 +468,20 @@ export const SelectionPanel = ({secretsToDeleteKeys={secretsToDeleteKeys}usedBySecretSyncsFiltered={usedBySecretSyncsFiltered}/>+ {duplicateSourceEnv && (+ <DuplicateSecretModal+ isOpen={popUp.bulkDuplicateSecrets.isOpen}+ onOpenChange={(isOpen) => {+ handlePopUpToggle("bulkDuplicateSecrets", isOpen);+ if (!isOpen) {+ resetSelectedEntries();+ }+ }}+ secrets={duplicateSecrets}+ secretPath={secretPath}+ sourceEnvironment={{ slug: duplicateSourceEnv.slug, name: duplicateSourceEnv.name }}+ />+ )}</>);};