Skip to content

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

Address greptile comments

Carlos Monastyrski3b2c85d9dfb0
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 daca96a57e..fc91d2768e 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -3016,9 +3016,12 @@ interface RemoveGroupFromProjectEvent {
type TCaKeySourceAuditMetadata = {
keySource?: string;
hsmConnectorId?: string;
+ hsmConnectorName?: string;
+ hsmKeyLabel?: string;
appConnectionId?: string;
appConnectionName?: string;
externalKeyId?: string;
+ region?: string;
};
interface CreateCa {
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-coalescing.test.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-coalescing.test.ts
index a286d33453..39523f193f 100644
--- a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-coalescing.test.ts
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-coalescing.test.ts
@@ -5,7 +5,7 @@ import * as pkijs from "pkijs";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
-import { buildHsmCaSigner } from "@app/services/certificate-authority/ca-signer";
+import { buildHsmCaSigner, createEphemeralKeyCache } from "@app/services/certificate-authority/ca-signer";
import { OCSP_NONCE_OID } from "./certificate-authority-ocsp-enums";
@@ -76,7 +76,8 @@ const buildHarness = async () => {
signCount += 1;
await gate;
return Buffer.from(await webcrypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, keys.privateKey, tbs));
- }
+ },
+ ephemeralKeys: createEphemeralKeyCache()
});
getCaSignerMock.mockResolvedValue({ signer });
diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-hsm.test.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-hsm.test.ts
index 3b46ae7ae4..c63ab0f606 100644
--- a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-hsm.test.ts
+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-hsm.test.ts
@@ -6,7 +6,7 @@ import * as pkijs from "pkijs";
import { beforeAll, describe, expect, it } from "vitest";
import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
-import { buildHsmCaSigner } from "@app/services/certificate-authority/ca-signer";
+import { buildHsmCaSigner, createEphemeralKeyCache } from "@app/services/certificate-authority/ca-signer";
import { OcspCertStatus, OcspResponseStatus } from "./certificate-authority-ocsp-enums";
import { buildSignedOcspResponse, parseOcspRequest } from "./certificate-authority-ocsp-fns";
@@ -61,7 +61,8 @@ describe.each(CASES)("HSM-backed OCSP signing: $keyAlgorithm", (testCase) => {
const signer = buildHsmCaSigner({
caPublicKey: keys.publicKey,
keyAlgorithm: testCase.keyAlgorithm,
- sign: async (tbs) => Buffer.from(await webcrypto.subtle.sign(testCase.sign, keys.privateKey, tbs))
+ sign: async (tbs) => Buffer.from(await webcrypto.subtle.sign(testCase.sign, keys.privateKey, tbs)),
+ ephemeralKeys: createEphemeralKeyCache()
});
const request = new pkijs.OCSPRequest();
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index eb35e0874b..7e24ced0e4 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -2857,6 +2857,7 @@ export const CertificateAuthorities = {
appConnectionId:
"The ID of the AWS connection used to create the CA's signing key in AWS KMS and to sign with it. Required when keySource is 'aws-kms'.",
appConnectionName: "The name of the AWS connection the CA's signing key is reached through. Not user-supplied.",
+ hsmConnectorName: "The name of the HSM Connector the CA's signing key is reached through. Not user-supplied.",
region:
"The AWS region the CA's signing key is created in. Required when keySource is 'aws-kms', and returned when reading the CA.",
externalKeyId:
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index a79a8a4d86..b937ed2328 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3328,6 +3328,7 @@ export const registerRoutes = async (
const caKeySourceService = caKeySourceServiceFactory({
hsmConnectorService,
+ hsmConnectorDAL,
certificateAuthoritySecretDAL,
appConnectionDAL,
appConnectionService,
diff --git a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source-fns.ts b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source-fns.ts
index 887ca676f2..024bf77f9e 100644
--- a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source-fns.ts
+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source-fns.ts
@@ -85,17 +85,20 @@ const AWS_KMS_ERROR_MESSAGES: Record<string, string> = {
UnsupportedOperationException: "AWS KMS does not support this key algorithm in the selected region.",
UnrecognizedClientException: "AWS rejected the AWS connection's credentials. Check the connection and try again.",
InvalidSignatureException: "AWS rejected the AWS connection's credentials. Check the connection and try again.",
- ExpiredTokenException: "The AWS connection's credentials have expired. Check the connection and try again."
+ ExpiredTokenException: "The AWS connection's credentials have expired. Check the connection and try again.",
+ ThrottlingException: "AWS KMS is throttling requests. Try again shortly.",
+ KMSInternalException: "AWS KMS had an internal error. Try again shortly.",
+ DependencyTimeoutException: "AWS KMS timed out. Try again shortly."
};
export const toAwsKmsError = (error: unknown, operation: string): Error => {
if (error instanceof BadRequestError) return error;
- const { name, message } = error as { name?: string; message?: string };
+ const { name } = error as { name?: string };
logger.error(error, `AWS KMS ${operation} failed [errorName=${name}]`);
const known = name ? AWS_KMS_ERROR_MESSAGES[name] : undefined;
return new BadRequestError({
- message: `Failed to ${operation} in AWS KMS: ${known ?? message ?? "unknown error"}`
+ message: `Failed to ${operation} in AWS KMS: ${known ?? `AWS returned ${name ?? "an unexpected error"}.`}`
});
};
diff --git a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts
index 5a97d56974..58c09741e2 100644
--- a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts
+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts
@@ -1,4 +1,8 @@
+import { execFileSync } from "node:child_process";
import nodeCrypto, { KeyObject, webcrypto } from "node:crypto";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import {
CreateKeyCommand,
@@ -11,11 +15,15 @@ import { AsnConvert } from "@peculiar/asn1-schema";
import { Certificate } from "@peculiar/asn1-x509";
import * as x509 from "@peculiar/x509";
+import { ProjectType } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto/cryptography";
+import { initializePqcSupport } from "@app/lib/crypto/pqc";
+import { opensslDerivePublicKey, opensslGenpkey, verifyPqcOpenSSLAvailability } from "@app/lib/crypto/pqc/pqc-openssl";
import { SigningAlgorithm } from "@app/lib/crypto/sign/types";
import { wrapRsaPkcs1DigestInfo } from "@app/lib/csr/pkcs11-algorithm-map";
import { BadRequestError } from "@app/lib/errors";
import { AWSRegion } from "@app/services/app-connection/app-connection-enums";
+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";
import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
import { CertKeySource } from "@app/services/signer/signer-enums";
@@ -41,7 +49,36 @@ const KEY_ARN = "arn:aws:kms:us-east-1:111122223333:key/0b7fd7dd-bac6-4ef2-8790-
type TSignInput = { Message: Uint8Array; MessageType: string; SigningAlgorithm: string };
-const fakeKms = (keyPair: { publicKey: KeyObject; privateKey: KeyObject }) => {
+const PQC_OPENSSL_BIN = process.env.PQC_OPENSSL_BIN_PATH || "/opt/openssl-pqc/bin/openssl";
+const PQC_OPENSSL_LIB = process.env.PQC_OPENSSL_LIB_PATH || "/opt/openssl-pqc/lib64:/opt/openssl-pqc/lib";
+
+const opensslPkeySign = (privateKeyDer: Buffer, input: Buffer, pkeyOpts: string[] = []) => {
+ const dir = mkdtempSync(join(tmpdir(), "kms-fake-"));
+ try {
+ writeFileSync(join(dir, "key.der"), privateKeyDer);
+ writeFileSync(join(dir, "input.bin"), input);
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("OPENSSL_")));
+ return execFileSync(
+ PQC_OPENSSL_BIN,
+ [
+ "pkeyutl",
+ "-sign",
+ "-inkey",
+ join(dir, "key.der"),
+ "-keyform",
+ "DER",
+ "-in",
+ join(dir, "input.bin"),
+ ...pkeyOpts.flatMap((opt) => ["-pkeyopt", opt])
+ ],
+ { env: { ...env, LD_LIBRARY_PATH: [PQC_OPENSSL_LIB, process.env.LD_LIBRARY_PATH].filter(Boolean).join(":") } }
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+};
+
+const fakeKms = ({ publicKeySpki, sign }: { publicKeySpki: Buffer; sign: (input: TSignInput) => Buffer }) => {
const signCalls: TSignInput[] = [];
const createCalls: Record<string, unknown>[] = [];
@@ -51,26 +88,63 @@ const fakeKms = (keyPair: { publicKey: KeyObject; privateKey: KeyObject }) => {
return { KeyMetadata: { Arn: KEY_ARN } };
}
if (command instanceof GetPublicKeyCommand) {
- return { PublicKey: keyPair.publicKey.export({ format: "der", type: "spki" }) };
+ return { PublicKey: publicKeySpki };
}
if (command instanceof SignCommand) {
const input = command.input as TSignInput;
signCalls.push(input);
- if (input.SigningAlgorithm.startsWith("RSASSA_PKCS1")) {
- return {
- Signature: nodeCrypto.privateEncrypt(
- { key: keyPair.privateKey, padding: nodeCrypto.constants.RSA_PKCS1_PADDING },
- wrapRsaPkcs1DigestInfo(input.SigningAlgorithm as SigningAlgorithm, Buffer.from(input.Message))
- )
- };
- }
- return { Signature: Buffer.from("3006020101020101", "hex") };
+ return { Signature: sign(input) };
}
throw new Error("unexpected KMS command");
};
vi.spyOn(KMSClient.prototype, "send").mockImplementation(send as never);
- return { signCalls, createCalls };
+ return { signCalls, createCalls, publicKeySpki };
+};
+
+const spkiOf = (publicKey: KeyObject) => publicKey.export({ format: "der", type: "spki" });
+
+const rsaKms = () => {
+ const { publicKey, privateKey } = nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
+ return fakeKms({
+ publicKeySpki: spkiOf(publicKey),
+ sign: (input) =>
+ nodeCrypto.privateEncrypt(
+ { key: privateKey, padding: nodeCrypto.constants.RSA_PKCS1_PADDING },
+ wrapRsaPkcs1DigestInfo(input.SigningAlgorithm as SigningAlgorithm, Buffer.from(input.Message))
+ )
+ });
+};
+
+const ecdsaKms = (namedCurve: string) => {
+ const { publicKey, privateKey } = nodeCrypto.generateKeyPairSync("ec", { namedCurve });
+ const privateKeyDer = privateKey.export({ format: "der", type: "pkcs8" });
+ return fakeKms({
+ publicKeySpki: spkiOf(publicKey),
+ sign: (input) => opensslPkeySign(privateKeyDer, Buffer.from(input.Message))
+ });
+};
+
+const mlDsaKms = async (algorithm: string) => {
+ const privateKeyDer = await opensslGenpkey(algorithm);
+ return fakeKms({
+ publicKeySpki: await opensslDerivePublicKey(privateKeyDer),
+ sign: (input) => opensslPkeySign(privateKeyDer, Buffer.from(input.Message), ["mu:1"])
+ });
+};
+
+const opensslVerifySelfSigned = (certificate: x509.X509Certificate) => {
+ const dir = mkdtempSync(join(tmpdir(), "kms-verify-"));
+ try {
+ const certPath = join(dir, "cert.pem");
+ writeFileSync(certPath, certificate.toString("pem"));
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("OPENSSL_")));
+ return execFileSync(PQC_OPENSSL_BIN, ["verify", "-check_ss_sig", "-CAfile", certPath, certPath], {
+ env: { ...env, LD_LIBRARY_PATH: [PQC_OPENSSL_LIB, process.env.LD_LIBRARY_PATH].filter(Boolean).join(":") }
+ }).toString();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
};
const buildDeps = (plan: Record<string, unknown> = { pkiAwsKmsSigning: true }) => ({
@@ -80,6 +154,7 @@ const buildDeps = (plan: Record<string, unknown> = { pkiAwsKmsSigning: true }) =
projectDAL: { findById: vi.fn(async () => ({ id: "project", orgId: "org" })) } as never,
licenseService: { getPlan: vi.fn(async () => plan) } as never,
hsmConnectorService: {} as never,
+ hsmConnectorDAL: {} as never,
certificateAuthoritySecretDAL: { findOne: vi.fn() } as never
});
@@ -104,9 +179,12 @@ const createAndSignRoot = async (keyAlgorithm: CertKeyAlgorithm, signatureAlgori
};
describe("AWS KMS CA key source", () => {
+ let isOpensslAvailable = false;
+
beforeAll(async () => {
await crypto.initialize({} as never, {} as never, {} as never);
x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+ isOpensslAvailable = await verifyPqcOpenSSLAvailability();
});
afterEach(() => {
@@ -114,21 +192,20 @@ describe("AWS KMS CA key source", () => {
});
test("creates a sign/verify key and stores only its reference", async () => {
- const keyPair = nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
- const { createCalls } = fakeKms(keyPair);
+ const { createCalls, publicKeySpki } = rsaKms();
const { reference } = await createAndSignRoot(CertKeyAlgorithm.RSA_2048);
expect(createCalls[0]).toMatchObject({ KeySpec: "RSA_2048", KeyUsage: "SIGN_VERIFY" });
- expect(reference).toEqual({
- appConnectionId: "conn",
- externalKeyId: KEY_ARN,
- publicKeySpki: keyPair.publicKey.export({ format: "der", type: "spki" })
- });
+ expect(reference).toEqual({ appConnectionId: "conn", externalKeyId: KEY_ARN, publicKeySpki });
+ expect(getAwsConnectionConfig).toHaveBeenCalledWith(
+ expect.objectContaining({ projectType: ProjectType.CertificateManager }),
+ AWSRegion.US_EAST_1
+ );
});
test("RSA certificates and CRLs signed through KMS verify against the KMS public key", async () => {
- const { signCalls } = fakeKms(nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }));
+ const { signCalls } = rsaKms();
const { signer, certificate } = await createAndSignRoot(CertKeyAlgorithm.RSA_2048);
const crl = await signer.createCrl({ issuer: "CN=Root CA", thisUpdate: new Date(), entries: [] });
@@ -140,7 +217,7 @@ describe("AWS KMS CA key source", () => {
});
test("RSA honours a SHA-384 signature algorithm override", async () => {
- const { signCalls } = fakeKms(nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }));
+ const { signCalls } = rsaKms();
const { certificate } = await createAndSignRoot(CertKeyAlgorithm.RSA_2048, {
name: "RSASSA-PKCS1-v1_5",
@@ -152,10 +229,12 @@ describe("AWS KMS CA key source", () => {
expect(await certificate.verify({ signatureOnly: true })).toBe(true);
});
- test("ECDSA sends the curve's digest of the TBS certificate", async () => {
- const { signCalls } = fakeKms(nodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-384" }));
+ test("ECDSA certificates and CRLs signed through KMS verify against the KMS public key", async ({ skip }) => {
+ if (!isOpensslAvailable) skip();
+ const { signCalls } = ecdsaKms("P-384");
- const { certificate } = await createAndSignRoot(CertKeyAlgorithm.ECDSA_P384);
+ const { signer, certificate } = await createAndSignRoot(CertKeyAlgorithm.ECDSA_P384);
+ const crl = await signer.createCrl({ issuer: "CN=Root CA", thisUpdate: new Date(), entries: [] });
const tbs = Buffer.from(AsnConvert.serialize(AsnConvert.parse(certificate.rawData, Certificate).tbsCertificate));
expect(signCalls[0].SigningAlgorithm).toBe("ECDSA_SHA_384");
@@ -163,10 +242,63 @@ describe("AWS KMS CA key source", () => {
nodeCrypto.createHash("sha384").update(tbs).digest()
);
expect(certificate.signatureAlgorithm).toMatchObject({ name: "ECDSA", hash: { name: "SHA-384" } });
+ expect(await certificate.verify({ publicKey: signer.caPublicKey, signatureOnly: true })).toBe(true);
+ expect(await crl.verify({ publicKey: signer.caPublicKey })).toBe(true);
+ });
+
+ test("ML-DSA certificates signed through KMS with EXTERNAL_MU verify against the KMS public key", async ({
+ skip
+ }) => {
+ if (!isOpensslAvailable) skip();
+ await initializePqcSupport();
+ try {
+ const { signCalls } = await mlDsaKms("ML-DSA-65");
+
+ const { certificate } = await createAndSignRoot(CertKeyAlgorithm.ML_DSA_65);
+
+ expect(signCalls[0]).toMatchObject({ MessageType: "EXTERNAL_MU", SigningAlgorithm: "ML_DSA_SHAKE_256" });
+ expect(opensslVerifySelfSigned(certificate)).toContain("OK");
+ } finally {
+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);
+ }
+ });
+
+ test("reuses one throwaway key per algorithm instead of generating one per signature", async () => {
+ rsaKms();
+ const generateKey = vi.spyOn(crypto.nativeCrypto.subtle, "generateKey");
+ const provider = awsKmsCaKeySourceFactory(buildDeps());
+ const reference = await provider.createKey({
+ projectId: "project",
+ caName: "root-ca",
+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,
+ input: { appConnectionId: "conn", region: AWSRegion.US_EAST_1 }
+ });
+
+ for (let i = 0; i < 3; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const signer = await provider.buildSigner({
+ projectId: "project",
+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,
+ reference
+ });
+ // eslint-disable-next-line no-await-in-loop
+ const certificate = await signer.createCertificate({
+ subject: "CN=Root CA",
+ issuer: "CN=Root CA",
+ serialNumber: `0${i + 1}`,
+ notBefore: new Date(),
+ notAfter: new Date(Date.now() + 86_400_000),
+ publicKey: signer.caPublicKey
+ });
+ // eslint-disable-next-line no-await-in-loop
+ expect(await certificate.verify({ publicKey: signer.caPublicKey, signatureOnly: true })).toBe(true);
+ }
+
+ expect(generateKey).toHaveBeenCalledTimes(1);
});
test("ECDSA rejects a hash AWS KMS cannot use with the curve", async () => {
- fakeKms(nodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }));
+ ecdsaKms("P-256");
await expect(
createAndSignRoot(CertKeyAlgorithm.ECDSA_P256, { name: "ECDSA", hash: "SHA-384" } as Algorithm)
@@ -174,7 +306,7 @@ describe("AWS KMS CA key source", () => {
});
test("refuses to create a key without the AWS KMS signing entitlement", async () => {
- fakeKms(nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }));
+ rsaKms();
const provider = awsKmsCaKeySourceFactory(buildDeps({ pkiAwsKmsSigning: false }));
await expect(
diff --git a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts
index 018c5a01ce..fd1ff9cf75 100644
--- a/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts
+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts
@@ -11,6 +11,7 @@ import {
import { AsnConvert } from "@peculiar/asn1-schema";
import { SubjectPublicKeyInfo } from "@peculiar/asn1-x509";
+import { ProjectType } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { CustomAWSHasher } from "@app/lib/aws/hashing";
import { crypto } from "@app/lib/crypto/cryptography";
@@ -29,7 +30,7 @@ import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { algorithmHashName, buildExternalCaSigner } from "../ca-signer";
+import { algorithmHashName, buildExternalCaSigner, createEphemeralKeyCache } from "../ca-signer";
import { keyAlgorithmToAlgCfg } from "../certificate-authority-fns";
import {
AWS_KMS_KEY_SPEC_BY_ALGORITHM,
@@ -66,6 +67,8 @@ export const awsKmsCaKeySourceFactory = ({
projectDAL,
licenseService
}: TAwsKmsCaKeySourceDep): TExternalCaKeyProvider => {
+ const ephemeralKeys = createEphemeralKeyCache();
+
const $getKmsClient = async (appConnectionId: string, region: string) => {
const appConnection = await appConnectionDAL.findById(appConnectionId);
if (!appConnection) {
@@ -76,7 +79,10 @@ export const awsKmsCaKeySourceFactory = ({
}
const decryptedConnection = (await decryptAppConnection(appConnection, kmsService)) as TAwsConnection;
- const awsConfig = await getAwsConnectionConfig(decryptedConnection, region as AWSRegion);
+ const awsConfig = await getAwsConnectionConfig(
+ { ...decryptedConnection, projectType: ProjectType.CertificateManager },
+ region as AWSRegion
+ );
return new KMSClient({
sha256: CustomAWSHasher,
@@ -195,7 +201,9 @@ export const awsKmsCaKeySourceFactory = ({
caPublicKey,
signingAlgorithm: keyAlgCfg,
generateEphemeralKey: () =>
- pqcCrypto.subtle.generateKey(keyAlgCfg as RsaHashedKeyGenParams, true, ["sign", "verify"]),
+ ephemeralKeys(keyAlgCfg, () =>
+ pqcCrypto.subtle.generateKey(keyAlgCfg as RsaHashedKeyGenParams, true, ["sign", "verify"])
+ ),
signTbs: (tbs) =>
sign(
computeMlDsaExternalMu(rawPublicKey, tbs),
@@ -218,7 +226,9 @@ export const awsKmsCaKeySourceFactory = ({
caPublicKey,
signingAlgorithm: certSigningAlgorithm,
generateEphemeralKey: () =>
- crypto.nativeCrypto.subtle.generateKey(ephemeralKeyParams, true, ["sign", "verify"]),
+ ephemeralKeys(ephemeralKeyParams, () =>
+ crypto.nativeCrypto.subtle.generateKey(ephemeralKeyParams, true, ["sign", "verify"])
+ ),
signTbs: (tbs) =>
sign(crypto.nativeCrypto.createHash(nodeHash).update(tbs).digest(), MessageType.DIGEST, signingAlgorithmSpec)
});
diff --git a/backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.ts b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.ts
index e353a24028..b3adced78c 100644
--- a/backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.ts
+++ b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.ts
@@ -21,6 +21,7 @@ export type TExternalCaKeyReference = Pick<
export type TCaKeyDetails = {
hsmConnectorId?: string;
+ hsmConnectorName?: string;
hsmKeyLabel?: string;
appConnectionId?: string;
appConnectionName?: string;
diff --git a/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts
index 4a7260bdb7..a4d24a49a9 100644
--- a/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts
+++ b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts
@@ -2,13 +2,15 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
+import { THsmConnectorDALFactory } from "@app/services/hsm-connector/hsm-connector-dal";
import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
-import { buildHsmCaSigner, caKeyAlgorithmToHsmShape } from "../ca-signer";
+import { buildHsmCaSigner, caKeyAlgorithmToHsmShape, createEphemeralKeyCache } from "../ca-signer";
import { TExternalCaKeyInput, TExternalCaKeyProvider } from "./ca-key-source-types";
type THsmCaKeySourceDep = {
hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "assertAttachPermission">;
+ hsmConnectorDAL: Pick<THsmConnectorDALFactory, "findById">;
};
const requireHsmConnectorId = (input: TExternalCaKeyInput) => {
@@ -18,66 +20,82 @@ const requireHsmConnectorId = (input: TExternalCaKeyInput) => {
return input.hsmConnectorId;
};
-export const hsmCaKeySourceFactory = ({ hsmConnectorService }: THsmCaKeySourceDep): TExternalCaKeyProvider => ({
- displayName: "HSM",
- supportedKeyAlgorithms: [
- CertKeyAlgorithm.RSA_2048,
- CertKeyAlgorithm.RSA_4096,
- CertKeyAlgorithm.ECDSA_P256,
- CertKeyAlgorithm.ECDSA_P384
- ],
+export const hsmCaKeySourceFactory = ({
+ hsmConnectorService,
+ hsmConnectorDAL
+}: THsmCaKeySourceDep): TExternalCaKeyProvider => {
+ const ephemeralKeys = createEphemeralKeyCache();
- assertCanUse: async ({ actor, projectId, input }) => {
- await hsmConnectorService.assertAttachPermission(actor, requireHsmConnectorId(input), projectId);
- },
+ return {
+ displayName: "HSM",
+ supportedKeyAlgorithms: [
+ CertKeyAlgorithm.RSA_2048,
+ CertKeyAlgorithm.RSA_4096,
+ CertKeyAlgorithm.ECDSA_P256,
+ CertKeyAlgorithm.ECDSA_P384
+ ],
- createKey: async ({ projectId, caName, keyAlgorithm, input }) => {
- const hsmConnectorId = requireHsmConnectorId(input);
- const generated = await hsmConnectorService.generateKeyPair({
- connectorId: hsmConnectorId,
- projectId,
- keyLabel: `ca-${caName}-${alphaNumericNanoId(5)}`,
- keyAlgorithm: caKeyAlgorithmToHsmShape(keyAlgorithm).hsmKeyAlgorithm
- });
- return {
- hsmConnectorId,
- externalKeyId: generated.keyLabel,
- publicKeySpki: generated.publicKeySpkiDer
- };
- },
+ assertCanUse: async ({ actor, projectId, input }) => {
+ await hsmConnectorService.assertAttachPermission(actor, requireHsmConnectorId(input), projectId);
+ },
- describeKey: async ({ reference }) => ({
- hsmConnectorId: reference.hsmConnectorId ?? undefined,
- hsmKeyLabel: reference.externalKeyId ?? undefined
- }),
+ createKey: async ({ projectId, caName, keyAlgorithm, input }) => {
+ const hsmConnectorId = requireHsmConnectorId(input);
+ const generated = await hsmConnectorService.generateKeyPair({
+ connectorId: hsmConnectorId,
+ projectId,
+ keyLabel: `ca-${caName}-${alphaNumericNanoId(5)}`,
+ keyAlgorithm: caKeyAlgorithmToHsmShape(keyAlgorithm).hsmKeyAlgorithm
+ });
+ return {
+ hsmConnectorId,
+ externalKeyId: generated.keyLabel,
+ publicKeySpki: generated.publicKeySpkiDer
+ };
+ },
- buildSigner: async ({ projectId, keyAlgorithm, reference, signatureAlgorithm }) => {
- const { hsmConnectorId, externalKeyId: keyLabel, publicKeySpki } = reference;
- if (!hsmConnectorId || !keyLabel || !publicKeySpki) {
- throw new BadRequestError({ message: "HSM-backed CA secret is missing its connector, key label, or public key" });
- }
+ describeKey: async ({ reference }) => {
+ const hsmConnector = reference.hsmConnectorId
+ ? await hsmConnectorDAL.findById(reference.hsmConnectorId)
+ : undefined;
+ return {
+ hsmConnectorId: reference.hsmConnectorId ?? undefined,
+ hsmConnectorName: hsmConnector?.name,
+ hsmKeyLabel: reference.externalKeyId ?? undefined
+ };
+ },
- const caPublicKey = await crypto.nativeCrypto.subtle.importKey(
- "spki",
- publicKeySpki,
- caKeyAlgorithmToHsmShape(keyAlgorithm).importParams,
- true,
- ["verify"]
- );
+ buildSigner: async ({ projectId, keyAlgorithm, reference, signatureAlgorithm }) => {
+ const { hsmConnectorId, externalKeyId: keyLabel, publicKeySpki } = reference;
+ if (!hsmConnectorId || !keyLabel || !publicKeySpki) {
+ throw new BadRequestError({
+ message: "HSM-backed CA secret is missing its connector, key label, or public key"
+ });
+ }
- return buildHsmCaSigner({
- caPublicKey,
- keyAlgorithm,
- signingAlgorithm: signatureAlgorithm,
- sign: (data, mechanism, isDigest) =>
- hsmConnectorService.sign({
- connectorId: hsmConnectorId,
- projectId,
- keyLabel,
- mechanism,
- data,
- isDigest
- })
- });
- }
-});
+ const caPublicKey = await crypto.nativeCrypto.subtle.importKey(
+ "spki",
+ publicKeySpki,
+ caKeyAlgorithmToHsmShape(keyAlgorithm).importParams,
+ true,
+ ["verify"]
+ );
+
+ return buildHsmCaSigner({
+ caPublicKey,
+ keyAlgorithm,
+ signingAlgorithm: signatureAlgorithm,
+ sign: (data, mechanism, isDigest) =>
+ hsmConnectorService.sign({
+ connectorId: hsmConnectorId,
+ projectId,
+ keyLabel,
+ mechanism,
+ data,
+ isDigest
+ }),
+ ephemeralKeys
+ });
+ }
+ };
+};
diff --git a/backend/src/services/certificate-authority/ca-signer.ts b/backend/src/services/certificate-authority/ca-signer.ts
index 8f4493bc72..7d747dd1a6 100644
--- a/backend/src/services/certificate-authority/ca-signer.ts
+++ b/backend/src/services/certificate-authority/ca-signer.ts
@@ -142,6 +142,25 @@ const HSM_MECHANISM_BY_HASH: Record<"rsa" | "ecdsa", Record<string, string>> = {
}
};
+export type TEphemeralKeyCache = (
+ keyGenParams: Algorithm,
+ generate: () => Promise<CryptoKeyPair>
+) => Promise<CryptoKeyPair>;
+
+export const createEphemeralKeyCache = (): TEphemeralKeyCache => {
+ const keyPairs = new Map<string, Promise<CryptoKeyPair>>();
+ return (keyGenParams, generate) => {
+ const cacheKey = JSON.stringify(keyGenParams);
+ const cached = keyPairs.get(cacheKey);
+ if (cached) return cached;
+
+ const keyPair = generate();
+ keyPairs.set(cacheKey, keyPair);
+ keyPair.catch(() => keyPairs.delete(cacheKey));
+ return keyPair;
+ };
+};
+
export const algorithmHashName = (alg: Algorithm): string | undefined => {
const { hash } = alg as { hash?: string | { name?: string } };
return typeof hash === "string" ? hash : hash?.name;
@@ -200,12 +219,14 @@ export const buildHsmCaSigner = ({
caPublicKey,
keyAlgorithm,
signingAlgorithm,
- sign
+ sign,
+ ephemeralKeys
}: {
caPublicKey: CryptoKey;
keyAlgorithm: CertKeyAlgorithm | string;
signingAlgorithm?: Algorithm;
sign: TCaExternalSignFn;
+ ephemeralKeys: TEphemeralKeyCache;
}): TCaSigner => {
const shape = caKeyAlgorithmToHsmShape(keyAlgorithm);
@@ -241,7 +262,9 @@ export const buildHsmCaSigner = ({
caPublicKey,
signingAlgorithm: certSigningAlgorithm,
generateEphemeralKey: () =>
- crypto.nativeCrypto.subtle.generateKey(keyGenParams as RsaHashedKeyGenParams, true, ["sign", "verify"]),
+ ephemeralKeys(keyGenParams, () =>
+ crypto.nativeCrypto.subtle.generateKey(keyGenParams as RsaHashedKeyGenParams, true, ["sign", "verify"])
+ ),
signTbs
});
};
diff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.ts
index e1b3013010..03997bc7be 100644
--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts
@@ -6,6 +6,7 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { derivePublicKeyFromSecret, getPqcCrypto, isPqcAlgorithm, PqcCryptoKey } from "@app/lib/crypto/pqc";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { pick } from "@app/lib/fn";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { CertKeyAlgorithm, CertStatus } from "../certificate/certificate-types";
@@ -727,11 +728,19 @@ export const rethrowCaDeleteError = (error: unknown): never => {
throw error;
};
-export const getCaKeySourceAuditMetadata = (configuration: unknown) => {
- const { keySource, hsmConnectorId, hsmKeyLabel, appConnectionId, appConnectionName, externalKeyId } =
- (configuration ?? {}) as TCaKeyDetails & { keySource?: string };
- return { keySource, hsmConnectorId, appConnectionId, appConnectionName, externalKeyId: externalKeyId ?? hsmKeyLabel };
-};
+const CA_KEY_SOURCE_AUDIT_FIELDS = [
+ "keySource",
+ "hsmConnectorId",
+ "hsmConnectorName",
+ "hsmKeyLabel",
+ "appConnectionId",
+ "appConnectionName",
+ "externalKeyId",
+ "region"
+] as const;
+
+export const getCaKeySourceAuditMetadata = (configuration: unknown) =>
+ pick((configuration ?? {}) as TCaKeyDetails & { keySource?: string }, [...CA_KEY_SOURCE_AUDIT_FIELDS]);
export const deleteCaAndReleaseExternalKey = async ({
caId,
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
index 8de030dc29..dfa83c04f7 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-schemas.ts
@@ -35,6 +35,7 @@ type TInternalCertificateAuthorityConfiguration = {
hsmKeyLabel?: string;
appConnectionId?: string;
appConnectionName?: string;
+ hsmConnectorName?: string;
region?: AWSRegion;
externalKeyId?: string;
dn?: string | null;
@@ -83,6 +84,7 @@ export const InternalCertificateAuthorityConfigurationSchema = z
.optional()
.describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.appConnectionId),
appConnectionName: z.string().optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.appConnectionName),
+ hsmConnectorName: z.string().optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.hsmConnectorName),
region: z.nativeEnum(AWSRegion).optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.region),
externalKeyId: z.string().optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.externalKeyId),
dn: z.string().trim().max(PKI_TEXT_COLUMN_MAX_LENGTH).nullish(),
@@ -130,11 +132,15 @@ export const CreateInternalCertificateAuthoritySchema = GenericCreateCertificate
.extend({
configuration: InternalCertificateAuthorityConfigurationSchema
})
- .refine(({ configuration }) => !configuration.externalKeyId && !configuration.appConnectionName, {
- message:
- "externalKeyId and appConnectionName are read-only and cannot be set when creating a certificate authority",
- path: ["configuration"]
- });
+ .refine(
+ ({ configuration }) =>
+ !configuration.externalKeyId && !configuration.appConnectionName && !configuration.hsmConnectorName,
+ {
+ message:
+ "externalKeyId, appConnectionName and hsmConnectorName are read-only and cannot be set when creating a certificate authority",
+ path: ["configuration"]
+ }
+ );
export const UpdateInternalCertificateAuthorityConfigurationSchema = z.object({
crlDistributionPointUrls: distributionPointUrlsSchema
diff --git a/frontend/src/components/license/UpgradeGate/index.ts b/frontend/src/components/license/UpgradeGate/index.ts
index 8f5fe8e1c5..244146e453 100644
--- a/frontend/src/components/license/UpgradeGate/index.ts
+++ b/frontend/src/components/license/UpgradeGate/index.ts
@@ -29,6 +29,7 @@ export {
export { hasEnvironmentCapacity } from "./environment-limit";
export type { UpgradeIntent } from "./upgrade-intents";
export {
+ AwsKmsCaSigningUpgradeIntent,
BillingPlan,
BillingProduct,
buildUpgradeReturnPath,
diff --git a/frontend/src/components/license/UpgradeGate/upgrade-intents.ts b/frontend/src/components/license/UpgradeGate/upgrade-intents.ts
index 70fe3d88a0..b973ffa64f 100644
--- a/frontend/src/components/license/UpgradeGate/upgrade-intents.ts
+++ b/frontend/src/components/license/UpgradeGate/upgrade-intents.ts
@@ -36,6 +36,7 @@ export const UpgradeFeature = {
CertificateAuthorities: "certificate-authorities",
ExternalCertificateAuthorities: "external-certificate-authorities",
PostQuantumCertificates: "post-quantum-certificates",
+ AwsKmsCaSigning: "aws-kms-ca-signing",
CertificateIssuanceLimits: "certificate-issuance-limits",
Pam: "pam",
PamAccountLimit: "pam-account-limit",
@@ -301,6 +302,16 @@ export const PostQuantumCertificatesUpgradeIntent = {
"Post-quantum certificate algorithms are included with the Enterprise plan. Review the plan to continue."
} satisfies UpgradeIntent;
+export const AwsKmsCaSigningUpgradeIntent = {
+ featureKey: UpgradeFeature.AwsKmsCaSigning,
+ productKey: BillingProduct.CertificateManagement,
+ planKey: BillingPlan.Enterprise,
+ upgradeLabel: "Unlock AWS KMS Signing Keys",
+ title: "Keep CA Keys in AWS KMS",
+ description:
+ "Keeping certificate authority signing keys in AWS KMS is included with the Enterprise plan. Review the plan to continue."
+} satisfies UpgradeIntent;
+
export const CertificateIssuanceLimitsUpgradeIntent = {
featureKey: UpgradeFeature.CertificateIssuanceLimits,
productKey: BillingProduct.CertificateManagement,
diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.ts
index d6b166b728..7b91b2f501 100644
--- a/frontend/src/hooks/api/ca/types.ts
+++ b/frontend/src/hooks/api/ca/types.ts
@@ -159,6 +159,7 @@ export type TInternalCertificateAuthority = {
keyAlgorithm: CertKeyAlgorithm;
keySource?: CertKeySource;
hsmConnectorId?: string;
+ hsmConnectorName?: string;
hsmKeyLabel?: string;
appConnectionId?: string;
appConnectionName?: string;
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
index dc0ad1404d..ffd6446923 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
@@ -60,7 +60,6 @@ import { caStatusToNameMap, caTypeToNameMap } from "@app/hooks/api/ca/constants"
import { caKeys } from "@app/hooks/api/ca/queries";
import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";
import { certKeyAlgorithmToNameMap } from "@app/hooks/api/certificates/constants";
-import { useGetHsmConnectorById } from "@app/hooks/api/hsmConnectors";
import { CertKeySource } from "@app/hooks/api/signers";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -124,9 +123,6 @@ export const CaDetailsSection = ({ caId }: Props) => {
const parentCa = parentCaData as TInternalCertificateAuthority | undefined;
const isHsmBacked = ca?.configuration?.keySource === CertKeySource.Hsm;
- const { data: hsmConnector } = useGetHsmConnectorById(ca?.configuration?.hsmConnectorId, {
- enabled: Boolean(isHsmBacked && ca?.configuration?.hsmConnectorId)
- });
const isAwsKmsBacked = ca?.configuration?.keySource === CertKeySource.AwsKms;
@@ -319,7 +315,7 @@ export const CaDetailsSection = ({ caId }: Props) => {
<Detail>
<DetailLabel>HSM Connector</DetailLabel>
<DetailValue className="break-all">
- {hsmConnector?.name ?? ca.configuration.hsmConnectorId ?? "-"}
+ {ca.configuration.hsmConnectorName ?? ca.configuration.hsmConnectorId ?? "-"}
</DetailValue>
</Detail>
{ca.configuration.hsmKeyLabel && (
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx
index 6eaad180c3..81d3c36cd5 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx
@@ -2,6 +2,7 @@ import { Controller, UseFormReturn } from "react-hook-form";
import { Link } from "@tanstack/react-router";
import {
+ AwsKmsCaSigningUpgradeIntent,
PostQuantumCertificatesUpgradeIntent,
useUpgradeGate
} from "@app/components/license/UpgradeGate";
@@ -94,6 +95,13 @@ export const KeyValidityStep = ({
<Select
value={field.value}
onValueChange={(value) => {
+ if (value === CertKeySource.AwsKms && !isAwsKmsLicensed) {
+ openUpgradeGate({
+ intent: AwsKmsCaSigningUpgradeIntent,
+ paywallKey: "cert-manager.ca-key-source"
+ });
+ return;
+ }
field.onChange(value);
if (
!isKeyAlgorithmSupportedByKeySource(
@@ -121,7 +129,7 @@ export const KeyValidityStep = ({
)}
</div>
</SelectItem>
- <SelectItem value={CertKeySource.AwsKms} disabled={!isAwsKmsLicensed}>
+ <SelectItem value={CertKeySource.AwsKms}>
<div className="flex items-center gap-2">
AWS KMS
{!isAwsKmsLicensed && <Badge variant="info">Enterprise</Badge>}