Skip to content

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

feat: implement bulk import functionality for KMS keys

Victor Hugo dos Santos680fcff3c92d
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 0b13b2a71b..775e9fb770 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -474,6 +474,7 @@ export enum EventType {
CMEK_GET_PUBLIC_KEY = "cmek-get-public-key",
CMEK_GET_PRIVATE_KEY = "cmek-get-private-key",
CMEK_BULK_EXPORT_PRIVATE_KEYS = "cmek-bulk-export-private-keys",
+ CMEK_BULK_IMPORT_KEYS = "cmek-bulk-import-keys",
UPDATE_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS = "update-external-group-org-role-mapping",
GET_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS = "get-external-group-org-role-mapping",
@@ -3657,6 +3658,14 @@ interface CmekBulkGetPrivateKeysEvent {
};
}
+interface CmekBulkImportKeysEvent {
+ type: EventType.CMEK_BULK_IMPORT_KEYS;
+ metadata: {
+ keyNames: string[];
+ projectId: string;
+ };
+}
+
interface GetExternalGroupOrgRoleMappingsEvent {
type: EventType.GET_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS;
metadata?: Record<string, never>; // not needed, based off orgId
@@ -6298,6 +6307,7 @@ export type Event =
| CmekGetPublicKeyEvent
| CmekGetPrivateKeyEvent
| CmekBulkGetPrivateKeysEvent
+ | CmekBulkImportKeysEvent
| GetExternalGroupOrgRoleMappingsEvent
| UpdateExternalGroupOrgRoleMappingsEvent
| GetProjectTemplatesEvent
diff --git a/backend/src/server/routes/v1/cmek-router.ts b/backend/src/server/routes/v1/cmek-router.ts
index 9c7ee9a5a9..2f0062ba36 100644
--- a/backend/src/server/routes/v1/cmek-router.ts
+++ b/backend/src/server/routes/v1/cmek-router.ts
@@ -518,6 +518,95 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/keys/bulk-import",
+ config: { rateLimit: writeLimit },
+ schema: {
+ hide: false,
+ operationId: "bulkImportKmsKeys",
+ tags: [ApiDocsTags.KmsKeys],
+ description: "Bulk import KMS keys with provided key material into a project.",
+ body: z.object({
+ projectId: z.string().uuid(),
+ keys: z
+ .array(
+ z
+ .object({
+ name: keyNameSchema,
+ keyUsage: z.nativeEnum(KmsKeyUsage),
+ encryptionAlgorithm: z.enum(AllowedEncryptionKeyAlgorithms),
+ keyMaterial: z.string().min(1)
+ })
+ .superRefine((data, ctx) => {
+ if (
+ data.keyUsage === KmsKeyUsage.ENCRYPT_DECRYPT &&
+ !Object.values(SymmetricKeyAlgorithm).includes(data.encryptionAlgorithm as SymmetricKeyAlgorithm)
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `encryptionAlgorithm must be a symmetric algorithm for encrypt-decrypt keys`
+ });
+ }
+ if (
+ data.keyUsage === KmsKeyUsage.SIGN_VERIFY &&
+ !Object.values(AsymmetricKeyAlgorithm).includes(data.encryptionAlgorithm as AsymmetricKeyAlgorithm)
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `encryptionAlgorithm must be an asymmetric algorithm for sign-verify keys`
+ });
+ }
+ })
+ )
+ .min(1)
+ .max(100)
+ }),
+ response: {
+ 200: z.object({
+ keys: z.array(z.object({ id: z.string(), name: z.string() })),
+ errors: z.array(z.object({ name: z.string(), message: z.string() }))
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const {
+ body: { projectId, keys },
+ permission
+ } = req;
+
+ const { keys: importedKeys, errors } = await server.services.cmek.bulkImportKeys(
+ {
+ projectId,
+ keys: keys.map((k) => ({
+ name: k.name,
+ algorithm: k.encryptionAlgorithm as TCmekKeyEncryptionAlgorithm,
+ keyUsage: k.keyUsage,
+ keyMaterial: k.keyMaterial
+ }))
+ },
+ permission
+ );
+
+ if (importedKeys.length > 0) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.CMEK_BULK_IMPORT_KEYS,
+ metadata: {
+ keyNames: importedKeys.map((k) => k.name),
+ projectId
+ }
+ }
+ });
+ }
+
+ return { keys: importedKeys, errors };
+ }
+ });
+
server.route({
method: "POST",
url: "/keys/bulk-export-private-keys",
diff --git a/backend/src/services/cmek/cmek-service.ts b/backend/src/services/cmek/cmek-service.ts
index e5b83158ac..2e758bebc6 100644
--- a/backend/src/services/cmek/cmek-service.ts
+++ b/backend/src/services/cmek/cmek-service.ts
@@ -9,6 +9,7 @@ import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
import {
TCmekBulkGetPrivateKeysDTO,
+ TCmekBulkImportKeysDTO,
TCmekDecryptDTO,
TCmekEncryptDTO,
TCmekGetPrivateKeyDTO,
@@ -496,6 +497,59 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
};
};
+ const bulkImportKeys = async ({ projectId, keys }: TCmekBulkImportKeysDTO, actor: OrgServiceActor) => {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.KMS
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCmekActions.Create, ProjectPermissionSub.Cmek);
+
+ const results = await Promise.allSettled(
+ keys.map(async (entry): Promise<{ id: string; name: string }> => {
+ const imported = await kmsService.importKeyMaterial({
+ key: Buffer.from(entry.keyMaterial, "base64"),
+ algorithm: entry.algorithm,
+ name: entry.name,
+ isReserved: false,
+ projectId,
+ orgId: actor.orgId,
+ keyUsage: entry.keyUsage
+ });
+ return { id: imported.id, name: imported.name };
+ })
+ );
+
+ const importedKeys: { id: string; name: string }[] = [];
+ const errors: { name: string; message: string }[] = [];
+
+ results.forEach((result, i) => {
+ const entry = keys[i];
+ if (!entry) return;
+ if (result.status === "fulfilled") {
+ importedKeys.push(result.value);
+ } else {
+ const reason = result.reason as Error;
+ let message = "Failed to import key";
+ if (
+ reason instanceof DatabaseError &&
+ (reason.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation
+ ) {
+ message = `A key with the name "${entry.name}" already exists in this project`;
+ } else if (reason instanceof BadRequestError) {
+ message = reason.message;
+ }
+ errors.push({ name: entry.name, message });
+ }
+ });
+
+ return { keys: importedKeys, errors, projectId };
+ };
+
return {
createCmek,
updateCmekById,
@@ -510,6 +564,7 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
listSigningAlgorithms,
getPublicKey,
getPrivateKey,
- bulkGetPrivateKeys
+ bulkGetPrivateKeys,
+ bulkImportKeys
};
};
diff --git a/backend/src/services/cmek/cmek-types.ts b/backend/src/services/cmek/cmek-types.ts
index d1b3267182..3f986f48a9 100644
--- a/backend/src/services/cmek/cmek-types.ts
+++ b/backend/src/services/cmek/cmek-types.ts
@@ -61,6 +61,18 @@ export type TCmekBulkGetPrivateKeysDTO = {
keyIds: string[];
};
+export type TCmekBulkImportKeyEntry = {
+ name: string;
+ algorithm: TCmekKeyEncryptionAlgorithm;
+ keyUsage: KmsKeyUsage;
+ keyMaterial: string;
+};
+
+export type TCmekBulkImportKeysDTO = {
+ projectId: string;
+ keys: TCmekBulkImportKeyEntry[];
+};
+
export type TCmekSignDTO = {
keyId: string;
data: string;
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index 8ac0b099b9..f7cee7ac7a 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -402,8 +402,18 @@ export const kmsServiceFactory = ({
{ key, algorithm, name, isReserved, projectId, orgId, keyUsage, kmipMetadata }: TImportKeyMaterialDTO,
tx?: Knex
) => {
- // daniel: currently we only support imports for encrypt/decrypt keys
- verifyKeyTypeAndAlgorithm(keyUsage, algorithm, { forceType: KmsKeyUsage.ENCRYPT_DECRYPT });
+ verifyKeyTypeAndAlgorithm(keyUsage, algorithm);
+
+ if (keyUsage === KmsKeyUsage.SIGN_VERIFY) {
+ const { getPublicKeyFromPrivateKey } = signingService(algorithm as AsymmetricKeyAlgorithm);
+ try {
+ getPublicKeyFromPrivateKey(key);
+ } catch {
+ throw new BadRequestError({
+ message: "Invalid private key material. Expected a PKCS8 PEM-encoded private key."
+ });
+ }
+ }
const cipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
@@ -413,7 +423,7 @@ export const kmsServiceFactory = ({
const kmsDoc = await kmsDAL.create(
{
name: sanitizedName,
- keyUsage: KmsKeyUsage.ENCRYPT_DECRYPT,
+ keyUsage,
orgId,
isReserved,
projectId,
diff --git a/backend/src/services/kms/kms-types.ts b/backend/src/services/kms/kms-types.ts
index f2c05b6ad8..27c6b45726 100644
--- a/backend/src/services/kms/kms-types.ts
+++ b/backend/src/services/kms/kms-types.ts
@@ -97,7 +97,7 @@ export type TGetBulkKeyMaterialDTO = {
export type TImportKeyMaterialDTO = {
key: Buffer;
- algorithm: SymmetricKeyAlgorithm;
+ algorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm;
name?: string;
isReserved: boolean;
projectId: string;
diff --git a/frontend/src/hooks/api/cmeks/mutations.tsx b/frontend/src/hooks/api/cmeks/mutations.tsx
index f322ff9e11..c140b89a41 100644
--- a/frontend/src/hooks/api/cmeks/mutations.tsx
+++ b/frontend/src/hooks/api/cmeks/mutations.tsx
@@ -6,6 +6,8 @@ import { cmekKeys } from "@app/hooks/api/cmeks/queries";
import {
TCmekBulkExportPrivateKeysDTO,
TCmekBulkExportPrivateKeysResponse,
+ TCmekBulkImportKeysDTO,
+ TCmekBulkImportKeysResponse,
TCmekDecrypt,
TCmekDecryptResponse,
TCmekEncrypt,
@@ -145,3 +147,20 @@ export const useBulkExportCmekPrivateKeys = () => {
}
});
};
+
+export const useBulkImportCmekKeys = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ projectId, keys }: TCmekBulkImportKeysDTO) => {
+ const { data } = await apiRequest.post<TCmekBulkImportKeysResponse>(
+ "/api/v1/kms/keys/bulk-import",
+ { projectId, keys }
+ );
+
+ return data;
+ },
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: cmekKeys.getCmeksByProjectId({ projectId }) });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/cmeks/types.ts b/frontend/src/hooks/api/cmeks/types.ts
index 35ff6a0140..ff18e9fd56 100644
--- a/frontend/src/hooks/api/cmeks/types.ts
+++ b/frontend/src/hooks/api/cmeks/types.ts
@@ -109,6 +109,23 @@ export type TCmekBulkExportPrivateKeysResponse = {
keys: TCmekBulkExportedKey[];
};
+export type TCmekBulkImportKeyEntry = {
+ name: string;
+ keyUsage: KmsKeyUsage;
+ encryptionAlgorithm: AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm;
+ keyMaterial: string;
+};
+
+export type TCmekBulkImportKeysDTO = {
+ projectId: string;
+ keys: TCmekBulkImportKeyEntry[];
+};
+
+export type TCmekBulkImportKeysResponse = {
+ keys: { id: string; name: string }[];
+ errors: { name: string; message: string }[];
+};
+
export enum CmekOrderBy {
Name = "name"
}
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekBulkImportModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekBulkImportModal.tsx
new file mode 100644
index 0000000000..2e3610d5e6
--- /dev/null
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekBulkImportModal.tsx
@@ -0,0 +1,436 @@
+import { useRef, useState } from "react";
+import { AlertTriangleIcon, UploadIcon } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ EmptyMedia,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ UnstableEmpty,
+ UnstableEmptyDescription,
+ UnstableEmptyHeader,
+ UnstableEmptyTitle,
+ UnstableTable,
+ UnstableTableBody,
+ UnstableTableCell,
+ UnstableTableHead,
+ UnstableTableHeader,
+ UnstableTableRow
+} from "@app/components/v3";
+import { kmsKeyUsageOptions } from "@app/helpers/kms";
+import {
+ AsymmetricKeyAlgorithm,
+ KmsKeyUsage,
+ SymmetricKeyAlgorithm,
+ useBulkImportCmekKeys
+} from "@app/hooks/api/cmeks";
+
+type ParsedKey = {
+ name: string;
+ keyType: "encrypt-decrypt" | "sign-verify";
+ algorithm: string;
+ keyMaterial?: string;
+ privateKey?: string;
+ publicKey?: string;
+};
+
+type ValidationError = {
+ index: number;
+ message: string;
+};
+
+const validateEntry = (entry: unknown, index: number): ValidationError | null => {
+ if (typeof entry !== "object" || entry === null) {
+ return { index, message: "must be an object" };
+ }
+ const e = entry as Record<string, unknown>;
+
+ if (!e.name || typeof e.name !== "string") {
+ return { index, message: `Entry ${index + 1}: "name" is required` };
+ }
+ if (e.keyType !== "encrypt-decrypt" && e.keyType !== "sign-verify") {
+ return {
+ index,
+ message: '"keyType" must be "encrypt-decrypt" or "sign-verify"'
+ };
+ }
+ if (!e.algorithm || typeof e.algorithm !== "string") {
+ return { index, message: '"algorithm" is required' };
+ }
+ if (e.keyType === "encrypt-decrypt") {
+ const validSymmetric = Object.values(SymmetricKeyAlgorithm) as string[];
+ if (!validSymmetric.includes(e.algorithm)) {
+ return {
+ index,
+ message: `"algorithm" must be one of ${validSymmetric.join(", ")} for encrypt-decrypt keys`
+ };
+ }
+ if (!e.keyMaterial || typeof e.keyMaterial !== "string") {
+ return {
+ index,
+ message: '"keyMaterial" is required for encrypt-decrypt keys'
+ };
+ }
+ }
+ if (e.keyType === "sign-verify") {
+ const validAsymmetric = Object.values(AsymmetricKeyAlgorithm) as string[];
+ if (!validAsymmetric.includes(e.algorithm)) {
+ return {
+ index,
+ message: `"algorithm" must be one of ${validAsymmetric.join(", ")} for sign-verify keys`
+ };
+ }
+ if (!e.privateKey || typeof e.privateKey !== "string") {
+ return {
+ index,
+ message: '"privateKey" is required for sign-verify keys'
+ };
+ }
+ }
+ return null;
+};
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ projectId: string;
+};
+
+type ImportResult = {
+ succeeded: { id: string; name: string }[];
+ failed: { name: string; message: string }[];
+};
+
+export const CmekBulkImportModal = ({ isOpen, onOpenChange, projectId }: Props) => {
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [parsedKeys, setParsedKeys] = useState<ParsedKey[] | null>(null);
+ const [parseError, setParseError] = useState<string | null>(null);
+ const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
+ const [importResult, setImportResult] = useState<ImportResult | null>(null);
+ const [isDragging, setIsDragging] = useState(false);
+ const bulkImport = useBulkImportCmekKeys();
+
+ const reset = () => {
+ setParsedKeys(null);
+ setParseError(null);
+ setValidationErrors([]);
+ setImportResult(null);
+ if (fileInputRef.current) fileInputRef.current.value = "";
+ };
+
+ const handleOpenChange = (open: boolean) => {
+ if (!open) reset();
+ onOpenChange(open);
+ };
+
+ const handleFile = (file: File) => {
+ setParseError(null);
+ setValidationErrors([]);
+ const reader = new FileReader();
+ reader.onload = (e) => {
+ try {
+ const raw = JSON.parse(e.target?.result as string) as unknown;
+ if (!Array.isArray(raw)) {
+ setParseError("File must contain a JSON array.");
+ return;
+ }
+ const errors = raw
+ .map((entry, i) => validateEntry(entry, i))
+ .filter((err): err is ValidationError => err !== null);
+ setValidationErrors(errors);
+ setParsedKeys(raw as ParsedKey[]);
+ } catch {
+ setParseError("Could not parse file. Make sure it is valid JSON.");
+ }
+ };
+ reader.readAsText(file);
+ };
+
+ const handleImport = async () => {
+ if (!parsedKeys) return;
+ try {
+ const { keys: imported, errors } = await bulkImport.mutateAsync({
+ projectId,
+ keys: parsedKeys.map((k) => ({
+ name: k.name,
+ keyUsage: k.keyType as KmsKeyUsage,
+ encryptionAlgorithm: k.algorithm as never,
+ keyMaterial: k.keyType === "sign-verify" ? (k.privateKey ?? "") : (k.keyMaterial ?? "")
+ }))
+ });
+ if (errors.length === 0) {
+ createNotification({
+ text: `Successfully imported ${imported.length} key(s)`,
+ type: "success"
+ });
+ reset();
+ onOpenChange(false);
+ } else {
+ setImportResult({ succeeded: imported, failed: errors });
+ }
+ } catch {
+ createNotification({ text: "Failed to import keys", type: "error" });
+ }
+ };
+
+ const encryptCount = parsedKeys?.filter((k) => k.keyType === "encrypt-decrypt").length ?? 0;
+ const signCount = parsedKeys?.filter((k) => k.keyType === "sign-verify").length ?? 0;
+ const errorByIndex = new Map(validationErrors.map((err) => [err.index, err.message]));
+ const hasErrors = validationErrors.length > 0;
+
+ const renderContent = () => {
+ if (importResult) {
+ const total = importResult.succeeded.length + importResult.failed.length;
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-mineshaft-300">
+ <span className="font-medium text-mineshaft-100">
+ {importResult.succeeded.length} of {total} keys imported
+ </span>
+ {importResult.failed.length > 0 && (
+ <span className="ml-1 text-red">— {importResult.failed.length} failed</span>
+ )}
+ </p>
+
+ {importResult.failed.length > 0 && (
+ <div className="rounded-md border border-red/30 bg-red/5 px-4 py-3">
+ <p className="mb-2 text-sm font-medium text-red">Failed imports</p>
+ <ul className="max-h-[50vh] thin-scrollbar space-y-1 overflow-y-auto pr-2">
+ {importResult.failed.map((err) => (
+ <li key={err.name} className="text-xs text-red/80">
+ <span className="font-medium">{err.name}</span>
+ {" — "}
+ {err.message}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="project" onClick={reset}>
+ Done
+ </Button>
+ </DialogClose>
+ </DialogFooter>
+ </div>
+ );
+ }
+
+ if (!parsedKeys) {
+ return (
+ <div className="space-y-4">
+ <UnstableEmpty
+ className={`cursor-pointer transition-colors duration-75 ${isDragging ? "bg-container-hover" : ""}`}
+ onClick={() => fileInputRef.current?.click()}
+ onDragOver={(e) => {
+ e.preventDefault();
+ setIsDragging(true);
+ }}
+ onDragLeave={() => setIsDragging(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setIsDragging(false);
+ const file = e.dataTransfer.files[0];
+ if (file) handleFile(file);
+ }}
+ >
+ <UnstableEmptyHeader>
+ <EmptyMedia variant="icon">
+ <UploadIcon />
+ </EmptyMedia>
+ <UnstableEmptyTitle>
+ {isDragging ? "Drop your file here" : "Upload your keys"}
+ </UnstableEmptyTitle>
+ <UnstableEmptyDescription>
+ Drag and drop your .json file here, or click to browse
+ </UnstableEmptyDescription>
+ </UnstableEmptyHeader>
+ </UnstableEmpty>
+
+ {parseError && (
+ <p className="rounded-md bg-red/10 px-3 py-2 text-sm text-red">{parseError}</p>
+ )}
+
+ <div className="rounded-md border border-mineshaft-600 bg-mineshaft-900 px-4 py-3 text-xs text-mineshaft-300">
+ <p className="mb-2 font-semibold text-mineshaft-200">Expected format</p>
+ <p className="mb-1">The file must be a JSON array. Each entry is one of:</p>
+ <pre className="mt-2 overflow-x-auto rounded bg-mineshaft-800 p-2 text-xs leading-relaxed">{`// Encrypt/Decrypt key
+{
+ "name": "...",
+ "keyType": "encrypt-decrypt",
+ "algorithm": "...",
+ "keyMaterial": "<base64>"
+}
+
+// Sign/Verify key
+{
+ "name": "...",
+ "keyType": "sign-verify",
+ "algorithm": "...",
+ "privateKey": "<base64>",
+ "publicKey": "<base64>"
+}`}</pre>
+ </div>
+
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="outline">Cancel</Button>
+ </DialogClose>
+ </DialogFooter>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <UnstableTable
+ className="border-collapse"
+ containerClassName="max-h-[60vh] overflow-y-auto overflow-x-hidden"
+ >
+ <UnstableTableHeader className="sticky top-0 z-[1] after:pointer-events-none after:absolute after:inset-x-0 after:-top-px after:h-px after:bg-container">
+ <UnstableTableRow className="relative h-9">
+ <UnstableTableHead className="w-16 bg-container shadow-[inset_0_-1px_0_var(--color-border)]">
+ #
+ </UnstableTableHead>
+ <UnstableTableHead className="bg-container shadow-[inset_0_-1px_0_var(--color-border)]">
+ Name
+ </UnstableTableHead>
+ <UnstableTableHead className="bg-container shadow-[inset_0_-1px_0_var(--color-border)]">
+ Key Type
+ </UnstableTableHead>
+ <UnstableTableHead className="bg-container shadow-[inset_0_-1px_0_var(--color-border)]">
+ Algorithm
+ </UnstableTableHead>
+ </UnstableTableRow>
+ </UnstableTableHeader>
+ <UnstableTableBody>
+ {parsedKeys.map((key, i) => {
+ const errorMsg = errorByIndex.get(i);
+ return (
+ <UnstableTableRow
+ // eslint-disable-next-line react/no-array-index-key
+ key={i}
+ className={errorMsg ? "border-danger/20 bg-danger/[0.075]" : ""}
+ >
+ <UnstableTableCell
+ className={`w-16 ${errorMsg ? "text-danger" : "text-mineshaft-400"}`}
+ >
+ <div className="flex items-center gap-1.5">
+ <span className="inline-block w-5 text-right tabular-nums">{i + 1}</span>
+ {errorMsg ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <AlertTriangleIcon className="size-3.5 text-danger" />
+ </TooltipTrigger>
+ <TooltipContent>{errorMsg}</TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="size-3.5" />
+ )}
+ </div>
+ </UnstableTableCell>
+ <UnstableTableCell isTruncatable className="w-1/2 max-w-0 font-mono text-xs">
+ <p className="truncate">{String(key.name ?? "")}</p>
+ </UnstableTableCell>
+ <UnstableTableCell isTruncatable className="w-1/4 max-w-0">
+ <p className="truncate">
+ {kmsKeyUsageOptions[key.keyType as KmsKeyUsage]?.label ?? key.keyType}
+ </p>
+ </UnstableTableCell>
+ <UnstableTableCell isTruncatable className="w-1/4 max-w-0 uppercase">
+ <p className="truncate">{String(key.algorithm ?? "")}</p>
+ </UnstableTableCell>
+ </UnstableTableRow>
+ );
+ })}
+ </UnstableTableBody>
+ </UnstableTable>
+
+ {hasErrors && (
+ <div className="flex min-h-10 items-center gap-2 rounded-md border border-danger/35 bg-danger/[0.075] px-3 py-2 text-sm">
+ <AlertTriangleIcon className="size-4 text-danger" />
+ <span>
+ {validationErrors.length} validation error
+ {validationErrors.length > 1 ? "s" : ""} — resolve to proceed
+ </span>
+ </div>
+ )}
+
+ <DialogFooter className="items-center">
+ <Button variant="ghost" onClick={reset} className="mr-auto">
+ Back
+ </Button>
+ <DialogClose asChild>
+ <Button variant="ghost">Cancel</Button>
+ </DialogClose>
+ <Button
+ variant="project"
+ isDisabled={hasErrors || bulkImport.isPending}
+ isPending={bulkImport.isPending}
+ onClick={handleImport}
+ >
+ Import {parsedKeys.length} Key{parsedKeys.length !== 1 ? "s" : ""}
+ </Button>
+ </DialogFooter>
+ </div>
+ );
+ };
+
+ const getHeaderContent = (): { title: string; description: string } => {
+ if (importResult) {
+ const total = importResult.succeeded.length + importResult.failed.length;
+ return {
+ title: "Import Results",
+ description: `${importResult.succeeded.length} of ${total} keys imported.`
+ };
+ }
+ if (parsedKeys) {
+ return {
+ title: "Review & Import Keys",
+ description: `${parsedKeys.length} key${parsedKeys.length !== 1 ? "s" : ""} found — ${encryptCount} encrypt/decrypt, ${signCount} sign/verify.`
+ };
+ }
+ return {
+ title: "Import Keys",
+ description:
+ "Upload a JSON file exported from Infisical KMS to import keys into this project."
+ };
+ };
+
+ const header = getHeaderContent();
+
+ return (
+ <Dialog open={isOpen} onOpenChange={handleOpenChange}>
+ <DialogContent className="max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{header.title}</DialogTitle>
+ <DialogDescription>{header.description}</DialogDescription>
+ </DialogHeader>
+
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".json"
+ className="hidden"
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ if (file) handleFile(file);
+ }}
+ />
+
+ {renderContent()}
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
index 4f3e1454ed..410fee9c75 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
@@ -7,6 +7,7 @@ import {
faDownload,
faEdit,
faEllipsis,
+ faFileImport,
faFileSignature,
faLock,
faLockOpen,
@@ -34,6 +35,7 @@ import {
Tooltip,
TooltipContent,
TooltipTrigger,
+ UnstableButtonGroup,
UnstableCard,
UnstableCardAction,
UnstableCardContent,
@@ -84,6 +86,7 @@ import {
} from "@app/hooks/api/cmeks/types";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { CmekBulkImportModal } from "./CmekBulkImportModal";
import { CmekDecryptModal } from "./CmekDecryptModal";
import { CmekEncryptModal } from "./CmekEncryptModal";
import { CmekExportKeyModal } from "./CmekExportKeyModal";
@@ -159,7 +162,8 @@ export const CmekTable = () => {
"decryptData",
"signData",
"verifyData",
- "exportKey"
+ "exportKey",
+ "importKeys"
] as const);
const handleSort = () => {
@@ -300,18 +304,57 @@ export const CmekTable = () => {
Manage keys and perform cryptographic operations.
</UnstableCardDescription>
<UnstableCardAction>
- <ProjectPermissionCan I={ProjectPermissionActions.Create} a={ProjectPermissionSub.Cmek}>
- {(isAllowed) => (
- <Button
- variant="project"
- onClick={() => handlePopUpOpen("upsertKey", null)}
- isDisabled={!isAllowed}
- >
- <FontAwesomeIcon icon={faPlus} className="mr-2" />
- Add Key
- </Button>
- )}
- </ProjectPermissionCan>
+ <UnstableButtonGroup>
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Create}
+ a={ProjectPermissionSub.Cmek}
+ >
+ {(isAllowed) => (
+ <Tooltip open={!isAllowed ? undefined : false}>
+ <TooltipTrigger>
+ <Button
+ className="rounded-r-none"
+ variant="project"
+ onClick={() => handlePopUpOpen("upsertKey", null)}
+ isDisabled={!isAllowed}
+ >
+ <FontAwesomeIcon icon={faPlus} className="mr-2" />
+ Add Key
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Access Denied</TooltipContent>
+ </Tooltip>
+ )}
+ </ProjectPermissionCan>
+ <UnstableDropdownMenu>
+ <UnstableDropdownMenuTrigger asChild>
+ <UnstableIconButton variant="project">
+ <ChevronDownIcon />
+ </UnstableIconButton>
+ </UnstableDropdownMenuTrigger>
+ <UnstableDropdownMenuContent align="end">
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Create}
+ a={ProjectPermissionSub.Cmek}
+ >
+ {(isAllowed) => (
+ <Tooltip open={!isAllowed ? undefined : false}>
+ <TooltipTrigger className="block w-full">
+ <UnstableDropdownMenuItem
+ onClick={() => handlePopUpOpen("importKeys")}
+ isDisabled={!isAllowed}
+ >
+ <FontAwesomeIcon icon={faFileImport} />
+ Import Keys
+ </UnstableDropdownMenuItem>
+ </TooltipTrigger>
+ <TooltipContent side="left">Access Restricted</TooltipContent>
+ </Tooltip>
+ )}
+ </ProjectPermissionCan>
+ </UnstableDropdownMenuContent>
+ </UnstableDropdownMenu>
+ </UnstableButtonGroup>
</UnstableCardAction>
</UnstableCardHeader>
<UnstableCardContent>
@@ -638,6 +681,11 @@ export const CmekTable = () => {
onOpenChange={(isOpen) => handlePopUpToggle("exportKey", isOpen)}
cmek={popUp.exportKey.data as TCmek}
/>
+ <CmekBulkImportModal
+ isOpen={popUp.importKeys.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("importKeys", isOpen)}
+ projectId={projectId}
+ />
</motion.div>
);
};