Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pki): add AWS KMS-backed signing keys for internal CAs
Carlos Monastyrski1479af3a75af
diff --git a/.infisicalignore b/.infisicalignoreindex 1726719b5d..05cb31218c 100644--- a/.infisicalignore+++ b/.infisicalignore@@ -72,3 +72,4 @@ backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts:generic-api-key:216backend/src/ee/services/audit-log-stream/splunk/splunk-provider-schemas.test.ts:generic-api-key:7frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts:generic-api-key:161docs/documentation/platform/secret-scanning/scan-locally.mdx:generic-api-key:65+docs/documentation/platform/pki/ca/private-ca.mdx:generic-api-key:334diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex bf77f81112..eab8edbd42 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -1018,6 +1018,29 @@ and nothing on our side errors. `TCaSigner` (`services/certificate-authority/ca-`signTbs` for this and abstracts over software, HSM and PQC CAs. PQC needs no special case beyond takingthe signature OID from `pqcNameToOid`.+### Internal CA key sources++An internal CA's signing key lives in Infisical (`keySource: infisical`, encrypted private key) or+outside it. Every external source (HSM, AWS KMS) is a provider in+`services/certificate-authority/ca-key-source/`, registered in `caKeySourceServiceFactory`, and+implements four things: `supportedKeyAlgorithms`, `assertCanUse` (permission to use the connection),+`createKey` (entitlement check, then key creation; returns the columns to store) and `buildSigner` (returns a `TCaSigner`, usually through+`buildExternalCaSigner`, which swaps a remote signature into structures built with a throwaway key).+CA creation and `getCaSigner` branch only on Infisical versus external, so adding a source means a+provider, a `CertKeySource` value, an arm in `certificate_authority_secret_key_source_chk`, and the+wizard option. Every external source stores its key in the generic `externalKeyId` and+`publicKeySpki` columns, and cloud KMS sources reach the key through `appConnectionId` (HSM through+`hsmConnectorId`). Each provider's `describeKey` builds the key fields of the CA read response and+the CA create and delete audit events, which is how the API still exposes an HSM CA's+`externalKeyId` as `hsmKeyLabel`.+Releasing a key is two-phase, through `prepareKeyReleases`. The provider's optional+`prepareKeyRelease` resolves what it needs (AWS KMS decrypts the connection and builds its client)+before the CA rows are deleted, and the returned function runs after the delete commits. The order+matters: a project hard delete cascades away project-scoped connections and the project KMS key in+the same transaction. Keys are released on CA delete, on project hard delete, and when CA creation+fails after its key was made. AWS KMS schedules deletion with a 30-day window; HSM keeps its key. A+failure is logged, never thrown, so the original outcome stands.+### Enterprise (EE) FeaturesEnterprise code lives in `src/ee/`:diff --git a/backend/src/db/migrations/20261012152847_ca-secret-external-key.ts b/backend/src/db/migrations/20261012152847_ca-secret-external-key.tsnew file mode 100644index 0000000000..b168d582a2--- /dev/null+++ b/backend/src/db/migrations/20261012152847_ca-secret-external-key.ts@@ -0,0 +1,64 @@+import { Knex } from "knex";++import { TableName } from "@app/db/schemas";++const CA_SECRET_KEY_SOURCE_CHK = "certificate_authority_secret_key_source_chk";+const CA_SECRET_APP_CONNECTION_IDX = "certificate_authority_secret_appconnectionid_idx";++const INFISICAL_ARM = `("keySource" = 'infisical' AND "encryptedPrivateKey" IS NOT NULL)`;+const LEGACY_HSM_ARM = `("keySource" = 'hsm' AND "hsmConnectorId" IS NOT NULL AND "hsmKeyLabel" IS NOT NULL)`;+const HSM_ARM = `("keySource" = 'hsm' AND "hsmConnectorId" IS NOT NULL AND "externalKeyId" IS NOT NULL)`;+const AWS_KMS_ARM = `("keySource" = 'aws-kms' AND "appConnectionId" IS NOT NULL AND "externalKeyId" IS NOT NULL AND "publicKeySpki" IS NOT NULL)`;++const replaceKeySourceConstraint = (knex: Knex, arms: string[]) =>+ knex.raw(`ALTER TABLE ?? DROP CONSTRAINT IF EXISTS ??, ADD CONSTRAINT ?? CHECK (${arms.join(" OR ")})`, [+ TableName.CertificateAuthoritySecret,+ CA_SECRET_KEY_SOURCE_CHK,+ CA_SECRET_KEY_SOURCE_CHK+ ]);++export async function up(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "externalKeyId")) return;++ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {+ t.uuid("appConnectionId").nullable();+ t.foreign("appConnectionId").references("id").inTable(TableName.AppConnection).deferrable("deferred");+ t.index(["appConnectionId"], CA_SECRET_APP_CONNECTION_IDX, { predicate: knex.whereNotNull("appConnectionId") });+ t.string("externalKeyId", 2048).nullable();+ t.binary("publicKeySpki").nullable();+ });++ await knex.raw(+ `UPDATE ?? SET "externalKeyId" = "hsmKeyLabel", "publicKeySpki" = "hsmPublicKeySpki" WHERE "keySource" = 'hsm'`,+ [TableName.CertificateAuthoritySecret]+ );++ await replaceKeySourceConstraint(knex, [INFISICAL_ARM, HSM_ARM, AWS_KMS_ARM]);++ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {+ t.dropColumn("hsmKeyLabel");+ t.dropColumn("hsmPublicKeySpki");+ });+}++export async function down(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasColumn(TableName.CertificateAuthoritySecret, "externalKeyId"))) return;++ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {+ t.string("hsmKeyLabel", 128).nullable();+ t.binary("hsmPublicKeySpki").nullable();+ });++ await knex.raw(+ `UPDATE ?? SET "hsmKeyLabel" = "externalKeyId", "hsmPublicKeySpki" = "publicKeySpki" WHERE "keySource" = 'hsm'`,+ [TableName.CertificateAuthoritySecret]+ );++ await replaceKeySourceConstraint(knex, [INFISICAL_ARM, LEGACY_HSM_ARM]);++ await knex.schema.alterTable(TableName.CertificateAuthoritySecret, (t) => {+ t.dropColumn("publicKeySpki");+ t.dropColumn("externalKeyId");+ t.dropColumn("appConnectionId");+ });+}diff --git a/backend/src/db/schemas/certificate-authority-secret.ts b/backend/src/db/schemas/certificate-authority-secret.tsindex 5d0d50d5d3..85cea1d638 100644--- a/backend/src/db/schemas/certificate-authority-secret.ts+++ b/backend/src/db/schemas/certificate-authority-secret.ts@@ -17,8 +17,9 @@ export const CertificateAuthoritySecretSchema = z.object({encryptedPrivateKey: zodBuffer.nullable().optional(),keySource: z.string().default("infisical"),hsmConnectorId: z.string().uuid().nullable().optional(),- hsmKeyLabel: z.string().nullable().optional(),- hsmPublicKeySpki: zodBuffer.nullable().optional()+ appConnectionId: z.string().uuid().nullable().optional(),+ externalKeyId: z.string().nullable().optional(),+ publicKeySpki: zodBuffer.nullable().optional()});export type TCertificateAuthoritySecret = z.infer<typeof CertificateAuthoritySecretSchema>;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 1fff0a3e52..daca96a57e 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -3013,14 +3013,20 @@ interface RemoveGroupFromProjectEvent {};}+type TCaKeySourceAuditMetadata = {+ keySource?: string;+ hsmConnectorId?: string;+ appConnectionId?: string;+ appConnectionName?: string;+ externalKeyId?: string;+};+interface CreateCa {type: EventType.CREATE_CA;- metadata: {+ metadata: TCaKeySourceAuditMetadata & {caId: string;name: string;dn?: string;- keySource?: string;- hsmConnectorId?: string;isOcspEnabled?: boolean;};}@@ -3054,7 +3060,7 @@ interface UpdateCa {interface DeleteCa {type: EventType.DELETE_CA;- metadata: {+ metadata: TCaKeySourceAuditMetadata & {caId: string;name: string;dn?: string;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.tsindex 5f047df485..a286d33453 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@@ -103,7 +103,7 @@ const buildHarness = async () => {decryptWithKmsKey: vi.fn(async () => async () => Buffer.from(caCert.rawData)),generateKmsKey: vi.fn()} as never,- hsmConnectorService: { sign: vi.fn() } as never,+ caKeySourceService: { buildSigner: vi.fn() } as never,keyStore: keyStore as never});diff --git a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service.ts b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service.tsindex 08e7ba320b..9aca436eba 100644--- a/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service.ts+++ b/backend/src/ee/services/certificate-authority-ocsp/certificate-authority-ocsp-service.ts@@ -11,11 +11,11 @@ import {} from "@app/lib/telemetry/metrics";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { CertStatus } from "@app/services/certificate/certificate-types";+import type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";import { getCaSigner } from "@app/services/certificate-authority/certificate-authority-fns";import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";-import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";@@ -57,7 +57,7 @@ type TCertificateAuthorityOcspServiceFactoryDep = {certificateDAL: Pick<TCertificateDALFactory, "find" | "primaryNode">;projectDAL: Pick<TProjectDALFactory, "findById" | "findOne" | "updateById" | "transaction">;kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;- hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;keyStore: Pick<TKeyStoreFactory, "getItemPrimary" | "setItemWithExpiry">;};@@ -100,7 +100,7 @@ export const certificateAuthorityOcspServiceFactory = ({certificateDAL,projectDAL,kmsService,- hsmConnectorService,+ caKeySourceService,keyStore}: TCertificateAuthorityOcspServiceFactoryDep): TCertificateAuthorityOcspServiceFactory => {const $getActiveCaCertificate = async (caId: string, projectId: string, activeCaCertId: string) => {@@ -274,7 +274,7 @@ export const certificateAuthorityOcspServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService,+ caKeySourceService,prefetched: { kmsKeyId: activeCaCert.kmsKeyId }});diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex ae1f3624f0..ba51db6538 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -120,6 +120,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({pkiPqc: false,caCrl: true,pkiOcsp: false,+ pkiAwsKmsSigning: false,pkiEnterpriseCaIntegrations: false,pkiExternalIntermediateCa: false,pkiDiscovery: false,diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.tsindex 2889f5d4a1..be404ae53b 100644--- a/backend/src/ee/services/license/license-types.ts+++ b/backend/src/ee/services/license/license-types.ts@@ -117,6 +117,7 @@ export type TFeatureSet = {// withholds it on cloud.caCrl: boolean;pkiOcsp: false;+ pkiAwsKmsSigning: false;pkiEnterpriseCaIntegrations: false;pkiExternalIntermediateCa: false;pkiDiscovery: false;diff --git a/backend/src/ee/services/pki-scep/pki-scep-fns.ts b/backend/src/ee/services/pki-scep/pki-scep-fns.tsindex 03ec28fbe7..ecd1031314 100644--- a/backend/src/ee/services/pki-scep/pki-scep-fns.ts+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.ts@@ -9,6 +9,7 @@ import { BadRequestError } from "@app/lib/errors";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { isCertChainValid } from "@app/services/certificate/certificate-fns";import { CertStatus } from "@app/services/certificate/certificate-types";+import type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";import { TCaSigner } from "@app/services/certificate-authority/ca-signer";import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";@@ -16,7 +17,6 @@ import { CaType } from "@app/services/certificate-authority/certificate-authoritimport { getCaCertChains, getCaSigner } from "@app/services/certificate-authority/certificate-authority-fns";import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";import { SUPPORTED_GENERAL_NAME_TYPES } from "@app/services/certificate-common/certificate-constants";-import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";@@ -127,7 +127,7 @@ type TGenerateScepRaCertificateDeps = {projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;kmsService: Parameters<typeof getCaCertChains>[0]["kmsService"] &Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey">;- hsmConnectorService: THsmConnectorServiceFactory;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;};// Whether Infisical can CA-sign the SCEP RA for a CA type so it chains to the CA (RFC 8894).@@ -180,7 +180,7 @@ const buildCaSignedRaCertificate = async (slug: string, caId: string, deps: TGencertificateAuthoritySecretDAL: deps.certificateAuthoritySecretDAL,projectDAL: deps.projectDAL,kmsService: deps.kmsService,- hsmConnectorService: deps.hsmConnectorService+ caKeySourceService: deps.caKeySourceService});const chains = await getCaCertChains({diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex c68da31e6a..eb35e0874b 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -2849,11 +2849,18 @@ export const CertificateAuthorities = {keyAlgorithm:"The type of public key algorithm and size, in bits, of the key pair for the CA; when you create an intermediate CA, you must use a key algorithm supported by the parent CA.",keySource:- "Where the CA's signing key is generated and stored. 'infisical' keeps the key in Infisical's KMS; 'hsm' generates and stores the key in the HSM reached through the specified HSM Connector.",+ "Where the CA's signing key is generated and stored. 'infisical' keeps the key in Infisical's KMS; 'hsm' generates and stores the key in the HSM reached through the specified HSM Connector; 'aws-kms' generates the key in AWS KMS through the specified AWS connection, and every signature is made by AWS KMS.",hsmConnectorId:"The ID of the HSM Connector to generate and store the CA's signing key in. Required when keySource is 'hsm'.",hsmKeyLabel:"The label of the CA's signing key on the HSM. Not user-supplied: it is the HSM Connector's configured key name prefix followed by a per-CA label built from the CA name and a random 5-character suffix (ca-<name>-<slug>).",+ 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.",+ 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:+ "The ARN of the CA's signing key in AWS KMS. Not user-supplied: the key is created when the CA is created.",crlDistributionPointUrls:"Additional CRL Distribution Point URLs (HTTP/HTTPS) embedded in every certificate issued by this CA. Up to 4 URLs; the Infisical-managed CRL endpoint is included by default unless disabled.",disableManagedCrlDistributionPointUrl:diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 229df1e045..a79a8a4d86 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -313,6 +313,7 @@ import { certificateDALFactory } from "@app/services/certificate/certificate-dalimport { certificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";import { certificateServiceFactory } from "@app/services/certificate/certificate-service";import { caAutoRenewalQueueFactory } from "@app/services/certificate-authority/ca-auto-renewal-queue";+import { caKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";import { caSigningConfigDALFactory } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-dal";import { caSigningConfigServiceFactory } from "@app/services/certificate-authority/ca-signing-config/ca-signing-config-service";import { certificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";@@ -2398,17 +2399,6 @@ export const registerRoutes = async (auditLogService});- const projectCleanupQueue = projectCleanupQueueFactory({- cronJob,- queueService,- projectDAL,- membershipUserDAL,- userDAL,- kmsService,- keyStore,- auditLogService- });-const projectEnvService = projectEnvServiceFactory({permissionService,projectEnvDAL,@@ -3336,6 +3326,29 @@ export const registerRoutes = async (licenseService});+ const caKeySourceService = caKeySourceServiceFactory({+ hsmConnectorService,+ certificateAuthoritySecretDAL,+ appConnectionDAL,+ appConnectionService,+ kmsService,+ projectDAL,+ licenseService+ });++ const projectCleanupQueue = projectCleanupQueueFactory({+ cronJob,+ queueService,+ projectDAL,+ membershipUserDAL,+ userDAL,+ kmsService,+ certificateAuthoritySecretDAL,+ caKeySourceService,+ keyStore,+ auditLogService+ });+const certificateProfileService = certificateProfileServiceFactory({certificateProfileDAL,certificatePolicyDAL,@@ -3350,7 +3363,7 @@ export const registerRoutes = async (certificateAuthorityDAL,certificateAuthoritySecretDAL,certificateAuthorityCertDAL,- hsmConnectorService,+ caKeySourceService,externalCertificateAuthorityDAL,permissionService,kmsService,@@ -3617,7 +3630,7 @@ export const registerRoutes = async (pkiSyncDAL,pkiSyncQueue,internalCertificateAuthorityDAL,- hsmConnectorService,+ caKeySourceService,gatewayV2Service,gatewayPoolService});@@ -3629,7 +3642,7 @@ export const registerRoutes = async (certificateDAL,projectDAL,kmsService,- hsmConnectorService,+ caKeySourceService,keyStore});@@ -3653,7 +3666,7 @@ export const registerRoutes = async (licenseService,caSigningConfigDAL,usageMeteringService,- hsmConnectorService+ caKeySourceService});const caAutoRenewalQueue = caAutoRenewalQueueFactory({@@ -3700,7 +3713,7 @@ export const registerRoutes = async (gatewayV2Service,gatewayPoolService,usageMeteringService,- hsmConnectorService,+ caKeySourceService,certificateAuthoritySecretDAL,licenseService,telemetryService,@@ -3791,7 +3804,7 @@ export const registerRoutes = async (certificatePolicyService,licenseService,usageMeteringService,- hsmConnectorService,+ caKeySourceService,internalCertificateAuthorityDAL});@@ -3948,7 +3961,7 @@ export const registerRoutes = async (certificateAuthorityDAL,certificateAuthoritySecretDAL,certificateAuthorityCertDAL,- hsmConnectorService,+ caKeySourceService,kmsService,projectDAL,permissionService@@ -4095,6 +4108,7 @@ export const registerRoutes = async (});const certificateV3Service = certificateV3ServiceFactory({+ caKeySourceService,usageCounterDAL,pkiApplicationDAL,keyStore,diff --git a/backend/src/server/routes/v1/certificate-authority-router.ts b/backend/src/server/routes/v1/certificate-authority-router.tsindex d1b9e1a0ba..5e6841ff34 100644--- a/backend/src/server/routes/v1/certificate-authority-router.ts+++ b/backend/src/server/routes/v1/certificate-authority-router.ts@@ -15,6 +15,7 @@ import {CaStatus,InternalCaType} from "@app/services/certificate-authority/certificate-authority-enums";+import { getCaKeySourceAuditMetadata } from "@app/services/certificate-authority/certificate-authority-fns";import {validateAltNamesField,validateCaDateField@@ -281,7 +282,7 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {}},handler: async (req) => {- const ca = await server.services.internalCertificateAuthority.deleteCaById({+ const { ca, keyDetails } = await server.services.internalCertificateAuthority.deleteCaById({caId: req.params.caId,actor: req.permission.type,actorId: req.permission.id,@@ -297,7 +298,8 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {metadata: {name: ca.name,caId: ca.id,- dn: ca.dn+ dn: ca.dn,+ ...getCaKeySourceAuditMetadata(keyDetails)}}});diff --git a/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts b/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.tsindex add47dcaee..174b2310d1 100644--- a/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts+++ b/backend/src/server/routes/v1/certificate-authority-routers/certificate-authority-endpoints.ts@@ -8,6 +8,7 @@ import { getTelemetryDistinctId } from "@app/server/lib/telemetry";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums";+import { getCaKeySourceAuditMetadata } from "@app/services/certificate-authority/certificate-authority-fns";import {TCertificateAuthority,TCertificateAuthorityInput@@ -142,11 +143,8 @@ export const registerCertificateAuthorityEndpoints = <},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),handler: async (req) => {- const body = req.body as {- projectId?: string;- configuration?: { keySource?: string; hsmConnectorId?: string };- };- const createdOcspSetting = (body as { configuration?: { isOcspEnabled?: boolean } }).configuration?.isOcspEnabled;+ const body = req.body as { projectId?: string; configuration?: { isOcspEnabled?: boolean } };+ const createdOcspSetting = body.configuration?.isOcspEnabled;const certificateAuthority = (await server.services.certificateAuthority.createCertificateAuthority({ ...req.body, projectId: body.projectId ?? req.internalCertManagerProjectId, type: caType },req.permission@@ -160,8 +158,7 @@ export const registerCertificateAuthorityEndpoints = <metadata: {name: certificateAuthority.name,caId: certificateAuthority.id,- keySource: body.configuration?.keySource,- hsmConnectorId: body.configuration?.hsmConnectorId,+ ...getCaKeySourceAuditMetadata(certificateAuthority.configuration),...(typeof createdOcspSetting === "boolean" && { isOcspEnabled: createdOcspSetting })}}@@ -278,7 +275,8 @@ export const registerCertificateAuthorityEndpoints = <type: EventType.DELETE_CA,metadata: {name: certificateAuthority.name,- caId: certificateAuthority.id+ caId: certificateAuthority.id,+ ...getCaKeySourceAuditMetadata(certificateAuthority.configuration)}}});diff --git a/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.ts b/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.tsindex 1dfce86d7e..244cb4fbe9 100644--- a/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.ts+++ b/backend/src/server/routes/v1/deprecated-certificate-authority-routers/certificate-authority-endpoints.ts@@ -6,6 +6,7 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMode } from "@app/services/auth/auth-type";import { CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums";+import { getCaKeySourceAuditMetadata } from "@app/services/certificate-authority/certificate-authority-fns";import {TCertificateAuthority,TCertificateAuthorityInput@@ -155,7 +156,8 @@ export const registerCertificateAuthorityEndpoints = <type: EventType.CREATE_CA,metadata: {name: certificateAuthority.name,- caId: certificateAuthority.id+ caId: certificateAuthority.id,+ ...getCaKeySourceAuditMetadata(certificateAuthority.configuration)}}});@@ -247,7 +249,8 @@ export const registerCertificateAuthorityEndpoints = <type: EventType.DELETE_CA,metadata: {name: certificateAuthority.name,- caId: certificateAuthority.id+ caId: certificateAuthority.id,+ ...getCaKeySourceAuditMetadata(certificateAuthority.configuration)}}});diff --git a/backend/src/server/routes/v1/signer-routers/certificate-router.ts b/backend/src/server/routes/v1/signer-routers/certificate-router.tsindex d33437d798..b195a7ea83 100644--- a/backend/src/server/routes/v1/signer-routers/certificate-router.ts+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts@@ -34,7 +34,7 @@ export const registerSignerCertificateRouter = async (server: FastifyZodProviderkeyAlgorithm: SignerKeyAlgorithm.schema.optional(),certificate: z.object({- keySource: z.nativeEnum(CertKeySource),+ keySource: z.enum([CertKeySource.Infisical, CertKeySource.Hsm]),hsmConnectorId: z.string().uuid().optional()}).optional(),diff --git a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts b/backend/src/server/routes/v1/signer-routers/lifecycle-router.tsindex e107cd287f..fef8c1e78e 100644--- a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts@@ -63,7 +63,10 @@ export const registerSignerLifecycleRouter = async (server: FastifyZodProvider)certificateId: z.string().uuid().optional(),certificate: z.object({- keySource: z.nativeEnum(CertKeySource).optional().default(CertKeySource.Infisical),+ keySource: z+ .enum([CertKeySource.Infisical, CertKeySource.Hsm])+ .optional()+ .default(CertKeySource.Infisical),hsmConnectorId: z.string().uuid().optional()}).optional(),diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 0ee7e65120..2128ed8840 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -1198,6 +1198,14 @@ export const appConnectionServiceFactory = ({err instanceof DatabaseError &&(err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation) {+ if (+ (err.error as { constraint?: string }).constraint === "certificate_authority_secret_appconnectionid_foreign"+ ) {+ throw new BadRequestError({+ message:+ "Cannot delete this App Connection because a certificate authority signs with an AWS KMS key reached through it. Delete that certificate authority first."+ });+ }throw new BadRequestError({message:"Cannot delete App Connection with existing connections. Remove all existing connections and try again."diff --git a/backend/src/services/cert-manager-export/cert-manager-export-service.ts b/backend/src/services/cert-manager-export/cert-manager-export-service.tsindex f29b3c77af..0992a87962 100644--- a/backend/src/services/cert-manager-export/cert-manager-export-service.ts+++ b/backend/src/services/cert-manager-export/cert-manager-export-service.ts@@ -5,6 +5,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { BadRequestError, ForbiddenRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";import { alphaNumericNanoId } from "@app/lib/nanoid";import { ActorType } from "@app/services/auth/auth-type";+import { isExternalCaKeySource } from "@app/services/certificate-authority/ca-key-source/ca-key-source-fns";import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";@@ -16,7 +17,6 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TOrgDALFactory } from "@app/services/org/org-dal";import { TProjectDALFactory } from "@app/services/project/project-dal";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";-import { CertKeySource } from "@app/services/signer/signer-enums";import { TExportCertManagerProjectDTO, TExportCertManagerProjectResult } from "./cert-manager-export-types";@@ -178,16 +178,16 @@ export const certManagerExportServiceFactory = ({else sourceSecretsByCaId.set(secret.caId, [secret]);}- const hsmBackedCaIds = new Set(- allSourceSecrets.filter((s) => s.keySource === CertKeySource.Hsm).map((s) => s.caId)+ const externallyKeyedCaIds = new Set(+ allSourceSecrets.filter((s) => isExternalCaKeySource(s.keySource)).map((s) => s.caId));- if (hsmBackedCaIds.size) {+ if (externallyKeyedCaIds.size) {const names = sourceInternalCAs- .filter((ca) => hsmBackedCaIds.has(ca.id))+ .filter((ca) => externallyKeyedCaIds.has(ca.id)).map((ca) => ca.name).join(", ");throw new BadRequestError({- message: `Cannot export HSM-backed certificate authorities (${names}). Their signing keys live on an HSM reached through a connector that exists only in the source project, so they cannot be recreated in the destination. Delete these certificate authorities, then export again.`+ message: `Cannot export certificate authorities whose signing keys are held in an HSM or AWS KMS (${names}). Their keys are reached through a connection that is not exported, so they cannot be recreated in the destination. Delete these certificate authorities, then export again.`});}@@ -235,9 +235,6 @@ export const certManagerExportServiceFactory = ({{caId: newCa.id,keySource: sourceSecret.keySource,- hsmConnectorId: sourceSecret.hsmConnectorId,- hsmKeyLabel: sourceSecret.hsmKeyLabel,- hsmPublicKeySpki: sourceSecret.hsmPublicKeySpki,encryptedPrivateKey: sourceSecret.encryptedPrivateKey? await reencrypt(sourceSecret.encryptedPrivateKey): undefineddiff --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.tsnew file mode 100644index 0000000000..887ca676f2--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source-fns.ts@@ -0,0 +1,101 @@+import { KeySpec, SigningAlgorithmSpec } from "@aws-sdk/client-kms";++import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";++import { keyAlgorithmToAlgCfg } from "../certificate-authority-fns";++export const AWS_KMS_KEY_SPEC_BY_ALGORITHM: Partial<Record<CertKeyAlgorithm, KeySpec>> = {+ [CertKeyAlgorithm.RSA_2048]: KeySpec.RSA_2048,+ [CertKeyAlgorithm.RSA_3072]: KeySpec.RSA_3072,+ [CertKeyAlgorithm.RSA_4096]: KeySpec.RSA_4096,+ [CertKeyAlgorithm.ECDSA_P256]: KeySpec.ECC_NIST_P256,+ [CertKeyAlgorithm.ECDSA_P384]: KeySpec.ECC_NIST_P384,+ [CertKeyAlgorithm.ECDSA_P521]: KeySpec.ECC_NIST_P521,+ [CertKeyAlgorithm.ML_DSA_44]: KeySpec.ML_DSA_44,+ [CertKeyAlgorithm.ML_DSA_65]: KeySpec.ML_DSA_65,+ [CertKeyAlgorithm.ML_DSA_87]: KeySpec.ML_DSA_87+};++const AWS_KMS_DIGEST_SIGNING_BY_HASH: Record<+ string,+ { rsa: SigningAlgorithmSpec; ecdsa: SigningAlgorithmSpec; nodeHash: string }+> = {+ "SHA-256": {+ rsa: SigningAlgorithmSpec.RSASSA_PKCS1_V1_5_SHA_256,+ ecdsa: SigningAlgorithmSpec.ECDSA_SHA_256,+ nodeHash: "sha256"+ },+ "SHA-384": {+ rsa: SigningAlgorithmSpec.RSASSA_PKCS1_V1_5_SHA_384,+ ecdsa: SigningAlgorithmSpec.ECDSA_SHA_384,+ nodeHash: "sha384"+ },+ "SHA-512": {+ rsa: SigningAlgorithmSpec.RSASSA_PKCS1_V1_5_SHA_512,+ ecdsa: SigningAlgorithmSpec.ECDSA_SHA_512,+ nodeHash: "sha512"+ }+};++export const resolveAwsKmsDigestSigning = (keyAlgorithm: CertKeyAlgorithm, hash: string) => {+ const keyAlgCfg = keyAlgorithmToAlgCfg(keyAlgorithm);+ const isEcdsa = keyAlgCfg.name === "ECDSA";+ if (isEcdsa && hash !== keyAlgCfg.hash) {+ throw new BadRequestError({+ message: `AWS KMS signs ${keyAlgorithm} keys only with ${keyAlgCfg.hash}, so the signature algorithm cannot use ${hash}. Choose a ${keyAlgCfg.hash} signature algorithm for this certificate authority.`+ });+ }++ const signing = AWS_KMS_DIGEST_SIGNING_BY_HASH[hash];+ if (!signing) {+ throw new BadRequestError({+ message: `Signature hash "${hash}" is not supported for AWS KMS-backed certificate authorities.`+ });+ }+ return { signingAlgorithmSpec: isEcdsa ? signing.ecdsa : signing.rsa, nodeHash: signing.nodeHash };+};++export const computeMlDsaExternalMu = (rawPublicKey: Uint8Array, message: Buffer): Buffer => {+ const tr = crypto.nativeCrypto.createHash("shake256", { outputLength: 64 }).update(rawPublicKey).digest();+ return crypto.nativeCrypto+ .createHash("shake256", { outputLength: 64 })+ .update(tr)+ .update(Buffer.from([0, 0]))+ .update(message)+ .digest();+};++export const parseAwsKmsKeyArnRegion = (keyArn: string) => {+ const region = keyArn.split(":")[3];+ if (!keyArn.startsWith("arn:") || !region) {+ throw new BadRequestError({ message: `AWS KMS key reference '${keyArn}' is not a valid key ARN.` });+ }+ return region;+};++const AWS_KMS_ERROR_MESSAGES: Record<string, string> = {+ AccessDeniedException:+ "AWS denied the request. Grant the AWS connection's IAM principal kms:CreateKey, kms:TagResource, kms:GetPublicKey, kms:Sign, and kms:ScheduleKeyDeletion.",+ DisabledException: "The AWS KMS key is disabled. Enable it in AWS KMS and try again.",+ KMSInvalidStateException: "The AWS KMS key is disabled or pending deletion. Restore it in AWS KMS and try again.",+ NotFoundException: "The AWS KMS key no longer exists or is not in the connection's AWS account and region.",+ 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."+};++export const toAwsKmsError = (error: unknown, operation: string): Error => {+ if (error instanceof BadRequestError) return error;++ const { name, message } = error as { name?: string; message?: 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"}`+ });+};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.tsnew file mode 100644index 0000000000..5a97d56974--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.test.ts@@ -0,0 +1,285 @@+import nodeCrypto, { KeyObject, webcrypto } from "node:crypto";++import {+ CreateKeyCommand,+ GetPublicKeyCommand,+ KMSClient,+ ScheduleKeyDeletionCommand,+ SignCommand+} from "@aws-sdk/client-kms";+import { AsnConvert } from "@peculiar/asn1-schema";+import { Certificate } from "@peculiar/asn1-x509";+import * as x509 from "@peculiar/x509";++import { crypto } from "@app/lib/crypto/cryptography";+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 { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+import { CertKeySource } from "@app/services/signer/signer-enums";++import { awsKmsCaKeySourceFactory } from "./aws-kms-ca-key-source";+import { caKeySourceServiceFactory } from "./ca-key-source-service";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }+}));++vi.mock("@app/services/app-connection/app-connection-fns", () => ({+ decryptAppConnection: vi.fn(async (connection: unknown) => connection)+}));++vi.mock("@app/services/app-connection/aws/aws-connection-fns", () => ({+ getAwsConnectionConfig: vi.fn(async (_connection: unknown, region: string) => ({+ credentials: { accessKeyId: "test", secretAccessKey: "test" },+ region+ }))+}));++const KEY_ARN = "arn:aws:kms:us-east-1:111122223333:key/0b7fd7dd-bac6-4ef2-8790-7413567cad8c";++type TSignInput = { Message: Uint8Array; MessageType: string; SigningAlgorithm: string };++const fakeKms = (keyPair: { publicKey: KeyObject; privateKey: KeyObject }) => {+ const signCalls: TSignInput[] = [];+ const createCalls: Record<string, unknown>[] = [];++ const send = async (command: unknown) => {+ if (command instanceof CreateKeyCommand) {+ createCalls.push(command.input as Record<string, unknown>);+ return { KeyMetadata: { Arn: KEY_ARN } };+ }+ if (command instanceof GetPublicKeyCommand) {+ return { PublicKey: keyPair.publicKey.export({ format: "der", type: "spki" }) };+ }+ 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") };+ }+ throw new Error("unexpected KMS command");+ };+ vi.spyOn(KMSClient.prototype, "send").mockImplementation(send as never);++ return { signCalls, createCalls };+};++const buildDeps = (plan: Record<string, unknown> = { pkiAwsKmsSigning: true }) => ({+ appConnectionDAL: { findById: vi.fn(async () => ({ id: "conn", app: "aws", orgId: "org" })) } as never,+ appConnectionService: { validateAppConnectionUsageById: vi.fn() } as never,+ kmsService: {} as never,+ projectDAL: { findById: vi.fn(async () => ({ id: "project", orgId: "org" })) } as never,+ licenseService: { getPlan: vi.fn(async () => plan) } as never,+ hsmConnectorService: {} as never,+ certificateAuthoritySecretDAL: { findOne: vi.fn() } as never+});++const createAndSignRoot = async (keyAlgorithm: CertKeyAlgorithm, signatureAlgorithm?: Algorithm) => {+ const provider = awsKmsCaKeySourceFactory(buildDeps());+ const reference = await provider.createKey({+ projectId: "project",+ caName: "root-ca",+ keyAlgorithm,+ input: { appConnectionId: "conn", region: AWSRegion.US_EAST_1 }+ });+ const signer = await provider.buildSigner({ projectId: "project", keyAlgorithm, reference, signatureAlgorithm });+ const certificate = await signer.createCertificate({+ subject: "CN=Root CA",+ issuer: "CN=Root CA",+ serialNumber: "01",+ notBefore: new Date(),+ notAfter: new Date(Date.now() + 86_400_000),+ publicKey: signer.caPublicKey+ });+ return { reference, signer, certificate };+};++describe("AWS KMS CA key source", () => {+ beforeAll(async () => {+ await crypto.initialize({} as never, {} as never, {} as never);+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ test("creates a sign/verify key and stores only its reference", async () => {+ const keyPair = nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 });+ const { createCalls } = fakeKms(keyPair);++ 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" })+ });+ });++ test("RSA certificates and CRLs signed through KMS verify against the KMS public key", async () => {+ const { signCalls } = fakeKms(nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }));++ const { signer, certificate } = await createAndSignRoot(CertKeyAlgorithm.RSA_2048);+ const crl = await signer.createCrl({ issuer: "CN=Root CA", thisUpdate: new Date(), entries: [] });++ expect(await certificate.verify({ publicKey: signer.caPublicKey, signatureOnly: true })).toBe(true);+ expect(await crl.verify({ publicKey: signer.caPublicKey })).toBe(true);+ expect(signCalls.every((call) => call.MessageType === "DIGEST")).toBe(true);+ expect(signCalls[0].SigningAlgorithm).toBe("RSASSA_PKCS1_V1_5_SHA_256");+ });++ test("RSA honours a SHA-384 signature algorithm override", async () => {+ const { signCalls } = fakeKms(nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }));++ const { certificate } = await createAndSignRoot(CertKeyAlgorithm.RSA_2048, {+ name: "RSASSA-PKCS1-v1_5",+ hash: "SHA-384"+ } as Algorithm);++ expect(signCalls[0].SigningAlgorithm).toBe("RSASSA_PKCS1_V1_5_SHA_384");+ expect(certificate.signatureAlgorithm).toMatchObject({ hash: { name: "SHA-384" } });+ 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" }));++ const { certificate } = await createAndSignRoot(CertKeyAlgorithm.ECDSA_P384);++ const tbs = Buffer.from(AsnConvert.serialize(AsnConvert.parse(certificate.rawData, Certificate).tbsCertificate));+ expect(signCalls[0].SigningAlgorithm).toBe("ECDSA_SHA_384");+ expect(Buffer.from(signCalls[0].Message as Uint8Array)).toEqual(+ nodeCrypto.createHash("sha384").update(tbs).digest()+ );+ expect(certificate.signatureAlgorithm).toMatchObject({ name: "ECDSA", hash: { name: "SHA-384" } });+ });++ test("ECDSA rejects a hash AWS KMS cannot use with the curve", async () => {+ fakeKms(nodeCrypto.generateKeyPairSync("ec", { namedCurve: "P-256" }));++ await expect(+ createAndSignRoot(CertKeyAlgorithm.ECDSA_P256, { name: "ECDSA", hash: "SHA-384" } as Algorithm)+ ).rejects.toThrow(BadRequestError);+ });++ test("refuses to create a key without the AWS KMS signing entitlement", async () => {+ fakeKms(nodeCrypto.generateKeyPairSync("rsa", { modulusLength: 2048 }));+ const provider = awsKmsCaKeySourceFactory(buildDeps({ pkiAwsKmsSigning: false }));++ await expect(+ provider.createKey({+ projectId: "project",+ caName: "root-ca",+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,+ input: { appConnectionId: "conn", region: AWSRegion.US_EAST_1 }+ })+ ).rejects.toThrow(/plan restriction/);+ });++ test("turns an AWS access denial into a readable error naming the IAM permissions", async () => {+ vi.spyOn(KMSClient.prototype, "send").mockRejectedValue(+ Object.assign(new Error("User is not authorized"), { name: "AccessDeniedException" })+ );+ const provider = awsKmsCaKeySourceFactory(buildDeps());++ await expect(+ provider.createKey({+ projectId: "project",+ caName: "root-ca",+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,+ input: { appConnectionId: "conn", region: AWSRegion.US_EAST_1 }+ })+ ).rejects.toThrow(/kms:CreateKey/);+ });++ test("releasing a key schedules its deletion with a 30-day window", async () => {+ const send = vi.spyOn(KMSClient.prototype, "send").mockResolvedValue({} as never);+ const provider = awsKmsCaKeySourceFactory(buildDeps());++ const release = await provider.prepareKeyRelease?.({+ reference: { appConnectionId: "conn", externalKeyId: KEY_ARN }+ });+ expect(send).not.toHaveBeenCalled();+ await release?.();++ const command = send.mock.calls[0][0] as unknown;+ expect(command).toBeInstanceOf(ScheduleKeyDeletionCommand);+ expect((command as ScheduleKeyDeletionCommand).input).toEqual({ KeyId: KEY_ARN, PendingWindowInDays: 30 });+ });++ test("schedules deletion of a newly created key whose public key cannot be read", async () => {+ const accessDenied = Object.assign(new Error("denied"), { name: "AccessDeniedException" });+ const send = vi.spyOn(KMSClient.prototype, "send").mockImplementation((async (command: unknown) => {+ if (command instanceof CreateKeyCommand) return { KeyMetadata: { Arn: KEY_ARN } };+ if (command instanceof GetPublicKeyCommand) throw accessDenied;+ return {};+ }) as never);+ const provider = awsKmsCaKeySourceFactory(buildDeps());++ await expect(+ provider.createKey({+ projectId: "project",+ caName: "root-ca",+ keyAlgorithm: CertKeyAlgorithm.RSA_2048,+ input: { appConnectionId: "conn", region: AWSRegion.US_EAST_1 }+ })+ ).rejects.toThrow(BadRequestError);++ const deletion = send.mock.calls.map(([command]) => command as unknown).at(-1);+ expect(deletion).toBeInstanceOf(ScheduleKeyDeletionCommand);+ expect((deletion as ScheduleKeyDeletionCommand).input).toEqual({ KeyId: KEY_ARN, PendingWindowInDays: 30 });+ });++ test("CSR signature algorithms resolve to what the CA's key source can sign with", async () => {+ const findOne = vi.fn();+ const service = caKeySourceServiceFactory({+ ...buildDeps(),+ certificateAuthoritySecretDAL: { findOne } as never+ });+ const resolve = (keySource: CertKeySource, keyAlgorithm: CertKeyAlgorithm) => {+ findOne.mockResolvedValueOnce({ keySource });+ return service.resolveCsrSignatureAlgorithm({ caId: "ca", keyAlgorithm, csrSignatureAlgorithm: "ECDSA-SHA256" });+ };++ expect(await resolve(CertKeySource.AwsKms, CertKeyAlgorithm.ECDSA_P384)).toBe("ECDSA-SHA384");+ expect(await resolve(CertKeySource.AwsKms, CertKeyAlgorithm.ECDSA_P521)).toBe("ECDSA-SHA512");+ expect(await resolve(CertKeySource.AwsKms, CertKeyAlgorithm.RSA_2048)).toBe("ECDSA-SHA256");+ expect(await resolve(CertKeySource.Hsm, CertKeyAlgorithm.ECDSA_P384)).toBe("ECDSA-SHA256");+ expect(await resolve(CertKeySource.Infisical, CertKeyAlgorithm.ECDSA_P384)).toBe("ECDSA-SHA256");+ });++ test("the registry rejects algorithms a key source cannot hold", async () => {+ const service = caKeySourceServiceFactory(buildDeps());++ await expect(+ service.createKey({+ keySource: CertKeySource.Hsm,+ projectId: "project",+ caName: "root-ca",+ keyAlgorithm: CertKeyAlgorithm.ML_DSA_65,+ input: { hsmConnectorId: "connector" }+ })+ ).rejects.toThrow(/not supported for HSM-backed/);++ await expect(+ service.createKey({+ keySource: CertKeySource.AwsKms,+ projectId: "project",+ caName: "root-ca",+ keyAlgorithm: CertKeyAlgorithm.SLH_DSA_SHA2_128F,+ input: { appConnectionId: "conn", region: AWSRegion.US_EAST_1 }+ })+ ).rejects.toThrow(/not supported for AWS KMS-backed/);+ });+});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.tsnew file mode 100644index 0000000000..018c5a01ce--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/aws-kms-ca-key-source.ts@@ -0,0 +1,251 @@+import {+ CreateKeyCommand,+ GetPublicKeyCommand,+ KeyUsageType,+ KMSClient,+ MessageType,+ ScheduleKeyDeletionCommand,+ SignCommand,+ SigningAlgorithmSpec+} from "@aws-sdk/client-kms";+import { AsnConvert } from "@peculiar/asn1-schema";+import { SubjectPublicKeyInfo } from "@peculiar/asn1-x509";++import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { CustomAWSHasher } from "@app/lib/aws/hashing";+import { crypto } from "@app/lib/crypto/cryptography";+import { getPqcCrypto, isPqcAlgorithm } from "@app/lib/crypto/pqc";+import { bufferToArrayBuffer } from "@app/lib/csr/pkcs11-algorithm-map";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";+import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";+import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";+import { getAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-fns";+import { TAwsConnection } from "@app/services/app-connection/aws/aws-connection-types";+import { ECDSA_SIGNATURE_ALGORITHMS } from "@app/services/certificate/certificate-fns";+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 { keyAlgorithmToAlgCfg } from "../certificate-authority-fns";+import {+ AWS_KMS_KEY_SPEC_BY_ALGORITHM,+ computeMlDsaExternalMu,+ parseAwsKmsKeyArnRegion,+ resolveAwsKmsDigestSigning,+ toAwsKmsError+} from "./aws-kms-ca-key-source-fns";+import { TExternalCaKeyInput, TExternalCaKeyProvider } from "./ca-key-source-types";++const AWS_KMS_KEY_DELETION_WINDOW_DAYS = 30;++type TAwsKmsCaKeySourceDep = {+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ projectDAL: Pick<TProjectDALFactory, "findById">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+};++const requireAwsKmsInput = (input: TExternalCaKeyInput) => {+ if (!input.appConnectionId || !input.region) {+ throw new BadRequestError({+ message: "An AWS connection and region are required when the key source is AWS KMS."+ });+ }+ return { appConnectionId: input.appConnectionId, region: input.region };+};++export const awsKmsCaKeySourceFactory = ({+ appConnectionDAL,+ appConnectionService,+ kmsService,+ projectDAL,+ licenseService+}: TAwsKmsCaKeySourceDep): TExternalCaKeyProvider => {+ const $getKmsClient = async (appConnectionId: string, region: string) => {+ const appConnection = await appConnectionDAL.findById(appConnectionId);+ if (!appConnection) {+ throw new NotFoundError({ message: `AWS connection with ID '${appConnectionId}' not found` });+ }+ if (appConnection.app !== AppConnection.AWS) {+ throw new BadRequestError({ message: `App connection with ID '${appConnectionId}' is not an AWS connection` });+ }++ const decryptedConnection = (await decryptAppConnection(appConnection, kmsService)) as TAwsConnection;+ const awsConfig = await getAwsConnectionConfig(decryptedConnection, region as AWSRegion);++ return new KMSClient({+ sha256: CustomAWSHasher,+ useFipsEndpoint: crypto.isFipsModeEnabled(),+ credentials: awsConfig.credentials,+ region: awsConfig.region+ });+ };++ const $scheduleKeyDeletion = async (client: KMSClient, keyArn: string) => {+ try {+ await client.send(+ new ScheduleKeyDeletionCommand({ KeyId: keyArn, PendingWindowInDays: AWS_KMS_KEY_DELETION_WINDOW_DAYS })+ );+ } catch (error) {+ throw toAwsKmsError(error, `schedule the deletion of '${keyArn}'`);+ }+ };++ return {+ displayName: "AWS KMS",+ supportedKeyAlgorithms: Object.keys(AWS_KMS_KEY_SPEC_BY_ALGORITHM) as CertKeyAlgorithm[],++ assertCanUse: async ({ actor, projectId, input }) => {+ const { appConnectionId } = requireAwsKmsInput(input);+ await appConnectionService.validateAppConnectionUsageById(+ AppConnection.AWS,+ { connectionId: appConnectionId, projectId },+ actor+ );+ },++ createKey: async ({ projectId, caName, keyAlgorithm, input }) => {+ const { appConnectionId, region } = requireAwsKmsInput(input);++ const project = await projectDAL.findById(projectId);+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });+ const plan = await licenseService.getPlan(project.orgId);+ if (!plan.pkiAwsKmsSigning) {+ throw new BadRequestError({+ message:+ "Failed to create certificate authority with an AWS KMS key due to plan restriction. Upgrade plan to use AWS KMS-backed certificate authorities."+ });+ }++ const client = await $getKmsClient(appConnectionId, region);++ let keyArn: string | undefined;+ try {+ const created = await client.send(+ new CreateKeyCommand({+ KeySpec: AWS_KMS_KEY_SPEC_BY_ALGORITHM[keyAlgorithm],+ KeyUsage: KeyUsageType.SIGN_VERIFY,+ Description: `Infisical certificate authority signing key: ${caName}`,+ Tags: [+ { TagKey: "author", TagValue: "infisical" },+ { TagKey: "purpose", TagValue: "certificate-authority" }+ ]+ })+ );+ keyArn = created.KeyMetadata?.Arn;+ } catch (error) {+ throw toAwsKmsError(error, "create the CA signing key");+ }+ if (!keyArn) throw new BadRequestError({ message: "AWS KMS did not return an ARN for the new signing key." });++ try {+ const { PublicKey: publicKeySpki } = await client.send(new GetPublicKeyCommand({ KeyId: keyArn }));+ if (!publicKeySpki) {+ throw new BadRequestError({ message: `AWS KMS did not return a public key for '${keyArn}'.` });+ }+ return { appConnectionId, externalKeyId: keyArn, publicKeySpki: Buffer.from(publicKeySpki) };+ } catch (error) {+ await $scheduleKeyDeletion(client, keyArn).catch((deletionError: unknown) => {+ logger.error(deletionError, `Failed to schedule deletion of unused AWS KMS CA key [keyArn=${keyArn}]`);+ });+ throw toAwsKmsError(error, `read the public key of '${keyArn}'`);+ }+ },++ buildSigner: async ({ keyAlgorithm, reference, signatureAlgorithm }) => {+ const { appConnectionId, externalKeyId: keyArn, publicKeySpki } = reference;+ if (!appConnectionId || !keyArn || !publicKeySpki) {+ throw new BadRequestError({+ message: "AWS KMS-backed CA secret is missing its AWS connection, key ARN, or public key"+ });+ }++ let client: KMSClient | undefined;+ const sign = async (message: Buffer, messageType: MessageType, signingAlgorithm: SigningAlgorithmSpec) => {+ client ??= await $getKmsClient(appConnectionId, parseAwsKmsKeyArnRegion(keyArn));+ try {+ const { Signature } = await client.send(+ new SignCommand({+ KeyId: keyArn,+ Message: message,+ MessageType: messageType,+ SigningAlgorithm: signingAlgorithm+ })+ );+ if (!Signature) throw new BadRequestError({ message: `AWS KMS returned no signature for '${keyArn}'.` });+ return bufferToArrayBuffer(Buffer.from(Signature));+ } catch (error) {+ throw toAwsKmsError(error, `sign with '${keyArn}'`);+ }+ };++ const keyAlgCfg = keyAlgorithmToAlgCfg(keyAlgorithm);++ if (isPqcAlgorithm(keyAlgorithm)) {+ const pqcCrypto = getPqcCrypto();+ const caPublicKey = await pqcCrypto.subtle.importKey("spki", publicKeySpki, keyAlgCfg, true, ["verify"]);+ const rawPublicKey = new Uint8Array(AsnConvert.parse(publicKeySpki, SubjectPublicKeyInfo).subjectPublicKey);++ return buildExternalCaSigner({+ caPublicKey,+ signingAlgorithm: keyAlgCfg,+ generateEphemeralKey: () =>+ pqcCrypto.subtle.generateKey(keyAlgCfg as RsaHashedKeyGenParams, true, ["sign", "verify"]),+ signTbs: (tbs) =>+ sign(+ computeMlDsaExternalMu(rawPublicKey, tbs),+ MessageType.EXTERNAL_MU,+ SigningAlgorithmSpec.ML_DSA_SHAKE_256+ )+ });+ }++ const hash = (signatureAlgorithm && algorithmHashName(signatureAlgorithm)) || keyAlgCfg.hash;+ const { signingAlgorithmSpec, nodeHash } = resolveAwsKmsDigestSigning(keyAlgorithm, hash);+ const certSigningAlgorithm = { name: keyAlgCfg.name, hash } as Algorithm;+ const ephemeralKeyParams = { ...keyAlgCfg, hash } as RsaHashedKeyGenParams;++ const caPublicKey = await crypto.nativeCrypto.subtle.importKey("spki", publicKeySpki, keyAlgCfg, true, [+ "verify"+ ]);++ return buildExternalCaSigner({+ caPublicKey,+ signingAlgorithm: certSigningAlgorithm,+ generateEphemeralKey: () =>+ crypto.nativeCrypto.subtle.generateKey(ephemeralKeyParams, true, ["sign", "verify"]),+ signTbs: (tbs) =>+ sign(crypto.nativeCrypto.createHash(nodeHash).update(tbs).digest(), MessageType.DIGEST, signingAlgorithmSpec)+ });+ },++ requiredSignatureAlgorithm: (keyAlgorithm) => {+ const keyAlgCfg = keyAlgorithmToAlgCfg(keyAlgorithm);+ return keyAlgCfg.name === "ECDSA" ? ECDSA_SIGNATURE_ALGORITHMS[keyAlgCfg.hash] : undefined;+ },++ describeKey: async ({ reference }) => {+ const { appConnectionId, externalKeyId: keyArn } = reference;+ const appConnection = appConnectionId ? await appConnectionDAL.findById(appConnectionId) : undefined;+ return {+ appConnectionId: appConnectionId ?? undefined,+ appConnectionName: appConnection?.name,+ externalKeyId: keyArn ?? undefined,+ region: keyArn ? parseAwsKmsKeyArnRegion(keyArn) : undefined+ };+ },++ prepareKeyRelease: async ({ reference }) => {+ const { appConnectionId, externalKeyId: keyArn } = reference;+ if (!appConnectionId || !keyArn) return async () => {};++ const client = await $getKmsClient(appConnectionId, parseAwsKmsKeyArnRegion(keyArn));+ return () => $scheduleKeyDeletion(client, keyArn);+ }+ };+};diff --git a/backend/src/services/certificate-authority/ca-key-source/ca-key-source-fns.ts b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-fns.tsnew file mode 100644index 0000000000..ede2033fa2--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-fns.ts@@ -0,0 +1,6 @@+import { CertKeySource } from "@app/services/signer/signer-enums";++import { TExternalCaKeySource } from "./ca-key-source-types";++export const isExternalCaKeySource = (keySource: string | null | undefined): keySource is TExternalCaKeySource =>+ Boolean(keySource) && keySource !== CertKeySource.Infisical;diff --git a/backend/src/services/certificate-authority/ca-key-source/ca-key-source-service.ts b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-service.tsnew file mode 100644index 0000000000..7445284822--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-service.ts@@ -0,0 +1,132 @@+import { TCertificateAuthoritySecret } from "@app/db/schemas";+import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";+import { OrgServiceActor } from "@app/lib/types";+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+import { CertKeySource } from "@app/services/signer/signer-enums";++import { TCertificateAuthoritySecretDALFactory } from "../certificate-authority-secret-dal";+import { awsKmsCaKeySourceFactory } from "./aws-kms-ca-key-source";+import { isExternalCaKeySource } from "./ca-key-source-fns";+import {+ TCaKeyDetails,+ TExternalCaKeyInput,+ TExternalCaKeyProvider,+ TExternalCaKeyReference,+ TExternalCaKeySource+} from "./ca-key-source-types";+import { hsmCaKeySourceFactory } from "./hsm-ca-key-source";++type TCaKeySourceServiceFactoryDep = Parameters<typeof hsmCaKeySourceFactory>[0] &+ Parameters<typeof awsKmsCaKeySourceFactory>[0] & {+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;+ };++export type TCaKeySourceServiceFactory = ReturnType<typeof caKeySourceServiceFactory>;++export const caKeySourceServiceFactory = (deps: TCaKeySourceServiceFactoryDep) => {+ const providers: Record<TExternalCaKeySource, TExternalCaKeyProvider> = {+ [CertKeySource.Hsm]: hsmCaKeySourceFactory(deps),+ [CertKeySource.AwsKms]: awsKmsCaKeySourceFactory(deps)+ };++ const $getProvider = (keySource: TExternalCaKeySource) => {+ const provider = providers[keySource];+ if (!provider)+ throw new BadRequestError({ message: `Unsupported certificate authority key source '${keySource}'` });+ return provider;+ };++ const assertCanUse = (args: {+ keySource: TExternalCaKeySource;+ actor: OrgServiceActor;+ projectId: string;+ input: TExternalCaKeyInput;+ }) => $getProvider(args.keySource).assertCanUse(args);++ const createKey = async (args: {+ keySource: TExternalCaKeySource;+ projectId: string;+ caName: string;+ keyAlgorithm: CertKeyAlgorithm;+ input: TExternalCaKeyInput;+ }) => {+ const provider = $getProvider(args.keySource);+ if (!provider.supportedKeyAlgorithms.includes(args.keyAlgorithm)) {+ throw new BadRequestError({+ message: `Key algorithm '${args.keyAlgorithm}' is not supported for ${provider.displayName}-backed certificate authorities. Supported algorithms: ${provider.supportedKeyAlgorithms.join(", ")}.`+ });+ }+ return provider.createKey(args);+ };++ const buildSigner = (args: {+ keySource: TExternalCaKeySource;+ projectId: string;+ keyAlgorithm: CertKeyAlgorithm;+ reference: Partial<TExternalCaKeyReference>;+ signatureAlgorithm?: Algorithm;+ }) => $getProvider(args.keySource).buildSigner(args);++ const describeKey = async (+ caSecret?: (Pick<TCertificateAuthoritySecret, "keySource"> & Partial<TExternalCaKeyReference>) | null+ ): Promise<TCaKeyDetails & { keySource: CertKeySource }> => {+ const keySource = (caSecret?.keySource as CertKeySource | undefined) ?? CertKeySource.Infisical;+ if (!caSecret || !isExternalCaKeySource(keySource)) return { keySource };+ return { keySource, ...(await $getProvider(keySource).describeKey({ reference: caSecret })) };+ };++ const prepareKeyReleases = async (+ caSecrets: ({ keySource: string; caId?: string } & Partial<TExternalCaKeyReference>)[]+ ) => {+ const logContext = (caSecret: (typeof caSecrets)[number]) =>+ `[caId=${caSecret.caId}] [keySource=${caSecret.keySource}] [externalKeyId=${caSecret.externalKeyId}]`;++ const releases = await Promise.all(+ caSecrets.map(async (caSecret) => {+ if (!isExternalCaKeySource(caSecret.keySource)) return undefined;+ const { prepareKeyRelease } = $getProvider(caSecret.keySource);+ if (!prepareKeyRelease) return undefined;+ try {+ return { caSecret, release: await prepareKeyRelease({ reference: caSecret }) };+ } catch (error) {+ logger.error(+ error,+ `Failed to prepare the release of a certificate authority signing key ${logContext(caSecret)}`+ );+ return undefined;+ }+ })+ );++ return async () => {+ await Promise.all(+ releases.map(async (prepared) => {+ if (!prepared) return;+ await prepared.release().catch((error: unknown) => {+ logger.error(+ error,+ `Failed to release a certificate authority signing key ${logContext(prepared.caSecret)}`+ );+ });+ })+ );+ };+ };++ const resolveCsrSignatureAlgorithm = async ({+ caId,+ keyAlgorithm,+ csrSignatureAlgorithm+ }: {+ caId: string;+ keyAlgorithm: CertKeyAlgorithm;+ csrSignatureAlgorithm?: string;+ }): Promise<string | undefined> => {+ const caSecret = await deps.certificateAuthoritySecretDAL.findOne({ caId });+ if (!caSecret || !isExternalCaKeySource(caSecret.keySource)) return csrSignatureAlgorithm;+ return $getProvider(caSecret.keySource).requiredSignatureAlgorithm?.(keyAlgorithm) ?? csrSignatureAlgorithm;+ };++ return { assertCanUse, createKey, buildSigner, describeKey, prepareKeyReleases, resolveCsrSignatureAlgorithm };+};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.tsnew file mode 100644index 0000000000..e353a24028--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.ts@@ -0,0 +1,50 @@+import { TCertificateAuthoritySecret } from "@app/db/schemas";+import { OrgServiceActor } from "@app/lib/types";+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";+import { CertKeyAlgorithm, CertSignatureAlgorithm } from "@app/services/certificate/certificate-types";+import { CertKeySource } from "@app/services/signer/signer-enums";++import { TCaSigner } from "../ca-signer";++export type TExternalCaKeySource = Exclude<CertKeySource, CertKeySource.Infisical>;++export type TExternalCaKeyInput = {+ hsmConnectorId?: string;+ appConnectionId?: string;+ region?: AWSRegion;+};++export type TExternalCaKeyReference = Pick<+ TCertificateAuthoritySecret,+ "hsmConnectorId" | "appConnectionId" | "externalKeyId" | "publicKeySpki"+>;++export type TCaKeyDetails = {+ hsmConnectorId?: string;+ hsmKeyLabel?: string;+ appConnectionId?: string;+ appConnectionName?: string;+ externalKeyId?: string;+ region?: string;+};++export type TExternalCaKeyProvider = {+ displayName: string;+ supportedKeyAlgorithms: readonly CertKeyAlgorithm[];+ assertCanUse: (args: { actor: OrgServiceActor; projectId: string; input: TExternalCaKeyInput }) => Promise<void>;+ createKey: (args: {+ projectId: string;+ caName: string;+ keyAlgorithm: CertKeyAlgorithm;+ input: TExternalCaKeyInput;+ }) => Promise<Partial<TExternalCaKeyReference>>;+ buildSigner: (args: {+ projectId: string;+ keyAlgorithm: CertKeyAlgorithm;+ reference: Partial<TExternalCaKeyReference>;+ signatureAlgorithm?: Algorithm;+ }) => Promise<TCaSigner>;+ describeKey: (args: { reference: Partial<TExternalCaKeyReference> }) => Promise<TCaKeyDetails>;+ prepareKeyRelease?: (args: { reference: Partial<TExternalCaKeyReference> }) => Promise<() => Promise<void>>;+ requiredSignatureAlgorithm?: (keyAlgorithm: CertKeyAlgorithm) => CertSignatureAlgorithm | undefined;+};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.tsnew file mode 100644index 0000000000..4a7260bdb7--- /dev/null+++ b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts@@ -0,0 +1,83 @@+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 { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";++import { buildHsmCaSigner, caKeyAlgorithmToHsmShape } from "../ca-signer";+import { TExternalCaKeyInput, TExternalCaKeyProvider } from "./ca-key-source-types";++type THsmCaKeySourceDep = {+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "assertAttachPermission">;+};++const requireHsmConnectorId = (input: TExternalCaKeyInput) => {+ if (!input.hsmConnectorId) {+ throw new BadRequestError({ message: "An HSM Connector is required when the key source is HSM." });+ }+ return input.hsmConnectorId;+};++export const hsmCaKeySourceFactory = ({ hsmConnectorService }: THsmCaKeySourceDep): TExternalCaKeyProvider => ({+ displayName: "HSM",+ supportedKeyAlgorithms: [+ CertKeyAlgorithm.RSA_2048,+ CertKeyAlgorithm.RSA_4096,+ CertKeyAlgorithm.ECDSA_P256,+ CertKeyAlgorithm.ECDSA_P384+ ],++ assertCanUse: async ({ actor, projectId, input }) => {+ await hsmConnectorService.assertAttachPermission(actor, requireHsmConnectorId(input), projectId);+ },++ 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+ };+ },++ describeKey: async ({ reference }) => ({+ hsmConnectorId: reference.hsmConnectorId ?? undefined,+ hsmKeyLabel: reference.externalKeyId ?? undefined+ }),++ 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" });+ }++ 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+ })+ });+ }+});diff --git a/backend/src/services/certificate-authority/ca-signer.ts b/backend/src/services/certificate-authority/ca-signer.tsindex dff05bcdda..8f4493bc72 100644--- a/backend/src/services/certificate-authority/ca-signer.ts+++ b/backend/src/services/certificate-authority/ca-signer.ts@@ -9,9 +9,10 @@ import { BadRequestError } from "@app/lib/errors";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";import { HsmKeyAlgorithm } from "@app/services/signer/signer-enums";-// @peculiar/x509's generators require a local CryptoKey, so for HSM-backed CAs we build the-// structure with a throwaway key of the matching algorithm, then swap in a signature the HSM-// produces over the TBS bytes (same pattern as build-csr-with-external-signer).+// @peculiar/x509's generators require a local CryptoKey, so for CAs whose key lives outside+// Infisical (HSM, AWS KMS) we build the structure with a throwaway key of the matching algorithm,+// then swap in a signature the key holder produces over the TBS bytes (same pattern as+// build-csr-with-external-signer).type TCertCreateParams = Parameters<typeof x509.X509CertificateGenerator.create>[0];type TCsrCreateParams = Parameters<typeof x509.Pkcs10CertificateRequestGenerator.create>[0];@@ -141,11 +142,60 @@ const HSM_MECHANISM_BY_HASH: Record<"rsa" | "ecdsa", Record<string, string>> = {}};-const algorithmHashName = (alg: Algorithm): string | undefined => {+export const algorithmHashName = (alg: Algorithm): string | undefined => {const { hash } = alg as { hash?: string | { name?: string } };return typeof hash === "string" ? hash : hash?.name;};+export const buildExternalCaSigner = ({+ caPublicKey,+ signingAlgorithm,+ generateEphemeralKey,+ signTbs+}: {+ caPublicKey: CryptoKey;+ signingAlgorithm: Algorithm;+ generateEphemeralKey: () => Promise<CryptoKeyPair>;+ signTbs: (tbs: Buffer) => Promise<ArrayBuffer>;+}): TCaSigner => ({+ caPublicKey,+ signingAlgorithm,+ createCertificate: async (params) => {+ const ephemeral = await generateEphemeralKey();+ const built = await x509.X509CertificateGenerator.create({+ ...params,+ signingKey: ephemeral.privateKey,+ signingAlgorithm+ });+ const cert = AsnConvert.parse(built.rawData, Certificate);+ cert.signatureValue = await signTbs(Buffer.from(AsnConvert.serialize(cert.tbsCertificate)));+ return new x509.X509Certificate(AsnConvert.serialize(cert));+ },+ createCsr: async (params) => {+ const ephemeral = await generateEphemeralKey();+ const built = await x509.Pkcs10CertificateRequestGenerator.create({+ ...params,+ keys: { privateKey: ephemeral.privateKey, publicKey: caPublicKey },+ signingAlgorithm+ });+ const csr = AsnConvert.parse(built.rawData, CertificationRequest);+ csr.signature = await signTbs(Buffer.from(AsnConvert.serialize(csr.certificationRequestInfo)));+ return new x509.Pkcs10CertificateRequest(AsnConvert.serialize(csr));+ },+ createCrl: async (params) => {+ const ephemeral = await generateEphemeralKey();+ const built = await x509.X509CrlGenerator.create({+ ...params,+ signingKey: ephemeral.privateKey,+ signingAlgorithm+ });+ const crl = AsnConvert.parse(built.rawData, CertificateList);+ crl.signature = await signTbs(Buffer.from(AsnConvert.serialize(crl.tbsCertList)));+ return new x509.X509Crl(AsnConvert.serialize(crl));+ },+ signTbs+});+export const buildHsmCaSigner = ({caPublicKey,keyAlgorithm,@@ -187,45 +237,11 @@ export const buildHsmCaSigner = ({return bufferToArrayBuffer(signature);};- const generateEphemeralKey = () =>- crypto.nativeCrypto.subtle.generateKey(keyGenParams as RsaHashedKeyGenParams, true, ["sign", "verify"]);-- return {+ return buildExternalCaSigner({caPublicKey,signingAlgorithm: certSigningAlgorithm,- createCertificate: async (params) => {- const ephemeral = await generateEphemeralKey();- const built = await x509.X509CertificateGenerator.create({- ...params,- signingKey: ephemeral.privateKey,- signingAlgorithm: certSigningAlgorithm- });- const cert = AsnConvert.parse(built.rawData, Certificate);- cert.signatureValue = await signTbs(Buffer.from(AsnConvert.serialize(cert.tbsCertificate)));- return new x509.X509Certificate(AsnConvert.serialize(cert));- },- createCsr: async (params) => {- const ephemeral = await generateEphemeralKey();- const built = await x509.Pkcs10CertificateRequestGenerator.create({- ...params,- keys: { privateKey: ephemeral.privateKey, publicKey: caPublicKey },- signingAlgorithm: certSigningAlgorithm- });- const csr = AsnConvert.parse(built.rawData, CertificationRequest);- csr.signature = await signTbs(Buffer.from(AsnConvert.serialize(csr.certificationRequestInfo)));- return new x509.Pkcs10CertificateRequest(AsnConvert.serialize(csr));- },- createCrl: async (params) => {- const ephemeral = await generateEphemeralKey();- const built = await x509.X509CrlGenerator.create({- ...params,- signingKey: ephemeral.privateKey,- signingAlgorithm: certSigningAlgorithm- });- const crl = AsnConvert.parse(built.rawData, CertificateList);- crl.signature = await signTbs(Buffer.from(AsnConvert.serialize(crl.tbsCertList)));- return new x509.X509Crl(AsnConvert.serialize(crl));- },+ generateEphemeralKey: () =>+ 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.tsindex 942904653b..e1b3013010 100644--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts@@ -7,13 +7,16 @@ import { derivePublicKeyFromSecret, getPqcCrypto, isPqcAlgorithm, PqcCryptoKey }import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";-import { CertKeySource } from "@app/services/signer/signer-enums";import { CertKeyAlgorithm, CertStatus } from "../certificate/certificate-types";import { CERT_CLOCK_SKEW_MS, DEFAULT_CRL_VALIDITY_DAYS } from "../certificate-common/certificate-constants";import { TCertificateProfileDALFactory } from "../certificate-profile/certificate-profile-dal";-import { buildHsmCaSigner, buildLocalCaSigner, caKeyAlgorithmToHsmShape, TCaSigner } from "./ca-signer";+import { isExternalCaKeySource } from "./ca-key-source/ca-key-source-fns";+import type { TCaKeySourceServiceFactory } from "./ca-key-source/ca-key-source-service";+import { TCaKeyDetails } from "./ca-key-source/ca-key-source-types";+import { buildLocalCaSigner, TCaSigner } from "./ca-signer";import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";+import { TCertificateAuthoritySecretDALFactory } from "./certificate-authority-secret-dal";import {TDNParts,TGetCaCertChainDTO,@@ -352,7 +355,7 @@ export const getCaCredentials = async ({if (!caSecret) throw new NotFoundError({ message: `CA secret for CA with ID '${caId}' not found` });if (!caSecret.encryptedPrivateKey) {throw new BadRequestError({- message: `Certificate authority '${caId}' is HSM-backed; its signing key is not available locally.`+ message: `Certificate authority '${caId}' signs with a key held outside Infisical; its signing key is not available locally.`});}@@ -417,8 +420,8 @@ export const getCaCredentials = async ({/*** Return a signer for CA with id [caId] that abstracts over where the signing key lives.- * For locally-keyed CAs it decrypts the KMS-stored private key; for HSM-backed CAs it routes- * signing through the HSM Connector. Every issuance / renewal / CRL path uses this so the+ * For locally-keyed CAs it decrypts the KMS-stored private key; for CAs whose key lives outside+ * Infisical (HSM, AWS KMS) it routes signing through that key source. Every issuance / renewal / CRL path uses this so the* call sites never branch on key source.*/export const getCaSigner = async ({@@ -427,7 +430,7 @@ export const getCaSigner = async ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService,+ caKeySourceService,signatureAlgorithm,prefetched}: TGetCaSignerDTO): Promise<{@@ -442,35 +445,13 @@ export const getCaSigner = async ({const keyAlgorithm = ca.internalCa.keyAlgorithm as CertKeyAlgorithm;- if (caSecret.keySource === CertKeySource.Hsm) {- if (!caSecret.hsmConnectorId || !caSecret.hsmKeyLabel || !caSecret.hsmPublicKeySpki) {- throw new BadRequestError({ message: "HSM-backed CA secret is missing its connector, key label, or public key" });- }-- const shape = caKeyAlgorithmToHsmShape(keyAlgorithm);- const caPublicKey = await crypto.nativeCrypto.subtle.importKey(- "spki",- caSecret.hsmPublicKeySpki,- shape.importParams,- true,- ["verify"]- );-- const connectorId = caSecret.hsmConnectorId;- const keyLabel = caSecret.hsmKeyLabel;- const signer = buildHsmCaSigner({- caPublicKey,+ if (isExternalCaKeySource(caSecret.keySource)) {+ const signer = await caKeySourceService.buildSigner({+ keySource: caSecret.keySource,+ projectId: ca.projectId,keyAlgorithm,- signingAlgorithm: signatureAlgorithm,- sign: (data, mechanism, isDigest) =>- hsmConnectorService.sign({- connectorId,- projectId: ca.projectId,- keyLabel,- mechanism,- data,- isDigest- })+ reference: caSecret,+ signatureAlgorithm});return { caSecret, signer };@@ -593,7 +574,7 @@ export const rebuildCaCrl = async ({projectDAL,certificateDAL,kmsService,- hsmConnectorService+ caKeySourceService}: TRebuildCaCrlDTO) => {const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);if (!ca?.internalCa?.id) throw new NotFoundError({ message: `Internal CA with ID '${caId}' not found` });@@ -604,7 +585,7 @@ export const rebuildCaCrl = async ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const keyId = await getProjectKmsCertificateKeyId({@@ -745,3 +726,30 @@ 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 };+};++export const deleteCaAndReleaseExternalKey = async ({+ caId,+ certificateAuthorityDAL,+ certificateAuthoritySecretDAL,+ caKeySourceService+}: {+ caId: string;+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "deleteById">;+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "describeKey" | "prepareKeyReleases">;+}) => {+ const caSecret = await certificateAuthoritySecretDAL.findOne({ caId });+ const keyDetails = await caKeySourceService.describeKey(caSecret);+ const releaseKeys = await caKeySourceService.prepareKeyReleases(caSecret ? [caSecret] : []);++ await certificateAuthorityDAL.deleteById(caId).catch(rethrowCaDeleteError);+ await releaseKeys();++ return keyDetails;+};diff --git a/backend/src/services/certificate-authority/certificate-authority-queue.ts b/backend/src/services/certificate-authority/certificate-authority-queue.tsindex 995ad332f2..eae69b9014 100644--- a/backend/src/services/certificate-authority/certificate-authority-queue.ts+++ b/backend/src/services/certificate-authority/certificate-authority-queue.ts@@ -9,8 +9,8 @@ import { logger } from "@app/lib/logger";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { CertStatus } from "@app/services/certificate/certificate-types";+import type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";import { DEFAULT_CRL_VALIDITY_DAYS } from "@app/services/certificate-common/certificate-constants";-import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";@@ -56,7 +56,7 @@ type TCertificateAuthorityQueueFactoryDep = {pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById">;internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "find">;- hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};@@ -82,7 +82,7 @@ export const certificateAuthorityQueueFactory = ({pkiSyncDAL,pkiSyncQueue,internalCertificateAuthorityDAL,- hsmConnectorService,+ caKeySourceService,gatewayV2Service,gatewayPoolService}: TCertificateAuthorityQueueFactoryDep) => {@@ -173,7 +173,7 @@ export const certificateAuthorityQueueFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const revokedCerts = await certificateDAL.find({diff --git a/backend/src/services/certificate-authority/certificate-authority-secret-dal.ts b/backend/src/services/certificate-authority/certificate-authority-secret-dal.tsindex 2ade72e7e3..f5cd54ba5a 100644--- a/backend/src/services/certificate-authority/certificate-authority-secret-dal.ts+++ b/backend/src/services/certificate-authority/certificate-authority-secret-dal.ts@@ -1,10 +1,25 @@+import { Knex } from "knex";+import { TDbClient } from "@app/db";-import { TableName } from "@app/db/schemas";-import { ormify } from "@app/lib/knex";+import { TableName, TCertificateAuthoritySecret } from "@app/db/schemas";+import { ormify, selectAllTableCols } from "@app/lib/knex";+import { CertKeySource } from "@app/services/signer/signer-enums";export type TCertificateAuthoritySecretDALFactory = ReturnType<typeof certificateAuthoritySecretDALFactory>;export const certificateAuthoritySecretDALFactory = (db: TDbClient) => {const caSecretOrm = ormify(db, TableName.CertificateAuthoritySecret);- return caSecretOrm;++ const findExternallyKeyedByProjectId = async (projectId: string, tx?: Knex): Promise<TCertificateAuthoritySecret[]> =>+ (tx || db.replicaNode())(TableName.CertificateAuthoritySecret)+ .join(+ TableName.CertificateAuthority,+ `${TableName.CertificateAuthority}.id`,+ `${TableName.CertificateAuthoritySecret}.caId`+ )+ .where(`${TableName.CertificateAuthority}.projectId`, projectId)+ .whereNot(`${TableName.CertificateAuthoritySecret}.keySource`, CertKeySource.Infisical)+ .select(selectAllTableCols(TableName.CertificateAuthoritySecret));++ return { ...caSecretOrm, findExternallyKeyedByProjectId };};diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.tsindex a22cf5715b..923685e179 100644--- a/backend/src/services/certificate-authority/certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts@@ -16,7 +16,6 @@ import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utiimport { BadRequestError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor, TProjectPermission } from "@app/lib/types";import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";-import { CertKeySource } from "@app/services/signer/signer-enums";import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";import { TAppConnectionServiceFactory } from "../app-connection/app-connection-service";@@ -33,7 +32,6 @@ import {TAttachCertificateToRequestDTO,TUpdateCertificateRequestStatusDTO} from "../certificate-request/certificate-request-types";-import type { THsmConnectorServiceFactory } from "../hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "../kms/kms-service";import { InternalCas } from "../license-client";import { TUsageMeteringServiceFactory } from "../license-client/usage";@@ -84,9 +82,11 @@ import {TCreateAzureAdCsCertificateAuthorityDTO,TUpdateAzureAdCsCertificateAuthorityDTO} from "./azure-ad-cs/azure-ad-cs-certificate-authority-types";+import { isExternalCaKeySource } from "./ca-key-source/ca-key-source-fns";+import type { TCaKeySourceServiceFactory } from "./ca-key-source/ca-key-source-service";import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";import { CaType } from "./certificate-authority-enums";-import { assertNoCertificateProfilesUsingCa, rethrowCaDeleteError } from "./certificate-authority-fns";+import { assertNoCertificateProfilesUsingCa, deleteCaAndReleaseExternalKey } from "./certificate-authority-fns";import { CERTIFICATE_AUTHORITIES_TYPE_MAP } from "./certificate-authority-maps";import { assertCertificateAuthorityQuota, resolveEffectiveMaxCas } from "./certificate-authority-quota-fns";import { TCertificateAuthoritySecretDALFactory } from "./certificate-authority-secret-dal";@@ -169,7 +169,7 @@ type TCertificateAuthorityServiceFactoryDep = {gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;keyStore: Pick<TKeyStoreFactory, "acquireLock">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;- hsmConnectorService: Pick<THsmConnectorServiceFactory, "assertAttachPermission">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "assertCanUse" | "describeKey" | "prepareKeyReleases">;certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;@@ -203,7 +203,7 @@ export const certificateAuthorityServiceFactory = ({gatewayPoolService,keyStore,usageMeteringService,- hsmConnectorService,+ caKeySourceService,certificateAuthoritySecretDAL,licenseService,pkiAlertV2Queue,@@ -368,15 +368,13 @@ export const certificateAuthorityServiceFactory = ({if (type === CaType.INTERNAL) {const internalConfig = configuration as TCreateInternalCertificateAuthorityDTO["configuration"];- if (internalConfig.keySource === CertKeySource.Hsm) {- if (!internalConfig.hsmConnectorId) {- throw new BadRequestError({ message: "An HSM Connector is required when the key source is HSM." });- }- await hsmConnectorService.assertAttachPermission(- { type: actor.type, id: actor.id, authMethod: actor.authMethod, orgId: actor.orgId },- internalConfig.hsmConnectorId,- projectId- );+ if (isExternalCaKeySource(internalConfig.keySource)) {+ await caKeySourceService.assertCanUse({+ keySource: internalConfig.keySource,+ actor,+ projectId,+ input: internalConfig+ });}const ca = await internalCertificateAuthorityService.createCa({@@ -394,6 +392,8 @@ export const certificateAuthorityServiceFactory = ({usageMeteringService.emitForProject(projectId, InternalCas.key);+ const caSecret = await certificateAuthoritySecretDAL.findOne({ caId: ca.id });+return {id: ca.id,type,@@ -401,7 +401,7 @@ export const certificateAuthorityServiceFactory = ({name: ca.name,projectId,status,- configuration: ca.internalCa+ configuration: { ...ca.internalCa, ...(await caKeySourceService.describeKey(caSecret)) }} as TCertificateAuthority;}@@ -523,12 +523,7 @@ export const certificateAuthorityServiceFactory = ({subject: ProjectPermissionSub.CertificateAuthorities,name: certificateAuthority.name,projectId: certificateAuthority.projectId,- configuration: {- ...certificateAuthority.internalCa,- keySource: (caSecret?.keySource as CertKeySource | undefined) ?? CertKeySource.Infisical,- hsmConnectorId: caSecret?.hsmConnectorId ?? undefined,- hsmKeyLabel: caSecret?.hsmKeyLabel ?? undefined- },+ configuration: { ...certificateAuthority.internalCa, ...(await caKeySourceService.describeKey(caSecret)) },status: certificateAuthority.status} as TCertificateAuthority;}@@ -959,7 +954,12 @@ export const certificateAuthorityServiceFactory = ({await assertNoCertificateProfilesUsingCa(certificateProfileDAL, certificateAuthority.id, certificateAuthority.name);- await certificateAuthorityDAL.deleteById(certificateAuthority.id).catch(rethrowCaDeleteError);+ const keyDetails = await deleteCaAndReleaseExternalKey({+ caId: certificateAuthority.id,+ certificateAuthorityDAL,+ certificateAuthoritySecretDAL,+ caKeySourceService+ });if (type === CaType.INTERNAL) {usageMeteringService.emitForProject(certificateAuthority.projectId, InternalCas.key);@@ -969,7 +969,7 @@ export const certificateAuthorityServiceFactory = ({enableDirectIssuance: certificateAuthority.enableDirectIssuance,name: certificateAuthority.name,projectId: certificateAuthority.projectId,- configuration: certificateAuthority.internalCa,+ configuration: { ...certificateAuthority.internalCa, ...keyDetails },status: certificateAuthority.status} as TCertificateAuthority;}@@ -1193,7 +1193,12 @@ export const certificateAuthorityServiceFactory = ({await assertNoCertificateProfilesUsingCa(certificateProfileDAL, certificateAuthority.id, certificateAuthority.name);- await certificateAuthorityDAL.deleteById(certificateAuthority.id).catch(rethrowCaDeleteError);+ const keyDetails = await deleteCaAndReleaseExternalKey({+ caId: certificateAuthority.id,+ certificateAuthorityDAL,+ certificateAuthoritySecretDAL,+ caKeySourceService+ });if (type === CaType.INTERNAL) {usageMeteringService.emitForProject(certificateAuthority.projectId, InternalCas.key);@@ -1203,7 +1208,7 @@ export const certificateAuthorityServiceFactory = ({enableDirectIssuance: certificateAuthority.enableDirectIssuance,name: certificateAuthority.name,projectId: certificateAuthority.projectId,- configuration: certificateAuthority.internalCa,+ configuration: { ...certificateAuthority.internalCa, ...keyDetails },status: certificateAuthority.status} as TCertificateAuthority;}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.tsindex 7076b737ed..8de030dc29 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@@ -1,6 +1,7 @@import { z } from "zod";import { CertificateAuthorities } from "@app/lib/api-docs/constants";+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";import {PKI_TEXT_COLUMN_MAX_LENGTH,@@ -32,6 +33,10 @@ type TInternalCertificateAuthorityConfiguration = {keySource?: CertKeySource;hsmConnectorId?: string;hsmKeyLabel?: string;+ appConnectionId?: string;+ appConnectionName?: string;+ region?: AWSRegion;+ externalKeyId?: string;dn?: string | null;parentCaId?: string | null;serialNumber?: string | null;@@ -72,6 +77,14 @@ export const InternalCertificateAuthorityConfigurationSchema = z.optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.hsmConnectorId),hsmKeyLabel: z.string().optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.hsmKeyLabel),+ appConnectionId: z+ .string()+ .uuid()+ .optional()+ .describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.appConnectionId),+ appConnectionName: z.string().optional().describe(CertificateAuthorities.CONFIGURATIONS.INTERNAL.appConnectionName),+ 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(),parentCaId: z.string().uuid().nullish(),serialNumber: z.string().trim().nullish(),@@ -98,18 +111,30 @@ export const InternalCertificateAuthorityConfigurationSchema = z"At least one of the fields commonName, organization, ou, country, province, or locality must be non-empty",path: []}- ) as unknown as z.ZodType<TInternalCertificateAuthorityConfiguration>;+ )+ .refine((data) => data.keySource === CertKeySource.AwsKms || (!data.appConnectionId && !data.region), {+ message: "appConnectionId and region can only be set when keySource is 'aws-kms'",+ path: ["keySource"]+ })+ .refine((data) => data.keySource !== CertKeySource.AwsKms || !data.hsmConnectorId, {+ message: "hsmConnectorId cannot be set when keySource is 'aws-kms'",+ path: ["keySource"]+ }) as unknown as z.ZodType<TInternalCertificateAuthorityConfiguration>;export const InternalCertificateAuthoritySchema = BaseCertificateAuthoritySchema.extend({type: z.literal(CaType.INTERNAL),configuration: InternalCertificateAuthorityConfigurationSchema});-export const CreateInternalCertificateAuthoritySchema = GenericCreateCertificateAuthorityFieldsSchema(- CaType.INTERNAL-).extend({- configuration: InternalCertificateAuthorityConfigurationSchema-});+export const CreateInternalCertificateAuthoritySchema = GenericCreateCertificateAuthorityFieldsSchema(CaType.INTERNAL)+ .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"]+ });export const UpdateInternalCertificateAuthorityConfigurationSchema = z.object({crlDistributionPointUrls: distributionPointUrlsSchemadiff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.tsindex 330202938c..6f6187f2e9 100644--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts@@ -33,7 +33,6 @@ import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import { CERT_SUBJECT_ALTERNATIVE_NAMES } from "@app/services/certificate-common/certificate-constants";-import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { ActiveCerts, WildcardCerts } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";@@ -67,7 +66,10 @@ import { validatePqcLicense } from "../../certificate-common/certificate-utils";import { TCertificateProfileDALFactory } from "../../certificate-profile/certificate-profile-dal";import { TCertificateTemplateDALFactory } from "../../certificate-template/certificate-template-dal";import { validateCertificateDetailsAgainstTemplate } from "../../certificate-template/certificate-template-fns";-import { buildHsmCaSigner, buildLocalCaSigner, caKeyAlgorithmToHsmShape, TCaSigner } from "../ca-signer";+import { isExternalCaKeySource } from "../ca-key-source/ca-key-source-fns";+import type { TCaKeySourceServiceFactory } from "../ca-key-source/ca-key-source-service";+import { TExternalCaKeyReference } from "../ca-key-source/ca-key-source-types";+import { buildLocalCaSigner, TCaSigner } from "../ca-signer";import { TCaSigningConfigDALFactory } from "../ca-signing-config/ca-signing-config-dal";import { CaSigningConfigType } from "../ca-signing-config/ca-signing-config-enums";import { TCertificateAuthorityCertDALFactory } from "../certificate-authority-cert-dal";@@ -80,13 +82,13 @@ import {buildOcspResponderUrl,createDistinguishedName,createSerialNumber,+ deleteCaAndReleaseExternalKey,expandInternalCa,extractDnParts,getCaCertChain, // TODO: consider renamegetCaCertChains,getCaSigner,keyAlgorithmToAlgCfg,- rethrowCaDeleteError,signatureAlgorithmToAlgCfg,validateImportedCertificate} from "../certificate-authority-fns";@@ -152,9 +154,9 @@ type TInternalCertificateAuthorityServiceFactoryDep = {licenseService: Pick<TLicenseServiceFactory, "getPlan">;caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "create" | "deleteById" | "transaction">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;- hsmConnectorService: Pick<- THsmConnectorServiceFactory,- "generateKeyPair" | "sign" | "getPublicKey" | "assertAttachPermission"+ caKeySourceService: Pick<+ TCaKeySourceServiceFactory,+ "createKey" | "buildSigner" | "describeKey" | "prepareKeyReleases">;};@@ -179,7 +181,7 @@ export const internalCertificateAuthorityServiceFactory = ({licenseService,caSigningConfigDAL,usageMeteringService,- hsmConnectorService+ caKeySourceService}: TInternalCertificateAuthorityServiceFactoryDep) => {const $validatePqcLicense = (keyAlgorithm: string, projectId: string) =>validatePqcLicense({ keyAlgorithm, projectId, projectDAL, licenseService });@@ -422,250 +424,216 @@ export const internalCertificateAuthorityServiceFactory = ({const resolvedCaName = name || slugify(`${(friendlyName || dn).slice(0, 16)}-${alphaNumericNanoId(8)}`);- const keySource = dto.keySource ?? CertKeySource.Infisical;- const useHsm = keySource === CertKeySource.Hsm;+ const keySource = dto.isInternal ? (dto.keySource ?? CertKeySource.Infisical) : CertKeySource.Infisical;let caSigner: TCaSigner;let localKeys: CryptoKeyPair | undefined;- let hsmKey: { keyLabel: string; publicKeySpkiDer: Buffer } | undefined;+ let externalKeyReference: Partial<TExternalCaKeyReference> | undefined;- if (useHsm) {- if (!dto.hsmConnectorId) {- throw new BadRequestError({ message: "An HSM Connector is required when the key source is HSM." });- }- if (isPqcAlgorithm(keyAlgorithm)) {- throw new BadRequestError({- message: "Post-quantum algorithms are not supported for HSM-backed certificate authorities."- });- }- const shape = caKeyAlgorithmToHsmShape(keyAlgorithm);+ try {+ if (dto.isInternal && isExternalCaKeySource(keySource)) {+ // A duplicate name only fails the (name, projectId) unique constraint after the external key+ // is created. HSM keys cannot be removed again and AWS KMS keys can only be scheduled for+ // deletion, so reject a taken name before creating any key.+ if (name) {+ const existingCa = await certificateAuthorityDAL.findOne({ projectId, name });+ if (existingCa) {+ throw new BadRequestError({+ message: `A certificate authority named "${name}" already exists in this project.`+ });+ }+ }- if (!dto.isInternal) {- await hsmConnectorService.assertAttachPermission(- { type: dto.actor, id: dto.actorId, authMethod: dto.actorAuthMethod, orgId: dto.actorOrgId },- dto.hsmConnectorId,- projectId- );+ externalKeyReference = await caKeySourceService.createKey({+ keySource,+ projectId,+ caName: resolvedCaName,+ keyAlgorithm,+ input: dto+ });+ caSigner = await caKeySourceService.buildSigner({+ keySource,+ projectId,+ keyAlgorithm,+ reference: externalKeyReference+ });+ } else {+ const cryptoEngine = isPqcAlgorithm(keyAlgorithm) ? getPqcCrypto() : crypto.nativeCrypto;+ localKeys = await cryptoEngine.subtle.generateKey(alg as RsaHashedKeyGenParams, true, ["sign", "verify"]);+ caSigner = buildLocalCaSigner({+ privateKey: localKeys.privateKey,+ publicKey: localKeys.publicKey,+ signingAlgorithm: alg+ });}- // A duplicate name only fails the (name, projectId) unique constraint after the key is- // generated, and an HSM key cannot be auto-removed, so reject a taken name before keygen to- // avoid leaving an orphaned key on the HSM.- if (name) {- const existingCa = await certificateAuthorityDAL.findOne({ projectId, name });- if (existingCa) {- throw new BadRequestError({- message: `A certificate authority named "${name}" already exists in this project.`- });- }+ let notBeforeDate: Date | undefined;+ let notAfterDate: Date | undefined;+ if (notAfter) {+ notBeforeDate = notBefore ? new Date(notBefore) : new Date();+ // if undefined, set [notAfterDate] to 10 years from now+ notAfterDate = new Date(notAfter);}+ const serialNumber = createSerialNumber();- const generated = await hsmConnectorService.generateKeyPair({- connectorId: dto.hsmConnectorId,+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({projectId,- keyLabel: `ca-${resolvedCaName}-${alphaNumericNanoId(5)}`,- keyAlgorithm: shape.hsmKeyAlgorithm- });- hsmKey = generated;-- const caPublicKey = await crypto.nativeCrypto.subtle.importKey(- "spki",- generated.publicKeySpkiDer,- shape.importParams,- true,- ["verify"]- );- const connectorId = dto.hsmConnectorId;- const { keyLabel } = generated;- caSigner = buildHsmCaSigner({- caPublicKey,- keyAlgorithm,- sign: (data, mechanism, isDigest) =>- hsmConnectorService.sign({ connectorId, projectId, keyLabel, mechanism, data, isDigest })+ projectDAL,+ kmsService});- } else {- const cryptoEngine = isPqcAlgorithm(keyAlgorithm) ? getPqcCrypto() : crypto.nativeCrypto;- localKeys = await cryptoEngine.subtle.generateKey(alg as RsaHashedKeyGenParams, true, ["sign", "verify"]);- caSigner = buildLocalCaSigner({- privateKey: localKeys.privateKey,- publicKey: localKeys.publicKey,- signingAlgorithm: alg+ const kmsEncryptor = await kmsService.encryptWithKmsKey({+ kmsId: certificateManagerKmsId});- }- let notBeforeDate: Date | undefined;- let notAfterDate: Date | undefined;- if (notAfter) {- notBeforeDate = notBefore ? new Date(notBefore) : new Date();- // if undefined, set [notAfterDate] to 10 years from now- notAfterDate = new Date(notAfter);- }- const serialNumber = createSerialNumber();+ let encryptedPrivateKey: Buffer | undefined;+ if (localKeys) {+ const localPrivateKey = localKeys.privateKey;+ // https://nodejs.org/api/crypto.html#static-method-keyobjectfromkey+ let privateKeyDer: Buffer;+ if (isPqcCryptoKey(localPrivateKey)) {+ privateKeyDer = await exportPqcKeyToDer(localPrivateKey);+ } else {+ const skObj = crypto.nativeCrypto.KeyObject.from(localPrivateKey);+ privateKeyDer = skObj.export({ type: "pkcs8", format: "der" });+ }+ encryptedPrivateKey = (await kmsEncryptor({ plainText: privateKeyDer })).cipherTextBlob;+ }- const certificateManagerKmsId = await getProjectKmsCertificateKeyId({- projectId,- projectDAL,- kmsService- });- const kmsEncryptor = await kmsService.encryptWithKmsKey({- kmsId: certificateManagerKmsId- });+ let rootCertMaterial: { encryptedCertificate: Buffer; encryptedCertificateChain: Buffer } | undefined;+ if (type === InternalCaType.ROOT && notAfter) {+ const cert = await caSigner.createCertificate({+ subject: dn,+ issuer: dn,+ serialNumber,+ notBefore: notBeforeDate,+ notAfter: notAfterDate,+ publicKey: caSigner.caPublicKey,+ extensions: [+ new x509.BasicConstraintsExtension(+ true,+ maxPathLength === -1 || maxPathLength === null ? undefined : maxPathLength,+ true+ ),+ new x509.KeyUsagesExtension(+ isPqcAlgorithm(keyAlgorithm) ? PQC_ROOT_CA_KEY_USAGES : ROOT_CA_KEY_USAGES,+ true+ ),+ await x509.SubjectKeyIdentifierExtension.create(caSigner.caPublicKey)+ ]+ });- let encryptedPrivateKey: Buffer | undefined;- if (!useHsm) {- const localPrivateKey = (localKeys as CryptoKeyPair).privateKey;- // https://nodejs.org/api/crypto.html#static-method-keyobjectfromkey- let privateKeyDer: Buffer;- if (isPqcCryptoKey(localPrivateKey)) {- privateKeyDer = await exportPqcKeyToDer(localPrivateKey);- } else {- const skObj = crypto.nativeCrypto.KeyObject.from(localPrivateKey);- privateKeyDer = skObj.export({ type: "pkcs8", format: "der" });+ rootCertMaterial = {+ encryptedCertificate: (await kmsEncryptor({ plainText: Buffer.from(new Uint8Array(cert.rawData)) }))+ .cipherTextBlob,+ encryptedCertificateChain: (await kmsEncryptor({ plainText: Buffer.alloc(0) })).cipherTextBlob+ };}- encryptedPrivateKey = (await kmsEncryptor({ plainText: privateKeyDer })).cipherTextBlob;- }- let rootCertMaterial: { encryptedCertificate: Buffer; encryptedCertificateChain: Buffer } | undefined;- if (type === InternalCaType.ROOT && notAfter) {- const cert = await caSigner.createCertificate({- subject: dn,+ const thisUpdate = new Date();+ const nextUpdate = new Date(thisUpdate);+ nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);+ const crl = await caSigner.createCrl({issuer: dn,- serialNumber,- notBefore: notBeforeDate,- notAfter: notAfterDate,- publicKey: caSigner.caPublicKey,- extensions: [- new x509.BasicConstraintsExtension(- true,- maxPathLength === -1 || maxPathLength === null ? undefined : maxPathLength,- true- ),- new x509.KeyUsagesExtension(isPqcAlgorithm(keyAlgorithm) ? PQC_ROOT_CA_KEY_USAGES : ROOT_CA_KEY_USAGES, true),- await x509.SubjectKeyIdentifierExtension.create(caSigner.caPublicKey)- ]+ thisUpdate,+ nextUpdate,+ entries: []+ });+ const { cipherTextBlob: encryptedCrl } = await kmsEncryptor({+ plainText: Buffer.from(new Uint8Array(crl.rawData))});- rootCertMaterial = {- encryptedCertificate: (await kmsEncryptor({ plainText: Buffer.from(new Uint8Array(cert.rawData)) }))- .cipherTextBlob,- encryptedCertificateChain: (await kmsEncryptor({ plainText: Buffer.alloc(0) })).cipherTextBlob- };- }-- const thisUpdate = new Date();- const nextUpdate = new Date(thisUpdate);- nextUpdate.setDate(nextUpdate.getDate() + DEFAULT_CRL_VALIDITY_DAYS);- const crl = await caSigner.createCrl({- issuer: dn,- thisUpdate,- nextUpdate,- entries: []- });- const { cipherTextBlob: encryptedCrl } = await kmsEncryptor({- plainText: Buffer.from(new Uint8Array(crl.rawData))- });+ const newCa = await certificateAuthorityDAL.transaction(async (tx) => {+ const ca = await certificateAuthorityDAL+ .create(+ {+ projectId,+ name: resolvedCaName,+ status: notAfter && type === InternalCaType.ROOT ? CaStatus.ACTIVE : CaStatus.PENDING_CERTIFICATE,+ enableDirectIssuance: false+ },+ tx+ )+ .catch((error) => {+ // unique_violation: same CA name in the same project+ if (+ error instanceof DatabaseError &&+ (error.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation+ ) {+ throw new BadRequestError({+ message: `A certificate authority named "${resolvedCaName}" already exists.`+ });+ }+ throw error;+ });- const newCa = await certificateAuthorityDAL.transaction(async (tx) => {- const ca = await certificateAuthorityDAL- .create(+ const internalCa = await internalCertificateAuthorityDAL.create({- projectId,- name: resolvedCaName,- status: notAfter && type === InternalCaType.ROOT ? CaStatus.ACTIVE : CaStatus.PENDING_CERTIFICATE,- enableDirectIssuance: false+ caId: ca.id,+ type,+ organization,+ ou,+ country,+ province,+ locality,+ friendlyName: friendlyName || dn,+ commonName,+ dn,+ keyAlgorithm,+ crlDistributionPointUrls: crlDistributionPointUrls ?? [],+ disableManagedCrlDistributionPointUrl: disableManagedCrlDistributionPointUrl ?? false,+ isOcspEnabled: resolvedIsOcspEnabled,+ ...(type === InternalCaType.ROOT && {+ maxPathLength,+ ...(notAfter && {+ notBefore: notBeforeDate,+ notAfter: notAfterDate,+ serialNumber+ })+ })},tx- )- .catch((error) => {- // unique_violation: same CA name in the same project- if (- error instanceof DatabaseError &&- (error.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation- ) {- throw new BadRequestError({- message: `A certificate authority named "${resolvedCaName}" already exists.`- });- }- throw error;- });+ );- const internalCa = await internalCertificateAuthorityDAL.create(- {- caId: ca.id,- type,- organization,- ou,- country,- province,- locality,- friendlyName: friendlyName || dn,- commonName,- dn,- keyAlgorithm,- crlDistributionPointUrls: crlDistributionPointUrls ?? [],- disableManagedCrlDistributionPointUrl: disableManagedCrlDistributionPointUrl ?? false,- isOcspEnabled: resolvedIsOcspEnabled,- ...(type === InternalCaType.ROOT && {- maxPathLength,- ...(notAfter && {- notBefore: notBeforeDate,- notAfter: notAfterDate,- serialNumber- })- })- },- tx- );+ const caSecret = await certificateAuthoritySecretDAL.create(+ { caId: ca.id, keySource, encryptedPrivateKey, ...externalKeyReference },+ tx+ );- const caSecret =- useHsm && hsmKey- ? await certificateAuthoritySecretDAL.create(- {- caId: ca.id,- keySource: CertKeySource.Hsm,- hsmConnectorId: dto.hsmConnectorId,- hsmKeyLabel: hsmKey.keyLabel,- hsmPublicKeySpki: hsmKey.publicKeySpkiDer- },- tx- )- : await certificateAuthoritySecretDAL.create(- {- caId: ca.id,- keySource: CertKeySource.Infisical,- encryptedPrivateKey- },- tx- );-- if (rootCertMaterial) {- const caCert = await certificateAuthorityCertDAL.create(+ if (rootCertMaterial) {+ const caCert = await certificateAuthorityCertDAL.create(+ {+ caId: ca.id,+ encryptedCertificate: rootCertMaterial.encryptedCertificate,+ encryptedCertificateChain: rootCertMaterial.encryptedCertificateChain,+ version: 1,+ caSecretId: caSecret.id+ },+ tx+ );++ await internalCertificateAuthorityDAL.updateById(internalCa.id, { activeCaCertId: caCert.id }, tx);+ }++ await certificateAuthorityCrlDAL.create({caId: ca.id,- encryptedCertificate: rootCertMaterial.encryptedCertificate,- encryptedCertificateChain: rootCertMaterial.encryptedCertificateChain,- version: 1,+ encryptedCrl,caSecretId: caSecret.id},tx);- await internalCertificateAuthorityDAL.updateById(internalCa.id, { activeCaCertId: caCert.id }, tx);- }-- await certificateAuthorityCrlDAL.create(- {- caId: ca.id,- encryptedCrl,- caSecretId: caSecret.id- },- tx- );-- return certificateAuthorityDAL.findByIdWithAssociatedCa(ca.id, tx);- });+ return certificateAuthorityDAL.findByIdWithAssociatedCa(ca.id, tx);+ });- return expandInternalCa(newCa);+ return expandInternalCa(newCa);+ } catch (error) {+ if (externalKeyReference) {+ const releaseKey = await caKeySourceService.prepareKeyReleases([{ keySource, ...externalKeyReference }]);+ await releaseKey();+ }+ throw error;+ }};/**@@ -792,9 +760,14 @@ export const internalCertificateAuthorityServiceFactory = ({await assertNoCertificateProfilesUsingCa(certificateProfileDAL, ca.id, ca.name);- await certificateAuthorityDAL.deleteById(ca.id).catch(rethrowCaDeleteError);+ const keyDetails = await deleteCaAndReleaseExternalKey({+ caId: ca.id,+ certificateAuthorityDAL,+ certificateAuthoritySecretDAL,+ caKeySourceService+ });- return expandInternalCa(ca);+ return { ca: expandInternalCa(ca), keyDetails };};/**@@ -834,7 +807,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const effectivePathLength =@@ -924,7 +897,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const kmsDecryptor = await kmsService.decryptWithKmsKey({@@ -1026,7 +999,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});if (!parentCa.internalCa) {@@ -1538,7 +1511,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const serialNumber = createSerialNumber();@@ -1709,7 +1682,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const { caPublicKey } = signer;@@ -1828,7 +1801,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const caKeyAlg = intermediateCa.internalCa.keyAlgorithm as CertKeyAlgorithm;@@ -2100,7 +2073,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService,+ caKeySourceService,signatureAlgorithm: signingAlg});@@ -2529,7 +2502,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService,+ caKeySourceService,signatureAlgorithm: alg});@@ -2948,7 +2921,7 @@ export const internalCertificateAuthorityServiceFactory = ({certificateAuthoritySecretDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService});const rootKeyAlg = ca.internalCa.keyAlgorithm as CertKeyAlgorithm;diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.tsindex b44b1a60fe..d2b35d0a2f 100644--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts@@ -4,6 +4,7 @@ import { z } from "zod";import { TCertificates } from "@app/db/schemas";import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";import { TProjectPermission } from "@app/lib/types";+import { AWSRegion } from "@app/services/app-connection/app-connection-enums";import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";import {@@ -14,11 +15,11 @@ import {} from "@app/services/certificate/certificate-types";import { CertSubjectAlternativeNameType } from "@app/services/certificate-common/certificate-constants";import { TResolvedCustomExtension } from "@app/services/certificate-common/certificate-extension-fns";-import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";import { CertKeySource } from "@app/services/signer/signer-enums";+import type { TCaKeySourceServiceFactory } from "../ca-key-source/ca-key-source-service";import { TCertificateAuthorityCertDALFactory } from "../certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "../certificate-authority-dal";import { CaRenewalType, CaStatus, CaType, InternalCaType } from "../certificate-authority-enums";@@ -56,6 +57,8 @@ export type TCreateCaDTO =keyAlgorithm: CertKeyAlgorithm;keySource?: CertKeySource;hsmConnectorId?: string;+ appConnectionId?: string;+ region?: AWSRegion;crlDistributionPointUrls?: string[];disableManagedCrlDistributionPointUrl?: boolean;isOcspEnabled?: boolean;@@ -77,8 +80,6 @@ export type TCreateCaDTO =notAfter?: string;maxPathLength?: number | null;keyAlgorithm: CertKeyAlgorithm;- keySource?: CertKeySource;- hsmConnectorId?: string;crlDistributionPointUrls?: string[];disableManagedCrlDistributionPointUrl?: boolean;isOcspEnabled?: boolean;@@ -358,7 +359,7 @@ export type TGetCaSignerDTO = {certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;- hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;signatureAlgorithm?: RsaHashedImportParams | EcKeyImportParams;prefetched?: { kmsKeyId?: string };};@@ -387,7 +388,7 @@ export type TRebuildCaCrlDTO = {projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;certificateDAL: Pick<TCertificateDALFactory, "find">;kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "decryptWithKmsKey" | "encryptWithKmsKey">;- hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;};export type TRotateCaCrlTriggerDTO = {diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.tsindex a797b732a9..3961c17721 100644--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts@@ -293,7 +293,7 @@ describe("CertificateProfileService", () => {certificateAuthorityDAL: mockCertificateAuthorityDAL,certificateAuthoritySecretDAL: { findOne: vi.fn() } as never,certificateAuthorityCertDAL: { find: vi.fn() } as never,- hsmConnectorService: {} as never,+ caKeySourceService: {} as never,externalCertificateAuthorityDAL: mockExternalCertificateAuthorityDAL,permissionService: mockPermissionService,kmsService: mockKmsService,diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.tsindex aa53530708..7c56c1c92d 100644--- a/backend/src/services/certificate-profile/certificate-profile-service.ts+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts@@ -28,6 +28,7 @@ import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal"import { getCertificateCredentials, isCertChainValid } from "../certificate/certificate-fns";import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";import { CertStatus } from "../certificate/certificate-types";+import type { TCaKeySourceServiceFactory } from "../certificate-authority/ca-key-source/ca-key-source-service";import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";import { CaCapability, CaType } from "../certificate-authority/certificate-authority-enums";@@ -61,7 +62,6 @@ import {} from "../enrollment-config/enrollment-config-types";import { TEstEnrollmentConfigDALFactory } from "../enrollment-config/est-enrollment-config-dal";import { TScepEnrollmentConfigDALFactory } from "../enrollment-config/scep-enrollment-config-dal";-import { THsmConnectorServiceFactory } from "../hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "../kms/kms-service";import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";import { TProjectDALFactory } from "../project/project-dal";@@ -337,7 +337,7 @@ type TCertificateProfileServiceFactoryDep = {certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find">;- hsmConnectorService: THsmConnectorServiceFactory;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "findById" | "findOne">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;@@ -401,7 +401,7 @@ export const certificateProfileServiceFactory = ({certificateAuthorityDAL,certificateAuthoritySecretDAL,certificateAuthorityCertDAL,- hsmConnectorService,+ caKeySourceService,externalCertificateAuthorityDAL,permissionService,kmsService,@@ -631,7 +631,7 @@ export const certificateProfileServiceFactory = ({certificateAuthorityCertDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService}});diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex 6a8c419466..428f319a75 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -331,6 +331,11 @@ describe("CertificateV3Service", () => {certificatePolicyService: mockCertificatePolicyService,acmeAccountDAL: mockAcmeAccountDAL,internalCaService: mockInternalCaService,+ caKeySourceService: {+ resolveCsrSignatureAlgorithm: vi.fn(+ async ({ csrSignatureAlgorithm }: { csrSignatureAlgorithm?: string }) => csrSignatureAlgorithm+ )+ },permissionService: mockPermissionService,certificateSyncDAL: {findPkiSyncIdsByCertificateId: vi.fn().mockResolvedValue([]),diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex c5463bbd9d..ecfbbcadab 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -41,6 +41,7 @@ import { TCertificateSecretDALFactory } from "@app/services/certificate/certificimport { CertKeyAlgorithm, CertSignatureAlgorithm } from "@app/services/certificate/certificate-types";import { validateAcmIssuanceInputs } from "@app/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns";import { validateAwsPcaCaIssuanceInputs } from "@app/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators";+import type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";import { assertCaInProfileProject } from "@app/services/certificate-authority/certificate-authority-fns";@@ -159,6 +160,7 @@ type TCertificateV3ServiceFactoryDep = {"validateCertificateRequest" | "validateRequestAgainstPolicy" | "getPolicyById">;internalCaService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa" | "issueCertFromCa">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "resolveCsrSignatureAlgorithm">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;certificateSyncDAL: Pick<TCertificateSyncDALFactory,@@ -346,6 +348,7 @@ export const certificateV3ServiceFactory = ({acmeAccountDAL,certificatePolicyService,internalCaService,+ caKeySourceService,permissionService,certificateSyncDAL,pkiSyncDAL,@@ -1419,8 +1422,17 @@ export const certificateV3ServiceFactory = ({const certificateRequest = applyProfileDefaults(csrCertificateRequest, profile.defaults);const mappedCertificateRequest = mapEnumsForValidation(certificateRequest);- const { keyAlgorithm: extractedKeyAlgorithm, signatureAlgorithm: extractedSignatureAlgorithm } =+ const { keyAlgorithm: extractedKeyAlgorithm, signatureAlgorithm: csrSignatureAlgorithm } =extractAlgorithmsFromCSR(csr);+ const extractedSignatureAlgorithm = (+ ca.internalCa+ ? await caKeySourceService.resolveCsrSignatureAlgorithm({+ caId: ca.id,+ keyAlgorithm: ca.internalCa.keyAlgorithm as CertKeyAlgorithm,+ csrSignatureAlgorithm+ })+ : csrSignatureAlgorithm+ ) as typeof csrSignatureAlgorithm;mappedCertificateRequest.keyAlgorithm = extractedKeyAlgorithm;mappedCertificateRequest.signatureAlgorithm = extractedSignatureAlgorithm;diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.tsindex ad0ed1073f..7636f33afe 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -340,7 +340,7 @@ const RSA_SIGNATURE_ALGORITHMS: Record<string, CertSignatureAlgorithm> = {"SHA-512": CertSignatureAlgorithm.RSA_SHA512};-const ECDSA_SIGNATURE_ALGORITHMS: Record<string, CertSignatureAlgorithm> = {+export const ECDSA_SIGNATURE_ALGORITHMS: Record<string, CertSignatureAlgorithm> = {"SHA-256": CertSignatureAlgorithm.ECDSA_SHA256,"SHA-384": CertSignatureAlgorithm.ECDSA_SHA384,"SHA-512": CertSignatureAlgorithm.ECDSA_SHA512diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex d79fa8f7e5..10e82e324e 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -27,6 +27,7 @@ import {} from "@app/services/certificate/certificate-alert-events";import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";+import type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";import { CaCapability, CaType } from "@app/services/certificate-authority/certificate-authority-enums";@@ -48,7 +49,6 @@ import { TCertificateProfileDALFactory } from "@app/services/certificate-profileimport { IssuerType } from "@app/services/certificate-profile/certificate-profile-types";import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";-import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { ActiveCerts, WildcardCerts } from "@app/services/license-client";import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";@@ -166,7 +166,7 @@ type TCertificateServiceFactoryDep = {>;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;- hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "update">;};@@ -203,7 +203,7 @@ export const certificateServiceFactory = ({usageCounterDAL,keyStore,usageMeteringService,- hsmConnectorService,+ caKeySourceService,internalCertificateAuthorityDAL}: TCertificateServiceFactoryDep) => {const $canActOnCertViaApplication = async (@@ -804,7 +804,7 @@ export const certificateServiceFactory = ({projectDAL,certificateDAL,kmsService,- hsmConnectorService+ caKeySourceService});}diff --git a/backend/src/services/hsm-connector/hsm-connector-dal.ts b/backend/src/services/hsm-connector/hsm-connector-dal.tsindex 2e6d180d01..039ac12137 100644--- a/backend/src/services/hsm-connector/hsm-connector-dal.ts+++ b/backend/src/services/hsm-connector/hsm-connector-dal.ts@@ -88,7 +88,7 @@ export const hsmConnectorDALFactory = (db: TDbClient) => {db.ref("status").withSchema(TableName.CertificateAuthority).as("status"),db.ref("type").withSchema(TableName.InternalCertificateAuthority).as("type"),db.ref("commonName").withSchema(TableName.InternalCertificateAuthority).as("commonName"),- db.ref("hsmKeyLabel").withSchema(TableName.CertificateAuthoritySecret).as("hsmKeyLabel"),+ db.ref("externalKeyId").withSchema(TableName.CertificateAuthoritySecret).as("hsmKeyLabel"),db.ref("createdAt").withSchema(TableName.CertificateAuthority).as("createdAt")).orderBy(`${TableName.CertificateAuthority}.createdAt`, "desc")diff --git a/backend/src/services/license-client/feature-mapping.ts b/backend/src/services/license-client/feature-mapping.tsindex 5a7ec25d36..5d6d8a6085 100644--- a/backend/src/services/license-client/feature-mapping.ts+++ b/backend/src/services/license-client/feature-mapping.ts@@ -254,6 +254,10 @@ const certManagerMappings: TFeatureMapping[] = [v2Key: "pki_ocsp",v1Field: "pkiOcsp"},+ {+ v2Key: "pki_aws_kms_signing",+ v1Field: "pkiAwsKmsSigning"+ },{v2Key: "pki_est",v1Field: "pkiEst"diff --git a/backend/src/services/pki-application/pki-application-enrollment-service.ts b/backend/src/services/pki-application/pki-application-enrollment-service.tsindex 4b83418462..035dcbc722 100644--- a/backend/src/services/pki-application/pki-application-enrollment-service.ts+++ b/backend/src/services/pki-application/pki-application-enrollment-service.ts@@ -23,6 +23,7 @@ import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-cimport { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";import { TCertRequestPolicy } from "@app/services/approval-policy/cert-request/cert-request-policy-types";+import type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";@@ -37,7 +38,6 @@ import { TAcmeEnrollmentConfigDALFactory } from "@app/services/enrollment-configimport { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";import { TEstEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";-import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TProjectDALFactory } from "@app/services/project/project-dal";import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";@@ -117,7 +117,7 @@ type TPkiApplicationEnrollmentServiceFactoryDep = {certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find">;- hsmConnectorService: THsmConnectorServiceFactory;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "buildSigner">;kmsService: Pick<TKmsServiceFactory,"generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey" | "createCipherPairWithDataKey"@@ -142,7 +142,7 @@ export const pkiApplicationEnrollmentServiceFactory = ({certificateAuthorityDAL,certificateAuthoritySecretDAL,certificateAuthorityCertDAL,- hsmConnectorService,+ caKeySourceService,kmsService,projectDAL,permissionService@@ -804,7 +804,7 @@ export const pkiApplicationEnrollmentServiceFactory = ({certificateAuthorityCertDAL,projectDAL,kmsService,- hsmConnectorService+ caKeySourceService}});}diff --git a/backend/src/services/project/project-cleanup-queue.ts b/backend/src/services/project/project-cleanup-queue.tsindex 9110a24db7..7c9bc1e354 100644--- a/backend/src/services/project/project-cleanup-queue.ts+++ b/backend/src/services/project/project-cleanup-queue.ts@@ -8,6 +8,8 @@ import { resolveCoreMeter } from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { ActorType } from "../auth/auth-type";+import { TCaKeySourceServiceFactory } from "../certificate-authority/ca-key-source/ca-key-source-service";+import { TCertificateAuthoritySecretDALFactory } from "../certificate-authority/certificate-authority-secret-dal";import { TKmsServiceFactory } from "../kms/kms-service";import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";import { TUserDALFactory } from "../user/user-dal";@@ -57,6 +59,8 @@ type TProjectCleanupQueueFactoryDep = {membershipUserDAL: Pick<TMembershipUserDALFactory, "delete">;userDAL: Pick<TUserDALFactory, "deleteById">;kmsService: Pick<TKmsServiceFactory, "deleteInternalKms">;+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findExternallyKeyedByProjectId">;+ caKeySourceService: Pick<TCaKeySourceServiceFactory, "prepareKeyReleases">;keyStore: Pick<TKeyStoreFactory, "acquireLock" | "deleteItem">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;queueService: Pick<TQueueServiceFactory, "queue" | "start">;@@ -70,6 +74,8 @@ export const projectCleanupQueueFactory = ({membershipUserDAL,userDAL,kmsService,+ certificateAuthoritySecretDAL,+ caKeySourceService,keyStore,auditLogService,queueService,@@ -177,6 +183,10 @@ export const projectCleanupQueueFactory = ({return;}+ const releaseCaKeys = await caKeySourceService.prepareKeyReleases(+ await certificateAuthoritySecretDAL.findExternallyKeyedByProjectId(projectId)+ );+// 4) Final cascade in one transaction — handles the remaining (smaller) child tables, including// deferred / NO ACTION FKs (e.g. secret_rotation_v2_secret_mappings) that PG resolves correctly// as a single cascade tree (the same proven path the synchronous delete used).@@ -221,6 +231,7 @@ export const projectCleanupQueueFactory = ({return;}+ await releaseCaKeys();await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(project.orgId));await auditLogService.createAuditLog({orgId: project.orgId,diff --git a/backend/src/services/signer/signer-enums.ts b/backend/src/services/signer/signer-enums.tsindex 20291f0ece..349d16faca 100644--- a/backend/src/services/signer/signer-enums.ts+++ b/backend/src/services/signer/signer-enums.ts@@ -21,7 +21,8 @@ export enum SignerIssuanceJobStatus {export enum CertKeySource {Infisical = "infisical",- Hsm = "hsm"+ Hsm = "hsm",+ AwsKms = "aws-kms"}export enum HsmKeyAlgorithm {diff --git a/docs/documentation/platform/pki/ca/private-ca.mdx b/docs/documentation/platform/pki/ca/private-ca.mdxindex f1d62b88a2..ba27033d3e 100644--- a/docs/documentation/platform/pki/ca/private-ca.mdx+++ b/docs/documentation/platform/pki/ca/private-ca.mdx@@ -46,8 +46,10 @@ Create a simple Private CA hierarchy with a root CA and intermediate CA.- Valid Until: The date until which the CA is valid in the date time string format specified [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format). For example, the following formats would be valid: `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, `YYYY-MM-DDTHH:mm:ss.sssZ`.- Path Length: The maximum number of intermediate CAs that can be chained to this CA. A path of `-1` implies no limit; a path of `0` implies no intermediate CAs can be chained.- Key Algorithm: The type of public key algorithm and size, in bits, of the key pair that the CA creates when it issues a certificate. Supported key algorithms are `RSA 2048`, `RSA 4096`, `ECDSA P-256`, and `ECDSA P-384` with the default being `RSA 2048`.- - Key Source: Where the CA's signing key is generated and stored. **Infisical** (the default) generates and manages the key for you. **HSM** generates the key inside your own Hardware Security Module through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors), and every signing operation the CA performs runs on the HSM. See [HSM-backed Internal CAs](#hsm-backed-internal-cas) below.+ - Key Source: Where the CA's signing key is generated and stored. **Infisical** (the default) generates and manages the key for you. **HSM** generates the key inside your own Hardware Security Module through an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors), and every signing operation the CA performs runs on the HSM. See [HSM-backed Internal CAs](#hsm-backed-internal-cas) below. **AWS KMS** creates the key in your AWS account, and every signing operation runs in [AWS KMS](#aws-kms-backed-internal-cas).- HSM Connector: The [HSM Connector](/documentation/platform/pki/settings/hsm-connectors) Infisical uses to reach your HSM. Shown only when **Key Source** is **HSM**. With an HSM key source the algorithm choices stay limited to `RSA 2048`, `RSA 4096`, `ECDSA P-256`, and `ECDSA P-384`.+ - AWS Connection: The [AWS connection](/integrations/app-connections/aws) used to create the key and sign with it. Shown only when **Key Source** is **AWS KMS**.+ - Region: The AWS region to create the key in. Shown only when **Key Source** is **AWS KMS**.- Name: A slug-friendly name for the CA.- Organization (O): The organization name.- Country (C): The country code.@@ -279,6 +281,71 @@ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca}'```+## AWS KMS-backed internal CAs++If your CA's private key must stay in AWS and you don't run your own HSM, set **Key Source** to **AWS KMS**. The CA's signing key is then created in AWS KMS through an [AWS connection](/integrations/app-connections/aws), and the private key never leaves AWS KMS. AWS KMS signs everything the CA produces: the self-signed root certificate, intermediate CSRs, the certificates the CA issues, its CRLs, and its OCSP responses.++Both root and intermediate CAs can be AWS KMS-backed. They support the `RSA 2048`, `RSA 3072`, `RSA 4096`, `ECDSA P-256`, `ECDSA P-384`, `ECDSA P-521`, `ML-DSA-44`, `ML-DSA-65`, and `ML-DSA-87` key algorithms.++### Prerequisites++- An [AWS connection](/integrations/app-connections/aws) available to Certificate Manager+- An IAM policy on the connection's IAM role or user that lets the connection create KMS keys and sign with them:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": ["kms:CreateKey", "kms:TagResource"],+ "Resource": "*"+ },+ {+ "Effect": "Allow",+ "Action": ["kms:GetPublicKey", "kms:Sign", "kms:ScheduleKeyDeletion"],+ "Resource": "*",+ "Condition": {+ "StringEquals": { "aws:ResourceTag/purpose": "certificate-authority" }+ }+ }+ ]+}+```++Each CA signing key is created with the `author=infisical` and `purpose=certificate-authority` tags, so the second statement only allows signing with and deleting keys created for CAs.++### Create the CA++In the **Create Internal CA** wizard, set **Key Source** to **AWS KMS**, then choose the **AWS Connection**, the **Region**, and the **Key Algorithm**. The CA's details page shows the key's ARN once the CA is created.++To create the CA over the API instead, call [the endpoint to create an internal CA](/api-reference/endpoints/certificate-authorities/internal/create) with `keySource` set to `aws-kms`, and include the `appConnectionId` and `region`:++```bash Request+curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca/internal' \+ --header 'Authorization: Bearer <access-token>' \+ --header 'Content-Type: application/json' \+ --data-raw '{+ "name": "kms-root-ca",+ "status": "active",+ "configuration": {+ "type": "root",+ "commonName": "My AWS KMS Root CA",+ "keyAlgorithm": "EC_secp384r1",+ "keySource": "aws-kms",+ "appConnectionId": "<aws-connection-id>",+ "region": "us-east-1",+ "notAfter": "2036-01-01"+ }+ }'+```++The response returns the key's ARN in `configuration.externalKeyId`.++### Deleting an AWS KMS-backed CA++Deleting the CA schedules its key for deletion in AWS KMS with a 30-day waiting period. If you still need the key, [cancel the deletion](https://docs.aws.amazon.com/kms/latest/developerguide/deleting-keys.html) in AWS KMS within those 30 days, then enable the key again, because AWS KMS leaves a key disabled when you cancel its deletion.+## FAQ<AccordionGroup>@@ -291,6 +358,9 @@ curl --location --request POST 'https://app.infisical.com/api/v1/cert-manager/ca<Accordion title="Can the CA signing key be kept in my own HSM?">Yes. Set **Key Source** to **HSM** when creating the CA and pick an [HSM Connector](/documentation/platform/pki/settings/hsm-connectors). The keypair is generated on your HSM and every signing operation the CA performs runs there. Both root and intermediate CAs support this. Supported algorithms are `RSA 2048`, `RSA 4096`, `ECDSA P-256`, and `ECDSA P-384`. See [HSM-backed Internal CAs](#hsm-backed-internal-cas).</Accordion>+ <Accordion title="Can the CA signing key be kept in AWS KMS?">+ Yes, including post-quantum ML-DSA keys. Set **Key Source** to **AWS KMS** and [create the CA through an AWS connection](#aws-kms-backed-internal-cas).+ </Accordion></AccordionGroup>## What's next?diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.tsindex 103bd8afa7..d6b166b728 100644--- a/frontend/src/hooks/api/ca/types.ts+++ b/frontend/src/hooks/api/ca/types.ts@@ -160,6 +160,10 @@ export type TInternalCertificateAuthority = {keySource?: CertKeySource;hsmConnectorId?: string;hsmKeyLabel?: string;+ appConnectionId?: string;+ appConnectionName?: string;+ region?: string;+ externalKeyId?: string;notAfter?: string;notBefore?: string;dn?: string;diff --git a/frontend/src/hooks/api/signers/types.ts b/frontend/src/hooks/api/signers/types.tsindex 5c011151c0..80663c5893 100644--- a/frontend/src/hooks/api/signers/types.ts+++ b/frontend/src/hooks/api/signers/types.ts@@ -34,7 +34,8 @@ export enum SignerKeyAlgorithm {export enum CertKeySource {Infisical = "infisical",- Hsm = "hsm"+ Hsm = "hsm",+ AwsKms = "aws-kms"}export const HSM_SUPPORTED_KEY_ALGORITHMS: readonly SignerKeyAlgorithm[] = [diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.tsindex 215fe04cdf..3108ec6dc2 100644--- a/frontend/src/hooks/api/subscriptions/types.ts+++ b/frontend/src/hooks/api/subscriptions/types.ts@@ -74,6 +74,7 @@ export type SubscriptionPlan = {pkiPqc: boolean;caCrl: boolean;pkiOcsp: boolean;+ pkiAwsKmsSigning: boolean;pkiEnterpriseCaIntegrations: boolean;pkiExternalIntermediateCa: boolean;pkiDiscovery: boolean;diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsxindex 05f68a2cd9..dc0ad1404d 100644--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx@@ -68,6 +68,12 @@ type Props = {caId: string;};+const KEY_SOURCE_LABELS: Record<CertKeySource, string> = {+ [CertKeySource.Infisical]: "Infisical",+ [CertKeySource.Hsm]: "HSM",+ [CertKeySource.AwsKms]: "AWS KMS"+};+const getStatusVariant = (status: CaStatus) => {switch (status) {case CaStatus.ACTIVE:@@ -95,6 +101,9 @@ export const CaDetailsSection = ({ caId }: Props) => {const [, isCopyingId, setCopyTextId] = useTimedReset<string>({initialState: "Copy ID to clipboard"});+ const [, isCopyingKeyArn, setCopyTextKeyArn] = useTimedReset<string>({+ initialState: "Copy ARN to clipboard"+ });const { popUp, handlePopUpToggle } = usePopUp(["editAutoRenewal"] as const);const { data } = useGetCa({@@ -119,6 +128,8 @@ export const CaDetailsSection = ({ caId }: Props) => {enabled: Boolean(isHsmBacked && ca?.configuration?.hsmConnectorId)});+ const isAwsKmsBacked = ca?.configuration?.keySource === CertKeySource.AwsKms;+const { data: autoRenewal } = useGetCaAutoRenewal(caId, {enabled:Boolean(caId) &&@@ -297,8 +308,8 @@ export const CaDetailsSection = ({ caId }: Props) => {<Detail><DetailLabel>Key Source</DetailLabel><DetailValue>- <Badge variant={isHsmBacked ? "info" : "neutral"}>- {isHsmBacked ? "HSM" : "Infisical"}+ <Badge variant={isHsmBacked || isAwsKmsBacked ? "info" : "neutral"}>+ {KEY_SOURCE_LABELS[ca.configuration.keySource ?? CertKeySource.Infisical]}</Badge></DetailValue></Detail>@@ -322,6 +333,55 @@ export const CaDetailsSection = ({ caId }: Props) => {</>)}+ {isAwsKmsBacked && (+ <>+ <Detail>+ <DetailLabel>AWS Connection</DetailLabel>+ <DetailValue className="break-all">+ {ca.configuration.appConnectionName ?? ca.configuration.appConnectionId ?? "-"}+ </DetailValue>+ </Detail>+ {ca.configuration.externalKeyId && (+ <>+ <Detail>+ <DetailLabel>Region</DetailLabel>+ <DetailValue>{ca.configuration.region ?? "-"}</DetailValue>+ </Detail>+ <Detail>+ <DetailLabel>Key ARN</DetailLabel>+ <DetailValue className="flex items-center gap-x-1">+ <span className="break-all">{ca.configuration.externalKeyId}</span>+ <Tooltip>+ <TooltipTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Copy key ARN"+ onClick={() => {+ navigator.clipboard.writeText(+ ca.configuration.externalKeyId as string+ );+ setCopyTextKeyArn("Copied");+ }}+ >+ {isCopyingKeyArn ? (+ <CheckIcon />+ ) : (+ <ClipboardListIcon className="text-label" />+ )}+ </IconButton>+ </TooltipTrigger>+ <TooltipContent>+ {isCopyingKeyArn ? "Copied" : "Copy ARN to clipboard"}+ </TooltipContent>+ </Tooltip>+ </DetailValue>+ </Detail>+ </>+ )}+ </>+ )}+{showAutoRenewal && (<><Detail>diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsxindex da9e893dd0..eaaec244cf 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx@@ -97,6 +97,10 @@ export const CaSection = () => {caPendingDelete?.configuration?.keySource === CertKeySource.Hsm? caPendingDelete?.configuration?.hsmKeyLabel: undefined;+ const pendingDeleteAwsKmsKeyArn =+ caPendingDelete?.configuration?.keySource === CertKeySource.AwsKms+ ? caPendingDelete?.configuration?.externalKeyId+ : undefined;const onRemoveCaSubmit = async (id: string) => {if (!currentProject?.slug) return;@@ -165,6 +169,10 @@ export const CaSection = () => {pendingDeleteHsmKeyLabel? ` This CA's key on the HSM (label: ${pendingDeleteHsmKeyLabel}) is not removed automatically and will remain as an orphaned key.`: ""+ }${+ pendingDeleteAwsKmsKeyArn+ ? ` Deleting this CA also schedules its signing key (${pendingDeleteAwsKmsKeyArn}) for deletion in AWS KMS. You can cancel that deletion in AWS KMS within 30 days.`+ : ""}`}onChange={(isOpen) => handlePopUpToggle("deleteCa", isOpen)}deleteKey="confirm"diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsxindex d605ad56c7..7f6de12840 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/CreateCaWizard.tsx@@ -16,7 +16,9 @@ import {StepperList,StepperStep} from "@app/components/v3";-import { useSubscription } from "@app/context";+import { useProject, useSubscription } from "@app/context";+import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";+import { AppConnection } from "@app/hooks/api/appConnections/enums";import { useCreateCa } from "@app/hooks/api/ca";import { CaStatus, CaType, InternalCaType } from "@app/hooks/api/ca/enums";import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";@@ -53,6 +55,8 @@ const DEFAULT_VALUES: CaWizardForm = {commonName: "",keySource: CertKeySource.Infisical,hsmConnectorId: null,+ appConnectionId: null,+ region: null,keyAlgorithm: CertKeyAlgorithm.ECDSA_P256,notAfter: getDateTenYearsFromToday(),maxPathLength: "-1",@@ -64,7 +68,15 @@ const DEFAULT_VALUES: CaWizardForm = {const STEP_FIELDS: (keyof CaWizardForm)[][] = [["name", "type"],["commonName", "organization", "ou", "country", "province", "locality"],- ["keySource", "hsmConnectorId", "keyAlgorithm", "notAfter", "maxPathLength"],+ [+ "keySource",+ "hsmConnectorId",+ "appConnectionId",+ "region",+ "keyAlgorithm",+ "notAfter",+ "maxPathLength"+ ],["crlDistributionPointUrls"]];@@ -82,6 +94,17 @@ export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {[hsmConnectors]);+ const { currentProject } = useProject();+ const { data: awsConnections = [], isPending: isAwsConnectionsLoading } =+ useListAvailableAppConnections(AppConnection.AWS, currentProject.id, {+ enabled: isOpen && Boolean(subscription?.pkiAwsKmsSigning)+ });++ const awsConnectionOptions = useMemo(+ () => awsConnections.map((c) => ({ id: c.id, name: c.name })),+ [awsConnections]+ );+const buildDefaultValues = (): CaWizardForm => ({...DEFAULT_VALUES,isOcspEnabled: Boolean(subscription?.pkiOcsp)@@ -124,6 +147,10 @@ export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {values.keySource === CertKeySource.Hsm? (values.hsmConnectorId ?? undefined): undefined,+ ...(values.keySource === CertKeySource.AwsKms && {+ appConnectionId: values.appConnectionId ?? undefined,+ region: values.region ?? undefined+ }),maxPathLength: Number(values.maxPathLength),...(isRoot ? { notAfter: values.notAfter } : {}),crlDistributionPointUrls: values.crlDistributionPointUrls.map(({ value }) => value),@@ -177,7 +204,7 @@ export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {</div><p className="text-sm leading-4 text-muted">A private Certificate Authority hosted by Infisical, with its signing key managed- by Infisical or kept in your HSM.+ by Infisical, kept in your HSM, or kept in AWS KMS.</p></div></div>@@ -223,6 +250,8 @@ export const CreateCaWizard = ({ isOpen, onOpenChange }: Props) => {form={form}hsmConnectorOptions={hsmConnectorOptions}isHsmConnectorsLoading={isHsmConnectorsLoading}+ awsConnectionOptions={awsConnectionOptions}+ isAwsConnectionsLoading={isAwsConnectionsLoading}/>)}{step === 3 && <DistributionStep form={form} />}diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsxindex c98331ad2b..6eaad180c3 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/KeyValidityStep.tsx@@ -1,9 +1,11 @@import { Controller, UseFormReturn } from "react-hook-form";+import { Link } from "@tanstack/react-router";import {PostQuantumCertificatesUpgradeIntent,useUpgradeGate} from "@app/components/license/UpgradeGate";+import { AwsRegionSelect } from "@app/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect";import {Badge,Field,@@ -20,7 +22,7 @@ import {SelectTrigger,SelectValue} from "@app/components/v3";-import { useProjectPermission, useSubscription } from "@app/context";+import { useOrganization, useProject, useProjectPermission, useSubscription } from "@app/context";import {ProjectPermissionHsmConnectorActions,ProjectPermissionSub@@ -31,18 +33,41 @@ import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";import { CertKeySource } from "@app/hooks/api/signers";import { CaWizardForm } from "./schemas";-import { HSM_SUPPORTED_CA_KEY_ALGORITHMS, HsmConnectorOption } from "./types";+import {+ AwsConnectionOption,+ HsmConnectorOption,+ isKeyAlgorithmSupportedByKeySource+} from "./types";++const KEY_SOURCE_DESCRIPTIONS: Record<CertKeySource, string> = {+ [CertKeySource.Infisical]: "Infisical generates and manages the CA keypair for you.",+ [CertKeySource.Hsm]:+ "The CA keypair is generated on a Hardware Security Module and every signature is performed there.",+ [CertKeySource.AwsKms]:+ "The CA keypair is generated in AWS KMS and every signature is performed there. The private key never leaves AWS."+};type Props = {form: UseFormReturn<CaWizardForm>;hsmConnectorOptions: HsmConnectorOption[];isHsmConnectorsLoading: boolean;+ awsConnectionOptions: AwsConnectionOption[];+ isAwsConnectionsLoading: boolean;};-export const KeyValidityStep = ({ form, hsmConnectorOptions, isHsmConnectorsLoading }: Props) => {+export const KeyValidityStep = ({+ form,+ hsmConnectorOptions,+ isHsmConnectorsLoading,+ awsConnectionOptions,+ isAwsConnectionsLoading+}: Props) => {const { subscription } = useSubscription();+ const { currentOrg } = useOrganization();+ const { currentProject } = useProject();const { openUpgradeGate, upgradeGate } = useUpgradeGate();const isHsmLicensed = Boolean(subscription?.hsm);+ const isAwsKmsLicensed = Boolean(subscription?.pkiAwsKmsSigning);const { permission } = useProjectPermission();const canAttachHsm = permission.can(ProjectPermissionHsmConnectorActions.Attach,@@ -52,6 +77,7 @@ export const KeyValidityStep = ({ form, hsmConnectorOptions, isHsmConnectorsLoadconst keySource = form.watch("keySource");const caType = form.watch("type");const isHsm = keySource === CertKeySource.Hsm;+ const isAwsKms = keySource === CertKeySource.AwsKms;const isRoot = caType === InternalCaType.ROOT;return (@@ -70,8 +96,10 @@ export const KeyValidityStep = ({ form, hsmConnectorOptions, isHsmConnectorsLoadonValueChange={(value) => {field.onChange(value);if (- value === CertKeySource.Hsm &&- !HSM_SUPPORTED_CA_KEY_ALGORITHMS.includes(form.getValues("keyAlgorithm"))+ !isKeyAlgorithmSupportedByKeySource(+ value as CertKeySource,+ form.getValues("keyAlgorithm")+ )) {form.setValue("keyAlgorithm", CertKeyAlgorithm.ECDSA_P256, {shouldValidate: true@@ -93,13 +121,15 @@ export const KeyValidityStep = ({ form, hsmConnectorOptions, isHsmConnectorsLoad)}</div></SelectItem>+ <SelectItem value={CertKeySource.AwsKms} disabled={!isAwsKmsLicensed}>+ <div className="flex items-center gap-2">+ AWS KMS+ {!isAwsKmsLicensed && <Badge variant="info">Enterprise</Badge>}+ </div>+ </SelectItem></SelectContent></Select>- <FieldDescription>- {isHsm- ? "The CA keypair is generated on a Hardware Security Module and every signature is performed there."- : "Infisical generates and manages the CA keypair for you."}- </FieldDescription>+ <FieldDescription>{KEY_SOURCE_DESCRIPTIONS[field.value]}</FieldDescription></FieldContent></Field>)}@@ -143,12 +173,88 @@ export const KeyValidityStep = ({ form, hsmConnectorOptions, isHsmConnectorsLoad/>)}+ {isAwsKms && (+ <>+ <Controller+ name="appConnectionId"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel>+ AWS Connection <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <FilterableSelect<AwsConnectionOption>+ isLoading={isAwsConnectionsLoading}+ options={awsConnectionOptions}+ value={awsConnectionOptions.find((o) => o.id === field.value) ?? null}+ onChange={(selected) => {+ const opt = selected as AwsConnectionOption | null;+ field.onChange(opt?.id ?? null);+ }}+ getOptionLabel={(opt) => opt.name}+ getOptionValue={(opt) => opt.id}+ placeholder="Select an AWS connection..."+ /* eslint-disable-next-line react/no-unstable-nested-components */+ noOptionsMessage={() =>+ awsConnectionOptions.length === 0 ? (+ <>+ No AWS connections yet.{" "}+ <Link+ to="/organizations/$orgId/projects/cert-manager/$projectId/app-connections"+ params={{ orgId: currentOrg.id, projectId: currentProject.id }}+ className="underline"+ >+ Add an AWS connection+ </Link>+ </>+ ) : (+ "No match."+ )+ }+ isError={Boolean(error)}+ />+ <FieldDescription>+ The AWS connection Infisical uses to create the key and send signing requests.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ name="region"+ control={form.control}+ render={({ field, fieldState: { error } }) => (+ <Field>+ <FieldLabel id="ca-aws-kms-region-label" htmlFor="ca-aws-kms-region">+ Region <span className="text-danger">*</span>+ </FieldLabel>+ <FieldContent>+ <AwsRegionSelect+ id="ca-aws-kms-region"+ value={field.value ?? ""}+ onChange={(value) => field.onChange(value || null)}+ isError={Boolean(error)}+ aria-labelledby="ca-aws-kms-region-label"+ />+ <FieldDescription>+ The AWS region where the CA signing key is created.+ </FieldDescription>+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}+ />+ </>+ )}+<Controllername="keyAlgorithm"control={form.control}render={({ field, fieldState: { error } }) => {- const options = certKeyAlgorithms.filter(- ({ value }) => !isHsm || HSM_SUPPORTED_CA_KEY_ALGORITHMS.includes(value)+ const options = certKeyAlgorithms.filter(({ value }) =>+ isKeyAlgorithmSupportedByKeySource(keySource, value));return (<Field>@@ -187,7 +293,8 @@ export const KeyValidityStep = ({ form, hsmConnectorOptions, isHsmConnectorsLoad</SelectContent></Select><FieldDescription>- Algorithm and size of the CA key pair. HSM-backed CAs support RSA and ECDSA only.+ Algorithm and size of the CA key pair.+ {isHsm && " HSM-backed CAs support RSA and ECDSA only."}</FieldDescription><FieldError errors={[error]} /></FieldContent>diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/schemas.ts b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/schemas.tsindex 4ea0d67333..2e2f6048c3 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/schemas.ts+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/schemas.ts@@ -9,7 +9,7 @@ import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";import { CertKeySource } from "@app/hooks/api/signers";import { slugSchema } from "@app/lib/schemas";-import { HSM_SUPPORTED_CA_KEY_ALGORITHMS } from "./types";+import { isKeyAlgorithmSupportedByKeySource } from "./types";const isValidDate = (dateString: string) => !Number.isNaN(new Date(dateString).getTime());@@ -55,6 +55,8 @@ export const caWizardSchema = zcommonName: z.string().trim().default(""),keySource: z.nativeEnum(CertKeySource).default(CertKeySource.Infisical),hsmConnectorId: z.string().uuid().optional().nullable(),+ appConnectionId: z.string().uuid().optional().nullable(),+ region: z.string().optional().nullable(),keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).default(CertKeyAlgorithm.ECDSA_P256),notAfter: z.string().trim().default(""),maxPathLength: z.string().default("-1"),@@ -85,15 +87,17 @@ export const caWizardSchema = zmessage: "Pick an HSM Connector.",path: ["hsmConnectorId"]})- .refine(- (data) =>- data.keySource !== CertKeySource.Hsm ||- HSM_SUPPORTED_CA_KEY_ALGORITHMS.includes(data.keyAlgorithm),- {- message:- "This algorithm is not supported by HSM-backed keys. Pick RSA 2048, RSA 4096, ECDSA P256, or ECDSA P384.",- path: ["keyAlgorithm"]- }- );+ .refine((data) => data.keySource !== CertKeySource.AwsKms || Boolean(data.appConnectionId), {+ message: "Pick an AWS connection.",+ path: ["appConnectionId"]+ })+ .refine((data) => data.keySource !== CertKeySource.AwsKms || Boolean(data.region), {+ message: "Pick an AWS region.",+ path: ["region"]+ })+ .refine((data) => isKeyAlgorithmSupportedByKeySource(data.keySource, data.keyAlgorithm), {+ message: "This algorithm is not supported by the selected key source.",+ path: ["keyAlgorithm"]+ });export type CaWizardForm = z.infer<typeof caWizardSchema>;diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.tsindex 660a2b2e96..21634b76ed 100644--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CreateCaWizard/types.ts@@ -1,16 +1,39 @@import { CertKeyAlgorithm } from "@app/hooks/api/certificates/enums";+import { CertKeySource } from "@app/hooks/api/signers";import { PkiDocsUrls } from "../../../pki-docs-urls";-export const HSM_SUPPORTED_CA_KEY_ALGORITHMS: readonly CertKeyAlgorithm[] = [- CertKeyAlgorithm.RSA_2048,- CertKeyAlgorithm.RSA_4096,- CertKeyAlgorithm.ECDSA_P256,- CertKeyAlgorithm.ECDSA_P384-];+export const KEY_SOURCE_SUPPORTED_CA_KEY_ALGORITHMS: Partial<+ Record<CertKeySource, readonly CertKeyAlgorithm[]>+> = {+ [CertKeySource.Hsm]: [+ CertKeyAlgorithm.RSA_2048,+ CertKeyAlgorithm.RSA_4096,+ CertKeyAlgorithm.ECDSA_P256,+ CertKeyAlgorithm.ECDSA_P384+ ],+ [CertKeySource.AwsKms]: [+ CertKeyAlgorithm.RSA_2048,+ CertKeyAlgorithm.RSA_3072,+ CertKeyAlgorithm.RSA_4096,+ CertKeyAlgorithm.ECDSA_P256,+ CertKeyAlgorithm.ECDSA_P384,+ CertKeyAlgorithm.ECDSA_P521,+ CertKeyAlgorithm.ML_DSA_44,+ CertKeyAlgorithm.ML_DSA_65,+ CertKeyAlgorithm.ML_DSA_87+ ]+};++export const isKeyAlgorithmSupportedByKeySource = (+ keySource: CertKeySource,+ keyAlgorithm: CertKeyAlgorithm+) => KEY_SOURCE_SUPPORTED_CA_KEY_ALGORITHMS[keySource]?.includes(keyAlgorithm) ?? true;export type HsmConnectorOption = { id: string; name: string; slotLabel: string };+export type AwsConnectionOption = { id: string; name: string };+export type WizardStep = {name: string;shortDescription: string;@@ -49,7 +72,7 @@ export const STEPS: WizardStep[] = [subtitle: "Choose where the signing key is generated and how long the CA is valid.",rightLabel: "KEY & VALIDITY",rightDescription:- "Pick the key source: Infisical generates and manages the keypair, or HSM keeps the keypair inside your own Hardware Security Module and performs every signature there. Root CAs are self-signed immediately, so their validity and path length are set here.",+ "Pick the key source: Infisical generates and manages the keypair, HSM keeps it inside your own Hardware Security Module, and AWS KMS creates it in your AWS account. With HSM and AWS KMS, every signature is performed there. Root CAs are self-signed immediately, so their validity and path length are set here.",docsUrl: PkiDocsUrls.ca.internal},{