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
Merge remote-tracking branch 'origin/main' into PKI-470
Carlos Monastyrski3bd74932b427
diff --cc backend/src/db/schemas/certificate-authority-secret.tsindex 5d589b44c7,85cea1d638..572b71da66--- a/backend/src/db/schemas/certificate-authority-secret.ts+++ b/backend/src/db/schemas/certificate-authority-secret.ts@@@ -17,9 -17,9 +17,10 @@@ export const CertificateAuthoritySecretencryptedPrivateKey: zodBuffer.nullable().optional(),keySource: z.string().default("infisical"),hsmConnectorId: z.string().uuid().nullable().optional(),- hsmKeyLabel: z.string().nullable().optional(),- hsmKeyId: z.string().nullable().optional(),- hsmPublicKeySpki: zodBuffer.nullable().optional()+ appConnectionId: z.string().uuid().nullable().optional(),+ externalKeyId: z.string().nullable().optional(),- publicKeySpki: zodBuffer.nullable().optional()++ publicKeySpki: zodBuffer.nullable().optional(),++ hsmKeyId: z.string().nullable().optional()});export type TCertificateAuthoritySecret = z.infer<typeof CertificateAuthoritySecretSchema>;diff --cc backend/src/server/routes/v1/signer-routers/certificate-router.tsindex 796343d445,b195a7ea83..74a2dfe045--- a/backend/src/server/routes/v1/signer-routers/certificate-router.ts+++ b/backend/src/server/routes/v1/signer-routers/certificate-router.ts@@@ -33,10 -32,31 +33,12 @@@ export const registerSignerCertificateRcommonName: z.string().trim().min(1).max(256).optional(),certificateTtlDays: z.number().int().min(1).max(3650).optional(),keyAlgorithm: SignerKeyAlgorithm.schema.optional(),- certificate: SignerCertificateInputSchema.extend({ keySource: z.nativeEnum(CertKeySource) }).optional(),- certificate: z- .object({- keySource: z.enum([CertKeySource.Infisical, CertKeySource.Hsm]),- hsmConnectorId: z.string().uuid().optional()- })- .optional(),++ certificate: SignerCertificateInputSchema.extend({++ keySource: z.enum([CertKeySource.Infisical, CertKeySource.Hsm])++ }).optional(),externalConfiguration: SignerExternalConfigurationSchema.optional()})- .superRefine((data, ctx) => {- if (data.certificate?.keySource !== CertKeySource.Hsm) return;- if (!data.certificate.hsmConnectorId) {- ctx.addIssue({- code: "custom",- message: `hsmConnectorId is required when keySource = '${CertKeySource.Hsm}'`,- path: ["certificate", "hsmConnectorId"]- });- }- if (!data.keyAlgorithm || !HSM_SUPPORTED_KEY_ALGORITHMS.includes(data.keyAlgorithm)) {- ctx.addIssue({- code: "custom",- message: `keyAlgorithm must be one of ${HSM_SUPPORTED_KEY_ALGORITHMS.join(", ")} when keySource = '${CertKeySource.Hsm}'`,- path: ["keyAlgorithm"]- });- }- }),+ .superRefine(refineSignerCertificateInput),response: { 200: PkiSignersSchema }},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),diff --cc backend/src/server/routes/v1/signer-routers/lifecycle-router.tsindex 223ffc746f,13379eb22b..69bd92294f--- a/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts+++ b/backend/src/server/routes/v1/signer-routers/lifecycle-router.ts@@@ -62,9 -61,15 +62,9 @@@ export const registerSignerLifecycleRoucertificateRenewBeforeDays: z.number().int().min(1).max(30).nullable().optional(),keyAlgorithm: SignerKeyAlgorithm.schema.optional(),certificateId: z.string().uuid().optional(),- certificate: z- .object({- keySource: z- .enum([CertKeySource.Infisical, CertKeySource.Hsm])- .optional()- .default(CertKeySource.Infisical),- hsmConnectorId: z.string().uuid().optional()- })- .optional(),+ certificate: SignerCertificateInputSchema.extend({- keySource: z.nativeEnum(CertKeySource).optional().default(CertKeySource.Infisical)++ keySource: z.enum([CertKeySource.Infisical, CertKeySource.Hsm]).optional().default(CertKeySource.Infisical)+ }).optional(),externalConfiguration: SignerExternalConfigurationSchema.optional(),approvalPolicyId: z.string().uuid().optional(),members: zdiff --cc backend/src/server/routes/v1/signer-routers/schemas.tsindex 2ed81e8ae1,93f74b8e81..8f0cb7b4a7--- a/backend/src/server/routes/v1/signer-routers/schemas.ts+++ b/backend/src/server/routes/v1/signer-routers/schemas.ts@@@ -11,58 -10,29 +11,58 @@@ export const SignerIdParamsSchema = z.oexport const SignerRequestParamsSchema = SignerIdParamsSchema.extend({ requestId: z.string().uuid() });-export const SignerExternalConfigurationSchema = z.discriminatedUnion("caType", [- z.object({- caType: z.literal(CaType.DIGICERT),- reissueFromExternalOrderId: z- .string()- .trim()- .min(1)- .optional()- .describe(- "Reissue into this existing DigiCert order instead of placing a new order (reuses the subscription slot)."- )- }),- z.object({- caType: z.literal(CaType.ADCS),- template: z- .string()- .trim()- .min(1)- .refine((v) => RE_NO_NEWLINES.test(v), "Template name must not contain newline characters")- .optional()- .describe("The AD CS certificate template this signer requests when issuing (e.g. a code-signing template).")- })-]);+const ExternalOrderIdSchema = z.string().trim().min(1).max(32);++export const SignerExternalConfigurationSchema = z.object({+ caType: z+ .enum([CaType.DIGICERT, CaType.ADCS])+ .optional()+ .describe(+ "Optional. The CA type is resolved from caId. If provided, it must match the type of that certificate authority."+ ),+ reissueFromExternalOrderId: ExternalOrderIdSchema.optional().describe(+ "DigiCert only. Reissue into this existing DigiCert order instead of placing a new order (reuses the subscription slot). DigiCert revokes the order's previous certificate."+ ),+ importFromExternalOrderId: ExternalOrderIdSchema.optional().describe(+ "DigiCert only. Use the certificate already issued in this DigiCert order, without reissuing it. Requires certificate.hsmKeyLabel to point at the certificate's private key on the HSM. The common name, validity and key algorithm come from that certificate, so commonName, certificateTtlDays and keyAlgorithm can't be sent with it."+ ),+ template: z+ .string()+ .trim()+ .min(1)+ .max(256)+ .refine((v) => RE_NO_NEWLINES.test(v), "Template name must not contain newline characters")+ .optional()+ .describe(+ "Active Directory Certificate Service only. The certificate template this signer requests when issuing (e.g. a code-signing template)."+ )+});++export const SignerCertificateInputSchema = z.object({- keySource: z.nativeEnum(CertKeySource).optional(),++ keySource: z.enum([CertKeySource.Infisical, CertKeySource.Hsm]).optional(),+ hsmConnectorId: z.string().uuid().optional(),+ hsmKeyLabel: z+ .string()+ .trim()+ .min(1)+ .max(128)+ .refine((v) => RE_NO_NEWLINES.test(v), "Key label must not contain newline characters")+ .optional()+ .describe(+ "The label of an existing private key on the HSM. Only used with externalConfiguration.importFromExternalOrderId. If more than one private key in the HSM Connector's slot has this label, also set hsmKeyId."+ ),+ hsmKeyId: z+ .string()+ .trim()+ .min(2)+ .max(256)+ .regex(/^(?:[0-9a-fA-F]{2})+$/, "Key ID must be the hex encoding of the key's CKA_ID")+ .transform((v) => v.toLowerCase())+ .optional()+ .describe(+ "The hex-encoded PKCS#11 key ID (CKA_ID) of the private key, used to tell apart keys that share a label. Only used with hsmKeyLabel."+ )+});export const SignerKeyAlgorithm = {values: [diff --cc backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.tsindex 0000000000,b3adced78c..98aee120abmode 000000,100644..100644--- a/backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.ts+++ b/backend/src/services/certificate-authority/ca-key-source/ca-key-source-types.ts@@@ -1,0 -1,51 +1,51 @@@+ 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"++ "hsmConnectorId" | "appConnectionId" | "externalKeyId" | "hsmKeyId" | "publicKeySpki"+ >;++ export type TCaKeyDetails = {+ hsmConnectorId?: string;+ hsmConnectorName?: 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 --cc backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.tsindex 0000000000,12b9ef00bb..36fb4a51a1mode 000000,100644..100644--- a/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts+++ b/backend/src/services/certificate-authority/ca-key-source/hsm-ca-key-source.ts@@@ -1,0 -1,102 +1,105 @@@+ import { crypto } from "@app/lib/crypto/cryptography";+ import { BadRequestError } from "@app/lib/errors";+ import { alphaNumericNanoId } from "@app/lib/nanoid";+ import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+ import { THsmConnectorDALFactory } from "@app/services/hsm-connector/hsm-connector-dal";+ import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";++ import { buildHsmCaSigner, caKeyAlgorithmToHsmShape, createEphemeralKeyCache } from "../ca-signer";+ import { TExternalCaKeyInput, TExternalCaKeyProvider } from "./ca-key-source-types";++ type THsmCaKeySourceDep = {+ hsmConnectorService: Pick<THsmConnectorServiceFactory, "generateKeyPair" | "sign" | "assertAttachPermission">;+ hsmConnectorDAL: Pick<THsmConnectorDALFactory, "findById">;+ };++ const requireHsmConnectorId = (input: TExternalCaKeyInput) => {+ 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,+ hsmConnectorDAL+ }: THsmCaKeySourceDep): TExternalCaKeyProvider => {+ const ephemeralKeys = createEphemeralKeyCache();++ return {+ 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,++ hsmKeyId: generated.keyId,+ publicKeySpki: generated.publicKeySpkiDer+ };+ },++ describeKey: async ({ reference }) => {+ const hsmConnector = reference.hsmConnectorId+ ? await hsmConnectorDAL.findById(reference.hsmConnectorId)+ : undefined;+ return {+ hsmConnectorId: reference.hsmConnectorId ?? undefined,+ hsmConnectorName: hsmConnector?.name,+ hsmKeyLabel: reference.externalKeyId ?? undefined,+ externalKeyId: reference.externalKeyId ?? undefined+ };+ },++ buildSigner: async ({ projectId, keyAlgorithm, reference, signatureAlgorithm }) => {- const { hsmConnectorId, externalKeyId: keyLabel, publicKeySpki } = reference;++ const { hsmConnectorId, externalKeyId: keyLabel, hsmKeyId, 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,++ keyId: hsmKeyId,++ publicKeySpki,+ mechanism,+ data,+ isDigest+ }),+ ephemeralKeys+ });+ }+ };+ };