Skip to content

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

misc: added gating to ACME

Sheen Capadngan90dd513a0db9
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.ts
index 176b3190e0..a3ee94fdd6 100644
--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts
+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts
@@ -42,6 +42,7 @@ import {
extractAlgorithmsFromCSR,
extractCertificateRequestFromCSR
} from "@app/services/certificate-common/certificate-csr-utils";
+import { validateCertificateRequestLicense } from "@app/services/certificate-common/certificate-utils";
import { TCertificatePolicyDALFactory } from "@app/services/certificate-policy/certificate-policy-dal";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
@@ -56,11 +57,13 @@ import { applyProfileDefaults, resolveEffectiveTtl } from "@app/services/certifi
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
import { TAcmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/acme-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";
+import { TLicenseServiceFactory } from "../license/license-service";
import { TPkiAcmeAccountDALFactory } from "./pki-acme-account-dal";
import { TPkiAcmeAuthDALFactory } from "./pki-acme-auth-dal";
import { TPkiAcmeChallengeDALFactory } from "./pki-acme-challenge-dal";
@@ -156,6 +159,11 @@ type TPkiAcmeServiceFactoryDep = {
"create" | "transaction" | "updateById" | "findByAccountAuthAndChallengeId" | "findByIdForChallengeValidation"
>;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ "countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
+ >;
kmsService: Pick<
TKmsServiceFactory,
"decryptWithKmsKey" | "generateKmsKey" | "encryptWithKmsKey" | "createCipherPairWithDataKey"
@@ -186,6 +194,8 @@ export const pkiAcmeServiceFactory = ({
acmeOrderAuthDAL,
acmeChallengeDAL,
keyStore,
+ licenseService,
+ usageCounterDAL,
kmsService,
certificateV3Service,
certificatePolicyService,
@@ -1086,6 +1096,14 @@ export const pkiAcmeServiceFactory = ({
throw new AcmeBadCSRError({ message: `Invalid CSR: ${validationResult.errors.join(", ")}` });
}
+ await validateCertificateRequestLicense({
+ request: updatedCertificateRequest,
+ projectId: profile.projectId,
+ projectDAL,
+ licenseService,
+ quotaDeps: { projectDAL, licenseService, usageCounterDAL, keyStore }
+ });
+
const certRequest = await certificateRequestService.createCertificateRequest({
actor: ActorType.ACME_ACCOUNT,
actorId: accountId,
diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.ts
index 12fa66b830..50a21ba45a 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts
@@ -33,6 +33,7 @@ import {
extractAlgorithmsFromCSR,
extractCertificateRequestFromCSR
} from "@app/services/certificate-common/certificate-csr-utils";
+import { validateCertificateRequestLicense } from "@app/services/certificate-common/certificate-utils";
import { TCertificatePolicyDALFactory } from "@app/services/certificate-policy/certificate-policy-dal";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
@@ -44,6 +45,7 @@ import { applyProfileDefaults, resolveEffectiveTtl } from "@app/services/certifi
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TPkiApplicationProfileDALFactory } from "@app/services/pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -87,11 +89,15 @@ type TPkiScepServiceFactoryDep = {
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find" | "findById">;
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "findById">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
- projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction" | "findById">;
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
- keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ "countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
+ >;
certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "findById">;
certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateCertificateRequest">;
certificateRequestService: Pick<TCertificateRequestServiceFactory, "createCertificateRequest">;
@@ -123,6 +129,7 @@ export const pkiScepServiceFactory = ({
appConnectionDAL,
keyStore,
licenseService,
+ usageCounterDAL,
certificatePolicyDAL,
certificatePolicyService,
certificateRequestService,
@@ -919,6 +926,14 @@ export const pkiScepServiceFactory = ({
});
}
+ await validateCertificateRequestLicense({
+ request: { ...certRequest, keyAlgorithm, signatureAlgorithm },
+ projectId: profile.projectId,
+ projectDAL,
+ licenseService,
+ quotaDeps: { projectDAL, licenseService, usageCounterDAL, keyStore }
+ });
+
const newCertRequest = await certificateRequestService.createCertificateRequest({
actor: ActorType.SCEP_ACCOUNT,
actorId: profile.id,
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 2f6ce0862f..49c7adfbcd 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3669,6 +3669,7 @@ export const registerRoutes = async (
const pkiScepService = pkiScepServiceFactory({
keyStore,
+ usageCounterDAL,
certificateV3Service,
certificateProfileDAL,
scepEnrollmentConfigDAL,
@@ -3704,6 +3705,8 @@ export const registerRoutes = async (
const pkiAcmeService = pkiAcmeServiceFactory({
projectDAL,
+ licenseService,
+ usageCounterDAL,
certificateAuthorityDAL,
certificateProfileDAL,
certificateBodyDAL,
diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.ts
index 77f488ce76..81cf3cbe51 100644
--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts
+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts
@@ -61,11 +61,14 @@ import {
assertCanEditCertificate,
assertCanEditCertificateResult
} from "../certificate-common/certificate-permission-fns";
+import { TCertificateQuotaDeps } from "../certificate-common/certificate-quota-fns";
+import { buildCertificateQuotaKey } from "../certificate-common/certificate-quota-key";
import {
convertExtendedKeyUsageArrayToLegacy,
convertKeyUsageArrayToLegacy,
normalizeDateForApi,
removeRootCaFromChain,
+ validateCertificateRequestLicense,
validatePqcLicense
} from "../certificate-common/certificate-utils";
import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
@@ -147,6 +150,8 @@ type TCertificateRenewalServiceFactoryDep = {
>;
apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ quotaDeps: TCertificateQuotaDeps;
+ recordQuotaUsage: (usage?: { orgId: string; isNewQuotaKey: boolean; isWildcard: boolean }) => Promise<void>;
resolveApplicationIdForProfile: TResolveApplicationIdForProfile;
reportCertificateIssued: TReportCertificateIssued;
};
@@ -209,6 +214,8 @@ export const certificateRenewalServiceFactory = ({
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL,
licenseService,
+ quotaDeps,
+ recordQuotaUsage,
resolveApplicationIdForProfile: $resolveApplicationIdForProfile,
reportCertificateIssued: $reportCertificateIssued
}: TCertificateRenewalServiceFactoryDep) => {
@@ -928,11 +935,11 @@ export const certificateRenewalServiceFactory = ({
};
const $assertRequestedAlgorithmsLicensed = async ({
- certificateId,
+ originalCert,
csrRenewalRequest,
attributes
}: {
- certificateId: string;
+ originalCert: TCertificates;
csrRenewalRequest: TCertificateRequest | null;
attributes?: TRenewalAttributes;
}) => {
@@ -945,16 +952,57 @@ export const certificateRenewalServiceFactory = ({
if (!requested.length) return;
- const originalCert = await certificateDAL.findById(certificateId);
- if (!originalCert) {
- throw new NotFoundError({ message: "Certificate not found" });
- }
-
for await (const keyAlgorithm of requested) {
await validatePqcLicense({ keyAlgorithm, projectId: originalCert.projectId, projectDAL, licenseService });
}
};
+ // Renewal is exempt from the certificate caps only while it stays the same logical certificate: a
+ // refused renewal lets a live certificate expire. The flow lets the caller rewrite the common name
+ // and SANs though, and a renewal that does inserts a row under a quota key the org has never held,
+ // so that one is a new certificate wearing a renewal's clothes and takes the issuance caps.
+ const $assertRenewalQuota = async ({
+ originalCert,
+ csrRenewalRequest,
+ attributes
+ }: {
+ originalCert: TCertificates;
+ csrRenewalRequest: TCertificateRequest | null;
+ attributes?: TRenewalAttributes;
+ }) => {
+ // Same merge $buildValidatedRenewalRequest performs, so the key checked here is the key stored.
+ const renewedRequest =
+ csrRenewalRequest ??
+ buildRenewalCertificateRequest({
+ original: {
+ commonName: originalCert.commonName || undefined,
+ subjectAlternativeNames: originalCert.altNames
+ ? originalCert.altNames.split(",").map((san) => detectSanType(san.trim()))
+ : []
+ } as TCertificateRequest,
+ attributes
+ });
+
+ const renewedAltNames = (renewedRequest.subjectAlternativeNames ?? []).map((san) => san.value).join(",");
+ const renewedQuotaKey = buildCertificateQuotaKey({
+ commonName: renewedRequest.commonName,
+ altNames: renewedAltNames
+ });
+
+ // Compared against the key derived from the row rather than the stored quotaKey, because the
+ // question is only whether the names changed. Were the hash ever to change, every stored key would
+ // go stale at once and reading it here would make every renewal look like a new certificate.
+ if (renewedQuotaKey === buildCertificateQuotaKey(originalCert)) return undefined;
+
+ return validateCertificateRequestLicense({
+ request: { ...renewedRequest, altNames: undefined },
+ projectId: originalCert.projectId,
+ projectDAL,
+ licenseService,
+ quotaDeps
+ });
+ };
+
const renewCertificate = async ({
certificateId,
actor,
@@ -980,7 +1028,15 @@ export const certificateRenewalServiceFactory = ({
const isEditingCertificate = isCertificateContentEdit({ keySource, attributes });
let changedAttributes: TRenewalAuditChange[] = [];
- await $assertRequestedAlgorithmsLicensed({ certificateId, csrRenewalRequest, attributes });
+ // Read once for both licence checks. They run before the transaction because getPlan can reach
+ // Redis and the License Server, and the renewal transaction must hold no network call.
+ const certForLicenseChecks = await certificateDAL.findById(certificateId);
+ if (!certForLicenseChecks) {
+ throw new NotFoundError({ message: "Certificate not found" });
+ }
+
+ await $assertRequestedAlgorithmsLicensed({ originalCert: certForLicenseChecks, csrRenewalRequest, attributes });
+ const quotaUsage = await $assertRenewalQuota({ originalCert: certForLicenseChecks, csrRenewalRequest, attributes });
const runRenewal = () =>
certificateDAL.transaction(async (tx) => {
@@ -1234,6 +1290,8 @@ export const certificateRenewalServiceFactory = ({
throw err;
}
+ await recordQuotaUsage(quotaUsage);
+
if (renewalResult.renewalMode === CertificateRenewalMode.KeyPreserving) {
const response = await $completeKeyPreservingRenewal({
...renewalResult,
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
index bbdc6c121a..2df92e0e88 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -179,6 +179,22 @@ describe("CertificateV3Service", () => {
})
};
+ const mockUsageCounterDAL = {
+ resolveRootOrgId: vi.fn(async (id: string) => id),
+ countActiveCertificateQuotaKeysByOrg: vi.fn(async () => ({ total: 0, wildcard: 0 })),
+ isCertificateQuotaKeyActiveInOrg: vi.fn(async () => 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 })
+ };
+
const mockCertificateIssuanceQueue = {
queueCertificateIssuance: vi.fn()
};
@@ -215,6 +231,15 @@ describe("CertificateV3Service", () => {
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);
@@ -331,19 +356,9 @@ describe("CertificateV3Service", () => {
apiEnrollmentConfigDAL: {
findById: vi.fn().mockResolvedValue(undefined)
},
- usageCounterDAL: {
- resolveRootOrgId: vi.fn(async (id: string) => id),
- countActiveCertificateQuotaKeysByOrg: vi.fn(async () => ({ total: 0, wildcard: 0 })),
- isCertificateQuotaKeyActiveInOrg: vi.fn(async () => false)
- },
- keyStore: {
- getItem: vi.fn(async () => null),
- setItemWithExpiry: vi.fn(async () => "OK" as const),
- deleteItem: vi.fn(async () => 1)
- },
- licenseService: {
- getPlan: vi.fn().mockResolvedValue({ pkiPqc: true })
- },
+ usageCounterDAL: mockUsageCounterDAL,
+ keyStore: mockKeyStore,
+ licenseService: mockLicenseService,
telemetryService: mockTelemetryService
});
});
@@ -2393,8 +2408,71 @@ describe("CertificateV3Service", () => {
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();
+ });
+ });
+
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);
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index 9a40bc2869..31c4aeb85b 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -1286,7 +1286,8 @@ export const certificateV3ServiceFactory = ({
mappedCertificateRequest.keyAlgorithm = extractedKeyAlgorithm;
mappedCertificateRequest.signatureAlgorithm = extractedSignatureAlgorithm;
- // Also the gate for ACME, SCEP and EST, which all reach issuance through here.
+ // Also the gate for the ACME and SCEP internal-CA branches, which sign through here. Their
+ // external-CA branches queue issuance instead and are gated in their own services.
const quotaUsage = await validateCertificateRequestLicense({
request: mappedCertificateRequest,
projectId: profile.projectId,
@@ -2160,6 +2161,8 @@ export const certificateV3ServiceFactory = ({
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL,
licenseService,
+ quotaDeps: $quotaDeps,
+ recordQuotaUsage: $recordQuotaUsage,
resolveApplicationIdForProfile: $resolveApplicationIdForProfile,
reportCertificateIssued: $reportCertificateIssued
});