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
feat(license): extend licenseService interface to include getInstanceType method across multiple services
Victor Hugo dos Santos2c8fc44fe186
diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.tsindex 2c62c71f14..62e598335f 100644--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts@@ -176,7 +176,7 @@ type TPkiAcmeServiceFactoryDep = {"create" | "transaction" | "updateById" | "findByAccountAuthAndChallengeId" | "findByIdForChallengeValidation">;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;usageCounterDAL: Pick<TUsageCounterDALFactory,"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.tsindex 2004003d0f..d6b5ff0bae 100644--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts@@ -97,7 +97,7 @@ type TPkiScepServiceFactoryDep = {kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;usageCounterDAL: Pick<TUsageCounterDALFactory,"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"diff --git a/backend/src/services/certificate-authority/certificate-authority-dal.ts b/backend/src/services/certificate-authority/certificate-authority-dal.tsindex 2230bce918..077c661b5b 100644--- a/backend/src/services/certificate-authority/certificate-authority-dal.ts+++ b/backend/src/services/certificate-authority/certificate-authority-dal.ts@@ -377,36 +377,36 @@ export const certificateAuthorityDALFactory = (db: TDbClient) => {}};- // 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) => {+ // Internal CAs across the org tree (orgId null: the whole instance), excluding soft-deleted projects.+ // External and ACME CAs are intentionally not counted; maxCas covers those via countCasByOrgId below.+ const countInternalCasByOrgId = async (orgId: string | null, tx?: Knex) => {try {- const doc = await (tx || db.replicaNode())(TableName.CertificateAuthority)+ const query = (tx || db.replicaNode())(TableName.CertificateAuthority).join(TableName.InternalCertificateAuthority,`${TableName.CertificateAuthority}.id`,`${TableName.InternalCertificateAuthority}.caId`).join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)- .whereIn(`${TableName.Project}.orgId`, orgTreeIds(tx || db.replicaNode(), orgId))- .whereNull(`${TableName.Project}.deleteAfter`)- .count();+ .whereNull(`${TableName.Project}.deleteAfter`);+ if (orgId) void query.whereIn(`${TableName.Project}.orgId`, orgTreeIds(tx || db.replicaNode(), orgId));+ const doc = await query.count();return Number(doc?.[0]?.count ?? 0);} catch (error) {throw new DatabaseError({ error, name: "Count Internal CAs By Org ID - Certificate Authority" });}};- // 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) => {+ // Every CA type across the org tree (orgId null: the whole instance). 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 | null, tx?: Knex) => {try {- const doc = await (tx || db.replicaNode())(TableName.CertificateAuthority)+ const query = (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();+ .whereNull(`${TableName.Project}.deleteAfter`);+ if (orgId) void query.whereIn(`${TableName.Project}.orgId`, orgTreeIds(tx || db.replicaNode(), orgId));+ const doc = await query.count();return Number(doc?.[0]?.count ?? 0);} catch (error) {throw new DatabaseError({ error, name: "Count CAs By Org ID - Certificate Authority" });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.tsindex f49adc03f2..c005aa4d0f 100644--- a/backend/src/services/certificate-authority/certificate-authority-quota-fns.test.ts+++ b/backend/src/services/certificate-authority/certificate-authority-quota-fns.test.ts@@ -1,22 +1,34 @@+import { InstanceType } from "@app/ee/services/license/license-types";+import { assertCertificateAuthorityQuota, TCertificateAuthorityQuotaDeps } from "./certificate-authority-quota-fns";const buildDeps = ({maxCas,maxInternalCas,casUsed = 0,- internalCasUsed = 0+ internalCasUsed = 0,+ instanceType = InstanceType.OnPrem,+ countedOrgIds = []}: {maxCas: number | null;maxInternalCas: number | null;casUsed?: number;internalCasUsed?: number;+ instanceType?: InstanceType;+ countedOrgIds?: (string | null)[];}) =>({projectDAL: { findById: async () => ({ id: "project-1", orgId: "org-1" }) },- licenseService: { getPlan: async () => ({ maxCas, maxInternalCas }) },+ licenseService: { getPlan: async () => ({ maxCas, maxInternalCas }), getInstanceType: () => instanceType },certificateAuthorityDAL: {- countCasByOrgId: async () => casUsed,- countInternalCasByOrgId: async () => internalCasUsed+ countCasByOrgId: async (orgId: string | null) => {+ countedOrgIds.push(orgId);+ return casUsed;+ },+ countInternalCasByOrgId: async (orgId: string | null) => {+ countedOrgIds.push(orgId);+ return internalCasUsed;+ }}}) as unknown as TCertificateAuthorityQuotaDeps;@@ -66,4 +78,23 @@ describe("assertCertificateAuthorityQuota", () => {assertQuota(buildDeps({ maxCas: 10, maxInternalCas: 3, casUsed: 3, internalCasUsed: 3 }), false)).resolves.toBeUndefined();});++ test.each([InstanceType.EnterpriseOnPrem, InstanceType.EnterpriseOnPremOffline])(+ "counts the whole instance under a self-hosted license (%s)",+ async (instanceType) => {+ const countedOrgIds: (string | null)[] = [];+ await expect(+ assertQuota(buildDeps({ maxCas: 10, maxInternalCas: 3, internalCasUsed: 3, instanceType, countedOrgIds }))+ ).rejects.toThrow("(3 of 3 internal certificate authorities across this instance)");+ expect(countedOrgIds).toEqual([null, null]);+ }+ );++ test.each([InstanceType.Cloud, InstanceType.OnPrem])("counts the organization tree on %s", async (instanceType) => {+ const countedOrgIds: (string | null)[] = [];+ await expect(+ assertQuota(buildDeps({ maxCas: 1, maxInternalCas: null, casUsed: 1, instanceType, countedOrgIds }))+ ).rejects.toThrow("(1 of 1 certificate authorities)");+ expect(countedOrgIds).toEqual(["org-1"]);+ });});diff --git a/backend/src/services/certificate-authority/certificate-authority-quota-fns.ts b/backend/src/services/certificate-authority/certificate-authority-quota-fns.tsindex d19fb67143..0cd7580eb5 100644--- a/backend/src/services/certificate-authority/certificate-authority-quota-fns.ts+++ b/backend/src/services/certificate-authority/certificate-authority-quota-fns.ts@@ -1,13 +1,14 @@import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TFeatureSet } from "@app/ee/services/license/license-types";import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { isInstanceWidePkiQuota } from "@app/services/certificate-common/certificate-quota-scope";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">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "countCasByOrgId" | "countInternalCasByOrgId">;};@@ -26,7 +27,8 @@ export const resolveEffectiveMaxCas = (plan: Pick<TFeatureSet, "maxCas" | "maxIn// 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.+// INTERNAL only. A tier sets one and leaves the other null. Both count the root org's tree, or the+// whole instance under a self-hosted license (isInstanceWidePkiQuota).export const assertCertificateAuthorityQuota = async ({projectId,isInternal,@@ -41,21 +43,24 @@ export const assertCertificateAuthorityQuota = async ({const plan = await deps.licenseService.getPlan(project.orgId);const maxCas = resolveEffectiveMaxCas(plan);+ const isInstanceWide = isInstanceWidePkiQuota(deps.licenseService);+ const countOrgId = isInstanceWide ? null : project.orgId;+ const scopeNote = isInstanceWide ? " across this instance" : "";if (typeof maxCas === "number") {- const used = await deps.certificateAuthorityDAL.countCasByOrgId(project.orgId);+ const used = await deps.certificateAuthorityDAL.countCasByOrgId(countOrgId);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.`+ message: `Failed to create certificate authority due to plan limit reached (${used} of ${maxCas} certificate authorities${scopeNote}). Upgrade plan to add more certificate authorities.`});}}if (isInternal && typeof plan.maxInternalCas === "number") {- const used = await deps.certificateAuthorityDAL.countInternalCasByOrgId(project.orgId);+ const used = await deps.certificateAuthorityDAL.countInternalCasByOrgId(countOrgId);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.`+ message: `Failed to create internal certificate authority due to plan limit reached (${used} of ${plan.maxInternalCas} internal certificate authorities${scopeNote}). 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 1bf39e0c11..f53f45bfdb 100644--- a/backend/src/services/certificate-authority/certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts@@ -15,6 +15,7 @@ import { TKeyStoreFactory } from "@app/keystore/keystore";import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor, TProjectPermission } from "@app/lib/types";+import { isInstanceWidePkiQuota } from "@app/services/certificate-common/certificate-quota-scope";import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";@@ -171,7 +172,7 @@ type TCertificateAuthorityServiceFactoryDep = {usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;caKeySourceService: Pick<TCaKeySourceServiceFactory, "assertCanUse" | "describeKey" | "prepareKeyReleases">;certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne" | "primaryNode">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;auditLogService: Pick<TAuditLogServiceFactory, "createCollapsedAuditLog">;@@ -678,9 +679,10 @@ export const certificateAuthorityServiceFactory = ({if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });const plan = await licenseService.getPlan(project.orgId);+ const countOrgId = isInstanceWidePkiQuota(licenseService) ? null : project.orgId;const [totalUsed, internalUsed] = await Promise.all([- certificateAuthorityDAL.countCasByOrgId(project.orgId),- certificateAuthorityDAL.countInternalCasByOrgId(project.orgId)+ certificateAuthorityDAL.countCasByOrgId(countOrgId),+ certificateAuthorityDAL.countInternalCasByOrgId(countOrgId)]);return {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 d8b2f0e2ec..765f475566 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@@ -151,7 +151,7 @@ type TInternalCertificateAuthorityServiceFactoryDep = {projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction" | "findProjectBySlug">;kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;caSigningConfigDAL: Pick<TCaSigningConfigDALFactory, "findByCaId" | "create" | "deleteById" | "transaction">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emitForProject">;caKeySourceService: Pick<diff --git a/backend/src/services/certificate-common/certificate-quota-fns.test.ts b/backend/src/services/certificate-common/certificate-quota-fns.test.tsnew file mode 100644index 0000000000..2a66dea103--- /dev/null+++ b/backend/src/services/certificate-common/certificate-quota-fns.test.ts@@ -0,0 +1,116 @@+import { InstanceType } from "@app/ee/services/license/license-types";++import { assertCertificateQuota, TCertificateQuotaDeps } from "./certificate-quota-fns";+import { buildCertificateQuotaKey } from "./certificate-quota-key";+import { PKI_INSTANCE_QUOTA_SCOPE } from "./certificate-quota-scope";++const buildDeps = ({+ instanceType,+ maxCertificates = null,+ maxWildcardCertificates = null,+ total = 0,+ wildcard = 0,+ activeKeys = [],+ calls+}: {+ instanceType: InstanceType;+ maxCertificates?: number | null;+ maxWildcardCertificates?: number | null;+ total?: number;+ wildcard?: number;+ activeKeys?: string[];+ calls: { counted: (string | undefined)[]; activeChecked: (string | undefined)[] };+}) =>+ ({+ projectDAL: { findById: async () => ({ id: "project-1", orgId: "sub-org" }) },+ licenseService: {+ getPlan: async () => ({ maxCertificates, maxWildcardCertificates }),+ getInstanceType: () => instanceType+ },+ usageCounterDAL: {+ resolveRootOrgId: async () => "root-org",+ countActiveCertificateQuotaKeysByOrg: async (orgId?: string) => {+ calls.counted.push(orgId);+ return { total, wildcard };+ },+ isCertificateQuotaKeyActiveInOrg: async (orgId: string | undefined, quotaKey: string) => {+ calls.activeChecked.push(orgId);+ return activeKeys.includes(quotaKey);+ }+ },+ keyStore: { getItem: async () => null, setItemWithExpiry: async () => "OK", deleteItem: async () => 1 }+ }) as unknown as TCertificateQuotaDeps;++const newCalls = () => ({ counted: [] as (string | undefined)[], activeChecked: [] as (string | undefined)[] });++describe("assertCertificateQuota scope", () => {+ test.each([InstanceType.EnterpriseOnPrem, InstanceType.EnterpriseOnPremOffline])(+ "counts every organization on the instance under a self-hosted license (%s)",+ async (instanceType) => {+ const calls = newCalls();+ await expect(+ assertCertificateQuota({+ orgId: "sub-org",+ commonName: "a.example.test",+ deps: buildDeps({ instanceType, maxCertificates: 5, total: 5, calls })+ })+ ).rejects.toThrow("(5 of 5 active certificates across this instance)");+ expect(calls).toEqual({ counted: [undefined], activeChecked: [undefined] });+ }+ );++ test("keys the instance-wide cache on the instance scope", async () => {+ const calls = newCalls();+ const result = await assertCertificateQuota({+ orgId: "sub-org",+ commonName: "a.example.test",+ deps: buildDeps({ instanceType: InstanceType.EnterpriseOnPremOffline, maxCertificates: 5, total: 1, calls })+ });+ expect(result).toMatchObject({ isNewQuotaKey: true, quotaOrgId: PKI_INSTANCE_QUOTA_SCOPE });+ });++ // A name another organization already holds is not a new unit of the shared count, so it must not+ // be refused at the cap.+ test("lets a name already active anywhere on the instance through at the cap", async () => {+ const calls = newCalls();+ const result = await assertCertificateQuota({+ orgId: "sub-org",+ commonName: "a.example.test",+ deps: buildDeps({+ instanceType: InstanceType.EnterpriseOnPremOffline,+ maxCertificates: 5,+ total: 5,+ activeKeys: [buildCertificateQuotaKey({ commonName: "a.example.test" })],+ calls+ })+ });+ expect(result.isNewQuotaKey).toBe(false);+ expect(calls.activeChecked).toEqual([undefined]);+ });++ test("names the instance in the refusal of an approved request", async () => {+ const calls = newCalls();+ await expect(+ assertCertificateQuota({+ orgId: "sub-org",+ commonName: "*.example.test",+ isApprovedRequest: true,+ deps: buildDeps({ instanceType: InstanceType.EnterpriseOnPrem, maxWildcardCertificates: 2, wildcard: 2, calls })+ })+ ).rejects.toThrow("this instance has since reached its plan limit of 2 active wildcard certificates");+ });++ test.each([InstanceType.Cloud, InstanceType.OnPrem])(+ "counts the root organization's tree on %s",+ async (instanceType) => {+ const calls = newCalls();+ const result = await assertCertificateQuota({+ orgId: "sub-org",+ commonName: "a.example.test",+ deps: buildDeps({ instanceType, maxCertificates: 5, total: 1, calls })+ });+ expect(result.quotaOrgId).toBe("root-org");+ expect(calls).toEqual({ counted: ["root-org"], activeChecked: ["sub-org"] });+ }+ );+});diff --git a/backend/src/services/certificate-common/certificate-quota-fns.ts b/backend/src/services/certificate-common/certificate-quota-fns.tsindex f762503665..dae51c01ac 100644--- a/backend/src/services/certificate-common/certificate-quota-fns.ts+++ b/backend/src/services/certificate-common/certificate-quota-fns.ts@@ -6,12 +6,13 @@ import { TUsageCounterDALFactory } from "@app/services/license-client/usage/usagimport { TProjectDALFactory } from "@app/services/project/project-dal";import { buildCertificateQuotaKey, certificateHasWildcard } from "./certificate-quota-key";+import { isInstanceWidePkiQuota, PKI_INSTANCE_QUOTA_SCOPE } from "./certificate-quota-scope";type TQuotaCounts = { total: number; wildcard: number };export type TCertificateQuotaDeps = {projectDAL: Pick<TProjectDALFactory, "findById">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;usageCounterDAL: Pick<TUsageCounterDALFactory,"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"@@ -21,6 +22,7 @@ export type TCertificateQuotaDeps = {// 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.+// orgId is the cache scope: a root org id, or PKI_INSTANCE_QUOTA_SCOPE for an instance-wide count.const $getQuotaCounts = async (orgId: string, deps: TCertificateQuotaDeps): Promise<TQuotaCounts> => {const totalKey = KeyStorePrefixes.PkiCertificateQuotaCount(orgId);const wildcardKey = KeyStorePrefixes.PkiWildcardCertificateQuotaCount(orgId);@@ -39,7 +41,9 @@ const $getQuotaCounts = async (orgId: string, deps: TCertificateQuotaDeps): Promlogger.error(error, `Failed to read certificate quota cache [orgId=${orgId}]`);}- const counts = await deps.usageCounterDAL.countActiveCertificateQuotaKeysByOrg(orgId);+ const counts = await deps.usageCounterDAL.countActiveCertificateQuotaKeysByOrg(+ orgId === PKI_INSTANCE_QUOTA_SCOPE ? undefined : orgId+ );try {const ttl = KeyStoreTtls.PkiCertificateQuotaCountInSeconds;@@ -85,8 +89,9 @@ export const assertCertificateQuota = async ({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.+ // quotaOrgId is the scope the cache is keyed on: the tree root, or PKI_INSTANCE_QUOTA_SCOPE when the+ // caps count the whole instance. 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 = certificateHasWildcard({ commonName, altNames });@@ -97,11 +102,18 @@ export const assertCertificateQuota = async ({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);+ // Correctness, not an optimization: reissuing names already held in the counted scope cannot raise+ // either count, and this is what lets an org sitting at its cap keep renewing. Remove it and its+ // certs expire.+ const isInstanceWide = isInstanceWidePkiQuota(deps.licenseService);+ const isAlreadyActive = await deps.usageCounterDAL.isCertificateQuotaKeyActiveInOrg(+ isInstanceWide ? undefined : orgId,+ quotaKey+ );+ const quotaOrgId = isInstanceWide ? PKI_INSTANCE_QUOTA_SCOPE : await deps.usageCounterDAL.resolveRootOrgId(orgId);if (isAlreadyActive) return { quotaKey, isNewQuotaKey: false, quotaOrgId, isWildcard };+ const scopeNote = isInstanceWide ? " across this instance" : "";+ const holder = isInstanceWide ? "this instance" : "your organization";// 0 is how a plan says it has no wildcard support at all.if (isWildcard && maxWildcardCertificates === 0) {@@ -115,11 +127,11 @@ export const assertCertificateQuota = async ({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.`+ message: `This certificate request was approved, but ${holder} 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.`+ message: `Failed to issue certificate due to plan limit reached (${used} of ${cap} ${subject}${scopeNote}). Upgrade plan to issue more certificates.`});};diff --git a/backend/src/services/certificate-common/certificate-quota-scope.ts b/backend/src/services/certificate-common/certificate-quota-scope.tsnew file mode 100644index 0000000000..bceb3abbdb--- /dev/null+++ b/backend/src/services/certificate-common/certificate-quota-scope.ts@@ -0,0 +1,9 @@+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";+import { InstanceType } from "@app/ee/services/license/license-types";++export const isInstanceWidePkiQuota = (licenseService: Pick<TLicenseServiceFactory, "getInstanceType">) => {+ const instanceType = licenseService.getInstanceType();+ return instanceType === InstanceType.EnterpriseOnPrem || instanceType === InstanceType.EnterpriseOnPremOffline;+};++export const PKI_INSTANCE_QUOTA_SCOPE = "instance";diff --git a/backend/src/services/certificate-v3/certificate-approval-fns.ts b/backend/src/services/certificate-v3/certificate-approval-fns.tsindex d11ad945d4..e85a13d3c3 100644--- a/backend/src/services/certificate-v3/certificate-approval-fns.ts+++ b/backend/src/services/certificate-v3/certificate-approval-fns.ts@@ -110,7 +110,7 @@ export type TIssueCertificateFromApprovedRequestDeps = {resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;pkiApplicationProfileDAL: Pick<TPkiApplicationProfileDALFactory, "findOneByApplicationAndProfile">;apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;usageCounterDAL: Pick<TUsageCounterDALFactory,"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"diff --git a/backend/src/services/certificate-v3/certificate-renewal-service.ts b/backend/src/services/certificate-v3/certificate-renewal-service.tsindex 29c05f253e..aa887570e6 100644--- a/backend/src/services/certificate-v3/certificate-renewal-service.ts+++ b/backend/src/services/certificate-v3/certificate-renewal-service.ts@@ -173,7 +173,7 @@ type TCertificateRenewalServiceFactoryDep = {"findAllByProfileId" | "findOneByApplicationAndProfile">;apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;quotaDeps: TCertificateQuotaDeps;recordQuotaUsage: (usage?: { orgId: string; isNewQuotaKey: boolean; isWildcard: boolean }) => Promise<void>;resolveApplicationIdForProfile: TResolveApplicationIdForProfile;diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.tsindex 428f319a75..d745d5872c 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts@@ -10,6 +10,7 @@ import { createMongoAbility, ForbiddenError } from "@casl/ability";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";+import { InstanceType } from "@app/ee/services/license/license-types";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionCertificateActions,@@ -195,7 +196,7 @@ describe("CertificateV3Service", () => {const mockUsageCounterDAL = {resolveRootOrgId: vi.fn(async (id: string) => id),countActiveCertificateQuotaKeysByOrg: vi.fn(async () => ({ total: 0, wildcard: 0 })),- isCertificateQuotaKeyActiveInOrg: vi.fn((orgId: string, quotaKey: string) =>+ isCertificateQuotaKeyActiveInOrg: vi.fn((orgId: string | undefined, quotaKey: string) =>Promise.resolve(Boolean(orgId && quotaKey && false)))};@@ -207,7 +208,8 @@ describe("CertificateV3Service", () => {};const mockLicenseService = {- getPlan: vi.fn().mockResolvedValue({ pkiPqc: true })+ getPlan: vi.fn().mockResolvedValue({ pkiPqc: true }),+ getInstanceType: vi.fn(() => InstanceType.OnPrem)};const mockCertificateIssuanceQueue = {diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.tsindex ecfbbcadab..89ce692f1a 100644--- a/backend/src/services/certificate-v3/certificate-v3-service.ts+++ b/backend/src/services/certificate-v3/certificate-v3-service.ts@@ -199,7 +199,7 @@ type TCertificateV3ServiceFactoryDep = {>;pkiApplicationDAL: Pick<TPkiApplicationDALFactory, "findById">;apiEnrollmentConfigDAL: Pick<TApiEnrollmentConfigDALFactory, "findById">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;usageCounterDAL: Pick<TUsageCounterDALFactory,"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.tsindex 39ead7d476..afd88e8bd6 100644--- a/backend/src/services/certificate/certificate-service.ts+++ b/backend/src/services/certificate/certificate-service.ts@@ -161,7 +161,7 @@ type TCertificateServiceFactoryDep = {resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;certificateAlertEventEmitter: Pick<TCertificateAlertEventEmitter, "notify">;- licenseService: Pick<TLicenseServiceFactory, "getPlan">;+ licenseService: Pick<TLicenseServiceFactory, "getPlan" | "getInstanceType">;usageCounterDAL: Pick<TUsageCounterDALFactory,"countActiveCertificateQuotaKeysByOrg" | "isCertificateQuotaKeyActiveInOrg" | "resolveRootOrgId"diff --git a/backend/src/services/license-client/usage/usage-counter-dal.ts b/backend/src/services/license-client/usage/usage-counter-dal.tsindex cfcefe8aed..4b04c51744 100644--- a/backend/src/services/license-client/usage/usage-counter-dal.ts+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts@@ -131,7 +131,8 @@ export const usageCounterDALFactory = (db: TDbClient) => {};// 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> => {+ // orgId omitted means instance-wide+ const isCertificateQuotaKeyActiveInOrg = async (orgId: string | undefined, quotaKey: string): Promise<boolean> => {try {const row = (await $activeQuotaCertificates(orgId).where(`${TableName.Certificate}.quotaKey`, quotaKey)diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.tsindex 735fa91b42..4133131256 100644--- a/frontend/src/hooks/api/subscriptions/types.ts+++ b/frontend/src/hooks/api/subscriptions/types.ts@@ -31,6 +31,7 @@ export type SubscriptionPlan = {id: string;memberLimit: number;identityLimit: number;+ enforceIdentityLimit?: boolean;auditLogs: boolean;dynamicSecret: boolean;auditLogsRetentionDays: number | null;diff --git a/frontend/src/pages/organization/BillingPage/BillingPage.tsx b/frontend/src/pages/organization/BillingPage/BillingPage.tsxindex 276afc2269..9fd25c0b49 100644--- a/frontend/src/pages/organization/BillingPage/BillingPage.tsx+++ b/frontend/src/pages/organization/BillingPage/BillingPage.tsx@@ -1,16 +1,3 @@-import { useSubscription } from "@app/context";-import { BillingV2Page } from "../BillingV2Page";-import { OfflineBillingPage } from "./OfflineBillingPage";--export const BillingPage = () => {- const { subscription } = useSubscription();-- // Offline (air-gapped) licenses can't reach the license server, so the billing surface can't load;- // short-circuit to the offline page (no API calls) before mounting it.- if (subscription?.isOffline) {- return <OfflineBillingPage />;- }- return <BillingV2Page />;-};+export const BillingPage = () => <BillingV2Page />;diff --git a/frontend/src/pages/organization/BillingPage/OfflineBillingPage.tsx b/frontend/src/pages/organization/BillingPage/OfflineBillingPage.tsxdeleted file mode 100644index 68c320350a..0000000000--- a/frontend/src/pages/organization/BillingPage/OfflineBillingPage.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { Helmet } from "react-helmet";-import { useTranslation } from "react-i18next";-import { ExternalLink, TriangleAlert } from "lucide-react";--import {- SELF_HOSTED_CONTACT_SALES_URL,- SELF_HOSTED_LICENSE_COPY-} from "@app/components/license/self-hosted-license";-import { OrgPermissionCan } from "@app/components/permissions";-import { Alert, AlertDescription, AlertTitle, Button } from "@app/components/v3";-import { PageHeader } from "@app/components/v3/platform";-import { OrgPermissionBillingActions, OrgPermissionSubjects } from "@app/context";--// Standalone billing page for offline (air-gapped) licenses. It makes no API calls — the license-// server is unreachable, so every billing/subscription request would fail — and just explains that-// billing is managed out-of-band.-export const OfflineBillingPage = () => {- const { t } = useTranslation();-- return (- <div className="bg-page">- <Helmet>- <title>{t("common.head-title", { title: t("billing.title") })}</title>- <link rel="icon" href="/infisical.ico" />- <meta property="og:image" content="/images/message.png" />- </Helmet>- <div className="flex w-full justify-center bg-page text-foreground-inverse">- <div className="w-full max-w-8xl">- <PageHeader- scope="org"- title={t("billing.title")}- description={SELF_HOSTED_LICENSE_COPY.offline.pageDescription}- />- <OrgPermissionCan- passThrough={false}- I={OrgPermissionBillingActions.Read}- a={OrgPermissionSubjects.Billing}- >- <Alert variant="info">- <TriangleAlert />- <AlertTitle>{SELF_HOSTED_LICENSE_COPY.offline.title}</AlertTitle>- <AlertDescription>- {SELF_HOSTED_LICENSE_COPY.offline.detail}- <div className="mt-3">- <Button variant="outline" size="sm" asChild>- <a- href={SELF_HOSTED_CONTACT_SALES_URL}- target="_blank"- rel="noopener noreferrer"- >- Contact Sales- <ExternalLink />- </a>- </Button>- </div>- </AlertDescription>- </Alert>- </OrgPermissionCan>- </div>- </div>- </div>- );-};diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsxindex ba0b9d3655..4e78ad7fa0 100644--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx@@ -37,6 +37,7 @@ import { ALL_ORGS_VALUE } from "./components/RootOrgFilter";import { UsageBreakdownSheet } from "./components/UsageBreakdownSheet";import { catalogById } from "./billing-v2-format";import { BillingV2RenderState } from "./billing-v2-view-types";+import { useOfflineBilling } from "./useOfflineBilling";const CONTACT_SALES_URL = "https://infisical.com/talk-to-us";@@ -55,6 +56,7 @@ export const BillingV2Page = () => {const { permission } = useOrgPermission();const { subscription } = useSubscription();const orgId = currentOrg?.id ?? "";+ const isOfflineLicense = getSelfHostedLicenseState(subscription) === "offline";const hasManageBillingPermission = permission.can(OrgPermissionBillingActions.ManageBilling,OrgPermissionSubjects.Billing@@ -82,14 +84,11 @@ export const BillingV2Page = () => {const { data: unsearchedOrgPage, isPending: isRootOrgCountPending } =useGetBillingV2Organizations(orgId, { limit: ORG_PAGE_SIZE });- const {- data: overview,- isPending,- isPlaceholderData,- isError,- refetch- } = useGetBillingV2Overview(selectedOrgId);- const { data: catalog = [], isPending: isCatalogPending } = useGetBillingV2Catalog(selectedOrgId);+ const onlineOverview = useGetBillingV2Overview(selectedOrgId, { enabled: !isOfflineLicense });+ const { data: onlineCatalog = [], isPending: isOnlineCatalogPending } = useGetBillingV2Catalog(+ selectedOrgId,+ { enabled: !isOfflineLicense }+ );const createPortalSession = useCreateBillingV2PortalSession();const addPaymentMethod = useAddBillingV2PaymentMethod();const confirmTrialPayment = useConfirmBillingV2TrialPayment();@@ -102,6 +101,22 @@ export const BillingV2Page = () => {const rootOrgCount = unsearchedOrgPage?.totalCount ?? 0;const showOrgFilter = rootOrgCount > 1;+ const offlineBilling = useOfflineBilling({+ orgId: selectedOrgId,+ scope: showOrgFilter ? breakdownScope : "organization",+ enabled:+ isOfflineLicense &&+ !isRootOrgCountPending &&+ permission.can(OrgPermissionBillingActions.Read, OrgPermissionSubjects.Billing)+ });+ const overview = isOfflineLicense ? offlineBilling.overview : onlineOverview.data;+ const isPending = isOfflineLicense ? offlineBilling.isPending : onlineOverview.isPending;+ const isPlaceholderData = !isOfflineLicense && onlineOverview.isPlaceholderData;+ const isError = isOfflineLicense ? offlineBilling.isError : onlineOverview.isError;+ const refetch = isOfflineLicense ? offlineBilling.refetch : onlineOverview.refetch;+ const catalog = isOfflineLicense ? offlineBilling.catalog : onlineCatalog;+ const isCatalogPending = !isOfflineLicense && isOnlineCatalogPending;+const [flow, setFlow] = useState<BillingV2Flow | null>(null);const openedUpgradeProduct = useRef(false);const [removeProdId, setRemoveProdId] = useState<string | null>(null);diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-offline-usage.test.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-offline-usage.test.tsnew file mode 100644index 0000000000..8baefdd8f2--- /dev/null+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-offline-usage.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it } from "vitest";++import { BillingV2BreakdownDimension as D } from "@app/hooks/api/billingV2/types";+import { SubscriptionPlan, SubscriptionPlanTypes } from "@app/hooks/api/subscriptions/types";++import {+ buildOfflineBilling,+ offlineQueryDimensions,+ OfflineUsagePlan,+ resolveOfflineLimit+} from "./billing-v2-offline-usage";++const plan = (overrides: Partial<OfflineUsagePlan> = {}): OfflineUsagePlan => ({+ slug: SubscriptionPlanTypes.Enterprise,+ identityLimit: null as unknown as number,+ maxCas: null,+ maxInternalCas: null,+ maxCertificates: null,+ maxWildcardCertificates: null,+ ...overrides+});++const productPlan = (productKey: string, status: string | null = "active") => ({+ productKey,+ planKey: "enterprise",+ status,+ trialPlanKey: null,+ trialEndsAt: null+});++const usageOf = (totals: Partial<Record<D, number>>) =>+ Object.fromEntries(Object.entries(totals).map(([key, total]) => [key, { total, unit: "unit" }]));++describe("resolveOfflineLimit", () => {+ it("skips the identity cap on an enterprise plan unless the key enforces it", () => {+ expect(resolveOfflineLimit(D.Identities, plan({ identityLimit: 50 }))).toBeNull();+ expect(+ resolveOfflineLimit(D.Identities, plan({ identityLimit: 50, enforceIdentityLimit: true }))+ ).toBe(50);+ });++ it("enforces the identity cap on a non-enterprise plan, and never a 0 or null cap", () => {+ expect(+ resolveOfflineLimit(D.Identities, plan({ slug: SubscriptionPlanTypes.Pro, identityLimit: 5 }))+ ).toBe(5);+ expect(+ resolveOfflineLimit(D.Identities, plan({ identityLimit: 0, enforceIdentityLimit: true }))+ ).toBeNull();+ expect(resolveOfflineLimit(D.Identities, plan({ enforceIdentityLimit: true }))).toBeNull();+ });++ it("uses maxInternalCas for internal CAs, falling back to maxCas only when it is tighter", () => {+ expect(resolveOfflineLimit(D.InternalCas, plan({ maxInternalCas: 10 }))).toBe(10);+ expect(resolveOfflineLimit(D.InternalCas, plan({ maxCas: 1 }))).toBe(1);+ // Both set: the backend honours the larger as the all-types cap, so maxInternalCas binds.+ expect(resolveOfflineLimit(D.InternalCas, plan({ maxCas: 3, maxInternalCas: 10 }))).toBe(10);+ expect(resolveOfflineLimit(D.InternalCas, plan({ maxCas: 10, maxInternalCas: 3 }))).toBe(3);+ expect(resolveOfflineLimit(D.InternalCas, plan())).toBeNull();+ });++ it("treats a 0 PKI cap as a real limit, since the backend refuses every create against it", () => {+ expect(resolveOfflineLimit(D.InternalCas, plan({ maxInternalCas: 0 }))).toBe(0);+ expect(resolveOfflineLimit(D.ActiveCerts, plan({ maxCertificates: 0 }))).toBe(0);+ expect(resolveOfflineLimit(D.WildcardCerts, plan({ maxWildcardCertificates: 0 }))).toBe(0);+ });++ it("maps certificates to their caps", () => {+ expect(resolveOfflineLimit(D.ActiveCerts, plan({ maxCertificates: 100 }))).toBe(100);+ expect(resolveOfflineLimit(D.WildcardCerts, plan({ maxWildcardCertificates: 5 }))).toBe(5);+ expect(resolveOfflineLimit(D.ActiveCerts, plan())).toBeNull();+ });++ it("shows no limit for dimensions without an enforced cap", () => {+ const capped = plan({+ identityLimit: 1,+ enforceIdentityLimit: true,+ maxCas: 1,+ maxInternalCas: 1,+ maxCertificates: 1,+ maxWildcardCertificates: 1+ }) as OfflineUsagePlan & Pick<SubscriptionPlan, "memberLimit" | "maxPamAccounts">;+ capped.memberLimit = 1;+ capped.maxPamAccounts = 1;+ expect(resolveOfflineLimit(D.UserIdentities, capped)).toBeNull();+ expect(resolveOfflineLimit(D.SecretIdentities, capped)).toBeNull();+ expect(resolveOfflineLimit(D.PamIdentities, capped)).toBeNull();+ });+});++describe("offlineQueryDimensions", () => {+ it("queries every dimension for a v1 key", () => {+ expect(offlineQueryDimensions(plan())).toHaveLength(7);+ });++ it("skips products a v2 key does not list or lists as churned", () => {+ const keys = offlineQueryDimensions(+ plan({+ productPlans: [+ productPlan("legacy_secret_management"),+ productPlan("cert_management"),+ productPlan("pam", "churned")+ ]+ })+ );+ expect(keys).toEqual([+ D.Identities,+ D.UserIdentities,+ D.InternalCas,+ D.ActiveCerts,+ D.WildcardCerts+ ]);+ });+});++describe("buildOfflineBilling", () => {+ it("shapes a managed overview with every product licensed on a v1 key", () => {+ const { overview, catalog } = buildOfflineBilling(+ plan({ maxInternalCas: 6 }),+ usageOf({ [D.Identities]: 5, [D.UserIdentities]: 1, [D.InternalCas]: 3 })+ );+ expect(overview.mode).toBe("managed");+ expect(overview.selfServe).toBe(false);+ expect(catalog.map((product) => product.id)).toEqual([+ "legacy_secret_management",+ "secrets_manager",+ "cert_management",+ "pam"+ ]);+ expect(overview.billing.activeProductCount).toBe(4);+ const cas = overview.entitlements.cert_management.dimensions?.find(+ (dim) => dim.key === D.InternalCas+ );+ expect(cas).toMatchObject({ used: 3, limit: 6, committed: null, metered: false });+ });++ it("splits the legacy identity meters from the new Secrets Management product", () => {+ const { overview } = buildOfflineBilling(+ plan(),+ usageOf({ [D.Identities]: 5, [D.UserIdentities]: 1, [D.SecretIdentities]: 4 })+ );+ expect(+ overview.entitlements.legacy_secret_management.dimensions?.map((dim) => dim.label)+ ).toEqual(["Identities", "User Identities"]);+ expect(overview.entitlements.secrets_manager.dimensions?.map((dim) => dim.label)).toEqual([+ "Secret Identities"+ ]);+ });++ it("keeps every v1 product whatever the selected scope counts", () => {+ const { overview } = buildOfflineBilling(plan(), usageOf({}));+ expect(Object.keys(overview.entitlements)).toHaveLength(4);+ expect(overview.entitlements.secrets_manager.dimensions?.[0]).toMatchObject({+ used: 0,+ limit: null+ });+ });++ it("lists unlicensed v2 products without an entitlement, so they render as not in the license", () => {+ const { overview, catalog } = buildOfflineBilling(+ plan({+ productPlans: [+ productPlan("legacy_secret_management"),+ productPlan("cert_management"),+ productPlan("pam", "churned")+ ]+ }),+ usageOf({ [D.Identities]: 2 })+ );+ expect(catalog.map((product) => product.id)).toEqual([+ "legacy_secret_management",+ "secrets_manager",+ "cert_management",+ "pam"+ ]);+ expect(Object.keys(overview.entitlements)).toEqual([+ "legacy_secret_management",+ "cert_management"+ ]);+ });++ it("marks the legacy product deprecated so it hides when the key does not include it", () => {+ const { catalog, overview } = buildOfflineBilling(+ plan({ productPlans: [productPlan("secrets_manager")] }),+ usageOf({})+ );+ expect(catalog.find((product) => product.id === "legacy_secret_management")?.deprecated).toBe(+ true+ );+ expect(Object.keys(overview.entitlements)).toEqual(["secrets_manager"]);+ });++ it("uses the v2 plan key as the product tier", () => {+ const { overview } = buildOfflineBilling(+ plan({ productPlans: [{ ...productPlan("cert_management"), planKey: "pro" }] }),+ usageOf({})+ );+ expect(overview.entitlements.cert_management.planTier).toBe("pro");+ });+});diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-offline-usage.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-offline-usage.tsnew file mode 100644index 0000000000..4093a03e95--- /dev/null+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-offline-usage.ts@@ -0,0 +1,199 @@+import { BillingProduct } from "@app/components/license/UpgradeGate/upgrade-intents";+import {+ BillingV2BreakdownDimension,+ BillingV2CatalogProduct,+ BillingV2EntitlementDim,+ BillingV2Overview+} from "@app/hooks/api/billingV2/types";+import { SubscriptionPlan, SubscriptionPlanTypes } from "@app/hooks/api/subscriptions/types";++const LEGACY_SECRETS_PRODUCT = "legacy_secret_management";++type OfflineProductDef = {+ name: string;+ icon: string;+ color: string;+ displayOrder: number;+ deprecated?: boolean;+ dimensions: { key: BillingV2BreakdownDimension; label: string }[];+};++const OFFLINE_PRODUCTS: Record<string, OfflineProductDef> = {+ [LEGACY_SECRETS_PRODUCT]: {+ name: "Legacy Secret Management",+ icon: "key_round",+ color: "var(--color-neutral)",+ displayOrder: 0,+ deprecated: true,+ dimensions: [+ { key: BillingV2BreakdownDimension.Identities, label: "Identities" },+ { key: BillingV2BreakdownDimension.UserIdentities, label: "User Identities" }+ ]+ },+ [BillingProduct.SecretsManagement]: {+ name: "Secrets Management",+ icon: "key_round",+ color: "var(--color-product-sm)",+ displayOrder: 1,+ dimensions: [{ key: BillingV2BreakdownDimension.SecretIdentities, label: "Secret Identities" }]+ },+ [BillingProduct.CertificateManagement]: {+ name: "Certificate Management",+ icon: "file_badge",+ color: "var(--color-product-pki)",+ displayOrder: 2,+ dimensions: [+ { key: BillingV2BreakdownDimension.InternalCas, label: "Internal CAs" },+ { key: BillingV2BreakdownDimension.ActiveCerts, label: "Active Certificates" },+ { key: BillingV2BreakdownDimension.WildcardCerts, label: "Wildcard Certificates" }+ ]+ },+ [BillingProduct.Pam]: {+ name: "Privileged Access Management",+ icon: "users",+ color: "var(--color-product-pam)",+ displayOrder: 3,+ dimensions: [{ key: BillingV2BreakdownDimension.PamIdentities, label: "PAM Identities" }]+ }+};++export type OfflineUsagePlan = Pick<+ SubscriptionPlan,+ | "slug"+ | "identityLimit"+ | "enforceIdentityLimit"+ | "maxCas"+ | "maxInternalCas"+ | "maxCertificates"+ | "maxWildcardCertificates"+ | "productPlans"+>;++const asCap = (value: number | null | undefined) => (typeof value === "number" ? value : null);++const effectiveMaxCas = (plan: OfflineUsagePlan) => {+ const maxCas = asCap(plan.maxCas);+ const maxInternalCas = asCap(plan.maxInternalCas);+ return maxCas !== null && maxInternalCas !== null ? Math.max(maxCas, maxInternalCas) : maxCas;+};++export const resolveOfflineLimit = (+ key: BillingV2BreakdownDimension,+ plan: OfflineUsagePlan+): number | null => {+ switch (key) {+ case BillingV2BreakdownDimension.Identities:+ if (plan.slug === SubscriptionPlanTypes.Enterprise && !plan.enforceIdentityLimit) return null;+ return plan.identityLimit || null;+ case BillingV2BreakdownDimension.InternalCas: {+ const caps = [asCap(plan.maxInternalCas), effectiveMaxCas(plan)].filter(+ (cap): cap is number => cap !== null+ );+ return caps.length > 0 ? Math.min(...caps) : null;+ }+ case BillingV2BreakdownDimension.ActiveCerts:+ return asCap(plan.maxCertificates);+ case BillingV2BreakdownDimension.WildcardCerts:+ return asCap(plan.maxWildcardCertificates);+ default:+ return null;+ }+};++type ResolvedOfflineProduct = {+ id: string;+ def: OfflineProductDef;+ isLicensed: boolean;+ planTier: string;+};++export const resolveOfflineProducts = (plan: OfflineUsagePlan): ResolvedOfflineProduct[] => {+ const { productPlans } = plan;+ const v1Tier = plan.slug ?? SubscriptionPlanTypes.Enterprise;+ return Object.entries(OFFLINE_PRODUCTS).map(([id, def]) => {+ const entry = productPlans?.find(+ (product) => product.productKey === id && product.status !== "churned"+ );+ return {+ id,+ def,+ isLicensed: !productPlans || Boolean(entry),+ planTier: entry?.planKey ?? v1Tier+ };+ });+};++export const offlineQueryDimensions = (plan: OfflineUsagePlan) =>+ resolveOfflineProducts(plan)+ .filter((product) => product.isLicensed)+ .flatMap((product) => product.def.dimensions.map((dim) => dim.key));++export type OfflineDimensionUsage = { total: number; unit: string };++export const buildOfflineBilling = (+ plan: OfflineUsagePlan,+ usage: Partial<Record<BillingV2BreakdownDimension, OfflineDimensionUsage>>+): { overview: BillingV2Overview; catalog: BillingV2CatalogProduct[] } => {+ const catalog: BillingV2CatalogProduct[] = [];+ const entitlements: BillingV2Overview["entitlements"] = {};++ resolveOfflineProducts(plan).forEach((product) => {+ const dimensions: BillingV2EntitlementDim[] = product.def.dimensions.map((dim) => ({+ key: dim.key,+ label: dim.label,+ noun: usage[dim.key]?.unit ?? dim.label,+ unit: usage[dim.key]?.unit ?? dim.label,+ metered: false,+ cadence: null,+ used: usage[dim.key]?.total ?? 0,+ limit: resolveOfflineLimit(dim.key, plan),+ committed: null,+ commitAvailable: false,+ onDemandAmount: 0+ }));+ catalog.push({+ id: product.id,+ name: product.def.name,+ icon: product.def.icon,+ color: product.def.color,+ displayOrder: product.def.displayOrder,+ deprecated: product.def.deprecated,+ plans: []+ });+ if (product.isLicensed) {+ entitlements[product.id] = {+ entitled: true,+ status: "active",+ planTier: product.planTier,+ dimensions+ };+ }+ });++ return {+ catalog,+ overview: {+ isCloud: false,+ mode: "managed",+ subState: "active",+ planName: "Offline License",+ billing: {+ monthlyRecurring: 0,+ annualCommitted: 0,+ activeProductCount: Object.keys(entitlements).length,+ nextCharge: null+ },+ onDemandAmount: 0,+ payment: null,+ billingDetails: null,+ invoices: [],+ entitlements,+ trialedProductKeys: [],+ trials: [],+ trialPaymentDue: null,+ paymentAlert: null,+ checkoutFrozen: false,+ selfServe: false+ }+ };+};diff --git a/frontend/src/pages/organization/BillingV2Page/components/ProductOverviewCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/ProductOverviewCard.tsxindex 19ad7fbf51..3c5f05eb9d 100644--- a/frontend/src/pages/organization/BillingV2Page/components/ProductOverviewCard.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/ProductOverviewCard.tsx@@ -271,6 +271,12 @@ const UsageDistribution = ({if (!entry.isRoot) subOrgIndex += 1;return { entry, shade };});+ const rootCount = breakdown.scopes+ .filter((entry) => entry.isRoot)+ .reduce((sum, entry) => sum + entry.count, 0);+ const subOrgCount = breakdown.scopes+ .filter((entry) => !entry.isRoot)+ .reduce((sum, entry) => sum + entry.count, 0);const projects = breakdown.hasProjectDetail? breakdown.scopes.flatMap((entry) => entry.projects.map((project) => ({ ...project, org: entry.name })))@@ -280,13 +286,15 @@ const UsageDistribution = ({body = (<><div className="flex h-2 w-full gap-0.5 overflow-hidden rounded-xs bg-border">- {shaded.map(({ entry, shade }) => (+ {rootCount > 0 && (+ <span className="h-full bg-org/85" style={{ width: `${(rootCount / total) * 100}%` }} />+ )}+ {subOrgCount > 0 && (<span- key={entry.orgId}- className={cn("h-full", shade)}- style={{ width: `${(entry.count / total) * 100}%` }}+ className="h-full bg-sub-org/85"+ style={{ width: `${(subOrgCount / total) * 100}%` }}/>- ))}+ )}</div><div className="flex flex-col gap-2.5">{shaded.map(({ entry, shade }) => (diff --git a/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsxindex ef34b4cf80..89746074c7 100644--- a/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/RootOrgFilter.tsx@@ -45,29 +45,30 @@ export const RootOrgFilter = ({const selectedOrg = orgInPage ?? (lastSelected?.id === value ? lastSelected : null);return (- <Combobox<BillingV2Organization>- id="billing-root-org-filter"- className="w-[34rem] max-w-full"- placeholder="Select an organization..."- searchPlaceholder="Search organizations..."- searchAriaLabel="Search root organizations"- isLoading={isLoading}- isClearable={false}- options={options}- value={selectedOrg}- getOptionGroup={(option) => (option.id === ALL_ORGS_VALUE ? "" : "Organizations")}- onValueChange={(option) => onChange(option.id)}- onSearchChange={onSearchChange}- getOptionValue={(option) => option.id}- getOptionLabel={(option) => option.name}- renderOption={(option) => <OrgLabel org={option} />}- renderValue={(option) => <OrgLabel org={option} />}- emptyMessage="No organizations found"- listFooter={- totalCount > orgs.length- ? `Showing ${orgs.length.toLocaleString()} of ${totalCount.toLocaleString()}. Type in the input to search.`- : null- }- />+ <div className="w-[34rem] max-w-full">+ <Combobox<BillingV2Organization>+ id="billing-root-org-filter"+ placeholder="Select an organization..."+ searchPlaceholder="Search organizations..."+ searchAriaLabel="Search root organizations"+ isLoading={isLoading}+ isClearable={false}+ options={options}+ value={selectedOrg}+ getOptionGroup={(option) => (option.id === ALL_ORGS_VALUE ? "" : "Organizations")}+ onValueChange={(option) => onChange(option.id)}+ onSearchChange={onSearchChange}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ renderOption={(option) => <OrgLabel org={option} />}+ renderValue={(option) => <OrgLabel org={option} />}+ emptyMessage="No organizations found"+ listFooter={+ totalCount > orgs.length+ ? `Showing ${orgs.length.toLocaleString()} of ${totalCount.toLocaleString()}. Type in the input to search.`+ : null+ }+ />+ </div>);};diff --git a/frontend/src/pages/organization/BillingV2Page/useOfflineBilling.ts b/frontend/src/pages/organization/BillingV2Page/useOfflineBilling.tsnew file mode 100644index 0000000000..2ead3ebf28--- /dev/null+++ b/frontend/src/pages/organization/BillingV2Page/useOfflineBilling.ts@@ -0,0 +1,56 @@+import { useSubscription } from "@app/context";+import {+ BillingV2BreakdownDimension,+ BillingV2BreakdownScopeKind,+ useGetBillingV2UsageBreakdown+} from "@app/hooks/api";++import {+ buildOfflineBilling,+ OfflineDimensionUsage,+ offlineQueryDimensions+} from "./billing-v2-offline-usage";++export const useOfflineBilling = ({+ orgId,+ scope,+ enabled+}: {+ orgId: string;+ scope: BillingV2BreakdownScopeKind;+ enabled: boolean;+}) => {+ const { subscription } = useSubscription();+ const wanted = new Set<string>(enabled ? offlineQueryDimensions(subscription) : []);+ const keyFor = (key: BillingV2BreakdownDimension) => (wanted.has(key) ? key : null);+ const D = BillingV2BreakdownDimension;++ const queries = {+ [D.Identities]: useGetBillingV2UsageBreakdown(orgId, keyFor(D.Identities), scope),+ [D.UserIdentities]: useGetBillingV2UsageBreakdown(orgId, keyFor(D.UserIdentities), scope),+ [D.SecretIdentities]: useGetBillingV2UsageBreakdown(orgId, keyFor(D.SecretIdentities), scope),+ [D.PamIdentities]: useGetBillingV2UsageBreakdown(orgId, keyFor(D.PamIdentities), scope),+ [D.InternalCas]: useGetBillingV2UsageBreakdown(orgId, keyFor(D.InternalCas), scope),+ [D.ActiveCerts]: useGetBillingV2UsageBreakdown(orgId, keyFor(D.ActiveCerts), scope),+ [D.WildcardCerts]: useGetBillingV2UsageBreakdown(orgId, keyFor(D.WildcardCerts), scope)+ };+ const active = Object.values(D)+ .filter((key) => wanted.has(key))+ .map((key) => ({ key, query: queries[key] }));++ const isPending = !enabled || active.some(({ query }) => query.isPending);+ const failed = active.filter(({ query }) => query.isError);+ const usage: Partial<Record<BillingV2BreakdownDimension, OfflineDimensionUsage>> = {};+ active.forEach(({ key, query }) => {+ if (query.data) usage[key] = { total: query.data.total, unit: query.data.unit };+ });+ const built = isPending || failed.length > 0 ? null : buildOfflineBilling(subscription, usage);++ return {+ overview: built?.overview,+ catalog: built?.catalog ?? [],+ isPending,+ isError: failed.length > 0,+ refetch: () => Promise.all(failed.map(({ query }) => query.refetch()))+ };+};