Skip to content

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

feat(license): dual-read v1/v2 + getPlan mode toggle (off/read-compare/on)

Tre Dubrava1ecef8631289
diff --git a/backend/src/db/migrations/utils/env-config.ts b/backend/src/db/migrations/utils/env-config.ts
index dc82c5d86d..056874f061 100644
--- a/backend/src/db/migrations/utils/env-config.ts
+++ b/backend/src/db/migrations/utils/env-config.ts
@@ -31,6 +31,7 @@ const envSchema = z
LICENSE_SERVER_KEY: zpStr(z.string().optional()),
LICENSE_KEY: zpStr(z.string().optional()),
LICENSE_KEY_OFFLINE: zpStr(z.string().optional()),
+ LICENSE_SERVER_V2_MODE: z.enum(["off", "read-compare", "on"]).default("off"),
INTERNAL_REGION: zpStr(z.enum(["us", "eu"]).optional()),
SITE_URL: zpStr(z.string().transform((val) => (val ? removeTrailingSlash(val) : val))).optional()
diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.ts
index a9821647e5..8f80329617 100644
--- a/backend/src/ee/services/license/license-service.ts
+++ b/backend/src/ee/services/license/license-service.ts
@@ -17,6 +17,9 @@ 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 { 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 { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -51,13 +54,21 @@ import {
type TLicenseServiceFactoryDep = {
envConfig: Pick<
TEnvConfig,
- "LICENSE_SERVER_URL" | "LICENSE_SERVER_KEY" | "LICENSE_KEY" | "LICENSE_KEY_OFFLINE" | "INTERNAL_REGION" | "SITE_URL"
+ | "LICENSE_SERVER_URL"
+ | "LICENSE_SERVER_KEY"
+ | "LICENSE_KEY"
+ | "LICENSE_KEY_OFFLINE"
+ | "INTERNAL_REGION"
+ | "SITE_URL"
+ | "LICENSE_SERVER_V2_MODE"
>;
orgDAL: Pick<TOrgDALFactory, "findRootOrgDetails" | "countAllOrgMembers" | "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
licenseDAL: TLicenseDALFactory;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "deleteItem">;
projectDAL: TProjectDALFactory;
+ licenseClient?: Pick<TLicenseClientFactory, "getEntitlements">;
+ licenseDualRead?: Pick<TDualReadServiceFactory, "compareInBackground">;
};
export type TLicenseServiceFactory = ReturnType<typeof licenseServiceFactory>;
@@ -71,7 +82,9 @@ export const licenseServiceFactory = ({
licenseDAL,
keyStore,
projectDAL,
- envConfig
+ envConfig,
+ licenseClient,
+ licenseDualRead
}: TLicenseServiceFactoryDep) => {
let isValidLicense = false;
let instanceType = InstanceType.OnPrem;
@@ -210,19 +223,38 @@ export const licenseServiceFactory = ({
if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
const rootOrgId = org.id;
- const {
- data: { currentPlan }
- } = await licenseServerCloudApi.request.get<{ currentPlan: TFeatureSet }>(
- `/api/license-server/v1/customers/${org.customerId}/cloud-plan`
- );
- const workspacesUsed = await projectDAL.countOfBillableOrgProjects(rootOrgId);
- currentPlan.workspacesUsed = workspacesUsed;
+ let currentPlan: TFeatureSet;
+ if (envConfig.LICENSE_SERVER_V2_MODE === "on") {
+ // Serve from License Server v2, projected into the v1 plan shape so getPlan callers are unchanged.
+ if (!licenseClient) {
+ throw new BadRequestError({ message: "License Server v2 client is not configured" });
+ }
+ const entitlements = await licenseClient.getEntitlements(rootOrgId);
+ if (!entitlements) {
+ throw new BadRequestError({ message: "License Server v2 entitlements are unavailable" });
+ }
+ currentPlan = projectV2ToFeatureSet(getDefaultOnPremFeatures(), entitlements);
+ } else {
+ const {
+ data: { currentPlan: v1Plan }
+ } = await licenseServerCloudApi.request.get<{ currentPlan: TFeatureSet }>(
+ `/api/license-server/v1/customers/${org.customerId}/cloud-plan`
+ );
+ currentPlan = v1Plan;
+ }
+
+ currentPlan.workspacesUsed = await projectDAL.countOfBillableOrgProjects(rootOrgId);
const membersUsed = await licenseDAL.countOfOrgMembers(rootOrgId);
currentPlan.membersUsed = membersUsed;
const identityUsed = await licenseDAL.countOrgUsersAndIdentities(rootOrgId);
- if (currentPlan?.identitiesUsed && currentPlan.identitiesUsed !== identityUsed) {
+ // Seat sync targets the v1 license server only; v2 derives usage from registered counters.
+ if (
+ envConfig.LICENSE_SERVER_V2_MODE !== "on" &&
+ currentPlan?.identitiesUsed &&
+ currentPlan.identitiesUsed !== identityUsed
+ ) {
try {
await licenseServerCloudApi.request.patch(`/api/license-server/v1/customers/${org.customerId}/cloud-plan`, {
quantity: membersUsed,
@@ -243,6 +275,11 @@ export const licenseServiceFactory = ({
JSON.stringify(currentPlan)
);
+ // read-compare bake: serve v1 but shadow-compare against v2 in the background ahead of the cutover.
+ if (envConfig.LICENSE_SERVER_V2_MODE === "read-compare") {
+ licenseDualRead?.compareInBackground(rootOrgId, currentPlan);
+ }
+
return currentPlan;
}
} catch (error) {
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts
index f66ad05043..f8f41e67d2 100644
--- a/backend/src/lib/config/env.ts
+++ b/backend/src/lib/config/env.ts
@@ -318,7 +318,7 @@ const envSchema = z
LICENSE_SERVER_KEY: zpStr(z.string().optional()),
LICENSE_KEY: zpStr(z.string().optional()),
LICENSE_KEY_OFFLINE: zpStr(z.string().optional()),
- LICENSE_SERVER_V2_ENABLED: zodStrBool.default("false"),
+ LICENSE_SERVER_V2_MODE: z.enum(["off", "read-compare", "on"]).default("off"),
LICENSE_SERVER_V2_URL: zpStr(z.string().optional()),
LICENSE_SERVER_V2_SERVICE_KEY: zpStr(z.string().optional()),
@@ -522,6 +522,7 @@ const envSchema = z
: undefined,
// Inferred from the legacy license server key; needs a new signal once License Server v2 fully replaces it.
isCloud: Boolean(data.LICENSE_SERVER_KEY),
+ isLicenseDualReadEnabled: data.LICENSE_SERVER_V2_MODE === "read-compare",
isSmtpConfigured: Boolean(data.SMTP_HOST),
isRedisConfigured: Boolean(data.REDIS_URL || data.REDIS_SENTINEL_HOSTS || data.REDIS_CLUSTER_HOSTS),
isClickHouseConfigured: Boolean(data.CLICKHOUSE_URL),
diff --git a/backend/src/lib/telemetry/instrumentation.ts b/backend/src/lib/telemetry/instrumentation.ts
index 4c5a0d004e..8611870672 100644
--- a/backend/src/lib/telemetry/instrumentation.ts
+++ b/backend/src/lib/telemetry/instrumentation.ts
@@ -57,6 +57,9 @@ const INFISICAL_CORE_METER_ATTRIBUTES = [
"db.pool.state",
"cache.result",
"rate_limit.bucket",
+ // License Server v2 dual-read comparison (bounded: feature key set + a small set of diff kinds)
+ "license.feature",
+ "license.dual_read.kind",
// Build info gauge labels — single-value per deploy, no cardinality concern
"service.version",
"git.commit.sha",
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index 48b62fc419..6c06270c03 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -388,6 +388,33 @@ export const rateLimitExceededCounter = infisicalCoreMeter.createCounter("infisi
unit: "{request}"
});
+// -- License Server v2 dual-read (InfisicalCore meter) ----------------------------------------------
+export const licenseDualReadDiffCounter = infisicalCoreMeter.createCounter("infisical.license.dual_read.diff.count", {
+ description:
+ "v1 vs License Server v2 entitlement comparison results, by feature and kind (mismatch/v2_missing/v1_absent/indeterminate). Match results are not counted.",
+ unit: "{result}"
+});
+
+export const licenseDualReadErrorCounter = infisicalCoreMeter.createCounter("infisical.license.dual_read.error.count", {
+ description: "Failures resolving the v2 entitlement set during dual-read comparison, by error type.",
+ unit: "{error}"
+});
+
+export const recordLicenseDualReadDiff = (params: { feature: string; kind: string }) => {
+ if (!isTelemetryEnabled()) return;
+ licenseDualReadDiffCounter.add(1, {
+ "license.feature": params.feature,
+ "license.dual_read.kind": params.kind
+ });
+};
+
+export const recordLicenseDualReadError = (params: { error?: unknown }) => {
+ if (!isTelemetryEnabled()) return;
+ const attributes: Record<string, string> = {};
+ if (params.error !== undefined) attributes["error.type"] = classifyError(params.error);
+ licenseDualReadErrorCounter.add(1, attributes);
+};
+
// -- Authentication latency (InfisicalCore meter) ---------------------------------------------------
export const authAttemptDurationHistogram = infisicalCoreMeter.createHistogram("infisical.auth.attempt.duration", {
description:
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 815fbcc5f6..aa5527fefa 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -381,6 +381,7 @@ import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal"
import { kmsServiceFactory } from "@app/services/kms/kms-service";
import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";
import { licenseClientFactory } from "@app/services/license-client";
+import { dualReadServiceFactory } from "@app/services/license-client/dual-read/dual-read-service";
import {
buildMeteredFeatures,
buildUsageReporter,
@@ -788,21 +789,26 @@ export const registerRoutes = async (
permissionService
});
+ // License Server v2 client SDK. Coexists with licenseService during migration - getFeature()
+ // is the single read primitive; falls back to feature defaults until the server is configured.
+ const licenseClient = licenseClientFactory({ envConfig, keyStore });
+
+ // Shadow-compares v1 getPlan against v2 entitlements in read-compare mode; reads v2 via the real SDK.
+ const licenseDualRead = dualReadServiceFactory({ licenseClient, envConfig });
+
const licenseService = licenseServiceFactory({
permissionService,
orgDAL,
licenseDAL,
keyStore,
projectDAL,
- envConfig
+ envConfig,
+ licenseClient,
+ licenseDualRead
});
- // License Server v2 client SDK. Coexists with licenseService during migration - getFeature()
- // is the single read primitive; falls back to feature defaults until the server is configured.
- const licenseClient = licenseClientFactory({ envConfig, keyStore });
-
- // Usage metering: counts the 5 metered features and reports them to the License Server. Inert
- // until LICENSE_SERVER_V2_ENABLED is on (the emitter no-ops, the worker no-ops without a reporter).
+ // Usage metering: counts the 5 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 });
meteredFeatures.forEach(({ feature, count }) => licenseClient.registerCounter(feature, count));
diff --git a/backend/src/services/license-client/dual-read/dual-read-service.ts b/backend/src/services/license-client/dual-read/dual-read-service.ts
new file mode 100644
index 0000000000..93e8082381
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/dual-read-service.ts
@@ -0,0 +1,56 @@
+import { TFeatureSet } from "@app/ee/services/license/license-types";
+import { TEnvConfig } from "@app/lib/config/env";
+import { logger } from "@app/lib/logger";
+import { recordLicenseDualReadDiff, recordLicenseDualReadError } from "@app/lib/telemetry/metrics";
+import { TLicenseClientFactory } from "@app/services/license-client/license-client";
+
+import { DualReadDiffKind } from "./dual-read-types";
+import { compareEntitlements } from "./entitlement-comparator";
+import { FEATURE_MAPPINGS } from "./feature-mapping";
+
+export type TDualReadServiceFactory = ReturnType<typeof dualReadServiceFactory>;
+
+type TDualReadServiceFactoryDep = {
+ licenseClient: Pick<TLicenseClientFactory, "getEntitlements">;
+ envConfig: Pick<TEnvConfig, "isLicenseDualReadEnabled">;
+};
+
+export const dualReadServiceFactory = ({ licenseClient, envConfig }: TDualReadServiceFactoryDep) => {
+ // Fire-and-forget shadow compare against the already-resolved v1 plan. Never awaited, never throws into
+ // the request path; inert unless mode is read-compare. Reads v2 through the real client SDK so the
+ // production read path is exercised under real traffic ahead of the cutover.
+ const compareInBackground = (orgId: string, planV1: TFeatureSet) => {
+ if (!envConfig.isLicenseDualReadEnabled) {
+ return;
+ }
+
+ void (async () => {
+ const entitlements = await licenseClient.getEntitlements(orgId);
+ if (!entitlements) {
+ recordLicenseDualReadError({ error: new Error("v2 entitlements unavailable") });
+ logger.warn(`license-dual-read: v2 entitlements unavailable [orgId=${orgId}]`);
+ return;
+ }
+
+ const discrepancies = compareEntitlements(planV1, entitlements, FEATURE_MAPPINGS);
+ const diffs = discrepancies.filter((d) => d.kind !== DualReadDiffKind.Match);
+
+ for (const d of diffs) {
+ recordLicenseDualReadDiff({ feature: d.v2Key, kind: d.kind });
+ logger.info(
+ { orgId, feature: d.v2Key, kind: d.kind, v1Value: d.v1Value, v2Value: d.v2Value },
+ `license-dual-read discrepancy [orgId=${orgId}] [feature=${d.v2Key}] [kind=${d.kind}] [v1=${String(d.v1Value)}] [v2=${String(d.v2Value)}]`
+ );
+ }
+
+ logger.info(
+ `license-dual-read: compared entitlements [orgId=${orgId}] [diffs=${diffs.length}] [total=${discrepancies.length}]`
+ );
+ })().catch((error: unknown) => {
+ recordLicenseDualReadError({ error });
+ logger.error(error, `license-dual-read: compare failed [orgId=${orgId}]`);
+ });
+ };
+
+ return { compareInBackground };
+};
diff --git a/backend/src/services/license-client/dual-read/dual-read-types.ts b/backend/src/services/license-client/dual-read/dual-read-types.ts
new file mode 100644
index 0000000000..a1a02bf359
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/dual-read-types.ts
@@ -0,0 +1,44 @@
+import { TFeatureSet } from "@app/ee/services/license/license-types";
+
+import { TFeatureValue } from "../feature";
+
+export enum DualReadDiffKind {
+ Match = "match",
+ Mismatch = "mismatch",
+ V2Missing = "v2_missing",
+ V1Absent = "v1_absent",
+ Indeterminate = "indeterminate"
+}
+
+// Sentinel so a v1 null (unlimited cap) compares equal to a v2 unlimited representation. It is a
+// plain string value, so TNormalizedValue stays TFeatureValue | null.
+export const UNLIMITED = "unlimited" as const;
+
+export type TNormalizedValue = TFeatureValue | null;
+
+export type TFeatureMapping = {
+ // Must match a License Server v2 feature registry key (a separate repo); a wrong key surfaces as a v2_missing diff.
+ v2Key: string;
+ // The TFeatureSet field name this maps to (drives the completeness test); dotted for nested
+ // fields (e.g. "rateLimits.readLimit"). null when v2-only.
+ v1Field: string | null;
+ // Resolves the v1 value. null when there is no corresponding v1 field (v2-only descriptor).
+ extractV1: ((plan: TFeatureSet) => TFeatureValue | null) | null;
+ // Normalizes a value before comparison (e.g. null -> UNLIMITED). Applied to both sides.
+ normalize?: (value: TFeatureValue | null) => TNormalizedValue;
+};
+
+export type TDiscrepancy = {
+ v2Key: string;
+ kind: DualReadDiffKind;
+ v1Value: TNormalizedValue;
+ v2Value: TNormalizedValue;
+};
+
+// Maps a possibly-null cap to UNLIMITED; reusable by mapping files for "null = unlimited" v1 caps.
+export const unlimitedWhenNull = (value: TFeatureValue | null): TNormalizedValue => {
+ if (value === null || value === undefined) {
+ return UNLIMITED;
+ }
+ return value;
+};
diff --git a/backend/src/services/license-client/dual-read/entitlement-comparator.test.ts b/backend/src/services/license-client/dual-read/entitlement-comparator.test.ts
new file mode 100644
index 0000000000..ea0fdf88b9
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/entitlement-comparator.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, test } from "vitest";
+
+import { TFeatureSet } from "@app/ee/services/license/license-types";
+
+import { TEntitlementsResponse } from "../license-client-types";
+import { DualReadDiffKind, TFeatureMapping, UNLIMITED, unlimitedWhenNull } from "./dual-read-types";
+import { compareEntitlements } from "./entitlement-comparator";
+
+// TFeatureSet fields are literal-typed (e.g. auditLogsRetentionDays: 0), so fixtures use loose values.
+const makePlan = (overrides: Partial<Record<keyof TFeatureSet, unknown>>): TFeatureSet =>
+ ({ ...overrides }) as TFeatureSet;
+
+const makeEntitlements = (features: TEntitlementsResponse["features"]): TEntitlementsResponse =>
+ ({ features }) as TEntitlementsResponse;
+
+const findByKey = (result: ReturnType<typeof compareEntitlements>, v2Key: string): (typeof result)[number] => {
+ const match = result.find((d) => d.v2Key === v2Key);
+ if (!match) {
+ throw new Error(`expected a discrepancy for [v2Key=${v2Key}]`);
+ }
+ return match;
+};
+
+describe("compareEntitlements", () => {
+ test("boolean values that agree report a Match", () => {
+ const mappings: TFeatureMapping[] = [
+ { v2Key: "sso_enforcement", v1Field: "enforceGoogleSSO", extractV1: (p) => p.enforceGoogleSSO }
+ ];
+ const plan = makePlan({ enforceGoogleSSO: false });
+ const entitlements = makeEntitlements({ sso_enforcement: { value: false } });
+
+ const result = compareEntitlements(plan, entitlements, mappings);
+ const diff = findByKey(result, "sso_enforcement");
+ expect(diff.kind).toBe(DualReadDiffKind.Match);
+ expect(diff.v1Value).toBe(false);
+ expect(diff.v2Value).toBe(false);
+ });
+
+ test("boolean values that disagree report a Mismatch", () => {
+ const mappings: TFeatureMapping[] = [
+ { v2Key: "sso_enforcement", v1Field: "enforceGoogleSSO", extractV1: (p) => p.enforceGoogleSSO }
+ ];
+ const plan = makePlan({ enforceGoogleSSO: false });
+ const entitlements = makeEntitlements({ sso_enforcement: { value: true } });
+
+ const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "sso_enforcement");
+ expect(diff.kind).toBe(DualReadDiffKind.Mismatch);
+ expect(diff.v1Value).toBe(false);
+ expect(diff.v2Value).toBe(true);
+ });
+
+ test("v1 null cap normalized to UNLIMITED matches a v2 unlimited representation", () => {
+ const mappings: TFeatureMapping[] = [
+ {
+ v2Key: "max_identities",
+ v1Field: "identityLimit",
+ extractV1: (p) => p.identityLimit,
+ normalize: unlimitedWhenNull
+ }
+ ];
+ const plan = makePlan({ identityLimit: null });
+ const entitlements = makeEntitlements({ max_identities: { value: UNLIMITED } });
+
+ const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "max_identities");
+ expect(diff.kind).toBe(DualReadDiffKind.Match);
+ expect(diff.v1Value).toBe(UNLIMITED);
+ expect(diff.v2Value).toBe(UNLIMITED);
+ });
+
+ test("a v2 key that is absent reports V2Missing", () => {
+ const mappings: TFeatureMapping[] = [
+ {
+ v2Key: "audit_retention_days",
+ v1Field: "auditLogsRetentionDays",
+ extractV1: (p) => p.auditLogsRetentionDays
+ }
+ ];
+ const plan = makePlan({ auditLogsRetentionDays: 30 });
+ const entitlements = makeEntitlements({});
+
+ const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "audit_retention_days");
+ expect(diff.kind).toBe(DualReadDiffKind.V2Missing);
+ expect(diff.v1Value).toBe(30);
+ expect(diff.v2Value).toBeNull();
+ });
+
+ test("a mapping with no v1 extractor reports V1Absent", () => {
+ const mappings: TFeatureMapping[] = [{ v2Key: "max_internal_cas", v1Field: null, extractV1: null }];
+ const plan = makePlan({});
+ const entitlements = makeEntitlements({ max_internal_cas: { value: 5 } });
+
+ const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "max_internal_cas");
+ expect(diff.kind).toBe(DualReadDiffKind.V1Absent);
+ expect(diff.v1Value).toBeNull();
+ expect(diff.v2Value).toBe(5);
+ });
+
+ test("v1 UNLIMITED versus a v2 finite number downgrades to Indeterminate", () => {
+ const mappings: TFeatureMapping[] = [
+ {
+ v2Key: "max_identities",
+ v1Field: "identityLimit",
+ extractV1: (p) => p.identityLimit,
+ normalize: unlimitedWhenNull
+ }
+ ];
+ const plan = makePlan({ identityLimit: null });
+ const entitlements = makeEntitlements({ max_identities: { value: 100 } });
+
+ const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "max_identities");
+ expect(diff.kind).toBe(DualReadDiffKind.Indeterminate);
+ expect(diff.v1Value).toBe(UNLIMITED);
+ expect(diff.v2Value).toBe(100);
+ });
+
+ test("a v2 value present but null reports V2Missing, not a false Mismatch, for a non-normalized feature", () => {
+ const mappings: TFeatureMapping[] = [{ v2Key: "rbac", v1Field: "rbac", extractV1: (p) => p.rbac }];
+ const plan = makePlan({ rbac: false });
+ const entitlements = makeEntitlements({ rbac: { value: null } });
+
+ const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "rbac");
+ expect(diff.kind).toBe(DualReadDiffKind.V2Missing);
+ expect(diff.v1Value).toBe(false);
+ expect(diff.v2Value).toBeNull();
+ });
+
+ test("a v2 null normalized via unlimitedWhenNull matches a v1 unlimited cap", () => {
+ const mappings: TFeatureMapping[] = [
+ {
+ v2Key: "workspace_limit",
+ v1Field: "workspaceLimit",
+ extractV1: (p) => p.workspaceLimit,
+ normalize: unlimitedWhenNull
+ }
+ ];
+ const plan = makePlan({ workspaceLimit: null });
+ const entitlements = makeEntitlements({ workspace_limit: { value: null } });
+
+ const diff = findByKey(compareEntitlements(plan, entitlements, mappings), "workspace_limit");
+ expect(diff.kind).toBe(DualReadDiffKind.Match);
+ expect(diff.v1Value).toBe(UNLIMITED);
+ expect(diff.v2Value).toBe(UNLIMITED);
+ });
+});
diff --git a/backend/src/services/license-client/dual-read/entitlement-comparator.ts b/backend/src/services/license-client/dual-read/entitlement-comparator.ts
new file mode 100644
index 0000000000..58eb30ec10
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/entitlement-comparator.ts
@@ -0,0 +1,44 @@
+import { TFeatureSet } from "@app/ee/services/license/license-types";
+
+import { TEntitlementsResponse } from "../license-client-types";
+import { DualReadDiffKind, TDiscrepancy, TFeatureMapping, TNormalizedValue, UNLIMITED } from "./dual-read-types";
+
+const identity = (value: TNormalizedValue): TNormalizedValue => value;
+
+const compareOne = (plan: TFeatureSet, entitlements: TEntitlementsResponse, mapping: TFeatureMapping): TDiscrepancy => {
+ const normalize = mapping.normalize ?? identity;
+ const v2Raw = entitlements.features[mapping.v2Key];
+
+ // Resolve the v2 side once. The entitlement schema allows a null value, and a normalize (e.g.
+ // unlimitedWhenNull) may turn that into a real value; anything still null means v2 resolved nothing.
+ let v2Value: TNormalizedValue = null;
+ if (v2Raw) {
+ v2Value = normalize(v2Raw.value);
+ }
+
+ if (mapping.extractV1 === null) {
+ return { v2Key: mapping.v2Key, kind: DualReadDiffKind.V1Absent, v1Value: null, v2Value };
+ }
+
+ const v1Value = normalize(mapping.extractV1(plan));
+
+ if (v2Value === null) {
+ return { v2Key: mapping.v2Key, kind: DualReadDiffKind.V2Missing, v1Value, v2Value: null };
+ }
+
+ let kind = DualReadDiffKind.Mismatch;
+ if (v1Value === v2Value) {
+ kind = DualReadDiffKind.Match;
+ } else if ((v1Value === UNLIMITED) !== (v2Value === UNLIMITED)) {
+ // v2 has no pinned cross-repo "unlimited" representation, so this can't be confirmed a mismatch.
+ kind = DualReadDiffKind.Indeterminate;
+ }
+
+ return { v2Key: mapping.v2Key, kind, v1Value, v2Value };
+};
+
+export const compareEntitlements = (
+ plan: TFeatureSet,
+ entitlements: TEntitlementsResponse,
+ mappings: TFeatureMapping[]
+): TDiscrepancy[] => mappings.map((mapping) => compareOne(plan, entitlements, mapping));
diff --git a/backend/src/services/license-client/dual-read/entitlement-projection.test.ts b/backend/src/services/license-client/dual-read/entitlement-projection.test.ts
new file mode 100644
index 0000000000..777b0b02cb
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/entitlement-projection.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "vitest";
+
+import { TFeatureSet } from "@app/ee/services/license/license-types";
+
+import { TEntitlementsResponse } from "../license-client-types";
+import { projectV2ToFeatureSet } from "./entitlement-projection";
+
+const makeBase = (overrides: Partial<Record<keyof TFeatureSet, unknown>>): TFeatureSet =>
+ ({ rateLimits: { readLimit: 0, writeLimit: 0, secretsLimit: 0 }, ...overrides }) as TFeatureSet;
+
+const makeEntitlements = (features: TEntitlementsResponse["features"]): TEntitlementsResponse =>
+ ({ features }) as TEntitlementsResponse;
+
+describe("projectV2ToFeatureSet", () => {
+ test("overlays a present v2 feature onto the base TFeatureSet field", () => {
+ const plan = projectV2ToFeatureSet(makeBase({ rbac: false }), makeEntitlements({ rbac: { value: true } }));
+ expect(plan.rbac).toBe(true);
+ });
+
+ test("keeps the base value when v2 omits the key", () => {
+ const plan = projectV2ToFeatureSet(makeBase({ rbac: true }), makeEntitlements({}));
+ expect(plan.rbac).toBe(true);
+ });
+
+ test("keeps the base value when v2 returns null", () => {
+ const plan = projectV2ToFeatureSet(
+ makeBase({ dynamicSecret: true }),
+ makeEntitlements({ dynamic_secret: { value: null } })
+ );
+ expect(plan.dynamicSecret).toBe(true);
+ });
+
+ test("projects a nested rateLimits field via its dotted v1Field", () => {
+ const plan = projectV2ToFeatureSet(makeBase({}), makeEntitlements({ rate_limits_read_limit: { value: 500 } }));
+ expect(plan.rateLimits.readLimit).toBe(500);
+ });
+
+ test("does not mutate the passed base", () => {
+ const base = makeBase({ rbac: false });
+ projectV2ToFeatureSet(base, makeEntitlements({ rbac: { value: true } }));
+ expect(base.rbac).toBe(false);
+ });
+});
diff --git a/backend/src/services/license-client/dual-read/entitlement-projection.ts b/backend/src/services/license-client/dual-read/entitlement-projection.ts
new file mode 100644
index 0000000000..478c62b6b4
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/entitlement-projection.ts
@@ -0,0 +1,31 @@
+import { TFeatureSet } from "@app/ee/services/license/license-types";
+
+import { TEntitlementsResponse } from "../license-client-types";
+import { FEATURE_MAPPINGS } from "./feature-mapping";
+
+// Builds a v1-shaped TFeatureSet from the v2 entitlement set so getPlan can serve v2 in "on" mode
+// without changing its callers. Starts from the passed base (free-tier defaults) and overlays each
+// mapped feature; a key v2 omits or returns null for keeps the base value. Base is passed in (not
+// imported from license-fns) to avoid a license-service <-> license-fns import cycle.
+export const projectV2ToFeatureSet = (base: TFeatureSet, entitlements: TEntitlementsResponse): TFeatureSet => {
+ const plan = JSON.parse(JSON.stringify(base)) as Record<string, unknown> & { rateLimits: Record<string, unknown> };
+
+ FEATURE_MAPPINGS.forEach((mapping) => {
+ if (mapping.v1Field === null) {
+ return;
+ }
+ const raw = entitlements.features[mapping.v2Key];
+ if (!raw || raw.value === null || raw.value === undefined) {
+ return;
+ }
+
+ if (mapping.v1Field.includes(".")) {
+ const [parent, child] = mapping.v1Field.split(".");
+ (plan[parent] as Record<string, unknown>)[child] = raw.value;
+ } else {
+ plan[mapping.v1Field] = raw.value;
+ }
+ });
+
+ return plan as unknown as TFeatureSet;
+};
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/access.ts b/backend/src/services/license-client/dual-read/feature-mapping/access.ts
new file mode 100644
index 0000000000..b569ca9274
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/feature-mapping/access.ts
@@ -0,0 +1,69 @@
+import { TFeatureMapping } from "../dual-read-types";
+
+export const accessMappings: TFeatureMapping[] = [
+ {
+ v2Key: "rbac",
+ v1Field: "rbac",
+ extractV1: (p) => p.rbac
+ },
+ {
+ v2Key: "groups",
+ v1Field: "groups",
+ extractV1: (p) => p.groups
+ },
+ {
+ v2Key: "ip_allowlisting",
+ v1Field: "ipAllowlisting",
+ extractV1: (p) => p.ipAllowlisting
+ },
+ {
+ v2Key: "saml_sso",
+ v1Field: "samlSSO",
+ extractV1: (p) => p.samlSSO
+ },
+ {
+ v2Key: "oidc_sso",
+ v1Field: "oidcSSO",
+ extractV1: (p) => p.oidcSSO
+ },
+ {
+ v2Key: "ldap",
+ v1Field: "ldap",
+ extractV1: (p) => p.ldap
+ },
+ {
+ v2Key: "scim",
+ v1Field: "scim",
+ extractV1: (p) => p.scim
+ },
+ {
+ v2Key: "enforce_google_sso",
+ v1Field: "enforceGoogleSSO",
+ extractV1: (p) => p.enforceGoogleSSO
+ },
+ {
+ v2Key: "enforce_mfa",
+ v1Field: "enforceMfa",
+ extractV1: (p) => p.enforceMfa
+ },
+ {
+ v2Key: "github_org_sync",
+ v1Field: "githubOrgSync",
+ extractV1: (p) => p.githubOrgSync
+ },
+ {
+ v2Key: "enforce_identity_limit",
+ v1Field: "enforceIdentityLimit",
+ extractV1: (p) => Boolean(p.enforceIdentityLimit)
+ },
+ {
+ v2Key: "audit_logs",
+ v1Field: "auditLogs",
+ extractV1: (p) => p.auditLogs
+ },
+ {
+ v2Key: "audit_log_streams",
+ v1Field: "auditLogStreams",
+ extractV1: (p) => p.auditLogStreams
+ }
+];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/core.ts b/backend/src/services/license-client/dual-read/feature-mapping/core.ts
new file mode 100644
index 0000000000..78267a8d01
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/feature-mapping/core.ts
@@ -0,0 +1,84 @@
+import { TFeatureMapping } from "../dual-read-types";
+
+export const coreMappings: TFeatureMapping[] = [
+ {
+ v2Key: "secret_versioning",
+ v1Field: "secretVersioning",
+ extractV1: (p) => p.secretVersioning
+ },
+ {
+ v2Key: "pit_recovery",
+ v1Field: "pitRecovery",
+ extractV1: (p) => p.pitRecovery
+ },
+ {
+ v2Key: "dynamic_secret",
+ v1Field: "dynamicSecret",
+ extractV1: (p) => p.dynamicSecret
+ },
+ {
+ v2Key: "sub_organization",
+ v1Field: "subOrganization",
+ extractV1: (p) => p.subOrganization
+ },
+ {
+ v2Key: "secret_approval",
+ v1Field: "secretApproval",
+ extractV1: (p) => p.secretApproval
+ },
+ {
+ v2Key: "secret_rotation",
+ v1Field: "secretRotation",
+ extractV1: (p) => p.secretRotation
+ },
+ {
+ v2Key: "secret_access_insights",
+ v1Field: "secretAccessInsights",
+ extractV1: (p) => p.secretAccessInsights
+ },
+ {
+ v2Key: "project_templates",
+ v1Field: "projectTemplates",
+ extractV1: (p) => p.projectTemplates
+ },
+ {
+ v2Key: "event_subscriptions",
+ v1Field: "eventSubscriptions",
+ extractV1: (p) => p.eventSubscriptions
+ },
+ {
+ v2Key: "machine_identity_auth_templates",
+ v1Field: "machineIdentityAuthTemplates",
+ extractV1: (p) => p.machineIdentityAuthTemplates
+ },
+ {
+ v2Key: "secret_share_external_branding",
+ v1Field: "secretShareExternalBranding",
+ extractV1: (p) => p.secretShareExternalBranding
+ },
+ {
+ v2Key: "instance_user_management",
+ v1Field: "instanceUserManagement",
+ extractV1: (p) => p.instanceUserManagement
+ },
+ {
+ v2Key: "secret_scanning",
+ v1Field: "secretScanning",
+ extractV1: (p) => p.secretScanning
+ },
+ {
+ v2Key: "enterprise_secret_syncs",
+ v1Field: "enterpriseSecretSyncs",
+ extractV1: (p) => p.enterpriseSecretSyncs
+ },
+ {
+ v2Key: "enterprise_certificate_syncs",
+ v1Field: "enterpriseCertificateSyncs",
+ extractV1: (p) => p.enterpriseCertificateSyncs
+ },
+ {
+ v2Key: "enterprise_app_connections",
+ v1Field: "enterpriseAppConnections",
+ extractV1: (p) => p.enterpriseAppConnections
+ }
+];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/existing.ts b/backend/src/services/license-client/dual-read/feature-mapping/existing.ts
new file mode 100644
index 0000000000..d2faaa45c3
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/feature-mapping/existing.ts
@@ -0,0 +1,45 @@
+import {
+ AuditRetentionDays,
+ MaxActiveCerts,
+ MaxIdentities,
+ MaxInternalCas,
+ MaxPamResources,
+ SsoEnforcement
+} from "../../features";
+import { TFeatureMapping, unlimitedWhenNull } from "../dual-read-types";
+
+export const existingDescriptorMappings: TFeatureMapping[] = [
+ {
+ v2Key: MaxIdentities.key,
+ v1Field: "identityLimit",
+ extractV1: (p) => p.identityLimit,
+ normalize: unlimitedWhenNull
+ },
+ {
+ v2Key: AuditRetentionDays.key,
+ v1Field: "auditLogsRetentionDays",
+ extractV1: (p) => p.auditLogsRetentionDays
+ },
+ {
+ // v2's sso_enforcement is the general "can enforce SSO" entitlement; v1 has no single field for it
+ // (SAML/OIDC enforcement rides on the samlSSO/oidcSSO capabilities, Google on enforceGoogleSSO).
+ v2Key: SsoEnforcement.key,
+ v1Field: null,
+ extractV1: null
+ },
+ {
+ v2Key: MaxInternalCas.key,
+ v1Field: null,
+ extractV1: null
+ },
+ {
+ v2Key: MaxActiveCerts.key,
+ v1Field: null,
+ extractV1: null
+ },
+ {
+ v2Key: MaxPamResources.key,
+ v1Field: null,
+ extractV1: null
+ }
+];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/index.ts b/backend/src/services/license-client/dual-read/feature-mapping/index.ts
new file mode 100644
index 0000000000..a5ab2b24ba
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/feature-mapping/index.ts
@@ -0,0 +1,28 @@
+import { TFeatureMapping } from "../dual-read-types";
+import { accessMappings } from "./access";
+import { coreMappings } from "./core";
+import { existingDescriptorMappings } from "./existing";
+import { limitsMappings } from "./limits";
+import { pkiSecurityMappings } from "./pki-security";
+
+export const FEATURE_MAPPINGS: TFeatureMapping[] = [
+ ...existingDescriptorMappings,
+ ...coreMappings,
+ ...accessMappings,
+ ...pkiSecurityMappings,
+ ...limitsMappings
+];
+
+// v1 TFeatureSet keys intentionally not compared (live usage counters + plan metadata).
+export const EXCLUDED_FIELDS: ReadonlySet<string> = new Set([
+ "_id",
+ "slug",
+ "tier",
+ "status",
+ "trial_end",
+ "has_used_trial",
+ "workspacesUsed",
+ "membersUsed",
+ "identitiesUsed",
+ "environmentsUsed"
+]);
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/limits.ts b/backend/src/services/license-client/dual-read/feature-mapping/limits.ts
new file mode 100644
index 0000000000..28cf1b72f9
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/feature-mapping/limits.ts
@@ -0,0 +1,47 @@
+import { TFeatureMapping, unlimitedWhenNull } from "../dual-read-types";
+
+export const limitsMappings: TFeatureMapping[] = [
+ {
+ v2Key: "workspace_limit",
+ v1Field: "workspaceLimit",
+ extractV1: (p) => p.workspaceLimit,
+ normalize: unlimitedWhenNull
+ },
+ {
+ v2Key: "member_limit",
+ v1Field: "memberLimit",
+ extractV1: (p) => p.memberLimit,
+ normalize: unlimitedWhenNull
+ },
+ {
+ v2Key: "environment_limit",
+ v1Field: "environmentLimit",
+ extractV1: (p) => p.environmentLimit,
+ normalize: unlimitedWhenNull
+ },
+ {
+ v2Key: "audit_log_stream_limit",
+ v1Field: "auditLogStreamLimit",
+ extractV1: (p) => p.auditLogStreamLimit
+ },
+ {
+ v2Key: "honey_token_limit",
+ v1Field: "honeyTokenLimit",
+ extractV1: (p) => p.honeyTokenLimit
+ },
+ {
+ v2Key: "rate_limits_read_limit",
+ v1Field: "rateLimits.readLimit",
+ extractV1: (p) => p.rateLimits.readLimit
+ },
+ {
+ v2Key: "rate_limits_write_limit",
+ v1Field: "rateLimits.writeLimit",
+ extractV1: (p) => p.rateLimits.writeLimit
+ },
+ {
+ v2Key: "rate_limits_secrets_limit",
+ v1Field: "rateLimits.secretsLimit",
+ extractV1: (p) => p.rateLimits.secretsLimit
+ }
+];
diff --git a/backend/src/services/license-client/dual-read/feature-mapping/mapping-completeness.test.ts b/backend/src/services/license-client/dual-read/feature-mapping/mapping-completeness.test.ts
new file mode 100644
index 0000000000..cfd2910bb4
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/feature-mapping/mapping-completeness.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test } from "vitest";
+
+import { getDefaultOnPremFeatures } from "@app/ee/services/license/license-fns";
+
+import { EXCLUDED_FIELDS, FEATURE_MAPPINGS } from "./index";
+
+const topLevelV1Field = (v1Field: string): string => {
+ const dotIndex = v1Field.indexOf(".");
+ if (dotIndex === -1) {
+ return v1Field;
+ }
+ return v1Field.slice(0, dotIndex);
+};
+
+describe("feature mapping completeness", () => {
+ test("every v1 TFeatureSet field is excluded or referenced by a mapping", () => {
+ const referenced = new Set<string>();
+ for (const mapping of FEATURE_MAPPINGS) {
+ if (mapping.v1Field) {
+ referenced.add(topLevelV1Field(mapping.v1Field));
+ }
+ }
+
+ const planFields = Object.keys(getDefaultOnPremFeatures());
+ const uncovered = planFields.filter((field) => !EXCLUDED_FIELDS.has(field) && !referenced.has(field));
+
+ expect(uncovered).toEqual([]);
+ });
+});
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
new file mode 100644
index 0000000000..07c8d47049
--- /dev/null
+++ b/backend/src/services/license-client/dual-read/feature-mapping/pki-security.ts
@@ -0,0 +1,89 @@
+import { TFeatureMapping } from "../dual-read-types";
+
+export const pkiSecurityMappings: TFeatureMapping[] = [
+ {
+ v2Key: "ca_crl",
+ v1Field: "caCrl",
+ extractV1: (p) => p.caCrl
+ },
+ {
+ v2Key: "pki_est",
+ v1Field: "pkiEst",
+ extractV1: (p) => p.pkiEst
+ },
+ {
+ v2Key: "pki_acme",
+ v1Field: "pkiAcme",
+ extractV1: (p) => p.pkiAcme
+ },
+ {
+ v2Key: "pki_scep",
+ v1Field: "pkiScep",
+ extractV1: (p) => p.pkiScep
+ },
+ {
+ v2Key: "pki_pqc",
+ v1Field: "pkiPqc",
+ extractV1: (p) => p.pkiPqc
+ },
+ {
+ v2Key: "pki_legacy_templates",
+ v1Field: "pkiLegacyTemplates",
+ extractV1: (p) => p.pkiLegacyTemplates
+ },
+ {
+ v2Key: "ssh_host_groups",
+ v1Field: "sshHostGroups",
+ extractV1: (p) => p.sshHostGroups
+ },
+ {
+ v2Key: "hsm",
+ v1Field: "hsm",
+ extractV1: (p) => p.hsm
+ },
+ {
+ v2Key: "external_kms",
+ v1Field: "externalKms",
+ extractV1: (p) => p.externalKms
+ },
+ {
+ v2Key: "kms_pqc",
+ v1Field: "kmsPqc",
+ extractV1: (p) => p.kmsPqc
+ },
+ {
+ v2Key: "kmip",
+ v1Field: "kmip",
+ extractV1: (p) => p.kmip
+ },
+ {
+ v2Key: "fips",
+ v1Field: "fips",
+ extractV1: (p) => p.fips
+ },
+ {
+ v2Key: "gateway",
+ v1Field: "gateway",
+ extractV1: (p) => p.gateway
+ },
+ {
+ v2Key: "gateway_pool",
+ v1Field: "gatewayPool",
+ extractV1: (p) => p.gatewayPool
+ },
+ {
+ v2Key: "honey_tokens",
+ v1Field: "honeyTokens",
+ extractV1: (p) => p.honeyTokens
+ },
+ {
+ v2Key: "custom_rate_limits",
+ v1Field: "customRateLimits",
+ extractV1: (p) => p.customRateLimits
+ },
+ {
+ v2Key: "custom_alerts",
+ v1Field: "customAlerts",
+ extractV1: (p) => p.customAlerts
+ }
+];
diff --git a/backend/src/services/license-client/index.ts b/backend/src/services/license-client/index.ts
index 83afcd88a5..19c27b7eb2 100644
--- a/backend/src/services/license-client/index.ts
+++ b/backend/src/services/license-client/index.ts
@@ -12,3 +12,4 @@ export { defineFeature, defineLimitFeature } from "./feature";
export * from "./features";
export type { TLicenseClientFactory } from "./license-client";
export { licenseClientFactory } from "./license-client";
+export type { TEntitlementsResponse } from "./license-client-types";
diff --git a/backend/src/services/license-client/license-client.test.ts b/backend/src/services/license-client/license-client.test.ts
index 388424b48f..8f60c0aa2e 100644
--- a/backend/src/services/license-client/license-client.test.ts
+++ b/backend/src/services/license-client/license-client.test.ts
@@ -123,7 +123,7 @@ describe("featureReaderFactory", () => {
describe("licenseClientFactory (usage example)", () => {
const licenseClient = licenseClientFactory({
envConfig: {
- LICENSE_SERVER_V2_ENABLED: false,
+ LICENSE_SERVER_V2_MODE: "off",
LICENSE_SERVER_V2_URL: undefined,
LICENSE_SERVER_V2_SERVICE_KEY: undefined
},
diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.ts
index f03f2b56bd..d00bb04a8c 100644
--- a/backend/src/services/license-client/license-client.ts
+++ b/backend/src/services/license-client/license-client.ts
@@ -8,7 +8,7 @@ import { entitlementResolverFactory } from "./license-client-cache";
import { TCreateCheckoutPayload, TCreatePortalPayload, TLicenseClientBackend } from "./license-client-types";
type TLicenseClientFactoryDep = {
- envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_ENABLED" | "LICENSE_SERVER_V2_URL" | "LICENSE_SERVER_V2_SERVICE_KEY">;
+ envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_MODE" | "LICENSE_SERVER_V2_URL" | "LICENSE_SERVER_V2_SERVICE_KEY">;
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
};
@@ -17,7 +17,7 @@ export type TLicenseClientFactory = ReturnType<typeof licenseClientFactory>;
// Returns null (SDK dormant -> getFeature serves fallbacks) unless the kill switch is on and the
// server URL + service key are configured.
const buildBackend = (envConfig: TLicenseClientFactoryDep["envConfig"]): TLicenseClientBackend | null => {
- if (!envConfig.LICENSE_SERVER_V2_ENABLED) {
+ if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
return null;
}
diff --git a/backend/src/services/license-client/usage/usage-metering-service.ts b/backend/src/services/license-client/usage/usage-metering-service.ts
index 9a50a0c614..c101546026 100644
--- a/backend/src/services/license-client/usage/usage-metering-service.ts
+++ b/backend/src/services/license-client/usage/usage-metering-service.ts
@@ -8,7 +8,7 @@ export type TUsageMeteringServiceFactory = ReturnType<typeof usageMeteringServic
type TUsageMeteringServiceFactoryDep = {
queueService: Pick<TQueueServiceFactory, "queue">;
projectDAL: Pick<TProjectDALFactory, "findById">;
- envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_ENABLED">;
+ envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_MODE">;
};
// Debounce window: bursts for the same {org, feature} collapse to one count because the delayed job
@@ -32,7 +32,7 @@ export const usageMeteringServiceFactory = ({
// Fire-and-forget signal from a metered create/delete on an org-scoped meter. Never awaited and
// never throws into the request path; inert until the v2 license server is enabled.
const emit = (orgId: string, featureKey: string) => {
- if (!envConfig.LICENSE_SERVER_V2_ENABLED) {
+ if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
return;
}
@@ -44,7 +44,7 @@ export const usageMeteringServiceFactory = ({
// Project-scoped meters sum across an org's projects, so the event is keyed by org. The org is
// resolved in the background to keep the request path free of an extra read.
const emitForProject = (projectId: string, featureKey: string) => {
- if (!envConfig.LICENSE_SERVER_V2_ENABLED) {
+ if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
return;
}
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 98d36033b4..7355aa24d9 100644
--- a/backend/src/services/license-client/usage/usage-metering.test.ts
+++ b/backend/src/services/license-client/usage/usage-metering.test.ts
@@ -43,7 +43,7 @@ describe("usageMeteringService.emit (org-scoped)", () => {
const svc = usageMeteringServiceFactory({
queueService: { queue },
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_ENABLED: false }
+ envConfig: { LICENSE_SERVER_V2_MODE: "off" }
});
svc.emit(ORG_ID, MaxIdentities.key);
@@ -57,7 +57,7 @@ describe("usageMeteringService.emit (org-scoped)", () => {
const svc = usageMeteringServiceFactory({
queueService: { queue },
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
});
svc.emit(ORG_ID, MaxIdentities.key);
@@ -79,7 +79,7 @@ describe("usageMeteringService.emit (org-scoped)", () => {
const svc = usageMeteringServiceFactory({
queueService: { queue },
projectDAL: { findById: vi.fn() },
- envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
});
expect(() => svc.emit(ORG_ID, MaxIdentities.key)).not.toThrow();
@@ -94,7 +94,7 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
const svc = usageMeteringServiceFactory({
queueService: { queue },
projectDAL: { findById } as never,
- envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
});
svc.emitForProject(PROJECT_ID, MaxPamResources.key);
@@ -112,7 +112,7 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
const svc = usageMeteringServiceFactory({
queueService: { queue },
projectDAL: { findById: vi.fn(async () => undefined) } as never,
- envConfig: { LICENSE_SERVER_V2_ENABLED: true }
+ envConfig: { LICENSE_SERVER_V2_MODE: "read-compare" }
});
svc.emitForProject(PROJECT_ID, MaxPamResources.key);
@@ -127,7 +127,7 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
const svc = usageMeteringServiceFactory({
queueService: { queue },
projectDAL: { findById },
- envConfig: { LICENSE_SERVER_V2_ENABLED: false }
+ envConfig: { LICENSE_SERVER_V2_MODE: "off" }
});
svc.emitForProject(PROJECT_ID, MaxPamResources.key);
@@ -140,16 +140,16 @@ describe("usageMeteringService.emitForProject (project-scoped)", () => {
describe("buildUsageReporter", () => {
test("is null when disabled", () => {
- expect(buildUsageReporter({ LICENSE_SERVER_V2_ENABLED: false })).toBeNull();
+ expect(buildUsageReporter({ LICENSE_SERVER_V2_MODE: "off" })).toBeNull();
});
test("is null when enabled but unconfigured", () => {
- expect(buildUsageReporter({ LICENSE_SERVER_V2_ENABLED: true })).toBeNull();
+ expect(buildUsageReporter({ LICENSE_SERVER_V2_MODE: "read-compare" })).toBeNull();
});
test("is a reporter when enabled and configured", () => {
const reporter = buildUsageReporter({
- LICENSE_SERVER_V2_ENABLED: true,
+ LICENSE_SERVER_V2_MODE: "read-compare",
LICENSE_SERVER_V2_URL: "https://license.example.com",
LICENSE_SERVER_V2_SERVICE_KEY: "svc-key"
});
diff --git a/backend/src/services/license-client/usage/usage-reporter.ts b/backend/src/services/license-client/usage/usage-reporter.ts
index 1e2624c9df..297ca09e53 100644
--- a/backend/src/services/license-client/usage/usage-reporter.ts
+++ b/backend/src/services/license-client/usage/usage-reporter.ts
@@ -37,11 +37,11 @@ export const usageReporterFactory = (serverUrl: string, serviceKey: string): TUs
});
// Returns null when the v2 license server is disabled or unconfigured, which keeps usage reporting
-// inert until Phase 2 flips LICENSE_SERVER_V2_ENABLED on.
+// inert until Phase 2 flips LICENSE_SERVER_V2_MODE on.
export const buildUsageReporter = (
- envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_ENABLED" | "LICENSE_SERVER_V2_URL" | "LICENSE_SERVER_V2_SERVICE_KEY">
+ envConfig: Pick<TEnvConfig, "LICENSE_SERVER_V2_MODE" | "LICENSE_SERVER_V2_URL" | "LICENSE_SERVER_V2_SERVICE_KEY">
): TUsageReporter | null => {
- if (!envConfig.LICENSE_SERVER_V2_ENABLED) {
+ if (envConfig.LICENSE_SERVER_V2_MODE === "off") {
return null;
}