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): support issuing CA certificates from AWS Private CA (#7543)
Saif Ur Rahmana60984533079
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.tsindex da653b557d..72d563d463 100644--- a/backend/src/queue/queue-service.ts+++ b/backend/src/queue/queue-service.ts@@ -470,6 +470,7 @@ export type TQueueJobTypes = {country?: string;state?: string;locality?: string;+ basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;};};[QueueName.PkiSubscriber]: {diff --git a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.tsindex dd041db9a4..66f7fd921a 100644--- a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-fns.ts@@ -38,6 +38,7 @@ import {CertSubjectAlternativeNameType,CrlReason} from "@app/services/certificate/certificate-types";+import { buildIdempotencyToken } from "@app/services/certificate-common/certificate-issuance-utils";import { CertificateRequestCancelledError } from "@app/services/certificate-common/certificate-request-errors";import { ExternalMetadataSchema } from "@app/services/certificate-common/external-metadata-schemas";import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";@@ -58,7 +59,6 @@ import {TUpdateAwsAcmPublicCaCertificateAuthorityDTO} from "./aws-acm-public-ca-certificate-authority-types";import {- buildIdempotencyToken,generateAcmPassphrase,mapCertKeyAlgorithmToAcm,validateAcmIssuanceInputsdiff --git a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-validators.ts b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-validators.tsindex 778202026e..96c6a4ef0f 100644--- a/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-validators.ts+++ b/backend/src/services/certificate-authority/aws-acm-public-ca/aws-acm-public-ca-certificate-authority-validators.ts@@ -122,7 +122,3 @@ const generateAcmPassphraseInternal = customAlphabet(32);export const generateAcmPassphrase = (): string => generateAcmPassphraseInternal();--// Strip hyphens from the certificate UUID to produce a 32-char token that-// satisfies AWS's IdempotencyToken constraints (max 32 chars, alphanumeric).-export const buildIdempotencyToken = (certificateId: string) => certificateId.split("-").join("").slice(0, 32);diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-enums.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-enums.tsindex b531125108..64777346c6 100644--- a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-enums.ts+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-enums.ts@@ -41,3 +41,15 @@ export const CRL_REASON_TO_REVOCATION_REASON_MAP: Record<CrlReason, RevocationRe*/export const API_CSR_PASSTHROUGH_TEMPLATE_ARN ="arn:aws:acm-pca:::template/BlankEndEntityCertificate_APICSRPassthrough/V1";++// AWS sets CA:TRUE from the template, not from ApiPassthrough or the CSR, and only publishes+// templates for pathLen 0-3.+export const SUBORDINATE_CA_API_CSR_PASSTHROUGH_TEMPLATE_ARN_BY_PATH_LENGTH: Record<number, string> = {+ 0: "arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen0_APICSRPassthrough/V1",+ 1: "arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen1_APICSRPassthrough/V1",+ 2: "arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen2_APICSRPassthrough/V1",+ 3: "arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen3_APICSRPassthrough/V1"+};++// Mirrored in frontend CertificateIssuanceModal.tsx; update both.+export const AWS_PCA_MAX_CA_PATH_LENGTH = 3;diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.tsindex d24b5b85c5..9434e0e428 100644--- a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-fns.ts@@ -42,6 +42,7 @@ import {getSanOtherNameOid,mapSanTypeToX509Type} from "@app/services/certificate/certificate-types";+import { buildIdempotencyToken } from "@app/services/certificate-common/certificate-issuance-utils";import { CertificateRequestCancelledError } from "@app/services/certificate-common/certificate-request-errors";import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -53,7 +54,6 @@ import { CaStatus, CaType } from "../certificate-authority-enums";import { createDistinguishedName, extractDnParts, keyAlgorithmToAlgCfg } from "../certificate-authority-fns";import { TExternalCertificateAuthorityDALFactory } from "../external-certificate-authority-dal";import {- API_CSR_PASSTHROUGH_TEMPLATE_ARN,CA_KEY_ALGORITHM_TO_SIGNING_ALGORITHM_MAP,CRL_REASON_TO_REVOCATION_REASON_MAP} from "./aws-pca-certificate-authority-enums";@@ -62,6 +62,7 @@ import {TCreateAwsPcaCertificateAuthorityDTO,TUpdateAwsPcaCertificateAuthorityDTO} from "./aws-pca-certificate-authority-types";+import { resolveAwsPcaTemplateArn } from "./aws-pca-certificate-authority-validators";const base64UrlToBase64 = (base64url: string): string => {let base64 = base64url.replace(new RE2(/-/g), "+").replace(new RE2(/_/g), "/");@@ -273,10 +274,10 @@ const pollForCertificate = async (/*** Queries the CA's key algorithm via DescribeCertificateAuthority and returns- * a compatible signing algorithm. The signing algorithm in IssueCertificateCommand- * must match the CA's key type, not the leaf certificate's key type.+ * a compatible signing algorithm, plus the usage mode. The SigningAlgorithm in+ * IssueCertificateCommand must match the CA's key type, not the leaf certificate's key type.*/-const getSigningAlgorithmForCa = async (pcaClient: ACMPCAClient, certificateAuthorityArn: string) => {+const describeCaForIssuance = async (pcaClient: ACMPCAClient, certificateAuthorityArn: string) => {const describeResult = await pcaClient.send(new DescribeCertificateAuthorityCommand({CertificateAuthorityArn: certificateAuthorityArn@@ -298,7 +299,7 @@ const getSigningAlgorithmForCa = async (pcaClient: ACMPCAClient, certificateAuth});}- return signingAlgorithm;+ return { signingAlgorithm, usageMode: describeResult.CertificateAuthority?.UsageMode };};export const castDbEntryToAwsPcaCertificateAuthority = (@@ -554,6 +555,7 @@ export const AwsPcaCertificateAuthorityFns = ({const orderCertificate = async ({caId,profileId,+ idempotencyKey,commonName,altNames = [],keyUsages = [],@@ -571,10 +573,13 @@ export const AwsPcaCertificateAuthorityFns = ({country,state,locality,+ basicConstraints,isCancelled}: {caId: string;profileId?: string;+ // Must be stable across retries so AWS dedupes instead of issuing twice. Expires after 5 min.+ idempotencyKey?: string;commonName: string;altNames?: Array<{ type: CertSubjectAlternativeNameType; value: string }>;keyUsages?: CertKeyUsage[];@@ -592,6 +597,7 @@ export const AwsPcaCertificateAuthorityFns = ({country?: string;state?: string;locality?: string;+ basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;isCancelled?: () => Promise<boolean>;}) => {const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(caId);@@ -619,7 +625,12 @@ export const AwsPcaCertificateAuthorityFns = ({const pcaClient = await createPcaClient({ appConnectionId, region, appConnectionDAL, kmsService });// Get signing algorithm from the CA's key type (not the leaf key type)- const awsSigningAlgorithm = await getSigningAlgorithmForCa(pcaClient, certificateAuthorityArn);+ const { signingAlgorithm: awsSigningAlgorithm, usageMode } = await describeCaForIssuance(+ pcaClient,+ certificateAuthorityArn+ );++ const templateArn = resolveAwsPcaTemplateArn({ basicConstraints, usageMode });let csrPem: string;let skLeaf: string | undefined;@@ -747,7 +758,8 @@ export const AwsPcaCertificateAuthorityFns = ({CertificateAuthorityArn: certificateAuthorityArn,Csr: Buffer.from(csrPem),SigningAlgorithm: awsSigningAlgorithm,- TemplateArn: API_CSR_PASSTHROUGH_TEMPLATE_ARN,+ TemplateArn: templateArn,+ ...(idempotencyKey && { IdempotencyToken: buildIdempotencyToken(idempotencyKey) }),...(Object.keys(apiPassthrough).length > 0 && { ApiPassthrough: apiPassthrough }),Validity: {Type: ValidityPeriodType.DAYS,diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators.test.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators.test.tsnew file mode 100644index 0000000000..322b066100--- /dev/null+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators.test.ts@@ -0,0 +1,66 @@+import { CertificateAuthorityUsageMode } from "@aws-sdk/client-acm-pca";++import { API_CSR_PASSTHROUGH_TEMPLATE_ARN } from "./aws-pca-certificate-authority-enums";+import { resolveAwsPcaTemplateArn, validateAwsPcaCaIssuanceInputs } from "./aws-pca-certificate-authority-validators";++describe("validateAwsPcaCaIssuanceInputs", () => {+ test.each([undefined, null, { isCA: false }, { isCA: false, pathLength: 9 }])(+ "accepts a non-CA request (%p)",+ (basicConstraints) => {+ expect(() => validateAwsPcaCaIssuanceInputs({ basicConstraints })).not.toThrow();+ }+ );++ test.each([0, 1, 2, 3])("accepts a CA request with path length %i", (pathLength) => {+ expect(() => validateAwsPcaCaIssuanceInputs({ basicConstraints: { isCA: true, pathLength } })).not.toThrow();+ });++ test.each([undefined, null])("rejects a CA request with an unlimited path length (%p)", (pathLength) => {+ expect(() => validateAwsPcaCaIssuanceInputs({ basicConstraints: { isCA: true, pathLength } })).toThrow(+ /path length between 0 and 3 is required/i+ );+ });++ test.each([4, 10, -1, 1.5])("rejects a CA request with an out-of-range path length (%p)", (pathLength) => {+ expect(() => validateAwsPcaCaIssuanceInputs({ basicConstraints: { isCA: true, pathLength } })).toThrow(+ /between 0 and 3/i+ );+ });+});++describe("resolveAwsPcaTemplateArn", () => {+ test("uses the end-entity template for a leaf request", () => {+ expect(resolveAwsPcaTemplateArn({ basicConstraints: { isCA: false } })).toBe(API_CSR_PASSTHROUGH_TEMPLATE_ARN);+ expect(resolveAwsPcaTemplateArn({})).toBe(API_CSR_PASSTHROUGH_TEMPLATE_ARN);+ });++ test.each([0, 1, 2, 3])("uses the matching subordinate CA template for path length %i", (pathLength) => {+ expect(resolveAwsPcaTemplateArn({ basicConstraints: { isCA: true, pathLength } })).toBe(+ `arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen${pathLength}_APICSRPassthrough/V1`+ );+ });++ test("rejects CA issuance from a short-lived certificate CA", () => {+ expect(() =>+ resolveAwsPcaTemplateArn({+ basicConstraints: { isCA: true, pathLength: 0 },+ usageMode: CertificateAuthorityUsageMode.SHORT_LIVED_CERTIFICATE+ })+ ).toThrow(/short-lived certificate mode/i);+ });++ test("allows leaf issuance from a short-lived certificate CA", () => {+ expect(+ resolveAwsPcaTemplateArn({+ basicConstraints: { isCA: false },+ usageMode: CertificateAuthorityUsageMode.SHORT_LIVED_CERTIFICATE+ })+ ).toBe(API_CSR_PASSTHROUGH_TEMPLATE_ARN);+ });++ test("rejects an out-of-range path length rather than falling back to the end-entity template", () => {+ expect(() => resolveAwsPcaTemplateArn({ basicConstraints: { isCA: true, pathLength: 4 } })).toThrow(+ /between 0 and 3/i+ );+ });+});diff --git a/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators.ts b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators.tsnew file mode 100644index 0000000000..2c62ad35e2--- /dev/null+++ b/backend/src/services/certificate-authority/aws-pca/aws-pca-certificate-authority-validators.ts@@ -0,0 +1,53 @@+import { CertificateAuthorityUsageMode } from "@aws-sdk/client-acm-pca";++import { BadRequestError } from "@app/lib/errors";++import {+ API_CSR_PASSTHROUGH_TEMPLATE_ARN,+ AWS_PCA_MAX_CA_PATH_LENGTH,+ SUBORDINATE_CA_API_CSR_PASSTHROUGH_TEMPLATE_ARN_BY_PATH_LENGTH+} from "./aws-pca-certificate-authority-enums";++// Called by the order API before enqueuing, so a bad path length is a 400 rather than a failed job.+export const validateAwsPcaCaIssuanceInputs = ({+ basicConstraints+}: {+ basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;+}) => {+ if (!basicConstraints?.isCA) return;++ const { pathLength } = basicConstraints;++ if (pathLength === undefined || pathLength === null) {+ throw new BadRequestError({+ message: `A path length between 0 and ${AWS_PCA_MAX_CA_PATH_LENGTH} is required when issuing a CA certificate from AWS Private CA, which has no template for an unlimited path length. If you are supplying a CSR, set it there, for example "basicConstraints=critical,CA:TRUE,pathlen:0".`+ });+ }++ if (!Number.isInteger(pathLength) || pathLength < 0 || pathLength > AWS_PCA_MAX_CA_PATH_LENGTH) {+ throw new BadRequestError({+ message: `Path length must be a whole number between 0 and ${AWS_PCA_MAX_CA_PATH_LENGTH} when issuing a CA certificate from AWS Private CA. Received: ${pathLength}.`+ });+ }+};++export const resolveAwsPcaTemplateArn = ({+ basicConstraints,+ usageMode+}: {+ basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;+ usageMode?: CertificateAuthorityUsageMode;+}) => {+ if (!basicConstraints?.isCA) return API_CSR_PASSTHROUGH_TEMPLATE_ARN;++ if (usageMode === CertificateAuthorityUsageMode.SHORT_LIVED_CERTIFICATE) {+ throw new BadRequestError({+ message:+ "This AWS Private CA is in short-lived certificate mode, which cannot issue CA certificates. Use a general-purpose AWS Private CA instead."+ });+ }++ validateAwsPcaCaIssuanceInputs({ basicConstraints });++ return SUBORDINATE_CA_API_CSR_PASSTHROUGH_TEMPLATE_ARN_BY_PATH_LENGTH[basicConstraints.pathLength as number];+};diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.tsindex 4d9206f72d..1db30aafda 100644--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts@@ -141,6 +141,7 @@ export type TIssueCertificateFromProfileJobData = {state?: string;locality?: string;applicationId?: string;+ basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;};type TCertificateIssuanceQueueFactoryDep = {@@ -346,7 +347,8 @@ export const certificateIssuanceQueueFactory = ({country,state,locality,- applicationId+ applicationId,+ basicConstraints}: TIssueCertificateFromProfileJobData) => {const jobData: TIssueCertificateFromProfileJobData = {certificateId,@@ -369,7 +371,8 @@ export const certificateIssuanceQueueFactory = ({country,state,locality,- applicationId+ applicationId,+ basicConstraints};// ACM DNS validation can take 5–30 minutes; the function is fully idempotent via@@ -419,7 +422,8 @@ export const certificateIssuanceQueueFactory = ({organizationalUnit,country,state,- locality+ locality,+ basicConstraints} = data;const setPending = async (message: string) => {@@ -782,6 +786,7 @@ export const certificateIssuanceQueueFactory = ({const awsPcaParams = {caId,profileId,+ idempotencyKey: certificateId,commonName: commonName || "",altNames: (altNames || []) as Array<{ type: CertSubjectAlternativeNameType; value: string }>,keyUsages: keyUsages as CertKeyUsage[],@@ -797,6 +802,7 @@ export const certificateIssuanceQueueFactory = ({country,state,locality,+ basicConstraints,isCancelled};diff --git a/backend/src/services/certificate-common/certificate-issuance-utils.ts b/backend/src/services/certificate-common/certificate-issuance-utils.tsindex 56ab540842..d77e310e39 100644--- a/backend/src/services/certificate-common/certificate-issuance-utils.ts+++ b/backend/src/services/certificate-common/certificate-issuance-utils.ts@@ -456,3 +456,7 @@ export const generateSelfSignedCertificate = async ({subjectAlternativeNames: certificateRequest.altNames || []};};++// Strip hyphens from a UUID to produce a 32-char token that+// satisfies AWS's IdempotencyToken constraints (max 32 chars, alphanumeric).+export const buildIdempotencyToken = (id: string) => id.split("-").join("").slice(0, 32);diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.tsindex fab9b5fd5b..8a02bd4b0e 100644--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts@@ -15,6 +15,7 @@ import { TCertificateDALFactory } from "@app/services/certificate/certificate-daimport { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";import { CertKeyAlgorithm, CertSignatureAlgorithm, CertStatus } 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 { 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";@@ -104,6 +105,7 @@ const buildRevalidationRequest = ({notBefore,notAfter,altNames,+ basicConstraints,profileDefaults,ttl}: {@@ -121,6 +123,7 @@ const buildRevalidationRequest = ({notBefore?: Date | null;notAfter?: Date | null;altNames?: TAltNameEntry[] | null;+ basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;profileDefaults: Parameters<typeof applyProfileDefaults>[1];ttl?: string;}): TCertificateRequest => {@@ -149,6 +152,13 @@ const buildRevalidationRequest = ({mappedRequest.keyAlgorithm = csrKeyAlg;mappedRequest.signatureAlgorithm = csrSigAlg;}+ // The stored value wins over anything reconstructed from the CSR or profile defaults.+ if (basicConstraints) {+ mappedRequest.basicConstraints = {+ isCA: basicConstraints.isCA,+ pathLength: basicConstraints.pathLength ?? undefined+ };+ }if (notAfter) {mappedRequest.notBefore = notBefore || undefined;mappedRequest.notAfter = notAfter;@@ -666,6 +676,12 @@ export const certificateApprovalServiceFactory = (});}+ if (caType === CaType.AWS_PCA) {+ validateAwsPcaCaIssuanceInputs({+ basicConstraints: certRequest.basicConstraints as { isCA: boolean; pathLength?: number | null } | null+ });+ }+if (caType === CaType.GODADDY) {// Validate the CSR's actual contents when one is present, so an approved BYO CSR can't carry a// non-RSA key or extra SANs the GoDaddy guard never saw.@@ -696,6 +712,7 @@ export const certificateApprovalServiceFactory = (notBefore: certRequest.notBefore,notAfter: certRequest.notAfter,altNames,+ basicConstraints: certRequest.basicConstraints as { isCA: boolean; pathLength?: number | null } | null,profileDefaults: profile.defaults,ttl: effectiveTtl});@@ -731,6 +748,7 @@ export const certificateApprovalServiceFactory = (country: certRequest.country || undefined,state: certRequest.state || undefined,locality: certRequest.locality || undefined,+ basicConstraints: certRequest.basicConstraints as { isCA: boolean; pathLength?: number | null } | null,...(certRequest.applicationId && { applicationId: certRequest.applicationId })});diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex 08d661cd21..a2d1eec48e 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -13,7 +13,7 @@ import { TCertificateDALFactory } from "@app/services/certificate/certificate-daimport { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";import { CertStatus } from "@app/services/certificate/certificate-types";import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";-import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";+import { CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums";import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";import {CertExtendedKeyUsageType,@@ -55,6 +55,10 @@ vi.mock("../certificate-authority/certificate-authority-fns", () => ({assertCaInProfileProject: vi.fn()}));+vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }+}));+describe("CertificateV3Service", () => {let service: TCertificateV3ServiceFactory;@@ -153,6 +157,32 @@ describe("CertificateV3Service", () => {})};+ const mockCertificateIssuanceQueue = {+ queueCertificateIssuance: vi.fn()+ };++ const mockCertificateRequestService = {+ createCertificateRequest: vi.fn()+ };++ const mockApprovalPolicyDAL = {+ findByProjectId: vi.fn(),+ findStepsByPolicyId: vi.fn()+ };++ const mockCertificateRequestDAL = {+ updateById: vi.fn(),+ findById: vi.fn(),+ create: vi.fn(),+ transaction: vi.fn(),+ transitionFromPending: vi.fn(),+ attachCertificate: vi.fn()+ };++ const mockApprovalPolicyService = {+ createRequestFromPolicy: vi.fn()+ };+const mockActor = {actor: ActorType.USER,actorId: "user-123",@@ -169,6 +199,19 @@ describe("CertificateV3Service", () => {});vi.mocked(mockCertificateDAL.getRequestEnrollmentTypeByCertId).mockResolvedValue(null);+ mockCertificateIssuanceQueue.queueCertificateIssuance.mockResolvedValue(undefined);+ mockCertificateRequestService.createCertificateRequest.mockResolvedValue({ id: "cert-req-123" });+ mockApprovalPolicyDAL.findByProjectId.mockResolvedValue([]);+ mockApprovalPolicyDAL.findStepsByPolicyId.mockResolvedValue([]);+ mockCertificateRequestDAL.updateById.mockResolvedValue({ id: "cert-req-123" });+ mockCertificateRequestDAL.findById.mockResolvedValue({ id: "cert-req-123" });+ mockCertificateRequestDAL.create.mockResolvedValue({ id: "cert-req-123", createdAt: new Date() });+ mockCertificateRequestDAL.transitionFromPending.mockResolvedValue({ id: "cert-req-123" });+ mockCertificateRequestDAL.attachCertificate.mockResolvedValue({ id: "cert-req-123" });+ mockApprovalPolicyService.createRequestFromPolicy.mockResolvedValue({+ request: { id: "approval-req-123", steps: [{ id: "step-1", stepNumber: 1, approvers: [] }] }+ });+// Mock ForbiddenError.from static methodvi.spyOn(ForbiddenError, "from").mockReturnValue({throwUnlessCan: vi.fn()@@ -239,38 +282,17 @@ describe("CertificateV3Service", () => {return callback(mockTx);})} as any,- certificateIssuanceQueue: {- queueCertificateIssuance: vi.fn().mockResolvedValue(undefined)- },- certificateRequestService: {- createCertificateRequest: vi.fn().mockResolvedValue({ id: "cert-req-123" })- },- approvalPolicyDAL: {- findByProjectId: vi.fn().mockResolvedValue([]),- findStepsByPolicyId: vi.fn().mockResolvedValue([])- },- certificateRequestDAL: {- updateById: vi.fn().mockResolvedValue({ id: "cert-req-123" }),- findById: vi.fn().mockResolvedValue({ id: "cert-req-123" }),- create: vi.fn().mockResolvedValue({ id: "cert-req-123" }),- transaction: vi.fn(),- transitionFromPending: vi.fn().mockResolvedValue({ id: "cert-req-123" }),- attachCertificate: vi.fn().mockResolvedValue({ id: "cert-req-123" })- },+ certificateIssuanceQueue: mockCertificateIssuanceQueue,+ certificateRequestService: mockCertificateRequestService,+ approvalPolicyDAL: mockApprovalPolicyDAL,+ certificateRequestDAL: mockCertificateRequestDAL,userDAL: {findById: vi.fn().mockResolvedValue({ id: "user-123" })},identityDAL: {findById: vi.fn().mockResolvedValue({ id: "identity-123", name: "test-identity" })},- approvalPolicyService: {- createRequestFromPolicy: vi.fn().mockResolvedValue({- request: {- id: "approval-req-123",- steps: [{ id: "step-1", stepNumber: 1, approvers: [] }]- }- })- },+ approvalPolicyService: mockApprovalPolicyService,resourceMetadataDAL: {insertMany: vi.fn().mockResolvedValue([]),delete: vi.fn().mockResolvedValue([]),@@ -1028,6 +1050,116 @@ describe("CertificateV3Service", () => {})).rejects.toThrow("Profile is not configured for api enrollment");});++ describe("CA certificate orders", () => {+ const profileId = "profile-ca-order";+ const caOrder = {+ ...mockCertificateOrder,+ basicConstraints: { isCA: true, pathLength: 1 }+ };++ const mockProfile = {+ id: profileId,+ projectId: "project-123",+ enrollmentType: EnrollmentType.API,+ issuerType: IssuerType.CA,+ caId: "ca-123",+ certificatePolicyId: "policy-123",+ createdAt: new Date(),+ updatedAt: new Date(),+ slug: "aws-pca-profile",+ description: "AWS PCA profile",+ estConfigId: null,+ apiConfigId: "api-config-1"+ };++ const setupCa = (externalCaType: CaType | null) => {+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);+ vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue({+ id: "ca-123",+ projectId: "project-123",+ status: CaStatus.ACTIVE,+ externalCa: externalCaType ? { id: "ext-ca-1", type: externalCaType } : null+ } as any);+ vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({+ isValid: true,+ errors: []+ } as any);+ vi.mocked(mockCertificateRequestDAL.transaction).mockImplementation(+ async (callback: (tx: any) => Promise<unknown>) => callback({})+ );+ };++ it("rejects CA issuance for an external CA other than AWS Private CA", async () => {+ setupCa(CaType.DIGICERT);++ await expect(service.orderCertificate({ profileId, certificateOrder: caOrder, ...mockActor })).rejects.toThrow(+ "CA certificate issuance is not supported for this external certificate authority"+ );+ });++ it("passes basicConstraints to the issuance queue for AWS Private CA", async () => {+ setupCa(CaType.AWS_PCA);+ vi.mocked(mockApprovalPolicyDAL.findByProjectId).mockResolvedValue([]);++ await service.orderCertificate({ profileId, certificateOrder: caOrder, ...mockActor });++ expect(mockCertificateIssuanceQueue.queueCertificateIssuance).toHaveBeenCalledWith(+ expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })+ );+ expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(+ expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })+ );+ });++ // The approval branch writes its own request row, and issuance later reads it back.+ it("persists basicConstraints on the request row when an approval policy applies", async () => {+ setupCa(CaType.AWS_PCA);+ vi.mocked(mockApprovalPolicyDAL.findByProjectId).mockResolvedValue([+ {+ id: "approval-policy-1",+ isActive: true,+ scopeType: null,+ scopeId: null,+ bypassForMachineIdentities: false,+ maxRequestTtl: null,+ conditions: { conditions: [{ profileNames: [mockProfile.slug] }] }+ }+ ] as any);++ await service.orderCertificate({ profileId, certificateOrder: caOrder, ...mockActor });++ expect(mockCertificateIssuanceQueue.queueCertificateIssuance).not.toHaveBeenCalled();+ // The value matters, the storage form does not.+ const [persistedRow] = vi.mocked(mockCertificateRequestDAL.create).mock.calls[0] as [+ { basicConstraints?: unknown }+ ];+ const persisted =+ typeof persistedRow.basicConstraints === "string"+ ? (JSON.parse(persistedRow.basicConstraints) as unknown)+ : persistedRow.basicConstraints;+ expect(persisted).toEqual({ isCA: true, pathLength: 1 });+ expect(mockApprovalPolicyService.createRequestFromPolicy).toHaveBeenCalledWith(+ expect.objectContaining({+ requestData: expect.objectContaining({+ certificateRequest: expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })+ })+ })+ );+ });++ it("rejects a CA order for AWS Private CA without a path length", async () => {+ setupCa(CaType.AWS_PCA);++ await expect(+ service.orderCertificate({+ profileId,+ certificateOrder: { ...mockCertificateOrder, basicConstraints: { isCA: true } },+ ...mockActor+ })+ ).rejects.toThrow("path length between 0 and 3 is required");+ });+ });});describe("algorithm compatibility (integration tests)", () => {@@ -1908,6 +2040,77 @@ describe("CertificateV3Service", () => {);});+ it("preserves CA basicConstraints when renewing a CA certificate", async () => {+ const caCert = { ...mockOriginalCert, isCA: true, pathLength: 1 };+ vi.mocked(mockCertificateDAL.findById)+ .mockResolvedValueOnce(caCert)+ .mockResolvedValueOnce({ ...caCert, id: "cert-456", serialNumber: "789012" });+ vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);+ vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);+ vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue({+ ...mockPolicy,+ basicConstraints: { isCA: "allowed", maxPathLength: 2 }+ } as any);+ vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({+ isValid: true,+ errors: [],+ warnings: []+ } as any);+ vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({+ certificate: "renewed-cert",+ certificateChain: "renewed-chain",+ issuingCaCertificate: "issuing-ca",+ privateKey: "private-key",+ serialNumber: "789012",+ certificateId: "cert-456",+ commonName: "test.example.com",+ ca: mockCA+ } as any);++ const newCert = { ...caCert, id: "cert-456", serialNumber: "789012" };+ vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(newCert);+ vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(newCert);++ await service.renewCertificate({ certificateId: "cert-123", ...mockActor });++ expect(mockInternalCaService.issueCertFromCa).toHaveBeenCalledWith(+ expect.objectContaining({+ basicConstraints: { isCA: true, pathLength: 2 },+ pathLength: 1+ })+ );+ expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(+ expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })+ );+ });++ // The policy only sees a CA renewal as a CA request if basicConstraints are passed to it,+ // so this covers denied policies and tightened path lengths on both renewal paths.+ it("sends the certificate's CA constraints to policy validation on renewal", async () => {+ const caCert = { ...mockOriginalCert, isCA: true, pathLength: 3 };+ vi.mocked(mockCertificateDAL.findById).mockResolvedValue(caCert);+ vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);+ vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);+ vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);+ vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({+ isValid: false,+ errors: ["Requested path length (3) exceeds maximum allowed by policy (2)."],+ warnings: []+ } as any);++ await expect(service.renewCertificate({ certificateId: "cert-123", ...mockActor })).rejects.toThrow(+ "exceeds maximum allowed by policy"+ );++ expect(mockCertificatePolicyService.validateCertificateRequest).toHaveBeenCalledWith(+ "policy-123",+ expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 3 } })+ );+ expect(mockInternalCaService.issueCertFromCa).not.toHaveBeenCalled();+ });+it("should validate certificate against current policy during renewal", async () => {vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex 2572bd26c4..efca384285 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 {CertStatus} 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 {TCertificateAuthorityDALFactory,TCertificateAuthorityWithAssociatedCa@@ -2092,6 +2093,7 @@ export const certificateV3ServiceFactory = ({notAfter: certificateOrder.notAfter,signatureAlgorithm: certificateOrder.signatureAlgorithm,keyAlgorithm: certificateOrder.keyAlgorithm,+ basicConstraints: certificateOrder.basicConstraints,organization: certificateOrder.organization,organizationalUnit: certificateOrder.organizationalUnit,country: certificateOrder.country,@@ -2101,13 +2103,26 @@ export const certificateV3ServiceFactory = ({certificateRequest = applyProfileDefaults(rawRequest, profile.defaults);}+ const preflightCa = profile.caId ? await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId) : undefined;+ if (preflightCa) {+ assertCaInProfileProject(preflightCa, profile);+ }+// Check if this is a CA certificate request (either explicit basicConstraints or keyCertSign in key usages)// Per RFC 5280, keyCertSign implies CA certificate. Some clients (like cert-manager) only send keyCertSign without basicConstraints.const orderCsrHasKeyCertSign = certificateRequest.keyUsages?.includes(CertKeyUsageType.KEY_CERT_SIGN) ?? false;- if (certificateRequest.basicConstraints?.isCA || orderCsrHasKeyCertSign) {- throw new BadRequestError({- message: "CA certificate issuance is not supported for external certificate authorities."- });+ const orderWantsCaCertificate = certificateRequest.basicConstraints?.isCA || orderCsrHasKeyCertSign;+ if (orderWantsCaCertificate) {+ if (preflightCa?.externalCa?.type !== CaType.AWS_PCA) {+ throw new BadRequestError({+ message: "CA certificate issuance is not supported for this external certificate authority."+ });+ }++ certificateRequest.basicConstraints = {+ isCA: true,+ pathLength: certificateRequest.basicConstraints?.pathLength+ };}const mappedCertificateRequest = mapEnumsForValidation(certificateRequest);@@ -2117,11 +2132,6 @@ export const certificateV3ServiceFactory = ({mappedCertificateRequest.signatureAlgorithm = extractedSignatureAlgorithm;}- const preflightCa = profile.caId ? await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId) : undefined;- if (preflightCa) {- assertCaInProfileProject(preflightCa, profile);- }-const validationResult = await certificatePolicyService.validateCertificateRequest(profile.certificatePolicyId,mappedCertificateRequest@@ -2152,6 +2162,10 @@ export const certificateV3ServiceFactory = ({});}+ if (preflightCa?.externalCa?.type === CaType.AWS_PCA) {+ validateAwsPcaCaIssuanceInputs({ basicConstraints: certificateRequest.basicConstraints });+ }+const orderApprovalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](ApprovalPolicyType.CertRequest);@@ -2199,6 +2213,10 @@ export const certificateV3ServiceFactory = ({: null,enrollmentType: EnrollmentType.API,status: CertificateRequestStatus.PENDING_APPROVAL,+ // Issuance after approval reads this row, not the approval payload.+ basicConstraints: certificateRequest.basicConstraints+ ? JSON.stringify(certificateRequest.basicConstraints)+ : null,createdAt: certRequestCreatedAt} as Parameters<typeof certificateRequestDAL.create>[0] & { createdAt: Date },tx@@ -2232,7 +2250,8 @@ export const certificateV3ServiceFactory = ({notBefore: certificateOrder.notBefore?.toISOString(),notAfter: certificateOrder.notAfter?.toISOString(),signatureAlgorithm: certificateOrder.signatureAlgorithm,- keyAlgorithm: certificateOrder.keyAlgorithm+ keyAlgorithm: certificateOrder.keyAlgorithm,+ basicConstraints: certificateRequest.basicConstraints},certificateRequestId: certRequest.id};@@ -2375,7 +2394,8 @@ export const certificateV3ServiceFactory = ({country: certificateRequest.country,state: certificateRequest.state,locality: certificateRequest.locality,- domainComponents: certificateRequest.domainComponents+ domainComponents: certificateRequest.domainComponents,+ basicConstraints: certificateRequest.basicConstraints});if (metadata && metadata.length > 0) {@@ -2407,6 +2427,7 @@ export const certificateV3ServiceFactory = ({country: certificateRequest.country,state: certificateRequest.state,locality: certificateRequest.locality,+ basicConstraints: certificateRequest.basicConstraints,...(applicationId && { applicationId })});@@ -2619,7 +2640,10 @@ export const certificateV3ServiceFactory = ({ttl},signatureAlgorithm: originalCert.signatureAlgorithm || undefined,- keyAlgorithm: originalCert.keyAlgorithm || undefined+ keyAlgorithm: originalCert.keyAlgorithm || undefined,+ ...(originalCert.isCA && {+ basicConstraints: { isCA: true, pathLength: originalCert.pathLength ?? undefined }+ })};let validationResult: { isValid: boolean; errors: string[] } = { isValid: true, errors: [] };@@ -2688,6 +2712,10 @@ export const certificateV3ServiceFactory = ({friendlyName: originalCert.friendlyName || originalCert.commonName || "Renewed Certificate",commonName: originalCert.commonName || "",altNames: originalCert.altNames || "",+ ...(originalCert.isCA && {+ basicConstraints: { isCA: true, pathLength: policy?.basicConstraints?.maxPathLength },+ pathLength: originalCert.pathLength ?? undefined+ }),ttl,notBefore: normalizeDateForApi(notBefore),notAfter: normalizeDateForApi(notAfter),@@ -2863,7 +2891,10 @@ export const certificateV3ServiceFactory = ({country: certificateRequest.country,state: certificateRequest.state,locality: certificateRequest.locality,- domainComponents: certificateRequest.domainComponents+ domainComponents: certificateRequest.domainComponents,+ ...(originalCert.isCA && {+ basicConstraints: { isCA: true, pathLength: originalCert.pathLength ?? undefined }+ })});// Copy metadata from original cert to new cert and cert request@@ -2900,6 +2931,10 @@ export const certificateV3ServiceFactory = ({: [];const structuredAltNames = altNamesArray.map((san) => detectSanType(san));+ const renewalBasicConstraints = originalCert.isCA+ ? { isCA: true, pathLength: originalCert.pathLength ?? undefined }+ : undefined;+const certificateRequest = await certificateRequestService.createCertificateRequest({internal: true,actor,@@ -2927,7 +2962,8 @@ export const certificateV3ServiceFactory = ({locality: originalCert.subjectLocality || undefined,domainComponents: originalCert.subjectDomainComponents? originalCert.subjectDomainComponents.split(",")- : undefined+ : undefined,+ basicConstraints: renewalBasicConstraints});certificateRequestId = certificateRequest.id;@@ -2960,6 +2996,7 @@ export const certificateV3ServiceFactory = ({isRenewal: true,originalCertificateId: certificateId,certificateRequestId: certificateRequest.id,+ basicConstraints: renewalBasicConstraints,...(originalCert.applicationId && { applicationId: originalCert.applicationId })});diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.tsindex 5978b5de8e..398edd9909 100644--- a/backend/src/services/certificate-v3/certificate-v3-types.ts+++ b/backend/src/services/certificate-v3/certificate-v3-types.ts@@ -83,6 +83,10 @@ export type TOrderCertificateFromProfileDTO = {keyAlgorithm?: string;template?: string;csr?: string;+ basicConstraints?: {+ isCA: boolean;+ pathLength?: number;+ };organization?: string;organizationalUnit?: string;country?: string;diff --git a/backend/src/services/certificate/certificate-fns.test.ts b/backend/src/services/certificate/certificate-fns.test.tsindex 9a5f6168bb..cd5301f463 100644--- a/backend/src/services/certificate/certificate-fns.test.ts+++ b/backend/src/services/certificate/certificate-fns.test.ts@@ -1,6 +1,16 @@+import { webcrypto } from "node:crypto";++import * as x509 from "@peculiar/x509";+import { BadRequestError } from "@app/lib/errors";-import { buildCertificateBundle, CertificateThumbprintAlgorithm, normalizeThumbprint } from "./certificate-fns";+import {+ buildCertificateBundle,+ CertificateThumbprintAlgorithm,+ extractCertificateFields,+ normalizeThumbprint,+ parseCertificateBody+} from "./certificate-fns";describe("normalizeThumbprint", () => {const sha1Hex = "a".repeat(40);@@ -41,3 +51,61 @@ describe("buildCertificateBundle", () => {expect(buildCertificateBundle("CERT", "KEY", "CHAIN")).toBe("CERT\nCHAIN\nKEY\n");});});++describe("parseCertificateBody usages", () => {+ x509.cryptoProvider.set(webcrypto as unknown as Crypto);++ const buildCert = async (extensions: x509.Extension[]) => {+ const keys = await webcrypto.subtle.generateKey(+ {+ name: "RSASSA-PKCS1-v1_5",+ hash: "SHA-256",+ publicExponent: new Uint8Array([1, 0, 1]),+ modulusLength: 2048+ },+ true,+ ["sign", "verify"]+ );++ const cert = await x509.X509CertificateGenerator.createSelfSigned({+ serialNumber: "01",+ name: "CN=probe.example.com",+ notBefore: new Date("2026-01-01"),+ notAfter: new Date("2027-01-01"),+ keys: keys as CryptoKeyPair,+ signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },+ extensions+ });++ return Buffer.from(cert.toString("pem"));+ };++ // Must stay in the legacy camelCase form the rest of the codebase reads and writes.+ test("reads key usages and extended key usages off the certificate in legacy form", async () => {+ const pem = await buildCert([+ new x509.BasicConstraintsExtension(true, 1, true),+ new x509.KeyUsagesExtension(+ // eslint-disable-next-line no-bitwise+ x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign,+ true+ ),+ new x509.ExtendedKeyUsageExtension(["1.3.6.1.5.5.7.3.1"], false)+ ]);++ const parsed = parseCertificateBody(pem);++ expect(parsed.keyUsages).toEqual(["digitalSignature", "keyCertSign", "cRLSign"]);+ expect(parsed.extendedKeyUsages).toEqual(["serverAuth"]);+ expect(parsed.basicConstraints).toEqual({ isCA: true, pathLength: 1 });+ });++ test("omits the usage fields when the certificate carries no usage extensions", async () => {+ const pem = await buildCert([new x509.BasicConstraintsExtension(false)]);++ const fields = extractCertificateFields(pem);++ expect(fields).not.toHaveProperty("keyUsages");+ expect(fields).not.toHaveProperty("extendedKeyUsages");+ expect(fields.isCA).toBe(false);+ });+});diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.tsindex dd6e59a66d..57db69718b 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -8,7 +8,10 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";import { extractDnParts } from "../certificate-authority/certificate-authority-fns";import { getProjectKmsCertificateKeyId } from "../project/project-fns";import {+ CertExtendedKeyUsage,+ CertExtendedKeyUsageOIDToName,CertKeyAlgorithm,+ CertKeyUsage,CrlReason,TCertificateFingerprints,TCertificateSubject,@@ -270,7 +273,24 @@ export const parseCertificateBody = (decryptedCertificate: Buffer): TParsedCerti};}- return { subject, fingerprints, basicConstraints };+ let keyUsages: CertKeyUsage[] | undefined;+ const keyUsagesExt = certObj.getExtension(x509.KeyUsagesExtension);+ if (keyUsagesExt) {+ keyUsages = Object.values(CertKeyUsage).filter(+ // eslint-disable-next-line no-bitwise+ (keyUsage) => (x509.KeyUsageFlags[keyUsage] & keyUsagesExt.usages) !== 0+ );+ }++ let extendedKeyUsages: CertExtendedKeyUsage[] | undefined;+ const extendedKeyUsagesExt = certObj.getExtension(x509.ExtendedKeyUsageExtension);+ if (extendedKeyUsagesExt) {+ extendedKeyUsages = extendedKeyUsagesExt.usages+ .map((oid) => CertExtendedKeyUsageOIDToName[oid as string])+ .filter(Boolean);+ }++ return { subject, fingerprints, basicConstraints, keyUsages, extendedKeyUsages };} catch {// If we can't parse the certificate, return empty object (graceful degradation)return {};@@ -302,6 +322,11 @@ export const extractCertificateFields = (decryptedCertificate: Buffer) => {// Basic constraintsisCA: parsed.basicConstraints?.isCA ?? null,- pathLength: parsed.basicConstraints?.pathLength ?? null+ pathLength: parsed.basicConstraints?.pathLength ?? null,++ // Callers spread these last so the issued usages win over the requested ones. Absent when the+ // certificate carries no such extension, leaving the requested values in place.+ ...(parsed.keyUsages && { keyUsages: parsed.keyUsages }),+ ...(parsed.extendedKeyUsages && { extendedKeyUsages: parsed.extendedKeyUsages })};};diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.tsindex cd473b0ca9..5ea82d6761 100644--- a/backend/src/services/certificate/certificate-types.ts+++ b/backend/src/services/certificate/certificate-types.ts@@ -246,4 +246,6 @@ export type TParsedCertificateBody = {subject?: TCertificateSubject;fingerprints?: TCertificateFingerprints;basicConstraints?: TCertificateBasicConstraints;+ keyUsages?: CertKeyUsage[];+ extendedKeyUsages?: CertExtendedKeyUsage[];};diff --git a/backend/src/services/signer/signer-issuance-service.ts b/backend/src/services/signer/signer-issuance-service.tsindex 73187755f9..2a145a64a4 100644--- a/backend/src/services/signer/signer-issuance-service.ts+++ b/backend/src/services/signer/signer-issuance-service.ts@@ -591,6 +591,7 @@ export const signerIssuanceServiceFactory = ({} else {const awsResult = await awsPcaFns.orderCertificate({caId: job.caId,+ idempotencyKey: job.id,commonName: job.commonName,altNames: [],keyUsages: [CertKeyUsage.DIGITAL_SIGNATURE, CertKeyUsage.KEY_ENCIPHERMENT],diff --git a/docs/documentation/platform/pki/ca/aws-pca.mdx b/docs/documentation/platform/pki/ca/aws-pca.mdxindex 099784765e..a6c815bd4f 100644--- a/docs/documentation/platform/pki/ca/aws-pca.mdx+++ b/docs/documentation/platform/pki/ca/aws-pca.mdx@@ -103,6 +103,16 @@ See the [AWS Connection](/integrations/app-connections/aws) page for full setup</Step></Steps>+## Issuing CA Certificates++To issue a certificate with `CA:TRUE`, set **Basic Constraints** to allow CA certificates on the [Certificate Policy](/documentation/platform/pki/settings/policies), then tick **Issue as Certificate Authority** when requesting one.++AWS Private CA adds a few constraints:++- **Path length is required** on the request, and must be between `0` and `3`. There is no unlimited option.+- **Key usages are set by AWS** to digital signature, certificate signing and CRL signing, overriding the profile.+- The private CA in AWS must be in general-purpose mode, and its own path length must allow another CA beneath it.+## Troubleshooting**CA Not in ACTIVE Status**@@ -116,3 +126,7 @@ See the [AWS Connection](/integrations/app-connections/aws) page for full setup**Invalid CA ARN**- Double-check the ARN format: `arn:aws:acm-pca:<region>:<account-id>:certificate-authority/<ca-id>`.++**CA Certificate Rejected**++- Check the path length is between `0` and `3`, the policy's **Basic Constraints** allow CA certificates, and the CA is general-purpose. See [Issuing CA Certificates](#issuing-ca-certificates).diff --git a/docs/integrations/app-connections/aws.mdx b/docs/integrations/app-connections/aws.mdxindex 33ae28e997..c9c123958b 100644--- a/docs/integrations/app-connections/aws.mdx+++ b/docs/integrations/app-connections/aws.mdx@@ -340,6 +340,12 @@ Infisical supports two methods for connecting to AWS.Using a specific CA ARN in `Resource` is recommended over `"*"` to follow the principle of least privilege.</Note>+ <Note>+ If you further restrict `IssueCertificate` with an `acm-pca:TemplateArn` condition, include every template Infisical uses, or issuance fails with a permission error:++ - `arn:aws:acm-pca:::template/BlankEndEntityCertificate_APICSRPassthrough/V1` for end-entity certificates+ - `arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen{0,1,2,3}_APICSRPassthrough/V1` for [CA certificates](/documentation/platform/pki/ca/aws-pca#issuing-ca-certificates)+ </Note></Accordion><Accordion title="AWS ACM Public CA">Use the following custom policy to grant the minimum permissions required by Infisical to issue publicly-trusted certificates via AWS Certificate Manager and perform DNS validation through Route 53.@@ -822,6 +828,12 @@ Infisical supports two methods for connecting to AWS.Using a specific CA ARN in `Resource` is recommended over `"*"` to follow the principle of least privilege.</Note>+ <Note>+ If you further restrict `IssueCertificate` with an `acm-pca:TemplateArn` condition, include every template Infisical uses, or issuance fails with a permission error:++ - `arn:aws:acm-pca:::template/BlankEndEntityCertificate_APICSRPassthrough/V1` for end-entity certificates+ - `arn:aws:acm-pca:::template/SubordinateCACertificate_PathLen{0,1,2,3}_APICSRPassthrough/V1` for [CA certificates](/documentation/platform/pki/ca/aws-pca#issuing-ca-certificates)+ </Note></Accordion><Accordion title="AWS ACM Public CA">Use the following custom policy to grant the minimum permissions required by Infisical to issue publicly-trusted certificates via AWS Certificate Manager and perform DNS validation through Route 53.diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsxindex 5ae8cbd1f5..5a58daca35 100644--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx@@ -109,7 +109,13 @@ const extendedKeyUsagesField = z}).default({});-const buildFormSchema = (isAdcs: boolean) => {+type CaFormVariant = "default" | "adcs" | "awsPca";++// Mirrored in backend aws-pca-certificate-authority-enums.ts; update both.+const AWS_PCA_MAX_CA_PATH_LENGTH = 3;++const buildFormSchema = (variant: CaFormVariant) => {+ const isAdcs = variant === "adcs";const baseSchema = z.object({profileId: z.string().min(1, "Profile is required"),ttl: isAdcs ? z.string().trim().optional() : z.string().trim().min(1, "TTL is required"),@@ -141,11 +147,34 @@ const buildFormSchema = (isAdcs: boolean) => {extendedKeyUsages: extendedKeyUsagesField});- return z.discriminatedUnion("requestMethod", [csrSchema, managedSchema]);+ return z+ .discriminatedUnion("requestMethod", [csrSchema, managedSchema])+ .superRefine((data, ctx) => {+ if (variant !== "awsPca" || data.requestMethod !== RequestMethod.MANAGED) return;+ if (!data.basicConstraints?.isCA) return;++ const { pathLength } = data.basicConstraints;+ if (pathLength === undefined || pathLength === null) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["basicConstraints", "pathLength"],+ message: `AWS Private CA requires a path length between 0 and ${AWS_PCA_MAX_CA_PATH_LENGTH} for CA certificates`+ });+ return;+ }+ if (pathLength > AWS_PCA_MAX_CA_PATH_LENGTH) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ["basicConstraints", "pathLength"],+ message: `AWS Private CA supports a maximum path length of ${AWS_PCA_MAX_CA_PATH_LENGTH}`+ });+ }+ });};-const strictFormSchema = buildFormSchema(false);-const adcsFormSchema = buildFormSchema(true);+const strictFormSchema = buildFormSchema("default");+const adcsFormSchema = buildFormSchema("adcs");+const awsPcaFormSchema = buildFormSchema("awsPca");export type FormData = z.infer<typeof adcsFormSchema>;@@ -274,6 +303,7 @@ export const CertificateIssuanceModal = ({const { mutateAsync: issueCertificate } = useUnifiedCertificateIssuance();const isAdcsProfileRef = useRef(false);+ const isAwsPcaProfileRef = useRef(false);const {control,@@ -284,12 +314,12 @@ export const CertificateIssuanceModal = ({formState,formState: { isSubmitting }} = useForm<FormData>({- resolver: (values, context, options) =>- zodResolver(isAdcsProfileRef.current ? adcsFormSchema : strictFormSchema)(- values,- context,- options- ),+ resolver: (values, context, options) => {+ let schema = strictFormSchema;+ if (isAdcsProfileRef.current) schema = adcsFormSchema;+ else if (isAwsPcaProfileRef.current) schema = awsPcaFormSchema;+ return zodResolver(schema)(values, context, options);+ },defaultValues: {requestMethod: RequestMethod.MANAGED,profileId: profileId || "",@@ -326,6 +356,9 @@ export const CertificateIssuanceModal = ({const isAdcsProfile = externalCaType === CaType.ADCS || externalCaType === CaType.AZURE_AD_CS;isAdcsProfileRef.current = isAdcsProfile;+ const isAwsPcaProfile = externalCaType === CaType.AWS_PCA;+ isAwsPcaProfileRef.current = isAwsPcaProfile;+const externalCaHint ="Validity, key usages, extended key usages and basic constraints are controlled by the external CA's certificate template.";@@ -862,8 +895,9 @@ export const CertificateIssuanceModal = ({name="basicConstraints.pathLength"render={({ field, fieldState: { error } }) => {const isPathLengthRequired =- typeof constraints.maxPathLength === "number" &&- constraints.maxPathLength !== -1;+ isAwsPcaProfile ||+ (typeof constraints.maxPathLength === "number" &&+ constraints.maxPathLength !== -1);return (<Field><FieldLabel>@@ -876,6 +910,11 @@ export const CertificateIssuanceModal = ({{...field}type="number"min={0}+ max={+ isAwsPcaProfile+ ? AWS_PCA_MAX_CA_PATH_LENGTH+ : undefined+ }isError={Boolean(error)}placeholder={isPathLengthRequired@@ -896,10 +935,9 @@ export const CertificateIssuanceModal = ({}}/><FieldDescription>- Sets the pathLen for this CA certificate. Controls how- many levels of sub-CAs can exist below. Empty means- unlimited; 0 means it can only sign end-entity- certificates.+ {isAwsPcaProfile+ ? `Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. AWS Private CA supports 0 to ${AWS_PCA_MAX_CA_PATH_LENGTH}; 0 means it can only sign end-entity certificates.`+ : "Sets the pathLen for this CA certificate. Controls how many levels of sub-CAs can exist below. Empty means unlimited; 0 means it can only sign end-entity certificates."}</FieldDescription><FieldError errors={[error]} /></Field>