Skip to content

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

feat: added user metric support

=8874ad3cb6b8
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index 1a156556bb..437a69116b 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -71,8 +71,6 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
secretSyncLimit: null,
maxInternalCas: null,
maxPamAccounts: null,
- pam: null,
- certManager: null,
memberLimit: null,
membersUsed: 0,
environmentLimit: null,
@@ -137,7 +135,10 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
secretShareExternalBranding: false,
honeyTokens: false,
honeyTokenLimit: 0,
- secretsBrokering: true
+ secretsBrokering: true,
+ // product gating
+ pam: null,
+ certManager: null
});
export const setupLicenseRequestWithStore = (
diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.ts
index 086eae7b63..88344e314b 100644
--- a/backend/src/ee/services/license/license-service.ts
+++ b/backend/src/ee/services/license/license-service.ts
@@ -17,9 +17,11 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
+import { UserIdentities } from "@app/services/license-client";
import { TDualReadServiceFactory } from "@app/services/license-client/dual-read/dual-read-service";
import { projectV2ToFeatureSet } from "@app/services/license-client/dual-read/entitlement-projection";
import { TLicenseClientFactory } from "@app/services/license-client/license-client";
+import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -71,6 +73,8 @@ type TLicenseServiceFactoryDep = {
projectDAL: TProjectDALFactory;
licenseClient?: Pick<TLicenseClientFactory, "getEntitlements" | "getSubscription" | "refreshEntitlements">;
licenseDualRead?: Pick<TDualReadServiceFactory, "compareInBackground">;
+ // Fire-and-forget v2 usage meter for org user seats; no-ops when the v2 license server is disabled.
+ usageMeteringService?: Pick<TUsageMeteringServiceFactory, "emit">;
};
export type TLicenseServiceFactory = ReturnType<typeof licenseServiceFactory>;
@@ -90,7 +94,8 @@ export const licenseServiceFactory = ({
projectDAL,
envConfig,
licenseClient,
- licenseDualRead
+ licenseDualRead,
+ usageMeteringService
}: TLicenseServiceFactoryDep) => {
let isValidLicense = false;
let instanceType = InstanceType.OnPrem;
@@ -433,6 +438,13 @@ export const licenseServiceFactory = ({
if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
const rootOrgId = org.id;
+
+ // This is the single "org member count changed" signal in the codebase (invite/signup, SSO/SCIM
+ // provisioning, member removal all call it), so emit the v2 user-seat meter here. Fire-and-forget
+ // and no-op when the v2 license server is off; extra fires on identity-only changes re-count and
+ // report-only-if-changed, so they're harmless.
+ usageMeteringService?.emit(rootOrgId, UserIdentities.key);
+
if (instanceType === InstanceType.Cloud && envConfig.LICENSE_SERVER_KEY) {
const quantity = await licenseDAL.countOfOrgMembers(rootOrgId, tx);
const quantityIdentities = await licenseDAL.countOrgUsersAndIdentities(rootOrgId, tx);
@@ -563,6 +575,12 @@ export const licenseServiceFactory = ({
actorAuthMethod,
actorOrgId
}: TCreateOrgPortalSession) => {
+ if (envConfig.DISABLE_LICENSE_V1_CLOUD) {
+ throw new BadRequestError({
+ message: "We're currently updating our license system. Please check back again later."
+ });
+ }
+
const { permission } = await permissionService.getOrgPermission({
actorId,
actor,
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 39d61136aa..092843c3af 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -812,6 +812,10 @@ export const registerRoutes = async (
// Shadow-compares v1 getPlan against v2 entitlements in read-compare mode; reads v2 via the real SDK.
const licenseDualRead = dualReadServiceFactory({ licenseClient, envConfig });
+ // Created before licenseService so the latter can emit the v2 user-seat meter from its
+ // updateSubscriptionOrgMemberCount chokepoint.
+ const usageMeteringService = usageMeteringServiceFactory({ queueService, projectDAL, envConfig });
+
const licenseService = licenseServiceFactory({
permissionService,
orgDAL,
@@ -820,16 +824,16 @@ export const registerRoutes = async (
projectDAL,
envConfig,
licenseClient,
- licenseDualRead
+ licenseDualRead,
+ usageMeteringService
});
- // Usage metering: counts the 5 metered features and reports them to the License Server. Inert while
+ // Usage metering: counts the metered features and reports them to the License Server. Inert while
// LICENSE_SERVER_V2_MODE is off; active in read-compare and on (emitter no-ops / worker no-ops without a reporter).
const usageCounterDAL = usageCounterDALFactory(db);
const meteredFeatures = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: envConfig.isCloud });
meteredFeatures.forEach(({ feature, count }) => licenseClient.registerCounter(feature, count));
const usageReporter = buildUsageReporter(envConfig);
- const usageMeteringService = usageMeteringServiceFactory({ queueService, projectDAL, envConfig });
let usageSource = "self-hosted";
if (envConfig.isCloud) {
usageSource = "cloud";
@@ -842,6 +846,7 @@ export const registerRoutes = async (
usageMeteringService,
meteredFeatures,
usageReporter,
+ licenseClient,
source: usageSource
});
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts b/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts
index 67e480d6fc..d525b9b3f7 100644
--- a/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts
+++ b/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts
@@ -12,7 +12,7 @@ export const pkiSecurityMappings: TFeatureMapping[] = [
extractV1: (p) => p.pkiEst
},
{
- v2Key: "acme_client",
+ v2Key: "pki_acme",
v1Field: "pkiAcme",
extractV1: (p) => p.pkiAcme
},
diff --git a/backend/src/services/license-client/features.ts b/backend/src/services/license-client/features.ts
index d490b79e60..fd6f4bd2ce 100644
--- a/backend/src/services/license-client/features.ts
+++ b/backend/src/services/license-client/features.ts
@@ -12,3 +12,5 @@ export const MaxActiveCerts = defineLimitFeature("max_active_certs", 0);
export const MaxPamResources = defineLimitFeature("max_resources", 0);
export const SecretIdentities = defineLimitFeature("secret_identities", 0);
export const PamIdentities = defineLimitFeature("pam_identities", 0);
+// Human users (org members), excluding machine identities. For legacy per-user plans that count seats.
+export const UserIdentities = defineLimitFeature("user_identities", 0);
diff --git a/backend/src/services/license-client/license-client.test.ts b/backend/src/services/license-client/license-client.test.ts
index 88b6ffbd34..0686a29728 100644
--- a/backend/src/services/license-client/license-client.test.ts
+++ b/backend/src/services/license-client/license-client.test.ts
@@ -64,9 +64,7 @@ const createStubBackend = (response: TEntitlementsResponse, opts: { fail?: boole
describe("entitlementResolverFactory", () => {
test("fetches once then serves subsequent reads from the cache", async () => {
const keyStore = createFakeKeyStore();
- const { backend, getCalls } = createStubBackend(
- makeEntitlements({ identities: { value: 100, source: "plan" } })
- );
+ const { backend, getCalls } = createStubBackend(makeEntitlements({ identities: { value: 100, source: "plan" } }));
const resolver = entitlementResolverFactory({ keyStore, backend });
const first = await resolver.getEntitlements({ id: ORG_ID });
@@ -103,9 +101,7 @@ describe("entitlementResolverFactory", () => {
test("syncs org identity once per ttl window then serves from the cache", async () => {
const keyStore = createFakeKeyStore();
- const { backend, getCalls } = createStubBackend(
- makeEntitlements({ identities: { value: 100, source: "plan" } })
- );
+ const { backend, getCalls } = createStubBackend(makeEntitlements({ identities: { value: 100, source: "plan" } }));
const resolver = entitlementResolverFactory({ keyStore, backend });
await resolver.getEntitlements({ id: ORG_ID, name: "Acme Corp", slug: "acme" });
diff --git a/backend/src/services/license-client/usage/usage-counters.ts b/backend/src/services/license-client/usage/usage-counters.ts
index 88b48d2b05..8700b9c57c 100644
--- a/backend/src/services/license-client/usage/usage-counters.ts
+++ b/backend/src/services/license-client/usage/usage-counters.ts
@@ -7,7 +7,8 @@ import {
MaxInternalCas,
MaxPamResources,
PamIdentities,
- SecretIdentities
+ SecretIdentities,
+ UserIdentities
} from "../features";
import { TUsageCounterDALFactory } from "./usage-counter-dal";
@@ -17,7 +18,7 @@ export type TMeteredFeature = {
};
type TBuildMeteredFeaturesDep = {
- licenseDAL: Pick<TLicenseDALFactory, "countOrgUsersAndIdentities">;
+ licenseDAL: Pick<TLicenseDALFactory, "countOrgUsersAndIdentities" | "countOfOrgMembers">;
usageCounterDAL: TUsageCounterDALFactory;
// Cloud meters per org; self-hosted meters the whole instance (a single license covers the DB).
isCloud: boolean;
@@ -41,5 +42,10 @@ export const buildMeteredFeatures = ({
{
feature: PamIdentities,
count: (orgId) => usageCounterDAL.countPamIdentities(isCloud ? orgId : undefined)
+ },
+ {
+ // Human users only (org members), never machine identities. Legacy per-user plans.
+ feature: UserIdentities,
+ count: (orgId) => licenseDAL.countOfOrgMembers(isCloud ? orgId : null)
}
];
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 7973f0f49f..b5fe16d7ca 100644
--- a/backend/src/services/license-client/usage/usage-event-queue.ts
+++ b/backend/src/services/license-client/usage/usage-event-queue.ts
@@ -5,6 +5,7 @@ import { logger } from "@app/lib/logger";
import { QueueName, TQueueServiceFactory } from "@app/queue";
import { TOrgDALFactory } from "@app/services/org/org-dal";
+import { TLicenseClientFactory } from "../license-client";
import { TMeteredFeature } from "./usage-counters";
import { TUsageMeteringServiceFactory } from "./usage-metering-service";
import { TUsageReporter } from "./usage-reporter";
@@ -17,6 +18,8 @@ type TUsageEventQueueFactoryDep = {
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
meteredFeatures: TMeteredFeature[];
usageReporter: TUsageReporter | null;
+ // Resolves the org's plan so we only report dimensions the plan actually includes. Cached.
+ licenseClient: Pick<TLicenseClientFactory, "getEntitlements">;
source: string;
};
@@ -28,6 +31,7 @@ export const usageEventQueueFactory = ({
usageMeteringService,
meteredFeatures,
usageReporter,
+ licenseClient,
source
}: TUsageEventQueueFactoryDep) => {
const featureByKey = new Map(meteredFeatures.map((m) => [m.feature.key, m]));
@@ -45,6 +49,19 @@ export const usageEventQueueFactory = ({
return;
}
+ // Only report a dimension the org's plan actually includes. Metered features are entitlement
+ // features (each meter resolves its cap from entitlements.features[key]), so a dimension the plan
+ // doesn't grant is absent here. Works for cloud (per-org entitlements) and self-hosted
+ // (instance-wide entitlements; the backend ignores the org id). Entitlements are cached, so this
+ // check is cheap and also spares the DB count below.
+ const entitlements = await licenseClient.getEntitlements({ id: orgId });
+ if (!entitlements || !(dimensionKey in entitlements.features)) {
+ logger.info(
+ `usage-event-queue: dimension not in org plan, skipping [orgId=${orgId}] [dimensionKey=${dimensionKey}]`
+ );
+ return;
+ }
+
const value = await metered.count(orgId);
const lastReportedKey = KeyStorePrefixes.LicenseUsageLastReported(orgId, 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 1e0f2c82b3..9b969a86f3 100644
--- a/backend/src/services/license-client/usage/usage-metering.test.ts
+++ b/backend/src/services/license-client/usage/usage-metering.test.ts
@@ -9,7 +9,8 @@ import {
MaxInternalCas,
MaxPamResources,
PamIdentities,
- SecretIdentities
+ SecretIdentities,
+ UserIdentities
} from "../features";
import { buildMeteredFeatures } from "./usage-counters";
import { usageEventQueueFactory } from "./usage-event-queue";
@@ -172,7 +173,10 @@ describe("buildUsageReporter", () => {
describe("buildMeteredFeatures", () => {
test("wires all meters to their count fns", async () => {
- const licenseDAL = { countOrgUsersAndIdentities: vi.fn(async () => 7) };
+ const licenseDAL = {
+ countOrgUsersAndIdentities: vi.fn(async () => 7),
+ countOfOrgMembers: vi.fn(async () => 8)
+ };
const usageCounterDAL = {
countInternalCas: vi.fn(async () => 1),
countActiveCerts: vi.fn(async () => 2),
@@ -190,7 +194,8 @@ describe("buildMeteredFeatures", () => {
MaxActiveCerts.key,
MaxPamResources.key,
SecretIdentities.key,
- PamIdentities.key
+ PamIdentities.key,
+ UserIdentities.key
].sort()
);
@@ -200,14 +205,19 @@ describe("buildMeteredFeatures", () => {
expect(await byKey[MaxPamResources.key](ORG_ID)).toBe(3);
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);
expect(licenseDAL.countOrgUsersAndIdentities).toHaveBeenCalledWith(ORG_ID);
// Cloud scopes the identity meters to the org.
expect(usageCounterDAL.countSecretManagementIdentities).toHaveBeenCalledWith(ORG_ID);
expect(usageCounterDAL.countPamIdentities).toHaveBeenCalledWith(ORG_ID);
+ expect(licenseDAL.countOfOrgMembers).toHaveBeenCalledWith(ORG_ID);
});
test("self-hosted meters secret identities across the whole instance (no org scope)", async () => {
- const licenseDAL = { countOrgUsersAndIdentities: vi.fn(async () => 0) };
+ const licenseDAL = {
+ countOrgUsersAndIdentities: vi.fn(async () => 0),
+ countOfOrgMembers: vi.fn(async () => 11)
+ };
const usageCounterDAL = {
countInternalCas: vi.fn(async () => 0),
countActiveCerts: vi.fn(async () => 0),
@@ -218,11 +228,15 @@ describe("buildMeteredFeatures", () => {
const metered = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: false });
const secret = metered.find((m) => m.feature.key === SecretIdentities.key);
const pam = metered.find((m) => m.feature.key === PamIdentities.key);
+ const user = metered.find((m) => m.feature.key === UserIdentities.key);
expect(await secret?.count(ORG_ID)).toBe(9);
expect(await pam?.count(ORG_ID)).toBe(6);
+ expect(await user?.count(ORG_ID)).toBe(11);
expect(usageCounterDAL.countSecretManagementIdentities).toHaveBeenCalledWith(undefined);
expect(usageCounterDAL.countPamIdentities).toHaveBeenCalledWith(undefined);
+ // Self-hosted meters users across the whole instance (null org scope).
+ expect(licenseDAL.countOfOrgMembers).toHaveBeenCalledWith(null);
});
});
@@ -230,13 +244,23 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {
const meteredFeatures = [{ feature: MaxIdentities, count: vi.fn(async () => 42) }];
const buildQueue = (
- overrides: { usageReporter?: unknown; keyStore?: ReturnType<typeof createFakeKeyStore>; orgFind?: unknown } = {}
+ overrides: {
+ usageReporter?: unknown;
+ keyStore?: ReturnType<typeof createFakeKeyStore>;
+ orgFind?: unknown;
+ // Feature keys the org's plan includes; defaults to the metered feature under test.
+ planFeatures?: string[];
+ } = {}
) => {
const reportSnapshots = vi.fn(async () => {});
const keyStore = overrides.keyStore ?? createFakeKeyStore();
const usageReporter = overrides.usageReporter === undefined ? { reportSnapshots } : overrides.usageReporter;
const emit = vi.fn();
const find = overrides.orgFind ?? vi.fn(async () => []);
+ const planFeatures = overrides.planFeatures ?? [MaxIdentities.key];
+ const getEntitlements = vi.fn(async () => ({
+ features: Object.fromEntries(planFeatures.map((key) => [key, { value: 100, source: "plan" }]))
+ }));
const queue = usageEventQueueFactory({
queueService: { start: vi.fn() },
cronJob: { register: vi.fn(), start: vi.fn(), stop: vi.fn() } as never,
@@ -245,9 +269,10 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {
usageMeteringService: { emit },
meteredFeatures,
usageReporter: usageReporter as never,
+ licenseClient: { getEntitlements } as never,
source: "test-region"
});
- return { queue, reportSnapshots, keyStore, emit, find };
+ return { queue, reportSnapshots, keyStore, emit, find, getEntitlements };
};
beforeEach(() => {
@@ -290,6 +315,14 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {
expect(reportSnapshots).not.toHaveBeenCalled();
});
+ test("skips the count and report when the dimension is not in the org's plan", async () => {
+ // The org's plan has no metered features, so the dimension is absent from entitlements.features.
+ const { queue, reportSnapshots } = buildQueue({ planFeatures: [] });
+ await queue.handleUsageEvent(ORG_ID, MaxIdentities.key, new Date());
+ expect(meteredFeatures[0].count).not.toHaveBeenCalled();
+ expect(reportSnapshots).not.toHaveBeenCalled();
+ });
+
test("flushAllOrgs pages through orgs and emits per meter", async () => {
const fullPage = Array.from({ length: 500 }, (_, i) => ({ id: `org-${i}` }));
const lastPage = [{ id: "org-500" }];
@@ -322,7 +355,10 @@ describe("canUse enforcement (using the framework from a call site)", () => {
counts: { identities?: number; internalCas?: number }
) => {
const reader = featureReaderFactory({ getEntitlements: async () => ({ features: caps, products: [] }) });
- const licenseDAL = { countOrgUsersAndIdentities: async () => counts.identities ?? 0 };
+ const licenseDAL = {
+ countOrgUsersAndIdentities: async () => counts.identities ?? 0,
+ countOfOrgMembers: async () => 0
+ };
const usageCounterDAL = {
countInternalCas: async () => counts.internalCas ?? 0,
countActiveCerts: async () => 0,