Skip to content

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

Add support for HMAC keys

Carlos Monastyrski6e81112774ba
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 44bdc38169..e4cf52764d 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -29,6 +29,7 @@ import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certif
import { SshCertTemplateStatus } from "@app/ee/services/ssh-certificate-template/ssh-certificate-template-types";
import { TLoginMapping } from "@app/ee/services/ssh-host/ssh-host-types";
import { SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
+import { HmacAlgorithm } from "@app/lib/crypto/hmac";
import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign/types";
import { TOrgPermission, TProjectPermission } from "@app/lib/types";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -541,6 +542,8 @@ export enum EventType {
CMEK_DECRYPT = "cmek-decrypt",
CMEK_SIGN = "cmek-sign",
CMEK_VERIFY = "cmek-verify",
+ CMEK_GENERATE_MAC = "cmek-generate-mac",
+ CMEK_VERIFY_MAC = "cmek-verify-mac",
CMEK_LIST_SIGNING_ALGORITHMS = "cmek-list-signing-algorithms",
CMEK_GET_PUBLIC_KEY = "cmek-get-public-key",
CMEK_GET_PRIVATE_KEY = "cmek-get-private-key",
@@ -4341,7 +4344,7 @@ interface CreateCmekEvent {
keyId: string;
name: string;
description?: string;
- encryptionAlgorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm;
+ encryptionAlgorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm | HmacAlgorithm;
isExportable?: boolean;
};
}
@@ -4417,6 +4420,25 @@ interface CmekVerifyEvent {
};
}
+interface CmekGenerateMacEvent {
+ type: EventType.CMEK_GENERATE_MAC;
+ metadata: {
+ keyId: string;
+ macAlgorithm: HmacAlgorithm;
+ mac: string;
+ };
+}
+
+interface CmekVerifyMacEvent {
+ type: EventType.CMEK_VERIFY_MAC;
+ metadata: {
+ keyId: string;
+ macAlgorithm: HmacAlgorithm;
+ mac: string;
+ macValid: boolean;
+ };
+}
+
interface CmekListSigningAlgorithmsEvent {
type: EventType.CMEK_LIST_SIGNING_ALGORITHMS;
metadata: {
@@ -7732,6 +7754,8 @@ export type Event =
| CmekDecryptEvent
| CmekSignEvent
| CmekVerifyEvent
+ | CmekGenerateMacEvent
+ | CmekVerifyMacEvent
| CmekListSigningAlgorithmsEvent
| CmekGetPublicKeyEvent
| CmekGetPrivateKeyEvent
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 90cf31fc4d..7466697516 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -279,6 +279,8 @@ const buildAdminPermissionRules = () => {
ProjectPermissionCmekActions.Decrypt,
ProjectPermissionCmekActions.Sign,
ProjectPermissionCmekActions.Verify,
+ ProjectPermissionCmekActions.GenerateMac,
+ ProjectPermissionCmekActions.VerifyMac,
ProjectPermissionCmekActions.Rotate,
ProjectPermissionCmekActions.ExportPrivateKey
],
@@ -643,6 +645,8 @@ const buildMemberPermissionRules = () => {
ProjectPermissionCmekActions.Decrypt,
ProjectPermissionCmekActions.Sign,
ProjectPermissionCmekActions.Verify,
+ ProjectPermissionCmekActions.GenerateMac,
+ ProjectPermissionCmekActions.VerifyMac,
ProjectPermissionCmekActions.Rotate
],
ProjectPermissionSub.Cmek
@@ -805,7 +809,9 @@ const buildCryptographicOperatorPermissionRules = () => {
ProjectPermissionCmekActions.Encrypt,
ProjectPermissionCmekActions.Decrypt,
ProjectPermissionCmekActions.Sign,
- ProjectPermissionCmekActions.Verify
+ ProjectPermissionCmekActions.Verify,
+ ProjectPermissionCmekActions.GenerateMac,
+ ProjectPermissionCmekActions.VerifyMac
],
ProjectPermissionSub.Cmek
);
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index a72e8660e2..5e1864966c 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -60,6 +60,8 @@ export enum ProjectPermissionCmekActions {
Decrypt = "decrypt",
Sign = "sign",
Verify = "verify",
+ GenerateMac = "generate-mac",
+ VerifyMac = "verify-mac",
Rotate = "rotate",
ExportPrivateKey = "export-private-key"
}
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index bdab71e86e..76159e9734 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2630,6 +2630,15 @@ export const KMS = {
data: "The data in string format to be verified (base64 encoded). For data larger than 1MB you must first create a digest of the data and then pass the digest in the data parameter.",
signature: "The signature to be verified (base64 encoded).",
isDigest: "Whether the data is already digested or not."
+ },
+ GENERATE_MAC: {
+ keyId: "The ID of the key to generate the MAC with. The key must be for generating and verifying MACs.",
+ data: "The data in string format to generate the MAC for (base64 encoded)."
+ },
+ VERIFY_MAC: {
+ keyId: "The ID of the key to verify the MAC with. The key must be for generating and verifying MACs.",
+ data: "The data in string format the MAC was generated for (base64 encoded).",
+ mac: "The MAC to be verified (base64 encoded)."
}
};
diff --git a/backend/src/lib/crypto/hmac/hmac.ts b/backend/src/lib/crypto/hmac/hmac.ts
new file mode 100644
index 0000000000..68cca7f5ee
--- /dev/null
+++ b/backend/src/lib/crypto/hmac/hmac.ts
@@ -0,0 +1,46 @@
+import { crypto } from "@app/lib/crypto/cryptography";
+import { BadRequestError } from "@app/lib/errors";
+
+import { HmacAlgorithm, THmacFns } from "./types";
+
+const HMAC_ALGORITHM_CONFIG: Record<HmacAlgorithm, { hash: string; keyByteLength: number }> = {
+ [HmacAlgorithm.HMAC_SHA_1]: { hash: "sha1", keyByteLength: 20 },
+ [HmacAlgorithm.HMAC_SHA_224]: { hash: "sha224", keyByteLength: 28 },
+ [HmacAlgorithm.HMAC_SHA_256]: { hash: "sha256", keyByteLength: 32 },
+ [HmacAlgorithm.HMAC_SHA_384]: { hash: "sha384", keyByteLength: 48 },
+ [HmacAlgorithm.HMAC_SHA_512]: { hash: "sha512", keyByteLength: 64 }
+};
+
+export const getHmacAlgorithmConfig = (algorithm: HmacAlgorithm) => {
+ const config = HMAC_ALGORITHM_CONFIG[algorithm];
+ if (!config) {
+ throw new BadRequestError({ message: `Unsupported HMAC algorithm: ${algorithm as string}` });
+ }
+ return config;
+};
+
+/**
+ * Service for HMAC (RFC 2104) message authentication code generation and verification.
+ *
+ * @param algorithm The HMAC algorithm, which also determines the hash function and generated key length.
+ * @returns Object with generateMac, verifyMac, generateKeyMaterial and getKeyByteLength functions.
+ */
+export const hmacService = (algorithm: HmacAlgorithm): THmacFns => {
+ const { hash, keyByteLength } = getHmacAlgorithmConfig(algorithm);
+
+ const generateMac = (data: Buffer, key: Buffer) => crypto.nativeCrypto.createHmac(hash, key).update(data).digest();
+
+ const verifyMac = (data: Buffer, mac: Buffer, key: Buffer) => {
+ const expected = crypto.nativeCrypto.createHmac(hash, key).update(data).digest();
+ if (expected.length !== mac.length) {
+ return false;
+ }
+ return crypto.nativeCrypto.timingSafeEqual(expected, mac);
+ };
+
+ const generateKeyMaterial = () => crypto.randomBytes(keyByteLength);
+
+ const getKeyByteLength = () => keyByteLength;
+
+ return { generateMac, verifyMac, generateKeyMaterial, getKeyByteLength };
+};
diff --git a/backend/src/lib/crypto/hmac/index.ts b/backend/src/lib/crypto/hmac/index.ts
new file mode 100644
index 0000000000..7d0f5c4cd6
--- /dev/null
+++ b/backend/src/lib/crypto/hmac/index.ts
@@ -0,0 +1,2 @@
+export { getHmacAlgorithmConfig, hmacService } from "./hmac";
+export { HmacAlgorithm, HmacAlgorithmEnum } from "./types";
diff --git a/backend/src/lib/crypto/hmac/types.ts b/backend/src/lib/crypto/hmac/types.ts
new file mode 100644
index 0000000000..709151ca64
--- /dev/null
+++ b/backend/src/lib/crypto/hmac/types.ts
@@ -0,0 +1,18 @@
+import { z } from "zod";
+
+export type THmacFns = {
+ generateMac: (data: Buffer, key: Buffer) => Buffer;
+ verifyMac: (data: Buffer, mac: Buffer, key: Buffer) => boolean;
+ generateKeyMaterial: () => Buffer;
+ getKeyByteLength: () => number;
+};
+
+export enum HmacAlgorithm {
+ HMAC_SHA_1 = "HMAC_SHA_1",
+ HMAC_SHA_224 = "HMAC_SHA_224",
+ HMAC_SHA_256 = "HMAC_SHA_256",
+ HMAC_SHA_384 = "HMAC_SHA_384",
+ HMAC_SHA_512 = "HMAC_SHA_512"
+}
+
+export const HmacAlgorithmEnum = z.enum(Object.values(HmacAlgorithm) as [string, ...string[]]).options;
diff --git a/backend/src/server/routes/v1/cmek-router.ts b/backend/src/server/routes/v1/cmek-router.ts
index 11f4822322..3bfdc20442 100644
--- a/backend/src/server/routes/v1/cmek-router.ts
+++ b/backend/src/server/routes/v1/cmek-router.ts
@@ -4,7 +4,8 @@ import { InternalKmsSchema, KmsKeysSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, KMS } from "@app/lib/api-docs";
import { getBase64SizeInBytes, isBase64 } from "@app/lib/base64";
-import { AllowedEncryptionKeyAlgorithms, SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
+import { SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
+import { HmacAlgorithm } from "@app/lib/crypto/hmac";
import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign";
import { OrderByDirection } from "@app/lib/types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -19,6 +20,12 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
const keyNameSchema = slugSchema({ min: 1, max: 32, field: "Name" });
const keyDescriptionSchema = z.string().trim().max(500).optional();
+const AllowedKmsKeyAlgorithms = [
+ ...Object.values(SymmetricKeyAlgorithm),
+ ...Object.values(AsymmetricKeyAlgorithm),
+ ...Object.values(HmacAlgorithm)
+] as [string, ...string[]];
+
const CmekSchema = KmsKeysSchema.merge(InternalKmsSchema.pick({ version: true, encryptionAlgorithm: true })).omit({
isReserved: true
});
@@ -52,6 +59,7 @@ const createBase64Schema = (field: string, maxBytes: number) =>
const base64Schema = createBase64Schema("data", MAX_KMS_PAYLOAD_BYTES);
const ciphertextBase64Schema = createBase64Schema("ciphertext", MAX_KMS_CIPHERTEXT_BYTES);
const signatureBase64Schema = createBase64Schema("signature", MAX_KMS_SIGNATURE_BYTES);
+const macBase64Schema = createBase64Schema("mac", 1024);
export const registerCmekRouter = async (server: FastifyZodProvider) => {
// create encryption key
@@ -77,7 +85,7 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
.default(KmsKeyUsage.ENCRYPT_DECRYPT)
.describe(KMS.CREATE_KEY.type),
encryptionAlgorithm: z
- .enum(AllowedEncryptionKeyAlgorithms)
+ .enum(AllowedKmsKeyAlgorithms)
.optional()
.default(SymmetricKeyAlgorithm.AES_GCM_256)
.describe(KMS.CREATE_KEY.encryptionAlgorithm),
@@ -106,6 +114,17 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
).join(", ")}`
});
}
+ if (
+ data.keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC &&
+ !Object.values(HmacAlgorithm).includes(data.encryptionAlgorithm as HmacAlgorithm)
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `encryptionAlgorithm must be a valid HMAC algorithm. Valid options are: ${Object.values(
+ HmacAlgorithm
+ ).join(", ")}`
+ });
+ }
}),
response: {
200: z.object({
@@ -624,7 +643,7 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
.object({
name: keyNameSchema,
keyUsage: z.nativeEnum(KmsKeyUsage),
- encryptionAlgorithm: z.enum(AllowedEncryptionKeyAlgorithms),
+ encryptionAlgorithm: z.enum(AllowedKmsKeyAlgorithms),
keyMaterial: z.string().min(1),
isExportable: z.boolean().optional().default(true).describe(KMS.CREATE_KEY.isExportable)
})
@@ -647,6 +666,15 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
message: `encryptionAlgorithm must be an asymmetric algorithm for sign-verify keys`
});
}
+ if (
+ data.keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC &&
+ !Object.values(HmacAlgorithm).includes(data.encryptionAlgorithm as HmacAlgorithm)
+ ) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `encryptionAlgorithm must be an HMAC algorithm for generate-verify-mac keys`
+ });
+ }
if (!isBase64(data.keyMaterial)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
@@ -919,6 +947,114 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ bodyLimit: KMS_PAYLOAD_BODY_LIMIT_BYTES,
+ url: "/keys/:keyId/generate-mac",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "generateMacWithKmsKey",
+ tags: [ApiDocsTags.KmsSigning],
+ description: "Generate an HMAC (MAC) for data with a KMS key.",
+ params: z.object({
+ keyId: z.string().uuid().describe(KMS.GENERATE_MAC.keyId)
+ }),
+ body: z.object({
+ data: base64Schema.describe(KMS.GENERATE_MAC.data)
+ }),
+ response: {
+ 200: z.object({
+ mac: z.string(),
+ keyId: z.string().uuid(),
+ macAlgorithm: z.nativeEnum(HmacAlgorithm)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const {
+ params: { keyId },
+ body: { data },
+ permission
+ } = req;
+
+ const { projectId, ...result } = await server.services.cmek.cmekGenerateMac({ keyId, data }, permission);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.CMEK_GENERATE_MAC,
+ metadata: {
+ keyId,
+ macAlgorithm: result.macAlgorithm,
+ mac: result.mac
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ bodyLimit: KMS_PAYLOAD_BODY_LIMIT_BYTES,
+ url: "/keys/:keyId/verify-mac",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "verifyMacWithKmsKey",
+ tags: [ApiDocsTags.KmsSigning],
+ description: "Verify an HMAC (MAC) for data with a KMS key.",
+ params: z.object({
+ keyId: z.string().uuid().describe(KMS.VERIFY_MAC.keyId)
+ }),
+ body: z.object({
+ data: base64Schema.describe(KMS.VERIFY_MAC.data),
+ mac: macBase64Schema.describe(KMS.VERIFY_MAC.mac)
+ }),
+ response: {
+ 200: z.object({
+ macValid: z.boolean(),
+ keyId: z.string().uuid(),
+ macAlgorithm: z.nativeEnum(HmacAlgorithm)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const {
+ params: { keyId },
+ body: { data, mac },
+ permission
+ } = req;
+
+ const { projectId, ...result } = await server.services.cmek.cmekVerifyMac({ keyId, data, mac }, permission);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.CMEK_VERIFY_MAC,
+ metadata: {
+ keyId,
+ macAlgorithm: result.macAlgorithm,
+ mac,
+ macValid: result.macValid
+ }
+ }
+ });
+
+ return result;
+ }
+ });
+
server.route({
method: "POST",
bodyLimit: KMS_PAYLOAD_BODY_LIMIT_BYTES,
diff --git a/backend/src/services/cmek/cmek-service.ts b/backend/src/services/cmek/cmek-service.ts
index d8c2d28a91..1b605d4c59 100644
--- a/backend/src/services/cmek/cmek-service.ts
+++ b/backend/src/services/cmek/cmek-service.ts
@@ -14,12 +14,14 @@ import {
TCmekBulkImportKeysResult,
TCmekDecryptDTO,
TCmekEncryptDTO,
+ TCmekGenerateMacDTO,
TCmekGetPrivateKeyDTO,
TCmekGetPublicKeyDTO,
TCmekKeyEncryptionAlgorithm,
TCmekListSigningAlgorithmsDTO,
TCmekSignDTO,
TCmekVerifyDTO,
+ TCmekVerifyMacDTO,
TCreateCmekDTO,
TListCmeksByProjectIdDTO,
TUpdabteCmekByIdDTO
@@ -538,6 +540,81 @@ export const cmekServiceFactory = ({
};
};
+ const cmekGenerateMac = async ({ keyId, data }: TCmekGenerateMacDTO, 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.GenerateMac, ProjectPermissionSub.Cmek);
+
+ if (key.keyUsage !== KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ throw new BadRequestError({ message: `Key with ID '${keyId}' is not intended for MAC generation` });
+ }
+
+ const generate = await kmsService.generateMac({ kmsId: keyId });
+
+ const { mac, algorithm } = generate({ data: Buffer.from(data, "base64") });
+
+ return {
+ mac: mac.toString("base64"),
+ keyId: key.id,
+ projectId: key.projectId,
+ macAlgorithm: algorithm
+ };
+ };
+
+ const cmekVerifyMac = async ({ keyId, data, mac }: TCmekVerifyMacDTO, 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.VerifyMac, ProjectPermissionSub.Cmek);
+
+ if (key.keyUsage !== KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ throw new BadRequestError({ message: `Key with ID '${keyId}' is not intended for MAC verification` });
+ }
+
+ const verify = await kmsService.verifyMac({ kmsId: keyId });
+
+ const { macValid, algorithm } = verify({
+ data: Buffer.from(data, "base64"),
+ mac: Buffer.from(mac, "base64")
+ });
+
+ return {
+ macValid,
+ keyId: key.id,
+ projectId: key.projectId,
+ macAlgorithm: algorithm
+ };
+ };
+
const cmekDecrypt = async ({ keyId, ciphertext }: TCmekDecryptDTO, actor: OrgServiceActor) => {
const key = await kmsDAL.findById(keyId);
@@ -650,6 +727,8 @@ export const cmekServiceFactory = ({
findCmekByName,
cmekSign,
cmekVerify,
+ cmekGenerateMac,
+ cmekVerifyMac,
listSigningAlgorithms,
getPublicKey,
getPrivateKey,
diff --git a/backend/src/services/cmek/cmek-types.ts b/backend/src/services/cmek/cmek-types.ts
index 185aa0213f..522ea873e4 100644
--- a/backend/src/services/cmek/cmek-types.ts
+++ b/backend/src/services/cmek/cmek-types.ts
@@ -1,10 +1,11 @@
import { SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
+import { HmacAlgorithm } from "@app/lib/crypto/hmac";
import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign";
import { OrderByDirection } from "@app/lib/types";
import { KmsKeyUsage } from "../kms/kms-types";
-export type TCmekKeyEncryptionAlgorithm = SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm;
+export type TCmekKeyEncryptionAlgorithm = SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm | HmacAlgorithm;
export type TCreateCmekDTO = {
orgId: string;
@@ -95,3 +96,14 @@ export type TCmekVerifyDTO = {
signingAlgorithm: SigningAlgorithm;
isDigest: boolean;
};
+
+export type TCmekGenerateMacDTO = {
+ keyId: string;
+ data: string;
+};
+
+export type TCmekVerifyMacDTO = {
+ keyId: string;
+ data: string;
+ mac: string;
+};
diff --git a/backend/src/services/kms/kms-fns.ts b/backend/src/services/kms/kms-fns.ts
index 8c7aa13dd5..1d579b7040 100644
--- a/backend/src/services/kms/kms-fns.ts
+++ b/backend/src/services/kms/kms-fns.ts
@@ -1,9 +1,13 @@
import { SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
+import { HmacAlgorithm } from "@app/lib/crypto/hmac";
import { AsymmetricKeyAlgorithm } from "@app/lib/crypto/sign";
import { BadRequestError } from "@app/lib/errors";
import { KmsKeyUsage } from "./kms-types";
+export const MIN_HMAC_IMPORT_KEY_BYTE_LENGTH = 1;
+export const MAX_HMAC_IMPORT_KEY_BYTE_LENGTH = 1024;
+
export const KMS_ROOT_CONFIG_UUID = "00000000-0000-0000-0000-000000000000";
export const getByteLengthForSymmetricEncryptionAlgorithm = (encryptionAlgorithm: SymmetricKeyAlgorithm) => {
@@ -18,7 +22,7 @@ export const getByteLengthForSymmetricEncryptionAlgorithm = (encryptionAlgorithm
export const verifyKeyTypeAndAlgorithm = (
keyUsage: KmsKeyUsage,
- algorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm,
+ algorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm | HmacAlgorithm,
extra?: {
forceType?: KmsKeyUsage;
}
@@ -49,6 +53,16 @@ export const verifyKeyTypeAndAlgorithm = (
return true;
}
+ if (keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ if (!Object.values(HmacAlgorithm).includes(algorithm as HmacAlgorithm)) {
+ throw new BadRequestError({
+ message: `Unsupported HMAC algorithm for generate/verify MAC key: ${algorithm as string}`
+ });
+ }
+
+ return true;
+ }
+
throw new BadRequestError({
message: `Unsupported key type: ${keyUsage as string}`
});
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index cf383feb43..8cf350b813 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -18,6 +18,7 @@ import { TEnvConfig } from "@app/lib/config/env";
import { generateSecretValueBlindIndexFromKmsKey } from "@app/lib/crypto/blind-index";
import { symmetricCipherService, SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
import { crypto } from "@app/lib/crypto/cryptography";
+import { HmacAlgorithm, hmacService } from "@app/lib/crypto/hmac";
import { detectPqcVariantFromDer } from "@app/lib/crypto/pqc/pqc-crypto";
import { AsymmetricKeyAlgorithm, isPqcKeyAlgorithm, KMS_TO_OPENSSL_NAME, signingService } from "@app/lib/crypto/sign";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
@@ -28,6 +29,8 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import {
getByteLengthForSymmetricEncryptionAlgorithm,
KMS_ROOT_CONFIG_UUID,
+ MAX_HMAC_IMPORT_KEY_BYTE_LENGTH,
+ MIN_HMAC_IMPORT_KEY_BYTE_LENGTH,
verifyKeyTypeAndAlgorithm
} from "@app/services/kms/kms-fns";
@@ -48,12 +51,14 @@ import {
TEncryptWithKmsDataKeyDTO,
TEncryptWithKmsDTO,
TGenerateKMSDTO,
+ TGenerateMacDTO,
TGetBulkKeyMaterialDTO,
TGetKeyMaterialDTO,
TGetPublicKeyDTO,
TImportKeyMaterialDTO,
TSignWithKmsDTO,
TUpdateProjectSecretManagerKmsKeyDTO,
+ TVerifyMacDTO,
TVerifyWithKmsDTO
} from "./kms-types";
@@ -143,6 +148,8 @@ export const kmsServiceFactory = ({
// daniel: safety check to ensure we're able to extract the public key from the private key before we proceed to key creation
await getPublicKeyFromPrivateKey(kmsKeyMaterial);
+ } else if (keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ kmsKeyMaterial = hmacService(encryptionAlgorithm as HmacAlgorithm).generateKeyMaterial();
}
if (!kmsKeyMaterial) {
@@ -216,7 +223,7 @@ export const kmsServiceFactory = ({
if ((kmsDoc.keyUsage as KmsKeyUsage) !== KmsKeyUsage.ENCRYPT_DECRYPT) {
throw new BadRequestError({
message:
- "Only encrypt-decrypt keys support rotation. Rotate sign-verify keys manually by creating a new key and updating your applications to use it."
+ "Only encrypt-decrypt keys support rotation. To rotate a sign-verify or MAC key, create a new key and update your applications to use it."
});
}
@@ -646,6 +653,14 @@ export const kmsServiceFactory = ({
}
}
+ if (keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ if (key.length < MIN_HMAC_IMPORT_KEY_BYTE_LENGTH || key.length > MAX_HMAC_IMPORT_KEY_BYTE_LENGTH) {
+ throw new BadRequestError({
+ message: `Invalid HMAC key material length. Expected between ${MIN_HMAC_IMPORT_KEY_BYTE_LENGTH} and ${MAX_HMAC_IMPORT_KEY_BYTE_LENGTH} bytes, got ${key.length}.`
+ });
+ }
+ }
+
const cipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
const encryptedKeyMaterial = cipher.encrypt(key, ROOT_ENCRYPTION_KEY);
@@ -748,6 +763,46 @@ export const kmsServiceFactory = ({
};
};
+ const generateMac = async ({ kmsId }: Pick<TGenerateMacDTO, "kmsId">) => {
+ const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId);
+ if (!kmsDoc) {
+ throw new NotFoundError({ message: `KMS with ID '${kmsId}' not found` });
+ }
+
+ const macAlgorithm = kmsDoc.internalKms?.encryptionAlgorithm as HmacAlgorithm;
+ verifyKeyTypeAndAlgorithm(kmsDoc.keyUsage as KmsKeyUsage, macAlgorithm, {
+ forceType: KmsKeyUsage.GENERATE_VERIFY_MAC
+ });
+
+ const keyCipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
+ const { generateMac: generate } = hmacService(macAlgorithm);
+ return ({ data }: Pick<TGenerateMacDTO, "data">) => {
+ const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
+ const mac = generate(data, kmsKey);
+ return { mac, algorithm: macAlgorithm };
+ };
+ };
+
+ const verifyMac = async ({ kmsId }: Pick<TVerifyMacDTO, "kmsId">) => {
+ const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId);
+ if (!kmsDoc) {
+ throw new NotFoundError({ message: `KMS with ID '${kmsId}' not found` });
+ }
+
+ const macAlgorithm = kmsDoc.internalKms?.encryptionAlgorithm as HmacAlgorithm;
+ verifyKeyTypeAndAlgorithm(kmsDoc.keyUsage as KmsKeyUsage, macAlgorithm, {
+ forceType: KmsKeyUsage.GENERATE_VERIFY_MAC
+ });
+
+ const keyCipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
+ const { verifyMac: verify } = hmacService(macAlgorithm);
+ return ({ data, mac }: Pick<TVerifyMacDTO, "data" | "mac">) => {
+ const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
+ const macValid = verify(data, mac, kmsKey);
+ return { macValid, algorithm: macAlgorithm };
+ };
+ };
+
const encryptWithKmsKey = async ({ kmsId }: Omit<TEncryptWithKmsDTO, "plainText">, tx?: Knex) => {
const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId, tx);
if (!kmsDoc) {
@@ -1358,6 +1413,8 @@ export const kmsServiceFactory = ({
importKeyMaterial,
signWithKmsKey,
verifyWithKmsKey,
+ generateMac,
+ verifyMac,
getPublicKey
};
};
diff --git a/backend/src/services/kms/kms-types.ts b/backend/src/services/kms/kms-types.ts
index f59990d7d7..3a7b8f0e42 100644
--- a/backend/src/services/kms/kms-types.ts
+++ b/backend/src/services/kms/kms-types.ts
@@ -1,6 +1,7 @@
import { Knex } from "knex";
import { SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
+import { HmacAlgorithm } from "@app/lib/crypto/hmac";
import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign/types";
export enum KmsDataKey {
@@ -16,7 +17,8 @@ export enum KmsType {
export enum KmsKeyUsage {
ENCRYPT_DECRYPT = "encrypt-decrypt",
- SIGN_VERIFY = "sign-verify"
+ SIGN_VERIFY = "sign-verify",
+ GENERATE_VERIFY_MAC = "generate-verify-mac"
}
export type TEncryptWithKmsDataKeyDTO =
@@ -31,7 +33,7 @@ export type TEncryptWithKmsDataKeyDTO =
export type TGenerateKMSDTO = {
orgId: string;
projectId?: string;
- encryptionAlgorithm?: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm;
+ encryptionAlgorithm?: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm | HmacAlgorithm;
keyUsage?: KmsKeyUsage;
isReserved?: boolean;
isExportable?: boolean;
@@ -64,6 +66,17 @@ export type TVerifyWithKmsDTO = {
isDigest: boolean;
};
+export type TGenerateMacDTO = {
+ kmsId: string;
+ data: Buffer;
+};
+
+export type TVerifyMacDTO = {
+ kmsId: string;
+ data: Buffer;
+ mac: Buffer;
+};
+
export type TEncryptionWithKeyDTO = {
key: Buffer;
plainText: Buffer;
@@ -98,7 +111,7 @@ export type TGetBulkKeyMaterialDTO = {
export type TImportKeyMaterialDTO = {
key: Buffer;
- algorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm;
+ algorithm: SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm | HmacAlgorithm;
name?: string;
isReserved: boolean;
isExportable?: boolean;
diff --git a/docs/api-reference/endpoints/kms/mac/generate-mac.mdx b/docs/api-reference/endpoints/kms/mac/generate-mac.mdx
new file mode 100644
index 0000000000..c1c5a46390
--- /dev/null
+++ b/docs/api-reference/endpoints/kms/mac/generate-mac.mdx
@@ -0,0 +1,4 @@
+---
+title: "Generate MAC"
+openapi: "POST /api/v1/kms/keys/{keyId}/generate-mac"
+---
diff --git a/docs/api-reference/endpoints/kms/mac/verify-mac.mdx b/docs/api-reference/endpoints/kms/mac/verify-mac.mdx
new file mode 100644
index 0000000000..b95962fa6a
--- /dev/null
+++ b/docs/api-reference/endpoints/kms/mac/verify-mac.mdx
@@ -0,0 +1,4 @@
+---
+title: "Verify MAC"
+openapi: "POST /api/v1/kms/keys/{keyId}/verify-mac"
+---
diff --git a/docs/docs.json b/docs/docs.json
index ef307d9722..b7bf47179b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -3982,6 +3982,13 @@
"api-reference/endpoints/kms/signing/verify",
"api-reference/endpoints/kms/signing/signing-algorithms"
]
+ },
+ {
+ "group": "Message Authentication",
+ "pages": [
+ "api-reference/endpoints/kms/mac/generate-mac",
+ "api-reference/endpoints/kms/mac/verify-mac"
+ ]
}
]
},
diff --git a/docs/documentation/platform/kms/overview.mdx b/docs/documentation/platform/kms/overview.mdx
index 431ed25b4d..98dcc61a7b 100644
--- a/docs/documentation/platform/kms/overview.mdx
+++ b/docs/documentation/platform/kms/overview.mdx
@@ -46,7 +46,7 @@ In the following steps, we explore how to generate a key and use it to encrypt d
Specify your key details. Here's some guidance on each field:
- Name: A slug-friendly name for the key.
- - Key Usage: The type of key to create (e.g `Encrypt/Decrypt` for encryption, and `Sign/Verify` for signing).
+ - Key Usage: The type of key to create (e.g `Encrypt/Decrypt` for encryption, `Sign/Verify` for signing, and `Generate/Verify MAC` for message authentication codes).
- Algorithm: The encryption algorithm associated with the key (e.g. `AES-GCM-256`).
- Description: An optional description of what the intended usage is for the key.
- Allow Export: Whether the raw key material can be exported later. When disabled, the key material can never leave Infisical, regardless of permissions. This cannot be changed after the key is created.
@@ -213,7 +213,7 @@ In the following steps, we explore how to generate a key and use it to sign data
Specify your key details. Here's some guidance on each field:
- Name: A slug-friendly name for the key.
- - Key Usage: The type of key to create (e.g `Encrypt/Decrypt` for encryption, and `Sign/Verify` for signing).
+ - Key Usage: The type of key to create (e.g `Encrypt/Decrypt` for encryption, `Sign/Verify` for signing, and `Generate/Verify MAC` for message authentication codes).
- Algorithm: The signing algorithm associated with the key (e.g. `RSA_4096`).
- Description: An optional description of what the intended usage is for the key.
@@ -366,6 +366,126 @@ In the following steps, we explore how to verify data using an existing key in I
</Tab>
</Tabs>
+## Message Authentication (MAC)
+
+HMAC keys generate and verify hash-based message authentication codes, which confirm the integrity and authenticity of data using a shared secret key. The algorithm you choose at key creation determines both the key length and the hash function, so every generate and verify operation on that key uses the same MAC algorithm.
+
+### Guide to Generating a MAC
+
+In the following steps, we explore how to generate a key and use it to produce a MAC.
+
+<Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step title="Creating a KMS key">
+ Navigate to Project > Key Management and tap on the **Add Key** button.
+ ![kms add key button](/images/platform/kms/infisical-kms/kms-add-key.png)
+
+ Specify your key details. Here's some guidance on each field:
+
+ - Name: A slug-friendly name for the key.
+ - Key Usage: Select `Generate/Verify MAC`.
+ - Algorithm: The HMAC algorithm associated with the key (e.g. `HMAC_SHA_256`). Supported algorithms are `HMAC_SHA_1`, `HMAC_SHA_224`, `HMAC_SHA_256`, `HMAC_SHA_384`, and `HMAC_SHA_512`.
+ - Description: An optional description of what the intended usage is for the key.
+ - Allow Export: Whether the raw key material can be exported later. When disabled, the key material can never leave Infisical, regardless of permissions. This cannot be changed after the key is created.
+ </Step>
+ <Step title="Generating a MAC with the KMS key">
+ Once your key is generated, open the options menu for the newly created key and select generate MAC.
+
+ Populate the text area with your data and tap on the Generate MAC button. The MAC algorithm is determined by the key.
+
+ <Note>
+ If your data is already Base64 encoded make sure to toggle the respective switch on to avoid
+ redundant encoding.
+ </Note>
+
+ Copy and store the MAC of your data.
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ <Steps>
+ <Step title="Generating a MAC">
+ To generate a MAC, make an API request to the [Generate
+ MAC](/api-reference/endpoints/kms/mac/generate-mac) API endpoint,
+ specifying the key to use.
+
+ ### Sample request
+
+ ```bash Request
+ curl --request POST \
+ --url https://app.infisical.com/api/v1/kms/keys/<key-id>/generate-mac \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "data": "SGVsbG8sIFdvcmxkIQ==" // base64 encoded data
+ }'
+ ```
+
+ ### Sample response
+
+ ```bash Response
+ {
+ "mac": "5Vki892/TV/exl2K+mgAJyRblgCdLQpL//rr/rmT5rY=", // base64 encoded MAC
+ "keyId": "62b2c14e-58af-4199-9842-02995c63edf9",
+ "macAlgorithm": "HMAC_SHA_256"
+ }
+ ```
+ </Step>
+ </Steps>
+ </Tab>
+</Tabs>
+
+### Guide to Verifying a MAC
+
+In the following steps, we explore how to verify a MAC using an existing key in Infisical KMS.
+
+<Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step title="Accessing your key">
+ Navigate to Project > Key Management and open the options menu for the key used to generate the MAC
+ you want to verify.
+ </Step>
+ <Step title="Verifying a MAC with the KMS key">
+ Select verify MAC, paste your MAC and data into the text areas, and tap on the Verify MAC button.
+
+ Your verification result will be displayed. If the MAC is invalid, the "MAC Status" field will be `Invalid`.
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ <Steps>
+ <Step title="Verifying a MAC">
+ To verify a MAC, make an API request to the [Verify
+ MAC](/api-reference/endpoints/kms/mac/verify-mac) API endpoint,
+ specifying the key to use.
+
+ ### Sample request
+
+ ```bash Request
+ curl --request POST \
+ --url https://app.infisical.com/api/v1/kms/keys/<key-id>/verify-mac \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "data": "SGVsbG8sIFdvcmxkIQ==", // base64 encoded data
+ "mac": "5Vki892/TV/exl2K+mgAJyRblgCdLQpL//rr/rmT5rY=" // base64 encoded MAC
+ }'
+ ```
+
+ ### Sample response
+
+ ```bash Response
+ {
+ "macValid": true,
+ "keyId": "62b2c14e-58af-4199-9842-02995c63edf9",
+ "macAlgorithm": "HMAC_SHA_256"
+ }
+ ```
+ </Step>
+ </Steps>
+ </Tab>
+</Tabs>
+
## Key Rotation
Every KMS key tracks a version, starting at 1. Rotating a key generates new cryptographic key material for it and increments the version. The key keeps the same ID and name, so applications referencing the key do not need any changes.
@@ -385,8 +505,9 @@ To rotate a key:
Keys can also be rotated programmatically via the [rotate key API endpoint](/api-reference/endpoints/kms/keys/rotate).
<Note>
- Rotation is supported for encrypt-decrypt keys with Infisical-managed key material. Sign-verify keys
- should be rotated manually by creating a new key and updating your applications to use it.
+ Rotation is supported for encrypt-decrypt keys with Infisical-managed key material. Sign-verify and
+ generate-verify-MAC keys should be rotated manually by creating a new key and updating your applications
+ to use it.
</Note>
<Warning>
@@ -428,6 +549,14 @@ The exported file is a JSON array where each entry is one of the following shape
"privateKey": "<base64-encoded private key>",
"publicKey": "<base64-encoded public key>"
}
+
+// Generate/Verify MAC key
+{
+ "name": "my-hmac-key",
+ "keyType": "generate-verify-mac",
+ "algorithm": "HMAC_SHA_256",
+ "keyMaterial": "<base64-encoded key material>"
+}
```
<Warning>
@@ -479,6 +608,13 @@ The exported file is a JSON array where each entry is one of the following shape
- `AES-256-GCM`
- `AES-128-GCM`
+ **Message authentication (MAC):**
+ - `HMAC_SHA_1`
+ - `HMAC_SHA_224`
+ - `HMAC_SHA_256`
+ - `HMAC_SHA_384`
+ - `HMAC_SHA_512`
+
<Info>
ML-DSA algorithms are an enterprise feature. Self-hosted users can contact [[email protected]](mailto:[email protected]) to purchase an enterprise license.
</Info>
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index 26f64668e3..19d028d03b 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -44,6 +44,8 @@ export enum ProjectPermissionCmekActions {
Decrypt = "decrypt",
Sign = "sign",
Verify = "verify",
+ GenerateMac = "generate-mac",
+ VerifyMac = "verify-mac",
Rotate = "rotate",
ExportPrivateKey = "export-private-key"
}
diff --git a/frontend/src/helpers/kms.ts b/frontend/src/helpers/kms.ts
index 11fd74fef1..b1ea08f978 100644
--- a/frontend/src/helpers/kms.ts
+++ b/frontend/src/helpers/kms.ts
@@ -1,5 +1,6 @@
import {
AsymmetricKeyAlgorithm,
+ HmacAlgorithm,
KmsKeyUsage,
SigningAlgorithm,
SymmetricKeyAlgorithm,
@@ -21,15 +22,21 @@ export const kmsKeyUsageOptions: Record<
label: "Sign/Verify",
tooltip:
"Key pairs for digital signing. Uses the private key for signing and the public key for verification."
+ },
+ [KmsKeyUsage.GENERATE_VERIFY_MAC]: {
+ label: "Generate/Verify MAC",
+ tooltip:
+ "Symmetric HMAC keys for generating and verifying hash-based message authentication codes (MACs)."
}
};
export const keyUsageDefaultOption: Record<
KmsKeyUsage,
- SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm
+ SymmetricKeyAlgorithm | AsymmetricKeyAlgorithm | HmacAlgorithm
> = {
[KmsKeyUsage.ENCRYPT_DECRYPT]: SymmetricKeyAlgorithm.AES_GCM_256,
- [KmsKeyUsage.SIGN_VERIFY]: AsymmetricKeyAlgorithm.RSA_4096
+ [KmsKeyUsage.SIGN_VERIFY]: AsymmetricKeyAlgorithm.RSA_4096,
+ [KmsKeyUsage.GENERATE_VERIFY_MAC]: HmacAlgorithm.HMAC_SHA_256
};
export const getDefaultSigningAlgorithm = (cmek: TCmek): SigningAlgorithm => {
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index f713c756ba..e23c509517 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -151,6 +151,8 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.CMEK_DECRYPT]: "Decrypt with KMS key",
[EventType.CMEK_SIGN]: "Sign with KMS key",
[EventType.CMEK_VERIFY]: "Verify with KMS key",
+ [EventType.CMEK_GENERATE_MAC]: "Generate MAC with KMS key",
+ [EventType.CMEK_VERIFY_MAC]: "Verify MAC with KMS key",
[EventType.CMEK_LIST_SIGNING_ALGORITHMS]: "List signing algorithms for KMS key",
[EventType.CMEK_GET_PUBLIC_KEY]: "Get public key for KMS key",
[EventType.CMEK_GET_PRIVATE_KEY]: "Get private key for KMS key",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index cbf730a9e2..fdb3f2ac16 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -162,6 +162,8 @@ export enum EventType {
CMEK_DECRYPT = "cmek-decrypt",
CMEK_SIGN = "cmek-sign",
CMEK_VERIFY = "cmek-verify",
+ CMEK_GENERATE_MAC = "cmek-generate-mac",
+ CMEK_VERIFY_MAC = "cmek-verify-mac",
CMEK_LIST_SIGNING_ALGORITHMS = "cmek-list-signing-algorithms",
CMEK_GET_PUBLIC_KEY = "cmek-get-public-key",
CMEK_GET_PRIVATE_KEY = "cmek-get-private-key",
diff --git a/frontend/src/hooks/api/cmeks/mutations.tsx b/frontend/src/hooks/api/cmeks/mutations.tsx
index a5781840d2..8dde01367c 100644
--- a/frontend/src/hooks/api/cmeks/mutations.tsx
+++ b/frontend/src/hooks/api/cmeks/mutations.tsx
@@ -12,9 +12,13 @@ import {
TCmekDecryptResponse,
TCmekEncrypt,
TCmekEncryptResponse,
+ TCmekGenerateMac,
+ TCmekGenerateMacResponse,
TCmekSign,
TCmekSignResponse,
TCmekVerify,
+ TCmekVerifyMac,
+ TCmekVerifyMacResponse,
TCmekVerifyResponse,
TCreateCmek,
TDeleteCmek,
@@ -135,6 +139,46 @@ export const useCmekVerify = () => {
});
};
+export const useCmekGenerateMac = () => {
+ return useMutation({
+ mutationFn: async ({
+ keyId,
+ data,
+ isBase64Encoded
+ }: TCmekGenerateMac & { isBase64Encoded: boolean }) => {
+ const res = await apiRequest.post<TCmekGenerateMacResponse>(
+ `/api/v1/kms/keys/${keyId}/generate-mac`,
+ {
+ data: isBase64Encoded ? data : encodeBase64(Buffer.from(data))
+ }
+ );
+
+ return res.data;
+ }
+ });
+};
+
+export const useCmekVerifyMac = () => {
+ return useMutation({
+ mutationFn: async ({
+ keyId,
+ data,
+ mac,
+ isBase64Encoded
+ }: TCmekVerifyMac & { isBase64Encoded: boolean }) => {
+ const res = await apiRequest.post<TCmekVerifyMacResponse>(
+ `/api/v1/kms/keys/${keyId}/verify-mac`,
+ {
+ data: isBase64Encoded ? data : encodeBase64(Buffer.from(data)),
+ mac
+ }
+ );
+
+ return res.data;
+ }
+ });
+};
+
export const useCmekDecrypt = () => {
return useMutation({
mutationFn: async ({ keyId, ciphertext }: TCmekDecrypt) => {
diff --git a/frontend/src/hooks/api/cmeks/types.ts b/frontend/src/hooks/api/cmeks/types.ts
index 29fbc5dc44..e89a5c9f4f 100644
--- a/frontend/src/hooks/api/cmeks/types.ts
+++ b/frontend/src/hooks/api/cmeks/types.ts
@@ -4,7 +4,8 @@ import { OrderByDirection } from "@app/hooks/api/generic/types";
export enum KmsKeyUsage {
ENCRYPT_DECRYPT = "encrypt-decrypt",
- SIGN_VERIFY = "sign-verify"
+ SIGN_VERIFY = "sign-verify",
+ GENERATE_VERIFY_MAC = "generate-verify-mac"
}
export type TCmek = {
@@ -12,7 +13,7 @@ export type TCmek = {
keyUsage: KmsKeyUsage;
name: string;
description?: string;
- encryptionAlgorithm: AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm;
+ encryptionAlgorithm: AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm | HmacAlgorithm;
projectId: string;
isDisabled: boolean;
isReserved: boolean;
@@ -45,6 +46,9 @@ export type TCmekVerify = KeyRef & {
signingAlgorithm: SigningAlgorithm;
};
+export type TCmekGenerateMac = KeyRef & { data: string };
+export type TCmekVerifyMac = KeyRef & { data: string; mac: string };
+
export type TProjectCmeksList = {
keys: TCmek[];
totalCount: number;
@@ -75,6 +79,18 @@ export type TCmekVerifyResponse = {
signingAlgorithm: SigningAlgorithm;
};
+export type TCmekGenerateMacResponse = {
+ mac: string;
+ keyId: string;
+ macAlgorithm: HmacAlgorithm;
+};
+
+export type TCmekVerifyMacResponse = {
+ macValid: boolean;
+ keyId: string;
+ macAlgorithm: HmacAlgorithm;
+};
+
export type TCmekDecryptResponse = {
plaintext: string;
};
@@ -103,7 +119,7 @@ export type TCmekBulkExportedKey = {
keyId: string;
name: string;
keyUsage: KmsKeyUsage;
- algorithm: AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm;
+ algorithm: AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm | HmacAlgorithm;
privateKey: string;
publicKey?: string;
};
@@ -115,7 +131,7 @@ export type TCmekBulkExportPrivateKeysResponse = {
export type TCmekBulkImportKeyEntry = {
name: string;
keyUsage: KmsKeyUsage;
- encryptionAlgorithm: AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm;
+ encryptionAlgorithm: AsymmetricKeyAlgorithm | SymmetricKeyAlgorithm | HmacAlgorithm;
keyMaterial: string;
isExportable?: boolean;
};
@@ -148,9 +164,18 @@ export enum SymmetricKeyAlgorithm {
AES_GCM_128 = "aes-128-gcm"
}
+export enum HmacAlgorithm {
+ HMAC_SHA_1 = "HMAC_SHA_1",
+ HMAC_SHA_224 = "HMAC_SHA_224",
+ HMAC_SHA_256 = "HMAC_SHA_256",
+ HMAC_SHA_384 = "HMAC_SHA_384",
+ HMAC_SHA_512 = "HMAC_SHA_512"
+}
+
export const AllowedEncryptionKeyAlgorithms = z.enum([
...Object.values(SymmetricKeyAlgorithm),
- ...Object.values(AsymmetricKeyAlgorithm)
+ ...Object.values(AsymmetricKeyAlgorithm),
+ ...Object.values(HmacAlgorithm)
] as [string, ...string[]]).options;
export enum SigningAlgorithm {
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekBulkImportModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekBulkImportModal.tsx
index 838b80ce39..d0951e96b7 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekBulkImportModal.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekBulkImportModal.tsx
@@ -37,6 +37,7 @@ import {
import { kmsKeyUsageOptions } from "@app/helpers/kms";
import {
AsymmetricKeyAlgorithm,
+ HmacAlgorithm,
KmsKeyUsage,
SymmetricKeyAlgorithm,
useBulkImportCmekKeys
@@ -44,7 +45,7 @@ import {
type ParsedKey = {
name: string;
- keyType: "encrypt-decrypt" | "sign-verify";
+ keyType: KmsKeyUsage;
algorithm: string;
keyMaterial?: string;
privateKey?: string;
@@ -52,6 +53,10 @@ type ParsedKey = {
isExportable?: boolean;
};
+// Imported HMAC keys may be any reasonable length per RFC 2104; mirrors the backend bounds.
+const MIN_HMAC_KEY_BYTE_LENGTH = 1;
+const MAX_HMAC_KEY_BYTE_LENGTH = 1024;
+
type ValidationError = {
index: number;
message: string;
@@ -102,10 +107,14 @@ const validateEntry = (entry: unknown, index: number): ValidationError | null =>
message: '"name" can only contain lowercase letters, numbers, and hyphens'
};
}
- if (e.keyType !== "encrypt-decrypt" && e.keyType !== "sign-verify") {
+ if (
+ e.keyType !== KmsKeyUsage.ENCRYPT_DECRYPT &&
+ e.keyType !== KmsKeyUsage.SIGN_VERIFY &&
+ e.keyType !== KmsKeyUsage.GENERATE_VERIFY_MAC
+ ) {
return {
index,
- message: '"keyType" must be "encrypt-decrypt" or "sign-verify"'
+ message: '"keyType" must be "encrypt-decrypt", "sign-verify" or "generate-verify-mac"'
};
}
if (!e.algorithm || typeof e.algorithm !== "string") {
@@ -114,7 +123,7 @@ const validateEntry = (entry: unknown, index: number): ValidationError | null =>
if (e.isExportable !== undefined && typeof e.isExportable !== "boolean") {
return { index, message: '"isExportable" must be a boolean' };
}
- if (e.keyType === "encrypt-decrypt") {
+ if (e.keyType === KmsKeyUsage.ENCRYPT_DECRYPT) {
const validSymmetric = Object.values(SymmetricKeyAlgorithm) as string[];
if (!validSymmetric.includes(e.algorithm)) {
return {
@@ -140,7 +149,7 @@ const validateEntry = (entry: unknown, index: number): ValidationError | null =>
};
}
}
- if (e.keyType === "sign-verify") {
+ if (e.keyType === KmsKeyUsage.SIGN_VERIFY) {
const validAsymmetric = Object.values(AsymmetricKeyAlgorithm) as string[];
if (!validAsymmetric.includes(e.algorithm)) {
return {
@@ -158,6 +167,35 @@ const validateEntry = (entry: unknown, index: number): ValidationError | null =>
return { index, message: '"privateKey" must be base64 encoded' };
}
}
+ if (e.keyType === KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ const validHmac = Object.values(HmacAlgorithm) as string[];
+ if (!validHmac.includes(e.algorithm)) {
+ return {
+ index,
+ message: `"algorithm" must be one of ${validHmac.join(", ")} for generate-verify-mac keys`
+ };
+ }
+ if (!e.keyMaterial || typeof e.keyMaterial !== "string") {
+ return {
+ index,
+ message: '"keyMaterial" is required for generate-verify-mac keys'
+ };
+ }
+ if (!isBase64(e.keyMaterial)) {
+ return { index, message: '"keyMaterial" must be base64 encoded' };
+ }
+ const actualLength = getBase64ByteLength(e.keyMaterial);
+ if (
+ actualLength === null ||
+ actualLength < MIN_HMAC_KEY_BYTE_LENGTH ||
+ actualLength > MAX_HMAC_KEY_BYTE_LENGTH
+ ) {
+ return {
+ index,
+ message: `"keyMaterial" must decode to between ${MIN_HMAC_KEY_BYTE_LENGTH} and ${MAX_HMAC_KEY_BYTE_LENGTH} bytes (got ${actualLength ?? "invalid"})`
+ };
+ }
+ }
return null;
};
@@ -241,9 +279,10 @@ export const CmekBulkImportModal = ({ isOpen, onOpenChange, projectId }: Props)
projectId,
keys: parsedKeys.map((k) => ({
name: k.name,
- keyUsage: k.keyType as KmsKeyUsage,
+ keyUsage: k.keyType,
encryptionAlgorithm: k.algorithm as never,
- keyMaterial: k.keyType === "sign-verify" ? (k.privateKey ?? "") : (k.keyMaterial ?? ""),
+ keyMaterial:
+ k.keyType === KmsKeyUsage.SIGN_VERIFY ? (k.privateKey ?? "") : (k.keyMaterial ?? ""),
isExportable: k.isExportable
}))
});
@@ -262,8 +301,11 @@ export const CmekBulkImportModal = ({ isOpen, onOpenChange, projectId }: Props)
}
};
- const encryptCount = parsedKeys?.filter((k) => k?.keyType === "encrypt-decrypt").length ?? 0;
- const signCount = parsedKeys?.filter((k) => k?.keyType === "sign-verify").length ?? 0;
+ const encryptCount =
+ parsedKeys?.filter((k) => k?.keyType === KmsKeyUsage.ENCRYPT_DECRYPT).length ?? 0;
+ const signCount = parsedKeys?.filter((k) => k?.keyType === KmsKeyUsage.SIGN_VERIFY).length ?? 0;
+ const macCount =
+ parsedKeys?.filter((k) => k?.keyType === KmsKeyUsage.GENERATE_VERIFY_MAC).length ?? 0;
const errorByIndex = new Map(validationErrors.map((err) => [err.index, err.message]));
const hasErrors = validationErrors.length > 0;
@@ -371,6 +413,15 @@ export const CmekBulkImportModal = ({ isOpen, onOpenChange, projectId }: Props)
"privateKey": "<base64>",
"publicKey": "<base64>",
"isExportable": true // optional, default: true
+}
+
+// Generate/Verify MAC (HMAC) key
+{
+ "name": "...",
+ "keyType": "generate-verify-mac",
+ "algorithm": "HMAC_SHA_256",
+ "keyMaterial": "<base64>",
+ "isExportable": true // optional, default: true
}`}</pre>
<p className="mt-2">
Set <code className="rounded bg-card px-1 py-0.5">isExportable</code> to{" "}
@@ -505,7 +556,7 @@ export const CmekBulkImportModal = ({ isOpen, onOpenChange, projectId }: Props)
if (parsedKeys) {
return {
title: "Review & Import Keys",
- description: `${parsedKeys.length} key${parsedKeys.length !== 1 ? "s" : ""} found — ${encryptCount} encrypt/decrypt, ${signCount} sign/verify.`
+ description: `${parsedKeys.length} key${parsedKeys.length !== 1 ? "s" : ""} found — ${encryptCount} encrypt/decrypt, ${signCount} sign/verify, ${macCount} generate/verify MAC.`
};
}
return {
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekGenerateMacModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekGenerateMacModal.tsx
new file mode 100644
index 0000000000..7bda5d5ba0
--- /dev/null
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekGenerateMacModal.tsx
@@ -0,0 +1,152 @@
+import { Controller, useForm } from "react-hook-form";
+import { faCheckCircle, faFileSignature, faInfoCircle } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ FormControl,
+ Modal,
+ ModalClose,
+ ModalContent,
+ Switch,
+ TextArea,
+ Tooltip
+} from "@app/components/v2";
+import { useTimedReset } from "@app/hooks";
+import { TCmek, useCmekGenerateMac } from "@app/hooks/api/cmeks";
+
+const formSchema = z.object({
+ data: z.string(),
+ isBase64Encoded: z.boolean()
+});
+
+export type FormData = z.infer<typeof formSchema>;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ cmek: TCmek;
+};
+
+type FormProps = Pick<Props, "cmek">;
+
+const GenerateMacForm = ({ cmek }: FormProps) => {
+ const cmekGenerateMac = useCmekGenerateMac();
+
+ const {
+ handleSubmit,
+ register,
+ control,
+ formState: { isSubmitting, errors }
+ } = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ isBase64Encoded: false
+ }
+ });
+
+ const [copyMac, isCopyingMac, setCopyMac] = useTimedReset<string>({
+ initialState: "Copy to Clipboard"
+ });
+
+ const handleGenerateMac = async (formData: FormData) => {
+ await cmekGenerateMac.mutateAsync({ ...formData, keyId: cmek.id });
+ createNotification({
+ text: "Successfully generated MAC",
+ type: "success"
+ });
+ };
+
+ const mac = cmekGenerateMac.data?.mac;
+
+ const handleCopyToClipboard = () => {
+ navigator.clipboard.writeText(mac ?? "");
+
+ setCopyMac("Copied to Clipboard");
+ };
+
+ return (
+ <form onSubmit={handleSubmit(handleGenerateMac)}>
+ {mac ? (
+ <FormControl label="Message Authentication Code">
+ <TextArea className="max-h-80 min-h-40 max-w-full min-w-full" isDisabled value={mac} />
+ </FormControl>
+ ) : (
+ <>
+ <FormControl
+ label="Data to Authenticate"
+ errorText={errors.data?.message}
+ isError={Boolean(errors.data)}
+ >
+ <TextArea {...register("data")} className="max-h-80 min-h-40 max-w-full min-w-full" />
+ </FormControl>
+
+ <div className="mb-6 flex w-full items-center justify-end gap-2">
+ <Controller
+ control={control}
+ name="isBase64Encoded"
+ render={({ field: { onChange, value } }) => (
+ <Switch id="encode-base-64" isChecked={value} onCheckedChange={onChange}>
+ Data is Base64 encoded{" "}
+ <Tooltip content="Toggle this switch on if your data is already Base64 encoded to avoid redundant encoding.">
+ <FontAwesomeIcon icon={faInfoCircle} className="text-mineshaft-400" />
+ </Tooltip>
+ </Switch>
+ )}
+ />
+ </div>
+ </>
+ )}
+ <div className="flex items-center">
+ <Button
+ className={`mr-4 ${mac ? "w-44" : ""}`}
+ size="sm"
+ leftIcon={
+ // eslint-disable-next-line no-nested-ternary
+ mac ? (
+ isCopyingMac ? (
+ <FontAwesomeIcon icon={faCheckCircle} />
+ ) : (
+ <FontAwesomeIcon icon={faFileSignature} />
+ )
+ ) : (
+ <FontAwesomeIcon icon={faFileSignature} />
+ )
+ }
+ onClick={mac ? handleCopyToClipboard : undefined}
+ type={mac ? "button" : "submit"}
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ {mac ? copyMac : "Generate MAC"}
+ </Button>
+ <ModalClose asChild>
+ <Button colorSchema="secondary" variant="plain">
+ {mac ? "Close" : "Cancel"}
+ </Button>
+ </ModalClose>
+ </div>
+ </form>
+ );
+};
+
+export const CmekGenerateMacModal = ({ isOpen, onOpenChange, cmek }: Props) => {
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent
+ title="Generate MAC"
+ subTitle={
+ <>
+ Generate a message authentication code using{" "}
+ <span className="font-bold">{cmek?.name}</span>. Returns a Base64 encoded MAC.
+ </>
+ }
+ >
+ <GenerateMacForm cmek={cmek} />
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx
index 7fe88e17d3..79fd19991b 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx
@@ -27,6 +27,7 @@ import { keyUsageDefaultOption, kmsKeyUsageOptions } from "@app/helpers/kms";
import {
AllowedEncryptionKeyAlgorithms,
AsymmetricKeyAlgorithm,
+ HmacAlgorithm,
KmsKeyUsage,
SymmetricKeyAlgorithm,
TCmek,
@@ -196,6 +197,11 @@ const CmekForm = ({ onComplete, cmek }: FormProps) => {
value as unknown as AsymmetricKeyAlgorithm
);
}
+ if (selectedKeyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ return Object.values(HmacAlgorithm).includes(
+ value as unknown as HmacAlgorithm
+ );
+ }
return false;
})
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
index fb81d2eb35..b27a5689e7 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
@@ -92,8 +92,10 @@ import { CmekBulkImportModal } from "./CmekBulkImportModal";
import { CmekDecryptModal } from "./CmekDecryptModal";
import { CmekEncryptModal } from "./CmekEncryptModal";
import { CmekExportKeyModal } from "./CmekExportKeyModal";
+import { CmekGenerateMacModal } from "./CmekGenerateMacModal";
import { CmekModal } from "./CmekModal";
import { CmekSignModal } from "./CmekSignModal";
+import { CmekVerifyMacModal } from "./CmekVerifyMacModal";
import { CmekVerifyModal } from "./CmekVerifyModal";
import { DeleteCmekModal } from "./DeleteCmekModal";
import { cmekKeysToExportJSON, downloadJSON } from "./jsonExport";
@@ -173,6 +175,8 @@ export const CmekTable = () => {
"decryptData",
"signData",
"verifyData",
+ "generateMac",
+ "verifyMac",
"exportKey",
"importKeys"
] as const);
@@ -244,6 +248,14 @@ export const CmekTable = () => {
ProjectPermissionCmekActions.Verify,
ProjectPermissionSub.Cmek
);
+ const cannotGenerateMac = permission.cannot(
+ ProjectPermissionCmekActions.GenerateMac,
+ ProjectPermissionSub.Cmek
+ );
+ const cannotVerifyMac = permission.cannot(
+ ProjectPermissionCmekActions.VerifyMac,
+ ProjectPermissionSub.Cmek
+ );
const cannotRotateKey = permission.cannot(
ProjectPermissionCmekActions.Rotate,
ProjectPermissionSub.Cmek
@@ -642,6 +654,24 @@ export const CmekTable = () => {
</DropdownMenuItem>
</>
)}
+ {keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC && (
+ <>
+ <DropdownMenuItem
+ onClick={() => handlePopUpOpen("generateMac", cmek)}
+ isDisabled={cannotGenerateMac || isDisabled}
+ >
+ <FileSignatureIcon className="mr-2 size-4" />
+ Generate MAC
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => handlePopUpOpen("verifyMac", cmek)}
+ isDisabled={cannotVerifyMac || isDisabled}
+ >
+ <CircleCheckIcon className="mr-2 size-4" />
+ Verify MAC
+ </DropdownMenuItem>
+ </>
+ )}
<DropdownMenuItem
onClick={() => handlePopUpOpen("exportKey", cmek)}
isDisabled={cannotExportKey || isDisabled}
@@ -746,6 +776,16 @@ export const CmekTable = () => {
onOpenChange={(isOpen) => handlePopUpToggle("verifyData", isOpen)}
cmek={popUp.verifyData.data as TCmek}
/>
+ <CmekGenerateMacModal
+ isOpen={popUp.generateMac.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("generateMac", isOpen)}
+ cmek={popUp.generateMac.data as TCmek}
+ />
+ <CmekVerifyMacModal
+ isOpen={popUp.verifyMac.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("verifyMac", isOpen)}
+ cmek={popUp.verifyMac.data as TCmek}
+ />
<CmekExportKeyModal
isOpen={popUp.exportKey.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("exportKey", isOpen)}
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekVerifyMacModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyMacModal.tsx
new file mode 100644
index 0000000000..7b27c966da
--- /dev/null
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyMacModal.tsx
@@ -0,0 +1,202 @@
+import { Controller, useForm } from "react-hook-form";
+import { faFileSignature, faInfoCircle } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import { decodeBase64 } from "@app/components/utilities/cryptography/crypto";
+import {
+ Button,
+ FormControl,
+ Modal,
+ ModalClose,
+ ModalContent,
+ Switch,
+ TextArea,
+ Tooltip
+} from "@app/components/v2";
+import { Badge } from "@app/components/v3";
+import { TCmek, useCmekVerifyMac } from "@app/hooks/api/cmeks";
+import { isBase64 } from "@app/lib/fn/base64";
+
+const formSchema = z.object({
+ data: z.string().min(1, { message: "Data cannot be empty" }),
+ mac: z
+ .string()
+ .min(1, { message: "MAC cannot be empty" })
+ .superRefine((val, ctx) => {
+ if (!isBase64(val)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "MAC must be base64-encoded"
+ });
+ }
+ }),
+ isBase64Encoded: z.boolean()
+});
+
+export type FormData = z.infer<typeof formSchema>;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ cmek: TCmek;
+};
+
+type FormProps = Pick<Props, "cmek">;
+
+const VerifyMacForm = ({ cmek }: FormProps) => {
+ const cmekVerifyMac = useCmekVerifyMac();
+
+ const {
+ handleSubmit,
+ register,
+ watch,
+ control,
+ formState: { isSubmitting, errors }
+ } = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: {
+ isBase64Encoded: false
+ }
+ });
+
+ const handleVerifyMac = async (formData: FormData) => {
+ const result = await cmekVerifyMac.mutateAsync({ ...formData, keyId: cmek.id });
+
+ if (result.macValid) {
+ createNotification({
+ text: "Successfully verified MAC",
+ type: "success"
+ });
+ } else {
+ createNotification({
+ title: "MAC Verification Failed",
+ text: "The MAC is invalid. It was not generated using the same key as the one used to verify it, or the data has been tampered with.",
+ type: "error"
+ });
+ }
+ };
+
+ const mac = watch("mac");
+ const data = watch("data");
+ const isBase64Encoded = watch("isBase64Encoded");
+
+ const macValid = cmekVerifyMac.data?.macValid;
+ const macAlgorithm = cmekVerifyMac.data?.macAlgorithm;
+
+ return (
+ <form onSubmit={handleSubmit(handleVerifyMac)}>
+ {macValid !== undefined ? (
+ <div className="mb-6 flex flex-col gap-2">
+ <div className="flex items-center justify-between space-x-2">
+ <span className="text-sm opacity-60">MAC Status:</span>
+ <Tooltip
+ content={
+ macValid
+ ? "The MAC is valid. It was generated using the same key as the one used to verify it."
+ : "The MAC is invalid. It was not generated using the same key as the one used to verify it, or the data has been tampered with."
+ }
+ >
+ <Badge variant={macValid ? "success" : "danger"}>
+ {macValid ? "Valid" : "Invalid"}
+ </Badge>
+ </Tooltip>
+ </div>
+
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-sm opacity-60">MAC Algorithm:</span>
+ <Badge variant="info">{macAlgorithm}</Badge>
+ </div>
+ <div className="mt-3">
+ <span className="text-sm opacity-60">MAC:</span>{" "}
+ <div className="rounded-md border border-mineshaft-700 bg-mineshaft-900 p-2 text-sm break-words whitespace-pre-wrap">
+ {mac}
+ </div>
+ </div>
+ <div>
+ <span className="text-sm opacity-60">Data:</span>{" "}
+ <div className="rounded-md border border-mineshaft-700 bg-mineshaft-900 p-2 text-sm">
+ {isBase64Encoded ? decodeBase64(data).toString() : data}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <>
+ <FormControl
+ label="Data to Verify"
+ errorText={errors.data?.message}
+ isError={Boolean(errors.data)}
+ >
+ <TextArea {...register("data")} className="max-h-80 min-h-40 max-w-full min-w-full" />
+ </FormControl>
+
+ <FormControl
+ label="Message Authentication Code"
+ tooltipText="Must be base64-encoded, like the MAC you received when you generated it."
+ errorText={errors.mac?.message}
+ isError={Boolean(errors.mac)}
+ >
+ <TextArea {...register("mac")} className="max-h-80 min-h-40 max-w-full min-w-full" />
+ </FormControl>
+
+ <div className="mb-6 flex w-full items-center justify-end gap-2">
+ <Controller
+ control={control}
+ name="isBase64Encoded"
+ render={({ field: { onChange, value } }) => (
+ <Switch id="encode-base-64" isChecked={value} onCheckedChange={onChange}>
+ Data is Base64 encoded{" "}
+ <Tooltip content="Toggle this switch on if your data is already Base64 encoded to avoid redundant encoding.">
+ <FontAwesomeIcon icon={faInfoCircle} className="text-mineshaft-400" />
+ </Tooltip>
+ </Switch>
+ )}
+ />
+ </div>
+ </>
+ )}
+ <div className="flex items-center">
+ {macValid === undefined && (
+ <Button
+ className="mr-4 w-44"
+ size="sm"
+ leftIcon={<FontAwesomeIcon icon={faFileSignature} />}
+ type="submit"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ Verify MAC
+ </Button>
+ )}
+ <ModalClose asChild>
+ <Button
+ colorSchema={macValid === undefined ? "secondary" : "primary"}
+ variant={macValid === undefined ? "plain" : undefined}
+ >
+ {macValid !== undefined ? "Close" : "Cancel"}
+ </Button>
+ </ModalClose>
+ </div>
+ </form>
+ );
+};
+
+export const CmekVerifyMacModal = ({ isOpen, onOpenChange, cmek }: Props) => {
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent
+ title="Verify MAC"
+ subTitle={
+ <>
+ Verify a message authentication code using{" "}
+ <span className="font-bold">{cmek?.name}</span>.
+ </>
+ }
+ >
+ <VerifyMacForm cmek={cmek} />
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/frontend/src/pages/kms/OverviewPage/components/jsonExport.ts b/frontend/src/pages/kms/OverviewPage/components/jsonExport.ts
index d6a4eb1819..b0bb2d178e 100644
--- a/frontend/src/pages/kms/OverviewPage/components/jsonExport.ts
+++ b/frontend/src/pages/kms/OverviewPage/components/jsonExport.ts
@@ -15,6 +15,12 @@ type CmekExportEntry =
algorithm: string;
privateKey: string;
publicKey: string;
+ }
+ | {
+ name: string;
+ keyType: "generate-verify-mac";
+ algorithm: string;
+ keyMaterial: string;
};
export const cmekKeysToExportJSON = (keys: TCmekBulkExportedKey[]): CmekExportEntry[] => {
@@ -29,6 +35,15 @@ export const cmekKeysToExportJSON = (keys: TCmekBulkExportedKey[]): CmekExportEn
};
}
+ if (key.keyUsage === KmsKeyUsage.GENERATE_VERIFY_MAC) {
+ return {
+ name: key.name,
+ keyType: "generate-verify-mac" as const,
+ algorithm: key.algorithm,
+ keyMaterial: key.privateKey
+ };
+ }
+
return {
name: key.name,
keyType: "encrypt-decrypt" as const,
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index aeac3caaf8..d00040e741 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -127,6 +127,8 @@ const CmekPolicyActionSchema = z.object({
[ProjectPermissionCmekActions.Decrypt]: z.boolean().optional(),
[ProjectPermissionCmekActions.Sign]: z.boolean().optional(),
[ProjectPermissionCmekActions.Verify]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.GenerateMac]: z.boolean().optional(),
+ [ProjectPermissionCmekActions.VerifyMac]: z.boolean().optional(),
[ProjectPermissionCmekActions.Rotate]: z.boolean().optional(),
[ProjectPermissionCmekActions.ExportPrivateKey]: z.boolean().optional()
});
@@ -1646,6 +1648,8 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
const canDecrypt = action.includes(ProjectPermissionCmekActions.Decrypt);
const canSign = action.includes(ProjectPermissionCmekActions.Sign);
const canVerify = action.includes(ProjectPermissionCmekActions.Verify);
+ const canGenerateMac = action.includes(ProjectPermissionCmekActions.GenerateMac);
+ const canVerifyMac = action.includes(ProjectPermissionCmekActions.VerifyMac);
const canRotate = action.includes(ProjectPermissionCmekActions.Rotate);
const canExportPrivateKey = action.includes(ProjectPermissionCmekActions.ExportPrivateKey);
@@ -1660,6 +1664,8 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
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 (canGenerateMac) formVal[subject]![0][ProjectPermissionCmekActions.GenerateMac] = true;
+ if (canVerifyMac) formVal[subject]![0][ProjectPermissionCmekActions.VerifyMac] = true;
if (canRotate) formVal[subject]![0][ProjectPermissionCmekActions.Rotate] = true;
if (canExportPrivateKey)
formVal[subject]![0][ProjectPermissionCmekActions.ExportPrivateKey] = true;
@@ -2214,6 +2220,16 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
value: ProjectPermissionCmekActions.Verify,
description: "Verify signatures using KMS keys"
},
+ {
+ label: "Generate MAC",
+ value: ProjectPermissionCmekActions.GenerateMac,
+ description: "Generate MACs using KMS keys"
+ },
+ {
+ label: "Verify MAC",
+ value: ProjectPermissionCmekActions.VerifyMac,
+ description: "Verify MACs using KMS keys"
+ },
{
label: "Rotate",
value: ProjectPermissionCmekActions.Rotate,