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
fix(pki): close issuance failure audit gaps and pre-authorization detail leaks
bernie-g9a6035ea3aa1
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.tsindex ad47553799..2c62c71f14 100644--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts@@ -46,7 +46,10 @@ import {extractAlgorithmsFromCSR,extractCertificateRequestFromCSR} from "@app/services/certificate-common/certificate-csr-utils";-import { recordCertificateIssuanceFailure } from "@app/services/certificate-common/certificate-issuance-audit-fns";+import {+ recordCertificateIssuanceFailure,+ tagErrorWithCertificateRequest+} from "@app/services/certificate-common/certificate-issuance-audit-fns";import { validateCertificateRequestLicense } from "@app/services/certificate-common/certificate-utils";import { TCertificatePolicyDALFactory } from "@app/services/certificate-policy/certificate-policy-dal";import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";@@ -1214,8 +1217,6 @@ export const pkiAcmeServiceFactory = ({// 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 ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId);if (!ca) {throw new NotFoundError({ message: "Certificate Authority not found" });@@ -1229,6 +1230,7 @@ export const pkiAcmeServiceFactory = ({? await acmeAccountDAL.findApplicationIdByJunctionId(accountApplicationProfileId): null;+ let csrCommonName: string | undefined;const $recordFinalizeFailure = (error: unknown) =>recordCertificateIssuanceFailure({ auditLogService, pkiApplicationDAL },@@ -1249,12 +1251,22 @@ export const pkiAcmeServiceFactory = ({profileName: profile.slug,caId: ca.id,caName: ca.name,- commonName: certificateRequest.commonName,+ commonName: csrCommonName,applicationId: accountApplicationId}});+ const certificateRequest = await (async () => {+ try {+ return extractCertificateRequestFromCSR(csr);+ } catch (error) {+ await $recordFinalizeFailure(error);+ throw error;+ }+ })();+ csrCommonName = certificateRequest.commonName;+const $rejectCsr = async (message: string) => {const error = new AcmeBadCSRError({ message });await $recordFinalizeFailure(error);@@ -1578,7 +1590,15 @@ export const pkiAcmeServiceFactory = ({if (certIssuanceJobData) {// We commit the order writes before queuing the job, otherwise the job may fail with a// not-found error.- await certificateIssuanceQueue.queueCertificateIssuance(certIssuanceJobData);+ try {+ await certificateIssuanceQueue.queueCertificateIssuance(certIssuanceJobData);+ } catch (error) {+ if (certIssuanceJobData.certificateRequestId) {+ tagErrorWithCertificateRequest(error, certIssuanceJobData.certificateRequestId);+ }+ await $recordFinalizeFailure(error);+ throw error;+ }}const updatedOrder = (await acmeOrderDAL.findByAccountAndOrderIdWithAuthorizations(accountId, orderId))!;const finalizedCsr = extractCertificateRequestFromCSR(updatedOrder.csr!);diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.tsindex d16471a58f..2004003d0f 100644--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts@@ -504,7 +504,6 @@ export const pkiScepServiceFactory = ({});}- const { ttl } = await resolveIssuanceParams(profile);const csrPem = derToPem(csrDer, "CERTIFICATE REQUEST");let result: TIssuanceResult;@@ -516,7 +515,6 @@ export const pkiScepServiceFactory = ({caType,parsed,csrPem,- ttl,applicationId,isRenewal: false,clientIp@@ -769,7 +767,6 @@ export const pkiScepServiceFactory = ({});}- const { ttl } = await resolveIssuanceParams(profile);const csrPem = derToPem(Buffer.from(parsed.csr), "CERTIFICATE REQUEST");// eslint-disable-next-line @typescript-eslint/no-use-before-define@@ -779,7 +776,6 @@ export const pkiScepServiceFactory = ({caType,parsed,csrPem,- ttl,applicationId,isRenewal: true,clientIp@@ -1045,9 +1041,10 @@ export const pkiScepServiceFactory = ({isRenewal,clientIp,...params- }: Parameters<typeof $issueOrQueueCertificate>[0] & { isRenewal: boolean; clientIp: string }) => {+ }: Omit<Parameters<typeof $issueOrQueueCertificate>[0], "ttl"> & { isRenewal: boolean; clientIp: string }) => {try {- return await $issueOrQueueCertificate(params);+ const { ttl } = await resolveIssuanceParams(params.profile);+ return await $issueOrQueueCertificate({ ...params, ttl });} catch (error) {let operation =params.caType === CaType.INTERNAL ? CertificateIssuanceOperation.SIGN : CertificateIssuanceOperation.ORDER;diff --git a/backend/src/services/certificate-common/certificate-issuance-audit-fns.ts b/backend/src/services/certificate-common/certificate-issuance-audit-fns.tsindex 9f6e245632..bc42dc54da 100644--- a/backend/src/services/certificate-common/certificate-issuance-audit-fns.ts+++ b/backend/src/services/certificate-common/certificate-issuance-audit-fns.ts@@ -54,6 +54,15 @@ export const tagErrorWithCertificateRequest = (error: unknown, certificateRequesconst getTaggedCertificateRequestId = (error: unknown) =>error && typeof error === "object" ? certificateRequestIdByError.get(error) : undefined;+const errorsAfterAuthorization = new WeakSet<object>();++export const tagErrorAsAfterAuthorization = (error: unknown) => {+ if (error && typeof error === "object") errorsAfterAuthorization.add(error);+};++export const isErrorAfterAuthorization = (error: unknown) =>+ Boolean(error && typeof error === "object" && errorsAfterAuthorization.has(error));+// Never throws, so callers can rethrow the original error untouched.export const recordCertificateIssuanceFailure = async ({ auditLogService, certificateAuthorityDAL, pkiApplicationDAL }: TRecordCertificateIssuanceFailureDeps,diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.tsindex e508b856bd..bb2b803061 100644--- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts+++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.test.ts@@ -316,6 +316,34 @@ describe("CertificateEstV3Service", () => {).rejects.toThrow(BadRequestError);});+ it("records an issuance failure when the profile's default TTL exceeds the policy maximum", async () => {+ mockCertificateProfileDAL.findByIdWithConfigs.mockResolvedValue({ ...mockProfile, defaults: { ttlDays: 365 } });++ await expect(+ service.simpleEnrollByProfile({+ csr: "mock-csr",+ profileId: "profile-123",+ sslClientCert: "",+ auditLogInfo: { ipAddress: "127.0.0.1", actor: { type: ActorType.PLATFORM, metadata: {} } }+ })+ ).rejects.toThrow("exceeds the policy's maximum validity");++ expect(mockCertificateV3Service.signCertificateFromProfile).not.toHaveBeenCalled();+ expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledWith(+ expect.objectContaining({+ actor: { type: ActorType.EST_ACCOUNT, metadata: { profileId: "profile-123" } },+ event: expect.objectContaining({+ type: EventType.CERTIFICATE_ISSUANCE_FAILED,+ metadata: expect.objectContaining({+ operation: CertificateIssuanceOperation.SIGN,+ enrollmentType: EnrollmentType.EST,+ certificateProfileId: "profile-123"+ })+ })+ })+ );+ });+it("should use flow default TTL when profile has no defaultTtlDays", async () => {mockCertificatePolicyDAL.findById.mockResolvedValue({id: "policy-123",diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.tsindex 58be9963f4..eef5ed2665 100644--- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts+++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts@@ -66,6 +66,63 @@ export const certificateEstV3ServiceFactory = ({pkiApplicationDAL,auditLogService}: TCertificateEstV3ServiceFactoryDep) => {+ const $recordEstFailure = async ({+ error,+ profile,+ csr,+ applicationId,+ auditLogInfo,+ operation,+ originalCertificateId+ }: {+ error: unknown;+ profile: { id: string; projectId: string; slug: string; caId?: string | null };+ csr: string;+ applicationId?: string;+ auditLogInfo?: AuditLogInfo;+ operation: CertificateIssuanceOperation;+ originalCertificateId?: string;+ }) => {+ if (!auditLogInfo) return;+ let commonName: string | undefined;+ try {+ commonName = extractCertificateRequestFromCSR(csr).commonName;+ } catch {+ commonName = undefined;+ }+ await recordCertificateIssuanceFailure(+ { auditLogService, certificateAuthorityDAL, pkiApplicationDAL },+ {+ auditLogInfo: { ...auditLogInfo, actor: { type: ActorType.EST_ACCOUNT, metadata: { profileId: profile.id } } },+ projectId: profile.projectId,+ error,+ metadata: {+ operation,+ enrollmentType: EnrollmentType.EST,+ certificateProfileId: profile.id,+ profileName: profile.slug,+ caId: profile.caId,+ commonName,+ originalCertificateId,+ applicationId+ }+ }+ );+ };++ const $resolveEstTtl = async (profile: {+ certificatePolicyId: string;+ defaults?: { ttlDays?: number | null } | null;+ }) => {+ const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);+ return resolveEffectiveTtl({+ requestTtl: undefined, // EST doesn't accept TTL in request+ profileDefaultTtlDays: profile.defaults?.ttlDays,+ policyMaxValidity: policy?.validity?.max,+ flowDefaultTtl: "90d"+ });+ };+const resolveEstConfigId = async (profile: { estConfigId?: string | null },profileId: string,@@ -181,12 +238,16 @@ export const certificateEstV3ServiceFactory = ({}await validateEstClientCertificate(estConfig, profile.projectId, sslClientCert);- const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);- const ttl = resolveEffectiveTtl({- requestTtl: undefined, // EST doesn't accept TTL in request- profileDefaultTtlDays: profile.defaults?.ttlDays,- policyMaxValidity: policy?.validity?.max,- flowDefaultTtl: "90d"+ const ttl = await $resolveEstTtl(profile).catch(async (error: unknown) => {+ await $recordEstFailure({+ error,+ profile,+ csr,+ applicationId,+ auditLogInfo,+ operation: CertificateIssuanceOperation.SIGN+ });+ throw error;});const result = await certificateV3Service.signCertificateFromProfile({@@ -311,32 +372,15 @@ export const certificateEstV3ServiceFactory = ({const $rejectReenrollCsr = async (message: string) => {const error = new BadRequestError({ message });- if (auditLogInfo) {- let commonName: string | undefined;- try {- commonName = extractCertificateRequestFromCSR(csr).commonName;- } catch {- commonName = undefined;- }- await recordCertificateIssuanceFailure(- { auditLogService, certificateAuthorityDAL, pkiApplicationDAL },- {- auditLogInfo: { ...auditLogInfo, actor: { type: ActorType.EST_ACCOUNT, metadata: { profileId } } },- projectId: profile.projectId,- error,- metadata: {- operation: CertificateIssuanceOperation.RENEW,- enrollmentType: EnrollmentType.EST,- certificateProfileId: profileId,- profileName: profile.slug,- caId: profile.caId,- commonName,- originalCertificateId: storedCert?.id,- applicationId- }- }- );- }+ await $recordEstFailure({+ error,+ profile,+ csr,+ applicationId,+ auditLogInfo,+ operation: CertificateIssuanceOperation.RENEW,+ originalCertificateId: storedCert?.id+ });return error;};@@ -363,12 +407,17 @@ export const certificateEstV3ServiceFactory = ({throw await $rejectReenrollCsr("Subject alternative names mismatch");}- const policy = await certificatePolicyDAL.findById(profile.certificatePolicyId);- const ttl = resolveEffectiveTtl({- requestTtl: undefined, // EST doesn't accept TTL in request- profileDefaultTtlDays: profile.defaults?.ttlDays,- policyMaxValidity: policy?.validity?.max,- flowDefaultTtl: "90d"+ const ttl = await $resolveEstTtl(profile).catch(async (error: unknown) => {+ await $recordEstFailure({+ error,+ profile,+ csr,+ applicationId,+ auditLogInfo,+ operation: CertificateIssuanceOperation.RENEW,+ originalCertificateId: storedCert?.id+ });+ throw error;});const result = await certificateV3Service.signCertificateFromProfile({diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.tsindex 29c05f253e..c67aa392c6 100644--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts@@ -55,6 +55,7 @@ import {mapExtendedKeyUsageToLegacy,mapKeyUsageToLegacy} from "../certificate-common/certificate-constants";+import { tagErrorAsAfterAuthorization } from "../certificate-common/certificate-issuance-audit-fns";import {detectSanType,extractCertificateFromBuffer,@@ -1069,20 +1070,23 @@ export const certificateRenewalServiceFactory = ({return application?.name ?? null;};- const renewCertificate = async ({- certificateId,- actor,- actorId,- actorAuthMethod,- actorOrgId,- internal = false,- removeRootsFromChain,- renewalKeySource: requestedKeySource,- csr,- attributes- }: Omit<TRenewCertificateDTO, "certificateRequestId"> & {- internal?: boolean;- }): Promise<TCertificateIssuanceResponse> => {+ const $renewCertificate = async (+ {+ certificateId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ internal = false,+ removeRootsFromChain,+ renewalKeySource: requestedKeySource,+ csr,+ attributes+ }: Omit<TRenewCertificateDTO, "certificateRequestId"> & {+ internal?: boolean;+ },+ onAuthorized: () => void+ ): Promise<TCertificateIssuanceResponse> => {const actorCtx: TRenewalActor = { actor, actorId, actorAuthMethod, actorOrgId };const keySource = resolveRenewalKeySource({ renewalKeySource: requestedKeySource, csr });let csrRenewalRequest: TCertificateRequest | null = null;@@ -1119,6 +1123,7 @@ export const certificateRenewalServiceFactory = ({const renewalAuth = internal? undefined: await $authorizeRenewal({ originalCert, profile, actorCtx, isEditingCertificate }, tx);+ onAuthorized();const { issuerType, ca, caType, policy } = await $resolveRenewalIssuer({@@ -1509,6 +1514,18 @@ export const certificateRenewalServiceFactory = ({return { ...response, changedAttributes };};+ const renewCertificate = async (dto: Parameters<typeof $renewCertificate>[0]) => {+ let authorized = false;+ try {+ return await $renewCertificate(dto, () => {+ authorized = true;+ });+ } catch (error) {+ if (authorized) tagErrorAsAfterAuthorization(error);+ throw error;+ }+ };+const $loadCertificateForRenewalConfig = async ({certificateId,actor,diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex 3f94998419..2bc0cdb800 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -43,6 +43,7 @@ import {extractAlgorithmsFromCSR,extractCertificateRequestFromCSR} from "../certificate-common/certificate-csr-utils";+import { tagErrorAsAfterAuthorization } from "../certificate-common/certificate-issuance-audit-fns";import { buildCertificateQuotaKey } from "../certificate-common/certificate-quota-key";import { certificateV3ServiceFactory, TCertificateV3ServiceFactory } from "./certificate-v3-service";import { CertificateRenewalKeySource } from "./certificate-v3-types";@@ -3587,11 +3588,17 @@ describe("CertificateV3Service", () => {} as never);});- it("records the failure with the reason and rethrows the original error", async () => {- const failure = new BadRequestError({ message: "TTL exceeds the policy maximum of 90 days" });- vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(failure);-- await expect(service.issueCertificateFromProfile({ ...issueDto, auditLogInfo })).rejects.toBe(failure);+ it("records the failure with the profile's details once the caller is authorized", async () => {+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue({+ id: "profile-123",+ projectId: "project-123",+ slug: "web-servers",+ caId: "ca-123",+ enrollmentType: EnrollmentType.API+ } as never);+ await expect(service.issueCertificateFromProfile({ ...issueDto, auditLogInfo })).rejects.toThrow(+ "This profile must be issued through an Application"+ );expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledTimes(1);expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledWith(@@ -3608,13 +3615,33 @@ describe("CertificateV3Service", () => {profileName: "web-servers",caId: "ca-123",errorName: "BadRequest",- error: "TTL exceeds the policy maximum of 90 days"+ error:+ "This profile must be issued through an Application. Attach it to an Application and issue from there."}}}));});+ it("records only what the caller sent when issuance fails before authorization", async () => {+ const failure = new NotFoundError({ message: "Application not found" });+ vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(failure);++ await expect(service.issueCertificateFromProfile({ ...issueDto, auditLogInfo })).rejects.toBe(failure);++ const [[call]] = mockAuditLogService.createCollapsedAuditLog.mock.calls as [+ [{ event: { metadata: Record<string, unknown> } }]+ ];+ expect(call.event.metadata).toEqual({+ operation: CertificateIssuanceOperation.ISSUE,+ enrollmentType: EnrollmentType.API,+ commonName: "fail.example.com",+ certificateProfileId: "profile-123",+ errorName: "NotFound",+ error: "Application not found"+ });+ });+it("records nothing without audit log info", async () => {vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(new BadRequestError({ message: "x" }));@@ -3710,28 +3737,31 @@ describe("CertificateV3Service", () => {);});- it("records a failed renewal against the original certificate", async () => {- vi.mocked(mockCertificateDAL.findById).mockResolvedValue({- id: "cert-123",- projectId: "project-123",- commonName: "renew.example.com",- profileId: "profile-123",- caId: "ca-123"- } as never);- vi.mocked(mockCertificateDAL.transaction).mockRejectedValueOnce(- new BadRequestError({ message: "CA is disabled" })- );+ const renewDto = {+ certificateId: "cert-123",+ actor: ActorType.USER,+ actorId: "user-123",+ actorAuthMethod: AuthMethod.EMAIL,+ actorOrgId: "org-123",+ auditLogInfo+ };- await expect(- service.renewCertificate({- certificateId: "cert-123",- actor: ActorType.USER,- actorId: "user-123",- actorAuthMethod: AuthMethod.EMAIL,- actorOrgId: "org-123",- auditLogInfo- })- ).rejects.toThrow("CA is disabled");+ const storedCertificate = {+ id: "cert-123",+ projectId: "project-123",+ commonName: "renew.example.com",+ profileId: "profile-123",+ caId: "ca-123",+ applicationId: "app-123"+ };++ it("records a failed renewal with the certificate's details once the caller is authorized", async () => {+ vi.mocked(mockCertificateDAL.findById).mockResolvedValue(storedCertificate as never);+ const failure = new BadRequestError({ message: "CA is disabled" });+ tagErrorAsAfterAuthorization(failure);+ vi.mocked(mockCertificateDAL.transaction).mockRejectedValueOnce(failure);++ await expect(service.renewCertificate(renewDto)).rejects.toThrow("CA is disabled");expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledWith(expect.objectContaining({@@ -3741,11 +3771,32 @@ describe("CertificateV3Service", () => {operation: CertificateIssuanceOperation.RENEW,originalCertificateId: "cert-123",commonName: "renew.example.com",- certificateProfileId: "profile-123"+ certificateProfileId: "profile-123",+ applicationId: "app-123"})})}));});++ it("records only what the caller sent when renewal fails before authorization", async () => {+ vi.mocked(mockCertificateDAL.findById).mockResolvedValue(storedCertificate as never);+ vi.mocked(mockCertificateDAL.transaction).mockRejectedValueOnce(+ new BadRequestError({ message: "A CSR is required when renewalKeySource is csr" })+ );++ await expect(service.renewCertificate(renewDto)).rejects.toThrow("A CSR is required");++ const [[call]] = mockAuditLogService.createCollapsedAuditLog.mock.calls as [+ [{ event: { metadata: Record<string, unknown> } }]+ ];+ expect(call.event.metadata).toEqual({+ operation: CertificateIssuanceOperation.RENEW,+ enrollmentType: EnrollmentType.API,+ originalCertificateId: "cert-123",+ errorName: "BadRequest",+ error: "A CSR is required when renewalKeySource is csr"+ });+ });});});diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex c5463bbd9d..6f7918739e 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -51,6 +51,7 @@ import {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 {+ isErrorAfterAuthorization,recordCertificateIssuanceFailure,tagErrorWithCertificateRequest} from "@app/services/certificate-common/certificate-issuance-audit-fns";@@ -563,6 +564,7 @@ export const certificateV3ServiceFactory = ({actorOrgId,projectId,profileId,+ authorized,error,metadata}: {@@ -570,6 +572,7 @@ export const certificateV3ServiceFactory = ({actorOrgId: string;projectId?: string;profileId?: string | null;+ authorized: boolean;error: unknown;metadata: Omit<Parameters<typeof recordCertificateIssuanceFailure>[1]["metadata"],@@ -586,8 +589,9 @@ export const certificateV3ServiceFactory = ({const project = await projectDAL.findById(resolvedProjectId);if (project?.orgId !== actorOrgId) return;+ // Before the caller is authorized, record only what they sent and look nothing up by name.await recordCertificateIssuanceFailure(- { auditLogService, certificateAuthorityDAL, pkiApplicationDAL },+ authorized ? { auditLogService, certificateAuthorityDAL, pkiApplicationDAL } : { auditLogService },{auditLogInfo,projectId: resolvedProjectId,@@ -595,8 +599,7 @@ export const certificateV3ServiceFactory = ({metadata: {...metadata,certificateProfileId: profile?.id,- profileName: profile?.slug,- caId: metadata.caId ?? profile?.caId+ ...(authorized && { profileName: profile?.slug, caId: metadata.caId ?? profile?.caId })}});@@ -614,17 +617,20 @@ export const certificateV3ServiceFactory = ({}};- const $issueCertificateFromProfile = async ({- profileId,- certificateRequest,- metadata,- actor,- actorId,- actorAuthMethod,- actorOrgId,- removeRootsFromChain,- applicationId: explicitApplicationId- }: TIssueCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {+ const $issueCertificateFromProfile = async (+ {+ profileId,+ certificateRequest,+ metadata,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ removeRootsFromChain,+ applicationId: explicitApplicationId+ }: TIssueCertificateFromProfileDTO,+ onAuthorized: () => void = () => {}+ ): Promise<TCertificateIssuanceResponse> => {const profile = await validateProfileAndPermissions({profileId,actor,@@ -638,6 +644,7 @@ export const certificateV3ServiceFactory = ({isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT,applicationId: explicitApplicationId});+ onAuthorized();const applicationId = await $resolveApplicationIdForProfile(profile,@@ -1349,23 +1356,26 @@ export const certificateV3ServiceFactory = ({};};- const $signCertificateFromProfile = async ({- profileId,- csr,- validity,- notBefore,- notAfter,- actor,- actorId,- actorAuthMethod,- actorOrgId,- enrollmentType,- metadata,- removeRootsFromChain,- basicConstraints,- applicationId: explicitApplicationId,- acmeOrderId- }: TSignCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {+ const $signCertificateFromProfile = async (+ {+ profileId,+ csr,+ validity,+ notBefore,+ notAfter,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ enrollmentType,+ metadata,+ removeRootsFromChain,+ basicConstraints,+ applicationId: explicitApplicationId,+ acmeOrderId+ }: TSignCertificateFromProfileDTO,+ onAuthorized: () => void = () => {}+ ): Promise<TCertificateIssuanceResponse> => {const profile = await validateProfileAndPermissions({profileId,actor,@@ -1379,6 +1389,7 @@ export const certificateV3ServiceFactory = ({isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT,applicationId: explicitApplicationId});+ onAuthorized();const applicationId = await $resolveApplicationIdForProfile(profile,explicitApplicationId,@@ -1843,16 +1854,19 @@ export const certificateV3ServiceFactory = ({};};- const $orderCertificate = async ({- profileId,- certificateOrder,- metadata,- actor,- actorId,- actorAuthMethod,- actorOrgId,- applicationId: explicitApplicationId- }: TOrderCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {+ const $orderCertificate = async (+ {+ profileId,+ certificateOrder,+ metadata,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId,+ applicationId: explicitApplicationId+ }: TOrderCertificateFromProfileDTO,+ onAuthorized: () => void = () => {}+ ): Promise<TCertificateIssuanceResponse> => {const profile = await validateProfileAndPermissions({profileId,actor,@@ -1866,6 +1880,7 @@ export const certificateV3ServiceFactory = ({isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT,applicationId: explicitApplicationId});+ onAuthorized();const applicationId = await $resolveApplicationIdForProfile(profile,explicitApplicationId,@@ -2381,13 +2396,17 @@ export const certificateV3ServiceFactory = ({});const issueCertificateFromProfile = async (dto: TIssueCertificateFromProfileDTO) => {+ let authorized = false;try {- return await $issueCertificateFromProfile(dto);+ return await $issueCertificateFromProfile(dto, () => {+ authorized = true;+ });} catch (error) {await $recordIssuanceFailure({auditLogInfo: dto.auditLogInfo,actorOrgId: dto.actorOrgId,profileId: dto.profileId,+ authorized,error,metadata: {operation: CertificateIssuanceOperation.ISSUE,@@ -2401,13 +2420,17 @@ export const certificateV3ServiceFactory = ({};const signCertificateFromProfile = async (dto: TSignCertificateFromProfileDTO) => {+ let authorized = false;try {- return await $signCertificateFromProfile(dto);+ return await $signCertificateFromProfile(dto, () => {+ authorized = true;+ });} catch (error) {await $recordIssuanceFailure({auditLogInfo: dto.auditLogInfo,actorOrgId: dto.actorOrgId,profileId: dto.profileId,+ authorized,error,metadata: {operation: dto.issuanceOperation ?? CertificateIssuanceOperation.SIGN,@@ -2422,13 +2445,17 @@ export const certificateV3ServiceFactory = ({};const orderCertificate = async (dto: TOrderCertificateFromProfileDTO) => {+ let authorized = false;try {- return await $orderCertificate(dto);+ return await $orderCertificate(dto, () => {+ authorized = true;+ });} catch (error) {await $recordIssuanceFailure({auditLogInfo: dto.auditLogInfo,actorOrgId: dto.actorOrgId,profileId: dto.profileId,+ authorized,error,metadata: {operation: CertificateIssuanceOperation.ORDER,@@ -2449,19 +2476,23 @@ export const certificateV3ServiceFactory = ({? await certificateDAL.findById(dto.certificateId).catch(() => undefined): undefined;if (certificate) {+ const authorized = isErrorAfterAuthorization(error);await $recordIssuanceFailure({auditLogInfo: dto.auditLogInfo,actorOrgId: dto.actorOrgId,projectId: certificate.projectId,- profileId: certificate.profileId,+ profileId: authorized ? certificate.profileId : null,+ authorized,error,metadata: {operation: CertificateIssuanceOperation.RENEW,enrollmentType: EnrollmentType.API,- originalCertificateId: certificate.id,- commonName: certificate.commonName,- caId: certificate.caId,- applicationId: certificate.applicationId+ originalCertificateId: dto.certificateId,+ ...(authorized && {+ commonName: certificate.commonName,+ caId: certificate.caId,+ applicationId: certificate.applicationId+ })}});}