Skip to content

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

misc: addressed reporting

Sheen Capadnganf0ca521cb814
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 a2664791d0..1d9a865126 100644
--- a/backend/src/services/license-client/usage/usage-counter-dal.ts
+++ b/backend/src/services/license-client/usage/usage-counter-dal.ts
@@ -33,25 +33,6 @@ export const usageCounterDALFactory = (db: TDbClient) => {
}
};
- const countActiveCerts = async (orgId: string): Promise<number> => {
- try {
- const row = await 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}.status`, CertStatus.ACTIVE)
- .where(`${TableName.Certificate}.notAfter`, ">", new Date())
- .whereNull(`${TableName.Certificate}.revokedAt`)
- .whereNull(`${TableName.Certificate}.renewedByCertificateId`)
- .count(`${TableName.Certificate}.id as count`)
- .first();
- return toCount(row);
- } catch (error) {
- throw new DatabaseError({ error, name: "Count active certificates for usage" });
- }
- };
-
// 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.
@@ -267,7 +248,6 @@ export const usageCounterDALFactory = (db: TDbClient) => {
return {
countInternalCas,
- countActiveCerts,
resolveRootOrgId,
countActiveCertificateQuotaKeysByOrg,
isCertificateQuotaKeyActiveInOrg,
diff --git a/backend/src/services/license-client/usage/usage-counters.ts b/backend/src/services/license-client/usage/usage-counters.ts
index 51b50da64f..0ae44c9555 100644
--- a/backend/src/services/license-client/usage/usage-counters.ts
+++ b/backend/src/services/license-client/usage/usage-counters.ts
@@ -14,6 +14,10 @@ import { TUsageCounterDALFactory } from "./usage-counter-dal";
export type TMeteredFeature = {
feature: TLimitFeatureDescriptor;
count: TFeatureCounterFn;
+ // Where the count is reported. Absent means the triggering org, which is right for a dimension
+ // counted per org. A dimension whose count spans the org tree must set this, or every sub-org
+ // reports the same tree-wide number under its own identity and the family is counted repeatedly.
+ resolveReportOrgId?: (orgId: string) => Promise<string>;
};
// Static list of every metered dimension key (no DAL needed). For callers that only need the keys, not
@@ -42,8 +46,17 @@ export const buildMeteredFeatures = ({
isCloud
}: TBuildMeteredFeaturesDep): TMeteredFeature[] => [
{ feature: IdentitiesMeter, count: (orgId) => licenseDAL.countOrgUsersAndIdentities(isCloud ? orgId : null) },
- { feature: InternalCas, count: (orgId) => usageCounterDAL.countInternalCas(orgId) },
- { feature: ActiveCerts, count: (orgId) => usageCounterDAL.countActiveCerts(orgId) },
+ // The PKI meters count the whole org tree, so both report once at the root.
+ {
+ feature: InternalCas,
+ count: (orgId) => usageCounterDAL.countInternalCas(orgId),
+ resolveReportOrgId: (orgId) => usageCounterDAL.resolveRootOrgId(orgId)
+ },
+ {
+ feature: ActiveCerts,
+ count: (orgId) => usageCounterDAL.countActiveCertificateQuotaKeysByOrg(orgId).then(({ total }) => total),
+ resolveReportOrgId: (orgId) => usageCounterDAL.resolveRootOrgId(orgId)
+ },
{
feature: SecretIdentities,
count: (orgId) => usageCounterDAL.countSecretManagementIdentities(isCloud ? orgId : undefined)
diff --git a/backend/src/services/license-client/usage/usage-event-queue.ts b/backend/src/services/license-client/usage/usage-event-queue.ts
index 96eab78505..6a8b4ef8c8 100644
--- a/backend/src/services/license-client/usage/usage-event-queue.ts
+++ b/backend/src/services/license-client/usage/usage-event-queue.ts
@@ -4,14 +4,10 @@ import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
import { QueueName, TQueueServiceFactory } from "@app/queue";
-import { ActiveCerts, InternalCas } from "../features";
import { TMeteredFeature } from "./usage-counters";
import { TUsageMeteringServiceFactory } from "./usage-metering-service";
import { TUsageReporter, UsageReportError } from "./usage-reporter";
-// Temporarily not reporting the internal-CA and certificate meters; events for these drain harmlessly.
-const SKIPPED_DIMENSION_KEYS = new Set<string>([InternalCas.key, ActiveCerts.key]);
-
// Self-hosted is a single license covering the whole database, so usage is reported once at this
// instance identity ("full database" level) rather than per organization. Mirrors
// SELF_HOSTED_LICENSE_ORG_ID in ee/license-service; inlined to avoid a services -> ee import.
@@ -48,9 +44,6 @@ export const usageEventQueueFactory = ({
// Counts the meter and reports it to the License Server only when the value changed since the last
// report. No-ops when the reporter is null (v2 disabled), so queued events drain harmlessly.
const handleUsageEvent = async (orgId: string, dimensionKey: string, observedAt: Date) => {
- if (SKIPPED_DIMENSION_KEYS.has(dimensionKey)) {
- return;
- }
if (!usageReporter) {
return;
}
@@ -64,18 +57,21 @@ export const usageEventQueueFactory = ({
}
}
+ const metered = featureByKey.get(dimensionKey);
+ if (!metered) {
+ logger.warn(`usage-metering: unknown metered feature, dropping event [dimensionKey=${dimensionKey}]`);
+ return;
+ }
+
// Self-hosted is one license over the whole database: report (and dedup) once at the instance
// identity, not per triggering org. The metered counts already span the whole instance in that
// mode, so the org that triggered the event is irrelevant here.
- const reportOrgId = isCloud ? orgId : SELF_HOSTED_LICENSE_ORG_ID;
+ //
+ // On cloud the identity is the meter's own: a tree-scoped dimension resolves to the root so the
+ // family reports once, and everything else stays keyed on the triggering org.
+ const reportOrgId = isCloud ? ((await metered.resolveReportOrgId?.(orgId)) ?? orgId) : SELF_HOSTED_LICENSE_ORG_ID;
try {
- const metered = featureByKey.get(dimensionKey);
- if (!metered) {
- logger.warn(`usage-metering: unknown metered feature, dropping event [dimensionKey=${dimensionKey}]`);
- return;
- }
-
const value = await metered.count(reportOrgId);
const lastReportedKey = KeyStorePrefixes.LicenseUsageLastReported(reportOrgId, dimensionKey);
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 5588b1ea99..c021b4b761 100644
--- a/backend/src/services/license-client/usage/usage-metering.test.ts
+++ b/backend/src/services/license-client/usage/usage-metering.test.ts
@@ -236,9 +236,8 @@ 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 })),
+ countActiveCertificateQuotaKeysByOrg: vi.fn(async () => ({ total: 2, wildcard: 1 })),
isCertificateQuotaKeyActiveInOrg: vi.fn(async () => false),
countPamResources: vi.fn(async () => 3),
countSecretManagementIdentities: vi.fn(async () => 4),
@@ -260,7 +259,9 @@ describe("buildMeteredFeatures", () => {
expect(await byKey[IdentitiesMeter.key](ORG_ID)).toBe(7);
expect(await byKey[InternalCas.key](ORG_ID)).toBe(1);
+ // Billed on the same unit the cap enforces: distinct quota keys, not certificate rows.
expect(await byKey[ActiveCerts.key](ORG_ID)).toBe(2);
+ expect(usageCounterDAL.countActiveCertificateQuotaKeysByOrg).toHaveBeenCalledWith(ORG_ID);
expect(await byKey[SecretIdentities.key](ORG_ID)).toBe(4);
expect(await byKey[PamIdentities.key](ORG_ID)).toBe(5);
expect(await byKey[UserIdentities.key](ORG_ID)).toBe(8);
@@ -278,7 +279,6 @@ 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),
@@ -302,7 +302,17 @@ describe("buildMeteredFeatures", () => {
});
describe("usageEventQueue.handleUsageEvent (worker)", () => {
- const meteredFeatures = [{ feature: IdentitiesMeter, count: vi.fn(async () => 42) }];
+ const ROOT_ORG_ID = "00000000-0000-0000-0000-0000000000aa";
+ const activeCertsCount = vi.fn(async () => 7);
+ const meteredFeatures = [
+ { feature: IdentitiesMeter, count: vi.fn(async () => 42) },
+ // Tree-scoped: reports at the root so a family is counted once, not once per sub-org.
+ {
+ feature: ActiveCerts,
+ count: activeCertsCount,
+ resolveReportOrgId: vi.fn(async () => ROOT_ORG_ID)
+ }
+ ];
const buildQueue = (
overrides: {
@@ -402,14 +412,36 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {
expect(reportSnapshots).toHaveBeenCalledTimes(1);
});
- test("skips the internal-CA and certificate meters entirely (before any plan lookup)", async () => {
- const { queue, reportSnapshots, getPlan } = buildQueue({ isCloud: true });
+ // A tree-scoped meter counts the whole family, so reporting under the triggering sub-org would file
+ // that same total once per org in the tree.
+ test("reports a tree-scoped meter at the root org, counting from the root", async () => {
+ const { queue, reportSnapshots } = buildQueue({ isCloud: true });
- await queue.handleUsageEvent(ORG_ID, InternalCas.key, new Date());
await queue.handleUsageEvent(ORG_ID, ActiveCerts.key, new Date());
- expect(getPlan).not.toHaveBeenCalled();
- expect(reportSnapshots).not.toHaveBeenCalled();
+ expect(activeCertsCount).toHaveBeenCalledWith(ROOT_ORG_ID);
+ expect(reportSnapshots).toHaveBeenCalledWith(ROOT_ORG_ID, [
+ expect.objectContaining({ dimension_key: ActiveCerts.key, value: 7 })
+ ]);
+ });
+
+ test("dedups a tree-scoped meter across sub-orgs, so a family reports once", async () => {
+ const { queue, reportSnapshots } = buildQueue({ isCloud: true });
+
+ await queue.handleUsageEvent(ORG_ID, ActiveCerts.key, new Date());
+ await queue.handleUsageEvent("11111111-1111-1111-1111-111111111111", ActiveCerts.key, new Date());
+
+ expect(reportSnapshots).toHaveBeenCalledTimes(1);
+ });
+
+ test("leaves a per-org meter keyed on the triggering org", async () => {
+ const { queue, reportSnapshots } = buildQueue({ isCloud: true });
+
+ await queue.handleUsageEvent(ORG_ID, IdentitiesMeter.key, new Date());
+
+ expect(reportSnapshots).toHaveBeenCalledWith(ORG_ID, [
+ expect.objectContaining({ dimension_key: IdentitiesMeter.key })
+ ]);
});
test("skips the report when the count is unchanged", async () => {
@@ -495,7 +527,6 @@ 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,