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
import { ForbiddenError, subject } from "@casl/ability";
import { randomUUID } from "crypto";
import { Knex } from "knex";
import { ActionProjectType } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionCertificateProfileActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { TPkiAcmeAccountDALFactory } from "@app/ee/services/pki-acme/pki-acme-account-dal";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
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";
import { caUsesExternalIssuanceQueue } from "@app/services/certificate-authority/certificate-authority-maps";
import { TCertificateIssuanceQueueFactory } from "@app/services/certificate-authority/certificate-issuance-queue";
import { validateGoDaddyIssuanceInputs } from "@app/services/certificate-authority/godaddy/godaddy-certificate-authority-validators";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
import {
buildSubjectOverrideForCsr,
extractAlgorithmsFromCSR,
extractCertificateRequestFromCSR
} from "@app/services/certificate-common/certificate-csr-utils";
import {
parseIssuedCustomExtensions,
toRequestCustomExtensions,
TRequestCustomExtension,
TResolvedCustomExtension
} from "@app/services/certificate-common/certificate-extension-fns";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateRequest, TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import { EnrollmentType, IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
import {
CertificateApplicationAlertEvent,
TCertificateAlertEventEmitter,
TCertificateAlertEventInput
} 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 { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { CertKeyAlgorithm, CertSignatureAlgorithm, CertStatus } from "@app/services/certificate/certificate-types";
import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { queueCertificateFilterReconcile } from "@app/services/pki-sync/pki-sync-utils";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
import { copyMetadataFromRequestToCertificate } from "@app/services/resource-metadata/resource-metadata-fns";
import {
CertExtendedKeyUsageType,
CertKeyUsageType,
CertPolicyState
} from "../certificate-common/certificate-constants";
import {
calculateFinalRenewBeforeDays,
extractCertificateFromBuffer,
generateSelfSignedCertificate,
getEffectiveAlgorithms,
resolveEffectiveApiConfig,
validateAlgorithmCompatibility,
validateCaSupport
} from "../certificate-common/certificate-issuance-utils";
import {
assertCertificateQuotaForProject,
recordNewCertificateQuotaKey
} from "../certificate-common/certificate-quota-fns";
import {
bufferToString,
buildCertificateSubjectFromTemplate,
buildSubjectAlternativeNamesFromTemplate,
convertExtendedKeyUsageArrayToLegacy,
convertKeyUsageArrayToLegacy,
mapEnumsForValidation,
normalizeDateForApi
} from "../certificate-common/certificate-utils";
import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";
import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
import { applyProfileDefaults } from "./certificate-v3-fns";
import { TAltNameEntry, TCertificateIssuanceResponse } from "./certificate-v3-types";
export type TIssueCertificateFromApprovedRequestDeps = {
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findById">;
certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
acmeAccountDAL: Pick<TPkiAcmeAccountDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
internalCaService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa" | "issueCertFromCa">;
certificateDAL: Pick<TCertificateDALFactory, "findById" | "updateById" | "transaction" | "create">;
pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "create">;
kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
projectDAL: TProjectDALFactory;
certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateCertificateRequest" | "getPolicyById">;
certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "queueCertificateIssuance">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;
pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;
apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;
usageCounterDAL: Pick<
TUsageCounterDALFactory,
"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
>;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;
};
export type TCertificateApprovalService = {
issueCertificate: (certificateRequestId: string) => Promise<TCertificateIssuanceResponse>;
};
const buildRevalidationRequest = ({
csr,
commonName,
organization,
organizationalUnit,
country,
state,
locality,
keyUsages,
extendedKeyUsages,
keyAlgorithm,
signatureAlgorithm,
notBefore,
notAfter,
altNames,
basicConstraints,
customExtensions,
profileDefaults,
ttl
}: {
csr?: string | null;
commonName?: string | null;
organization?: string | null;
organizationalUnit?: string | null;
country?: string | null;
state?: string | null;
locality?: string | null;
keyUsages?: string[] | null;
extendedKeyUsages?: string[] | null;
keyAlgorithm?: string | null;
signatureAlgorithm?: string | null;
notBefore?: Date | null;
notAfter?: Date | null;
altNames?: TAltNameEntry[] | null;
basicConstraints?: { isCA: boolean; pathLength?: number | null } | null;
customExtensions?: TRequestCustomExtension[];
profileDefaults: Parameters<typeof applyProfileDefaults>[1];
ttl?: string;
}): TCertificateRequest => {
const reconstructedRequest: TCertificateRequest = csr
? applyProfileDefaults(extractCertificateRequestFromCSR(csr), profileDefaults)
: applyProfileDefaults(
{
commonName: commonName || undefined,
organization: organization || undefined,
organizationalUnit: organizationalUnit || undefined,
country: country || undefined,
state: state || undefined,
locality: locality || undefined,
keyUsages: (keyUsages as CertKeyUsageType[] | null) || undefined,
extendedKeyUsages: (extendedKeyUsages as CertExtendedKeyUsageType[] | null) || undefined,
subjectAlternativeNames: altNames ?? undefined,
keyAlgorithm: keyAlgorithm || undefined,
signatureAlgorithm: signatureAlgorithm || undefined
},
profileDefaults
);
const mappedRequest = mapEnumsForValidation(reconstructedRequest);
if (csr) {
const { keyAlgorithm: csrKeyAlg, signatureAlgorithm: csrSigAlg } = extractAlgorithmsFromCSR(csr);
mappedRequest.keyAlgorithm = csrKeyAlg;
mappedRequest.signatureAlgorithm = csrSigAlg;
}
// The stored value wins over anything reconstructed from the CSR or profile defaults.
if (customExtensions?.length) {
mappedRequest.customExtensions = customExtensions;
}
if (basicConstraints) {
mappedRequest.basicConstraints = {
isCA: basicConstraints.isCA,
pathLength: basicConstraints.pathLength ?? undefined
};
}
if (notAfter) {
mappedRequest.notBefore = notBefore || undefined;
mappedRequest.notAfter = notAfter;
} else if (ttl) {
mappedRequest.validity = { ttl };
}
return mappedRequest;
};
export const certificateApprovalServiceFactory = (
deps: TIssueCertificateFromApprovedRequestDeps
): TCertificateApprovalService => {
const {
certificateRequestDAL,
certificateProfileDAL,
acmeAccountDAL,
permissionService,
certificateAuthorityDAL,
internalCaService,
certificateDAL,
certificateBodyDAL,
certificateSecretDAL,
kmsService,
projectDAL,
licenseService,
usageCounterDAL,
keyStore,
certificatePolicyService,
certificateIssuanceQueue,
resourceMetadataDAL,
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL,
pkiSyncQueue,
pkiAlertV2Queue,
certificateAlertEventEmitter
} = deps;
const $emitIssuanceAlert = (input: Omit<TCertificateAlertEventInput, "eventType">, tx: Knex) =>
certificateAlertEventEmitter.emit({ ...input, eventType: CertificateApplicationAlertEvent.Issuance }, tx);
const $queueIssuanceAlert = async (certificateId: string, projectId: string, applicationId?: string | null) => {
try {
await pkiAlertV2Queue?.queueCertificateEvent({
certificateId,
projectId,
eventType: PkiAlertEventType.ISSUANCE,
applicationId: applicationId ?? null
});
} catch (error) {
logger.warn(
error,
`Failed to queue PKI issuance alert event for approved request [certificateId=${certificateId}]`
);
}
};
const $validateProfileAndPermissions = async ({
profileId,
actor,
actorId,
actorAuthMethod,
actorOrgId,
requiredEnrollmentType,
isInternal = false
}: {
profileId: string;
actor?: ActorType;
actorId?: string;
actorAuthMethod?: ActorAuthMethod;
actorOrgId?: string;
requiredEnrollmentType: EnrollmentType;
isInternal?: boolean;
}) => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
if (!profile) {
throw new NotFoundError({ message: "Certificate profile not found" });
}
if (isInternal) {
return profile;
}
if (profile.enrollmentType !== requiredEnrollmentType) {
throw new ForbiddenRequestError({
message: `Profile is not configured for ${requiredEnrollmentType} enrollment`
});
}
if (
(actor === ActorType.ACME_ACCOUNT && requiredEnrollmentType === EnrollmentType.ACME) ||
(actor === ActorType.EST_ACCOUNT && requiredEnrollmentType === EnrollmentType.EST)
) {
const account = await acmeAccountDAL.findById(actorId!);
if (!account) {
throw new NotFoundError({ message: "ACME account not found" });
}
if (account.profileId !== profile.id) {
throw new ForbiddenRequestError({
message: "ACME account is not associated with this profile"
});
}
return profile;
}
const { permission } = await permissionService.getProjectPermission({
actor: actor!,
actorId: actorId!,
projectId: profile.projectId,
actorAuthMethod: actorAuthMethod!,
actorOrgId: actorOrgId!,
actionProjectType: ActionProjectType.CertificateManager
});
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionCertificateProfileActions.IssueCert,
subject(ProjectPermissionSub.CertificateProfiles, {
slug: profile.slug
})
);
return profile;
};
const $createSelfSignedCertificateRecord = async ({
selfSignedResult,
certificateRequest,
profile,
customExtensions,
tx
}: {
selfSignedResult: Awaited<ReturnType<typeof generateSelfSignedCertificate>>;
customExtensions?: TResolvedCustomExtension[];
certificateRequest: {
commonName?: string;
keyUsages?: CertKeyUsageType[];
extendedKeyUsages?: CertExtendedKeyUsageType[];
};
profile?: { id: string; projectId: string } | null;
tx: Parameters<TCertificateDALFactory["create"]>[1];
}) => {
const subjectCommonName =
(selfSignedResult.certificateSubject.common_name as string) || certificateRequest.commonName || "";
const altNamesList = selfSignedResult.subjectAlternativeNames.map((san) => san.value).join(",");
const projectId = profile?.projectId;
if (!projectId) {
throw new BadRequestError({ message: "Project ID is required for certificate creation" });
}
return certificateDAL.create(
{
serialNumber: selfSignedResult.serialNumber,
friendlyName: subjectCommonName,
commonName: subjectCommonName,
altNames: altNamesList,
status: CertStatus.ACTIVE,
notBefore: selfSignedResult.notBefore,
notAfter: selfSignedResult.notAfter,
projectId,
keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
customExtensions: JSON.stringify(parseIssuedCustomExtensions(selfSignedResult.certificate, customExtensions)),
profileId: profile?.id || null
},
tx
);
};
const $createEncryptedCertificateData = async ({
certificateId,
certificate,
privateKey,
projectId,
tx
}: {
certificateId: string;
certificate: Buffer;
privateKey: Buffer;
projectId: string;
tx: Parameters<TCertificateBodyDALFactory["create"]>[1];
}) => {
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
projectId,
projectDAL,
kmsService
});
const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKeyId });
const encryptedCertificate = await kmsEncryptor({
plainText: certificate
});
await certificateBodyDAL.create(
{
certId: certificateId,
encryptedCertificate: encryptedCertificate.cipherTextBlob
},
tx
);
const encryptedPrivateKey = await kmsEncryptor({
plainText: privateKey
});
await certificateSecretDAL.create(
{
certId: certificateId,
encryptedPrivateKey: encryptedPrivateKey.cipherTextBlob
},
tx
);
};
const $processSelfSignedCertificate = async ({
certificateRequest,
policy,
profile,
effectiveAlgorithms,
customExtensions,
tx
}: {
certificateRequest: {
commonName?: string;
organization?: string;
organizationalUnit?: string;
country?: string;
state?: string;
locality?: string;
domainComponents?: string[];
keyUsages?: CertKeyUsageType[];
extendedKeyUsages?: CertExtendedKeyUsageType[];
validity: { ttl: string };
notBefore?: Date;
notAfter?: Date;
};
policy?: {
subject?: TSubjectRule[];
sans?: Array<{
type: string;
allowed?: string[];
required?: string[];
denied?: string[];
}>;
} | null;
profile?: { id: string; projectId: string } | null;
effectiveAlgorithms: {
signatureAlgorithm: CertSignatureAlgorithm;
keyAlgorithm: CertKeyAlgorithm;
};
customExtensions?: TResolvedCustomExtension[];
tx: Parameters<TCertificateDALFactory["create"]>[1];
}) => {
const projectId = profile?.projectId;
if (!projectId) {
throw new BadRequestError({ message: "Project ID is required for certificate creation" });
}
const selfSignedResult = await generateSelfSignedCertificate({
certificateRequest,
policy,
effectiveSignatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
effectiveKeyAlgorithm: effectiveAlgorithms.keyAlgorithm,
customExtensions
});
const certificateData = await $createSelfSignedCertificateRecord({
selfSignedResult,
certificateRequest,
profile,
customExtensions,
tx
});
await certificateDAL.updateById(
certificateData.id,
{
signatureAlgorithm: effectiveAlgorithms.signatureAlgorithm,
keyAlgorithm: effectiveAlgorithms.keyAlgorithm
},
tx
);
await $createEncryptedCertificateData({
certificateId: certificateData.id,
certificate: selfSignedResult.certificate,
privateKey: selfSignedResult.privateKey,
projectId,
tx
});
return {
selfSignedResult,
certificateData
};
};
const $processCSRSigningRequest = async (
certRequest: NonNullable<Awaited<ReturnType<TCertificateRequestDALFactory["findById"]>>>,
certificateRequestId: string,
profileId: string,
ttl: string
): Promise<TCertificateIssuanceResponse> => {
const { csr } = certRequest;
const profile = await $validateProfileAndPermissions({
profileId,
requiredEnrollmentType: (certRequest.enrollmentType as EnrollmentType) || EnrollmentType.API,
isInternal: true
});
if (!profile.caId) {
throw new BadRequestError({
message: "Self-signed certificates are not supported for CSR signing"
});
}
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId);
if (!ca) {
throw new NotFoundError({ message: "Certificate Authority not found" });
}
assertCaInProfileProject(ca, profile);
validateCaSupport(ca, "CSR signing");
const certPolicy = await certificatePolicyService.getPolicyById({
actor: undefined,
actorId: undefined,
actorAuthMethod: undefined,
actorOrgId: undefined,
policyId: profile.certificatePolicyId,
internal: true
});
if (!certPolicy) {
throw new NotFoundError({ message: "Certificate policy not found for this profile" });
}
validateAlgorithmCompatibility(ca, certPolicy);
const csrBasicConstraints = certRequest.basicConstraints as { isCA: boolean; pathLength?: number } | undefined;
const policyIsCAState: CertPolicyState =
(certPolicy.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED;
if (csrBasicConstraints?.isCA && policyIsCAState === CertPolicyState.DENIED) {
throw new BadRequestError({
message:
"CA certificate issuance is not allowed by the current policy. The policy's CA:true basicConstraints must be set to 'allowed' or 'required'."
});
}
let effectiveBasicConstraints = csrBasicConstraints;
const storedPathLength = csrBasicConstraints?.pathLength;
let effectivePathLength = storedPathLength !== undefined && storedPathLength >= 0 ? storedPathLength : undefined;
if (csrBasicConstraints?.isCA && policyIsCAState !== CertPolicyState.DENIED) {
const policyMaxPathLength = certPolicy.basicConstraints?.maxPathLength;
effectiveBasicConstraints = {
isCA: true,
pathLength: policyMaxPathLength
};
if (
policyMaxPathLength !== undefined &&
policyMaxPathLength !== null &&
policyMaxPathLength !== -1 &&
(csrBasicConstraints.pathLength === undefined || csrBasicConstraints.pathLength === null)
) {
effectivePathLength = policyMaxPathLength;
}
}
const reconstructedRequest = applyProfileDefaults(extractCertificateRequestFromCSR(csr || ""), profile.defaults);
const { keyAlgorithm: reconstructedKeyAlg, signatureAlgorithm: reconstructedSigAlg } = extractAlgorithmsFromCSR(
csr || ""
);
const mappedReconstructedRequest = mapEnumsForValidation(reconstructedRequest);
mappedReconstructedRequest.keyAlgorithm = reconstructedKeyAlg;
mappedReconstructedRequest.signatureAlgorithm = reconstructedSigAlg;
if (certRequest.notAfter) {
mappedReconstructedRequest.notBefore = certRequest.notBefore || undefined;
mappedReconstructedRequest.notAfter = certRequest.notAfter;
} else {
mappedReconstructedRequest.validity = { ttl };
}
if (effectiveBasicConstraints) {
mappedReconstructedRequest.basicConstraints = effectiveBasicConstraints;
}
mappedReconstructedRequest.customExtensions = toRequestCustomExtensions(certRequest.customExtensions);
// Same re-check the non-CSR branch does: this path returns before that one runs, and an approval
// can land days after the count it was compared against at submit.
const {
quotaOrgId: csrQuotaOrgId,
isNewQuotaKey: isNewCsrQuotaKey,
isWildcard: isCsrWildcard
} = await assertCertificateQuotaForProject({
projectId: profile.projectId,
commonName: mappedReconstructedRequest.commonName,
// A CSR-derived request carries its SANs in subjectAlternativeNames, not altNames.
altNames: (mappedReconstructedRequest.subjectAlternativeNames ?? [])
.map((san: { value: string }) => san.value)
.join(","),
deps: { projectDAL, licenseService, usageCounterDAL, keyStore },
isApprovedRequest: true
});
const revalidationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
mappedReconstructedRequest
);
if (!revalidationResult.isValid) {
throw new BadRequestError({
message: `Certificate request validation failed: ${revalidationResult.errors.join(", ")}`
});
}
const subjectOverride = buildSubjectOverrideForCsr(csr || "", {
commonName: reconstructedRequest.commonName,
organization: reconstructedRequest.organization,
organizationalUnit: reconstructedRequest.organizationalUnit,
country: reconstructedRequest.country,
state: reconstructedRequest.state,
locality: reconstructedRequest.locality,
domainComponents: reconstructedRequest.domainComponents
});
// This path is already intent-first: the certificate request exists (it was created when the
// approval was requested), so it only needs the same treatment as direct issuance — no
// transaction held across the CA key access and signing, with the bookkeeping committed
// atomically alongside the certificate rows via onPersisted.
const effectiveApiConfig = await resolveEffectiveApiConfig({
applicationId: certRequest.applicationId ?? undefined,
profileId,
profileApiConfig: profile.apiConfig,
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL
});
const certResult = await internalCaService.signCertFromCa({
isInternal: true,
caId: ca.id,
csr: csr || "",
ttl,
subjectOverride,
altNames: undefined,
keyUsages: reconstructedRequest.keyUsages
? convertKeyUsageArrayToLegacy(reconstructedRequest.keyUsages)
: undefined,
extendedKeyUsages: reconstructedRequest.extendedKeyUsages
? convertExtendedKeyUsageArrayToLegacy(reconstructedRequest.extendedKeyUsages)
: undefined,
notBefore: normalizeDateForApi(certRequest.notBefore || undefined),
notAfter: normalizeDateForApi(certRequest.notAfter || undefined),
signatureAlgorithm: certRequest.signatureAlgorithm || undefined,
keyAlgorithm: certRequest.keyAlgorithm || undefined,
customExtensions: revalidationResult.resolvedCustomExtensions,
isFromProfile: true,
basicConstraints: effectiveBasicConstraints,
pathLength: effectivePathLength,
onPersisted: async (newCert, tx) => {
const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
{ apiConfig: effectiveApiConfig },
ttl,
new Date(newCert.notAfter)
);
const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = { profileId };
if (finalRenewBeforeDays !== undefined) {
updateData.renewBeforeDays = finalRenewBeforeDays;
}
if (certRequest.applicationId) {
updateData.applicationId = certRequest.applicationId;
}
await certificateDAL.updateById(newCert.id, updateData, tx);
await certificateRequestDAL.updateById(
certificateRequestId,
{
status: CertificateRequestStatus.ISSUED,
certificateId: newCert.id
},
tx
);
// Copy metadata from cert request to newly issued cert
await copyMetadataFromRequestToCertificate(resourceMetadataDAL, {
certificateRequestId,
certificateId: newCert.id,
tx
});
await $emitIssuanceAlert(
{
certificateId: newCert.id,
projectId: profile.projectId,
orgId: profile.project?.orgId,
applicationId: certRequest.applicationId
},
tx
);
}
});
const { certificate, certificateChain, issuingCaCertificate, serialNumber } = certResult;
await $queueIssuanceAlert(certResult.certificateId, profile.projectId, certRequest.applicationId);
if (certResult.certificateId && certRequest.applicationId) {
await queueCertificateFilterReconcile(certResult.certificateId, certRequest.applicationId, pkiSyncQueue);
}
const certificateString = extractCertificateFromBuffer(certificate as unknown as Buffer);
const certificateChainString = extractCertificateFromBuffer(certificateChain as unknown as Buffer);
if (isNewCsrQuotaKey) await recordNewCertificateQuotaKey(csrQuotaOrgId, { keyStore }, isCsrWildcard);
return {
status: CertificateRequestStatus.ISSUED,
certificate: certificateString,
issuingCaCertificate: extractCertificateFromBuffer(issuingCaCertificate as unknown as Buffer),
certificateChain: certificateChainString,
serialNumber,
certificateId: certResult.certificateId,
certificateRequestId,
projectId: profile.projectId,
profileName: profile.slug,
commonName: certResult.commonName || ""
};
};
const $processExternalCARequest = async (
certRequest: NonNullable<Awaited<ReturnType<TCertificateRequestDALFactory["findById"]>>>,
certificateRequestId: string,
profile: NonNullable<Awaited<ReturnType<TCertificateProfileDALFactory["findByIdWithConfigs"]>>>,
altNames: TAltNameEntry[] | null,
ttl?: string
): Promise<TCertificateIssuanceResponse | null> => {
if (!profile.caId) {
return null;
}
const targetCa = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId);
if (!targetCa) {
return null;
}
assertCaInProfileProject(targetCa, profile);
const caType = (targetCa.externalCa?.type as CaType) ?? CaType.INTERNAL;
if (!caUsesExternalIssuanceQueue(caType)) {
return null;
}
// This branch returns before the shared re-check below, so it needs its own. Not recorded: the
// issuance queue creates the certificate later, once the external CA responds.
await assertCertificateQuotaForProject({
projectId: profile.projectId,
commonName: certRequest.commonName,
altNames: (altNames ?? []).map((san) => san.value).join(","),
deps: { projectDAL, licenseService, usageCounterDAL, keyStore },
isApprovedRequest: true
});
// Pre-flight validation for ACM — fail the approval synchronously rather than
// letting the job produce a FAILED request row after the approver already accepted.
if (caType === CaType.AWS_ACM_PUBLIC_CA) {
validateAcmIssuanceInputs({
csr: certRequest.csr || undefined,
keyAlgorithm: certRequest.keyAlgorithm || undefined,
altNames: altNames ?? undefined,
ttl,
organization: certRequest.organization || undefined,
organizationalUnit: certRequest.organizationalUnit || undefined,
country: certRequest.country || undefined,
state: certRequest.state || undefined,
locality: certRequest.locality || undefined
});
}
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.
const csrDerived = certRequest.csr ? extractCertificateRequestFromCSR(certRequest.csr) : undefined;
validateGoDaddyIssuanceInputs({
keyAlgorithm: certRequest.csr
? extractAlgorithmsFromCSR(certRequest.csr).keyAlgorithm
: certRequest.keyAlgorithm || undefined,
altNames: csrDerived?.subjectAlternativeNames ?? altNames ?? undefined,
commonName: csrDerived?.commonName ?? certRequest.commonName ?? undefined
});
}
const effectiveTtl = ttl || "1y";
const mappedReconstructedRequest = buildRevalidationRequest({
csr: certRequest.csr,
commonName: certRequest.commonName,
organization: certRequest.organization,
organizationalUnit: certRequest.organizationalUnit,
country: certRequest.country,
state: certRequest.state,
locality: certRequest.locality,
keyUsages: certRequest.keyUsages,
extendedKeyUsages: certRequest.extendedKeyUsages,
keyAlgorithm: certRequest.keyAlgorithm,
signatureAlgorithm: certRequest.signatureAlgorithm,
notBefore: certRequest.notBefore,
notAfter: certRequest.notAfter,
altNames,
basicConstraints: certRequest.basicConstraints as { isCA: boolean; pathLength?: number | null } | null,
customExtensions: toRequestCustomExtensions(certRequest.customExtensions),
profileDefaults: profile.defaults,
ttl: effectiveTtl
});
const revalidationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
mappedReconstructedRequest
);
if (!revalidationResult.isValid) {
throw new BadRequestError({
message: `Certificate request validation failed: ${revalidationResult.errors.join(", ")}`
});
}
const orderId = randomUUID();
await certificateIssuanceQueue.queueCertificateIssuance({
certificateId: orderId,
profileId: profile.id,
caId: profile.caId || "",
caType,
ttl: effectiveTtl,
signatureAlgorithm: certRequest.signatureAlgorithm || "",
keyAlgorithm: certRequest.keyAlgorithm || "",
commonName: mappedReconstructedRequest.commonName || "",
altNames:
mappedReconstructedRequest.subjectAlternativeNames?.map((san) => ({ type: san.type, value: san.value })) || [],
keyUsages: convertKeyUsageArrayToLegacy(mappedReconstructedRequest.keyUsages) || [],
extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(mappedReconstructedRequest.extendedKeyUsages) || [],
certificateRequestId,
csr: certRequest.csr || undefined,
organization: mappedReconstructedRequest.organization || undefined,
organizationalUnit: mappedReconstructedRequest.organizationalUnit || undefined,
country: mappedReconstructedRequest.country || undefined,
state: mappedReconstructedRequest.state || undefined,
locality: mappedReconstructedRequest.locality || undefined,
basicConstraints: certRequest.basicConstraints as { isCA: boolean; pathLength?: number | null } | null,
customExtensions: revalidationResult.resolvedCustomExtensions,
...(certRequest.applicationId && { applicationId: certRequest.applicationId })
});
return {
status: CertificateRequestStatus.PENDING,
certificate: "",
issuingCaCertificate: "",
certificateChain: "",
serialNumber: "",
certificateId: "",
certificateRequestId,
projectId: profile.projectId,
profileName: profile.slug,
commonName: certRequest.commonName || ""
};
};
const $processSelfSignedRequest = async (
certificateRequestInput: {
commonName?: string;
keyUsages?: CertKeyUsageType[];
extendedKeyUsages?: CertExtendedKeyUsageType[];
altNames?: TAltNameEntry[];
validity: { ttl: string };
notBefore?: Date;
notAfter?: Date;
signatureAlgorithm?: string;
keyAlgorithm?: string;
organization?: string;
organizationalUnit?: string;
country?: string;
state?: string;
locality?: string;
basicConstraints?: { isCA: boolean; pathLength?: number };
},
certificateRequestId: string,
profile: NonNullable<Awaited<ReturnType<TCertificateProfileDALFactory["findByIdWithConfigs"]>>>,
certPolicy: NonNullable<Awaited<ReturnType<TCertificatePolicyServiceFactory["getPolicyById"]>>>,
applicationId?: string | null,
customExtensions?: TResolvedCustomExtension[]
): Promise<TCertificateIssuanceResponse> => {
const effectiveSignatureAlgorithm = certificateRequestInput.signatureAlgorithm as
| CertSignatureAlgorithm
| undefined;
const effectiveKeyAlgorithm = certificateRequestInput.keyAlgorithm as CertKeyAlgorithm | undefined;
const result = await certificateDAL.transaction(async (tx) => {
const effectiveAlgorithms = getEffectiveAlgorithms(effectiveSignatureAlgorithm, effectiveKeyAlgorithm);
const processResult = await $processSelfSignedCertificate({
certificateRequest: certificateRequestInput,
policy: certPolicy,
profile,
effectiveAlgorithms,
customExtensions,
tx
});
await certificateRequestDAL.updateById(
certificateRequestId,
{
status: CertificateRequestStatus.ISSUED,
certificateId: processResult.certificateData.id
},
tx
);
// Copy metadata from cert request to newly issued cert
await copyMetadataFromRequestToCertificate(resourceMetadataDAL, {
certificateRequestId,
certificateId: processResult.certificateData.id,
tx
});
const effectiveApiConfig = await resolveEffectiveApiConfig({
applicationId: applicationId ?? undefined,
profileId: profile.id,
profileApiConfig: profile.apiConfig,
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL
});
const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
{ apiConfig: effectiveApiConfig },
certificateRequestInput.validity.ttl,
processResult.selfSignedResult.notAfter
);
if (finalRenewBeforeDays !== undefined) {
await certificateDAL.updateById(
processResult.certificateData.id,
{
renewBeforeDays: finalRenewBeforeDays
},
tx
);
}
if (applicationId) {
await certificateDAL.updateById(processResult.certificateData.id, { applicationId }, tx);
}
await $emitIssuanceAlert(
{
certificateId: processResult.certificateData.id,
projectId: profile.projectId,
orgId: profile.project?.orgId,
applicationId
},
tx
);
return processResult;
});
const { selfSignedResult, certificateData } = result;
await $queueIssuanceAlert(certificateData.id, profile.projectId, applicationId);
if (certificateData.id && applicationId) {
await queueCertificateFilterReconcile(certificateData.id, applicationId, pkiSyncQueue);
}
const subjectCommonName =
(selfSignedResult.certificateSubject.common_name as string) ||
certificateRequestInput.commonName ||
"Self-signed Certificate";
return {
status: CertificateRequestStatus.ISSUED,
certificate: selfSignedResult.certificate.toString("utf8"),
issuingCaCertificate: "",
certificateChain: selfSignedResult.certificate.toString("utf8"),
privateKey: selfSignedResult.privateKey.toString("utf8"),
serialNumber: selfSignedResult.serialNumber,
certificateId: certificateData.id,
certificateRequestId,
projectId: profile.projectId,
profileName: profile.slug,
commonName: subjectCommonName
};
};
const $processCASignedRequest = async (
certificateRequestInput: {
commonName?: string;
keyUsages?: CertKeyUsageType[];
extendedKeyUsages?: CertExtendedKeyUsageType[];
altNames?: TAltNameEntry[];
validity: { ttl: string };
notBefore?: Date;
notAfter?: Date;
signatureAlgorithm?: string;
keyAlgorithm?: string;
organization?: string;
organizationalUnit?: string;
country?: string;
state?: string;
locality?: string;
domainComponents?: string[];
basicConstraints?: { isCA: boolean; pathLength?: number };
},
certificateRequestId: string,
profile: NonNullable<Awaited<ReturnType<TCertificateProfileDALFactory["findByIdWithConfigs"]>>>,
certPolicy: NonNullable<Awaited<ReturnType<TCertificatePolicyServiceFactory["getPolicyById"]>>>,
applicationId?: string | null,
customExtensions?: TResolvedCustomExtension[]
): Promise<TCertificateIssuanceResponse> => {
if (!profile.caId) {
throw new NotFoundError({ message: "Certificate Authority ID not found" });
}
const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId);
if (!ca) {
throw new NotFoundError({ message: "Certificate Authority not found" });
}
assertCaInProfileProject(ca, profile);
validateCaSupport(ca, "direct certificate issuance");
validateAlgorithmCompatibility(ca, certPolicy);
const effectiveSignatureAlgorithm = certificateRequestInput.signatureAlgorithm as
| CertSignatureAlgorithm
| undefined;
const effectiveKeyAlgorithm = certificateRequestInput.keyAlgorithm as CertKeyAlgorithm | undefined;
const certificateSubject = buildCertificateSubjectFromTemplate(certificateRequestInput, certPolicy?.subject);
const subjectAlternativeNames = buildSubjectAlternativeNamesFromTemplate(
{ subjectAlternativeNames: certificateRequestInput.altNames },
certPolicy?.sans
);
const { certificate, certificateChain, issuingCaCertificate, privateKey, serialNumber, cert } =
await certificateDAL.transaction(async (tx) => {
const certResult = await internalCaService.issueCertFromCa({
caId: ca.id,
friendlyName: certificateSubject.common_name || "Certificate",
commonName: certificateSubject.common_name || "",
altNames: subjectAlternativeNames,
altNameEntries: certificateRequestInput.altNames,
ttl: certificateRequestInput.validity.ttl,
keyUsages: convertKeyUsageArrayToLegacy(certificateRequestInput.keyUsages) || [],
extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestInput.extendedKeyUsages) || [],
notBefore: normalizeDateForApi(certificateRequestInput.notBefore),
notAfter: normalizeDateForApi(certificateRequestInput.notAfter),
signatureAlgorithm: effectiveSignatureAlgorithm,
keyAlgorithm: effectiveKeyAlgorithm,
customExtensions,
actor: undefined,
actorId: undefined,
actorAuthMethod: undefined,
actorOrgId: undefined,
isFromProfile: true,
internal: true,
organization: certificateRequestInput.organization,
country: certificateRequestInput.country,
state: certificateRequestInput.state,
locality: certificateRequestInput.locality,
ou: certificateRequestInput.organizationalUnit,
domainComponents: certificateRequestInput.domainComponents,
basicConstraints: certificateRequestInput.basicConstraints,
pathLength: certificateRequestInput.basicConstraints?.pathLength,
tx
});
const certificateRecord = await certificateDAL.findById(certResult.certificateId, tx);
if (!certificateRecord) {
throw new NotFoundError({ message: "Certificate was issued but could not be found in database" });
}
const effectiveApiConfig = await resolveEffectiveApiConfig({
applicationId: applicationId ?? undefined,
profileId: profile.id,
profileApiConfig: profile.apiConfig,
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL
});
const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
{ apiConfig: effectiveApiConfig },
certificateRequestInput.validity.ttl,
new Date(certificateRecord.notAfter)
);
const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = {
profileId: profile.id
};
if (finalRenewBeforeDays !== undefined) {
updateData.renewBeforeDays = finalRenewBeforeDays;
}
if (applicationId) {
updateData.applicationId = applicationId;
}
await certificateDAL.updateById(certificateRecord.id, updateData, tx);
await certificateRequestDAL.updateById(
certificateRequestId,
{
status: CertificateRequestStatus.ISSUED,
certificateId: certResult.certificateId
},
tx
);
// Copy metadata from cert request to newly issued cert
await copyMetadataFromRequestToCertificate(resourceMetadataDAL, {
certificateRequestId,
certificateId: certResult.certificateId,
tx
});
await $emitIssuanceAlert(
{
certificateId: certificateRecord.id,
projectId: profile.projectId,
orgId: profile.project?.orgId,
applicationId
},
tx
);
return { ...certResult, cert: certificateRecord };
});
const finalCertificateChain = bufferToString(certificateChain);
await $queueIssuanceAlert(cert.id, profile.projectId, applicationId);
if (cert.id && applicationId) {
await queueCertificateFilterReconcile(cert.id, applicationId, pkiSyncQueue);
}
return {
status: CertificateRequestStatus.ISSUED,
certificate: bufferToString(certificate),
issuingCaCertificate: bufferToString(issuingCaCertificate),
certificateChain: finalCertificateChain,
privateKey: bufferToString(privateKey),
serialNumber,
certificateId: cert.id,
certificateRequestId,
projectId: profile.projectId,
profileName: profile.slug,
commonName: cert.commonName || ""
};
};
const issueCertificate = async (certificateRequestId: string): Promise<TCertificateIssuanceResponse> => {
const certRequest = await certificateRequestDAL.findById(certificateRequestId);
if (!certRequest) {
throw new NotFoundError({ message: "Certificate request not found" });
}
if (certRequest.status !== CertificateRequestStatus.PENDING) {
throw new BadRequestError({
message: `Certificate request is not in pending issuance state. Current status: ${certRequest.status}`
});
}
const { profileId } = certRequest;
if (!profileId) {
throw new BadRequestError({ message: "Certificate request is missing profile ID" });
}
const { ttl } = certRequest;
const altNames = certRequest.altNames as TAltNameEntry[] | null;
await certificateRequestDAL.updateById(certificateRequestId, {
status: CertificateRequestStatus.PENDING
});
try {
const targetProfile = await $validateProfileAndPermissions({
profileId,
requiredEnrollmentType: (certRequest.enrollmentType as EnrollmentType) || EnrollmentType.API,
isInternal: true
});
const externalCaResult = await $processExternalCARequest(
certRequest,
certificateRequestId,
targetProfile,
altNames,
ttl || undefined
);
if (externalCaResult) {
return externalCaResult;
}
if (!ttl) {
throw new BadRequestError({ message: "Certificate request is missing TTL" });
}
if (certRequest.csr) {
return await $processCSRSigningRequest(certRequest, certificateRequestId, profileId, ttl);
}
const basicConstraints = certRequest.basicConstraints as { isCA: boolean; pathLength?: number } | null;
const certificateRequestInput = {
commonName: certRequest.commonName || undefined,
domainComponents: certRequest.domainComponents ? certRequest.domainComponents.split(",") : undefined,
keyUsages: certRequest.keyUsages as CertKeyUsageType[] | undefined,
extendedKeyUsages: certRequest.extendedKeyUsages as CertExtendedKeyUsageType[] | undefined,
altNames: altNames || undefined,
validity: { ttl },
notBefore: certRequest.notBefore || undefined,
notAfter: certRequest.notAfter || undefined,
signatureAlgorithm: certRequest.signatureAlgorithm || undefined,
keyAlgorithm: certRequest.keyAlgorithm || undefined,
organization: certRequest.organization || undefined,
organizationalUnit: certRequest.organizationalUnit || undefined,
country: certRequest.country || undefined,
state: certRequest.state || undefined,
locality: certRequest.locality || undefined,
basicConstraints: basicConstraints || undefined,
customExtensions: toRequestCustomExtensions(certRequest.customExtensions)
};
// Validate against certificate policy
const mappedCertificateRequest = mapEnumsForValidation({
...certificateRequestInput,
subjectAlternativeNames: certificateRequestInput.altNames
});
const certPolicy = await certificatePolicyService.getPolicyById({
actor: undefined,
actorId: undefined,
actorAuthMethod: undefined,
actorOrgId: undefined,
policyId: targetProfile.certificatePolicyId,
internal: true
});
if (!certPolicy) {
throw new NotFoundError({ message: "Certificate policy not found for this profile" });
}
const validationResult = await certificatePolicyService.validateCertificateRequest(
targetProfile.certificatePolicyId,
mappedCertificateRequest
);
if (!validationResult.isValid) {
throw new BadRequestError({
message: `Certificate request validation failed: ${validationResult.errors.join(", ")}`
});
}
// Re-checked here as well as at submit: an approval can land days later, so the count compared
// against at submit says nothing about current usage. Not pushed into certificateDAL.create,
// which would also gate discovery and renewal writes.
const { quotaOrgId, isNewQuotaKey, isWildcard } = await assertCertificateQuotaForProject({
projectId: targetProfile.projectId,
commonName: certificateRequestInput.commonName,
altNames: (altNames ?? []).map((san) => san.value).join(","),
deps: { projectDAL, licenseService, usageCounterDAL, keyStore },
isApprovedRequest: true
});
const issuerType = targetProfile?.issuerType || (targetProfile?.caId ? IssuerType.CA : IssuerType.SELF_SIGNED);
const issuanceResult =
issuerType === IssuerType.SELF_SIGNED
? await $processSelfSignedRequest(
certificateRequestInput,
certificateRequestId,
targetProfile,
certPolicy,
certRequest.applicationId,
validationResult.resolvedCustomExtensions
)
: await $processCASignedRequest(
certificateRequestInput,
certificateRequestId,
targetProfile,
certPolicy,
certRequest.applicationId,
validationResult.resolvedCustomExtensions
);
if (isNewQuotaKey) await recordNewCertificateQuotaKey(quotaOrgId, { keyStore }, isWildcard);
return issuanceResult;
} catch (error) {
await certificateRequestDAL.updateById(certificateRequestId, {
status: CertificateRequestStatus.FAILED,
errorMessage: error instanceof Error ? error.message : String(error)
});
throw error;
}
};
return {
issueCertificate
};
};