Skip to content

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

138 KB
Raw Blame
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { readFileSync } from "node:fs";
import { join } from "node:path";

import { createMongoAbility, ForbiddenError } from "@casl/ability";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { InstanceType } from "@app/ee/services/license/license-types";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
  ProjectPermissionCertificateActions,
  ProjectPermissionCertificateProfileActions,
  ProjectPermissionSet,
  ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { TPkiAcmeAccountDALFactory } from "@app/ee/services/pki-acme/pki-acme-account-dal";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import { CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
import {
  CertExtendedKeyUsageType,
  CertificateIssuanceOperation,
  CertIncludeType,
  CertKeyUsageType,
  CertSubjectAlternativeNameType,
  CertSubjectAttributeType
} from "@app/services/certificate-common/certificate-constants";
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 { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal";
import { CertStatus } from "@app/services/certificate/certificate-types";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";

import { ActorType, AuthMethod } from "../auth/auth-type";
import {
  extractAlgorithmsFromCSR,
  extractCertificateRequestFromCSR
} from "../certificate-common/certificate-csr-utils";
import { buildCertificateQuotaKey } from "../certificate-common/certificate-quota-key";
import { certificateV3ServiceFactory, TCertificateV3ServiceFactory } from "./certificate-v3-service";
import { CertificateRenewalKeySource } from "./certificate-v3-types";

vi.mock("../certificate-common/certificate-csr-utils", () => ({
  extractCertificateRequestFromCSR: vi.fn(),
  extractAlgorithmsFromCSR: vi.fn(),
  buildSubjectOverrideForCsr: vi.fn()
}));

vi.mock("@peculiar/x509", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@peculiar/x509")>();
  return {
    ...actual,
    Pkcs10CertificateRequest: vi.fn().mockImplementation(() => ({
      subject: "CN=test.example.com"
    }))
  };
});

vi.mock("../certificate-authority/certificate-authority-fns", async (importOriginal) => {
  const actual = await importOriginal<typeof import("../certificate-authority/certificate-authority-fns")>();
  return {
    ...actual,
    assertCaInProfileProject: vi.fn()
  };
});

vi.mock("@app/lib/logger", () => ({
  logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
}));

describe("CertificateV3Service", () => {
  let service: TCertificateV3ServiceFactory;

  const mockTelemetryService = {
    sendPostHogEvents: vi.fn().mockResolvedValue(undefined)
  };

  const mockAuditLogService = {
    createCollapsedAuditLog: vi.fn().mockResolvedValue(undefined)
  };

  const mockCertificateDAL: Pick<
    TCertificateDALFactory,
    | "findOne"
    | "findById"
    | "findByIdForUpdate"
    | "findByIdForShare"
    | "updateById"
    | "transaction"
    | "create"
    | "find"
    | "getRequestEnrollmentTypeByCertId"
    | "getOriginatingRequestByCertId"
    | "findCertificatesMatchingSyncFilters"
    | "findActiveCertificatesByIds"
  > = {
    findOne: vi.fn(),
    findById: vi.fn(),
    findByIdForUpdate: vi.fn(),
    findByIdForShare: vi.fn(),
    findCertificatesMatchingSyncFilters: vi.fn().mockResolvedValue([]),
    findActiveCertificatesByIds: vi.fn().mockResolvedValue([]),
    updateById: vi.fn(),
    getRequestEnrollmentTypeByCertId: vi.fn().mockResolvedValue(null),
    getOriginatingRequestByCertId: vi.fn().mockResolvedValue({ enrollmentType: null, csr: null }),
    create: vi.fn().mockResolvedValue({
      id: "new-cert-id",
      serialNumber: "123456789",
      friendlyName: "Test Certificate",
      commonName: "test.example.com",
      status: "ACTIVE",
      source: "issued",
      keySource: "infisical",
      quotaKey: "a".repeat(64),
      orderId: "00000000-0000-0000-0000-000000000000"
    }),
    transaction: vi.fn().mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
      const mockTx = {};
      return callback(mockTx);
    }),
    find: vi.fn().mockResolvedValue([])
  };

  const mockCertificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne" | "create"> = {
    findOne: vi.fn(),
    create: vi.fn()
  };

  const mockCertificateAuthorityDAL: Pick<
    TCertificateAuthorityDALFactory,
    "findByIdWithAssociatedCa" | "create" | "updateById" | "findById" | "transaction" | "findWithAssociatedCa"
  > = {
    findByIdWithAssociatedCa: vi.fn(),
    create: vi.fn().mockResolvedValue({ id: "ca-123" }),
    updateById: vi.fn().mockResolvedValue({ id: "ca-123" }),
    findById: vi.fn().mockResolvedValue({ id: "ca-123" }),
    findWithAssociatedCa: vi.fn().mockResolvedValue([]),
    transaction: vi.fn().mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
      const mockTx = {};
      return callback(mockTx);
    })
  };

  const mockCertificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs" | "findById"> = {
    findByIdWithConfigs: vi.fn(),
    findById: vi.fn()
  };

  const mockCertificatePolicyService: Pick<
    TCertificatePolicyServiceFactory,
    "validateCertificateRequest" | "validateRequestAgainstPolicy" | "getPolicyById"
  > = {
    validateCertificateRequest: vi.fn(),
    validateRequestAgainstPolicy: vi.fn().mockReturnValue({ isValid: true, errors: [] }),
    getPolicyById: vi.fn()
  };

  const mockAcmeAccountDAL: Pick<TPkiAcmeAccountDALFactory, "findById"> = {
    findById: vi.fn()
  };

  const mockInternalCaService: Pick<TInternalCertificateAuthorityServiceFactory, "signCertFromCa" | "issueCertFromCa"> =
    {
      signCertFromCa: vi.fn(),
      issueCertFromCa: vi.fn()
    };

  const mockPermissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission"> = {
    getProjectPermission: vi.fn().mockResolvedValue({
      permission: {
        throwUnlessCan: vi.fn(),
        can: vi.fn().mockReturnValue(true),
        cannot: vi.fn().mockReturnValue(false),
        relevantRuleFor: vi.fn(),
        rules: []
      }
    }),
    getResourcePermission: vi.fn().mockResolvedValue({
      permission: {
        throwUnlessCan: vi.fn(),
        can: vi.fn().mockReturnValue(true),
        cannot: vi.fn().mockReturnValue(false),
        relevantRuleFor: vi.fn(),
        rules: []
      },
      memberships: [],
      hasRole: vi.fn().mockReturnValue(false),
      isImplicitAdmin: false
    })
  };

  const mockUsageCounterDAL = {
    resolveRootOrgId: vi.fn(async (id: string) => id),
    countActiveCertificateQuotaKeysByOrg: vi.fn(async () => ({ total: 0, wildcard: 0 })),
    isCertificateQuotaKeyActiveInOrg: vi.fn((orgId: string | undefined, quotaKey: string) =>
      Promise.resolve(Boolean(orgId && quotaKey && false))
    )
  };

  const mockKeyStore = {
    getItem: vi.fn(async () => null),
    setItemWithExpiry: vi.fn(async () => "OK" as const),
    deleteItem: vi.fn(async () => 1)
  };

  const mockLicenseService = {
    getPlan: vi.fn().mockResolvedValue({ pkiPqc: true }),
    getInstanceType: vi.fn(() => InstanceType.OnPrem)
  };

  const mockCertificateIssuanceQueue = {
    queueCertificateIssuance: vi.fn()
  };

  const mockCertificateRequestService = {
    createCertificateRequest: vi.fn()
  };

  const mockApprovalPolicyDAL = {
    findByProjectId: vi.fn(),
    findStepsByPolicyId: vi.fn()
  };

  const mockCertificateRequestDAL = {
    updateById: vi.fn(),
    findById: vi.fn(),
    create: vi.fn(),
    transaction: vi.fn(),
    transitionFromPending: vi.fn(),
    attachCertificate: vi.fn()
  };

  const mockApprovalPolicyService = {
    createRequestFromPolicy: vi.fn(),
    matchPolicy: vi.fn()
  };

  const mockActor = {
    actor: ActorType.USER,
    actorId: "user-123",
    actorAuthMethod: AuthMethod.EMAIL,
    actorOrgId: "org-123"
  };

  beforeEach(() => {
    // Reset all mocks before each test
    vi.resetAllMocks();
    // These three are shared across tests rather than rebuilt per test, so resetAllMocks strips their
    // implementations and they have to be re-established here.
    mockUsageCounterDAL.resolveRootOrgId.mockImplementation(async (id: string) => id);
    mockUsageCounterDAL.countActiveCertificateQuotaKeysByOrg.mockResolvedValue({ total: 0, wildcard: 0 });
    mockUsageCounterDAL.isCertificateQuotaKeyActiveInOrg.mockResolvedValue(false);
    mockKeyStore.getItem.mockResolvedValue(null);
    mockKeyStore.setItemWithExpiry.mockResolvedValue("OK" as const);
    mockKeyStore.deleteItem.mockResolvedValue(1);
    mockLicenseService.getPlan.mockResolvedValue({ pkiPqc: true });
    vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
      const mockTx = {};
      return callback(mockTx);
    });
    vi.mocked(mockCertificateDAL.findByIdForUpdate).mockImplementation((id: string) => mockCertificateDAL.findById(id));
    vi.mocked(mockCertificateDAL.getRequestEnrollmentTypeByCertId).mockResolvedValue(null);
    vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue({
      enrollmentType: null,
      csr: null,
      exists: true,
      commonName: null,
      organization: null,
      organizationalUnit: null,
      country: null,
      state: null,
      locality: null,
      domainComponents: null,
      altNames: null,
      keyUsages: null,
      extendedKeyUsages: null,
      customExtensions: null,
      keyAlgorithm: null,
      signatureAlgorithm: null
    });

    mockCertificateIssuanceQueue.queueCertificateIssuance.mockResolvedValue(undefined);
    mockCertificateRequestService.createCertificateRequest.mockResolvedValue({ id: "cert-req-123" });
    mockApprovalPolicyDAL.findByProjectId.mockResolvedValue([]);
    mockApprovalPolicyDAL.findStepsByPolicyId.mockResolvedValue([]);
    mockCertificateRequestDAL.updateById.mockResolvedValue({ id: "cert-req-123" });
    mockCertificateRequestDAL.findById.mockResolvedValue({ id: "cert-req-123" });
    mockCertificateRequestDAL.create.mockResolvedValue({ id: "cert-req-123", createdAt: new Date() });
    mockCertificateRequestDAL.transitionFromPending.mockResolvedValue({ id: "cert-req-123" });
    mockCertificateRequestDAL.attachCertificate.mockResolvedValue({ id: "cert-req-123" });
    mockApprovalPolicyService.matchPolicy.mockResolvedValue(null);
    mockApprovalPolicyService.createRequestFromPolicy.mockResolvedValue({
      request: { id: "approval-req-123", steps: [{ id: "step-1", stepNumber: 1, approvers: [] }] }
    });

    // Mock ForbiddenError.from static method
    vi.spyOn(ForbiddenError, "from").mockReturnValue({
      throwUnlessCan: vi.fn()
    } as any);

    // Ensure the permission service mock is properly set up
    (mockPermissionService.getProjectPermission as any).mockResolvedValue({
      permission: {
        throwUnlessCan: vi.fn(),
        can: vi.fn().mockReturnValue(true),
        cannot: vi.fn().mockReturnValue(false),
        relevantRuleFor: vi.fn(),
        rules: [],
        detectSubjectType: vi.fn()
      }
    });

    vi.mocked(extractCertificateRequestFromCSR).mockReturnValue({
      commonName: "test.example.com",
      keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE],
      extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH]
    });

    vi.mocked(extractAlgorithmsFromCSR).mockReturnValue({
      keyAlgorithm: "RSA_2048" as any,
      signatureAlgorithm: "RSA-SHA256" as any
    });

    service = certificateV3ServiceFactory({
      certificateAlertEventEmitter: { emit: vi.fn() },
      certificateDAL: mockCertificateDAL,
      certificateSecretDAL: mockCertificateSecretDAL,
      certificateAuthorityDAL: mockCertificateAuthorityDAL,
      certificateProfileDAL: mockCertificateProfileDAL,
      certificatePolicyService: mockCertificatePolicyService,
      acmeAccountDAL: mockAcmeAccountDAL,
      internalCaService: mockInternalCaService,
      caKeySourceService: {
        resolveCsrSignatureAlgorithm: vi.fn(
          async ({ csrSignatureAlgorithm }: { csrSignatureAlgorithm?: string }) => csrSignatureAlgorithm
        )
      },
      permissionService: mockPermissionService,
      certificateSyncDAL: {
        findPkiSyncIdsByCertificateId: vi.fn().mockResolvedValue([]),
        addCertificates: vi.fn().mockResolvedValue([]),
        findByPkiSyncAndCertificate: vi.fn().mockResolvedValue(null),
        updateSyncMetadata: vi.fn().mockResolvedValue(null),
        primaryNode: vi.fn()
      },
      pkiSyncDAL: {
        find: vi.fn().mockResolvedValue([])
      },
      pkiSyncQueue: {
        queuePkiSyncSyncCertificatesById: vi.fn().mockResolvedValue(undefined),
        queuePkiSyncLinkMatchingCertificates: vi.fn().mockResolvedValue(undefined)
      },
      certificateBodyDAL: {
        create: vi.fn().mockResolvedValue({ id: "body-123" })
      },
      kmsService: {
        generateKmsKey: vi.fn().mockResolvedValue("kms-key-123"),
        encryptWithKmsKey: vi.fn().mockResolvedValue(vi.fn().mockResolvedValue(Buffer.from("encrypted"))),
        decryptWithKmsKey: vi.fn().mockResolvedValue(vi.fn().mockResolvedValue(Buffer.from("decrypted"))),
        createCipherPairWithDataKey: vi.fn().mockResolvedValue({
          cipherTextBlob: Buffer.from("encrypted"),
          plainTextKey: Buffer.from("plainkey")
        })
      },
      projectDAL: {
        findOne: vi.fn().mockResolvedValue({ id: "project-123" }),
        findById: vi.fn().mockResolvedValue({ id: "project-123", orgId: "org-123" }),
        updateById: vi.fn().mockResolvedValue({ id: "project-123" }),
        transaction: vi.fn().mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
          const mockTx = {};
          return callback(mockTx);
        })
      } as any,
      certificateIssuanceQueue: mockCertificateIssuanceQueue,
      certificateRequestService: mockCertificateRequestService,
      approvalPolicyDAL: mockApprovalPolicyDAL,
      certificateRequestDAL: mockCertificateRequestDAL,
      userDAL: {
        findById: vi.fn().mockResolvedValue({ id: "user-123" })
      },
      identityDAL: {
        findById: vi.fn().mockResolvedValue({ id: "identity-123", name: "test-identity" })
      },
      approvalPolicyService: mockApprovalPolicyService,
      resourceMetadataDAL: {
        insertMany: vi.fn().mockResolvedValue([]),
        delete: vi.fn().mockResolvedValue([]),
        find: vi.fn().mockResolvedValue([])
      },
      pkiApplicationProfileDAL: {
        findAllByProfileId: vi.fn().mockResolvedValue([]),
        findOneByApplicationAndProfile: vi.fn().mockResolvedValue(undefined)
      } as never,
      pkiApplicationDAL: {
        findById: vi.fn().mockResolvedValue(undefined)
      } as never,
      apiEnrollmentConfigDAL: {
        findById: vi.fn().mockResolvedValue(undefined)
      },
      usageCounterDAL: mockUsageCounterDAL,
      keyStore: mockKeyStore,
      licenseService: mockLicenseService,
      telemetryService: mockTelemetryService,
      auditLogService: mockAuditLogService
    });
  });

  afterEach(() => {
    vi.clearAllMocks();
    vi.restoreAllMocks(); // Ensure static method mocks are properly restored
  });

  describe("issueCertificateFromProfile", () => {
    const mockCertificateRequest = {
      commonName: "test.example.com",
      keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE],
      extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH],
      validity: { ttl: "30d" },
      signatureAlgorithm: "RSA-SHA256",
      keyAlgorithm: "RSA_2048"
    };

    it("should issue certificate successfully for API enrollment profile", async () => {
      const profileId = "profile-123";
      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "test-profile",
        description: "Test profile",
        apiConfigId: "api-config-legacy"
      };

      const mockCA = {
        id: "ca-123",
        projectId: "project-123",
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-123",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "Test CA",
          dn: "CN=Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "RSA_2048",
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-123",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        },
        name: "Test CA",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true
      };

      const mockPolicy = {
        id: "policy-123",
        name: "Test Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        description: "Test policy",
        signatureAlgorithm: { defaultAlgorithm: "RSA-SHA256" },
        keyAlgorithm: { defaultKeyType: "RSA_2048" },
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ]
      };

      const mockCertificateResult = {
        certificate: "cert",
        certificateChain: "chain",
        issuingCaCertificate: "issuing-ca",
        privateKey: "key",
        serialNumber: "123456",
        certificateId: "cert-1",
        commonName: "test.example.com",
        ca: {
          id: "ca-123",
          projectId: "project-123",
          name: "Test CA",
          status: "ACTIVE",
          createdAt: new Date(),
          updatedAt: new Date(),
          enableDirectIssuance: true,
          externalCa: undefined,
          internalCa: {
            id: "internal-ca-123",
            parentCaId: null,
            type: "ROOT",
            friendlyName: "Test CA",
            organization: "Test Org",
            ou: "Test OU",
            country: "US",
            province: "CA",
            locality: "SF",
            commonName: "Test CA",
            dn: "CN=Test CA",
            serialNumber: "123",
            maxPathLength: null,
            keyAlgorithm: "RSA_2048",
            notBefore: null,
            notAfter: null,
            activeCaCertId: "cert-123",
            caId: "ca-123",
            crlDistributionPointUrls: [],
            disableManagedCrlDistributionPointUrl: false,
            isOcspEnabled: false,
            ocspGeneration: 0
          }
        }
      };

      const mockCertRecord = {
        id: "cert-123",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        commonName: "test.example.com",
        friendlyName: "Test Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        revokedAt: null,
        revokedBy: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue(mockCertificateResult as any);
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(mockCertRecord);
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCertRecord);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord);

      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        return callback(undefined as any);
      });

      const result = await service.issueCertificateFromProfile({
        profileId,
        certificateRequest: mockCertificateRequest,
        ...mockActor
      });

      expect(result).toHaveProperty("certificate");
      expect(result).toHaveProperty("issuingCaCertificate");
      expect(result).toHaveProperty("certificateChain");
      expect(result).toHaveProperty("privateKey");
      expect(result).toHaveProperty("serialNumber", "123456");
      expect(result).toHaveProperty("certificateId", "cert-123");

      expect(mockTelemetryService.sendPostHogEvents).toHaveBeenCalledWith(
        expect.objectContaining({
          event: PostHogEventTypes.IssueCert,
          properties: expect.objectContaining({
            profileId,
            projectId: "project-123",
            enrollmentType: EnrollmentType.API,
            operation: CertificateIssuanceOperation.ISSUE
          })
        })
      );
    });

    describe("read-private-key permission scoping", () => {
      const profileId = "profile-123";

      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "test-profile",
        description: "Test profile",
        apiConfigId: "api-config-legacy"
      };

      const mockCA = {
        id: "ca-123",
        projectId: "project-123",
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-123",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "Test CA",
          dn: "CN=Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "RSA_2048",
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-123",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        },
        name: "Test CA",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true
      };

      const mockPolicy = {
        id: "policy-123",
        name: "Test Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        description: "Test policy",
        signatureAlgorithm: { defaultAlgorithm: "RSA-SHA256" },
        keyAlgorithm: { defaultKeyType: "RSA_2048" },
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ]
      };

      const mockCertificateResult = {
        certificate: "cert",
        certificateChain: "chain",
        issuingCaCertificate: "issuing-ca",
        privateKey: "key",
        serialNumber: "123456",
        certificateId: "cert-1",
        commonName: "test.example.com"
      };

      const mockCertRecord = {
        id: "cert-123",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        commonName: "test.example.com",
        friendlyName: "Test Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        revokedAt: null,
        revokedBy: null,
        source: "issued",
        keySource: "infisical"
      };

      // Return a real ability so the read-private-key check is evaluated against the certificate subject
      // rather than a mocked boolean.
      const grantPermission = (rules: any) => {
        (mockPermissionService.getProjectPermission as any).mockResolvedValue({
          permission: createMongoAbility<ProjectPermissionSet>(rules)
        });
      };

      beforeEach(() => {
        vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
        vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
          isValid: true,
          errors: [],
          warnings: []
        });
        vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA as any);
        vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy as any);
        vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue(mockCertificateResult as any);
        vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(mockCertRecord as any);
        vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCertRecord as any);
        vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord as any);
        vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) =>
          callback(undefined as any)
        );
      });

      it("returns the private key when read-private-key is granted unconditionally", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          { action: ProjectPermissionCertificateActions.ReadPrivateKey, subject: ProjectPermissionSub.Certificates }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeDefined();
      });

      it("omits the private key when read-private-key is granted only for a non-matching certificate subject", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          {
            action: ProjectPermissionCertificateActions.ReadPrivateKey,
            subject: ProjectPermissionSub.Certificates,
            conditions: { commonName: "not-the-issued-name.invalid" }
          }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeUndefined();
      });

      it("returns the private key when the read-private-key condition matches the issued certificate subject", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          {
            action: ProjectPermissionCertificateActions.ReadPrivateKey,
            subject: ProjectPermissionSub.Certificates,
            conditions: { commonName: "test.example.com" }
          }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeDefined();
      });

      it("returns the private key when a read-private-key condition on a non-common-name field matches", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          {
            action: ProjectPermissionCertificateActions.ReadPrivateKey,
            subject: ProjectPermissionSub.Certificates,
            conditions: { status: "ACTIVE" }
          }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeDefined();
      });

      it("omits the private key when a read-private-key condition on a non-common-name field excludes the certificate", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          {
            action: ProjectPermissionCertificateActions.ReadPrivateKey,
            subject: ProjectPermissionSub.Certificates,
            conditions: { status: { $ne: "ACTIVE" } }
          }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeUndefined();
      });
    });

    // Exercises the self-signed issuance branch (real key generation), which passes a different
    // certificate record (certificateData) into the same permission subject as the CA branch.
    describe("read-private-key permission scoping (self-signed issuance)", () => {
      const profileId = "self-signed-profile-123";

      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.SELF_SIGNED,
        caId: null,
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "self-signed-profile",
        description: "Self-signed profile",
        apiConfigId: "api-config-legacy"
      };

      const mockPolicy = {
        id: "policy-123",
        name: "Test Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        description: "Test policy",
        signatureAlgorithm: { defaultAlgorithm: "RSA-SHA256" },
        keyAlgorithm: { defaultKeyType: "RSA_2048" },
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ]
      };

      const mockCertRecord = {
        id: "cert-123",
        serialNumber: "123456",
        status: "ACTIVE",
        commonName: "test.example.com",
        friendlyName: "Test Cert",
        altNames: "",
        projectId: "project-123",
        caId: null,
        createdAt: new Date(),
        updatedAt: new Date(),
        notBefore: new Date(),
        notAfter: new Date(),
        source: "issued",
        keySource: "infisical"
      };

      const grantPermission = (rules: any) => {
        (mockPermissionService.getProjectPermission as any).mockResolvedValue({
          permission: createMongoAbility<ProjectPermissionSet>(rules)
        });
      };

      beforeEach(() => {
        vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
        vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
          isValid: true,
          errors: [],
          warnings: []
        });
        vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy as any);
        vi.mocked(mockCertificateDAL.create).mockResolvedValue(mockCertRecord as any);
        vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord as any);
        vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) =>
          callback(undefined as any)
        );
      });

      it("returns the private key when read-private-key is granted unconditionally", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          { action: ProjectPermissionCertificateActions.ReadPrivateKey, subject: ProjectPermissionSub.Certificates }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeDefined();
      });

      it("omits the private key when the read-private-key condition does not match the issued certificate", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          {
            action: ProjectPermissionCertificateActions.ReadPrivateKey,
            subject: ProjectPermissionSub.Certificates,
            conditions: { commonName: "not-the-issued-name.invalid" }
          }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeUndefined();
      });

      it("returns the private key when the read-private-key condition matches the issued certificate", async () => {
        grantPermission([
          { action: ProjectPermissionCertificateActions.Read, subject: ProjectPermissionSub.Certificates },
          {
            action: ProjectPermissionCertificateActions.ReadPrivateKey,
            subject: ProjectPermissionSub.Certificates,
            conditions: { commonName: "test.example.com" }
          }
        ]);

        const result = await service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        });

        expect(result.privateKey).toBeDefined();
      });
    });

    it("should correctly map camelCase key usages to snake_case before validation", async () => {
      const profileId = "profile-123";
      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "test-profile-camel",
        description: "Test camelCase profile",
        estConfigId: null,
        apiConfigId: "api-config-legacy"
      };

      const mockCA = {
        id: "ca-123",
        projectId: "project-123",
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-123",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "Test CA",
          dn: "CN=Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "RSA_2048",
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-123",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        },
        name: "Test CA",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true
      };

      const mockPolicy = {
        id: "policy-123",
        name: "Test Policy for CamelCase",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        description: "Test policy for camelCase validation",
        signatureAlgorithm: { defaultAlgorithm: "RSA-SHA256" },
        keyAlgorithm: { defaultKeyType: "RSA_2048" },
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ],
        subject: undefined,
        sans: undefined,
        keyUsages: undefined,
        extendedKeyUsages: undefined,
        algorithms: undefined,
        validity: undefined
      };

      const mockCertRecord = {
        id: "cert-123",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        commonName: "test.example.com",
        friendlyName: "Test Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      };

      const camelCaseRequest = {
        commonName: "test.example.com",
        keyUsages: [
          CertKeyUsageType.DIGITAL_SIGNATURE,
          CertKeyUsageType.NON_REPUDIATION,
          CertKeyUsageType.KEY_AGREEMENT,
          CertKeyUsageType.CRL_SIGN,
          CertKeyUsageType.DECIPHER_ONLY
        ],
        extendedKeyUsages: [
          CertExtendedKeyUsageType.CLIENT_AUTH,
          CertExtendedKeyUsageType.CODE_SIGNING,
          CertExtendedKeyUsageType.OCSP_SIGNING,
          CertExtendedKeyUsageType.SERVER_AUTH
        ],
        validity: { ttl: "10d" }
      };

      const mockCertificateResultWithCa = {
        certificate: "cert",
        certificateChain: "chain",
        issuingCaCertificate: "issuing-ca",
        privateKey: "key",
        serialNumber: "123456",
        certificateId: "cert-1",
        commonName: "test.example.com",
        ca: {
          id: "ca-123",
          projectId: "project-123",
          name: "Test CA",
          status: "ACTIVE",
          createdAt: new Date(),
          updatedAt: new Date(),
          enableDirectIssuance: true,
          externalCa: undefined,
          internalCa: {
            id: "internal-ca-123",
            parentCaId: null,
            type: "ROOT",
            friendlyName: "Test CA",
            organization: "Test Org",
            ou: "Test OU",
            country: "US",
            province: "CA",
            locality: "SF",
            commonName: "Test CA",
            dn: "CN=Test CA",
            serialNumber: "123",
            maxPathLength: null,
            keyAlgorithm: "RSA_2048",
            notBefore: null,
            notAfter: null,
            activeCaCertId: "cert-123",
            caId: "ca-123",
            crlDistributionPointUrls: [],
            disableManagedCrlDistributionPointUrl: false,
            isOcspEnabled: false,
            ocspGeneration: 0
          }
        }
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue(mockCertificateResultWithCa as any);
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(mockCertRecord);
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord);

      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        return callback(undefined as any);
      });

      await service.issueCertificateFromProfile({
        profileId,
        certificateRequest: camelCaseRequest,
        ...mockActor
      });

      // Verify that the policy validation service was called with mapped snake_case values
      expect(mockCertificatePolicyService.validateCertificateRequest).toHaveBeenCalledWith(
        "policy-123",
        expect.objectContaining({
          keyUsages: [
            CertKeyUsageType.DIGITAL_SIGNATURE,
            CertKeyUsageType.NON_REPUDIATION,
            CertKeyUsageType.KEY_AGREEMENT,
            CertKeyUsageType.CRL_SIGN,
            CertKeyUsageType.DECIPHER_ONLY
          ],
          extendedKeyUsages: [
            CertExtendedKeyUsageType.CLIENT_AUTH,
            CertExtendedKeyUsageType.CODE_SIGNING,
            CertExtendedKeyUsageType.OCSP_SIGNING,
            CertExtendedKeyUsageType.SERVER_AUTH
          ]
        }),
        expect.anything()
      );
    });

    it("should throw ForbiddenRequestError when profile is not configured for API enrollment", async () => {
      const profileId = "profile-123";
      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.EST, // Wrong enrollment type
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "test-profile-est",
        description: "Test EST profile",
        estConfigId: null,
        apiConfigId: "api-config-legacy"
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);

      await expect(
        service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        })
      ).rejects.toThrow(ForbiddenRequestError);

      await expect(
        service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        })
      ).rejects.toThrow("Profile is not configured for api enrollment");
    });

    it("should throw NotFoundError when profile doesn't exist", async () => {
      const profileId = "non-existent-profile";
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(undefined);

      await expect(
        service.issueCertificateFromProfile({
          profileId,
          certificateRequest: mockCertificateRequest,
          ...mockActor
        })
      ).rejects.toThrow(NotFoundError);
    });
  });

  describe("signCertificateFromProfile", () => {
    const mockCSR = "-----BEGIN CERTIFICATE REQUEST-----\nMIIC...";
    const mockValidity = { ttl: "30d" };

    it("should sign certificate successfully for API enrollment profile", async () => {
      const profileId = "profile-123";
      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "test-profile-sign",
        description: "Test signing profile",
        estConfigId: null,
        apiConfigId: "api-config-legacy"
      };

      const mockCA = {
        id: "ca-123",
        projectId: "project-123",
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-123",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "Test CA",
          dn: "CN=Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "RSA_2048",
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-123",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        },
        name: "Test CA",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true
      };

      const mockSignResult = {
        certificate: "signed-cert",
        certificateChain: "chain",
        issuingCaCertificate: "issuing-ca",
        serialNumber: "789012",
        // signCertFromCa always returns the id of the certificate it persisted, and the response is
        // built from that rather than from a follow-up read.
        certificateId: "cert-456",
        commonName: "test.example.com",
        ca: {
          id: "ca-123",
          projectId: "project-123",
          name: "Test CA",
          status: "ACTIVE",
          createdAt: new Date(),
          updatedAt: new Date(),
          enableDirectIssuance: true,
          externalCa: undefined,
          internalCa: {
            id: "internal-ca-123",
            parentCaId: null,
            type: "ROOT",
            friendlyName: "Test CA",
            organization: "Test Org",
            ou: "Test OU",
            country: "US",
            province: "CA",
            locality: "SF",
            commonName: "Test CA",
            dn: "CN=Test CA",
            serialNumber: "123",
            maxPathLength: null,
            keyAlgorithm: "RSA_2048",
            notBefore: null,
            notAfter: null,
            activeCaCertId: "cert-123",
            caId: "ca-123",
            crlDistributionPointUrls: [],
            disableManagedCrlDistributionPointUrl: false,
            isOcspEnabled: false,
            ocspGeneration: 0
          }
        }
      };

      const mockCertRecord = {
        id: "cert-456",
        serialNumber: "789012",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        commonName: "test.example.com",
        friendlyName: "Test Signing Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      };

      const mockPolicy = {
        id: "policy-123",
        name: "Test Signing Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-123",
        description: "Test policy for signing certificates",
        signatureAlgorithm: { defaultAlgorithm: "RSA-SHA256" },
        keyAlgorithm: { defaultKeyType: "RSA_2048" },
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ],
        subject: undefined,
        sans: undefined,
        keyUsages: undefined,
        extendedKeyUsages: undefined,
        algorithms: undefined,
        validity: undefined
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockInternalCaService.signCertFromCa).mockResolvedValue(mockSignResult as any);
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(mockCertRecord);
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCertRecord);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord);

      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        return callback(undefined as any);
      });

      const result = await service.signCertificateFromProfile({
        profileId,
        csr: mockCSR,
        validity: mockValidity,
        enrollmentType: EnrollmentType.API,
        ...mockActor
      });

      expect(result).toHaveProperty("certificate");
      expect(result).toHaveProperty("issuingCaCertificate");
      expect(result).toHaveProperty("certificateChain");
      expect(result).toHaveProperty("serialNumber", "789012");
      expect(result).toHaveProperty("certificateId", "cert-456");
      expect(result).not.toHaveProperty("privateKey");

      expect(mockTelemetryService.sendPostHogEvents).toHaveBeenCalledWith(
        expect.objectContaining({
          event: PostHogEventTypes.IssueCert,
          properties: expect.objectContaining({
            enrollmentType: EnrollmentType.API,
            operation: CertificateIssuanceOperation.SIGN
          })
        })
      );
    });

    it("should throw ForbiddenRequestError when profile is not configured for API enrollment", async () => {
      const profileId = "profile-123";
      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.EST, // Wrong enrollment type
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "test-profile-est-sign",
        description: "Test EST signing profile",
        estConfigId: null,
        apiConfigId: "api-config-legacy"
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);

      await expect(
        service.signCertificateFromProfile({
          profileId,
          csr: mockCSR,
          validity: mockValidity,
          enrollmentType: EnrollmentType.API,
          ...mockActor
        })
      ).rejects.toThrow(ForbiddenRequestError);

      await expect(
        service.signCertificateFromProfile({
          profileId,
          csr: mockCSR,
          validity: mockValidity,
          enrollmentType: EnrollmentType.API,
          ...mockActor
        })
      ).rejects.toThrow("Profile is not configured for api enrollment");
    });
  });

  // applyProfileDefaults keys off altNames, and a CSR-derived request carries its SANs in
  // subjectAlternativeNames instead. So the profile's default SANs land on a field this flow never
  // issues from, and keying the quota on them would charge names the certificate does not carry.
  describe("quota key SAN source on the CSR path", () => {
    it("keys on the CSR's SANs, not the profile default SANs applyProfileDefaults leaves behind", async () => {
      const profileWithDefaultSans = {
        id: "profile-123",
        projectId: "project-123",
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        status: "active",
        enrollmentType: EnrollmentType.API,
        apiConfigId: "api-config-123",
        defaults: { subjectAltNames: [{ type: "dns_name", value: "profile-default.example.com" }] }
      };

      mockLicenseService.getPlan.mockResolvedValue({ pkiPqc: true, maxCertificates: 5, maxWildcardCertificates: null });
      vi.mocked(mockPermissionService.getProjectPermission).mockResolvedValue({
        permission: {
          throwUnlessCan: vi.fn(),
          can: vi.fn().mockReturnValue(true),
          cannot: vi.fn().mockReturnValue(false)
        }
      } as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(profileWithDefaultSans as any);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue({
        id: "ca-123",
        projectId: "project-123",
        externalCa: undefined,
        internalCa: { id: "internal-ca-123", type: "ROOT", keyAlgorithm: "RSA_2048" }
      } as any);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue({
        id: "policy-123",
        projectId: "project-123"
      } as any);
      vi.mocked(extractCertificateRequestFromCSR).mockReturnValue({
        commonName: "app.example.com",
        subjectAlternativeNames: [{ type: "dns_name", value: "app.example.com" }]
      } as any);

      await service
        .signCertificateFromProfile({
          profileId: "profile-123",
          csr: "-----BEGIN CERTIFICATE REQUEST-----\nMIIC...",
          validity: { ttl: "30d" },
          enrollmentType: EnrollmentType.API,
          ...mockActor
        })
        .catch(() => undefined);

      const [, probedKey] = mockUsageCounterDAL.isCertificateQuotaKeyActiveInOrg.mock.calls[0];
      expect(probedKey).toBe(buildCertificateQuotaKey({ commonName: "app.example.com", altNames: "app.example.com" }));
      expect(probedKey).not.toBe(
        buildCertificateQuotaKey({
          commonName: "app.example.com",
          altNames: "profile-default.example.com,app.example.com"
        })
      );
    });
  });

  describe("orderCertificate", () => {
    const mockCertificateOrder = {
      altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "example.com" }],
      validity: { ttl: "30d" },
      commonName: "example.com",
      keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE],
      extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH],
      signatureAlgorithm: "RSA-SHA256",
      keyAlgorithm: "RSA_2048"
    };

    it("should throw ForbiddenRequestError when profile is not configured for API enrollment", async () => {
      const profileId = "profile-123";
      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.EST, // Wrong enrollment type
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "test-profile-est-order",
        description: "Test EST order profile",
        estConfigId: null,
        apiConfigId: "api-config-legacy"
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);

      await expect(
        service.orderCertificate({
          profileId,
          certificateOrder: mockCertificateOrder,
          ...mockActor
        })
      ).rejects.toThrow(ForbiddenRequestError);

      await expect(
        service.orderCertificate({
          profileId,
          certificateOrder: mockCertificateOrder,
          ...mockActor
        })
      ).rejects.toThrow("Profile is not configured for api enrollment");
    });

    describe("CA certificate orders", () => {
      const profileId = "profile-ca-order";
      const caOrder = {
        ...mockCertificateOrder,
        basicConstraints: { isCA: true, pathLength: 1 }
      };

      const mockProfile = {
        id: profileId,
        projectId: "project-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        caId: "ca-123",
        certificatePolicyId: "policy-123",
        createdAt: new Date(),
        updatedAt: new Date(),
        slug: "aws-pca-profile",
        description: "AWS PCA profile",
        estConfigId: null,
        apiConfigId: "api-config-1"
      };

      const setupCa = (externalCaType: CaType | null) => {
        vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
        vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue({
          id: "ca-123",
          projectId: "project-123",
          status: CaStatus.ACTIVE,
          externalCa: externalCaType ? { id: "ext-ca-1", type: externalCaType } : null
        } as any);
        vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
          isValid: true,
          errors: []
        } as any);
        vi.mocked(mockCertificateRequestDAL.transaction).mockImplementation(
          async (callback: (tx: any) => Promise<unknown>) => callback({})
        );
      };

      it("rejects CA issuance for an external CA other than AWS Private CA", async () => {
        setupCa(CaType.DIGICERT);

        await expect(service.orderCertificate({ profileId, certificateOrder: caOrder, ...mockActor })).rejects.toThrow(
          "CA certificate issuance is not supported for this external certificate authority"
        );
      });

      it("persists the CSR subject on the request row when an approval policy applies", async () => {
        const source = readFileSync(join(__dirname, "certificate-v3-service.ts"), "utf8");
        const approvalWrite = source.slice(source.indexOf("CertificateRequestStatus.PENDING_APPROVAL") - 2500);

        for (const field of ["organization", "organizationalUnit", "country", "state", "locality"]) {
          expect(approvalWrite, `the CSR approval branch must persist ${field}`).toContain(
            `${field}: mappedCertificateRequest.${field}`
          );
        }
      });

      it("passes basicConstraints to the issuance queue for AWS Private CA", async () => {
        setupCa(CaType.AWS_PCA);
        vi.mocked(mockApprovalPolicyDAL.findByProjectId).mockResolvedValue([]);

        await service.orderCertificate({ profileId, certificateOrder: caOrder, ...mockActor });

        expect(mockCertificateIssuanceQueue.queueCertificateIssuance).toHaveBeenCalledWith(
          expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })
        );
        expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(
          expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })
        );
      });

      // The approval branch writes its own request row, and issuance later reads it back.
      it("persists basicConstraints on the request row when an approval policy applies", async () => {
        setupCa(CaType.AWS_PCA);
        vi.mocked(mockApprovalPolicyService.matchPolicy).mockResolvedValue({
          id: "approval-policy-1",
          isActive: true,
          scopeType: null,
          scopeId: null,
          bypassForMachineIdentities: false,
          maxRequestTtl: null,
          conditions: { conditions: [{ profileNames: [mockProfile.slug] }] }
        } as any);

        await service.orderCertificate({ profileId, certificateOrder: caOrder, ...mockActor });

        expect(mockCertificateIssuanceQueue.queueCertificateIssuance).not.toHaveBeenCalled();
        // The value matters, the storage form does not.
        const [persistedRow] = vi.mocked(mockCertificateRequestDAL.create).mock.calls[0] as [
          { basicConstraints?: unknown }
        ];
        const persisted =
          typeof persistedRow.basicConstraints === "string"
            ? (JSON.parse(persistedRow.basicConstraints) as unknown)
            : persistedRow.basicConstraints;
        expect(persisted).toEqual({ isCA: true, pathLength: 1 });
        expect(mockApprovalPolicyService.createRequestFromPolicy).toHaveBeenCalledWith(
          expect.objectContaining({
            requestData: expect.objectContaining({
              certificateRequest: expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })
            })
          })
        );
      });

      it("rejects a CA order for AWS Private CA without a path length", async () => {
        setupCa(CaType.AWS_PCA);

        await expect(
          service.orderCertificate({
            profileId,
            certificateOrder: { ...mockCertificateOrder, basicConstraints: { isCA: true } },
            ...mockActor
          })
        ).rejects.toThrow("path length between 0 and 3 is required");
      });
    });
  });

  describe("algorithm compatibility (integration tests)", () => {
    const mockProfile = {
      id: "profile-1",
      slug: "test-profile",
      projectId: "project-1",
      caId: "ca-1",
      certificatePolicyId: "policy-1",
      enrollmentType: EnrollmentType.API,
      issuerType: IssuerType.CA,
      createdAt: new Date(),
      updatedAt: new Date(),
      description: "Test profile for algorithm compatibility",
      estConfigId: null,
      apiConfigId: "api-config-legacy"
    };

    const mockCertificateRequest = {
      commonName: "test.example.com",
      validity: { ttl: "30d" },
      keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE],
      extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH]
    };

    beforeEach(() => {
      vi.clearAllMocks();
    });

    it("should successfully process RSA algorithms with RSA CAs", async () => {
      const rsaCa = {
        id: "ca-1",
        projectId: "project-1",
        status: "active",
        name: "RSA Test CA",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true,
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-1",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "RSA Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "RSA Test CA",
          dn: "CN=RSA Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "RSA_2048",
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-1",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        }
      };

      const rsaPolicy = {
        id: "policy-1",
        name: "RSA Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        description: "RSA policy for algorithm compatibility",
        signatureAlgorithm: {
          allowedAlgorithms: ["SHA256-RSA", "SHA384-RSA"]
        },
        keyAlgorithm: null,
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ],
        subject: undefined,
        sans: undefined,
        keyUsages: undefined,
        extendedKeyUsages: undefined,
        algorithms: undefined,
        validity: undefined
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(rsaCa);
      vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(rsaPolicy);
      vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({
        certificate: "cert",
        certificateChain: "chain",
        issuingCaCertificate: "ca-cert",
        privateKey: "key",
        serialNumber: "123456",
        certificateId: "cert-1",
        commonName: "test.example.com",
        ca: rsaCa as any
      });
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        return callback(undefined as any);
      });

      // Should not throw - RSA CA is compatible with RSA signature algorithms
      await expect(
        service.issueCertificateFromProfile({
          profileId: mockProfile.id,
          certificateRequest: {
            ...mockCertificateRequest,
            signatureAlgorithm: "RSA-SHA256"
          },
          ...mockActor
        })
      ).resolves.toBeDefined();
    });

    it("should successfully process ECDSA algorithms with EC CAs", async () => {
      const ecCa = {
        id: "ca-1",
        projectId: "project-1",
        status: "active",
        name: "EC Test CA",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true,
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-1",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "EC Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "EC Test CA",
          dn: "CN=EC Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "EC_prime256v1",
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-1",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        }
      };

      const ecdsaPolicy = {
        id: "policy-1",
        name: "ECDSA Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        description: "ECDSA policy for algorithm compatibility",
        signatureAlgorithm: {
          allowedAlgorithms: ["SHA256-ECDSA", "SHA384-ECDSA"]
        },
        keyAlgorithm: null,
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ],
        subject: undefined,
        sans: undefined,
        keyUsages: undefined,
        extendedKeyUsages: undefined,
        algorithms: undefined,
        validity: undefined
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(ecCa);
      vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(ecdsaPolicy);
      vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({
        certificate: "cert",
        certificateChain: "chain",
        issuingCaCertificate: "ca-cert",
        privateKey: "key",
        serialNumber: "123456",
        certificateId: "cert-1",
        commonName: "test.example.com",
        ca: ecCa as any
      });
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        return callback(undefined as any);
      });

      // Should not throw - EC CA is compatible with ECDSA signature algorithms
      await expect(
        service.issueCertificateFromProfile({
          profileId: mockProfile.id,
          certificateRequest: {
            ...mockCertificateRequest,
            signatureAlgorithm: "ECDSA-SHA256"
          },
          ...mockActor
        })
      ).resolves.toBeDefined();
    });

    it("should dynamically support new RSA key sizes", async () => {
      const rsa8192Ca = {
        id: "ca-1",
        projectId: "project-1",
        status: "active",
        name: "RSA 8192 Test CA",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true,
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-1",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "RSA 8192 Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "RSA 8192 Test CA",
          dn: "CN=RSA 8192 Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "RSA_8192", // Future RSA key size
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-1",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        }
      };

      const rsaPolicy = {
        id: "policy-1",
        name: "RSA 8192 Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        description: "RSA 8192 policy for future key sizes",
        signatureAlgorithm: {
          allowedAlgorithms: ["SHA256-RSA"]
        },
        keyAlgorithm: null,
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ],
        subject: undefined,
        sans: undefined,
        keyUsages: undefined,
        extendedKeyUsages: undefined,
        algorithms: undefined,
        validity: undefined
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(rsa8192Ca);
      vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(rsaPolicy);
      vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({
        certificate: "cert",
        certificateChain: "chain",
        issuingCaCertificate: "ca-cert",
        privateKey: "key",
        serialNumber: "123456",
        certificateId: "cert-1",
        commonName: "test.example.com",
        ca: rsa8192Ca as any
      });
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        return callback(undefined as any);
      });

      // Should not throw - dynamic check supports new RSA key sizes
      await expect(
        service.issueCertificateFromProfile({
          profileId: mockProfile.id,
          certificateRequest: {
            ...mockCertificateRequest,
            signatureAlgorithm: "RSA-SHA256"
          },
          ...mockActor
        })
      ).resolves.toBeDefined();
    });

    it("should dynamically support new EC curve types", async () => {
      const newEcCa = {
        id: "ca-1",
        projectId: "project-1",
        status: "active",
        name: "EC secp521r1 Test CA",
        createdAt: new Date(),
        updatedAt: new Date(),
        enableDirectIssuance: true,
        externalCa: undefined,
        internalCa: {
          id: "internal-ca-1",
          parentCaId: null,
          type: "ROOT",
          friendlyName: "EC secp521r1 Test CA",
          organization: "Test Org",
          ou: "Test OU",
          country: "US",
          province: "CA",
          locality: "SF",
          commonName: "EC secp521r1 Test CA",
          dn: "CN=EC secp521r1 Test CA",
          serialNumber: "123",
          maxPathLength: null,
          keyAlgorithm: "EC_secp521r1", // Future EC curve
          notBefore: undefined,
          notAfter: undefined,
          activeCaCertId: "cert-123",
          caId: "ca-1",
          crlDistributionPointUrls: [],
          disableManagedCrlDistributionPointUrl: false,
          isOcspEnabled: false,
          ocspGeneration: 0
        }
      };

      const ecdsaPolicy = {
        id: "policy-1",
        name: "ECDSA secp521r1 Policy",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        description: "ECDSA secp521r1 policy for future EC curves",
        signatureAlgorithm: {
          allowedAlgorithms: ["SHA384-ECDSA"]
        },
        keyAlgorithm: null,
        attributes: [
          {
            type: CertSubjectAttributeType.COMMON_NAME,
            include: CertIncludeType.OPTIONAL,
            value: ["example.com"]
          }
        ],
        subject: undefined,
        sans: undefined,
        keyUsages: undefined,
        extendedKeyUsages: undefined,
        algorithms: undefined,
        validity: undefined
      };

      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(newEcCa);
      vi.mocked(mockCertificatePolicyService.validateCertificateRequest).mockResolvedValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(ecdsaPolicy);
      vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({
        certificate: "cert",
        certificateChain: "chain",
        issuingCaCertificate: "ca-cert",
        privateKey: "key",
        serialNumber: "123456",
        certificateId: "cert-1",
        commonName: "test.example.com",
        ca: newEcCa as any
      });
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
        id: "cert-1",
        serialNumber: "123456",
        status: "ACTIVE",
        createdAt: new Date(),
        updatedAt: new Date(),
        projectId: "project-1",
        commonName: "test.example.com",
        friendlyName: "Test Algorithm Cert",
        notBefore: new Date(),
        notAfter: new Date(),
        caId: "ca-1",
        certificateTemplateId: "template-1",
        revokedAt: null,
        altNames: null,
        caCertId: null,
        keyUsages: null,
        extendedKeyUsages: null,
        revocationReason: null,
        pkiSubscriberId: null,
        profileId: null,
        source: "issued",
        keySource: "infisical",
        quotaKey: "a".repeat(64),
        orderId: "00000000-0000-0000-0000-000000000000"
      });
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        return callback(undefined as any);
      });

      // Should not throw - dynamic check supports new EC curves
      await expect(
        service.issueCertificateFromProfile({
          profileId: mockProfile.id,
          certificateRequest: {
            ...mockCertificateRequest,
            signatureAlgorithm: "ECDSA-SHA384"
          },
          ...mockActor
        })
      ).resolves.toBeDefined();
    });
  });

  describe("renewCertificate", () => {
    const mockOriginalCert = {
      id: "cert-123",
      status: CertStatus.ACTIVE,
      serialNumber: "123456",
      friendlyName: "Test Certificate",
      commonName: "test.example.com",
      notBefore: new Date("2024-01-01"),
      notAfter: new Date("2024-02-01"), // 31 days
      revokedAt: null,
      renewedByCertificateId: null,
      profileId: "profile-123",
      renewBeforeDays: 7,
      caId: "ca-123",
      pkiSubscriberId: null,
      keyUsages: ["digital_signature", "key_agreement"],
      extendedKeyUsages: ["server_auth"],
      altNames: "test.example.com,api.example.com",
      projectId: "project-123",
      createdAt: new Date(),
      updatedAt: new Date(),
      certificatePolicyId: "policy-123",
      revocationReason: null,
      caCertId: null,
      renewedFromCertificateId: null,
      renewalError: null,
      keyAlgorithm: "RSA_2048",
      signatureAlgorithm: "RSA-SHA256",
      source: "issued",
      keySource: "infisical",
      quotaKey: "a".repeat(64),
      orderId: "00000000-0000-0000-0000-000000000000"
    };

    const mockProfile = {
      id: "profile-123",
      projectId: "project-123",
      enrollmentType: EnrollmentType.API,
      issuerType: IssuerType.CA,
      caId: "ca-123",
      certificatePolicyId: "policy-123",
      apiConfig: {
        id: "api-config-123",
        autoRenew: true,
        renewBeforeDays: 14
      },
      createdAt: new Date(),
      updatedAt: new Date(),
      slug: "test-profile",
      description: "Test profile"
    };

    const mockCA = {
      id: "ca-123",
      projectId: "project-123",
      status: CaStatus.ACTIVE,
      createdAt: new Date(),
      updatedAt: new Date(),
      enableDirectIssuance: true,
      name: "Test CA",
      requirePolicyForIssuance: false,
      externalCa: undefined,
      parentCaId: null,
      type: "ROOT",
      friendlyName: "Test CA",
      organization: "Test Org",
      ou: "Test OU",
      country: "US",
      province: "CA",
      locality: "SF",
      commonName: "Test CA",
      keyAlgorithm: "RSA_2048",
      notAfter: "2025-01-01T00:00:00Z",
      notBefore: "2024-01-01T00:00:00Z",
      maxPathLength: -1,
      activeCaCertId: "cert-123",
      dn: "CN=Test CA,O=Test Org,OU=Test OU,C=US",
      serialNumber: "123456789",
      internalCa: {
        id: "internal-ca-123",
        parentCaId: null,
        type: "ROOT",
        friendlyName: "Test CA",
        organization: "Test Org",
        ou: "Test OU",
        country: "US",
        province: "CA",
        locality: "SF",
        commonName: "Test CA",
        keyAlgorithm: "RSA_2048",
        notAfter: "2025-01-01T00:00:00Z",
        notBefore: "2024-01-01T00:00:00Z",
        maxPathLength: -1,
        activeCaCertId: "cert-123",
        dn: "CN=Test CA,O=Test Org,OU=Test OU,C=US",
        serialNumber: "123456789",
        crlDistributionPointUrls: [],
        disableManagedCrlDistributionPointUrl: false,
        isOcspEnabled: false,
        ocspGeneration: 0
      }
    };

    const mockPolicy = {
      id: "policy-123",
      projectId: "project-123",
      name: "Test Policy",
      createdAt: new Date(),
      updatedAt: new Date(),
      algorithms: {
        signature: ["SHA256-RSA", "SHA384-RSA"],
        keyType: ["RSA_2048", "RSA_4096"]
      }
    };

    beforeEach(() => {
      // Mock current date to be within renewal window
      vi.useFakeTimers();
      vi.setSystemTime(new Date("2024-01-26")); // 6 days before cert expires, within renewal window
    });

    afterEach(() => {
      vi.useRealTimers();
    });

    // The renewal flow lets the caller rewrite the common name and SANs, which mints a row under a
    // quota key the org has never held. Renewal is exempt from the caps only while the names are
    // unchanged, because refusing that would let a live certificate expire.
    describe("certificate quota on renewal", () => {
      const AT_CAP = { pkiPqc: true, maxCertificates: 5, maxWildcardCertificates: null };

      const atCap = (plan: Record<string, unknown> = AT_CAP, total = 5, wildcard = 0) => {
        vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
        vi.mocked(mockLicenseService.getPlan).mockResolvedValue(plan as never);
        vi.mocked(mockUsageCounterDAL.countActiveCertificateQuotaKeysByOrg).mockResolvedValue({ total, wildcard });
        vi.mocked(mockUsageCounterDAL.isCertificateQuotaKeyActiveInOrg).mockResolvedValue(false);
      };

      it("refuses a renewal that changes the SANs once the certificate cap is reached", async () => {
        atCap();

        await expect(
          service.renewCertificate({
            certificateId: "cert-123",
            ...mockActor,
            attributes: {
              altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "brand-new.example.com" }]
            }
          })
        ).rejects.toThrow(/plan limit/i);
      });

      it("refuses a renewal that changes the common name once the certificate cap is reached", async () => {
        atCap();

        await expect(
          service.renewCertificate({
            certificateId: "cert-123",
            ...mockActor,
            attributes: { commonName: "brand-new.example.com" }
          })
        ).rejects.toThrow(/plan limit/i);
      });

      it("refuses a renewal that introduces a wildcard on a plan without wildcard support", async () => {
        atCap({ pkiPqc: true, maxCertificates: null, maxWildcardCertificates: 0 }, 0, 0);

        await expect(
          service.renewCertificate({
            certificateId: "cert-123",
            ...mockActor,
            attributes: { altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "*.example.com" }] }
          })
        ).rejects.toThrow(/wildcard/i);
      });

      it("never consults the cap when the names are unchanged, so a live certificate cannot be blocked from renewing", async () => {
        atCap();

        // Fails later for want of the issuance mocks; the point is that it gets past the quota gate.
        await service.renewCertificate({ certificateId: "cert-123", ...mockActor }).catch(() => undefined);

        expect(mockUsageCounterDAL.countActiveCertificateQuotaKeysByOrg).not.toHaveBeenCalled();
      });
    });

    describe("DigiCert reissue", () => {
      const setupRenewal = (ca: unknown) => {
        vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
        vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
        vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
        vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(ca as any);
        vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
        vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
          isValid: true,
          errors: [],
          warnings: []
        } as any);
      };

      it("rejects a reissue for a certificate that a DigiCert CA did not issue", async () => {
        setupRenewal(mockCA);

        await expect(
          service.renewCertificate({
            certificateId: "cert-123",
            externalConfiguration: { reissue: true },
            ...mockActor
          })
        ).rejects.toThrow("Reissue is only available for certificates issued by these CAs: DigiCert.");
        expect(mockCertificateIssuanceQueue.queueCertificateIssuance).not.toHaveBeenCalled();
      });

      it("rejects a TTL on a DigiCert reissue", async () => {
        setupRenewal({
          ...mockCA,
          internalCa: undefined,
          externalCa: { id: "ext-ca-1", type: CaType.DIGICERT, configuration: {} }
        });

        await expect(
          service.renewCertificate({
            certificateId: "cert-123",
            externalConfiguration: { reissue: true },
            attributes: { ttl: "30d" },
            ...mockActor
          })
        ).rejects.toThrow("Remove the TTL. It can't be set on a reissue.");
        expect(mockCertificateIssuanceQueue.queueCertificateIssuance).not.toHaveBeenCalled();
      });
    });

    it("should successfully renew eligible certificate", async () => {
      // Three reads: the pre-transaction licence check, the in-transaction load, then the renewed row.
      vi.mocked(mockCertificateDAL.findById)
        .mockResolvedValueOnce(mockOriginalCert)
        .mockResolvedValueOnce(mockOriginalCert)
        .mockResolvedValueOnce({ ...mockOriginalCert, id: "cert-456", serialNumber: "789012" });
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockInternalCaService.issueCertFromCa).mockImplementation((async (dto: any) => {
        await dto.onPersisted?.({ ...mockOriginalCert, id: "cert-456", serialNumber: "789012" }, {});
        return {
          certificate: "renewed-cert",
          certificateChain: "renewed-chain",
          issuingCaCertificate: "issuing-ca",
          privateKey: "private-key",
          serialNumber: "789012",
          certificateId: "cert-456",
          commonName: "test.example.com",
          ca: mockCA
        };
      }) as any);

      const newCert = { ...mockOriginalCert, id: "cert-456", serialNumber: "789012" };
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(newCert);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(newCert);

      // Mock the transaction to return the expected structure
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        const result = await callback(mockTx);
        return result;
      });

      const result = await service.renewCertificate({
        certificateId: "cert-123",
        ...mockActor
      });

      expect(result).toHaveProperty("certificate", "renewed-cert");
      expect(result).toHaveProperty("certificateId", "cert-456");
      expect(mockCertificateDAL.updateById).toHaveBeenCalledWith(
        "cert-456",
        {
          profileId: "profile-123",
          renewBeforeDays: 14,
          renewedFromCertificateId: "cert-123",
          orderId: "00000000-0000-0000-0000-000000000000"
        },
        {}
      );
      expect(mockCertificateDAL.updateById).toHaveBeenCalledWith(
        "cert-123",
        {
          renewedByCertificateId: "cert-456",
          renewalError: null
        },
        {}
      );
    });

    it("preserves CA basicConstraints when renewing a CA certificate", async () => {
      const caCert = { ...mockOriginalCert, isCA: true, pathLength: 1 };
      vi.mocked(mockCertificateDAL.findById)
        .mockResolvedValueOnce(caCert)
        .mockResolvedValueOnce({ ...caCert, id: "cert-456", serialNumber: "789012" });
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue({
        ...mockPolicy,
        basicConstraints: { isCA: "allowed", maxPathLength: 2 }
      } as any);
      vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
        isValid: true,
        errors: [],
        warnings: []
      } as any);
      vi.mocked(mockInternalCaService.issueCertFromCa).mockImplementation((async (dto: any) => {
        await dto.onPersisted?.({ ...caCert, id: "cert-456", serialNumber: "789012" }, {});
        return {
          certificate: "renewed-cert",
          certificateChain: "renewed-chain",
          issuingCaCertificate: "issuing-ca",
          privateKey: "private-key",
          serialNumber: "789012",
          certificateId: "cert-456",
          commonName: "test.example.com",
          ca: mockCA
        };
      }) as any);

      const newCert = { ...caCert, id: "cert-456", serialNumber: "789012" };
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(newCert);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(newCert);

      await service.renewCertificate({ certificateId: "cert-123", ...mockActor });

      expect(mockInternalCaService.issueCertFromCa).toHaveBeenCalledWith(
        expect.objectContaining({
          basicConstraints: { isCA: true, pathLength: 2 },
          pathLength: 1
        })
      );
      expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(
        expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 1 } })
      );
    });

    describe("sources the new request from the originating certificate request", () => {
      const originatingRequest = {
        enrollmentType: EnrollmentType.API,
        csr: null,
        exists: true,
        commonName: "asked-for.example.com",
        organization: "Asked Corp",
        organizationalUnit: "Asked OU",
        country: "GB",
        state: "Asked State",
        locality: "Asked City",
        domainComponents: null,
        altNames: [{ type: CertSubjectAlternativeNameType.DNS_NAME, value: "asked-for.example.com" }],
        keyUsages: ["digital_signature"],
        extendedKeyUsages: ["client_auth"],
        customExtensions: null,
        keyAlgorithm: null,
        signatureAlgorithm: null
      };

      beforeEach(() => {
        vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
          ...mockOriginalCert,
          commonName: "ca-rewrote.example.com",
          subjectOrganization: "Issuer Corp",
          subjectOrganizationalUnit: "Issuer OU",
          subjectCountry: "US",
          subjectState: "Issuer State",
          subjectLocality: "Issuer City",
          altNames: "ca-added.example.com",
          keyUsages: ["digital_signature", "key_encipherment"],
          extendedKeyUsages: ["server_auth"]
        } as never);
        vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({
          id: "secret-123",
          certId: "cert-123"
        } as never);
        vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
        vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
        vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
        vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue(originatingRequest);
        vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
          isValid: true,
          errors: [],
          warnings: []
        } as never);
        vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({
          certificate: "cert",
          certificateChain: "chain",
          issuingCaCertificate: "issuing-ca",
          privateKey: "key",
          serialNumber: "123456",
          certificateId: "renewed-cert-1"
        } as never);
        vi.mocked(mockCertificateDAL.transaction).mockImplementation(
          async (callback: (tx: never) => Promise<unknown>) => callback(undefined as never)
        );
      });

      const expectedRequest = expect.objectContaining({
        commonName: "asked-for.example.com",
        organization: "Asked Corp",
        organizationalUnit: "Asked OU",
        country: "GB",
        state: "Asked State",
        locality: "Asked City",
        keyUsages: ["digital_signature"],
        extendedKeyUsages: ["client_auth"]
      });

      it("uses it for a manual renewal", async () => {
        await service.renewCertificate({ certificateId: "cert-123", ...mockActor });

        expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(expectedRequest);
      });

      it("uses it for a scheduled renewal", async () => {
        await service.renewCertificate({ certificateId: "cert-123", internal: true, ...mockActor });

        expect(mockCertificateRequestService.createCertificateRequest).toHaveBeenCalledWith(expectedRequest);
      });

      it("still runs the certificate policy over what it replays", async () => {
        await service.renewCertificate({ certificateId: "cert-123", ...mockActor });

        expect(mockCertificatePolicyService.validateRequestAgainstPolicy).toHaveBeenCalledWith(
          mockPolicy,
          expect.objectContaining({ commonName: "asked-for.example.com" }),
          expect.anything()
        );
      });
    });

    // The policy only sees a CA renewal as a CA request if basicConstraints are passed to it,
    // so this covers denied policies and tightened path lengths on both renewal paths.
    it("sends the certificate's CA constraints to policy validation on renewal", async () => {
      const caCert = { ...mockOriginalCert, isCA: true, pathLength: 3 };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(caCert);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
        isValid: false,
        errors: ["Requested path length (3) exceeds maximum allowed by policy (2)."],
        warnings: []
      } as any);

      await expect(service.renewCertificate({ certificateId: "cert-123", ...mockActor })).rejects.toThrow(
        "exceeds maximum allowed by policy"
      );

      expect(mockCertificatePolicyService.validateRequestAgainstPolicy).toHaveBeenCalledWith(
        mockPolicy,
        expect.objectContaining({ basicConstraints: { isCA: true, pathLength: 3 } }),
        expect.anything()
      );
      expect(mockInternalCaService.issueCertFromCa).not.toHaveBeenCalled();
    });

    it("should validate certificate against current policy during renewal", async () => {
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
        isValid: false,
        errors: ["Subject alternative name not allowed"],
        warnings: []
      });
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      // Mock updateById to handle the renewal error logging
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockOriginalCert);

      // Set up transaction mock to properly handle errors
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("Certificate renewal failed. Errors: Subject alternative name not allowed");

      expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", {
        renewalError: "Certificate renewal failed. Errors: Subject alternative name not allowed"
      });
    });

    it("should reject renewal if certificate has no profile and no CA", async () => {
      const certWithoutProfileAndCA = { ...mockOriginalCert, profileId: null, caId: null };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(certWithoutProfileAndCA);

      // Set up transaction mock to properly handle errors
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(ForbiddenRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("This certificate is not linked to a certificate profile, so it cannot be renewed");
    });

    it("refuses to renew a certificate into a name the caller may not edit", async () => {
      // The suite-wide beforeEach stubs ForbiddenError.from into a no-op, which would let any
      // permission check pass. This test is about the check itself, so it needs the real one.
      vi.mocked(ForbiddenError).from.mockRestore();

      // A real ability, so the condition is evaluated by CASL rather than by a mock. The caller may
      // edit certificates named allowed.example.com and issue from the profile, nothing else.
      const cnScoped = createMongoAbility([
        {
          action: [ProjectPermissionCertificateActions.Read, ProjectPermissionCertificateActions.Edit],
          subject: ProjectPermissionSub.Certificates,
          conditions: { commonName: "allowed.example.com" }
        },
        {
          action: ProjectPermissionCertificateProfileActions.IssueCert,
          subject: ProjectPermissionSub.CertificateProfiles
        }
      ]);
      (mockPermissionService.getProjectPermission as any).mockResolvedValue({ permission: cnScoped });

      const scopedCert = { ...mockOriginalCert, commonName: "allowed.example.com" };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(scopedCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
        isValid: true,
        errors: [],
        warnings: []
      } as any);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({
        id: "secret-123",
        certId: "cert-123"
      } as any);
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) =>
        callback({})
      );

      // Renaming it outside that scope must be refused even though the profile policy accepts the
      // name: the replacement inherits the original's syncs and would be pushed. The allow path is
      // covered by the other renewal tests, which run with an unconditional ability.
      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          attributes: { commonName: "out-of-scope.example.com" },
          ...mockActor
        })
      ).rejects.toThrow(ForbiddenError);
    });

    it("refuses to reuse a key pair it holds neither the key nor the signing request for", async () => {
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue(null as any);
      vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue({
        enrollmentType: EnrollmentType.API,
        csr: null,
        exists: true,
        commonName: null,
        organization: null,
        organizationalUnit: null,
        country: null,
        state: null,
        locality: null,
        domainComponents: null,
        altNames: null,
        keyUsages: null,
        extendedKeyUsages: null,
        customExtensions: null,
        keyAlgorithm: null,
        signatureAlgorithm: null
      });

      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          renewalKeySource: CertificateRenewalKeySource.Reuse,
          ...mockActor
        })
      ).rejects.toThrow("cannot be reused");
    });

    it("should reject renewal for a protocol-enrolled certificate", async () => {
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateDAL.getOriginatingRequestByCertId).mockResolvedValue({
        enrollmentType: EnrollmentType.ACME,
        csr: null,
        exists: true,
        commonName: null,
        organization: null,
        organizationalUnit: null,
        country: null,
        state: null,
        locality: null,
        domainComponents: null,
        altNames: null,
        keyUsages: null,
        extendedKeyUsages: null,
        customExtensions: null,
        keyAlgorithm: null,
        signatureAlgorithm: null
      });
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(ForbiddenRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("Certificate is not eligible for renewal: ACME certificates cannot be renewed");
    });

    it("should reject renewal if certificate is already renewed", async () => {
      const alreadyRenewedCert = { ...mockOriginalCert, renewedByCertificateId: "cert-456" };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(alreadyRenewedCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      // Mock updateById to handle the renewal error logging
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(alreadyRenewedCert);

      // Set up transaction mock to properly handle errors
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("Certificate has already been renewed");
    });

    it("should reject renewal if certificate is expired", async () => {
      const expiredCert = {
        ...mockOriginalCert,
        notAfter: new Date("2024-01-20") // Expired 6 days ago
      };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(expiredCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      // Mock updateById to handle the renewal error logging
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(expiredCert);

      // Set up transaction mock to properly handle errors
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("Certificate is already expired");
    });

    it("should reject renewal if certificate is revoked", async () => {
      const revokedCert = {
        ...mockOriginalCert,
        revokedAt: new Date("2024-01-15")
      };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(revokedCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      // Mock updateById to handle the renewal error logging
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(revokedCert);

      // Set up transaction mock to properly handle errors
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("Certificate is revoked and cannot be renewed");
    });

    it("should reject renewal if certificate is deleted", async () => {
      const deletedCert = {
        ...mockOriginalCert,
        deletedAt: new Date("2026-10-20T14:38:27.000Z")
      };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(deletedCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(deletedCert);
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) =>
        callback({})
      );

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("was deleted on 2026-10-20T14:38:27.000Z. It can no longer be renewed or changed");
    });

    it("should reject renewal if CA is inactive", async () => {
      const inactiveCA = { ...mockCA, status: CaStatus.DISABLED };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(inactiveCA);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      // Mock updateById to handle the renewal error logging
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockOriginalCert);

      // Set up transaction mock to properly handle errors
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow("Certificate is not eligible for renewal: Certificate Authority is disabled, must be active");
    });

    it("should reject renewal if new certificate would outlive CA", async () => {
      const shortLivedCA = {
        ...mockCA,
        internalCa: {
          ...mockCA.internalCa,
          notAfter: "2024-01-28T00:00:00Z"
        }
      };
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(shortLivedCA);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      // Mock updateById to handle the renewal error logging
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockOriginalCert);

      // Set up transaction mock to properly handle errors
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.renewCertificate({
          certificateId: "cert-123",
          ...mockActor
        })
      ).rejects.toThrow(/New certificate would expire \(.+\) after its issuing CA \(.+\)/);
    });

    it("should allow manual renewal outside window (manual renewal always bypasses window)", async () => {
      vi.setSystemTime(new Date("2024-01-15")); // 17 days before expiry, outside 7-day window

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile);
      vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
      vi.mocked(mockCertificatePolicyService.getPolicyById).mockResolvedValue(mockPolicy);
      vi.mocked(mockCertificatePolicyService.validateRequestAgainstPolicy).mockReturnValue({
        isValid: true,
        errors: [],
        warnings: []
      });
      vi.mocked(mockInternalCaService.issueCertFromCa).mockImplementation((async (dto: any) => {
        await dto.onPersisted?.({ ...mockOriginalCert, id: "cert-456", serialNumber: "789012" }, {});
        return {
          certificate: "renewed-cert",
          certificateChain: "renewed-chain",
          issuingCaCertificate: "issuing-ca",
          privateKey: "private-key",
          serialNumber: "789012",
          certificateId: "cert-456",
          commonName: "test.example.com",
          ca: mockCA
        };
      }) as any);

      const newCert = { ...mockOriginalCert, id: "cert-456", serialNumber: "789012" };
      vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(newCert);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(newCert);

      // Set up transaction mock to properly handle the renewal process
      vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise<unknown>) => {
        const mockTx = {};
        return callback(mockTx);
      });

      const result = await service.renewCertificate({
        certificateId: "cert-123",
        ...mockActor
      });

      expect(result).toHaveProperty("certificate", "renewed-cert");
    });
  });

  describe("updateRenewalConfig", () => {
    it("should update renewal configuration successfully", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: "profile-123",
        renewedByCertificateId: null,
        notBefore: new Date(),
        notAfter: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30),
        projectId: "project-123",
        status: CertStatus.ACTIVE,
        revokedAt: null,
        commonName: ""
      };

      const mockProfile = {
        id: "profile-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCert as any);

      const result = await service.updateRenewalConfig({
        actor: ActorType.USER,
        actorId: "user-123",
        actorAuthMethod: AuthMethod.EMAIL,
        actorOrgId: "org-123",
        certificateId: "cert-123",
        renewBeforeDays: 7
      });

      expect(result).toEqual({
        projectId: "project-123",
        renewBeforeDays: 7,
        commonName: "",
        applicationId: null,
        applicationName: null
      });

      expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { renewBeforeDays: 7 });
    });

    it("should reject update if certificate is not from profile", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: null,
        renewedByCertificateId: null,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);

      await expect(
        service.updateRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123",
          renewBeforeDays: 7
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.updateRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123",
          renewBeforeDays: 7
        })
      ).rejects.toThrow("Certificate is not eligible for auto-renewal: certificate was not issued from a profile");
    });

    it("should reject update if certificate is already renewed", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: "profile-123",
        renewedByCertificateId: "cert-456",
        projectId: "project-123",
        status: CertStatus.ACTIVE,
        revokedAt: null,
        notBefore: new Date(),
        notAfter: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30)
      };

      const mockProfile = {
        id: "profile-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      await expect(
        service.updateRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123",
          renewBeforeDays: 7
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.updateRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123",
          renewBeforeDays: 7
        })
      ).rejects.toThrow("Certificate is not eligible for auto-renewal: certificate has already been renewed");
    });

    it("should allow update for an API-issued certificate under a legacy ACME-labeled profile", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: "profile-123",
        renewedByCertificateId: null,
        notBefore: new Date(),
        notAfter: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30),
        projectId: "project-123",
        status: CertStatus.ACTIVE,
        revokedAt: null,
        commonName: ""
      };

      const mockProfile = {
        id: "profile-123",
        enrollmentType: EnrollmentType.ACME,
        issuerType: IssuerType.CA,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
      vi.mocked(mockCertificateDAL.getRequestEnrollmentTypeByCertId).mockResolvedValue(EnrollmentType.API);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCert as any);

      const result = await service.updateRenewalConfig({
        actor: ActorType.USER,
        actorId: "user-123",
        actorAuthMethod: AuthMethod.EMAIL,
        actorOrgId: "org-123",
        certificateId: "cert-123",
        renewBeforeDays: 7
      });

      expect(result).toEqual({
        projectId: "project-123",
        renewBeforeDays: 7,
        commonName: "",
        applicationId: null,
        applicationName: null
      });
      expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { renewBeforeDays: 7 });
    });

    it("should reject update for a protocol-enrolled certificate regardless of key presence", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: "profile-123",
        renewedByCertificateId: null,
        notBefore: new Date(),
        notAfter: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30),
        projectId: "project-123",
        status: CertStatus.ACTIVE,
        revokedAt: null
      };

      const mockProfile = {
        id: "profile-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
      vi.mocked(mockCertificateDAL.getRequestEnrollmentTypeByCertId).mockResolvedValue(EnrollmentType.ACME);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      await expect(
        service.updateRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123",
          renewBeforeDays: 7
        })
      ).rejects.toThrow("Certificate is not eligible for auto-renewal: ACME certificates cannot be auto-renewed");
    });

    it("should reject update if renewBeforeDays >= certificate TTL", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: "profile-123",
        renewedByCertificateId: null,
        notBefore: new Date(),
        notAfter: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
        projectId: "project-123",
        status: CertStatus.ACTIVE,
        revokedAt: null
      };

      const mockProfile = {
        id: "profile-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
      vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any);

      await expect(
        service.updateRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123",
          renewBeforeDays: 8 // Greater than 7-day TTL
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.updateRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123",
          renewBeforeDays: 8
        })
      ).rejects.toThrow("Invalid renewal configuration: renewal threshold exceeds certificate validity period");
    });
  });

  describe("disableRenewalConfig", () => {
    it("should disable renewal configuration successfully", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: "profile-123",
        projectId: "project-123",
        commonName: ""
      };

      const mockProfile = {
        id: "profile-123",
        enrollmentType: EnrollmentType.API,
        issuerType: IssuerType.CA,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any);
      vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCert as any);

      const result = await service.disableRenewalConfig({
        actor: ActorType.USER,
        actorId: "user-123",
        actorAuthMethod: AuthMethod.EMAIL,
        actorOrgId: "org-123",
        certificateId: "cert-123"
      });

      expect(result).toEqual({
        projectId: "project-123",
        commonName: "",
        applicationId: null,
        applicationName: null
      });

      expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { renewBeforeDays: null });
    });

    it("should reject disable if certificate is not from profile", async () => {
      const mockCert = {
        id: "cert-123",
        profileId: null,
        projectId: "project-123"
      };

      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any);

      await expect(
        service.disableRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123"
        })
      ).rejects.toThrow(BadRequestError);

      await expect(
        service.disableRenewalConfig({
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          certificateId: "cert-123"
        })
      ).rejects.toThrow("Certificate is not eligible for auto-renewal: certificate was not issued from a profile");
    });
  });
  describe("certificate issuance failure audit", () => {
    const auditLogInfo = {
      ipAddress: "127.0.0.1",
      userAgent: "test-agent",
      userAgentType: UserAgentType.OTHER,
      actor: { type: ActorType.USER as const, metadata: { userId: "user-123", email: "[email protected]", username: "[email protected]" } }
    };

    const issueDto = {
      profileId: "profile-123",
      certificateRequest: { commonName: "fail.example.com", validity: { ttl: "30d" } },
      actor: ActorType.USER,
      actorId: "user-123",
      actorAuthMethod: AuthMethod.EMAIL,
      actorOrgId: "org-123"
    };

    beforeEach(() => {
      vi.mocked(mockCertificateProfileDAL.findById).mockResolvedValue({
        id: "profile-123",
        projectId: "project-123",
        slug: "web-servers",
        caId: "ca-123"
      } as never);
    });

    it("records the failure with the reason and the profile's details", async () => {
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue({
        id: "profile-123",
        projectId: "project-123",
        slug: "web-servers",
        caId: "ca-123",
        enrollmentType: EnrollmentType.API
      } as never);
      await expect(service.issueCertificateFromProfile({ ...issueDto, auditLogInfo })).rejects.toThrow(
        "This profile must be issued through an Application"
      );

      expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledTimes(1);
      expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledWith(
        expect.objectContaining({
          projectId: "project-123",
          actor: auditLogInfo.actor,
          event: {
            type: EventType.CERTIFICATE_ISSUANCE_FAILED,
            metadata: {
              operation: CertificateIssuanceOperation.ISSUE,
              enrollmentType: EnrollmentType.API,
              commonName: "fail.example.com",
              certificateProfileId: "profile-123",
              profileName: "web-servers",
              caId: "ca-123",
              errorName: "BadRequest",
              error:
                "This profile must be issued through an Application. Attach it to an Application and issue from there."
            }
          }
        })
      );
    });

    it("records nothing without audit log info", async () => {
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(new BadRequestError({ message: "x" }));

      await expect(service.issueCertificateFromProfile(issueDto)).rejects.toThrow("x");

      expect(mockAuditLogService.createCollapsedAuditLog).not.toHaveBeenCalled();
    });

    it("leaves permission denials to the permission-denied event", async () => {
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(
        new ForbiddenRequestError({ message: "denied" })
      );

      await expect(service.issueCertificateFromProfile({ ...issueDto, auditLogInfo })).rejects.toThrow("denied");

      expect(mockAuditLogService.createCollapsedAuditLog).not.toHaveBeenCalled();
    });

    it("never writes into another org's audit log", async () => {
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(new NotFoundError({ message: "x" }));

      await expect(
        service.issueCertificateFromProfile({ ...issueDto, actorOrgId: "other-org", auditLogInfo })
      ).rejects.toThrow("x");

      expect(mockAuditLogService.createCollapsedAuditLog).not.toHaveBeenCalled();
    });

    it("still surfaces the original error when recording fails", async () => {
      const failure = new BadRequestError({ message: "bad csr" });
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(failure);
      mockAuditLogService.createCollapsedAuditLog.mockRejectedValueOnce(new Error("redis down"));

      await expect(service.issueCertificateFromProfile({ ...issueDto, auditLogInfo })).rejects.toBe(failure);
    });

    it("records a sign failure under the operation the caller passed", async () => {
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(new BadRequestError({ message: "x" }));

      await expect(
        service.signCertificateFromProfile({
          profileId: "profile-123",
          csr: "not a csr",
          validity: { ttl: "30d" },
          enrollmentType: EnrollmentType.EST,
          issuanceOperation: CertificateIssuanceOperation.RENEW,
          originalCertificateId: "cert-old",
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          auditLogInfo
        } as never)
      ).rejects.toThrow("x");

      expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledWith(
        expect.objectContaining({
          event: expect.objectContaining({
            metadata: expect.objectContaining({
              operation: CertificateIssuanceOperation.RENEW,
              enrollmentType: EnrollmentType.EST,
              originalCertificateId: "cert-old"
            })
          })
        })
      );
    });

    it("records an order failure with the order's common name", async () => {
      vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockRejectedValue(new BadRequestError({ message: "x" }));

      await expect(
        service.orderCertificate({
          profileId: "profile-123",
          certificateOrder: { commonName: "order.example.com", altNames: [], validity: { ttl: "30d" } },
          actor: ActorType.USER,
          actorId: "user-123",
          actorAuthMethod: AuthMethod.EMAIL,
          actorOrgId: "org-123",
          auditLogInfo
        } as never)
      ).rejects.toThrow("x");

      expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledWith(
        expect.objectContaining({
          event: expect.objectContaining({
            metadata: expect.objectContaining({
              operation: CertificateIssuanceOperation.ORDER,
              commonName: "order.example.com"
            })
          })
        })
      );
    });

    const renewDto = {
      certificateId: "cert-123",
      actor: ActorType.USER,
      actorId: "user-123",
      actorAuthMethod: AuthMethod.EMAIL,
      actorOrgId: "org-123",
      auditLogInfo
    };

    const storedCertificate = {
      id: "cert-123",
      projectId: "project-123",
      commonName: "renew.example.com",
      profileId: "profile-123",
      caId: "ca-123",
      applicationId: "app-123"
    };

    it("records a failed renewal against the original certificate", async () => {
      vi.mocked(mockCertificateDAL.findById).mockResolvedValue(storedCertificate as never);
      vi.mocked(mockCertificateDAL.transaction).mockRejectedValueOnce(
        new BadRequestError({ message: "CA is disabled" })
      );

      await expect(service.renewCertificate(renewDto)).rejects.toThrow("CA is disabled");

      expect(mockAuditLogService.createCollapsedAuditLog).toHaveBeenCalledWith(
        expect.objectContaining({
          event: expect.objectContaining({
            type: EventType.CERTIFICATE_ISSUANCE_FAILED,
            metadata: expect.objectContaining({
              operation: CertificateIssuanceOperation.RENEW,
              originalCertificateId: "cert-123",
              commonName: "renew.example.com",
              certificateProfileId: "profile-123",
              applicationId: "app-123"
            })
          })
        })
      );
    });
  });
});