Skip to content

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

fix: address deadlock for cert issuance

Sheen Capadngan2c6cfc4f9b52
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index 3ef7f35d20..118e44b2ca 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -976,7 +976,10 @@ export const pkiAcmeServiceFactory = ({
: // ttl is not used if notAfter is provided
({ ttl: "0d" } as const),
enrollmentType: EnrollmentType.ACME,
- applicationId
+ applicationId,
+ // Links the certificate request to this order so checkAndSyncAcmeOrderStatus can reconcile
+ // an order left in `processing` if the process dies mid-issuance.
+ acmeOrderId: orderId
});
if ("certificateId" in result) {
return {
@@ -1106,117 +1109,137 @@ export const pkiAcmeServiceFactory = ({
throw new NotFoundError({ message: "ACME order not found" });
}
if (order.status === AcmeOrderStatus.Ready) {
- const {
- order: updatedOrder,
- error,
- certIssuanceJobData
- } = await acmeOrderDAL.transaction(async (tx) => {
- const finalizingOrder = (await acmeOrderDAL.findByIdForFinalization(orderId, tx))!;
- // TODO: ideally, this should be doen with onRequest: verifyAuth([AuthMode.ACME_JWS_SIGNATURE]), instead?
- const { ownerOrgId: actorOrgId } = (await certificateProfileDAL.findByIdWithOwnerOrgId(profileId, tx))!;
- if (finalizingOrder.status !== AcmeOrderStatus.Ready) {
- throw new AcmeOrderNotReadyError({ message: "ACME order is not ready" });
- }
- if (finalizingOrder.expiresAt < new Date()) {
- throw new AcmeOrderNotReadyError({ message: "ACME order has expired" });
- }
+ const { csr } = payload;
+
+ // Everything that can reject the request is validated *before* the order is claimed, so a
+ // rejected finalization leaves the order in `ready` and the client can retry with a
+ // corrected CSR. This mirrors the previous behaviour, where these errors rolled the
+ // enclosing transaction back.
+ const certificateRequest = extractCertificateRequestFromCSR(csr);
+ const allowedSanTypes = new Set([
+ CertSubjectAlternativeNameType.DNS_NAME,
+ CertSubjectAlternativeNameType.IP_ADDRESS
+ ]);
+ if (certificateRequest.subjectAlternativeNames?.some((san) => !allowedSanTypes.has(san.type))) {
+ throw new AcmeBadCSRError({
+ message: "Invalid CSR: Only DNS and IP subject alternative names are supported"
+ });
+ }
- const { csr } = payload;
-
- // Check and validate the CSR
- const certificateRequest = extractCertificateRequestFromCSR(csr);
- const allowedSanTypes = new Set([
- CertSubjectAlternativeNameType.DNS_NAME,
- CertSubjectAlternativeNameType.IP_ADDRESS
- ]);
- if (certificateRequest.subjectAlternativeNames?.some((san) => !allowedSanTypes.has(san.type))) {
- throw new AcmeBadCSRError({
- message: "Invalid CSR: Only DNS and IP subject alternative names are supported"
- });
- }
- const orderWithAuthorizations = (await acmeOrderDAL.findByAccountAndOrderIdWithAuthorizations(
- accountId,
- orderId,
- tx
- ))!;
-
- // Build a set of "type:value" pairs from CSR SANs to match against authorized identifiers
- const sanTypeToIdentifierType: Partial<Record<CertSubjectAlternativeNameType, AcmeIdentifierType>> = {
- [CertSubjectAlternativeNameType.DNS_NAME]: AcmeIdentifierType.DNS,
- [CertSubjectAlternativeNameType.IP_ADDRESS]: AcmeIdentifierType.IP
- };
- const csrIdentifierPairs = new Set(
- (certificateRequest.subjectAlternativeNames ?? [])
- .map((san) => {
- const identifierType = sanTypeToIdentifierType[san.type];
- return identifierType ? `${identifierType}:${san.value.toLowerCase()}` : null;
- })
- .filter(Boolean)
- );
- // ACME clients (e.g., lego) set the CN to the IP address for IP certificate requests.
- // We need to detect whether the CN is an IP to match it against the correct identifier type,
- // otherwise "ip:127.0.0.1" in the authorization won't match "dns:127.0.0.1" from the CN.
- if (certificateRequest.commonName) {
- const cnType = validateIpIdentifier(certificateRequest.commonName)
- ? AcmeIdentifierType.IP
- : AcmeIdentifierType.DNS;
- csrIdentifierPairs.add(`${cnType}:${certificateRequest.commonName.toLowerCase()}`);
- }
- const authIdentifierPairs = new Set(
- orderWithAuthorizations.authorizations.map((auth) => {
- const value = auth.wildcard ? `*.${auth.identifierValue}` : auth.identifierValue;
- return `${auth.identifierType}:${value.toLowerCase()}`;
+ // Build a set of "type:value" pairs from CSR SANs to match against authorized identifiers
+ const sanTypeToIdentifierType: Partial<Record<CertSubjectAlternativeNameType, AcmeIdentifierType>> = {
+ [CertSubjectAlternativeNameType.DNS_NAME]: AcmeIdentifierType.DNS,
+ [CertSubjectAlternativeNameType.IP_ADDRESS]: AcmeIdentifierType.IP
+ };
+ const csrIdentifierPairs = new Set(
+ (certificateRequest.subjectAlternativeNames ?? [])
+ .map((san) => {
+ const identifierType = sanTypeToIdentifierType[san.type];
+ return identifierType ? `${identifierType}:${san.value.toLowerCase()}` : null;
})
- );
- if (
- csrIdentifierPairs.size !== authIdentifierPairs.size ||
- ![...authIdentifierPairs].every((id) => csrIdentifierPairs.has(id))
- ) {
- throw new AcmeBadCSRError({ message: "Invalid CSR: Common name + SANs mismatch with order identifiers" });
- }
+ .filter(Boolean)
+ );
+ // ACME clients (e.g., lego) set the CN to the IP address for IP certificate requests.
+ // We need to detect whether the CN is an IP to match it against the correct identifier type,
+ // otherwise "ip:127.0.0.1" in the authorization won't match "dns:127.0.0.1" from the CN.
+ if (certificateRequest.commonName) {
+ const cnType = validateIpIdentifier(certificateRequest.commonName)
+ ? AcmeIdentifierType.IP
+ : AcmeIdentifierType.DNS;
+ csrIdentifierPairs.add(`${cnType}:${certificateRequest.commonName.toLowerCase()}`);
+ }
+ const authIdentifierPairs = new Set(
+ order.authorizations.map((auth) => {
+ const value = auth.wildcard ? `*.${auth.identifierValue}` : auth.identifierValue;
+ return `${auth.identifierType}:${value.toLowerCase()}`;
+ })
+ );
+ if (
+ csrIdentifierPairs.size !== authIdentifierPairs.size ||
+ ![...authIdentifierPairs].every((id) => csrIdentifierPairs.has(id))
+ ) {
+ throw new AcmeBadCSRError({ message: "Invalid CSR: Common name + SANs mismatch with order identifiers" });
+ }
+
+ // Issuance context. These are reads only, and they deliberately run outside a transaction:
+ // holding a pooled connection across signing is what let concurrent finalizations exhaust
+ // the connection pool and deadlock every request in the process.
+ // TODO: ideally, this should be doen with onRequest: verifyAuth([AuthMode.ACME_JWS_SIGNATURE]), instead?
+ const { ownerOrgId: actorOrgId } = (await certificateProfileDAL.findByIdWithOwnerOrgId(profileId))!;
+
+ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId!);
+ if (!ca) {
+ throw new NotFoundError({ message: "Certificate Authority not found" });
+ }
+
+ assertCaInProfileProject(ca, profile);
- const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId!);
- if (!ca) {
- throw new NotFoundError({ message: "Certificate Authority not found" });
+ const finalizeAccount = await acmeAccountDAL.findByProjectIdAndAccountId(profile.id, accountId);
+ const accountApplicationProfileId = (finalizeAccount as { applicationProfileId?: string | null } | null)
+ ?.applicationProfileId;
+ const accountApplicationId = accountApplicationProfileId
+ ? await acmeAccountDAL.findApplicationIdByJunctionId(accountApplicationProfileId)
+ : null;
+
+ const approvalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](
+ ApprovalPolicyType.CertRequest
+ );
+ const matchedApprovalPolicy = (await approvalFactory.matchPolicy(
+ approvalPolicyDAL as TApprovalPolicyDALFactory,
+ profile.projectId,
+ {
+ profileName: profile.slug,
+ applicationId: accountApplicationId ?? undefined
}
+ )) as TCertRequestPolicy | null;
- assertCaInProfileProject(ca, profile);
-
- const finalizeAccount = await acmeAccountDAL.findByProjectIdAndAccountId(profile.id, accountId);
- const accountApplicationProfileId = (finalizeAccount as { applicationProfileId?: string | null } | null)
- ?.applicationProfileId;
- const accountApplicationId = accountApplicationProfileId
- ? await acmeAccountDAL.findApplicationIdByJunctionId(accountApplicationProfileId)
- : null;
-
- const approvalFactory = APPROVAL_POLICY_FACTORY_MAP[ApprovalPolicyType.CertRequest](
- ApprovalPolicyType.CertRequest
- );
- const matchedApprovalPolicy = (await approvalFactory.matchPolicy(
- approvalPolicyDAL as TApprovalPolicyDALFactory,
- profile.projectId,
- {
- profileName: profile.slug,
- applicationId: accountApplicationId ?? undefined
- }
- )) as TCertRequestPolicy | null;
+ const approvalContext = matchedApprovalPolicy
+ ? await (async () => {
+ const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);
+ if (!policy) {
+ throw new NotFoundError({ message: "Certificate policy not found" });
+ }
- if (matchedApprovalPolicy) {
- const approvalPolicy = matchedApprovalPolicy;
- const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);
- if (!policy) {
- throw new NotFoundError({ message: "Certificate policy not found" });
- }
+ const validationResult = await certificatePolicyService.validateCertificateRequest(
+ policy.id,
+ certificateRequest
+ );
+ if (!validationResult.isValid) {
+ throw new AcmeBadCSRError({ message: `Invalid CSR: ${validationResult.errors.join(", ")}` });
+ }
- const validationResult = await certificatePolicyService.validateCertificateRequest(
- policy.id,
- certificateRequest
- );
- if (!validationResult.isValid) {
- throw new AcmeBadCSRError({ message: `Invalid CSR: ${validationResult.errors.join(", ")}` });
- }
+ return {
+ approvalPolicy: matchedApprovalPolicy,
+ policy,
+ policySteps: await approvalPolicyDAL.findStepsByPolicyId(matchedApprovalPolicy.id)
+ };
+ })()
+ : undefined;
+
+ // Claims the order under a row lock and asserts it is still finalizable. The approval path
+ // runs this inside the same transaction as its writes, since it never signs and so never
+ // holds a connection across network I/O. The signing path commits the claim on its own, so
+ // that no connection stays held while the certificate is signed.
+ const $claimOrderForFinalization = async (tx: Knex) => {
+ const claimedOrder = (await acmeOrderDAL.findByIdForFinalization(orderId, tx))!;
+ if (claimedOrder.status !== AcmeOrderStatus.Ready) {
+ throw new AcmeOrderNotReadyError({ message: "ACME order is not ready" });
+ }
+ if (claimedOrder.expiresAt < new Date()) {
+ throw new AcmeOrderNotReadyError({ message: "ACME order has expired" });
+ }
+ return claimedOrder;
+ };
+
+ let certIssuanceJobData: TIssueCertificateFromProfileJobData | undefined;
- const policySteps = await approvalPolicyDAL.findStepsByPolicyId(approvalPolicy.id);
+ if (approvalContext) {
+ const { approvalPolicy, policy, policySteps } = approvalContext;
+
+ // No signing happens on this path, so it keeps its original single-transaction shape: the
+ // claim, the certificate request, its approval request and the status flip stay atomic.
+ await acmeOrderDAL.transaction(async (tx) => {
+ const finalizingOrder = await $claimOrderForFinalization(tx);
const requesterName = `ACME Account (${accountId})`;
@@ -1324,14 +1347,8 @@ export const pkiAcmeServiceFactory = ({
tx
);
- await acmeOrderDAL.updateById(
- orderId,
- {
- status: AcmeOrderStatus.Processing,
- csr
- },
- tx
- );
+ // Return the order in processing status - client will poll until approved
+ await acmeOrderDAL.updateById(orderId, { status: AcmeOrderStatus.Processing, csr }, tx);
logger.info(
{
@@ -1343,19 +1360,20 @@ export const pkiAcmeServiceFactory = ({
},
"ACME certificate request requires approval"
);
-
- // Return the order in processing status - client will poll until approved
- return {
- order: (await acmeOrderDAL.findByAccountAndOrderIdWithAuthorizations(accountId, orderId, tx))!,
- error: undefined,
- certIssuanceJobData: undefined
- };
- }
+ });
+ } else {
+ // Commit the claim on its own so the connection is released before signing starts.
+ const finalizingOrder = await acmeOrderDAL.transaction(async (tx) => {
+ const claimedOrder = await $claimOrderForFinalization(tx);
+ await acmeOrderDAL.updateById(orderId, { status: AcmeOrderStatus.Processing, csr }, tx);
+ return claimedOrder;
+ });
const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;
- let errorToReturn: Error | undefined;
- let certIssuanceJobDataToReturn: TIssueCertificateFromProfileJobData | undefined;
try {
+ // Signing runs with no ambient transaction. The internal CA and the external-CA paths
+ // each open their own short write transaction internally, so at no point does one
+ // request hold a connection while waiting for another.
const result = await processCertificateIssuanceForOrder({
caType,
accountId,
@@ -1367,54 +1385,40 @@ export const pkiAcmeServiceFactory = ({
certificateRequest,
profile,
ca,
- tx,
applicationId: accountApplicationId ?? undefined
});
- await acmeOrderDAL.updateById(
- orderId,
- {
- status: result.certificateId ? AcmeOrderStatus.Valid : AcmeOrderStatus.Processing,
- csr,
- certificateId: result.certificateId
- },
- tx
- );
- certIssuanceJobDataToReturn = result.certIssuanceJobData;
+ await acmeOrderDAL.updateById(orderId, {
+ status: result.certificateId ? AcmeOrderStatus.Valid : AcmeOrderStatus.Processing,
+ csr,
+ certificateId: result.certificateId
+ });
+ certIssuanceJobData = result.certIssuanceJobData;
} catch (exp) {
- await acmeOrderDAL.updateById(
- orderId,
- {
- csr,
- status: AcmeOrderStatus.Invalid,
- error: exp instanceof Error ? exp.message : "Unknown error"
- },
- tx
- );
+ await acmeOrderDAL.updateById(orderId, {
+ csr,
+ status: AcmeOrderStatus.Invalid,
+ error: exp instanceof Error ? exp.message : "Unknown error"
+ });
logger.error(exp, "Failed to sign certificate");
// TODO: audit log the error
if (exp instanceof BadRequestError) {
- errorToReturn = new AcmeBadCSRError({ message: `Invalid CSR: ${exp.message}` });
- } else if (exp instanceof AcmeError) {
- errorToReturn = exp;
- } else {
- errorToReturn = new AcmeServerInternalError({
- message: "Failed to sign certificate with internal error"
- });
+ throw new AcmeBadCSRError({ message: `Invalid CSR: ${exp.message}` });
+ }
+ if (exp instanceof AcmeError) {
+ throw exp;
}
+ throw new AcmeServerInternalError({
+ message: "Failed to sign certificate with internal error"
+ });
}
- return {
- order: (await acmeOrderDAL.findByAccountAndOrderIdWithAuthorizations(accountId, orderId, tx))!,
- error: errorToReturn,
- certIssuanceJobData: certIssuanceJobDataToReturn
- };
- });
- if (error) {
- throw error;
}
+
if (certIssuanceJobData) {
- // We commit the transaction before queuing the job, otherwise the job may fail with a not-found error.
+ // We commit the order writes before queuing the job, otherwise the job may fail with a
+ // not-found error.
await certificateIssuanceQueue.queueCertificateIssuance(certIssuanceJobData);
}
+ const updatedOrder = (await acmeOrderDAL.findByAccountAndOrderIdWithAuthorizations(accountId, orderId))!;
order = updatedOrder;
await auditLogService.createAuditLog({
...auditLogInfo,
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
index 48486e20ce..7bd8080441 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts
@@ -2680,11 +2680,22 @@ export const internalCertificateAuthorityServiceFactory = ({
return newCert;
};
+ // Everything above this point is reads, CA key access and signing, and deliberately runs with no
+ // transaction open. Only the writes below take a connection, so a caller can get atomic issuance
+ // without pinning one across the KMS/HSM round trips.
+ const persist = async (transaction: Knex) => {
+ const newCert = await createSignedCert(transaction);
+ if (dto.onPersisted) {
+ await dto.onPersisted(newCert, transaction);
+ }
+ return newCert;
+ };
+
let cert;
if (tx) {
- cert = await createSignedCert(tx);
+ cert = await persist(tx);
} else {
- cert = await certificateDAL.transaction(createSignedCert);
+ cert = await certificateDAL.transaction(persist);
}
usageMeteringService.emitForProject(ca.projectId, ActiveCerts.key);
diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
index 93482f3ecd..725c4d1ce2 100644
--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts
@@ -1,6 +1,7 @@
import { Knex } from "knex";
import { z } from "zod";
+import { TCertificates } from "@app/db/schemas";
import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal";
import { TProjectPermission } from "@app/lib/types";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
@@ -277,6 +278,14 @@ export type TSignCertFromCaDTO =
pathLength?: number | null;
subjectOverride?: string;
tx?: Knex;
+ /**
+ * Runs inside the same transaction that writes the certificate rows, after they are created
+ * but before it commits. Use this to record caller-side bookkeeping (profile linkage,
+ * certificate request status, metadata) atomically with the certificate itself, without
+ * having to hold a transaction open across the CA key access and signing that precede it.
+ * Throwing from here rolls the certificate back.
+ */
+ onPersisted?: (cert: TCertificates, tx: Knex) => Promise<void>;
}
| ({
isInternal: false;
@@ -300,6 +309,8 @@ export type TSignCertFromCaDTO =
pathLength?: number | null;
subjectOverride?: string;
tx?: Knex;
+ /** See the `onPersisted` note on the internal variant above. */
+ onPersisted?: (cert: TCertificates, tx: Knex) => Promise<void>;
} & Omit<TProjectPermission, "projectId">);
export type TGetCaCertificateTemplatesDTO = {
diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.ts
index 9799af11de..fab9b5fd5b 100644
--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts
@@ -533,47 +533,43 @@ export const certificateApprovalServiceFactory = (
domainComponents: reconstructedRequest.domainComponents
});
- const { certificate, certificateChain, issuingCaCertificate, serialNumber, cert } =
- await certificateDAL.transaction(async (tx) => {
- 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,
- isFromProfile: true,
- basicConstraints: effectiveBasicConstraints,
- pathLength: effectivePathLength,
- tx
- });
-
- const signedCertRecord = await certificateDAL.findById(certResult.certificateId, tx);
- if (!signedCertRecord) {
- throw new NotFoundError({ message: "Certificate was signed but could not be found in database" });
- }
+ // 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 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,
+ isFromProfile: true,
+ basicConstraints: effectiveBasicConstraints,
+ pathLength: effectivePathLength,
+ onPersisted: async (newCert, tx) => {
const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
{ apiConfig: effectiveApiConfig },
ttl,
- new Date(signedCertRecord.notAfter)
+ new Date(newCert.notAfter)
);
const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = { profileId };
@@ -583,13 +579,13 @@ export const certificateApprovalServiceFactory = (
if (certRequest.applicationId) {
updateData.applicationId = certRequest.applicationId;
}
- await certificateDAL.updateById(signedCertRecord.id, updateData, tx);
+ await certificateDAL.updateById(newCert.id, updateData, tx);
await certificateRequestDAL.updateById(
certificateRequestId,
{
status: CertificateRequestStatus.ISSUED,
- certificateId: certResult.certificateId
+ certificateId: newCert.id
},
tx
);
@@ -597,12 +593,13 @@ export const certificateApprovalServiceFactory = (
// Copy metadata from cert request to newly issued cert
await copyMetadataFromRequestToCertificate(resourceMetadataDAL, {
certificateRequestId,
- certificateId: certResult.certificateId,
+ certificateId: newCert.id,
tx
});
+ }
+ });
- return { ...certResult, cert: signedCertRecord };
- });
+ const { certificate, certificateChain, issuingCaCertificate, serialNumber } = certResult;
const certificateString = extractCertificateFromBuffer(certificate as unknown as Buffer);
const certificateChainString = extractCertificateFromBuffer(certificateChain as unknown as Buffer);
@@ -613,11 +610,11 @@ export const certificateApprovalServiceFactory = (
issuingCaCertificate: extractCertificateFromBuffer(issuingCaCertificate as unknown as Buffer),
certificateChain: certificateChainString,
serialNumber,
- certificateId: cert.id,
+ certificateId: certResult.certificateId,
certificateRequestId,
projectId: profile.projectId,
profileName: profile.slug,
- commonName: cert.commonName || ""
+ commonName: certResult.commonName || ""
};
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 13576ea03c..bd4f34aa10 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -159,7 +159,10 @@ type TCertificateV3ServiceFactoryDep = {
>;
certificateRequestService: Pick<TCertificateRequestServiceFactory, "createCertificateRequest">;
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findByProjectId" | "findStepsByPolicyId">;
- certificateRequestDAL: Pick<TCertificateRequestDALFactory, "updateById" | "findById" | "create" | "transaction">;
+ certificateRequestDAL: Pick<
+ TCertificateRequestDALFactory,
+ "updateById" | "findById" | "create" | "transaction" | "attachCertificate" | "transitionFromPending"
+ >;
userDAL: Pick<TUserDALFactory, "findById">;
identityDAL: Pick<TIdentityDALFactory, "findById">;
approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy">;
@@ -1517,7 +1520,8 @@ export const certificateV3ServiceFactory = ({
metadata,
removeRootsFromChain,
basicConstraints,
- applicationId: explicitApplicationId
+ applicationId: explicitApplicationId,
+ acmeOrderId
}: TSignCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {
const profile = await validateProfileAndPermissions({
profileId,
@@ -1780,106 +1784,121 @@ export const certificateV3ServiceFactory = ({
domainComponents: certificateRequest.domainComponents
});
- const { certificate, certificateChain, issuingCaCertificate, serialNumber, cert, certificateRequestId } =
- await certificateDAL.transaction(async (tx) => {
- const certResult = await internalCaService.signCertFromCa({
- isInternal: true,
- caId: ca.id,
- csr,
- subjectOverride,
- basicConstraints: caBasicConstraints,
- pathLength: effectiveBasicConstraints?.pathLength,
- ttl: effectiveTtl,
- altNames: undefined,
- notBefore: normalizeDateForApi(notBefore),
- notAfter: normalizeDateForApi(notAfter),
- keyUsages: certificateRequest.keyUsages
- ? convertKeyUsageArrayToLegacy(certificateRequest.keyUsages)
- : undefined,
- extendedKeyUsages: certificateRequest.extendedKeyUsages
- ? convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages)
- : undefined,
- signatureAlgorithm: effectiveSignatureAlgorithm,
- keyAlgorithm: effectiveKeyAlgorithm,
- isFromProfile: true,
- tx
- });
-
- const signedCertRecord = await certificateDAL.findById(certResult.certificateId, tx);
- if (!signedCertRecord) {
- throw new NotFoundError({ message: "Certificate was signed but could not be found in database" });
- }
-
- const effectiveApiConfig = await resolveEffectiveApiConfig({
- applicationId,
- profileId: profile.id,
- profileApiConfig: profile.apiConfig,
- pkiApplicationProfileDAL,
- apiEnrollmentConfigDAL
- });
- const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
- { apiConfig: effectiveApiConfig },
- effectiveTtl,
- new Date(signedCertRecord.notAfter)
- );
+ // Record intent before the irreversible act. Signing is an external side effect that no database
+ // rollback can undo, so the only way to stay accountable for it is to have a row on disk that
+ // says what we were about to do. If signing or persistence fails, this request is what makes the
+ // failure reportable and reconcilable, instead of leaving behind a stored certificate that
+ // nothing references.
+ const pendingRequest = await certificateRequestService.createCertificateRequest({
+ internal: true,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId: profile.projectId,
+ caId: ca.id,
+ profileId: profile.id,
+ applicationId,
+ acmeOrderId,
+ csr,
+ commonName: mappedCertificateRequest.commonName,
+ altNames: mappedCertificateRequest.subjectAlternativeNames,
+ domainComponents: mappedCertificateRequest.domainComponents,
+ keyUsages: convertKeyUsageArrayToLegacy(mappedCertificateRequest.keyUsages),
+ extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(mappedCertificateRequest.extendedKeyUsages),
+ notBefore,
+ notAfter,
+ keyAlgorithm: effectiveKeyAlgorithm,
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ status: CertificateRequestStatus.PENDING,
+ basicConstraints,
+ ttl: validity.ttl,
+ enrollmentType
+ });
- const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = {
- profileId
- };
- if (finalRenewBeforeDays !== undefined) {
- updateData.renewBeforeDays = finalRenewBeforeDays;
- }
- if (applicationId) {
- updateData.applicationId = applicationId;
- }
- await certificateDAL.updateById(signedCertRecord.id, updateData, tx);
+ const effectiveApiConfig = await resolveEffectiveApiConfig({
+ applicationId,
+ profileId: profile.id,
+ profileApiConfig: profile.apiConfig,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL
+ });
- const certRequestResult = await certificateRequestService.createCertificateRequest({
- internal: true,
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- projectId: profile.projectId,
- tx,
- caId: ca.id,
- profileId: profile.id,
- applicationId,
- csr,
- commonName: mappedCertificateRequest.commonName,
- altNames: mappedCertificateRequest.subjectAlternativeNames,
- domainComponents: mappedCertificateRequest.domainComponents,
- keyUsages: convertKeyUsageArrayToLegacy(mappedCertificateRequest.keyUsages),
- extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(mappedCertificateRequest.extendedKeyUsages),
- notBefore,
- notAfter,
- keyAlgorithm: effectiveKeyAlgorithm,
- signatureAlgorithm: effectiveSignatureAlgorithm,
- status: CertificateRequestStatus.ISSUED,
- certificateId: certResult.certificateId,
- basicConstraints,
- ttl: validity.ttl,
- enrollmentType
- });
+ let certResult: Awaited<ReturnType<typeof internalCaService.signCertFromCa>>;
+ try {
+ // No transaction is open across this call. signCertFromCa does its reads, CA key access and
+ // signing unwrapped, then opens one short transaction for the writes and invokes onPersisted
+ // inside it, so the certificate rows and the bookkeeping below commit together.
+ certResult = await internalCaService.signCertFromCa({
+ isInternal: true,
+ caId: ca.id,
+ csr,
+ subjectOverride,
+ basicConstraints: caBasicConstraints,
+ pathLength: effectiveBasicConstraints?.pathLength,
+ ttl: effectiveTtl,
+ altNames: undefined,
+ notBefore: normalizeDateForApi(notBefore),
+ notAfter: normalizeDateForApi(notAfter),
+ keyUsages: certificateRequest.keyUsages
+ ? convertKeyUsageArrayToLegacy(certificateRequest.keyUsages)
+ : undefined,
+ extendedKeyUsages: certificateRequest.extendedKeyUsages
+ ? convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages)
+ : undefined,
+ signatureAlgorithm: effectiveSignatureAlgorithm,
+ keyAlgorithm: effectiveKeyAlgorithm,
+ isFromProfile: true,
+ onPersisted: async (newCert, tx) => {
+ const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
+ { apiConfig: effectiveApiConfig },
+ effectiveTtl,
+ new Date(newCert.notAfter)
+ );
- if (metadata && metadata.length > 0) {
- await insertMetadataForCertificate(resourceMetadataDAL, {
- metadata,
- certificateId: certResult.certificateId,
- orgId: actorOrgId,
- tx
- });
- await insertMetadataForCertificateRequest(resourceMetadataDAL, {
- metadata,
- certificateRequestId: certRequestResult.id,
- certificateRequestCreatedAt: certRequestResult.createdAt,
- orgId: actorOrgId,
- tx
- });
+ const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = {
+ profileId
+ };
+ if (finalRenewBeforeDays !== undefined) {
+ updateData.renewBeforeDays = finalRenewBeforeDays;
+ }
+ if (applicationId) {
+ updateData.applicationId = applicationId;
+ }
+ await certificateDAL.updateById(newCert.id, updateData, tx);
+
+ // Records the outcome: flips the request to ISSUED and links the certificate in one update.
+ await certificateRequestDAL.attachCertificate(pendingRequest.id, newCert.id, tx);
+
+ if (metadata && metadata.length > 0) {
+ await insertMetadataForCertificate(resourceMetadataDAL, {
+ metadata,
+ certificateId: newCert.id,
+ orgId: actorOrgId,
+ tx
+ });
+ await insertMetadataForCertificateRequest(resourceMetadataDAL, {
+ metadata,
+ certificateRequestId: pendingRequest.id,
+ certificateRequestCreatedAt: pendingRequest.createdAt,
+ orgId: actorOrgId,
+ tx
+ });
+ }
}
-
- return { ...certResult, cert: signedCertRecord, certificateRequestId: certRequestResult.id };
});
+ } catch (err) {
+ // The request row is why this is recoverable. Mark it failed so the certificate is accounted
+ // for as an attempt rather than disappearing silently.
+ await certificateRequestDAL.transitionFromPending(
+ pendingRequest.id,
+ CertificateRequestStatus.FAILED,
+ err instanceof Error ? err.message : "Certificate issuance failed"
+ );
+ throw err;
+ }
+
+ const { certificate, certificateChain, issuingCaCertificate, serialNumber } = certResult;
const certificateString = extractCertificateFromBuffer(certificate as unknown as Buffer);
let certificateChainString = extractCertificateFromBuffer(certificateChain as unknown as Buffer);
@@ -1889,7 +1908,7 @@ export const certificateV3ServiceFactory = ({
try {
await pkiAlertV2Queue?.queueCertificateEvent({
- certificateId: cert.id,
+ certificateId: certResult.certificateId,
projectId: profile.projectId,
eventType: PkiAlertEventType.ISSUANCE,
applicationId: applicationId ?? null
@@ -1904,11 +1923,11 @@ export const certificateV3ServiceFactory = ({
issuingCaCertificate: extractCertificateFromBuffer(issuingCaCertificate as unknown as Buffer),
certificateChain: certificateChainString,
serialNumber,
- certificateId: cert.id,
- certificateRequestId,
+ certificateId: certResult.certificateId,
+ certificateRequestId: pendingRequest.id,
projectId: profile.projectId,
profileName: profile.slug,
- commonName: cert.commonName || ""
+ commonName: certResult.commonName || ""
};
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.ts
index 3e2cd3a4c4..5978b5de8e 100644
--- a/backend/src/services/certificate-v3/certificate-v3-types.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-types.ts
@@ -57,6 +57,11 @@ export type TSignCertificateFromProfileDTO = {
pathLength?: number;
};
applicationId?: string;
+ /**
+ * Links the certificate request this issuance creates back to its ACME order, so a crash between
+ * signing and persistence can be reconciled by `checkAndSyncAcmeOrderStatus`.
+ */
+ acmeOrderId?: string;
} & Omit<TProjectPermission, "projectId">;
export type TOrderCertificateFromProfileDTO = {