Skip to content

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

feat: add export support for kms keys

Sheen Capadngan707ea202a765
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 d77d623b55..c5f2db964b 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -420,6 +420,7 @@ export enum EventType {
CMEK_VERIFY = "cmek-verify",
CMEK_LIST_SIGNING_ALGORITHMS = "cmek-list-signing-algorithms",
CMEK_GET_PUBLIC_KEY = "cmek-get-public-key",
+ CMEK_GET_PRIVATE_KEY = "cmek-get-private-key",
UPDATE_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS = "update-external-group-org-role-mapping",
GET_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS = "get-external-group-org-role-mapping",
@@ -3153,6 +3154,15 @@ interface CmekGetPublicKeyEvent {
type: EventType.CMEK_GET_PUBLIC_KEY;
metadata: {
keyId: string;
+ keyName: string;
+ };
+}
+
+interface CmekGetPrivateKeyEvent {
+ type: EventType.CMEK_GET_PRIVATE_KEY;
+ metadata: {
+ keyId: string;
+ keyName: string;
};
}
@@ -5120,6 +5130,7 @@ export type Event =
| CmekVerifyEvent
| CmekListSigningAlgorithmsEvent
| CmekGetPublicKeyEvent
+ | CmekGetPrivateKeyEvent
| GetExternalGroupOrgRoleMappingsEvent
| UpdateExternalGroupOrgRoleMappingsEvent
| GetProjectTemplatesEvent
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 781757fcad..fdeaadfd2a 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -234,7 +234,8 @@ const buildAdminPermissionRules = () => {
ProjectPermissionCmekActions.Encrypt,
ProjectPermissionCmekActions.Decrypt,
ProjectPermissionCmekActions.Sign,
- ProjectPermissionCmekActions.Verify
+ ProjectPermissionCmekActions.Verify,
+ ProjectPermissionCmekActions.ExportPrivateKey
],
ProjectPermissionSub.Cmek
);
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index e7f75f6589..ca944345e9 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -58,7 +58,8 @@ export enum ProjectPermissionCmekActions {
Encrypt = "encrypt",
Decrypt = "decrypt",
Sign = "sign",
- Verify = "verify"
+ Verify = "verify",
+ ExportPrivateKey = "export-private-key"
}
export enum ProjectPermissionDynamicSecretActions {
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index e6cc2a4942..11534ea8cc 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2297,6 +2297,10 @@ export const KMS = {
keyId: "The ID of the key to get the public key for. The key must be for signing and verifying."
},
+ GET_PRIVATE_KEY: {
+ keyId: "The ID of the key to export the private key or key material for."
+ },
+
SIGN: {
keyId: "The ID of the key to sign the data with.",
data: "The data in string format to be signed (base64 encoded).",
diff --git a/backend/src/server/routes/v1/cmek-router.ts b/backend/src/server/routes/v1/cmek-router.ts
index c8fd485a7a..b76e47c16d 100644
--- a/backend/src/server/routes/v1/cmek-router.ts
+++ b/backend/src/server/routes/v1/cmek-router.ts
@@ -446,7 +446,7 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
permission
} = req;
- const { publicKey, projectId } = await server.services.cmek.getPublicKey({ keyId }, permission);
+ const { publicKey, projectId, keyName } = await server.services.cmek.getPublicKey({ keyId }, permission);
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
@@ -454,7 +454,8 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
event: {
type: EventType.CMEK_GET_PUBLIC_KEY,
metadata: {
- keyId
+ keyId,
+ keyName
}
}
});
@@ -463,6 +464,51 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "GET",
+ url: "/keys/:keyId/private-key",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.KmsKeys],
+ description:
+ "Export the private key (or key material) for a KMS key. For asymmetric keys (sign/verify), the private key is returned. For symmetric keys (encrypt/decrypt), the key material is returned.",
+ params: z.object({
+ keyId: z.string().uuid().describe(KMS.GET_PRIVATE_KEY.keyId)
+ }),
+ response: {
+ 200: z.object({
+ privateKey: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const {
+ params: { keyId },
+ permission
+ } = req;
+
+ const { privateKey, projectId, keyName } = await server.services.cmek.getPrivateKey({ keyId }, permission);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.CMEK_GET_PRIVATE_KEY,
+ metadata: {
+ keyId,
+ keyName
+ }
+ }
+ });
+
+ return { privateKey };
+ }
+ });
+
server.route({
method: "GET",
url: "/keys/:keyId/signing-algorithms",
diff --git a/backend/src/services/cmek/cmek-service.ts b/backend/src/services/cmek/cmek-service.ts
index f913f972f6..2acc95ee6d 100644
--- a/backend/src/services/cmek/cmek-service.ts
+++ b/backend/src/services/cmek/cmek-service.ts
@@ -10,6 +10,7 @@ import { OrgServiceActor } from "@app/lib/types";
import {
TCmekDecryptDTO,
TCmekEncryptDTO,
+ TCmekGetPrivateKeyDTO,
TCmekGetPublicKeyDTO,
TCmekKeyEncryptionAlgorithm,
TCmekListSigningAlgorithmsDTO,
@@ -284,7 +285,37 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCmekActions.Read, ProjectPermissionSub.Cmek);
const publicKey = await kmsService.getPublicKey({ kmsId: keyId });
- return { publicKey: publicKey.toString("base64"), projectId: key.projectId };
+ return { publicKey: publicKey.toString("base64"), projectId: key.projectId, keyName: key.name };
+ };
+
+ const getPrivateKey = async ({ keyId }: TCmekGetPrivateKeyDTO, actor: OrgServiceActor) => {
+ const key = await kmsDAL.findCmekById(keyId);
+
+ if (!key) throw new NotFoundError({ message: `Key with ID "${keyId}" not found` });
+ if (!key.projectId || key.isReserved) throw new BadRequestError({ message: "Key is not customer managed" });
+ if (key.isDisabled) throw new BadRequestError({ message: "Key is disabled" });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: key.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.KMS
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCmekActions.ExportPrivateKey,
+ ProjectPermissionSub.Cmek
+ );
+
+ const keyMaterial = await kmsService.getKeyMaterial({ kmsId: keyId });
+
+ return {
+ privateKey: keyMaterial.toString("base64"),
+ projectId: key.projectId,
+ keyName: key.name
+ };
};
const cmekSign = async ({ keyId, data, signingAlgorithm, isDigest }: TCmekSignDTO, actor: OrgServiceActor) => {
@@ -400,6 +431,7 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC
cmekSign,
cmekVerify,
listSigningAlgorithms,
- getPublicKey
+ getPublicKey,
+ getPrivateKey
};
};
diff --git a/backend/src/services/cmek/cmek-types.ts b/backend/src/services/cmek/cmek-types.ts
index 0421bce0e8..eafd39e39f 100644
--- a/backend/src/services/cmek/cmek-types.ts
+++ b/backend/src/services/cmek/cmek-types.ts
@@ -53,6 +53,10 @@ export type TCmekGetPublicKeyDTO = {
keyId: string;
};
+export type TCmekGetPrivateKeyDTO = {
+ keyId: string;
+};
+
export type TCmekSignDTO = {
keyId: string;
data: string;
diff --git a/docs/api-reference/endpoints/kms/keys/private-key.mdx b/docs/api-reference/endpoints/kms/keys/private-key.mdx
new file mode 100644
index 0000000000..cffd787aba
--- /dev/null
+++ b/docs/api-reference/endpoints/kms/keys/private-key.mdx
@@ -0,0 +1,4 @@
+---
+title: "Export Private Key"
+openapi: "GET /api/v1/kms/keys/{keyId}/private-key"
+---
diff --git a/docs/api-reference/endpoints/kms/signing/public-key.mdx b/docs/api-reference/endpoints/kms/keys/public-key.mdx
similarity index 100%
rename from docs/api-reference/endpoints/kms/signing/public-key.mdx
rename to docs/api-reference/endpoints/kms/keys/public-key.mdx
diff --git a/docs/docs.json b/docs/docs.json
index 4730900b9f..d009dfc90b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -2788,7 +2788,9 @@
"api-reference/endpoints/kms/keys/get-by-name",
"api-reference/endpoints/kms/keys/create",
"api-reference/endpoints/kms/keys/update",
- "api-reference/endpoints/kms/keys/delete"
+ "api-reference/endpoints/kms/keys/delete",
+ "api-reference/endpoints/kms/keys/public-key",
+ "api-reference/endpoints/kms/keys/private-key"
]
},
{
@@ -2803,7 +2805,6 @@
"pages": [
"api-reference/endpoints/kms/signing/sign",
"api-reference/endpoints/kms/signing/verify",
- "api-reference/endpoints/kms/signing/public-key",
"api-reference/endpoints/kms/signing/signing-algorithms"
]
}
diff --git a/docs/internals/permissions/project-permissions.mdx b/docs/internals/permissions/project-permissions.mdx
index 2eaff05ea4..57ba24a75c 100644
--- a/docs/internals/permissions/project-permissions.mdx
+++ b/docs/internals/permissions/project-permissions.mdx
@@ -262,14 +262,17 @@ Supports conditions and permission inversion
#### Subject: `cmek`
-| Action | Description |
-| --------- | ------------------------------------- |
-| `read` | View Customer-Managed Encryption Keys |
-| `create` | Add new encryption keys |
-| `edit` | Modify key properties |
-| `delete` | Remove encryption keys |
-| `encrypt` | Use keys for encryption operations |
-| `decrypt` | Use keys for decryption operations |
+| Action | Description |
+| -------------------- | --------------------------------------------------------------------------- |
+| `read` | View Customer-Managed Encryption Keys |
+| `create` | Add new encryption keys |
+| `edit` | Modify key properties |
+| `delete` | Remove encryption keys |
+| `encrypt` | Use keys for encryption operations |
+| `decrypt` | Use keys for decryption operations |
+| `sign` | Use keys for signing operations |
+| `verify` | Use keys for signature verification operations |
+| `export-private-key` | Export key material (private key for asymmetric, secret key for symmetric) |
### Public Key Infrastructure (PKI)
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index 025aff0656..109889721f 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -43,7 +43,8 @@ export enum ProjectPermissionCmekActions {
Encrypt = "encrypt",
Decrypt = "decrypt",
Sign = "sign",
- Verify = "verify"
+ Verify = "verify",
+ ExportPrivateKey = "export-private-key"
}
export enum ProjectPermissionKmipActions {
diff --git a/frontend/src/hooks/api/cmeks/queries.tsx b/frontend/src/hooks/api/cmeks/queries.tsx
index 69eedfb429..ca96d85cb3 100644
--- a/frontend/src/hooks/api/cmeks/queries.tsx
+++ b/frontend/src/hooks/api/cmeks/queries.tsx
@@ -1,14 +1,22 @@
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { CmekOrderBy, TListProjectCmeksDTO, TProjectCmeksList } from "@app/hooks/api/cmeks/types";
+import {
+ CmekOrderBy,
+ TCmekGetPrivateKeyResponse,
+ TCmekGetPublicKeyResponse,
+ TListProjectCmeksDTO,
+ TProjectCmeksList
+} from "@app/hooks/api/cmeks/types";
import { OrderByDirection } from "@app/hooks/api/generic/types";
export const cmekKeys = {
all: ["cmek"] as const,
lists: () => [...cmekKeys.all, "list"] as const,
getCmeksByProjectId: ({ projectId, ...filters }: TListProjectCmeksDTO) =>
- [...cmekKeys.lists(), projectId, filters] as const
+ [...cmekKeys.lists(), projectId, filters] as const,
+ getPublicKey: (keyId: string) => [...cmekKeys.all, "public-key", keyId] as const,
+ getPrivateKey: (keyId: string) => [...cmekKeys.all, "private-key", keyId] as const
};
export const useGetCmeksByProjectId = (
@@ -51,3 +59,53 @@ export const useGetCmeksByProjectId = (
...options
});
};
+
+export const useGetCmekPublicKey = (
+ keyId: string,
+ options?: Omit<
+ UseQueryOptions<
+ TCmekGetPublicKeyResponse,
+ unknown,
+ TCmekGetPublicKeyResponse,
+ ReturnType<typeof cmekKeys.getPublicKey>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: cmekKeys.getPublicKey(keyId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TCmekGetPublicKeyResponse>(
+ `/api/v1/kms/keys/${keyId}/public-key`
+ );
+ return data;
+ },
+ enabled: Boolean(keyId) && (options?.enabled ?? true),
+ ...options
+ });
+};
+
+export const useGetCmekPrivateKey = (
+ keyId: string,
+ options?: Omit<
+ UseQueryOptions<
+ TCmekGetPrivateKeyResponse,
+ unknown,
+ TCmekGetPrivateKeyResponse,
+ ReturnType<typeof cmekKeys.getPrivateKey>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: cmekKeys.getPrivateKey(keyId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TCmekGetPrivateKeyResponse>(
+ `/api/v1/kms/keys/${keyId}/private-key`
+ );
+ return data;
+ },
+ enabled: Boolean(keyId) && (options?.enabled ?? true),
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/cmeks/types.ts b/frontend/src/hooks/api/cmeks/types.ts
index 2f6b8788b4..f88717bab0 100644
--- a/frontend/src/hooks/api/cmeks/types.ts
+++ b/frontend/src/hooks/api/cmeks/types.ts
@@ -76,6 +76,22 @@ export type TCmekDecryptResponse = {
plaintext: string;
};
+export type TCmekGetPublicKeyDTO = {
+ keyId: string;
+};
+
+export type TCmekGetPublicKeyResponse = {
+ publicKey: string;
+};
+
+export type TCmekGetPrivateKeyDTO = {
+ keyId: string;
+};
+
+export type TCmekGetPrivateKeyResponse = {
+ privateKey: string;
+};
+
export enum CmekOrderBy {
Name = "name"
}
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekExportKeyModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekExportKeyModal.tsx
new file mode 100644
index 0000000000..f4ffae02b5
--- /dev/null
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekExportKeyModal.tsx
@@ -0,0 +1,170 @@
+import { faCheck, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import FileSaver from "file-saver";
+
+import { IconButton, Modal, ModalContent, Spinner, Tooltip } from "@app/components/v2";
+import {
+ ProjectPermissionCmekActions,
+ ProjectPermissionSub,
+ useProjectPermission
+} from "@app/context";
+import { useTimedReset } from "@app/hooks";
+import { useGetCmekPrivateKey, useGetCmekPublicKey } from "@app/hooks/api/cmeks/queries";
+import { AsymmetricKeyAlgorithm, TCmek } from "@app/hooks/api/cmeks/types";
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ cmek: TCmek;
+};
+
+type FormProps = Pick<Props, "cmek">;
+
+const ExportKeyForm = ({ cmek }: FormProps) => {
+ const { permission } = useProjectPermission();
+ const isAsymmetricKey = Object.values(AsymmetricKeyAlgorithm).includes(
+ cmek?.encryptionAlgorithm as AsymmetricKeyAlgorithm
+ );
+
+ const canReadPublicKey = permission.can(
+ ProjectPermissionCmekActions.Read,
+ ProjectPermissionSub.Cmek
+ );
+
+ const canExportPrivateKey = permission.can(
+ ProjectPermissionCmekActions.ExportPrivateKey,
+ ProjectPermissionSub.Cmek
+ );
+
+ const { data: privateKeyData, isPending: isPrivateKeyPending } = useGetCmekPrivateKey(
+ cmek?.id ?? "",
+ {
+ // Only fetch private key if user has ExportPrivateKey permission
+ enabled: Boolean(cmek?.id) && canExportPrivateKey
+ }
+ );
+
+ const { data: publicKeyData, isPending: isPublicKeyPending } = useGetCmekPublicKey(
+ cmek?.id ?? "",
+ {
+ // Only fetch public key if user has Read permission and it's an asymmetric key
+ enabled: Boolean(cmek?.id) && isAsymmetricKey && canReadPublicKey
+ }
+ );
+
+ const [copyPrivateKeyText, isCopyingPrivateKey, setCopyPrivateKeyText] = useTimedReset<string>({
+ initialState: "Copy to clipboard"
+ });
+
+ const [copyPublicKeyText, isCopyingPublicKey, setCopyPublicKeyText] = useTimedReset<string>({
+ initialState: "Copy to clipboard"
+ });
+
+ const downloadTxtFile = (filename: string, content: string) => {
+ const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
+ FileSaver.saveAs(blob, filename);
+ };
+
+ const isLoading =
+ (canExportPrivateKey && isPrivateKeyPending) ||
+ (isAsymmetricKey && canReadPublicKey && isPublicKeyPending);
+
+ if (isLoading) {
+ return (
+ <div className="flex items-center justify-center py-8">
+ <Spinner size="lg" />
+ </div>
+ );
+ }
+
+ return (
+ <div>
+ {canExportPrivateKey && privateKeyData?.privateKey && (
+ <>
+ <div className="mb-4 flex items-center justify-between">
+ <h2>{isAsymmetricKey ? "Private Key (Base64)" : "Key Material (Base64)"}</h2>
+ <div className="flex">
+ <Tooltip content={copyPrivateKeyText}>
+ <IconButton
+ ariaLabel="copy icon"
+ colorSchema="secondary"
+ className="group relative"
+ onClick={() => {
+ navigator.clipboard.writeText(privateKeyData?.privateKey ?? "");
+ setCopyPrivateKeyText("Copied");
+ }}
+ >
+ <FontAwesomeIcon icon={isCopyingPrivateKey ? faCheck : faCopy} />
+ </IconButton>
+ </Tooltip>
+ <Tooltip content="Download">
+ <IconButton
+ ariaLabel="download icon"
+ colorSchema="secondary"
+ className="group relative ml-2"
+ onClick={() => {
+ downloadTxtFile(
+ isAsymmetricKey ? "private_key" : "key_material",
+ privateKeyData?.privateKey ?? ""
+ );
+ }}
+ >
+ <FontAwesomeIcon icon={faDownload} />
+ </IconButton>
+ </Tooltip>
+ </div>
+ </div>
+ <div className="mb-8 flex items-center justify-between rounded-md bg-white/[0.07] p-2 text-base text-gray-400">
+ <p className="mr-4 break-all whitespace-pre-wrap">{privateKeyData?.privateKey}</p>
+ </div>
+ </>
+ )}
+
+ {isAsymmetricKey && canReadPublicKey && publicKeyData?.publicKey && (
+ <>
+ <div className="mb-4 flex items-center justify-between">
+ <h2>Public Key (Base64)</h2>
+ <div className="flex">
+ <Tooltip content={copyPublicKeyText}>
+ <IconButton
+ ariaLabel="copy icon"
+ colorSchema="secondary"
+ className="group relative"
+ onClick={() => {
+ navigator.clipboard.writeText(publicKeyData?.publicKey ?? "");
+ setCopyPublicKeyText("Copied");
+ }}
+ >
+ <FontAwesomeIcon icon={isCopyingPublicKey ? faCheck : faCopy} />
+ </IconButton>
+ </Tooltip>
+ <Tooltip content="Download">
+ <IconButton
+ ariaLabel="download icon"
+ colorSchema="secondary"
+ className="group relative ml-2"
+ onClick={() => {
+ downloadTxtFile("public_key", publicKeyData?.publicKey ?? "");
+ }}
+ >
+ <FontAwesomeIcon icon={faDownload} />
+ </IconButton>
+ </Tooltip>
+ </div>
+ </div>
+ <div className="mb-8 flex items-center justify-between rounded-md bg-white/[0.07] p-2 text-base text-gray-400">
+ <p className="mr-4 break-all whitespace-pre-wrap">{publicKeyData?.publicKey}</p>
+ </div>
+ </>
+ )}
+ </div>
+ );
+};
+
+export const CmekExportKeyModal = ({ isOpen, onOpenChange, cmek }: Props) => {
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent title="Export Key">{cmek && <ExportKeyForm cmek={cmek} />}</ModalContent>
+ </Modal>
+ );
+};
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
index c9a0054c56..1b8eec8297 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
@@ -6,6 +6,7 @@ import {
faCheck,
faCheckCircle,
faCopy,
+ faDownload,
faEdit,
faEllipsis,
faFileSignature,
@@ -59,11 +60,17 @@ import {
} from "@app/helpers/userTablePreferences";
import { usePagination, usePopUp, useResetPageHelper, useTimedReset } from "@app/hooks";
import { useGetCmeksByProjectId, useUpdateCmek } from "@app/hooks/api/cmeks";
-import { CmekOrderBy, KmsKeyUsage, TCmek } from "@app/hooks/api/cmeks/types";
+import {
+ AsymmetricKeyAlgorithm,
+ CmekOrderBy,
+ KmsKeyUsage,
+ TCmek
+} from "@app/hooks/api/cmeks/types";
import { OrderByDirection } from "@app/hooks/api/generic/types";
import { CmekDecryptModal } from "./CmekDecryptModal";
import { CmekEncryptModal } from "./CmekEncryptModal";
+import { CmekExportKeyModal } from "./CmekExportKeyModal";
import { CmekModal } from "./CmekModal";
import { CmekSignModal } from "./CmekSignModal";
import { CmekVerifyModal } from "./CmekVerifyModal";
@@ -140,7 +147,8 @@ export const CmekTable = () => {
"encryptData",
"decryptData",
"signData",
- "verifyData"
+ "verifyData",
+ "exportKey"
] as const);
const handleSort = () => {
@@ -193,6 +201,17 @@ export const CmekTable = () => {
ProjectPermissionCmekActions.Verify,
ProjectPermissionSub.Cmek
);
+
+ const cannotExportPrivateKey = permission.cannot(
+ ProjectPermissionCmekActions.ExportPrivateKey,
+ ProjectPermissionSub.Cmek
+ );
+
+ const cannotReadKey = permission.cannot(
+ ProjectPermissionCmekActions.Read,
+ ProjectPermissionSub.Cmek
+ );
+
return (
<motion.div
key="kms-keys-tab"
@@ -443,6 +462,41 @@ export const CmekTable = () => {
</>
)}
+ {(() => {
+ // For asymmetric keys, user can export if they have Read OR ExportPrivateKey permission
+ // For symmetric keys, user needs ExportPrivateKey permission
+ const isAsymmetricKey = Object.values(
+ AsymmetricKeyAlgorithm
+ ).includes(encryptionAlgorithm as AsymmetricKeyAlgorithm);
+ const cannotExportKey = isAsymmetricKey
+ ? cannotExportPrivateKey && cannotReadKey
+ : cannotExportPrivateKey;
+
+ return (
+ <Tooltip
+ content={
+ // eslint-disable-next-line no-nested-ternary
+ cannotExportKey
+ ? "Access Restricted"
+ : isDisabled
+ ? "Key Disabled"
+ : ""
+ }
+ position="left"
+ >
+ <div>
+ <DropdownMenuItem
+ onClick={() => handlePopUpOpen("exportKey", cmek)}
+ icon={<FontAwesomeIcon icon={faDownload} />}
+ iconPos="left"
+ isDisabled={cannotExportKey || isDisabled}
+ >
+ Export Key
+ </DropdownMenuItem>
+ </div>
+ </Tooltip>
+ );
+ })()}
<Tooltip
content={cannotEditKey ? "Access Restricted" : ""}
position="left"
@@ -551,6 +605,11 @@ export const CmekTable = () => {
onOpenChange={(isOpen) => handlePopUpToggle("verifyData", isOpen)}
cmek={popUp.verifyData.data as TCmek}
/>
+ <CmekExportKeyModal
+ isOpen={popUp.exportKey.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("exportKey", isOpen)}
+ cmek={popUp.exportKey.data as TCmek}
+ />
</div>
</motion.div>
);
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index 2099ccb744..7e2a1254e0 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -91,14 +91,15 @@ const ApprovalPolicyActionSchema = z.object({
});
const CmekPolicyActionSchema = z.object({
- read: z.boolean().optional(),
- edit: z.boolean().optional(),
- delete: z.boolean().optional(),
- create: z.boolean().optional(),
- encrypt: z.boolean().optional(),
- decrypt: z.boolean().optional(),
- sign: z.boolean().optional(),
- verify: z.boolean().optional()
+ [ProjectPermissionCmekActions.Read]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.Delete]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.Create]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.Encrypt]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.Decrypt]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.Sign]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.Verify]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.ExportPrivateKey]: z.boolean().optional()
});
const DynamicSecretPolicyActionSchema = z.object({
@@ -1038,18 +1039,21 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
const canDecrypt = action.includes(ProjectPermissionCmekActions.Decrypt);
const canSign = action.includes(ProjectPermissionCmekActions.Sign);
const canVerify = action.includes(ProjectPermissionCmekActions.Verify);
+ const canExportPrivateKey = action.includes(ProjectPermissionCmekActions.ExportPrivateKey);
if (!formVal[subject]) formVal[subject] = [{}];
// from above statement we are sure it won't be undefined
- if (canRead) formVal[subject]![0].read = true;
- if (canEdit) formVal[subject]![0].edit = true;
- if (canCreate) formVal[subject]![0].create = true;
- if (canDelete) formVal[subject]![0].delete = true;
- if (canEncrypt) formVal[subject]![0].encrypt = true;
- if (canDecrypt) formVal[subject]![0].decrypt = true;
- if (canSign) formVal[subject]![0].sign = true;
- if (canVerify) formVal[subject]![0].verify = true;
+ if (canRead) formVal[subject]![0][ProjectPermissionCmekActions.Read] = true;
+ if (canEdit) formVal[subject]![0][ProjectPermissionCmekActions.Edit] = true;
+ if (canCreate) formVal[subject]![0][ProjectPermissionCmekActions.Create] = true;
+ if (canDelete) formVal[subject]![0][ProjectPermissionCmekActions.Delete] = true;
+ if (canEncrypt) formVal[subject]![0][ProjectPermissionCmekActions.Encrypt] = true;
+ if (canDecrypt) formVal[subject]![0][ProjectPermissionCmekActions.Decrypt] = true;
+ if (canSign) formVal[subject]![0][ProjectPermissionCmekActions.Sign] = true;
+ if (canVerify) formVal[subject]![0][ProjectPermissionCmekActions.Verify] = true;
+ if (canExportPrivateKey)
+ formVal[subject]![0][ProjectPermissionCmekActions.ExportPrivateKey] = true;
return;
}
@@ -1576,14 +1580,15 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
[ProjectPermissionSub.Cmek]: {
title: "KMS",
actions: [
- { label: "Read", value: "read" },
- { label: "Create", value: "create" },
- { label: "Modify", value: "edit" },
- { label: "Remove", value: "delete" },
- { label: "Encrypt", value: "encrypt" },
- { label: "Decrypt", value: "decrypt" },
- { label: "Sign", value: "sign" },
- { label: "Verify", value: "verify" }
+ { label: "Read", value: ProjectPermissionCmekActions.Read },
+ { label: "Create", value: ProjectPermissionCmekActions.Create },
+ { label: "Modify", value: ProjectPermissionCmekActions.Edit },
+ { label: "Remove", value: ProjectPermissionCmekActions.Delete },
+ { label: "Encrypt", value: ProjectPermissionCmekActions.Encrypt },
+ { label: "Decrypt", value: ProjectPermissionCmekActions.Decrypt },
+ { label: "Sign", value: ProjectPermissionCmekActions.Sign },
+ { label: "Verify", value: ProjectPermissionCmekActions.Verify },
+ { label: "Export Private Key", value: ProjectPermissionCmekActions.ExportPrivateKey }
]
},
[ProjectPermissionSub.Kms]: {