Skip to content

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

feat: ca and cert count enforcement

Sheen Capadngan6b75f66a69fb
diff --git a/backend/src/db/migrations/20260903051500_add-certificate-quota-key.ts b/backend/src/db/migrations/20260903051500_add-certificate-quota-key.ts
new file mode 100644
index 0000000000..86b41bdbfe
--- /dev/null
+++ b/backend/src/db/migrations/20260903051500_add-certificate-quota-key.ts
@@ -0,0 +1,59 @@
+import { Knex } from "knex";
+
+import { buildCertificateQuotaKey } from "@app/services/certificate-common/certificate-quota-key";
+
+import { TableName } from "../schemas";
+
+const BACKFILL_BATCH_SIZE = 10_000;
+// Only reached if an instance predating the DAL override is still inserting rows without a key.
+// Leftover nulls are tolerable, so this stops rather than failing the deploy.
+const MAX_BACKFILL_BATCHES = 10_000;
+
+// Nullable on purpose: NOT NULL needs a CHECK added, validated, promoted and dropped, three of those
+// taking ACCESS EXCLUSIVE. The DAL's create() supplies the value, and a stray null only makes the
+// quota under-count. A follow-up migration can add NOT NULL once every instance is on the new code.
+//
+// config.transaction is false so each batch commits on its own; otherwise knex would hold the
+// ADD COLUMN lock for the whole backfill.
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasColumn(TableName.Certificate, "quotaKey"))) {
+ // While an ACCESS EXCLUSIVE lock is waiting, every query arriving after it queues behind it, reads
+ // included, so the wait is bounded. The transaction exists only so SET LOCAL lands on the same
+ // pooled connection as the ALTER.
+ await knex.transaction(async (tx) => {
+ await tx.raw("SET LOCAL lock_timeout = '5s'");
+ await tx.schema.alterTable(TableName.Certificate, (t) => {
+ t.string("quotaKey", 64).nullable();
+ });
+ });
+ }
+
+ // No OFFSET: the WHERE clause is the cursor, since each batch fills the rows it just selected.
+ for (let batch = 0; batch < MAX_BACKFILL_BATCHES; batch += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const rows = await knex(TableName.Certificate)
+ .whereNull("quotaKey")
+ .select("id", "commonName", "altNames")
+ .limit(BACKFILL_BATCH_SIZE);
+
+ if (!rows.length) break;
+
+ // unnest of two arrays, so this takes two bind parameters whatever the batch size.
+ // eslint-disable-next-line no-await-in-loop
+ await knex.raw(
+ `UPDATE ?? AS c SET "quotaKey" = u.key FROM unnest(?::uuid[], ?::text[]) AS u(id, key) WHERE c.id = u.id`,
+ [TableName.Certificate, rows.map((row) => row.id), rows.map((row) => buildCertificateQuotaKey(row))]
+ );
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasColumn(TableName.Certificate, "quotaKey"))) return;
+
+ await knex.schema.alterTable(TableName.Certificate, (t) => {
+ t.dropColumn("quotaKey");
+ });
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/db/migrations/20260903051600_add-certificate-quota-key-index.ts b/backend/src/db/migrations/20260903051600_add-certificate-quota-key-index.ts
new file mode 100644
index 0000000000..9e200e971e
--- /dev/null
+++ b/backend/src/db/migrations/20260903051600_add-certificate-quota-key-index.ts
@@ -0,0 +1,56 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const QUOTA_KEY_INDEX = "certificates_projectid_quotakey_index";
+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds
+
+// Serves both quota queries: the point probe and the COUNT(DISTINCT) that fills the quota cache.
+// notAfter, status and extendedKeyUsages are INCLUDE columns so the count stays an index-only scan;
+// without them every candidate row needs a heap fetch, which is material at tens of thousands.
+export async function up(knex: Knex): Promise<void> {
+ const connection = await knex.client.acquireConnection();
+ const raw = (sql: string) => knex.raw(sql).connection(connection);
+
+ try {
+ const stmtResult = await raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout as string;
+ const lockResult = await raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout as string;
+
+ try {
+ await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+
+ if (await knex.schema.hasColumn(TableName.Certificate, "quotaKey")) {
+ // An interrupted CREATE INDEX CONCURRENTLY leaves an invalid index that is never used but is
+ // still maintained on write, and IF NOT EXISTS would skip past it.
+ const invalid = await raw(
+ `SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid WHERE c.relname = '${QUOTA_KEY_INDEX}' AND NOT i.indisvalid`
+ );
+ if (invalid.rows.length > 0) {
+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${QUOTA_KEY_INDEX}"`);
+ }
+
+ await raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${QUOTA_KEY_INDEX}"
+ ON "${TableName.Certificate}" ("projectId", "quotaKey")
+ INCLUDE ("notAfter", "status", "extendedKeyUsages")
+ `);
+ }
+ } finally {
+ await raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+ } finally {
+ await knex.client.releaseConnection(connection);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${QUOTA_KEY_INDEX}"`);
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.ts
index bdf4c9ec4e..e48d3002fd 100644
--- a/backend/src/db/schemas/certificates.ts
+++ b/backend/src/db/schemas/certificates.ts
@@ -54,7 +54,8 @@ export const CertificatesSchema = z.object({
hsmKeyLabel: z.string().nullable().optional(),
hsmPublicKeySpki: zodBuffer.nullable().optional(),
subjectDomainComponents: z.string().nullable().optional(),
- orderId: z.string().uuid().default("00000000-0000-0000-0000-000000000000")
+ orderId: z.string().uuid().default("00000000-0000-0000-0000-000000000000"),
+ quotaKey: z.string().nullable().optional()
});
export type TCertificates = z.infer<typeof CertificatesSchema>;
diff --git a/backend/src/ee/services/license/__mocks__/license-fns.ts b/backend/src/ee/services/license/__mocks__/license-fns.ts
index 0bd4d10b72..913fdcb2f2 100644
--- a/backend/src/ee/services/license/__mocks__/license-fns.ts
+++ b/backend/src/ee/services/license/__mocks__/license-fns.ts
@@ -67,7 +67,6 @@ export const getDefaultOnPremFeatures = () => {
pkiScep: false,
pkiPqc: false,
caCrl: true,
- pkiWildcardSans: true,
pkiEnterpriseCaIntegrations: false,
pkiExternalIntermediateCa: false,
pkiDiscovery: false,
@@ -76,7 +75,10 @@ export const getDefaultOnPremFeatures = () => {
pkiSyncs: false,
pkiLegacyTemplates: false,
pkiCodeSigning: false,
+ maxCas: null,
maxInternalCas: null,
+ maxCertificates: null,
+ maxWildcardCertificates: null,
maxSansPerCertificate: null,
// product gating
pam: null,
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index 97d04cc09c..084a1f4616 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -118,7 +118,6 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
pkiScep: false,
pkiPqc: false,
caCrl: true,
- pkiWildcardSans: true,
pkiEnterpriseCaIntegrations: false,
pkiExternalIntermediateCa: false,
pkiDiscovery: false,
@@ -127,7 +126,13 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
pkiSyncs: false,
pkiLegacyTemplates: false,
pkiCodeSigning: false,
+ // All null on purpose: this object is also the base the cloud plan is projected onto, so a non-null
+ // default would cap every cloud org on a deploy where the License Server has not sent that key yet.
+ // The self-hosted single-CA allowance is applied in license-service.
+ maxCas: null,
maxInternalCas: null,
+ maxCertificates: null,
+ maxWildcardCertificates: null,
maxSansPerCertificate: null,
// product gating
pam: null,
diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.ts
index b99a2ee466..1e4efebd16 100644
--- a/backend/src/ee/services/license/license-service.ts
+++ b/backend/src/ee/services/license/license-service.ts
@@ -148,8 +148,16 @@ export const licenseServiceFactory = ({
}
}
- // anything that reaches here without setting an instance type is the self-hosted OSS version,
- // which keeps the default onPremFeatures.
+ // Unlicensed self-hosted gets the community single-CA allowance. Keyed on instanceType rather
+ // than on reaching this line: the offline branch above sets its type without returning, so a
+ // valid air-gapped enterprise license would otherwise be capped at one CA too.
+ //
+ // Applied here rather than in getDefaultOnPremFeatures because that object is also the cloud
+ // plan's base and getPlan's error fallback, so a non-null cap on it would cap every paid cloud
+ // org whenever the License Server is briefly unreachable.
+ if (instanceType === InstanceType.OnPrem) {
+ onPremFeatures = { ...onPremFeatures, maxCas: 1 };
+ }
} catch (error) {
logger.error(error, `init-license: encountered an error when init license`);
}
diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts
index e25cb40334..729f7b194e 100644
--- a/backend/src/ee/services/license/license-types.ts
+++ b/backend/src/ee/services/license/license-types.ts
@@ -105,10 +105,9 @@ export type TFeatureSet = {
pkiEst: boolean;
pkiScep: false;
pkiPqc: false;
- // caCrl and pkiWildcardSans default on, so self-hosted OSS keeps them; the License Server's free-plan
- // default is what withholds them on cloud.
+ // caCrl defaults on, so self-hosted OSS keeps it; the License Server's free-plan default is what
+ // withholds it on cloud.
caCrl: boolean;
- pkiWildcardSans: boolean;
pkiEnterpriseCaIntegrations: false;
pkiExternalIntermediateCa: false;
pkiDiscovery: false;
@@ -117,9 +116,16 @@ export type TFeatureSet = {
pkiSyncs: false;
pkiLegacyTemplates: false;
pkiCodeSigning: false;
- maxInternalCas: null;
- // Declared for the License Server plan map; enforcement lands with the CA/certificate counting work.
- maxSansPerCertificate: null;
+ // maxCas covers every CA type, maxInternalCas covers INTERNAL only. Both enforced, whichever binds
+ // first. Typed number | null rather than the literal null the flags above use, so consumers can
+ // name the limit in an error without casting.
+ maxCas: number | null;
+ maxInternalCas: number | null;
+ maxCertificates: number | null;
+ // Wildcards have no separate boolean gate: 0 means the plan does not include them at all, which is
+ // how the free tier withholds them. A wildcard certificate counts against maxCertificates too.
+ maxWildcardCertificates: number | null;
+ maxSansPerCertificate: number | null;
pam: null;
certManager: null;
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts
index 69ca6e8e62..0295f65eb2 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts
@@ -704,7 +704,10 @@ const processDiscoveredCertificate = async (
const serialNumber = certResult.serialNumber || certResult.fingerprint.substring(0, 40);
- const certData: TCertificatesInsert = {
+ // Deliberately not gated on the certificate quota: this is a background scan, and every PKI
+ // license gate blocks creation only. A scan can push an org past its cap, after which new
+ // issuance is refused until it upgrades or cleans up.
+ const certData: Omit<TCertificatesInsert, "quotaKey"> = {
projectId,
status: CertStatus.ACTIVE,
serialNumber: truncateString(serialNumber, DB_SHORT_VARCHAR_LIMIT) || "unknown",
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index f6f6974197..da01da3ba6 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -186,6 +186,11 @@ export const KeyStorePrefixes = {
LicenseUsageReconcileMarker: (orgId: string) => `license-usage-reconcile-${orgId}` as const,
LicenseUsageLastReported: (orgId: string, featureKey: string) =>
`license-usage-last-reported-${orgId}-${featureKey}` as const,
+ // Cached distinct active certificate quota keys per org tree. Not LicenseUsageLastReported, which
+ // counts rows and is only written on a successful License Server report.
+ PkiCertificateQuotaCount: (orgId: string) => `pki-certificate-quota-count-${orgId}` as const,
+ // Separate key rather than a JSON blob with the total, so both stay INCR-able on creation.
+ PkiWildcardCertificateQuotaCount: (orgId: string) => `pki-wildcard-certificate-quota-count-${orgId}` as const,
IdentityLockoutState: (identityId: string, authMethod: string, slug: string) =>
`lockout:identity:{${identityId}}:${authMethod}:${slug}` as const,
// Sorted set of the identity's *locked* auth methods, scored by when each lockout ends.
@@ -250,6 +255,9 @@ export const KeyStoreTtls = {
// How often a billable org's usage is re-emitted for reconciliation (demand-driven from getPlan).
LicenseUsageReconcileIntervalInSeconds: 21600, // 6 hours
LicenseUsageLastReportedInSeconds: 604800, // 7 days
+ // Short: the count drifts high as certificates expire and low when an ungated path such as a
+ // discovery scan inserts rows, and only this expiry corrects either.
+ PkiCertificateQuotaCountInSeconds: 60,
OauthAuthorizationCodeInSeconds: 600, // 10 minutes
DashboardCacheInSeconds: 600, // 10 minutes
ProjectEnvironmentOperationMarkerInSeconds: 10,
diff --git a/backend/src/lib/knex/index.ts b/backend/src/lib/knex/index.ts
index 123931fec1..974b00a510 100644
--- a/backend/src/lib/knex/index.ts
+++ b/backend/src/lib/knex/index.ts
@@ -10,6 +10,7 @@ import { buildDynamicKnexQuery, TKnexDynamicOperator } from "./dynamic";
export * from "./connection";
export * from "./join";
+export * from "./org-tree";
export * from "./prependTableNameToFindFilter";
export * from "./select";
diff --git a/backend/src/lib/knex/org-tree.ts b/backend/src/lib/knex/org-tree.ts
new file mode 100644
index 0000000000..ee381c749c
--- /dev/null
+++ b/backend/src/lib/knex/org-tree.ts
@@ -0,0 +1,19 @@
+import { Knex } from "knex";
+
+import { TableName } from "@app/db/schemas";
+
+// Root org + its sub-orgs. Quotas count over the tree because plans resolve at the root, so scoping a
+// counter to one org hands out the full allowance per sub-org.
+export const orgTreeIds = (knex: Knex, orgId: string) => {
+ const rootOrgId = knex
+ .select(knex.raw(`COALESCE("rootOrgId", "id")`))
+ .from(TableName.Organization)
+ .where("id", orgId);
+
+ return knex
+ .select("id")
+ .from(TableName.Organization)
+ .where((bd) => {
+ void bd.where("id", rootOrgId).orWhere("rootOrgId", rootOrgId);
+ });
+};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 8497818933..2f6ce0862f 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3442,6 +3442,8 @@ export const registerRoutes = async (
});
const certificateService = certificateServiceFactory({
+ usageCounterDAL,
+ keyStore,
certificateDAL,
certificateBodyDAL,
certificateSecretDAL,
@@ -3529,6 +3531,9 @@ export const registerRoutes = async (
});
const certificateApprovalService = certificateApprovalServiceFactory({
+ licenseService,
+ usageCounterDAL,
+ keyStore,
certificateRequestDAL,
certificateProfileDAL,
acmeAccountDAL,
@@ -3574,6 +3579,8 @@ export const registerRoutes = async (
});
const certificateV3Service = certificateV3ServiceFactory({
+ usageCounterDAL,
+ keyStore,
certificateDAL,
certificateSecretDAL,
certificateAuthorityDAL,
diff --git a/backend/src/services/certificate-authority/certificate-authority-dal.ts b/backend/src/services/certificate-authority/certificate-authority-dal.ts
index 02cc3013d2..f2346b67cf 100644
--- a/backend/src/services/certificate-authority/certificate-authority-dal.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-dal.ts
@@ -3,7 +3,7 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { CertificateAuthoritiesSchema, TableName, TCertificateAuthorities } from "@app/db/schemas";
import { DatabaseError, NotFoundError } from "@app/lib/errors";
-import { buildFindFilter, ormify, selectAllTableCols, TFindOpt } from "@app/lib/knex";
+import { buildFindFilter, orgTreeIds, ormify, selectAllTableCols, TFindOpt } from "@app/lib/knex";
import {
applyProcessedPermissionRulesToQuery,
type ProcessedPermissionRules
@@ -365,9 +365,8 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
}
};
- // Internal CAs (those with an internal_certificate_authorities row) across all of the org's projects,
- // excluding soft-deleted projects. Used to enforce the plan's maxInternalCas at creation time; external
- // CAs are intentionally not counted.
+ // Internal CAs across the org tree, excluding soft-deleted projects. External and ACME CAs are
+ // intentionally not counted; maxCas covers those via countCasByOrgId below.
const countInternalCasByOrgId = async (orgId: string, tx?: Knex) => {
try {
const doc = await (tx || db.replicaNode())(TableName.CertificateAuthority)
@@ -377,7 +376,7 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
`${TableName.InternalCertificateAuthority}.caId`
)
.join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.Project}.orgId`, orgId)
+ .whereIn(`${TableName.Project}.orgId`, orgTreeIds(tx || db.replicaNode(), orgId))
.whereNull(`${TableName.Project}.deleteAfter`)
.count();
return Number(doc?.[0]?.count ?? 0);
@@ -386,12 +385,29 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {
}
};
+ // Every CA type across the org tree. Counting all types rather than INTERNAL + ACME behaves
+ // identically, since tiers that set maxCas cannot create the others (pkiEnterpriseCaIntegrations
+ // blocks them) and is simpler.
+ const countCasByOrgId = async (orgId: string, tx?: Knex) => {
+ try {
+ const doc = await (tx || db.replicaNode())(TableName.CertificateAuthority)
+ .join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
+ .whereIn(`${TableName.Project}.orgId`, orgTreeIds(tx || db.replicaNode(), orgId))
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .count();
+ return Number(doc?.[0]?.count ?? 0);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count CAs By Org ID - Certificate Authority" });
+ }
+ };
+
return {
...caOrm,
findWithAssociatedCa,
buildCertificateChain,
findByIdWithAssociatedCa,
findByNameAndProjectIdWithAssociatedCa,
- countInternalCasByOrgId
+ countInternalCasByOrgId,
+ countCasByOrgId
};
};
diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts
index 627cbbe969..e1de802754 100644
--- a/backend/src/services/certificate-authority/certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts
@@ -133,6 +133,7 @@ type TCertificateAuthorityServiceFactoryDep = {
| "findWithAssociatedCa"
| "findByNameAndProjectIdWithAssociatedCa"
| "countInternalCasByOrgId"
+ | "countCasByOrgId"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update" | "findOne">;
internalCertificateAuthorityService: TInternalCertificateAuthorityServiceFactory;
@@ -333,6 +334,18 @@ export const certificateAuthorityServiceFactory = ({
});
}
+ // Two independent caps, whichever binds first: maxCas covers every type (the free tier's single
+ // "internal or ACME" allowance), maxInternalCas covers INTERNAL only and is the per-contract
+ // enterprise lever. In practice a tier sets one and leaves the other null.
+ if (typeof plan.maxCas === "number") {
+ const currentCaCount = await certificateAuthorityDAL.countCasByOrgId(actor.orgId);
+ if (currentCaCount >= plan.maxCas) {
+ throw new BadRequestError({
+ message: `Failed to create certificate authority due to plan limit reached (${currentCaCount} of ${plan.maxCas} certificate authorities). Upgrade plan to add more certificate authorities.`
+ });
+ }
+ }
+
if (type === CaType.INTERNAL) {
const internalConfig = configuration as TCreateInternalCertificateAuthorityDTO["configuration"];
@@ -340,8 +353,7 @@ export const certificateAuthorityServiceFactory = ({
const currentInternalCaCount = await certificateAuthorityDAL.countInternalCasByOrgId(actor.orgId);
if (currentInternalCaCount >= plan.maxInternalCas) {
throw new BadRequestError({
- message:
- "Failed to create internal certificate authority due to plan limit reached. Upgrade plan to add more internal certificate authorities."
+ message: `Failed to create internal certificate authority due to plan limit reached (${currentInternalCaCount} of ${plan.maxInternalCas} internal certificate authorities). Upgrade plan to add more internal certificate authorities.`
});
}
}
diff --git a/backend/src/services/certificate-common/certificate-quota-fns.ts b/backend/src/services/certificate-common/certificate-quota-fns.ts
new file mode 100644
index 0000000000..d5c8e0bd9e
--- /dev/null
+++ b/backend/src/services/certificate-common/certificate-quota-fns.ts
@@ -0,0 +1,146 @@
+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { isWildcardPattern } from "@app/services/certificate-policy/certificate-policy-fns";
+import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+
+import { buildCertificateQuotaKey } from "./certificate-quota-key";
+
+type TQuotaCounts = { total: number; wildcard: number };
+
+export type TCertificateQuotaDeps = {
+ projectDAL: Pick<TProjectDALFactory, "findById">;
+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ "countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
+ >;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
+};
+
+const $getQuotaCounts = async (orgId: string, deps: TCertificateQuotaDeps): Promise<TQuotaCounts> => {
+ const totalKey = KeyStorePrefixes.PkiCertificateQuotaCount(orgId);
+ const wildcardKey = KeyStorePrefixes.PkiWildcardCertificateQuotaCount(orgId);
+
+ const [cachedTotal, cachedWildcard] = await Promise.all([
+ deps.keyStore.getItem(totalKey),
+ deps.keyStore.getItem(wildcardKey)
+ ]);
+ if (cachedTotal !== null && cachedWildcard !== null) {
+ const total = Number(cachedTotal);
+ const wildcard = Number(cachedWildcard);
+ if (Number.isFinite(total) && Number.isFinite(wildcard)) return { total, wildcard };
+ }
+
+ const counts = await deps.usageCounterDAL.countActiveCertificateQuotaKeysByOrg(orgId);
+ const ttl = KeyStoreTtls.PkiCertificateQuotaCountInSeconds;
+ await Promise.all([
+ deps.keyStore.setItemWithExpiry(totalKey, ttl, String(counts.total)),
+ deps.keyStore.setItemWithExpiry(wildcardKey, ttl, String(counts.wildcard))
+ ]);
+
+ return counts;
+};
+
+// Call once a certificate with a new quota key has actually been written. Drops the cached counts
+// rather than incrementing them: incrementByWithExpiry re-sets the TTL on every call, so a steadily
+// issuing org would roll the expiry forward indefinitely and never see a revocation or an expiry.
+// Never throws, since a stale cache is cheaper than failing a certificate that was already granted.
+export const recordNewCertificateQuotaKey = async (
+ orgId: string,
+ deps: Pick<TCertificateQuotaDeps, "keyStore">,
+ isWildcard = false
+): Promise<void> => {
+ try {
+ await deps.keyStore.deleteItem(KeyStorePrefixes.PkiCertificateQuotaCount(orgId));
+ if (isWildcard) await deps.keyStore.deleteItem(KeyStorePrefixes.PkiWildcardCertificateQuotaCount(orgId));
+ } catch (error) {
+ logger.error(error, `Failed to reset certificate quota cache [orgId=${orgId}]`);
+ }
+};
+
+// Nothing locks between this check and the insert, so the caps are commercial limits with bounded
+// overshoot rather than hard boundaries.
+export const assertCertificateQuota = async ({
+ orgId,
+ commonName,
+ altNames,
+ deps,
+ isApprovedRequest = false
+}: {
+ orgId: string;
+ commonName?: string | null;
+ altNames?: string | null;
+ deps: TCertificateQuotaDeps;
+ isApprovedRequest?: boolean;
+ // quotaOrgId is the tree root the cache is keyed on. Callers must pass it back to
+ // recordNewCertificateQuotaKey rather than their own orgId.
+}): Promise<{ quotaKey: string; isNewQuotaKey: boolean; quotaOrgId: string; isWildcard: boolean }> => {
+ const quotaKey = buildCertificateQuotaKey({ commonName, altNames });
+ const isWildcard = [commonName ?? "", ...(altNames ?? "").split(",")].some(isWildcardPattern);
+ const plan = await deps.licenseService.getPlan(orgId);
+ const unlimited = { quotaKey, isNewQuotaKey: false, quotaOrgId: orgId, isWildcard };
+
+ const { maxCertificates, maxWildcardCertificates } = plan;
+ const hasWildcardCap = isWildcard && typeof maxWildcardCertificates === "number";
+ if (typeof maxCertificates !== "number" && !hasWildcardCap) return unlimited;
+
+ // Correctness, not an optimization: reissuing names the org already holds cannot raise either count,
+ // and this is what lets an org sitting at its cap keep renewing. Remove it and its certs expire.
+ const isAlreadyActive = await deps.usageCounterDAL.isCertificateQuotaKeyActiveInOrg(orgId, quotaKey);
+ const quotaOrgId = await deps.usageCounterDAL.resolveRootOrgId(orgId);
+ if (isAlreadyActive) return { quotaKey, isNewQuotaKey: false, quotaOrgId, isWildcard };
+
+ // 0 is how a plan says it has no wildcard support at all.
+ if (isWildcard && maxWildcardCertificates === 0) {
+ throw new BadRequestError({
+ message: `Failed to issue certificate with a wildcard name due to plan restriction. Upgrade plan to issue wildcard certificates.`
+ });
+ }
+
+ const counts = await $getQuotaCounts(quotaOrgId, deps);
+
+ const refuse = (used: number, cap: number, subject: string) => {
+ if (isApprovedRequest) {
+ throw new BadRequestError({
+ message: `This certificate request was approved, but your organization has since reached its plan limit of ${cap} ${subject} (${used} of ${cap} in use). Upgrade plan or revoke an unused certificate, then submit the request again.`
+ });
+ }
+ throw new BadRequestError({
+ message: `Failed to issue certificate due to plan limit reached (${used} of ${cap} ${subject}). Upgrade plan to issue more certificates.`
+ });
+ };
+
+ // Before the total, so the refusal names the limit the caller actually hit.
+ if (hasWildcardCap && counts.wildcard >= maxWildcardCertificates) {
+ refuse(counts.wildcard, maxWildcardCertificates, "active wildcard certificates");
+ }
+
+ if (typeof maxCertificates === "number" && counts.total >= maxCertificates) {
+ refuse(counts.total, maxCertificates, "active certificates");
+ }
+
+ return { quotaKey, isNewQuotaKey: true, quotaOrgId, isWildcard };
+};
+
+/** Same check for callers holding a projectId. Returns the orgId so usage can be recorded after the write. */
+export const assertCertificateQuotaForProject = async ({
+ projectId,
+ commonName,
+ altNames,
+ deps,
+ isApprovedRequest = false
+}: {
+ projectId: string;
+ commonName?: string | null;
+ altNames?: string | null;
+ deps: TCertificateQuotaDeps;
+ isApprovedRequest?: boolean;
+}): Promise<{ quotaKey: string; isNewQuotaKey: boolean; quotaOrgId: string; isWildcard: boolean }> => {
+ const project = await deps.projectDAL.findById(projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+
+ return assertCertificateQuota({ orgId: project.orgId, commonName, altNames, deps, isApprovedRequest });
+};
diff --git a/backend/src/services/certificate-common/certificate-quota-key.test.ts b/backend/src/services/certificate-common/certificate-quota-key.test.ts
new file mode 100644
index 0000000000..ff7947e42b
--- /dev/null
+++ b/backend/src/services/certificate-common/certificate-quota-key.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest";
+
+import { buildCertificateQuotaKey } from "./certificate-quota-key";
+
+const CN_ONLY = "ac8da107e6e4e13b34d491fb0eb4093d907a7f4cfad7772c1146a72c41791887";
+const CN_PLUS_TWO_SANS = "fbdbe1005e3a5b5bc197281b552c0b66882f6c1ffbe797a193c4f0fb2b407042";
+
+describe("buildCertificateQuotaKey", () => {
+ // Pinned, so changing the canonicalization fails here rather than silently re-hashing the fleet.
+ it("pins the hash for a known input", () => {
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: null })).toBe(CN_ONLY);
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: "a.example.com,b.example.com" })).toBe(
+ CN_PLUS_TWO_SANS
+ );
+ });
+
+ it("is stable across SAN ordering", () => {
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: "b.example.com,a.example.com" })).toBe(
+ CN_PLUS_TWO_SANS
+ );
+ });
+
+ it("treats ', ' and ',' separators as equivalent", () => {
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: "a.example.com, b.example.com" })).toBe(
+ CN_PLUS_TWO_SANS
+ );
+ });
+
+ it("treats null, undefined and empty-string altNames as equivalent", () => {
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: null })).toBe(CN_ONLY);
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: "" })).toBe(CN_ONLY);
+ expect(buildCertificateQuotaKey({ commonName: "example.com" })).toBe(CN_ONLY);
+ });
+
+ it("is case insensitive", () => {
+ expect(buildCertificateQuotaKey({ commonName: "EXAMPLE.com", altNames: "A.Example.COM,b.example.com" })).toBe(
+ CN_PLUS_TWO_SANS
+ );
+ });
+
+ it("ignores duplicate SANs", () => {
+ expect(
+ buildCertificateQuotaKey({ commonName: "example.com", altNames: "a.example.com,a.example.com,b.example.com" })
+ ).toBe(CN_PLUS_TWO_SANS);
+ });
+
+ it("ignores surrounding whitespace and empty entries", () => {
+ expect(
+ buildCertificateQuotaKey({ commonName: " example.com ", altNames: " a.example.com , b.example.com " })
+ ).toBe(CN_PLUS_TWO_SANS);
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: "a.example.com,,b.example.com" })).toBe(
+ CN_PLUS_TWO_SANS
+ );
+ });
+
+ it("distinguishes certificates that are genuinely different", () => {
+ const base = buildCertificateQuotaKey({ commonName: "example.com", altNames: "a.example.com" });
+
+ expect(buildCertificateQuotaKey({ commonName: "other.com", altNames: "a.example.com" })).not.toBe(base);
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: "b.example.com" })).not.toBe(base);
+ expect(buildCertificateQuotaKey({ commonName: "example.com", altNames: "a.example.com,b.example.com" })).not.toBe(
+ base
+ );
+ // A SAN moving into the common name is a different certificate, not the same one.
+ expect(buildCertificateQuotaKey({ commonName: "a.example.com", altNames: "example.com" })).not.toBe(base);
+ });
+});
diff --git a/backend/src/services/certificate-common/certificate-quota-key.ts b/backend/src/services/certificate-common/certificate-quota-key.ts
new file mode 100644
index 0000000000..9da1c408d4
--- /dev/null
+++ b/backend/src/services/certificate-common/certificate-quota-key.ts
@@ -0,0 +1,20 @@
+import { createHash } from "node:crypto";
+
+// Identity of "one logical certificate" for quotas. orderId already collapses renewal chains; this
+// exists for re-enrollment, where ACME mints a new order for the same names every cycle.
+export const buildCertificateQuotaKey = ({
+ commonName,
+ altNames
+}: {
+ commonName?: string | null;
+ altNames?: string | null;
+}): string => {
+ const sans = (altNames ?? "")
+ .split(",")
+ .map((san) => san.trim().toLowerCase())
+ .filter(Boolean);
+ const cn = (commonName ?? "").trim().toLowerCase();
+ const canonical = `CN=${cn}|SAN=${[...new Set(sans)].sort().join(",")}`;
+
+ return createHash("sha256").update(canonical).digest("hex");
+};
diff --git a/backend/src/services/certificate-common/certificate-utils.ts b/backend/src/services/certificate-common/certificate-utils.ts
index 2839cf2915..6493e4f27e 100644
--- a/backend/src/services/certificate-common/certificate-utils.ts
+++ b/backend/src/services/certificate-common/certificate-utils.ts
@@ -3,7 +3,7 @@ import RE2 from "re2";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { isPqcAlgorithm } from "@app/lib/crypto/pqc";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { isWildcardPattern, matchesNormalizedPattern } from "@app/services/certificate-policy/certificate-policy-fns";
+import { matchesNormalizedPattern } from "@app/services/certificate-policy/certificate-policy-fns";
import { TSubjectRule } from "@app/services/certificate-policy/certificate-policy-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -16,6 +16,7 @@ import {
mapLegacyExtendedKeyUsageToStandard,
mapLegacyKeyUsageToStandard
} from "./certificate-constants";
+import { assertCertificateQuota, TCertificateQuotaDeps } from "./certificate-quota-fns";
export const validatePqcLicense = async ({
keyAlgorithm,
@@ -42,11 +43,15 @@ export const validatePqcLicense = async ({
// Call with the request as it will actually be signed. A PQC algorithm or wildcard that only appears
// in a CSR or a profile default is invisible until applyProfileDefaults has run.
+//
+// Submit-time gate only; certificate-approval-fns re-checks the caps when it materializes an approval.
export const validateCertificateRequestLicense = async ({
request,
projectId,
projectDAL,
- licenseService
+ licenseService,
+ quotaDeps,
+ isRenewal = false
}: {
request: {
keyAlgorithm?: string;
@@ -60,17 +65,20 @@ export const validateCertificateRequestLicense = async ({
projectId: string;
projectDAL: Pick<TProjectDALFactory, "findById">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ // When absent the caps are skipped, so an issuance entry point that forgets it is silently uncapped.
+ quotaDeps?: TCertificateQuotaDeps;
+ // Nothing sets this today: renewal does not route through here. Kept because a refused renewal lets
+ // a live certificate expire, so the exemption should already exist if that ever changes.
+ isRenewal?: boolean;
}) => {
const pqcAlgorithm = [request.keyAlgorithm, request.signatureAlgorithm].find(
(algorithm): algorithm is string => !!algorithm && isPqcAlgorithm(algorithm)
);
- const wildcardSan = [
- ...(request.commonName ? [request.commonName] : []),
- ...(request.altNames ?? []).map(({ value }) => value),
- ...(request.subjectAlternativeNames ?? []).map(({ value }) => value)
- ].find(isWildcardPattern);
- if (!pqcAlgorithm && !wildcardSan) return;
+ const requestedSans = [...(request.altNames ?? []), ...(request.subjectAlternativeNames ?? [])].map(
+ ({ value }) => value
+ );
+ const distinctSanCount = new Set(requestedSans.map((value) => value.trim().toLowerCase()).filter(Boolean)).size;
const project = await projectDAL.findById(projectId);
if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
@@ -84,11 +92,23 @@ export const validateCertificateRequestLicense = async ({
});
}
- if (wildcardSan && !plan.pkiWildcardSans) {
+ const { maxSansPerCertificate } = plan;
+ if (typeof maxSansPerCertificate === "number" && distinctSanCount > maxSansPerCertificate) {
throw new BadRequestError({
- message: `Failed to issue certificate with wildcard name '${wildcardSan}' due to plan restriction. Upgrade plan to issue wildcard certificates.`
+ message: `This certificate requests ${distinctSanCount} subject alternative names, above the ${maxSansPerCertificate} allowed on your plan. Upgrade plan to issue certificates with more SANs.`
});
}
+
+ if (!quotaDeps || isRenewal) return undefined;
+
+ const { isNewQuotaKey, quotaOrgId, isWildcard } = await assertCertificateQuota({
+ orgId: project.orgId,
+ commonName: request.commonName,
+ altNames: requestedSans.join(","),
+ deps: quotaDeps
+ });
+
+ return { orgId: quotaOrgId, isNewQuotaKey, isWildcard };
};
interface CertificateRequestInput {
diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.ts
index 5bb2f5f677..6581a6b6d5 100644
--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts
+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts
@@ -2,12 +2,14 @@ import { ForbiddenError, subject } from "@casl/ability";
import { randomUUID } from "crypto";
import { ActionProjectType } from "@app/db/schemas";
+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionCertificateProfileActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { TPkiAcmeAccountDALFactory } from "@app/ee/services/pki-acme/pki-acme-account-dal";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
@@ -34,6 +36,7 @@ import { TCertificateProfileDALFactory } from "@app/services/certificate-profile
import { EnrollmentType, IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-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";
@@ -54,6 +57,10 @@ import {
validateAlgorithmCompatibility,
validateCaSupport
} from "../certificate-common/certificate-issuance-utils";
+import {
+ assertCertificateQuotaForProject,
+ recordNewCertificateQuotaKey
+} from "../certificate-common/certificate-quota-fns";
import {
bufferToString,
buildCertificateSubjectFromTemplate,
@@ -85,6 +92,12 @@ export type TIssueCertificateFromApprovedRequestDeps = {
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;
pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;
apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ "countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
+ >;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
};
export type TCertificateApprovalService = {
@@ -185,6 +198,9 @@ export const certificateApprovalServiceFactory = (
certificateSecretDAL,
kmsService,
projectDAL,
+ licenseService,
+ usageCounterDAL,
+ keyStore,
certificatePolicyService,
certificateIssuanceQueue,
resourceMetadataDAL,
@@ -519,6 +535,23 @@ export const certificateApprovalServiceFactory = (
mappedReconstructedRequest.basicConstraints = effectiveBasicConstraints;
}
+ // Same re-check the non-CSR branch does: this path returns before that one runs, and an approval
+ // can land days after the count it was compared against at submit.
+ const {
+ quotaOrgId: csrQuotaOrgId,
+ isNewQuotaKey: isNewCsrQuotaKey,
+ isWildcard: isCsrWildcard
+ } = await assertCertificateQuotaForProject({
+ projectId: profile.projectId,
+ commonName: mappedReconstructedRequest.commonName,
+ // A CSR-derived request carries its SANs in subjectAlternativeNames, not altNames.
+ altNames: (mappedReconstructedRequest.subjectAlternativeNames ?? [])
+ .map((san: { value: string }) => san.value)
+ .join(","),
+ deps: { projectDAL, licenseService, usageCounterDAL, keyStore },
+ isApprovedRequest: true
+ });
+
const revalidationResult = await certificatePolicyService.validateCertificateRequest(
profile.certificatePolicyId,
mappedReconstructedRequest
@@ -610,6 +643,8 @@ export const certificateApprovalServiceFactory = (
const certificateString = extractCertificateFromBuffer(certificate as unknown as Buffer);
const certificateChainString = extractCertificateFromBuffer(certificateChain as unknown as Buffer);
+ if (isNewCsrQuotaKey) await recordNewCertificateQuotaKey(csrQuotaOrgId, { keyStore }, isCsrWildcard);
+
return {
status: CertificateRequestStatus.ISSUED,
certificate: certificateString,
@@ -648,6 +683,16 @@ export const certificateApprovalServiceFactory = (
return null;
}
+ // This branch returns before the shared re-check below, so it needs its own. Not recorded: the
+ // issuance queue creates the certificate later, once the external CA responds.
+ await assertCertificateQuotaForProject({
+ projectId: profile.projectId,
+ commonName: certRequest.commonName,
+ altNames: (altNames ?? []).map((san) => san.value).join(","),
+ deps: { projectDAL, licenseService, usageCounterDAL, keyStore },
+ isApprovedRequest: true
+ });
+
// Pre-flight validation for ACM — fail the approval synchronously rather than
// letting the job produce a FAILED request row after the approver already accepted.
if (caType === CaType.AWS_ACM_PUBLIC_CA) {
@@ -1105,25 +1150,39 @@ export const certificateApprovalServiceFactory = (
});
}
- const issuerType = targetProfile?.issuerType || (targetProfile?.caId ? IssuerType.CA : IssuerType.SELF_SIGNED);
+ // Re-checked here as well as at submit: an approval can land days later, so the count compared
+ // against at submit says nothing about current usage. Not pushed into certificateDAL.create,
+ // which would also gate discovery and renewal writes.
+ const { quotaOrgId, isNewQuotaKey, isWildcard } = await assertCertificateQuotaForProject({
+ projectId: targetProfile.projectId,
+ commonName: certificateRequestInput.commonName,
+ altNames: (altNames ?? []).map((san) => san.value).join(","),
+ deps: { projectDAL, licenseService, usageCounterDAL, keyStore },
+ isApprovedRequest: true
+ });
- if (issuerType === IssuerType.SELF_SIGNED) {
- return await $processSelfSignedRequest(
- certificateRequestInput,
- certificateRequestId,
- targetProfile,
- certPolicy,
- certRequest.applicationId
- );
- }
+ const issuerType = targetProfile?.issuerType || (targetProfile?.caId ? IssuerType.CA : IssuerType.SELF_SIGNED);
- return await $processCASignedRequest(
- certificateRequestInput,
- certificateRequestId,
- targetProfile,
- certPolicy,
- certRequest.applicationId
- );
+ const issuanceResult =
+ issuerType === IssuerType.SELF_SIGNED
+ ? await $processSelfSignedRequest(
+ certificateRequestInput,
+ certificateRequestId,
+ targetProfile,
+ certPolicy,
+ certRequest.applicationId
+ )
+ : await $processCASignedRequest(
+ certificateRequestInput,
+ certificateRequestId,
+ targetProfile,
+ certPolicy,
+ certRequest.applicationId
+ );
+
+ if (isNewQuotaKey) await recordNewCertificateQuotaKey(quotaOrgId, { keyStore }, isWildcard);
+
+ return issuanceResult;
} catch (error) {
await certificateRequestDAL.updateById(certificateRequestId, {
status: CertificateRequestStatus.FAILED,
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 d9a9be4191..bbdc6c121a 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts
@@ -101,6 +101,7 @@ describe("CertificateV3Service", () => {
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>) => {
@@ -330,6 +331,16 @@ 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 })
},
@@ -478,6 +489,7 @@ describe("CertificateV3Service", () => {
revokedBy: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
};
@@ -965,6 +977,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
};
@@ -1061,6 +1074,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord);
@@ -1266,6 +1280,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
};
@@ -1663,6 +1678,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
@@ -1688,6 +1704,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
@@ -1713,6 +1730,7 @@ describe("CertificateV3Service", () => {
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>) => {
@@ -1833,6 +1851,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
@@ -1858,6 +1877,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
@@ -1883,6 +1903,7 @@ describe("CertificateV3Service", () => {
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>) => {
@@ -2003,6 +2024,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
@@ -2028,6 +2050,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
@@ -2053,6 +2076,7 @@ describe("CertificateV3Service", () => {
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>) => {
@@ -2173,6 +2197,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.updateById).mockResolvedValue({
@@ -2198,6 +2223,7 @@ describe("CertificateV3Service", () => {
profileId: null,
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
});
vi.mocked(mockCertificateDAL.findById).mockResolvedValue({
@@ -2223,6 +2249,7 @@ describe("CertificateV3Service", () => {
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>) => {
@@ -2273,6 +2300,7 @@ describe("CertificateV3Service", () => {
signatureAlgorithm: "RSA-SHA256",
source: "issued",
keySource: "infisical",
+ quotaKey: "a".repeat(64),
orderId: "00000000-0000-0000-0000-000000000000"
};
diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts
index b3ff6894c3..9a40bc2869 100644
--- a/backend/src/services/certificate-v3/certificate-v3-service.ts
+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts
@@ -14,6 +14,7 @@ import {
ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
import { TPkiAcmeAccountDALFactory } from "@app/ee/services/pki-acme/pki-acme-account-dal";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
@@ -40,12 +41,14 @@ import { assertCaInProfileProject } from "@app/services/certificate-authority/ce
import { caUsesExternalIssuanceQueue } from "@app/services/certificate-authority/certificate-authority-maps";
import { validateGoDaddyIssuanceInputs } from "@app/services/certificate-authority/godaddy/godaddy-certificate-authority-validators";
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
+import { recordNewCertificateQuotaKey } from "@app/services/certificate-common/certificate-quota-fns";
import { TCertificatePolicyServiceFactory } from "@app/services/certificate-policy/certificate-policy-service";
import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import { EnrollmentType, IssuerType } from "@app/services/certificate-profile/certificate-profile-types";
import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -172,6 +175,11 @@ type TCertificateV3ServiceFactoryDep = {
>;
apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ "countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
+ >;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
};
@@ -332,8 +340,16 @@ export const certificateV3ServiceFactory = ({
pkiApplicationProfileDAL,
apiEnrollmentConfigDAL,
licenseService,
+ usageCounterDAL,
+ keyStore,
telemetryService
}: TCertificateV3ServiceFactoryDep) => {
+ const $quotaDeps = { projectDAL, licenseService, usageCounterDAL, keyStore };
+
+ // Called once the certificate row exists, never at the check.
+ const $recordQuotaUsage = async (usage?: { orgId: string; isNewQuotaKey: boolean; isWildcard: boolean }) => {
+ if (usage?.isNewQuotaKey) await recordNewCertificateQuotaKey(usage.orgId, { keyStore }, usage.isWildcard);
+ };
const $reportCertificateIssued = async ({
orgId,
projectId,
@@ -550,11 +566,12 @@ export const certificateV3ServiceFactory = ({
const certificateRequestWithDefaults = applyProfileDefaults(certificateRequest, profile.defaults);
- await validateCertificateRequestLicense({
+ const quotaUsage = await validateCertificateRequestLicense({
request: certificateRequestWithDefaults,
projectId: profile.projectId,
projectDAL,
- licenseService
+ licenseService,
+ quotaDeps: $quotaDeps
});
if (matchedApprovalPolicy && !shouldBypassApproval(actor, matchedApprovalPolicy)) {
@@ -1177,6 +1194,8 @@ export const certificateV3ServiceFactory = ({
actorId
});
+ await $recordQuotaUsage(quotaUsage);
+
return {
status: CertificateRequestStatus.ISSUED,
certificate: bufferToString(certificate),
@@ -1268,11 +1287,12 @@ export const certificateV3ServiceFactory = ({
mappedCertificateRequest.signatureAlgorithm = extractedSignatureAlgorithm;
// Also the gate for ACME, SCEP and EST, which all reach issuance through here.
- await validateCertificateRequestLicense({
+ const quotaUsage = await validateCertificateRequestLicense({
request: mappedCertificateRequest,
projectId: profile.projectId,
projectDAL,
- licenseService
+ licenseService,
+ quotaDeps: $quotaDeps
});
// When notAfter is explicitly provided, validate using date range (notAfter overrides TTL in cert generation).
@@ -1636,6 +1656,8 @@ export const certificateV3ServiceFactory = ({
actorId
});
+ await $recordQuotaUsage(quotaUsage);
+
return {
status: CertificateRequestStatus.ISSUED,
certificate: certificateString,
@@ -1745,11 +1767,14 @@ export const certificateV3ServiceFactory = ({
mappedCertificateRequest.signatureAlgorithm = extractedSignatureAlgorithm;
}
+ // Not recorded here: the issuance queue creates the certificate later, once the external CA
+ // responds, so the cached count picks it up on its next refresh.
await validateCertificateRequestLicense({
request: mappedCertificateRequest,
projectId: profile.projectId,
projectDAL,
- licenseService
+ licenseService,
+ quotaDeps: $quotaDeps
});
const validationResult = await certificatePolicyService.validateCertificateRequest(
diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts
index 2fd1e30d70..7702d2fa45 100644
--- a/backend/src/services/certificate/certificate-dal.ts
+++ b/backend/src/services/certificate/certificate-dal.ts
@@ -1,7 +1,7 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { TableName, TCertificates } from "@app/db/schemas";
+import { TableName, TCertificates, TCertificatesInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
import { sanitizeSqlLikeString } from "@app/lib/fn/string";
import { ormify, selectAllTableCols } from "@app/lib/knex";
@@ -14,6 +14,7 @@ import {
mapExtendedKeyUsageToLegacy,
mapLegacyExtendedKeyUsageToStandard
} from "@app/services/certificate-common/certificate-constants";
+import { buildCertificateQuotaKey } from "@app/services/certificate-common/certificate-quota-key";
import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";
import { keySizeToAlgorithms } from "./certificate-fns";
@@ -48,6 +49,16 @@ const toLegacyExtendedKeyUsageForQuery = (usage: string): string => {
export const certificateDALFactory = (db: TDbClient) => {
const certificateOrm = ormify(db, TableName.Certificate);
+ // Every certificate insert funnels through here, so no site can forget the quota key.
+ const create = async (data: Omit<TCertificatesInsert, "quotaKey">, tx?: Knex) =>
+ certificateOrm.create(
+ {
+ ...data,
+ quotaKey: buildCertificateQuotaKey({ commonName: data.commonName, altNames: data.altNames })
+ },
+ tx
+ );
+
const findLatestActiveCertForSubscriber = async ({ subscriberId }: { subscriberId: string }) => {
try {
const cert = await db
@@ -1242,6 +1253,7 @@ export const certificateDALFactory = (db: TDbClient) => {
return {
...certificateOrm,
+ create,
countCertificatesInProject,
countActiveCertificatesForSync,
countCertificatesForPkiSubscriber,
diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts
index 393be02e12..81cf19bbeb 100644
--- a/backend/src/services/certificate/certificate-service.ts
+++ b/backend/src/services/certificate/certificate-service.ts
@@ -14,6 +14,7 @@ import {
ResourcePermissionCertificateActions,
ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -25,11 +26,16 @@ import { CaCapability, CaType } from "@app/services/certificate-authority/certif
import { caSupportsCapability } from "@app/services/certificate-authority/certificate-authority-maps";
import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
+import {
+ assertCertificateQuotaForProject,
+ recordNewCertificateQuotaKey
+} from "@app/services/certificate-common/certificate-quota-fns";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import type { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { ActiveCerts } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
+import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usage-counter-dal";
import { TPkiAlertV2QueueServiceFactory } from "@app/services/pki-alert-v2/pki-alert-v2-queue";
import { PkiAlertEventType } from "@app/services/pki-alert-v2/pki-alert-v2-types";
import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
@@ -109,6 +115,11 @@ type TCertificateServiceFactoryDep = {
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;
pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
+ usageCounterDAL: Pick<
+ TUsageCounterDALFactory,
+ "countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"
+ >;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;
hsmConnectorService: Pick<THsmConnectorServiceFactory, "sign">;
};
@@ -136,6 +147,8 @@ export const certificateServiceFactory = ({
pkiAlertV2Queue,
pkiApplicationDAL,
licenseService,
+ usageCounterDAL,
+ keyStore,
usageMeteringService,
hsmConnectorService
}: TCertificateServiceFactoryDep) => {
@@ -945,6 +958,15 @@ export const certificateServiceFactory = ({
? (await kmsEncryptor({ plainText: Buffer.from(chainPem) })).cipherTextBlob
: null;
+ // Imported certificates count toward the quota, so import is gated like issuance. Before the
+ // transaction, since this reads the plan and may run a count.
+ const { quotaOrgId, isNewQuotaKey, isWildcard } = await assertCertificateQuotaForProject({
+ projectId,
+ commonName,
+ altNames,
+ deps: { projectDAL, licenseService, usageCounterDAL, keyStore }
+ });
+
const cert = await certificateDAL.transaction(async (tx) => {
try {
// Extract certificate fields for storage
@@ -1012,6 +1034,8 @@ export const certificateServiceFactory = ({
}
});
+ if (isNewQuotaKey) await recordNewCertificateQuotaKey(quotaOrgId, { keyStore }, isWildcard);
+
usageMeteringService.emitForProject(projectId, ActiveCerts.key);
return {
diff --git a/backend/src/services/license-client/feature-mapping.ts b/backend/src/services/license-client/feature-mapping.ts
index fae994b28f..890887e84a 100644
--- a/backend/src/services/license-client/feature-mapping.ts
+++ b/backend/src/services/license-client/feature-mapping.ts
@@ -263,11 +263,6 @@ const certManagerMappings: TFeatureMapping[] = [
v2Key: "pki_code_signing",
v1Field: "pkiCodeSigning"
},
- {
- // Defaults on, so the free plan has to send false; the features below default off instead.
- v2Key: "pki_wildcard_sans",
- v1Field: "pkiWildcardSans"
- },
{
v2Key: "pki_enterprise_ca_integrations",
v1Field: "pkiEnterpriseCaIntegrations"
@@ -293,10 +288,20 @@ const certManagerMappings: TFeatureMapping[] = [
v1Field: "pkiSyncs"
},
{
- // Declared for completeness; enforcement lands with the CA/certificate counting work.
v2Key: "max_sans_per_certificate",
v1Field: "maxSansPerCertificate"
},
+ {
+ // Counted by quotaKey rather than by row, so a renewal or re-enrollment is not a second unit.
+ v2Key: "max_certificates",
+ v1Field: "maxCertificates"
+ },
+ {
+ // Wildcard certificates, counted the same way. 0 means the plan has no wildcard support at all,
+ // which is how the free tier withholds them; these also count toward max_certificates.
+ v2Key: "max_wildcard_certificates",
+ v1Field: "maxWildcardCertificates"
+ },
{
// v2's `internal_cas` is a usage meter; the internal-CA cap is a separate v2 feature
// (max_internal_cas) mapped below, so the meter itself maps to no v1 field.
@@ -308,9 +313,16 @@ const certManagerMappings: TFeatureMapping[] = [
v1Field: null
},
{
- // Max internal CAs allowed. Dedicated cap feature, separate from the `internal_cas` usage meter.
+ // Dedicated cap feature, separate from the `internal_cas` usage meter though both count the same
+ // set. The per-contract enterprise lever: caps internal CAs, leaves external and ACME unlimited.
v2Key: "max_internal_cas",
v1Field: "maxInternalCas"
+ },
+ {
+ // Separate from max_internal_cas because the tiers differ: free grants one CA of either kind,
+ // enterprise caps internal CAs only. Both enforced, whichever binds first.
+ v2Key: "max_cas",
+ v1Field: "maxCas"
}
];
diff --git a/backend/src/services/license-client/usage/usage-counter-dal.ts b/backend/src/services/license-client/usage/usage-counter-dal.ts
index efbfb4fe38..3763b7756a 100644
--- a/backend/src/services/license-client/usage/usage-counter-dal.ts
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -1,15 +1,18 @@
+import { Knex } from "knex";
+
import { TDbClient } from "@app/db";
import { AccessScope, ProjectType, TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
+import { orgTreeIds } from "@app/lib/knex";
import { CertStatus } from "@app/services/certificate/certificate-types";
+import { CertExtendedKeyUsage, CertExtendedKeyUsageType } from "@app/services/certificate-common/certificate-constants";
export type TUsageCounterDALFactory = ReturnType<typeof usageCounterDALFactory>;
const toCount = (row: unknown): number => Number((row as { count?: string | number } | undefined)?.count ?? 0);
-// Live counts for the project-scoped metered features. Each sums across the org's projects,
-// excluding soft-deleted projects so they don't inflate a quota. Org-scoped identities are
-// counted via licenseDAL.countOrgUsersAndIdentities and wired in usage-counters.ts.
+// Live counts for the project-scoped metered features, summed across the whole org tree and excluding
+// soft-deleted projects so they don't inflate a quota.
export const usageCounterDALFactory = (db: TDbClient) => {
const countInternalCas = async (orgId: string): Promise<number> => {
try {
@@ -21,7 +24,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {
`${TableName.InternalCertificateAuthority}.caId`
)
.join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.Project}.orgId`, orgId)
+ .whereIn(`${TableName.Project}.orgId`, orgTreeIds(db.replicaNode(), orgId))
.whereNull(`${TableName.Project}.deleteAfter`)
.count(`${TableName.CertificateAuthority}.id as count`)
.first();
@@ -36,7 +39,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {
const row = await db
.replicaNode()(TableName.Certificate)
.join(TableName.Project, `${TableName.Certificate}.projectId`, `${TableName.Project}.id`)
- .where(`${TableName.Project}.orgId`, orgId)
+ .whereIn(`${TableName.Project}.orgId`, orgTreeIds(db.replicaNode(), orgId))
.whereNull(`${TableName.Project}.deleteAfter`)
.where(`${TableName.Certificate}.status`, CertStatus.ACTIVE)
.where(`${TableName.Certificate}.notAfter`, ">", new Date())
@@ -50,6 +53,78 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
+ // Matched on EKU rather than a pki_signers join, which tracks only a signer's current certificate
+ // and would recount it on renewal. The COALESCE is required: extendedKeyUsages is nullable and
+ // `NULL && ARRAY[...]` is NULL, which fails the WHERE and drops every EKU-less certificate.
+ const $excludeCodeSigningCertificates = (qb: Knex.QueryBuilder) =>
+ qb.whereRaw(`NOT (COALESCE(??, '{}') && ?::text[])`, [
+ `${TableName.Certificate}.extendedKeyUsages`,
+ [CertExtendedKeyUsageType.CODE_SIGNING, CertExtendedKeyUsage.CODE_SIGNING]
+ ]);
+
+ // No `status = 'active'` filter: nothing writes EXPIRED or RENEWED, both are derived at read time.
+ const $activeQuotaCertificates = (orgId: string) => {
+ const qb = db
+ .replicaNode()(TableName.Certificate)
+ .join(TableName.Project, `${TableName.Certificate}.projectId`, `${TableName.Project}.id`)
+ .whereIn(`${TableName.Project}.orgId`, orgTreeIds(db.replicaNode(), orgId))
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .where(`${TableName.Certificate}.notAfter`, ">", new Date())
+ .whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED);
+
+ return $excludeCodeSigningCertificates(qb);
+ };
+
+ // The count spans the org tree, so its cache must be keyed on the root: per-org keys would give each
+ // sub-org its own copy that only its own writes increment.
+ const resolveRootOrgId = async (orgId: string): Promise<string> => {
+ try {
+ const row = (await db
+ .replicaNode()(TableName.Organization)
+ .where("id", orgId)
+ .select(db.raw(`COALESCE("rootOrgId", "id") as "rootOrgId"`))
+ .first()) as { rootOrgId?: string } | undefined;
+ return row?.rootOrgId ?? orgId;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Resolve root org id" });
+ }
+ };
+
+ // Joins on projectId rather than caId, which is nullable and would drop imported and discovered
+ // certificates. Wildcards need no stored column because isWildcardPattern is just includes("*"), so
+ // this LIKE cannot drift from it.
+ const countActiveCertificateQuotaKeysByOrg = async (orgId: string): Promise<{ total: number; wildcard: number }> => {
+ try {
+ const row = (await $activeQuotaCertificates(orgId)
+ .countDistinct(`${TableName.Certificate}.quotaKey as total`)
+ .select(
+ db.raw(`COUNT(DISTINCT ??) FILTER (WHERE ?? LIKE '%*%' OR ?? LIKE '%*%') as "wildcard"`, [
+ `${TableName.Certificate}.quotaKey`,
+ `${TableName.Certificate}.commonName`,
+ `${TableName.Certificate}.altNames`
+ ])
+ )
+ .first()) as { total?: string | number; wildcard?: string | number } | undefined;
+
+ return { total: Number(row?.total ?? 0), wildcard: Number(row?.wildcard ?? 0) };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count active certificate quota keys for org" });
+ }
+ };
+
+ // Lets an org at its cap keep renewing: reissuing names it already holds cannot raise the count.
+ const isCertificateQuotaKeyActiveInOrg = async (orgId: string, quotaKey: string): Promise<boolean> => {
+ try {
+ const row = (await $activeQuotaCertificates(orgId)
+ .where(`${TableName.Certificate}.quotaKey`, quotaKey)
+ .select(`${TableName.Certificate}.id`)
+ .first()) as { id?: string } | undefined;
+ return Boolean(row);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Check certificate quota key active for org" });
+ }
+ };
+
const countPamResources = async (orgId: string): Promise<number> => {
try {
const row = await db
@@ -183,5 +258,14 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
- return { countInternalCas, countActiveCerts, countPamResources, countSecretManagementIdentities, countPamIdentities };
+ return {
+ countInternalCas,
+ countActiveCerts,
+ resolveRootOrgId,
+ countActiveCertificateQuotaKeysByOrg,
+ isCertificateQuotaKeyActiveInOrg,
+ countPamResources,
+ countSecretManagementIdentities,
+ countPamIdentities
+ };
};
diff --git a/backend/src/services/license-client/usage/usage-metering.test.ts b/backend/src/services/license-client/usage/usage-metering.test.ts
index ca8537284b..5588b1ea99 100644
--- a/backend/src/services/license-client/usage/usage-metering.test.ts
+++ b/backend/src/services/license-client/usage/usage-metering.test.ts
@@ -237,6 +237,9 @@ describe("buildMeteredFeatures", () => {
const usageCounterDAL = {
countInternalCas: vi.fn(async () => 1),
countActiveCerts: vi.fn(async () => 2),
+ resolveRootOrgId: vi.fn(async (id: string) => id),
+ countActiveCertificateQuotaKeysByOrg: vi.fn(async () => ({ total: 0, wildcard: 0 })),
+ isCertificateQuotaKeyActiveInOrg: vi.fn(async () => false),
countPamResources: vi.fn(async () => 3),
countSecretManagementIdentities: vi.fn(async () => 4),
countPamIdentities: vi.fn(async () => 5)
@@ -276,6 +279,9 @@ describe("buildMeteredFeatures", () => {
const usageCounterDAL = {
countInternalCas: vi.fn(async () => 0),
countActiveCerts: vi.fn(async () => 0),
+ resolveRootOrgId: vi.fn(async (id: string) => id),
+ countActiveCertificateQuotaKeysByOrg: vi.fn(async () => ({ total: 0, wildcard: 0 })),
+ isCertificateQuotaKeyActiveInOrg: vi.fn(async () => false),
countPamResources: vi.fn(async () => 0),
countSecretManagementIdentities: vi.fn(async () => 9),
countPamIdentities: vi.fn(async () => 6)
@@ -490,6 +496,9 @@ describe("canUse enforcement (using the framework from a call site)", () => {
const usageCounterDAL = {
countInternalCas: async () => counts.internalCas ?? 0,
countActiveCerts: async () => 0,
+ resolveRootOrgId: async (id: string) => id,
+ countActiveCertificateQuotaKeysByOrg: async () => ({ total: 0, wildcard: 0 }),
+ isCertificateQuotaKeyActiveInOrg: async () => false,
countPamResources: async () => 0,
countSecretManagementIdentities: async () => 0,
countPamIdentities: async () => 0
diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.ts
index 7b2585769a..ceaf889204 100644
--- a/frontend/src/hooks/api/subscriptions/types.ts
+++ b/frontend/src/hooks/api/subscriptions/types.ts
@@ -66,7 +66,6 @@ export type SubscriptionPlan = {
pkiScep: boolean;
pkiPqc: boolean;
caCrl: boolean;
- pkiWildcardSans: boolean;
pkiEnterpriseCaIntegrations: boolean;
pkiExternalIntermediateCa: boolean;
pkiDiscovery: boolean;
@@ -75,7 +74,12 @@ export type SubscriptionPlan = {
pkiSyncs: boolean;
pkiLegacyTemplates: boolean;
pkiCodeSigning: boolean;
+ // maxCas caps every CA type, maxInternalCas caps INTERNAL only. Both enforced.
+ maxCas: number | null;
maxInternalCas: number | null;
+ maxCertificates: number | null;
+ // 0 means the plan has no wildcard support; wildcards also count toward maxCertificates.
+ maxWildcardCertificates: number | null;
maxSansPerCertificate: number | null;
kmsPqc: boolean;
enforceMfa: boolean;