Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
misc: addressed comments
Sheen Capadngan3ab9bec51529
diff --git a/backend/src/db/migrations/20260903051500_add-certificate-quota-key.ts b/backend/src/db/migrations/20260903051500_add-certificate-quota-key.tsindex 86b41bdbfe..32c6ffd09d 100644--- a/backend/src/db/migrations/20260903051500_add-certificate-quota-key.ts+++ b/backend/src/db/migrations/20260903051500_add-certificate-quota-key.ts@@ -1,6 +1,9 @@import { Knex } from "knex";-import { buildCertificateQuotaKey } from "@app/services/certificate-common/certificate-quota-key";+import {+ buildCertificateQuotaKey,+ certificateHasWildcard+} from "@app/services/certificate-common/certificate-quota-key";import { TableName } from "../schemas";@@ -8,25 +11,25 @@ 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;+const ALTER_LOCK_TIMEOUT = 10 * 1000; // fail fast rather than queue behind writes on a hot table-// 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.+// Columns are 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.//// config.transaction is false so each batch commits on its own; otherwise knex would hold the-// ADD COLUMN lock for the whole backfill.+// ADD COLUMN lock for the whole backfill. The transaction below exists solely so SET LOCAL lands on+// the ALTER's connection.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();- });- });- }+ // IF NOT EXISTS per column rather than one hasColumn guard, so a re-run after a partial run adds+ // only what is missing instead of colliding on the column that already landed.+ await knex.transaction(async (tx) => {+ await tx.raw(`SET LOCAL lock_timeout = ${ALTER_LOCK_TIMEOUT}`);+ await tx.raw(+ `ALTER TABLE ?? ADD COLUMN IF NOT EXISTS "quotaKey" varchar(64), ADD COLUMN IF NOT EXISTS "hasWildcard" boolean`,+ [TableName.Certificate]+ );+ });// 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) {@@ -38,21 +41,25 @@ export async function up(knex: Knex): Promise<void> {if (!rows.length) break;- // unnest of two arrays, so this takes two bind parameters whatever the batch size.+ // unnest of arrays, so this takes a fixed number of bind parameters whatever the batch size.// eslint-disable-next-line no-await-in-loopawait 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))]+ `UPDATE ?? AS c SET "quotaKey" = u.key, "hasWildcard" = u.wild+ FROM unnest(?::uuid[], ?::text[], ?::boolean[]) AS u(id, key, wild) WHERE c.id = u.id`,+ [+ TableName.Certificate,+ rows.map((row) => row.id),+ rows.map((row) => buildCertificateQuotaKey(row)),+ rows.map((row) => certificateHasWildcard(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");- });+ await knex.raw(`ALTER TABLE ?? DROP COLUMN IF EXISTS "quotaKey", DROP COLUMN IF EXISTS "hasWildcard"`, [+ TableName.Certificate+ ]);}const config = { transaction: false };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.tsindex 9e200e971e..a53ed53f5b 100644--- a/backend/src/db/migrations/20260903051600_add-certificate-quota-key-index.ts+++ b/backend/src/db/migrations/20260903051600_add-certificate-quota-key-index.ts@@ -7,8 +7,7 @@ const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutesconst 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.+// notAfter, status and hasWildcard are INCLUDE columns so both counts stay index-only scans.export async function up(knex: Knex): Promise<void> {const connection = await knex.client.acquireConnection();const raw = (sql: string) => knex.raw(sql).connection(connection);@@ -36,7 +35,7 @@ export async function up(knex: Knex): Promise<void> {await raw(`CREATE INDEX CONCURRENTLY IF NOT EXISTS "${QUOTA_KEY_INDEX}"ON "${TableName.Certificate}" ("projectId", "quotaKey")- INCLUDE ("notAfter", "status", "extendedKeyUsages")+ INCLUDE ("notAfter", "status", "hasWildcard")`);}} finally {diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.tsindex e48d3002fd..e6ba55baae 100644--- a/backend/src/db/schemas/certificates.ts+++ b/backend/src/db/schemas/certificates.ts@@ -55,7 +55,8 @@ export const CertificatesSchema = z.object({hsmPublicKeySpki: zodBuffer.nullable().optional(),subjectDomainComponents: z.string().nullable().optional(),orderId: z.string().uuid().default("00000000-0000-0000-0000-000000000000"),- quotaKey: z.string().nullable().optional()+ quotaKey: z.string().nullable().optional(),+ hasWildcard: z.boolean().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.tsindex 913fdcb2f2..42f6114834 100644--- a/backend/src/ee/services/license/__mocks__/license-fns.ts+++ b/backend/src/ee/services/license/__mocks__/license-fns.ts@@ -75,7 +75,7 @@ export const getDefaultOnPremFeatures = () => {pkiSyncs: false,pkiLegacyTemplates: false,pkiCodeSigning: false,- maxCas: null,+ maxCas: 1,maxInternalCas: null,maxCertificates: null,maxWildcardCertificates: null,diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex 084a1f4616..8c65c36121 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -126,10 +126,7 @@ 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,+ maxCas: 1,maxInternalCas: null,maxCertificates: null,maxWildcardCertificates: null,diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.tsindex 1e4efebd16..b99a2ee466 100644--- a/backend/src/ee/services/license/license-service.ts+++ b/backend/src/ee/services/license/license-service.ts@@ -148,16 +148,8 @@ export const licenseServiceFactory = ({}}- // 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 };- }+ // anything that reaches here without setting an instance type is the self-hosted OSS version,+ // which keeps the default onPremFeatures.} catch (error) {logger.error(error, `init-license: encountered an error when init license`);}diff --git a/backend/src/services/certificate-authority/certificate-authority-quota-fns.test.ts b/backend/src/services/certificate-authority/certificate-authority-quota-fns.test.tsnew file mode 100644index 0000000000..f49adc03f2--- /dev/null+++ b/backend/src/services/certificate-authority/certificate-authority-quota-fns.test.ts@@ -0,0 +1,69 @@+import { assertCertificateAuthorityQuota, TCertificateAuthorityQuotaDeps } from "./certificate-authority-quota-fns";++const buildDeps = ({+ maxCas,+ maxInternalCas,+ casUsed = 0,+ internalCasUsed = 0+}: {+ maxCas: number | null;+ maxInternalCas: number | null;+ casUsed?: number;+ internalCasUsed?: number;+}) =>+ ({+ projectDAL: { findById: async () => ({ id: "project-1", orgId: "org-1" }) },+ licenseService: { getPlan: async () => ({ maxCas, maxInternalCas }) },+ certificateAuthorityDAL: {+ countCasByOrgId: async () => casUsed,+ countInternalCasByOrgId: async () => internalCasUsed+ }+ }) as unknown as TCertificateAuthorityQuotaDeps;++const assertQuota = (deps: TCertificateAuthorityQuotaDeps, isInternal = true) =>+ assertCertificateAuthorityQuota({ projectId: "project-1", isInternal, deps });++describe("assertCertificateAuthorityQuota", () => {+ test("allows creation when neither cap is set", async () => {+ await expect(assertQuota(buildDeps({ maxCas: null, maxInternalCas: null, casUsed: 500 }))).resolves.toBeUndefined();+ });++ // A contract granting more internal CAs than total CAs is a License Server misconfiguration.+ test("raises the total cap to the internal cap when the internal grant is larger", async () => {+ await expect(+ assertQuota(buildDeps({ maxCas: 1, maxInternalCas: 25, casUsed: 5, internalCasUsed: 5 }))+ ).resolves.toBeUndefined();+ });++ test("reports the raised cap in the error rather than the misconfigured one", async () => {+ await expect(+ assertQuota(buildDeps({ maxCas: 1, maxInternalCas: 25, casUsed: 25, internalCasUsed: 0 }))+ ).rejects.toThrow("(25 of 25 certificate authorities)");+ });++ // The guard that keeps the free tier capped: null means the tier does not cap internal CAs+ // separately, not that they are unlimited.+ test("does not raise the total cap when the internal cap is null", async () => {+ await expect(assertQuota(buildDeps({ maxCas: 1, maxInternalCas: null, casUsed: 1 }))).rejects.toThrow(+ "(1 of 1 certificate authorities)"+ );+ });++ test("leaves the total cap alone when it already exceeds the internal cap", async () => {+ await expect(+ assertQuota(buildDeps({ maxCas: 10, maxInternalCas: 3, casUsed: 10, internalCasUsed: 0 }))+ ).rejects.toThrow("(10 of 10 certificate authorities)");+ });++ test("still enforces the internal cap once the total cap allows the create", async () => {+ await expect(+ assertQuota(buildDeps({ maxCas: 10, maxInternalCas: 3, casUsed: 3, internalCasUsed: 3 }))+ ).rejects.toThrow("(3 of 3 internal certificate authorities)");+ });++ test("skips the internal cap for a non-internal certificate authority", async () => {+ await expect(+ assertQuota(buildDeps({ maxCas: 10, maxInternalCas: 3, casUsed: 3, internalCasUsed: 3 }), false)+ ).resolves.toBeUndefined();+ });+});diff --git a/backend/src/services/certificate-authority/certificate-authority-quota-fns.ts b/backend/src/services/certificate-authority/certificate-authority-quota-fns.tsnew file mode 100644index 0000000000..4f4151f197--- /dev/null+++ b/backend/src/services/certificate-authority/certificate-authority-quota-fns.ts@@ -0,0 +1,58 @@+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { TProjectDALFactory } from "@app/services/project/project-dal";++import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";++export type TCertificateAuthorityQuotaDeps = {+ projectDAL: Pick<TProjectDALFactory, "findById">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "countCasByOrgId" | "countInternalCasByOrgId">;+};++// Enforced where the CA row is written rather than in createCertificateAuthority alone: the still-live+// POST /cert-manager/ca route calls internalCertificateAuthorityService.createCa directly, so a check+// that only sat in the former was bypassable.+//+// Two independent caps, whichever binds first: maxCas covers every type, maxInternalCas covers+// INTERNAL only. A tier sets one and leaves the other null.+export const assertCertificateAuthorityQuota = async ({+ projectId,+ isInternal,+ deps+}: {+ projectId: string;+ isInternal: boolean;+ deps: TCertificateAuthorityQuotaDeps;+}): Promise<void> => {+ const project = await deps.projectDAL.findById(projectId);+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });++ const plan = await deps.licenseService.getPlan(project.orgId);++ // A contract granting more internal CAs than total CAs is a License Server misconfiguration; honour+ // the larger grant. Guarded on both being numbers because the free tier leaves maxInternalCas null+ // while capping maxCas at 1, so treating null as unlimited would lift that cap.+ const maxCas =+ typeof plan.maxCas === "number" && typeof plan.maxInternalCas === "number"+ ? Math.max(plan.maxCas, plan.maxInternalCas)+ : plan.maxCas;++ if (typeof maxCas === "number") {+ const used = await deps.certificateAuthorityDAL.countCasByOrgId(project.orgId);+ if (used >= maxCas) {+ throw new BadRequestError({+ message: `Failed to create certificate authority due to plan limit reached (${used} of ${maxCas} certificate authorities). Upgrade plan to add more certificate authorities.`+ });+ }+ }++ if (isInternal && typeof plan.maxInternalCas === "number") {+ const used = await deps.certificateAuthorityDAL.countInternalCasByOrgId(project.orgId);+ if (used >= plan.maxInternalCas) {+ throw new BadRequestError({+ message: `Failed to create internal certificate authority due to plan limit reached (${used} of ${plan.maxInternalCas} internal certificate authorities). Upgrade plan to add more internal certificate authorities.`+ });+ }+ }+};diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.tsindex e1de802754..e660d124fe 100644--- a/backend/src/services/certificate-authority/certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts@@ -81,6 +81,7 @@ import {import { TCertificateAuthorityDALFactory } from "./certificate-authority-dal";import { CaType } from "./certificate-authority-enums";import { CERTIFICATE_AUTHORITIES_TYPE_MAP } from "./certificate-authority-maps";+import { assertCertificateAuthorityQuota } from "./certificate-authority-quota-fns";import { TCertificateAuthoritySecretDALFactory } from "./certificate-authority-secret-dal";import {TCertificateAuthority,@@ -334,30 +335,19 @@ 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.`- });- }+ // Internal CAs are gated inside internalCertificateAuthorityService.createCa, which every internal+ // creation path funnels through, so only the external types are checked here.+ if (type !== CaType.INTERNAL) {+ await assertCertificateAuthorityQuota({+ projectId,+ isInternal: false,+ deps: { projectDAL, licenseService, certificateAuthorityDAL }+ });}if (type === CaType.INTERNAL) {const internalConfig = configuration as TCreateInternalCertificateAuthorityDTO["configuration"];- if (typeof plan.maxInternalCas === "number") {- 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 (${currentInternalCaCount} of ${plan.maxInternalCas} internal certificate authorities). Upgrade plan to add more internal certificate authorities.`- });- }- }-if (internalConfig.keySource === CertKeySource.Hsm) {if (!internalConfig.hsmConnectorId) {throw new BadRequestError({ message: "An HSM Connector is required when the key source is HSM." });diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.tsindex e3861b2fab..c8864ca9e1 100644--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts@@ -84,6 +84,7 @@ import {validateImportedCertificate} from "../certificate-authority-fns";import { TCertificateAuthorityQueueFactory } from "../certificate-authority-queue";+import { assertCertificateAuthorityQuota } from "../certificate-authority-quota-fns";import { TCertificateAuthoritySecretDALFactory } from "../certificate-authority-secret-dal";import { validateAndMapAltNameType } from "../certificate-authority-validators";import { TInternalCertificateAuthorityDALFactory } from "./internal-certificate-authority-dal";@@ -117,6 +118,8 @@ type TInternalCertificateAuthorityServiceFactoryDep = {| "findOne"| "findByIdWithAssociatedCa"| "findWithAssociatedCa"+ | "countCasByOrgId"+ | "countInternalCasByOrgId">;internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory,@@ -353,6 +356,15 @@ export const internalCertificateAuthorityServiceFactory = ({await $validatePqcLicense(keyAlgorithm, projectId);+ // Enforced here rather than only in certificateAuthorityService.createCertificateAuthority: the+ // POST /cert-manager/ca route calls this method directly, so a check that only sat there was+ // bypassable.+ await assertCertificateAuthorityQuota({+ projectId,+ isInternal: true,+ deps: { projectDAL, licenseService, certificateAuthorityDAL }+ });+// Refused rather than silently dropped, since the caller asked for it explicitly.if (crlDistributionPointUrls?.length && !(await $isManagedCrlDistributionAllowed(projectId))) {throw new BadRequestError({diff --git a/backend/src/services/certificate-common/certificate-quota-fns.ts b/backend/src/services/certificate-common/certificate-quota-fns.tsindex d5c8e0bd9e..f762503665 100644--- a/backend/src/services/certificate-common/certificate-quota-fns.ts+++ b/backend/src/services/certificate-common/certificate-quota-fns.ts@@ -2,11 +2,10 @@ import { TLicenseServiceFactory } from "@app/ee/services/license/license-serviceimport { 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";+import { buildCertificateQuotaKey, certificateHasWildcard } from "./certificate-quota-key";type TQuotaCounts = { total: number; wildcard: number };@@ -20,26 +19,37 @@ export type TCertificateQuotaDeps = {keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;};+// The cache only saves a query, so a keystore failure degrades to the exact count rather than failing+// issuance. That keeps issuance dependent on Postgres alone, which it already needs to write the row.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 };+ try {+ 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 };+ }+ } catch (error) {+ logger.error(error, `Failed to read certificate quota cache [orgId=${orgId}]`);}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))- ]);++ try {+ const ttl = KeyStoreTtls.PkiCertificateQuotaCountInSeconds;+ await Promise.all([+ deps.keyStore.setItemWithExpiry(totalKey, ttl, String(counts.total)),+ deps.keyStore.setItemWithExpiry(wildcardKey, ttl, String(counts.wildcard))+ ]);+ } catch (error) {+ logger.error(error, `Failed to write certificate quota cache [orgId=${orgId}]`);+ }return counts;};@@ -79,7 +89,7 @@ export const assertCertificateQuota = async ({// 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 isWildcard = certificateHasWildcard({ commonName, altNames });const plan = await deps.licenseService.getPlan(orgId);const unlimited = { quotaKey, isNewQuotaKey: false, quotaOrgId: orgId, isWildcard };diff --git a/backend/src/services/certificate-common/certificate-quota-key.ts b/backend/src/services/certificate-common/certificate-quota-key.tsindex a694136db2..f25221466d 100644--- a/backend/src/services/certificate-common/certificate-quota-key.ts+++ b/backend/src/services/certificate-common/certificate-quota-key.ts@@ -18,3 +18,13 @@ export const buildCertificateQuotaKey = ({return createHash("sha256").update(canonical).digest("hex");};++// Stored on the row so the wildcard quota can be counted from the index. Deriving it in SQL instead+// would need commonName and altNames in the index, and altNames is varchar(4096).+export const certificateHasWildcard = ({+ commonName,+ altNames+}: {+ commonName?: string | null;+ altNames?: string | null;+}): boolean => `${commonName ?? ""},${altNames ?? ""}`.includes("*");diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.tsindex 7702d2fa45..e9897d95eb 100644--- a/backend/src/services/certificate/certificate-dal.ts+++ b/backend/src/services/certificate/certificate-dal.ts@@ -14,7 +14,10 @@ import {mapExtendedKeyUsageToLegacy,mapLegacyExtendedKeyUsageToStandard} from "@app/services/certificate-common/certificate-constants";-import { buildCertificateQuotaKey } from "@app/services/certificate-common/certificate-quota-key";+import {+ buildCertificateQuotaKey,+ certificateHasWildcard+} from "@app/services/certificate-common/certificate-quota-key";import { applyMetadataFilter } from "@app/services/resource-metadata/resource-metadata-fns";import { keySizeToAlgorithms } from "./certificate-fns";@@ -49,12 +52,13 @@ 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) =>+ // Every certificate insert funnels through here, so no site can forget these.+ const create = async (data: Omit<TCertificatesInsert, "quotaKey" | "hasWildcard">, tx?: Knex) =>certificateOrm.create({...data,- quotaKey: buildCertificateQuotaKey({ commonName: data.commonName, altNames: data.altNames })+ quotaKey: buildCertificateQuotaKey({ commonName: data.commonName, altNames: data.altNames }),+ hasWildcard: certificateHasWildcard({ commonName: data.commonName, altNames: data.altNames })},tx);diff --git a/backend/src/services/certificate/certificate-fns.test.ts b/backend/src/services/certificate/certificate-fns.test.tsindex 0e862998f3..3066642374 100644--- a/backend/src/services/certificate/certificate-fns.test.ts+++ b/backend/src/services/certificate/certificate-fns.test.ts@@ -55,7 +55,7 @@ describe("buildCertificateBundle", () => {describe("parseCertificateBody usages", () => {x509.cryptoProvider.set(webcrypto as unknown as Crypto);- const buildCert = async (extensions: x509.Extension[]) => {+ const buildCert = async (extensions: x509.Extension[], name = "CN=probe.example.com") => {const keys = await webcrypto.subtle.generateKey({name: "RSASSA-PKCS1-v1_5",@@ -69,7 +69,7 @@ describe("parseCertificateBody usages", () => {const cert = await x509.X509CertificateGenerator.createSelfSigned({serialNumber: "01",- name: "CN=probe.example.com",+ name,notBefore: new Date("2026-01-01"),notAfter: new Date("2027-01-01"),keys: keys as CryptoKeyPair,@@ -109,6 +109,32 @@ describe("parseCertificateBody usages", () => {expect(fields.isCA).toBe(false);});+ // The row's commonName has to match the certificate that was actually signed: on the CSR paths the+ // issued subject comes from a subjectOverride the CSR itself never carried.+ test("reads the common name off the certificate so it wins over the requested one", async () => {+ const pem = await buildCert([new x509.BasicConstraintsExtension(false)], "CN=issued.example.com");++ const fields = extractCertificateFields(pem);++ expect(fields.commonName).toBe("issued.example.com");+ expect({ commonName: "requested.example.com", ...fields }.commonName).toBe("issued.example.com");+ });++ test("omits the common name when the certificate has none, so a NOT NULL column keeps the requested value", async () => {+ const pem = await buildCert([new x509.BasicConstraintsExtension(false)], "");++ const fields = extractCertificateFields(pem);++ expect(fields).not.toHaveProperty("commonName");+ expect({ commonName: "requested.example.com", ...fields }.commonName).toBe("requested.example.com");+ });++ test("omits the common name when the certificate cannot be parsed", () => {+ const fields = extractCertificateFields(Buffer.from("not a certificate"));++ expect(fields).not.toHaveProperty("commonName");+ });+test("drops extended key usage OIDs it cannot map rather than leaving holes in the array", async () => {const pem = await buildCert([new x509.ExtendedKeyUsageExtension(["1.3.6.1.5.5.7.3.1", "1.3.6.1.4.1.311.20.2.2", "1.3.6.1.5.5.7.3.17"], false)diff --git a/backend/src/services/certificate/certificate-fns.ts b/backend/src/services/certificate/certificate-fns.tsindex 1d285bec25..99bcdb0608 100644--- a/backend/src/services/certificate/certificate-fns.ts+++ b/backend/src/services/certificate/certificate-fns.ts@@ -397,8 +397,9 @@ export const extractCertificateFields = (decryptedCertificate: Buffer) => {isCA: parsed.basicConstraints?.isCA ?? null,pathLength: parsed.basicConstraints?.pathLength ?? null,- // Callers spread these last so the issued usages win over the requested ones. Absent when the- // certificate carries no such extension, leaving the requested values in place.+ // Callers spread these last so the issued values win over the requested ones. Absent when the+ // certificate does not carry them, leaving the requested values in place.+ ...(parsed.subject?.commonName && { commonName: parsed.subject.commonName }),...(parsed.keyUsages && { keyUsages: parsed.keyUsages }),...(parsed.extendedKeyUsages && { extendedKeyUsages: parsed.extendedKeyUsages })};diff --git a/backend/src/services/license-client/usage/usage-counter-dal.ts b/backend/src/services/license-client/usage/usage-counter-dal.tsindex 3763b7756a..a2664791d0 100644--- a/backend/src/services/license-client/usage/usage-counter-dal.ts+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts@@ -5,7 +5,6 @@ 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>;@@ -53,14 +52,23 @@ 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]- ]);+ // Code signing is licensed separately, so signer certificates are excluded. Anchored on the signer+ // rather than on the code_signing EKU: that usage is caller-supplied, so a tenant could append it to+ // every request and escape the quota entirely.+ //+ // Matched on quotaKey rather than on pki_signers.certificateId, which points only at a signer's+ // current certificate. Every certificate a signer issues carries the signer's commonName, so the+ // whole renewal chain shares one quotaKey and this covers it without a schema change.+ const $excludeSignerCertificates = (qb: Knex.QueryBuilder) =>+ qb.whereNotExists((sub) => {+ void sub+ .select(db.raw("1"))+ .from(`${TableName.PkiSigners} as s`)+ .join(`${TableName.Certificate} as sc`, "sc.id", "s.certificateId")+ .whereRaw(`sc."quotaKey" = ??`, [`${TableName.Certificate}.quotaKey`])+ // Same project, so one tenant cannot exempt a certificate by matching another's signer names.+ .whereRaw(`s."projectId" = ??`, [`${TableName.Certificate}.projectId`]);+ });// No `status = 'active'` filter: nothing writes EXPIRED or RENEWED, both are derived at read time.const $activeQuotaCertificates = (orgId: string) => {@@ -72,7 +80,7 @@ export const usageCounterDALFactory = (db: TDbClient) => {.where(`${TableName.Certificate}.notAfter`, ">", new Date()).whereNot(`${TableName.Certificate}.status`, CertStatus.REVOKED);- return $excludeCodeSigningCertificates(qb);+ return $excludeSignerCertificates(qb);};// The count spans the org tree, so its cache must be keyed on the root: per-org keys would give each@@ -91,17 +99,16 @@ export const usageCounterDALFactory = (db: TDbClient) => {};// 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.+ // certificates. Both counts read hasWildcard from the covering index; filtering with LIKE over+ // commonName/altNames instead forces a sequential scan (measured: ~2x at 600k rows).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"`, [+ db.raw(`COUNT(DISTINCT ??) FILTER (WHERE ??) as "wildcard"`, [`${TableName.Certificate}.quotaKey`,- `${TableName.Certificate}.commonName`,- `${TableName.Certificate}.altNames`+ `${TableName.Certificate}.hasWildcard`])).first()) as { total?: string | number; wildcard?: string | number } | undefined;