Skip to content

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

95.8 KB
Raw Blame
import { ForbiddenError, subject } from "@casl/ability";
import { randomUUID } from "crypto";
import { Knex } from "knex";

import { ActionProjectType, ResourceType } from "@app/db/schemas";
import { AuditLogInfo, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
  ProjectPermissionCertificateActions,
  ProjectPermissionCertificateProfileActions,
  ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import {
  ResourcePermissionCertificateActions,
  ResourcePermissionSub
} from "@app/ee/services/permission/resource-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 { ms } from "@app/lib/ms";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";
import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";
import {
  TCertRequestPolicy,
  TCertRequestRequestData
} from "@app/services/approval-policy/cert-request/cert-request-policy-types";
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 type { TCaKeySourceServiceFactory } from "@app/services/certificate-authority/ca-key-source/ca-key-source-service";
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 {
  assertCaSupportsCustomExtensions,
  caUsesExternalIssuanceQueue
} from "@app/services/certificate-authority/certificate-authority-maps";
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 {
  recordCertificateIssuanceFailure,
  tagErrorWithCertificateRequest
} from "@app/services/certificate-common/certificate-issuance-audit-fns";
import { recordNewCertificateQuotaKey } from "@app/services/certificate-common/certificate-quota-fns";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
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 { assertCertificateNotDeleted } from "@app/services/certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { CertKeyAlgorithm, CertSignatureAlgorithm } from "@app/services/certificate/certificate-types";
import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
import { TIdentityDALFactory } from "@app/services/identity/identity-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 { queueCertificateFilterReconcile } from "@app/services/pki-sync/pki-sync-utils";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { TUserDALFactory } from "@app/services/user/user-dal";

import {
  CertificateIssuanceOperation,
  CertKeyUsageType,
  CertPolicyState,
  CUSTOM_EXTENSIONS_WITH_CSR_ERROR_MESSAGE
} from "../certificate-common/certificate-constants";
import {
  buildSubjectOverrideForCsr,
  extractAlgorithmsFromCSR,
  extractCertificateRequestFromCSR
} from "../certificate-common/certificate-csr-utils";
import { assertAwsPcaCustomExtensionLimit } from "../certificate-common/certificate-extension-fns";
import {
  calculateFinalRenewBeforeDays,
  extractCertificateFromBuffer,
  getEffectiveAlgorithms,
  resolveEffectiveApiConfig,
  validateAlgorithmCompatibility,
  validateCaSupport
} from "../certificate-common/certificate-issuance-utils";
import {
  assertCanEditCertificate,
  assertCanEditCertificateResult
} from "../certificate-common/certificate-permission-fns";
import { reportCertificateIssued } from "../certificate-common/certificate-telemetry-fns";
import {
  bufferToString,
  buildCertificateSubjectFromTemplate,
  buildSubjectAlternativeNamesFromTemplate,
  convertExtendedKeyUsageArrayToLegacy,
  convertKeyUsageArrayToLegacy,
  mapEnumsForValidation,
  normalizeDateForApi,
  removeRootCaFromChain,
  validateCertificateRequestLicense
} from "../certificate-common/certificate-utils";
import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
import { TCertificateRequestDALFactory } from "../certificate-request/certificate-request-dal";
import {
  attachCertificateToPendingRequest,
  markPendingRequestFailed
} from "../certificate-request/certificate-request-fns";
import { TCertificateRequestServiceFactory } from "../certificate-request/certificate-request-service";
import { CertificateRequestStatus } from "../certificate-request/certificate-request-types";
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { TPkiApplicationDALFactory } from "../pki-application/pki-application-dal";
import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";
import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal";
import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue";
import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";
import {
  insertMetadataForCertificate,
  insertMetadataForCertificateRequest
} from "../resource-metadata/resource-metadata-fns";
import { certificateRenewalServiceFactory } from "./certificate-renewal-service";
import { processSelfSignedCertificate } from "./certificate-self-signed-fns";
import { applyProfileDefaults, resolveEffectiveTtl } from "./certificate-v3-fns";
import {
  TCertificateIssuanceResponse,
  TIssueCertificateFromProfileDTO,
  TOrderCertificateFromProfileDTO,
  TSignCertificateFromProfileDTO,
  TUpdateCertificateDTO
} from "./certificate-v3-types";

type TCertificateV3ServiceFactoryDep = {
  certificateDAL: Pick<
    TCertificateDALFactory,
    | "findOne"
    | "findById"
    | "findByIdForUpdate"
    | "findByIdForShare"
    | "updateById"
    | "transaction"
    | "create"
    | "find"
    | "getRequestEnrollmentTypeByCertId"
    | "getOriginatingRequestByCertId"
  >;
  certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
  certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create">;
  certificateAuthorityDAL: Pick<
    TCertificateAuthorityDALFactory,
    "findByIdWithAssociatedCa" | "create" | "transaction" | "updateById" | "findWithAssociatedCa" | "findById"
  >;
  certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs" | "findById">;
  acmeAccountDAL: Pick<TPkiAcmeAccountDALFactory, "findById">;
  certificatePolicyService: Pick<
    TCertificatePolicyServiceFactory,
    "validateCertificateRequest" | "validateRequestAgainstPolicy" | "getPolicyById"
  >;
  internalCaService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa" | "issueCertFromCa">;
  caKeySourceService: Pick<TCaKeySourceServiceFactory, "resolveCsrSignatureAlgorithm">;
  permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
  certificateSyncDAL: Pick<
    TCertificateSyncDALFactory,
    | "findPkiSyncIdsByCertificateId"
    | "addCertificates"
    | "findByPkiSyncAndCertificate"
    | "updateSyncMetadata"
    | "primaryNode"
  >;
  pkiSyncDAL: Pick<TPkiSyncDALFactory, "find">;
  pkiSyncQueue: Pick<TPkiSyncQueueFactory, "queuePkiSyncSyncCertificatesById" | "queuePkiSyncLinkMatchingCertificates">;
  kmsService: Pick<
    TKmsServiceFactory,
    "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey" | "createCipherPairWithDataKey"
  >;
  projectDAL: TProjectDALFactory;
  certificateIssuanceQueue: Pick<
    import("../certificate-authority/certificate-issuance-queue").TCertificateIssuanceQueueFactory,
    "queueCertificateIssuance"
  >;
  certificateRequestService: Pick<TCertificateRequestServiceFactory, "createCertificateRequest">;
  approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findByProjectId" | "findStepsByPolicyId">;
  certificateRequestDAL: Pick<
    TCertificateRequestDALFactory,
    "updateById" | "findById" | "create" | "transaction" | "attachCertificate" | "transitionFromPending"
  >;
  userDAL: Pick<TUserDALFactory, "findById">;
  identityDAL: Pick<TIdentityDALFactory, "findById">;
  approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "createRequestFromPolicy" | "matchPolicy">;
  resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete" | "find">;
  pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
  certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "emit">;
  pkiApplicationProfileDAL: Pick<
    TPkiApplicationProfileDALFactory,
    "findAllByProfileId" | "findOneByApplicationAndProfile"
  >;
  pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;
  apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
  licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;
  usageCounterDAL: Pick<
    TUsageCounterDALFactory,
    "countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
  >;
  keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
  telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
  auditLogService: Pick<TAuditLogServiceFactory, "createCollapsedAuditLog">;
};

export type TCertificateV3ServiceFactory = ReturnType<typeof certificateV3ServiceFactory>;

const validateProfileAndPermissions = async ({
  profileId,
  actor,
  actorId,
  actorAuthMethod,
  actorOrgId,
  certificateProfileDAL,
  acmeAccountDAL,
  permissionService,
  requiredEnrollmentType,
  isInternal = false,
  applicationId
}: {
  profileId: string;
  actor?: ActorType;
  actorId?: string;
  actorAuthMethod?: ActorAuthMethod;
  actorOrgId?: string;
  certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
  acmeAccountDAL: Pick<TPkiAcmeAccountDALFactory, "findById">;
  permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
  requiredEnrollmentType: EnrollmentType;
  isInternal?: boolean;
  applicationId?: string;
}) => {
  const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
  if (!profile) {
    throw new NotFoundError({ message: "Certificate profile not found" });
  }

  if (!applicationId && profile.enrollmentType !== requiredEnrollmentType) {
    throw new ForbiddenRequestError({
      message: `Profile is not configured for ${requiredEnrollmentType} enrollment`
    });
  }

  if (isInternal) {
    return profile;
  }

  if (!actor || !actorId || !actorOrgId) {
    throw new BadRequestError({ message: "Actor is required" });
  }

  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;
  }

  if (actor === ActorType.SCEP_ACCOUNT && requiredEnrollmentType === EnrollmentType.SCEP) {
    if (actorId !== profile.id) {
      throw new ForbiddenRequestError({
        message: "SCEP profile mismatch"
      });
    }
    return profile;
  }

  if (applicationId && (actor === ActorType.USER || actor === ActorType.IDENTITY)) {
    const { permission } = await permissionService.getResourcePermission({
      actor,
      actorId,
      projectId: profile.projectId,
      resourceType: ResourceType.CertificateApplication,
      resourceId: applicationId,
      actorAuthMethod: actorAuthMethod || null,
      actorOrgId
    });

    ForbiddenError.from(permission).throwUnlessCan(
      ProjectPermissionCertificateProfileActions.IssueCert,
      ProjectPermissionSub.CertificateProfiles
    );
    return profile;
  }

  const { permission } = await permissionService.getProjectPermission({
    actor,
    actorId,
    projectId: profile.projectId,
    actorAuthMethod: actorAuthMethod || null,
    actorOrgId,
    actionProjectType: ActionProjectType.CertificateManager
  });

  ForbiddenError.from(permission).throwUnlessCan(
    ProjectPermissionCertificateProfileActions.IssueCert,
    subject(ProjectPermissionSub.CertificateProfiles, {
      slug: profile.slug
    })
  );

  return profile;
};

// Builds the certificate permission subject from a persisted certificate record so the private-key
// read permission is evaluated against the same fields the certificate read paths use. Includes every
// field the certificate permission conditions support, so attribute-scoped grants match consistently.
const buildCertificateReadPrivateKeySubject = (
  certRecord: {
    commonName?: string | null;
    altNames?: string | null;
    serialNumber?: string | null;
    friendlyName?: string | null;
    status?: string | null;
  },
  metadata?: { key: string; value: string }[]
) =>
  subject(ProjectPermissionSub.Certificates, {
    commonName: certRecord.commonName ?? undefined,
    altNames: certRecord.altNames ? certRecord.altNames.split(",").map((san) => san.trim()) : undefined,
    serialNumber: certRecord.serialNumber ?? undefined,
    friendlyName: certRecord.friendlyName ?? undefined,
    status: certRecord.status ?? undefined,
    metadata
  });

export const certificateV3ServiceFactory = ({
  certificateDAL,
  certificateBodyDAL,
  certificateSecretDAL,
  certificateAuthorityDAL,
  certificateProfileDAL,
  acmeAccountDAL,
  certificatePolicyService,
  internalCaService,
  caKeySourceService,
  permissionService,
  certificateSyncDAL,
  pkiSyncDAL,
  pkiSyncQueue,
  kmsService,
  projectDAL,
  certificateIssuanceQueue,
  certificateRequestService,
  approvalPolicyDAL,
  certificateRequestDAL,
  userDAL,
  identityDAL,
  approvalPolicyService,
  resourceMetadataDAL,
  pkiAlertV2Queue,
  certificateAlertEventEmitter,
  pkiApplicationProfileDAL,
  pkiApplicationDAL,
  apiEnrollmentConfigDAL,
  licenseService,
  usageCounterDAL,
  keyStore,
  telemetryService,
  auditLogService
}: TCertificateV3ServiceFactoryDep) => {
  const $quotaDeps = { projectDAL, licenseService, usageCounterDAL, keyStore };

  const $emitIssuanceAlert = (input: Omit<TCertificateAlertEventInput, "eventType">, tx: Knex) =>
    certificateAlertEventEmitter.emit({ ...input, eventType: CertificateApplicationAlertEvent.Issuance }, tx);

  // Called once the certificate row exists, never at the check.
  const $recordQuotaUsage = async (usage?: { orgId: string; isNewQuotaKey: boolean; isWildcard: boolean }) => {
    if (usage?.isNewQuotaKey) await recordNewCertificateQuotaKey(usage.orgId, { keyStore }, usage.isWildcard);
  };
  const $reportCertificateIssued = async ({
    orgId,
    projectId,
    profileId,
    applicationId,
    enrollmentType,
    operation,
    actor,
    actorId
  }: {
    orgId?: string;
    projectId: string;
    profileId?: string | null;
    applicationId?: string | null;
    enrollmentType: EnrollmentType;
    operation: CertificateIssuanceOperation;
    actor?: ActorType;
    actorId?: string;
  }) => {
    let distinctId: string | undefined;
    try {
      if (actor === ActorType.USER && actorId) {
        const user = await requestMemoize(requestMemoKeys.userFindById(actorId), () => userDAL.findById(actorId));
        distinctId = user?.username ?? user?.email;
      } else if (actor === ActorType.IDENTITY && actorId) {
        distinctId = `identity-${actorId}`;
      }
    } catch (error) {
      logger.debug({ error }, "Failed to resolve distinctId for certificate issuance telemetry");
    }

    await reportCertificateIssued({
      telemetryService,
      projectDAL,
      orgId,
      projectId,
      profileId,
      applicationId,
      enrollmentType,
      operation,
      distinctId
    });
  };

  const $resolveApplicationIdForProfile = async (
    profile: {
      id: string;
      projectId: string;
      apiConfigId?: string | null;
      estConfigId?: string | null;
      acmeConfigId?: string | null;
      scepConfigId?: string | null;
    },
    explicit: string | undefined,
    actorContext?: {
      actor?: ActorType;
      actorId?: string;
      actorAuthMethod?: ActorAuthMethod;
      actorOrgId?: string;
    },
    requiredEnrollmentType?: EnrollmentType
  ): Promise<string | undefined> => {
    const junctions = await pkiApplicationProfileDAL.findAllByProfileId(profile.id);

    if (explicit) {
      const junction = junctions.find((j) => j.applicationId === explicit);
      if (!junction) {
        throw new BadRequestError({
          message: "This profile is not attached to the specified Application."
        });
      }

      if (requiredEnrollmentType) {
        let junctionConfigId: string | null | undefined;
        switch (requiredEnrollmentType) {
          case EnrollmentType.API:
            junctionConfigId = junction.apiConfigId;
            break;
          case EnrollmentType.EST:
            junctionConfigId = junction.estConfigId;
            break;
          case EnrollmentType.ACME:
            junctionConfigId = junction.acmeConfigId;
            break;
          case EnrollmentType.SCEP:
            junctionConfigId = junction.scepConfigId;
            break;
          default:
            junctionConfigId = null;
        }
        if (!junctionConfigId) {
          throw new BadRequestError({
            message: `${requiredEnrollmentType.toUpperCase()} enrollment is not configured for this profile on the Application.`
          });
        }
      }

      if (
        actorContext?.actor &&
        actorContext.actor !== ActorType.ACME_ACCOUNT &&
        actorContext.actor !== ActorType.ACME_PROFILE &&
        actorContext.actor !== ActorType.EST_ACCOUNT &&
        actorContext.actor !== ActorType.SCEP_ACCOUNT &&
        actorContext.actorId &&
        actorContext.actorOrgId
      ) {
        const { permission } = await permissionService.getResourcePermission({
          actor: actorContext.actor,
          actorId: actorContext.actorId,
          projectId: profile.projectId,
          resourceType: ResourceType.CertificateApplication,
          resourceId: explicit,
          actorAuthMethod: actorContext.actorAuthMethod ?? null,
          actorOrgId: actorContext.actorOrgId
        });
        ForbiddenError.from(permission).throwUnlessCan(
          ResourcePermissionCertificateActions.Create,
          ResourcePermissionSub.Certificates
        );
      }

      return explicit;
    }

    const hasProfileLevelEnrollment = Boolean(
      profile.apiConfigId || profile.estConfigId || profile.acmeConfigId || profile.scepConfigId
    );
    if (!hasProfileLevelEnrollment) {
      throw new BadRequestError({
        message: "This profile must be issued through an Application. Attach it to an Application and issue from there."
      });
    }

    return undefined;
  };

  const resolveRequesterInfo = async (
    actor: ActorType,
    actorId: string,
    enrollmentType: EnrollmentType
  ): Promise<{ requesterName: string; requesterEmail: string }> => {
    if (actor === ActorType.USER) {
      const user = await userDAL.findById(actorId);
      if (user) {
        return {
          requesterName: `${user.firstName || ""} ${user.lastName || ""}`.trim() || user.email || "Unknown User",
          requesterEmail: user.email || ""
        };
      }
    } else if (actor === ActorType.IDENTITY) {
      const identity = await requestMemoize(requestMemoKeys.identityFindById(actorId), () =>
        identityDAL.findById(actorId)
      );
      if (identity) {
        return {
          requesterName: identity.name || "Machine Identity",
          requesterEmail: ""
        };
      }
      return { requesterName: "Machine Identity", requesterEmail: "" };
    } else if (actor === ActorType.ACME_ACCOUNT || actor === ActorType.ACME_PROFILE) {
      return { requesterName: "ACME Client", requesterEmail: "" };
    } else if (enrollmentType === EnrollmentType.EST) {
      return { requesterName: "EST Client", requesterEmail: "" };
    }
    return { requesterName: "Unknown Client", requesterEmail: "" };
  };

  const shouldBypassApproval = (actor: ActorType, policy: TCertRequestPolicy | null): boolean => {
    return actor === ActorType.IDENTITY && policy?.bypassForMachineIdentities === true;
  };

  const $resolveApplicationName = async (applicationId?: string | null) => {
    if (!applicationId) return null;
    const application = await pkiApplicationDAL.findById(applicationId);
    return application?.name ?? null;
  };

  const $recordIssuanceFailure = async ({
    auditLogInfo,
    actorOrgId,
    projectId,
    profileId,
    error,
    metadata
  }: {
    auditLogInfo?: AuditLogInfo;
    actorOrgId: string;
    projectId?: string;
    profileId?: string | null;
    error: unknown;
    metadata: Omit<
      Parameters<typeof recordCertificateIssuanceFailure>[1]["metadata"],
      "certificateProfileId" | "profileName" | "applicationName" | "caName"
    >;
  }) => {
    if (!auditLogInfo) return;
    try {
      const profile = profileId ? await certificateProfileDAL.findById(profileId) : undefined;
      const resolvedProjectId = projectId ?? profile?.projectId;
      if (!resolvedProjectId) return;

      // The ids come from the caller, so never write into another org's audit log.
      const project = await projectDAL.findById(resolvedProjectId);
      if (project?.orgId !== actorOrgId) return;

      await recordCertificateIssuanceFailure(
        { auditLogService, certificateAuthorityDAL, pkiApplicationDAL },
        {
          auditLogInfo,
          projectId: resolvedProjectId,
          error,
          metadata: {
            ...metadata,
            certificateProfileId: profile?.id,
            profileName: profile?.slug,
            caId: metadata.caId ?? profile?.caId
          }
        }
      );
    } catch (lookupError) {
      logger.warn(lookupError, `Failed to record certificate issuance failure [operation=${metadata.operation}]`);
    }
  };

  const $commonNameFromCsr = (csr?: string) => {
    if (!csr) return undefined;
    try {
      return extractCertificateRequestFromCSR(csr).commonName || undefined;
    } catch {
      return undefined;
    }
  };

  const $issueCertificateFromProfile = async ({
    profileId,
    certificateRequest,
    metadata,
    actor,
    actorId,
    actorAuthMethod,
    actorOrgId,
    removeRootsFromChain,
    applicationId: explicitApplicationId
  }: TIssueCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {
    const profile = await validateProfileAndPermissions({
      profileId,
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId,
      certificateProfileDAL,
      acmeAccountDAL,
      permissionService,
      requiredEnrollmentType: EnrollmentType.API,
      isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT,
      applicationId: explicitApplicationId
    });

    const applicationId = await $resolveApplicationIdForProfile(
      profile,
      explicitApplicationId,
      { actor, actorId, actorAuthMethod, actorOrgId },
      EnrollmentType.API
    );
    const applicationName = await $resolveApplicationName(applicationId);

    const matchedApprovalPolicy = (await approvalPolicyService.matchPolicy(
      ApprovalPolicyType.CertRequest,
      profile.projectId,
      { profileName: profile.slug, applicationId }
    )) as TCertRequestPolicy | null;

    const certificateRequestWithDefaults = applyProfileDefaults(certificateRequest, profile.defaults);

    const quotaUsage = await validateCertificateRequestLicense({
      request: certificateRequestWithDefaults,
      // This flow issues from altNames; the CSR flows below issue from subjectAlternativeNames.
      altNames: (certificateRequestWithDefaults.altNames ?? []).map((san) => san.value).join(","),
      projectId: profile.projectId,
      projectDAL,
      licenseService,
      quotaDeps: $quotaDeps
    });

    if (matchedApprovalPolicy && !shouldBypassApproval(actor, matchedApprovalPolicy)) {
      const approvalPolicy = matchedApprovalPolicy;

      const mappedCertificateRequestForValidation = mapEnumsForValidation({
        ...certificateRequestWithDefaults,
        subjectAlternativeNames: certificateRequestWithDefaults.altNames
      });

      const policy = await certificatePolicyService.getPolicyById({
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId,
        policyId: profile.certificatePolicyId,
        internal: true
      });
      if (!policy) {
        throw new NotFoundError({ message: "Certificate policy not found for this profile" });
      }

      const validationResult = await certificatePolicyService.validateCertificateRequest(
        profile.certificatePolicyId,
        mappedCertificateRequestForValidation,
        { profileCustomExtensions: profile.defaults?.customExtensions }
      );

      if (!validationResult.isValid) {
        throw new BadRequestError({
          message: `Certificate request validation failed: ${validationResult.errors.join(", ")}`
        });
      }

      const policySteps = await approvalPolicyDAL.findStepsByPolicyId(approvalPolicy.id);
      const { requesterName, requesterEmail } = await resolveRequesterInfo(actor, actorId, EnrollmentType.API);

      const resolvedTtl = resolveEffectiveTtl({
        requestTtl: certificateRequest.validity.ttl || undefined,
        profileDefaultTtlDays: profile.defaults?.ttlDays,
        policyMaxValidity: policy?.validity?.max,
        flowDefaultTtl: ""
      });

      const { certRequestId, approvalRequestId } = await certificateRequestDAL.transaction(async (tx) => {
        // Explicitly set createdAt to ensure millisecond precision matches when used in composite FK references
        // (resource_metadata references the partitioned certificate_requests table via [id, createdAt]).
        const certRequestCreatedAt = new Date();
        const certRequest = await certificateRequestDAL.create(
          {
            projectId: profile.projectId,
            profileId: profile.id,
            caId: profile.caId ?? null,
            applicationId: applicationId ?? null,
            commonName: certificateRequestWithDefaults.commonName || null,
            altNames: certificateRequestWithDefaults.altNames
              ? JSON.stringify(certificateRequestWithDefaults.altNames)
              : null,
            keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages) || [],
            extendedKeyUsages:
              convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages) || [],
            notBefore: certificateRequestWithDefaults.notBefore || null,
            notAfter: certificateRequestWithDefaults.notAfter || null,
            keyAlgorithm: certificateRequestWithDefaults.keyAlgorithm || null,
            signatureAlgorithm: certificateRequestWithDefaults.signatureAlgorithm || null,
            ttl: resolvedTtl,
            enrollmentType: EnrollmentType.API,
            status: CertificateRequestStatus.PENDING_APPROVAL,
            customExtensions: validationResult.resolvedCustomExtensions
              ? JSON.stringify(validationResult.resolvedCustomExtensions)
              : null,
            organization: certificateRequestWithDefaults.organization || null,
            organizationalUnit: certificateRequestWithDefaults.organizationalUnit || null,
            country: certificateRequestWithDefaults.country || null,
            state: certificateRequestWithDefaults.state || null,
            locality: certificateRequestWithDefaults.locality || null,
            domainComponents: certificateRequestWithDefaults.domainComponents
              ? certificateRequestWithDefaults.domainComponents.join(",")
              : null,
            basicConstraints: certificateRequestWithDefaults.basicConstraints
              ? JSON.stringify(certificateRequestWithDefaults.basicConstraints)
              : null,
            createdAt: certRequestCreatedAt
          } as Parameters<typeof certificateRequestDAL.create>[0] & { createdAt: Date },
          tx
        );

        if (metadata && metadata.length > 0) {
          await insertMetadataForCertificateRequest(resourceMetadataDAL, {
            metadata,
            certificateRequestId: certRequest.id,
            certificateRequestCreatedAt: certRequest.createdAt,
            orgId: actorOrgId,
            tx
          });
        }

        const requestData: TCertRequestRequestData = {
          profileId,
          profileName: profile.slug,
          certificateRequest: {
            commonName: certificateRequestWithDefaults.commonName,
            organization: certificateRequestWithDefaults.organization,
            organizationalUnit: certificateRequestWithDefaults.organizationalUnit,
            country: certificateRequestWithDefaults.country,
            state: certificateRequestWithDefaults.state,
            locality: certificateRequestWithDefaults.locality,
            domainComponents: certificateRequestWithDefaults.domainComponents,
            keyUsages: certificateRequestWithDefaults.keyUsages,
            extendedKeyUsages: certificateRequestWithDefaults.extendedKeyUsages,
            altNames: certificateRequestWithDefaults.altNames,
            validity: certificateRequestWithDefaults.validity,
            notBefore: certificateRequestWithDefaults.notBefore?.toISOString(),
            notAfter: certificateRequestWithDefaults.notAfter?.toISOString(),
            signatureAlgorithm: certificateRequestWithDefaults.signatureAlgorithm,
            keyAlgorithm: certificateRequestWithDefaults.keyAlgorithm,
            basicConstraints: certificateRequestWithDefaults.basicConstraints,
            customExtensions: validationResult.resolvedCustomExtensions
          },
          certificateRequestId: certRequest.id
        };

        const expiresAt = approvalPolicy.maxRequestTtl ? new Date(Date.now() + ms(approvalPolicy.maxRequestTtl)) : null;

        const { request: approvalRequest } = await approvalPolicyService.createRequestFromPolicy({
          projectId: profile.projectId,
          organizationId: actorOrgId,
          policy: { ...approvalPolicy, steps: policySteps },
          requestData,
          justification: `Certificate issuance request for ${certificateRequest.commonName || profile.slug}`,
          expiresAt,
          requesterUserId: actor === ActorType.USER ? actorId : null,
          machineIdentityId: actor === ActorType.IDENTITY ? actorId : null,
          requesterName,
          requesterEmail,
          tx
        });

        await certificateRequestDAL.updateById(
          certRequest.id,
          {
            approvalRequestId: approvalRequest.id
          },
          tx
        );

        return { certRequestId: certRequest.id, approvalRequestId: approvalRequest.id };
      });

      logger.info(
        {
          certificateRequestId: certRequestId,
          approvalRequestId,
          profileId,
          profileName: profile.slug
        },
        "Certificate request requires approval"
      );

      return {
        status: CertificateRequestStatus.PENDING_APPROVAL,
        certificateRequestId: certRequestId,
        message: "Certificate request requires approval",
        projectId: profile.projectId,
        profileName: profile.slug,
        commonName: certificateRequest.commonName,
        applicationId,
        applicationName
      };
    }

    if (certificateRequest.commonName && Array.isArray(certificateRequest.commonName)) {
      throw new BadRequestError({
        message: "Common Name must be a single value, not an array"
      });
    }

    const mappedCertificateRequest = mapEnumsForValidation({
      ...certificateRequestWithDefaults,
      subjectAlternativeNames: certificateRequestWithDefaults.altNames
    });

    const policy = await certificatePolicyService.getPolicyById({
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId,
      policyId: profile.certificatePolicyId,
      internal: true
    });
    if (!policy) {
      throw new NotFoundError({ message: "Certificate policy not found for this profile" });
    }

    const validationResult = await certificatePolicyService.validateCertificateRequest(
      profile.certificatePolicyId,
      mappedCertificateRequest,
      { profileCustomExtensions: profile.defaults?.customExtensions }
    );

    if (!validationResult.isValid) {
      throw new BadRequestError({
        message: `Certificate request validation failed: ${validationResult.errors.join(", ")}`
      });
    }

    const { resolvedCustomExtensions } = validationResult;

    const effectiveSignatureAlgorithm = certificateRequestWithDefaults.signatureAlgorithm as
      | CertSignatureAlgorithm
      | undefined;
    const effectiveKeyAlgorithm = certificateRequestWithDefaults.keyAlgorithm as CertKeyAlgorithm | undefined;

    if (policy.algorithms?.keyAlgorithm && !effectiveKeyAlgorithm) {
      throw new BadRequestError({
        message: "Key algorithm is required by this policy but not provided in request"
      });
    }

    if (policy.algorithms?.signature && !effectiveSignatureAlgorithm) {
      throw new BadRequestError({
        message: "Signature algorithm is required by this policy but not provided in request"
      });
    }

    const certificateSubject = buildCertificateSubjectFromTemplate(certificateRequestWithDefaults, policy?.subject);
    const subjectAlternativeNames = buildSubjectAlternativeNamesFromTemplate(
      { subjectAlternativeNames: certificateRequestWithDefaults.altNames },
      policy?.sans
    );

    const issuerType = profile?.issuerType || (profile?.caId ? IssuerType.CA : IssuerType.SELF_SIGNED);

    if (issuerType === IssuerType.SELF_SIGNED) {
      const resolvedTtl = resolveEffectiveTtl({
        requestTtl: certificateRequest.validity.ttl || undefined,
        profileDefaultTtlDays: profile.defaults?.ttlDays,
        policyMaxValidity: policy?.validity?.max,
        flowDefaultTtl: ""
      });

      const result = await certificateDAL.transaction(async (tx) => {
        const effectiveAlgorithms = getEffectiveAlgorithms(effectiveSignatureAlgorithm, effectiveKeyAlgorithm);

        const processResult = await processSelfSignedCertificate({
          certificateRequest: {
            ...certificateRequestWithDefaults,
            validity: { ttl: resolvedTtl }
          },
          policy,
          profile,
          customExtensions: resolvedCustomExtensions,
          effectiveAlgorithms,
          certificateDAL,
          certificateBodyDAL,
          certificateSecretDAL,
          kmsService,
          projectDAL,
          tx
        });

        const certRequestResult = await certificateRequestService.createCertificateRequest({
          internal: true,
          actor,
          actorId,
          actorAuthMethod,
          actorOrgId,
          projectId: profile.projectId,
          tx,
          profileId: profile.id,
          applicationId,
          commonName: certificateRequestWithDefaults.commonName,
          altNames: certificateRequestWithDefaults.altNames,
          keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages),
          extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages),
          notBefore: certificateRequestWithDefaults.notBefore,
          notAfter: certificateRequestWithDefaults.notAfter,
          keyAlgorithm: effectiveKeyAlgorithm,
          signatureAlgorithm: effectiveSignatureAlgorithm,
          status: CertificateRequestStatus.ISSUED,
          certificateId: processResult.certificateData.id,
          customExtensions: resolvedCustomExtensions,
          ttl: resolvedTtl,
          enrollmentType: EnrollmentType.API,
          organization: certificateRequestWithDefaults.organization,
          organizationalUnit: certificateRequestWithDefaults.organizationalUnit,
          country: certificateRequestWithDefaults.country,
          state: certificateRequestWithDefaults.state,
          locality: certificateRequestWithDefaults.locality,
          domainComponents: certificateRequestWithDefaults.domainComponents
        });

        if (metadata && metadata.length > 0) {
          await insertMetadataForCertificate(resourceMetadataDAL, {
            metadata,
            certificateId: processResult.certificateData.id,
            orgId: actorOrgId,
            tx
          });
          await insertMetadataForCertificateRequest(resourceMetadataDAL, {
            metadata,
            certificateRequestId: certRequestResult.id,
            certificateRequestCreatedAt: certRequestResult.createdAt,
            orgId: actorOrgId,
            tx
          });
        }

        const effectiveApiConfig = await resolveEffectiveApiConfig({
          applicationId,
          profileId: profile.id,
          profileApiConfig: profile.apiConfig,
          pkiApplicationProfileDAL,
          apiEnrollmentConfigDAL
        });
        const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
          { apiConfig: effectiveApiConfig },
          resolvedTtl,
          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, certificateRequestId: certRequestResult.id };
      });

      const { selfSignedResult, certificateData, certificateRequestId } = result;

      const subjectCommonName =
        (selfSignedResult.certificateSubject.common_name as string) ||
        certificateRequest.commonName ||
        "Self-signed Certificate";

      const { permission } = await permissionService.getProjectPermission({
        actor,
        actorId,
        projectId: profile.projectId,
        actorAuthMethod,
        actorOrgId,
        actionProjectType: ActionProjectType.CertificateManager
      });

      let canReadPrivateKey: boolean;
      if (applicationId) {
        const { permission: resourcePermission } = await permissionService.getResourcePermission({
          actor,
          actorId,
          projectId: profile.projectId,
          resourceType: ResourceType.CertificateApplication,
          resourceId: applicationId,
          actorAuthMethod,
          actorOrgId
        });
        canReadPrivateKey = resourcePermission.can(
          ResourcePermissionCertificateActions.ReadPrivateKey,
          ResourcePermissionSub.Certificates
        );
      } else {
        canReadPrivateKey = permission.can(
          ProjectPermissionCertificateActions.ReadPrivateKey,
          buildCertificateReadPrivateKeySubject(certificateData, metadata)
        );
      }

      const privateKeyForResponse = canReadPrivateKey ? selfSignedResult.privateKey.toString("utf8") : undefined;

      try {
        await pkiAlertV2Queue?.queueCertificateEvent({
          certificateId: certificateData.id,
          projectId: profile.projectId,
          eventType: PkiAlertEventType.ISSUANCE,
          applicationId: applicationId ?? null
        });
      } catch {
        logger.debug("Failed to queue PKI issuance alert event");
      }

      if (certificateData.id && applicationId) {
        await queueCertificateFilterReconcile(certificateData.id, applicationId, pkiSyncQueue);
      }

      await $reportCertificateIssued({
        orgId: profile.project?.orgId ?? actorOrgId,
        projectId: profile.projectId,
        profileId,
        applicationId,
        enrollmentType: EnrollmentType.API,
        operation: CertificateIssuanceOperation.ISSUE,
        actor,
        actorId
      });

      return {
        status: CertificateRequestStatus.ISSUED,
        certificate: selfSignedResult.certificate.toString("utf8"),
        issuingCaCertificate: "",
        certificateChain: selfSignedResult.certificate.toString("utf8"),
        privateKey: privateKeyForResponse,
        serialNumber: selfSignedResult.serialNumber,
        certificateId: certificateData.id,
        certificateRequestId,
        projectId: profile.projectId,
        profileName: profile.slug,
        commonName: subjectCommonName,
        applicationId,
        applicationName
      };
    }

    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, policy);

    const shouldIssueAsCA = certificateRequest.basicConstraints?.isCA === true;
    const policyIsCAState: CertPolicyState =
      (policy.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED;

    if (shouldIssueAsCA && policyIsCAState === CertPolicyState.DENIED) {
      throw new BadRequestError({
        message:
          "CA certificate issuance is not allowed by this policy. The policy's CA:true basicConstraints must be set to 'allowed' or 'required'."
      });
    }

    const caBasicConstraints = shouldIssueAsCA
      ? { isCA: true, pathLength: policy.basicConstraints?.maxPathLength }
      : undefined;

    const {
      certificate,
      certificateChain,
      issuingCaCertificate,
      privateKey,
      serialNumber,
      cert,
      certificateRequestId
    } = await certificateDAL.transaction(async (tx) => {
      const baseCertParams = {
        caId: ca.id,
        friendlyName: certificateSubject.common_name || "Certificate",
        commonName: certificateSubject.common_name || "",
        altNames: subjectAlternativeNames,
        altNameEntries: certificateRequestWithDefaults.altNames,
        basicConstraints: caBasicConstraints,
        pathLength: certificateRequestWithDefaults.basicConstraints?.pathLength,
        ttl: resolveEffectiveTtl({
          requestTtl: certificateRequest.validity.ttl,
          profileDefaultTtlDays: profile.defaults?.ttlDays,
          policyMaxValidity: policy?.validity?.max,
          flowDefaultTtl: ""
        }),
        keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages) || [],
        extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages) || [],
        notBefore: normalizeDateForApi(certificateRequest.notBefore),
        notAfter: normalizeDateForApi(certificateRequest.notAfter),
        signatureAlgorithm: effectiveSignatureAlgorithm,
        keyAlgorithm: effectiveKeyAlgorithm,
        isFromProfile: true,
        organization: certificateRequestWithDefaults.organization,
        ou: certificateRequestWithDefaults.organizationalUnit,
        country: certificateRequestWithDefaults.country,
        state: certificateRequestWithDefaults.state,
        locality: certificateRequestWithDefaults.locality,
        domainComponents: certificateRequestWithDefaults.domainComponents,
        customExtensions: resolvedCustomExtensions,
        tx
      };

      const certResult = await internalCaService.issueCertFromCa({
        ...baseCertParams,
        internal: true as const
      });

      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 effectiveTtl = resolveEffectiveTtl({
        requestTtl: certificateRequest.validity.ttl,
        profileDefaultTtlDays: profile.defaults?.ttlDays,
        policyMaxValidity: policy?.validity?.max,
        flowDefaultTtl: ""
      });

      const effectiveApiConfig = await resolveEffectiveApiConfig({
        applicationId,
        profileId: profile.id,
        profileApiConfig: profile.apiConfig,
        pkiApplicationProfileDAL,
        apiEnrollmentConfigDAL
      });
      const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
        { apiConfig: effectiveApiConfig },
        effectiveTtl,
        new Date(certificateRecord.notAfter)
      );

      const updateData: { profileId: string; renewBeforeDays?: number; applicationId?: string } = {
        profileId
      };
      if (finalRenewBeforeDays !== undefined) {
        updateData.renewBeforeDays = finalRenewBeforeDays;
      }
      if (applicationId) {
        updateData.applicationId = applicationId;
      }
      await certificateDAL.updateById(certificateRecord.id, updateData, tx);

      const certRequestResult = await certificateRequestService.createCertificateRequest({
        internal: true,
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId,
        projectId: profile.projectId,
        tx,
        caId: ca.id,
        profileId: profile.id,
        applicationId,
        commonName: certificateRequestWithDefaults.commonName,
        altNames: certificateRequestWithDefaults.altNames,
        keyUsages: convertKeyUsageArrayToLegacy(certificateRequestWithDefaults.keyUsages),
        extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequestWithDefaults.extendedKeyUsages),
        notBefore: certificateRequestWithDefaults.notBefore,
        notAfter: certificateRequestWithDefaults.notAfter,
        keyAlgorithm: effectiveKeyAlgorithm,
        signatureAlgorithm: effectiveSignatureAlgorithm,
        status: CertificateRequestStatus.ISSUED,
        certificateId: certResult.certificateId,
        customExtensions: resolvedCustomExtensions,
        basicConstraints: certificateRequestWithDefaults.basicConstraints,
        ttl: effectiveTtl,
        enrollmentType: EnrollmentType.API,
        organization: certificateRequestWithDefaults.organization,
        organizationalUnit: certificateRequestWithDefaults.organizationalUnit,
        country: certificateRequestWithDefaults.country,
        state: certificateRequestWithDefaults.state,
        locality: certificateRequestWithDefaults.locality,
        domainComponents: certificateRequestWithDefaults.domainComponents
      });

      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
        });
      }

      await $emitIssuanceAlert(
        {
          certificateId: certResult.certificateId,
          projectId: profile.projectId,
          orgId: profile.project?.orgId,
          applicationId
        },
        tx
      );

      return { ...certResult, cert: certificateRecord, certificateRequestId: certRequestResult.id };
    });

    let finalCertificateChain = bufferToString(certificateChain);
    if (removeRootsFromChain) {
      finalCertificateChain = removeRootCaFromChain(finalCertificateChain);
    }

    // Check if user has permission to read private key
    const { permission } = await permissionService.getProjectPermission({
      actor,
      actorId,
      projectId: profile.projectId,
      actorAuthMethod,
      actorOrgId,
      actionProjectType: ActionProjectType.CertificateManager
    });

    let canReadPrivateKey: boolean;
    if (applicationId) {
      const { permission: resourcePermission } = await permissionService.getResourcePermission({
        actor,
        actorId,
        projectId: profile.projectId,
        resourceType: ResourceType.CertificateApplication,
        resourceId: applicationId,
        actorAuthMethod,
        actorOrgId
      });
      canReadPrivateKey = resourcePermission.can(
        ResourcePermissionCertificateActions.ReadPrivateKey,
        ResourcePermissionSub.Certificates
      );
    } else {
      canReadPrivateKey = permission.can(
        ProjectPermissionCertificateActions.ReadPrivateKey,
        buildCertificateReadPrivateKeySubject(cert, metadata)
      );
    }

    const privateKeyForResponse = canReadPrivateKey ? bufferToString(privateKey) : undefined;

    try {
      await pkiAlertV2Queue?.queueCertificateEvent({
        certificateId: cert.id,
        projectId: profile.projectId,
        eventType: PkiAlertEventType.ISSUANCE,
        applicationId: applicationId ?? null
      });
    } catch {
      logger.debug("Failed to queue PKI issuance alert event");
    }

    if (cert.id && applicationId) {
      await queueCertificateFilterReconcile(cert.id, applicationId, pkiSyncQueue);
    }

    await $reportCertificateIssued({
      orgId: profile.project?.orgId ?? actorOrgId,
      projectId: profile.projectId,
      profileId,
      applicationId,
      enrollmentType: EnrollmentType.API,
      operation: CertificateIssuanceOperation.ISSUE,
      actor,
      actorId
    });

    await $recordQuotaUsage(quotaUsage);

    return {
      status: CertificateRequestStatus.ISSUED,
      certificate: bufferToString(certificate),
      issuingCaCertificate: bufferToString(issuingCaCertificate),
      certificateChain: finalCertificateChain,
      privateKey: privateKeyForResponse,
      serialNumber,
      certificateId: cert.id,
      certificateRequestId,
      projectId: profile.projectId,
      profileName: profile.slug,
      commonName: cert.commonName || "",
      applicationId,
      applicationName
    };
  };

  const $signCertificateFromProfile = async ({
    profileId,
    csr,
    validity,
    notBefore,
    notAfter,
    actor,
    actorId,
    actorAuthMethod,
    actorOrgId,
    enrollmentType,
    metadata,
    removeRootsFromChain,
    basicConstraints,
    applicationId: explicitApplicationId,
    acmeOrderId
  }: TSignCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {
    const profile = await validateProfileAndPermissions({
      profileId,
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId,
      certificateProfileDAL,
      acmeAccountDAL,
      permissionService,
      requiredEnrollmentType: enrollmentType,
      isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT,
      applicationId: explicitApplicationId
    });
    const applicationId = await $resolveApplicationIdForProfile(
      profile,
      explicitApplicationId,
      { actor, actorId, actorAuthMethod, actorOrgId },
      enrollmentType
    );
    const applicationName = await $resolveApplicationName(applicationId);

    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 policy = await certificatePolicyService.getPolicyById({
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId,
      policyId: profile.certificatePolicyId,
      internal: true
    });

    if (!policy) {
      throw new NotFoundError({ message: "Certificate policy not found for this profile" });
    }

    const csrCertificateRequest = extractCertificateRequestFromCSR(csr);
    const certificateRequest = applyProfileDefaults(csrCertificateRequest, profile.defaults);
    const mappedCertificateRequest = mapEnumsForValidation(certificateRequest);

    const { keyAlgorithm: extractedKeyAlgorithm, signatureAlgorithm: csrSignatureAlgorithm } =
      extractAlgorithmsFromCSR(csr);
    const extractedSignatureAlgorithm = (
      ca.internalCa
        ? await caKeySourceService.resolveCsrSignatureAlgorithm({
            caId: ca.id,
            keyAlgorithm: ca.internalCa.keyAlgorithm as CertKeyAlgorithm,
            csrSignatureAlgorithm
          })
        : csrSignatureAlgorithm
    ) as typeof csrSignatureAlgorithm;

    mappedCertificateRequest.keyAlgorithm = extractedKeyAlgorithm;
    mappedCertificateRequest.signatureAlgorithm = extractedSignatureAlgorithm;

    // Also the gate for the ACME and SCEP internal-CA branches, which sign through here. Their
    // external-CA branches queue issuance instead and are gated in their own services.
    const quotaUsage = await validateCertificateRequestLicense({
      request: mappedCertificateRequest,
      altNames: (mappedCertificateRequest.subjectAlternativeNames ?? []).map((san) => san.value).join(","),
      projectId: profile.projectId,
      projectDAL,
      licenseService,
      quotaDeps: $quotaDeps
    });

    // When notAfter is explicitly provided, validate using date range (notAfter overrides TTL in cert generation).
    // Otherwise, validate using TTL. These are mutually exclusive to avoid "Cannot specify both" validation error.
    if (notAfter) {
      mappedCertificateRequest.notBefore = notBefore;
      mappedCertificateRequest.notAfter = notAfter;
    } else {
      mappedCertificateRequest.validity = validity;
    }

    // Determine effective basicConstraints early (before approval flow)
    // so it's available for both the approval path and direct signing path.
    // Per RFC 5280, keyCertSign in key usage implies CA certificate. We add this because some clients will not send basicConstraints in the CSR.
    const csrHasKeyCertSign = certificateRequest.keyUsages?.includes(CertKeyUsageType.KEY_CERT_SIGN) ?? false;
    const effectiveBasicConstraints = basicConstraints ?? certificateRequest.basicConstraints;
    const shouldIssueAsCA = effectiveBasicConstraints?.isCA === true || csrHasKeyCertSign;

    // Compute the final basicConstraints to store/use
    const resolvedBasicConstraints = shouldIssueAsCA
      ? { isCA: true, pathLength: effectiveBasicConstraints?.pathLength }
      : effectiveBasicConstraints;

    if (resolvedBasicConstraints) {
      mappedCertificateRequest.basicConstraints = resolvedBasicConstraints;
    }

    const validationResult = await certificatePolicyService.validateCertificateRequest(
      profile.certificatePolicyId,
      mappedCertificateRequest,
      { profileCustomExtensions: profile.defaults?.customExtensions }
    );

    if (!validationResult.isValid) {
      throw new BadRequestError({
        message: `Certificate request validation failed: ${validationResult.errors.join(", ")}`
      });
    }

    const { resolvedCustomExtensions } = validationResult;

    validateAlgorithmCompatibility(ca, policy);

    const policyIsCAState: CertPolicyState =
      (policy.basicConstraints?.isCA as CertPolicyState) || CertPolicyState.DENIED;

    if (shouldIssueAsCA && policyIsCAState === CertPolicyState.DENIED) {
      throw new BadRequestError({
        message:
          "CA certificate issuance is not allowed by this policy. The policy's CA:true basicConstraints must be set to 'allowed' or 'required'."
      });
    }

    const csrMatchedApprovalPolicy = (await approvalPolicyService.matchPolicy(
      ApprovalPolicyType.CertRequest,
      profile.projectId,
      { profileName: profile.slug, applicationId }
    )) as TCertRequestPolicy | null;

    if (csrMatchedApprovalPolicy && !shouldBypassApproval(actor, csrMatchedApprovalPolicy)) {
      const approvalPolicy = csrMatchedApprovalPolicy;

      const policySteps = await approvalPolicyDAL.findStepsByPolicyId(approvalPolicy.id);
      const { requesterName, requesterEmail } = await resolveRequesterInfo(actor, actorId, enrollmentType);

      const { certRequestId, approvalRequestId } = await certificateRequestDAL.transaction(async (tx) => {
        // Explicitly set createdAt to ensure millisecond precision matches when used in composite FK references
        const certRequestCreatedAt = new Date();
        const certRequest = await certificateRequestDAL.create(
          {
            projectId: profile.projectId,
            profileId: profile.id,
            caId: profile.caId ?? null,
            applicationId: applicationId ?? null,
            csr,
            commonName: mappedCertificateRequest.commonName || null,
            altNames: mappedCertificateRequest.subjectAlternativeNames
              ? JSON.stringify(mappedCertificateRequest.subjectAlternativeNames)
              : null,
            domainComponents: mappedCertificateRequest.domainComponents
              ? mappedCertificateRequest.domainComponents.join(",")
              : null,
            keyUsages: convertKeyUsageArrayToLegacy(mappedCertificateRequest.keyUsages) || [],
            extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(mappedCertificateRequest.extendedKeyUsages) || [],
            organization: mappedCertificateRequest.organization || null,
            organizationalUnit: mappedCertificateRequest.organizationalUnit || null,
            country: mappedCertificateRequest.country || null,
            state: mappedCertificateRequest.state || null,
            locality: mappedCertificateRequest.locality || null,
            notBefore: notBefore || null,
            notAfter: notAfter || null,
            keyAlgorithm: extractedKeyAlgorithm || null,
            signatureAlgorithm: extractedSignatureAlgorithm || null,
            ttl: validity.ttl,
            enrollmentType,
            status: CertificateRequestStatus.PENDING_APPROVAL,
            basicConstraints: resolvedBasicConstraints ? JSON.stringify(resolvedBasicConstraints) : null,
            customExtensions: resolvedCustomExtensions ? JSON.stringify(resolvedCustomExtensions) : null,
            createdAt: certRequestCreatedAt
          } as Parameters<typeof certificateRequestDAL.create>[0] & { createdAt: Date },
          tx
        );

        if (metadata && metadata.length > 0) {
          await insertMetadataForCertificateRequest(resourceMetadataDAL, {
            metadata,
            certificateRequestId: certRequest.id,
            certificateRequestCreatedAt: certRequest.createdAt,
            orgId: actorOrgId,
            tx
          });
        }

        const requestData: TCertRequestRequestData = {
          profileId,
          profileName: profile.slug,
          certificateRequest: {
            commonName: mappedCertificateRequest.commonName,
            organization: mappedCertificateRequest.organization,
            organizationalUnit: mappedCertificateRequest.organizationalUnit,
            country: mappedCertificateRequest.country,
            state: mappedCertificateRequest.state,
            locality: mappedCertificateRequest.locality,
            domainComponents: mappedCertificateRequest.domainComponents,
            keyUsages: mappedCertificateRequest.keyUsages,
            extendedKeyUsages: mappedCertificateRequest.extendedKeyUsages,
            altNames: mappedCertificateRequest.subjectAlternativeNames,
            validity,
            notBefore: notBefore?.toISOString(),
            notAfter: notAfter?.toISOString(),
            signatureAlgorithm: extractedSignatureAlgorithm,
            keyAlgorithm: extractedKeyAlgorithm,
            basicConstraints: resolvedBasicConstraints,
            customExtensions: resolvedCustomExtensions
          },
          certificateRequestId: certRequest.id
        };

        const expiresAt = approvalPolicy.maxRequestTtl ? new Date(Date.now() + ms(approvalPolicy.maxRequestTtl)) : null;

        const { request: approvalRequest } = await approvalPolicyService.createRequestFromPolicy({
          projectId: profile.projectId,
          organizationId: actorOrgId,
          policy: { ...approvalPolicy, steps: policySteps },
          requestData,
          justification: `Certificate signing request for ${mappedCertificateRequest.commonName || profile.slug}`,
          expiresAt,
          requesterUserId: actor === ActorType.USER ? actorId : null,
          machineIdentityId: actor === ActorType.IDENTITY ? actorId : null,
          requesterName,
          requesterEmail,
          tx
        });

        await certificateRequestDAL.updateById(
          certRequest.id,
          {
            approvalRequestId: approvalRequest.id
          },
          tx
        );

        return { certRequestId: certRequest.id, approvalRequestId: approvalRequest.id };
      });

      logger.info(
        {
          certificateRequestId: certRequestId,
          approvalRequestId,
          profileId,
          profileName: profile.slug
        },
        "CSR signing request requires approval"
      );

      return {
        status: CertificateRequestStatus.PENDING_APPROVAL,
        certificateRequestId: certRequestId,
        message: "Certificate signing request requires approval",
        projectId: profile.projectId,
        profileName: profile.slug,
        commonName: mappedCertificateRequest.commonName,
        applicationId,
        applicationName
      };
    }

    const effectiveSignatureAlgorithm = extractedSignatureAlgorithm;
    const effectiveKeyAlgorithm = extractedKeyAlgorithm;

    // Transform policy basicConstraints to the format expected by the CA service
    const caBasicConstraints = shouldIssueAsCA
      ? { isCA: true, pathLength: policy.basicConstraints?.maxPathLength }
      : undefined;

    const effectiveTtl = resolveEffectiveTtl({
      requestTtl: validity.ttl,
      profileDefaultTtlDays: profile.defaults?.ttlDays,
      policyMaxValidity: policy?.validity?.max,
      flowDefaultTtl: ""
    });

    const subjectOverride = buildSubjectOverrideForCsr(csr, {
      commonName: certificateRequest.commonName,
      organization: certificateRequest.organization,
      organizationalUnit: certificateRequest.organizationalUnit,
      country: certificateRequest.country,
      state: certificateRequest.state,
      locality: certificateRequest.locality,
      domainComponents: certificateRequest.domainComponents
    });

    // 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,
      customExtensions: resolvedCustomExtensions,
      ttl: validity.ttl,
      enrollmentType,
      organization: mappedCertificateRequest.organization,
      organizationalUnit: mappedCertificateRequest.organizationalUnit,
      country: mappedCertificateRequest.country,
      state: mappedCertificateRequest.state,
      locality: mappedCertificateRequest.locality
    });

    const effectiveApiConfig = await resolveEffectiveApiConfig({
      applicationId,
      profileId: profile.id,
      profileApiConfig: profile.apiConfig,
      pkiApplicationProfileDAL,
      apiEnrollmentConfigDAL
    });

    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,
        customExtensions: resolvedCustomExtensions,
        isFromProfile: true,
        onPersisted: async (newCert, tx) => {
          const finalRenewBeforeDays = calculateFinalRenewBeforeDays(
            { apiConfig: effectiveApiConfig },
            effectiveTtl,
            new Date(newCert.notAfter)
          );

          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.
          // Returns null when the request is no longer attachable, meaning it left a pending status
          // while the signing above was in flight — cancelled by a user, or failed by ACME order
          // reconciliation. Throwing here rolls this transaction back, certificate rows included, so a
          // cancelled request can never silently yield an issued certificate. The signature itself is
          // wasted, which is the right trade: an unstored signature costs an HSM operation and a
          // serial, whereas committing would hand back a certificate nothing accounts for.
          await attachCertificateToPendingRequest(
            certificateRequestDAL,
            {
              certificateRequestId: pendingRequest.id,
              certificateId: newCert.id,
              projectId: profile.projectId,
              operation: CertificateIssuanceOperation.SIGN
            },
            tx
          );

          await $emitIssuanceAlert(
            {
              certificateId: newCert.id,
              projectId: profile.projectId,
              orgId: profile.project?.orgId,
              applicationId
            },
            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
            });
          }
        }
      });
    } catch (err) {
      await markPendingRequestFailed(certificateRequestDAL, {
        certificateRequestId: pendingRequest.id,
        error: err,
        fallbackMessage: "Certificate issuance failed"
      });
      tagErrorWithCertificateRequest(err, pendingRequest.id);
      throw err;
    }

    const { certificate, certificateChain, issuingCaCertificate, serialNumber } = certResult;

    const certificateString = extractCertificateFromBuffer(certificate as unknown as Buffer);
    let certificateChainString = extractCertificateFromBuffer(certificateChain as unknown as Buffer);
    if (removeRootsFromChain) {
      certificateChainString = removeRootCaFromChain(certificateChainString);
    }

    try {
      await pkiAlertV2Queue?.queueCertificateEvent({
        certificateId: certResult.certificateId,
        projectId: profile.projectId,
        eventType: PkiAlertEventType.ISSUANCE,
        applicationId: applicationId ?? null
      });
    } catch {
      logger.debug("Failed to queue PKI issuance alert event");
    }

    if (certResult.certificateId && applicationId) {
      await queueCertificateFilterReconcile(certResult.certificateId, applicationId, pkiSyncQueue);
    }

    await $reportCertificateIssued({
      orgId: profile.project?.orgId ?? actorOrgId,
      projectId: profile.projectId,
      profileId,
      applicationId,
      enrollmentType,
      operation: CertificateIssuanceOperation.SIGN,
      actor,
      actorId
    });

    await $recordQuotaUsage(quotaUsage);

    return {
      status: CertificateRequestStatus.ISSUED,
      certificate: certificateString,
      issuingCaCertificate: extractCertificateFromBuffer(issuingCaCertificate as unknown as Buffer),
      certificateChain: certificateChainString,
      serialNumber,
      certificateId: certResult.certificateId,
      certificateRequestId: pendingRequest.id,
      projectId: profile.projectId,
      profileName: profile.slug,
      commonName: certResult.commonName || "",
      applicationId,
      applicationName
    };
  };

  const $orderCertificate = async ({
    profileId,
    certificateOrder,
    metadata,
    actor,
    actorId,
    actorAuthMethod,
    actorOrgId,
    applicationId: explicitApplicationId
  }: TOrderCertificateFromProfileDTO): Promise<TCertificateIssuanceResponse> => {
    const profile = await validateProfileAndPermissions({
      profileId,
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId,
      certificateProfileDAL,
      acmeAccountDAL,
      permissionService,
      requiredEnrollmentType: EnrollmentType.API,
      isInternal: actor === ActorType.EST_ACCOUNT || actor === ActorType.SCEP_ACCOUNT,
      applicationId: explicitApplicationId
    });
    const applicationId = await $resolveApplicationIdForProfile(
      profile,
      explicitApplicationId,
      { actor, actorId, actorAuthMethod, actorOrgId },
      EnrollmentType.API
    );
    const applicationName = await $resolveApplicationName(applicationId);

    let certificateRequest: TCertificateRequest;
    let extractedKeyAlgorithm: string | undefined;
    let extractedSignatureAlgorithm: string | undefined;

    if (certificateOrder.csr) {
      if (certificateOrder.customExtensions?.length) {
        throw new BadRequestError({ message: CUSTOM_EXTENSIONS_WITH_CSR_ERROR_MESSAGE });
      }

      const csrRequest = extractCertificateRequestFromCSR(certificateOrder.csr);
      certificateRequest = applyProfileDefaults(csrRequest, profile.defaults);
      const algorithms = extractAlgorithmsFromCSR(certificateOrder.csr);
      extractedKeyAlgorithm = algorithms.keyAlgorithm;
      extractedSignatureAlgorithm = algorithms.signatureAlgorithm;
      certificateRequest.validity = certificateOrder.validity;
      if (certificateOrder.notBefore && certificateOrder.notAfter) {
        certificateRequest.notBefore = certificateOrder.notBefore;
        certificateRequest.notAfter = certificateOrder.notAfter;
      }
    } else {
      const orderedFields = {
        commonName: certificateOrder.commonName,
        keyUsages: certificateOrder.keyUsages,
        extendedKeyUsages: certificateOrder.extendedKeyUsages,
        subjectAlternativeNames: certificateOrder.altNames,
        notBefore: certificateOrder.notBefore,
        notAfter: certificateOrder.notAfter,
        signatureAlgorithm: certificateOrder.signatureAlgorithm,
        keyAlgorithm: certificateOrder.keyAlgorithm,
        basicConstraints: certificateOrder.basicConstraints,
        organization: certificateOrder.organization,
        organizationalUnit: certificateOrder.organizationalUnit,
        country: certificateOrder.country,
        state: certificateOrder.state,
        locality: certificateOrder.locality,
        customExtensions: certificateOrder.customExtensions
      };
      const rawRequest = {
        validity: certificateOrder.validity,
        ...Object.fromEntries(Object.entries(orderedFields).filter(([, value]) => value !== undefined))
      } as TCertificateRequest;
      certificateRequest = applyProfileDefaults(rawRequest, profile.defaults);
    }

    const preflightCa = profile.caId ? await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId) : undefined;
    if (preflightCa) {
      assertCaInProfileProject(preflightCa, profile);
    }

    // Check if this is a CA certificate request (either explicit basicConstraints or keyCertSign in key usages)
    // Per RFC 5280, keyCertSign implies CA certificate. Some clients (like cert-manager) only send keyCertSign without basicConstraints.
    const orderCsrHasKeyCertSign = certificateRequest.keyUsages?.includes(CertKeyUsageType.KEY_CERT_SIGN) ?? false;
    const orderWantsCaCertificate = certificateRequest.basicConstraints?.isCA || orderCsrHasKeyCertSign;
    if (orderWantsCaCertificate) {
      if (preflightCa?.externalCa?.type !== CaType.AWS_PCA) {
        throw new BadRequestError({
          message: "CA certificate issuance is not supported for this external certificate authority."
        });
      }

      certificateRequest.basicConstraints = {
        isCA: true,
        pathLength: certificateRequest.basicConstraints?.pathLength
      };
    }

    const orderEffectiveTtl = resolveEffectiveTtl({
      requestTtl: certificateOrder.validity?.ttl,
      profileDefaultTtlDays: profile.defaults?.ttlDays,
      flowDefaultTtl: ""
    });
    const mappedCertificateRequest = mapEnumsForValidation(certificateRequest);

    if (certificateOrder.csr) {
      mappedCertificateRequest.keyAlgorithm = extractedKeyAlgorithm;
      mappedCertificateRequest.signatureAlgorithm = extractedSignatureAlgorithm;
    }

    // Not recorded here: the issuance queue creates the certificate later, once the external CA
    // responds, so the cached count picks it up on its next refresh.
    await validateCertificateRequestLicense({
      request: mappedCertificateRequest,
      altNames: (mappedCertificateRequest.subjectAlternativeNames ?? []).map((san) => san.value).join(","),
      projectId: profile.projectId,
      projectDAL,
      licenseService,
      quotaDeps: $quotaDeps
    });

    const validationResult = await certificatePolicyService.validateCertificateRequest(
      profile.certificatePolicyId,
      mappedCertificateRequest,
      { profileCustomExtensions: profile.defaults?.customExtensions }
    );

    if (!validationResult.isValid) {
      throw new BadRequestError({
        message: `Certificate order validation failed: ${validationResult.errors.join(", ")}`
      });
    }

    // ACM pre-flight validation runs before the approval branch so bad inputs (e.g., a TTL that
    // isn't ACM's fixed 198 days) are rejected at submit time rather than after the approver has
    // already approved a request that's guaranteed to fail downstream.
    const orderCustomExtensions = validationResult.resolvedCustomExtensions;

    if (orderCustomExtensions?.length && preflightCa) {
      const preflightCaType = (preflightCa.externalCa?.type ?? CaType.INTERNAL) as CaType;
      assertCaSupportsCustomExtensions(preflightCaType, orderCustomExtensions.length);

      if (preflightCaType === CaType.AWS_PCA) {
        assertAwsPcaCustomExtensionLimit(orderCustomExtensions.length);
      }
    }

    if (preflightCa?.externalCa?.type === CaType.AWS_ACM_PUBLIC_CA) {
      validateAcmIssuanceInputs({
        csr: certificateOrder.csr,
        keyAlgorithm: certificateOrder.keyAlgorithm,
        altNames: certificateOrder.altNames,
        ttl: orderEffectiveTtl,
        notBefore: certificateOrder.notBefore,
        notAfter: certificateOrder.notAfter,
        organization: certificateRequest.organization,
        organizationalUnit: certificateRequest.organizationalUnit,
        country: certificateRequest.country,
        state: certificateRequest.state,
        locality: certificateRequest.locality
      });
    }

    if (preflightCa?.externalCa?.type === CaType.AWS_PCA) {
      validateAwsPcaCaIssuanceInputs({ basicConstraints: certificateRequest.basicConstraints });
    }

    const orderMatchedApprovalPolicy = (await approvalPolicyService.matchPolicy(
      ApprovalPolicyType.CertRequest,
      profile.projectId,
      { profileName: profile.slug, applicationId }
    )) as TCertRequestPolicy | null;

    if (orderMatchedApprovalPolicy && !shouldBypassApproval(actor, orderMatchedApprovalPolicy)) {
      const approvalPolicy = orderMatchedApprovalPolicy;

      const policySteps = await approvalPolicyDAL.findStepsByPolicyId(approvalPolicy.id);
      const { requesterName, requesterEmail } = await resolveRequesterInfo(actor, actorId, EnrollmentType.API);

      const { certRequestId, approvalRequestId } = await certificateRequestDAL.transaction(async (tx) => {
        // Explicitly set createdAt to ensure millisecond precision matches when used in composite FK references
        const certRequestCreatedAt = new Date();
        const certRequest = await certificateRequestDAL.create(
          {
            projectId: profile.projectId,
            profileId: profile.id,
            caId: profile.caId ?? null,
            applicationId: applicationId ?? null,
            csr: certificateOrder.csr || null,
            // Subject and algorithms come from `certificateRequest`, not the raw order: with a BYO CSR
            // the request body carries none of them, and issuance after approval reads this row.
            commonName: certificateRequest.commonName || null,
            altNames: certificateRequest.subjectAlternativeNames
              ? JSON.stringify(certificateRequest.subjectAlternativeNames)
              : null,
            keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
            extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
            notBefore: certificateOrder.notBefore || null,
            notAfter: certificateOrder.notAfter || null,
            keyAlgorithm: extractedKeyAlgorithm || certificateRequest.keyAlgorithm || null,
            signatureAlgorithm: extractedSignatureAlgorithm || certificateRequest.signatureAlgorithm || null,
            ttl: orderEffectiveTtl || null,
            metadata: certificateOrder.template ? JSON.stringify({ template: certificateOrder.template }) : null,
            organization: certificateRequest.organization || null,
            organizationalUnit: certificateRequest.organizationalUnit || null,
            country: certificateRequest.country || null,
            state: certificateRequest.state || null,
            locality: certificateRequest.locality || null,
            domainComponents: certificateRequest.domainComponents
              ? certificateRequest.domainComponents.join(",")
              : null,
            enrollmentType: EnrollmentType.API,
            status: CertificateRequestStatus.PENDING_APPROVAL,
            // Issuance after approval reads this row, not the approval payload.
            basicConstraints: certificateRequest.basicConstraints
              ? JSON.stringify(certificateRequest.basicConstraints)
              : null,
            customExtensions: orderCustomExtensions ? JSON.stringify(orderCustomExtensions) : null,
            createdAt: certRequestCreatedAt
          } as Parameters<typeof certificateRequestDAL.create>[0] & { createdAt: Date },
          tx
        );

        if (metadata && metadata.length > 0) {
          await insertMetadataForCertificateRequest(resourceMetadataDAL, {
            metadata,
            certificateRequestId: certRequest.id,
            certificateRequestCreatedAt: certRequest.createdAt,
            orgId: actorOrgId,
            tx
          });
        }

        const requestData: TCertRequestRequestData = {
          profileId,
          profileName: profile.slug,
          // What the approver reviews has to be what gets issued, so this reads the same resolved
          // request the row above persists rather than the raw order.
          certificateRequest: {
            commonName: certificateRequest.commonName,
            organization: certificateRequest.organization,
            organizationalUnit: certificateRequest.organizationalUnit,
            country: certificateRequest.country,
            state: certificateRequest.state,
            locality: certificateRequest.locality,
            domainComponents: certificateRequest.domainComponents,
            keyUsages: certificateRequest.keyUsages as string[] | undefined,
            extendedKeyUsages: certificateRequest.extendedKeyUsages as string[] | undefined,
            altNames: certificateRequest.subjectAlternativeNames,
            validity: certificateOrder.validity,
            notBefore: certificateOrder.notBefore?.toISOString(),
            notAfter: certificateOrder.notAfter?.toISOString(),
            signatureAlgorithm: extractedSignatureAlgorithm || certificateRequest.signatureAlgorithm,
            keyAlgorithm: extractedKeyAlgorithm || certificateRequest.keyAlgorithm,
            basicConstraints: certificateRequest.basicConstraints
          },
          certificateRequestId: certRequest.id
        };

        const expiresAt = approvalPolicy.maxRequestTtl ? new Date(Date.now() + ms(approvalPolicy.maxRequestTtl)) : null;

        const { request: approvalRequest } = await approvalPolicyService.createRequestFromPolicy({
          projectId: profile.projectId,
          organizationId: actorOrgId,
          policy: { ...approvalPolicy, steps: policySteps },
          requestData,
          justification: `Certificate order request for ${certificateOrder.commonName || profile.slug}`,
          expiresAt,
          requesterUserId: actor === ActorType.USER ? actorId : null,
          machineIdentityId: actor === ActorType.IDENTITY ? actorId : null,
          requesterName,
          requesterEmail,
          tx
        });

        await certificateRequestDAL.updateById(
          certRequest.id,
          {
            approvalRequestId: approvalRequest.id
          },
          tx
        );

        return { certRequestId: certRequest.id, approvalRequestId: approvalRequest.id };
      });

      logger.info(
        {
          certificateRequestId: certRequestId,
          approvalRequestId,
          profileId,
          profileName: profile.slug
        },
        "Certificate order request requires approval"
      );

      return {
        status: CertificateRequestStatus.PENDING_APPROVAL,
        certificateRequestId: certRequestId,
        message: "Certificate order request requires approval",
        projectId: profile.projectId,
        profileName: profile.slug,
        commonName: certificateOrder.commonName,
        applicationId,
        applicationName
      };
    }

    if (!profile.caId) {
      throw new BadRequestError({
        message: "Self-signed certificates are not supported for certificate ordering"
      });
    }

    const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId);
    if (!ca) {
      throw new NotFoundError({ message: "Certificate Authority not found" });
    }

    assertCaInProfileProject(ca, profile);

    const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL;

    if (caType === CaType.INTERNAL) {
      throw new BadRequestError({
        message: "Certificate ordering is not supported for the specified CA type"
      });
    }

    if (caUsesExternalIssuanceQueue(caType)) {
      // Pre-flight validation for ACM — reject bad inputs synchronously so the user
      // gets a 400 on submit rather than a FAILED request row after the job runs.
      if (caType === CaType.AWS_ACM_PUBLIC_CA) {
        validateAcmIssuanceInputs({
          csr: certificateOrder.csr,
          keyAlgorithm: certificateOrder.keyAlgorithm,
          altNames: certificateOrder.altNames,
          ttl: orderEffectiveTtl,
          notBefore: certificateOrder.notBefore,
          notAfter: certificateOrder.notAfter,
          organization: certificateRequest.organization,
          organizationalUnit: certificateRequest.organizationalUnit,
          country: certificateRequest.country,
          state: certificateRequest.state,
          locality: certificateRequest.locality
        });
      }

      if (caType === CaType.GODADDY) {
        // When a CSR is supplied, validate what it actually contains (key algorithm + SANs + CN)
        // rather than the declared request fields, so a BYO CSR can't smuggle a non-RSA key or
        // extra SANs past the guard and on to GoDaddy.
        const csrDerived = certificateOrder.csr ? extractCertificateRequestFromCSR(certificateOrder.csr) : undefined;
        validateGoDaddyIssuanceInputs({
          keyAlgorithm: certificateOrder.csr
            ? extractAlgorithmsFromCSR(certificateOrder.csr).keyAlgorithm
            : certificateOrder.keyAlgorithm,
          altNames: csrDerived?.subjectAlternativeNames ?? certificateOrder.altNames,
          commonName: csrDerived?.commonName ?? certificateOrder.commonName
        });
      }

      const orderId = randomUUID();

      const certRequest = await certificateRequestService.createCertificateRequest({
        internal: true,
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId,
        projectId: profile.projectId,
        caId: ca.id,
        profileId: profile.id,
        applicationId,
        csr: certificateOrder.csr,
        commonName: certificateRequest.commonName || "",
        keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
        extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
        keyAlgorithm: certificateRequest.keyAlgorithm || "",
        signatureAlgorithm: certificateRequest.signatureAlgorithm || "",
        altNames: certificateRequest.subjectAlternativeNames,
        notBefore: certificateRequest.notBefore,
        notAfter: certificateRequest.notAfter,
        status: CertificateRequestStatus.PENDING,
        customExtensions: orderCustomExtensions,
        ttl: orderEffectiveTtl,
        enrollmentType: EnrollmentType.API,
        organization: certificateRequest.organization,
        organizationalUnit: certificateRequest.organizationalUnit,
        country: certificateRequest.country,
        state: certificateRequest.state,
        locality: certificateRequest.locality,
        domainComponents: certificateRequest.domainComponents,
        basicConstraints: certificateRequest.basicConstraints
      });

      if (metadata && metadata.length > 0) {
        await insertMetadataForCertificateRequest(resourceMetadataDAL, {
          metadata,
          certificateRequestId: certRequest.id,
          certificateRequestCreatedAt: certRequest.createdAt,
          orgId: actorOrgId
        });
      }

      await certificateIssuanceQueue.queueCertificateIssuance({
        certificateId: orderId,
        profileId: profile.id,
        caId: profile.caId || "",
        caType,
        ttl: orderEffectiveTtl || "1y",
        signatureAlgorithm: certificateRequest.signatureAlgorithm || "",
        keyAlgorithm: certificateRequest.keyAlgorithm || "",
        commonName: certificateRequest.commonName || "",
        altNames:
          certificateRequest.subjectAlternativeNames?.map((san) => ({ type: san.type, value: san.value })) || [],
        keyUsages: convertKeyUsageArrayToLegacy(certificateRequest.keyUsages) || [],
        extendedKeyUsages: convertExtendedKeyUsageArrayToLegacy(certificateRequest.extendedKeyUsages) || [],
        certificateRequestId: certRequest.id,
        csr: certificateOrder.csr,
        organization: certificateRequest.organization,
        organizationalUnit: certificateRequest.organizationalUnit,
        country: certificateRequest.country,
        state: certificateRequest.state,
        locality: certificateRequest.locality,
        basicConstraints: certificateRequest.basicConstraints,
        customExtensions: orderCustomExtensions,
        ...(applicationId && { applicationId })
      });

      return {
        status: CertificateRequestStatus.PENDING,
        certificateRequestId: certRequest.id,
        projectId: certRequest.projectId,
        profileName: profile.slug,
        applicationId,
        applicationName
      };
    }

    throw new BadRequestError({
      message: "Certificate ordering is not supported for the specified CA type"
    });
  };

  const updateCertificate = async ({
    certificateId,
    metadata,
    actor,
    actorId,
    actorAuthMethod,
    actorOrgId
  }: TUpdateCertificateDTO) => {
    const certificate = await certificateDAL.findById(certificateId);
    if (!certificate) {
      throw new NotFoundError({ message: "Certificate not found" });
    }

    const { projectPermission } = await assertCanEditCertificate({
      certificate,
      actor,
      actorId,
      actorAuthMethod,
      actorOrgId,
      permissionService,
      resourceMetadataDAL
    });

    assertCertificateNotDeleted(certificate);

    if (metadata && projectPermission) {
      assertCanEditCertificateResult({
        projectPermission,
        commonName: certificate.commonName,
        altNames: certificate.altNames?.split(",").map((s) => s.trim()),
        serialNumber: certificate.serialNumber,
        metadata
      });
    }

    let updatedMetadata: Array<{ key: string; value: string }> = [];

    if (metadata) {
      await certificateDAL.transaction(async (tx) => {
        const lockedCertificate = await certificateDAL.findByIdForShare(certificateId, tx);
        if (!lockedCertificate) {
          throw new NotFoundError({ message: "Certificate not found" });
        }
        assertCertificateNotDeleted(lockedCertificate);
        await resourceMetadataDAL.delete({ certificateId }, tx);
        await insertMetadataForCertificate(resourceMetadataDAL, {
          metadata,
          certificateId,
          orgId: actorOrgId,
          tx
        });
      });
      updatedMetadata = metadata;

      if (certificate.applicationId) {
        await queueCertificateFilterReconcile(certificateId, certificate.applicationId, pkiSyncQueue);
      }
    }

    return {
      metadata: updatedMetadata,
      projectId: certificate.projectId,
      commonName: certificate.commonName,
      applicationId: certificate.applicationId ?? null,
      applicationName: certificate.applicationId
        ? ((await pkiApplicationDAL.findById(certificate.applicationId))?.name ?? null)
        : null
    };
  };

  const renewalService = certificateRenewalServiceFactory({
    certificateDAL,
    certificateBodyDAL,
    certificateSecretDAL,
    certificateAuthorityDAL,
    certificateProfileDAL,
    certificatePolicyService,
    internalCaService,
    permissionService,
    certificateSyncDAL,
    pkiSyncDAL,
    pkiSyncQueue,
    kmsService,
    projectDAL,
    certificateIssuanceQueue,
    certificateRequestService,
    certificateRequestDAL,
    resourceMetadataDAL,
    pkiAlertV2Queue,
    certificateAlertEventEmitter,
    pkiApplicationProfileDAL,
    pkiApplicationDAL,
    apiEnrollmentConfigDAL,
    licenseService,
    quotaDeps: $quotaDeps,
    recordQuotaUsage: $recordQuotaUsage,
    resolveApplicationIdForProfile: $resolveApplicationIdForProfile,
    reportCertificateIssued: $reportCertificateIssued
  });

  const issueCertificateFromProfile = async (dto: TIssueCertificateFromProfileDTO) => {
    try {
      return await $issueCertificateFromProfile(dto);
    } catch (error) {
      await $recordIssuanceFailure({
        auditLogInfo: dto.auditLogInfo,
        actorOrgId: dto.actorOrgId,
        profileId: dto.profileId,
        error,
        metadata: {
          operation: CertificateIssuanceOperation.ISSUE,
          enrollmentType: EnrollmentType.API,
          commonName: dto.certificateRequest.commonName,
          applicationId: dto.applicationId
        }
      });
      throw error;
    }
  };

  const signCertificateFromProfile = async (dto: TSignCertificateFromProfileDTO) => {
    try {
      return await $signCertificateFromProfile(dto);
    } catch (error) {
      await $recordIssuanceFailure({
        auditLogInfo: dto.auditLogInfo,
        actorOrgId: dto.actorOrgId,
        profileId: dto.profileId,
        error,
        metadata: {
          operation: dto.issuanceOperation ?? CertificateIssuanceOperation.SIGN,
          enrollmentType: dto.enrollmentType,
          originalCertificateId: dto.originalCertificateId,
          commonName: $commonNameFromCsr(dto.csr),
          applicationId: dto.applicationId
        }
      });
      throw error;
    }
  };

  const orderCertificate = async (dto: TOrderCertificateFromProfileDTO) => {
    try {
      return await $orderCertificate(dto);
    } catch (error) {
      await $recordIssuanceFailure({
        auditLogInfo: dto.auditLogInfo,
        actorOrgId: dto.actorOrgId,
        profileId: dto.profileId,
        error,
        metadata: {
          operation: CertificateIssuanceOperation.ORDER,
          enrollmentType: EnrollmentType.API,
          commonName: dto.certificateOrder.commonName || $commonNameFromCsr(dto.certificateOrder.csr),
          applicationId: dto.applicationId
        }
      });
      throw error;
    }
  };

  const renewCertificate = async (dto: Parameters<typeof renewalService.renewCertificate>[0]) => {
    try {
      return await renewalService.renewCertificate(dto);
    } catch (error) {
      const certificate = dto.auditLogInfo
        ? await certificateDAL.findById(dto.certificateId).catch(() => undefined)
        : undefined;
      if (certificate) {
        await $recordIssuanceFailure({
          auditLogInfo: dto.auditLogInfo,
          actorOrgId: dto.actorOrgId,
          projectId: certificate.projectId,
          profileId: certificate.profileId,
          error,
          metadata: {
            operation: CertificateIssuanceOperation.RENEW,
            enrollmentType: EnrollmentType.API,
            originalCertificateId: certificate.id,
            commonName: certificate.commonName,
            caId: certificate.caId,
            applicationId: certificate.applicationId
          }
        });
      }
      throw error;
    }
  };

  return {
    ...renewalService,
    renewCertificate,
    issueCertificateFromProfile,
    signCertificateFromProfile,
    orderCertificate,
    updateCertificate
  };
};