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: implemented the main changes for self hosted
=efca022bfb1f
diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.tsindex 8c328c73ac..d916706afd 100644--- a/backend/src/ee/services/license-v2/license-v2-service.ts+++ b/backend/src/ee/services/license-v2/license-v2-service.ts@@ -15,7 +15,6 @@ import {import { TMeteredFeature } from "@app/services/license-client/usage/usage-counters";import { TOrgDALFactory } from "@app/services/org/org-dal";-import { isV2SelfHostedLicenseKey } from "../license/license-fns";import { OrgPermissionBillingActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";import {@@ -390,9 +389,7 @@ export const licenseV2ServiceFactory = ({return { planTier: plan.tier, quantities, declaredUsage };};- // A self-hosted v2 license is managed out-of-band: the billing surface is read-only. Self-serve- // mutations don't need an explicit guard here, the self-hosted license client rejects them itself.- const isSelfHostedLicense = isV2SelfHostedLicenseKey(envConfig.LICENSE_KEY ?? "");+ const isSelfHostedLicense = Boolean(envConfig.LICENSE_KEY);const ensureBillingRead = async (orgId: string, actor: TGetBillingV2OverviewDTO["actor"]) => {const { permission } = await permissionService.getOrgPermission({diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex 8c78b81217..75bad2c30b 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -19,12 +19,6 @@ export const isOfflineLicenseKey = (licenseKey: string): boolean => {}};-// Self-hosted License Server v2 keys carry this prefix; legacy online keys look like "QVHK-HIGYH".-export const SELF_HOSTED_V2_LICENSE_KEY_PREFIX = "infisical_lk_";--export const isV2SelfHostedLicenseKey = (licenseKey: string): boolean =>- licenseKey.startsWith(SELF_HOSTED_V2_LICENSE_KEY_PREFIX);-export const getLicenseKeyConfig = (config?: Pick<TEnvConfig, "LICENSE_KEY" | "LICENSE_KEY_OFFLINE">): TLicenseKeyConfig => {@@ -37,10 +31,6 @@ export const getLicenseKeyConfig = (const licenseKey = cfg.LICENSE_KEY;if (licenseKey) {- if (isV2SelfHostedLicenseKey(licenseKey)) {- return { isValid: true, licenseKey, type: LicenseType.OnlineV2 };- }-if (isOfflineLicenseKey(licenseKey)) {return { isValid: true, licenseKey, type: LicenseType.Offline };}diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.tsindex c478b3bdbd..f043c53204 100644--- a/backend/src/ee/services/license/license-service.ts+++ b/backend/src/ee/services/license/license-service.ts@@ -166,26 +166,6 @@ export const licenseServiceFactory = ({}const currentPlan = projectV2ToFeatureSet(getDefaultOnPremFeatures(), entitlements);- // The entitlement projection only carries feature flags; derive the plan tier from the- // subscription/contract view. Non-fatal so a subscription read failure keeps the features.- try {- const subscription = await licenseClient.getSubscription(SELF_HOSTED_LICENSE_ORG_ID);- const paidTiers = (subscription?.items ?? [])- .map((item) => item.plan.toLowerCase())- .filter((tier) => tier !== "free");- if (paidTiers.some((tier) => tier.includes("enterprise"))) {- currentPlan.slug = "enterprise";- } else if (paidTiers.some((tier) => tier.includes("advanced"))) {- currentPlan.slug = "advanced";- } else if (paidTiers.length > 0) {- currentPlan.slug = "pro";- }- } catch (error) {- logger.error(error, "syncSelfHostedV2Features: failed to resolve plan tier from subscription");- }-- // Usage is instance-wide for self-hosted (null orgId aggregates the whole instance), as in the v1 sync.- currentPlan.workspacesUsed = await projectDAL.countOfBillableOrgProjects(null);currentPlan.membersUsed = await licenseDAL.countOfOrgMembers(null);currentPlan.identitiesUsed = await licenseDAL.countOrgUsersAndIdentities(null);@@ -490,14 +470,14 @@ export const licenseServiceFactory = ({}await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(rootOrgId));} else if (instanceType === InstanceType.EnterpriseOnPrem) {- const usedSeats = await licenseDAL.countOfOrgMembers(null, tx);- const usedIdentitySeats = await licenseDAL.countOrgUsersAndIdentities(null, tx);- onPremFeatures.membersUsed = usedSeats;- onPremFeatures.identitiesUsed = usedIdentitySeats;- await licenseServerOnPremApi.request.patch(`/api/license/v1/license`, {- usedSeats,- usedIdentitySeats- });+ // const usedSeats = await licenseDAL.countOfOrgMembers(null, tx);+ // const usedIdentitySeats = await licenseDAL.countOrgUsersAndIdentities(null, tx);+ // onPremFeatures.membersUsed = usedSeats;+ // onPremFeatures.identitiesUsed = usedIdentitySeats;+ // await licenseServerOnPremApi.request.patch(`/api/license/v1/license`, {+ // usedSeats,+ // usedIdentitySeats+ // });} else if (instanceType === InstanceType.EnterpriseOnPremV2) {// v2 self-hosted reports usage asynchronously via the usage-snapshot queue, not a synchronous seat// patch; keep the in-memory counts current so limit checks are accurate until the next sync.diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex 4ada40f300..a11e806b9b 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -349,7 +349,7 @@ const envSchema = zLICENSE_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"),+ LICENSE_SERVER_V2_MODE: z.enum(["off", "read-compare", "on"]).default("on"),LICENSE_SERVER_V2_URL: zpStr(z.string().optional()),LICENSE_SERVER_V2_SERVICE_KEY: zpStr(z.string().optional()),// When true, new checkouts (adding a payment method) and trials on License Server v1 cloud arediff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex e23b544dcf..9d90a41a6e 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -102,7 +102,9 @@ import { ldapConfigDALFactory } from "@app/ee/services/ldap-config/ldap-config-dimport { ldapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";import { ldapGroupMapDALFactory } from "@app/ee/services/ldap-config/ldap-group-map-dal";import { licenseDALFactory } from "@app/ee/services/license/license-dal";+import { getLicenseKeyConfig } from "@app/ee/services/license/license-fns";import { licenseServiceFactory } from "@app/ee/services/license/license-service";+import { LicenseType } from "@app/ee/services/license/license-types";import { licenseV2ServiceFactory } from "@app/ee/services/license-v2/license-v2-service";import { oidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";import { oidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";@@ -835,7 +837,11 @@ export const registerRoutes = async (const usageCounterDAL = usageCounterDALFactory(db);const meteredFeatures = buildMeteredFeatures({ licenseDAL, usageCounterDAL, isCloud: envConfig.isCloud });meteredFeatures.forEach(({ feature, count }) => licenseClient.registerCounter(feature, count));- const usageReporter = buildUsageReporter(envConfig);+ // An offline (air-gapped) license can't reach the license server, so usage reporting + its daily+ // true-up cron are inert: skip the reporter entirely and disable the cron below.+ const licenseKeyConfig = getLicenseKeyConfig(envConfig);+ const isOfflineLicense = licenseKeyConfig.isValid && licenseKeyConfig.type === LicenseType.Offline;+ const usageReporter = isOfflineLicense ? null : buildUsageReporter(envConfig);let usageSource = "self-hosted";if (envConfig.isCloud) {usageSource = "cloud";@@ -844,12 +850,12 @@ export const registerRoutes = async (queueService,cronJob,keyStore,- orgDAL,licenseService,usageMeteringService,meteredFeatures,usageReporter,isCloud: envConfig.isCloud,+ isOffline: isOfflineLicense,source: usageSource});diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.tsindex b31fc294c1..3381680930 100644--- a/backend/src/services/license-client/license-client-backends.ts+++ b/backend/src/services/license-client/license-client-backends.ts@@ -35,6 +35,7 @@ import {TTrialResult,TTrialsResponse} from "./license-client-types";+import { TLicenseTokenProvider } from "./license-token-provider";// Token-scoped paths for the self-hosted (license-key) backend: the key identifies the license, so// no org_id is carried. The global catalog is org-independent and shared by both backends.@@ -361,76 +362,81 @@ export const licenseServerBackend = (const notSupportedOnSelfHosted = (operation: string) => (): Promise<never> =>Promise.reject(new Error(`license operation "${operation}" is not supported for self-hosted licenses`));-// Backend for a self-hosted License Server v2 license. Unlike the cloud backend it authenticates with-// the raw license key as a bearer token (not a minted RS256 service JWT) and is single-tenant: the key+// Backend for a self-hosted License Server v2 license. Unlike the cloud backend (which mints an RS256+// service JWT), it exchanges the license key for a short-lived JWT at the token endpoint and sends that+// as the bearer — the same convention both self-hosted key formats now follow. Single-tenant: the key// identifies the license, so entitlement/subscription reads carry no org_id. Only the read + usage +// refresh endpoints the self-hosted contract exposes are implemented; everything billing-related throws.export const licenseServerSelfHostedBackend = (serverUrl: string,- licenseKey: string,+ tokenProvider: TLicenseTokenProvider,region?: string-): TLicenseClientBackend => ({- fetchEntitlements: async (): Promise<TEntitlementsResponse> => {- const url = new URL(ENTITLEMENTS_PATH, serverUrl);- if (region) {- url.searchParams.set("region", region);+): TLicenseClientBackend => {+ // GET with the exchanged JWT; on a 401 (token expired mid-flight) drop the cache and retry once.+ const authedGet = async (url: URL): Promise<Response> => {+ const send = async () =>+ fetch(url, {+ method: "GET",+ headers: { Authorization: `Bearer ${await tokenProvider.getToken()}` },+ redirect: "manual"+ });+ const res = await send();+ if (res.status !== 401) {+ return res;}- const res = await fetch(url, {- method: "GET",- headers: { Authorization: `Bearer ${licenseKey}` },- redirect: "manual"- });- await throwIfResponseError(res);- const body: unknown = await res.json();- return entitlementsResponseSchema.parse(body);- },+ tokenProvider.invalidate();+ return send();+ };- fetchCatalog: async (): Promise<TCatalogResponse> => {- const url = new URL(PRODUCTS_PATH, serverUrl);- const res = await fetch(url, {- method: "GET",- headers: { Authorization: `Bearer ${licenseKey}` },- redirect: "manual"- });- await throwIfResponseError(res);- const body: unknown = await res.json();- return catalogResponseSchema.parse(body);- },+ return {+ fetchEntitlements: async (): Promise<TEntitlementsResponse> => {+ const url = new URL(ENTITLEMENTS_PATH, serverUrl);+ if (region) {+ url.searchParams.set("region", region);+ }+ const res = await authedGet(url);+ await throwIfResponseError(res);+ const body: unknown = await res.json();+ return entitlementsResponseSchema.parse(body);+ },- // The license's subscription/contract view. A 404 (no contract yet) degrades to "no subscription".- fetchSubscription: async (): Promise<TSubscriptionResponse | null> => {- const url = new URL(SUBSCRIPTION_PATH, serverUrl);- const res = await fetch(url, {- method: "GET",- headers: { Authorization: `Bearer ${licenseKey}` },- redirect: "manual"- });- if (res.status === 404) {- return null;- }- await throwIfResponseError(res);- const body: unknown = await res.json();- const parsed = subscriptionResponseSchema.safeParse(body);- if (!parsed.success) {- logger.error({ err: parsed.error }, "license-client: /subscription failed schema validation (self-hosted)");- return null;- }- if (!parsed.data.status) {- return null;- }- return parsed.data;- },+ fetchCatalog: async (): Promise<TCatalogResponse> => {+ const res = await authedGet(new URL(PRODUCTS_PATH, serverUrl));+ await throwIfResponseError(res);+ const body: unknown = await res.json();+ return catalogResponseSchema.parse(body);+ },- fetchCloudPlan: notSupportedOnSelfHosted("fetchCloudPlan"),- fetchBillingProfile: notSupportedOnSelfHosted("fetchBillingProfile"),- createPortalSession: notSupportedOnSelfHosted("createPortalSession"),- previewSubscriptionChange: notSupportedOnSelfHosted("previewSubscriptionChange"),- buyProduct: notSupportedOnSelfHosted("buyProduct"),- removeProduct: notSupportedOnSelfHosted("removeProduct"),- changeCommitments: notSupportedOnSelfHosted("changeCommitments"),- startTrial: notSupportedOnSelfHosted("startTrial"),- cancelTrial: notSupportedOnSelfHosted("cancelTrial"),- fetchTrials: notSupportedOnSelfHosted("fetchTrials"),- cancelSubscription: notSupportedOnSelfHosted("cancelSubscription"),- resumeSubscription: notSupportedOnSelfHosted("resumeSubscription")-});+ // The license's subscription/contract view. A 404 (no contract yet) degrades to "no subscription".+ fetchSubscription: async (): Promise<TSubscriptionResponse | null> => {+ const res = await authedGet(new URL(SUBSCRIPTION_PATH, serverUrl));+ if (res.status === 404) {+ return null;+ }+ await throwIfResponseError(res);+ const body: unknown = await res.json();+ const parsed = subscriptionResponseSchema.safeParse(body);+ if (!parsed.success) {+ logger.error({ err: parsed.error }, "license-client: /subscription failed schema validation (self-hosted)");+ return null;+ }+ if (!parsed.data.status) {+ return null;+ }+ return parsed.data;+ },++ fetchCloudPlan: notSupportedOnSelfHosted("fetchCloudPlan"),+ fetchBillingProfile: notSupportedOnSelfHosted("fetchBillingProfile"),+ createPortalSession: notSupportedOnSelfHosted("createPortalSession"),+ previewSubscriptionChange: notSupportedOnSelfHosted("previewSubscriptionChange"),+ buyProduct: notSupportedOnSelfHosted("buyProduct"),+ removeProduct: notSupportedOnSelfHosted("removeProduct"),+ changeCommitments: notSupportedOnSelfHosted("changeCommitments"),+ startTrial: notSupportedOnSelfHosted("startTrial"),+ cancelTrial: notSupportedOnSelfHosted("cancelTrial"),+ fetchTrials: notSupportedOnSelfHosted("fetchTrials"),+ cancelSubscription: notSupportedOnSelfHosted("cancelSubscription"),+ resumeSubscription: notSupportedOnSelfHosted("resumeSubscription")+ };+};diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.tsindex 3e3af953b3..e6d1e826fd 100644--- a/backend/src/services/license-client/license-client.ts+++ b/backend/src/services/license-client/license-client.ts@@ -15,6 +15,7 @@ import {TStartTrialPayload,TSubscriptionPreviewPayload} from "./license-client-types";+import { createSelfHostedTokenProvider } from "./license-token-provider";type TLicenseClientFactoryDep = {envConfig: Pick<@@ -22,6 +23,7 @@ type TLicenseClientFactoryDep = {| "LICENSE_SERVER_V2_MODE"| "LICENSE_SERVER_V2_URL"| "LICENSE_SERVER_V2_SERVICE_KEY"+ | "LICENSE_SERVER_URL"| "LICENSE_KEY"| "INTERNAL_REGION">;@@ -30,15 +32,19 @@ type TLicenseClientFactoryDep = {export type TLicenseClientFactory = ReturnType<typeof licenseClientFactory>;-// Mirrors SELF_HOSTED_V2_LICENSE_KEY_PREFIX in ee/license-fns; inlined to avoid a services -> ee-// runtime import cycle (license-client <- license-service <- license-fns).-const SELF_HOSTED_V2_LICENSE_KEY_PREFIX = "infisical_lk_";-// Returns null (SDK dormant -> getFeature serves fallbacks) unless the kill switch is on and either a-// self-hosted v2 license key or the cloud service key (plus server URL) is configured.+// self-hosted license key or the cloud service key (plus server URL) is configured.const buildBackend = (envConfig: TLicenseClientFactoryDep["envConfig"]): TLicenseClientBackend | null => {- if (envConfig.LICENSE_SERVER_V2_MODE === "off") {- return null;+ const licenseKey = envConfig.LICENSE_KEY;+ if (licenseKey) {+ if (!envConfig.LICENSE_SERVER_URL) {+ logger.warn(+ "license-client: self-hosted key set but LICENSE_SERVER_URL (token endpoint) is missing; serving feature fallbacks"+ );+ return null;+ }+ const tokenProvider = createSelfHostedTokenProvider(licenseKey, { serverUrl: envConfig.LICENSE_SERVER_URL });+ return licenseServerSelfHostedBackend(envConfig.LICENSE_SERVER_URL, tokenProvider, envConfig.INTERNAL_REGION);}const serverUrl = envConfig.LICENSE_SERVER_V2_URL;@@ -60,13 +66,6 @@ const buildBackend = (envConfig: TLicenseClientFactoryDep["envConfig"]): TLicensreturn null;}- // A self-hosted v2 license authenticates with its own key as a bearer token; the cloud path mints an- // RS256 service JWT from the service key instead.- const licenseKey = envConfig.LICENSE_KEY;- if (licenseKey?.startsWith(SELF_HOSTED_V2_LICENSE_KEY_PREFIX)) {- return licenseServerSelfHostedBackend(serverUrl, licenseKey, envConfig.INTERNAL_REGION);- }-const signingKey = envConfig.LICENSE_SERVER_V2_SERVICE_KEY;if (!signingKey) {logger.warn("license-client: enabled but LICENSE_SERVER_V2_SERVICE_KEY is missing; serving feature fallbacks");diff --git a/backend/src/services/license-client/license-token-provider.test.ts b/backend/src/services/license-client/license-token-provider.test.tsnew file mode 100644index 0000000000..2818a51850--- /dev/null+++ b/backend/src/services/license-client/license-token-provider.test.ts@@ -0,0 +1,109 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++import { createSelfHostedTokenProvider } from "./license-token-provider";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }+}));++const SERVER_URL = "https://license.example.com";+const LICENSE_KEY = "infisical_lk_test";++// Build a JWT-shaped string ("header.payload.sig") whose payload carries the given exp (unix seconds).+const makeJwt = (expSeconds: number | null): string => {+ const payload = expSeconds === null ? {} : { exp: expSeconds };+ const encode = (obj: object) => Buffer.from(JSON.stringify(obj)).toString("base64url");+ return `${encode({ alg: "HS256" })}.${encode(payload)}.sig`;+};++const nowSeconds = () => Math.floor(Date.now() / 1000);++const mockFetchReturning = (token: string) =>+ vi.fn(async () => ({+ ok: true,+ json: async () => ({ token })+ })) as unknown as typeof fetch;++describe("createSelfHostedTokenProvider", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ test("exchanges once and serves the cached token until near expiry", async () => {+ const fetchMock = mockFetchReturning(makeJwt(nowSeconds() + 3600));+ vi.stubGlobal("fetch", fetchMock);+ const provider = createSelfHostedTokenProvider(LICENSE_KEY, { serverUrl: SERVER_URL });++ const first = await provider.getToken();+ const second = await provider.getToken();++ expect(first).toBe(second);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ // Posts the key to the token endpoint as X-API-KEY.+ const [url, init] = (fetchMock as unknown as ReturnType<typeof vi.fn>).mock.calls[0] as [URL, RequestInit];+ expect(url.toString()).toBe(`${SERVER_URL}/api/auth/v1/license-login`);+ expect((init.headers as Record<string, string>)["X-API-KEY"]).toBe(LICENSE_KEY);+ });++ test("re-exchanges after invalidate()", async () => {+ const fetchMock = mockFetchReturning(makeJwt(nowSeconds() + 3600));+ vi.stubGlobal("fetch", fetchMock);+ const provider = createSelfHostedTokenProvider(LICENSE_KEY, { serverUrl: SERVER_URL });++ await provider.getToken();+ provider.invalidate();+ await provider.getToken();++ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ test("re-exchanges when the cached token is within the expiry margin", async () => {+ // exp only 30s out (< 60s margin), so every read is treated as expired.+ const fetchMock = mockFetchReturning(makeJwt(nowSeconds() + 30));+ vi.stubGlobal("fetch", fetchMock);+ const provider = createSelfHostedTokenProvider(LICENSE_KEY, { serverUrl: SERVER_URL });++ await provider.getToken();+ await provider.getToken();++ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ test("single-flights concurrent exchanges", async () => {+ let resolveFetch: (value: { ok: boolean; json: () => Promise<{ token: string }> }) => void = () => {};+ const fetchMock = vi.fn(+ () =>+ new Promise((resolve) => {+ resolveFetch = resolve;+ })+ ) as unknown as typeof fetch;+ vi.stubGlobal("fetch", fetchMock);+ const provider = createSelfHostedTokenProvider(LICENSE_KEY, { serverUrl: SERVER_URL });++ const token = makeJwt(nowSeconds() + 3600);+ const [a, b] = await Promise.all([+ (async () => {+ const p = provider.getToken();+ resolveFetch({ ok: true, json: async () => ({ token }) });+ return p;+ })(),+ provider.getToken()+ ]);++ expect(a).toBe(token);+ expect(b).toBe(token);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ test("throws when the token endpoint returns an error", async () => {+ const fetchMock = vi.fn(async () => ({+ ok: false,+ status: 401,+ text: async () => "unauthorized"+ })) as unknown as typeof fetch;+ vi.stubGlobal("fetch", fetchMock);+ const provider = createSelfHostedTokenProvider(LICENSE_KEY, { serverUrl: SERVER_URL });++ await expect(provider.getToken()).rejects.toThrow(/token exchange failed/);+ });+});diff --git a/backend/src/services/license-client/license-token-provider.ts b/backend/src/services/license-client/license-token-provider.tsnew file mode 100644index 0000000000..e5d81fd915--- /dev/null+++ b/backend/src/services/license-client/license-token-provider.ts@@ -0,0 +1,95 @@+import { logger } from "@app/lib/logger";++export type TLicenseTokenProvider = {+ // Exchanges the license key for a JWT (cached until near expiry) and returns it as a bearer.+ getToken: () => Promise<string>;+ // Drops the cached token so the next getToken re-exchanges (used to recover from a mid-flight 401).+ invalidate: () => void;+};++// Both self-hosted license key formats (legacy and infisical_lk_) authenticate the same way: POST the+// key to the license server's token endpoint and use the returned short-lived JWT as a bearer. The+// endpoint lives on LICENSE_SERVER_URL (the same base the v1 on-prem login uses), not the v2 API base.+const LICENSE_LOGIN_PATH = "/api/auth/v1/license-login";++// Refresh this many seconds before the JWT's exp so an in-flight request never carries an expired token.+const EXPIRY_MARGIN_SECONDS = 60;++// Fallback cache lifetime when the token carries no readable exp — short enough to re-exchange often,+// long enough to avoid a login per request.+const FALLBACK_TTL_SECONDS = 5 * 60;++// Read exp (unix seconds) from a JWT without verifying it — the license server verifies the signature;+// we only need the expiry to schedule a refresh. Returns null when exp is missing/unreadable.+const readJwtExp = (token: string): number | null => {+ const segments = token.split(".");+ if (segments.length !== 3) {+ return null;+ }+ try {+ const payload = JSON.parse(Buffer.from(segments[1], "base64url").toString("utf8")) as { exp?: number };+ return typeof payload.exp === "number" ? payload.exp : null;+ } catch {+ return null;+ }+};++export const createSelfHostedTokenProvider = (+ licenseKey: string,+ opts: { serverUrl: string }+): TLicenseTokenProvider => {+ let cachedToken: string | null = null;+ let expiresAtSeconds = 0;+ // Single-flight: concurrent callers on an expired token share one exchange instead of stampeding.+ let pending: Promise<string> | null = null;++ const exchange = async (): Promise<string> => {+ const url = new URL(LICENSE_LOGIN_PATH, opts.serverUrl);+ const res = await fetch(url, {+ method: "POST",+ headers: { "X-API-KEY": licenseKey, "Content-Type": "application/json" },+ body: "{}",+ redirect: "manual"+ });+ if (!res.ok) {+ const detail = await res.text().catch(() => "");+ throw new Error(`license-client: token exchange failed [status=${res.status}] ${detail}`.trim());+ }+ const body = (await res.json()) as { token?: string };+ if (!body.token) {+ throw new Error("license-client: token exchange returned no token");+ }+ return body.token;+ };++ const getToken = async (): Promise<string> => {+ const nowSeconds = Math.floor(Date.now() / 1000);+ if (cachedToken && nowSeconds < expiresAtSeconds - EXPIRY_MARGIN_SECONDS) {+ return cachedToken;+ }+ if (pending) {+ return pending;+ }+ pending = (async () => {+ try {+ const token = await exchange();+ cachedToken = token;+ expiresAtSeconds = readJwtExp(token) ?? nowSeconds + FALLBACK_TTL_SECONDS;+ return token;+ } catch (error) {+ logger.error(error, "license-client: failed to obtain a license token");+ throw error;+ } finally {+ pending = null;+ }+ })();+ return pending;+ };++ const invalidate = () => {+ cachedToken = null;+ expiresAtSeconds = 0;+ };++ return { getToken, invalidate };+};diff --git a/backend/src/services/license-client/usage/usage-counters.ts b/backend/src/services/license-client/usage/usage-counters.tsindex 1efeea9d4b..51b50da64f 100644--- a/backend/src/services/license-client/usage/usage-counters.ts+++ b/backend/src/services/license-client/usage/usage-counters.ts@@ -41,7 +41,7 @@ export const buildMeteredFeatures = ({usageCounterDAL,isCloud}: TBuildMeteredFeaturesDep): TMeteredFeature[] => [- { feature: IdentitiesMeter, count: (orgId) => licenseDAL.countOrgUsersAndIdentities(orgId) },+ { feature: IdentitiesMeter, count: (orgId) => licenseDAL.countOrgUsersAndIdentities(isCloud ? orgId : null) },{ feature: InternalCas, count: (orgId) => usageCounterDAL.countInternalCas(orgId) },{ feature: ActiveCerts, count: (orgId) => usageCounterDAL.countActiveCerts(orgId) },{diff --git a/backend/src/services/license-client/usage/usage-event-queue.ts b/backend/src/services/license-client/usage/usage-event-queue.tsindex 80b63c33e1..0255f4bc19 100644--- a/backend/src/services/license-client/usage/usage-event-queue.ts+++ b/backend/src/services/license-client/usage/usage-event-queue.ts@@ -3,7 +3,6 @@ import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";import { logger } from "@app/lib/logger";import { QueueName, TQueueServiceFactory } from "@app/queue";-import { TOrgDALFactory } from "@app/services/org/org-dal";import { ActiveCerts, InternalCas } from "../features";import { TMeteredFeature } from "./usage-counters";@@ -13,16 +12,22 @@ 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.+const SELF_HOSTED_LICENSE_ORG_ID = "self-hosted";+type TUsageEventQueueFactoryDep = {queueService: Pick<TQueueServiceFactory, "start">;cronJob: TCronJobFactory;keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;- orgDAL: Pick<TOrgDALFactory, "find">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;meteredFeatures: TMeteredFeature[];usageReporter: TUsageReporter | null;isCloud: boolean;+ // Offline (air-gapped) licenses can't reach the license server, so the true-up cron stays disabled.+ isOffline: boolean;source: string;};@@ -30,12 +35,12 @@ export const usageEventQueueFactory = ({queueService,cronJob,keyStore,- orgDAL,licenseService,usageMeteringService,meteredFeatures,usageReporter,isCloud,+ isOffline,source}: TUsageEventQueueFactoryDep) => {const featureByKey = new Map(meteredFeatures.map((m) => [m.feature.key, m]));@@ -58,6 +63,12 @@ export const usageEventQueueFactory = ({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;+try {const metered = featureByKey.get(dimensionKey);if (!metered) {@@ -65,9 +76,9 @@ export const usageEventQueueFactory = ({return;}- const value = await metered.count(orgId);+ const value = await metered.count(reportOrgId);- const lastReportedKey = KeyStorePrefixes.LicenseUsageLastReported(orgId, dimensionKey);+ const lastReportedKey = KeyStorePrefixes.LicenseUsageLastReported(reportOrgId, dimensionKey);const lastReported = await keyStore.getItem(lastReportedKey);if (lastReported !== null && Number(lastReported) === value) {return;@@ -78,12 +89,12 @@ export const usageEventQueueFactory = ({// dimension, so swallow it (no retry, don't record it as reported). Any other failure rethrows to// the outer handler so the job retries.try {- await usageReporter.reportSnapshots(orgId, [+ await usageReporter.reportSnapshots(reportOrgId, [{dimension_key: dimensionKey,value,observed_at: observedAt.toISOString(),- idempotency_key: `${source}:${orgId}:${dimensionKey}:${observedAt.getTime()}`,+ idempotency_key: `${source}:${reportOrgId}:${dimensionKey}:${observedAt.getTime()}`,source}]);@@ -91,7 +102,7 @@ export const usageEventQueueFactory = ({if (error instanceof UsageReportError) {if (error.status === 404 && error.serverMessage.includes("license not found")) {logger.info(- `usage-event-queue: license not found, skipping [orgId=${orgId}] [dimensionKey=${dimensionKey}]`+ `usage-event-queue: license not found, skipping [orgId=${reportOrgId}] [dimensionKey=${dimensionKey}]`);return;}@@ -100,7 +111,7 @@ export const usageEventQueueFactory = ({error.serverMessage.includes("not priced by any active product on this license")) {logger.info(- `usage-event-queue: dimension not priced on this license, skipping [orgId=${orgId}] [dimensionKey=${dimensionKey}]`+ `usage-event-queue: dimension not priced on this license, skipping [orgId=${reportOrgId}] [dimensionKey=${dimensionKey}]`);return;}@@ -109,40 +120,29 @@ export const usageEventQueueFactory = ({}logger.info(- `usage-event-queue: reported usage event [orgId=${orgId}] [dimensionKey=${dimensionKey}] [value=${value}]`+ `usage-event-queue: reported usage event [orgId=${reportOrgId}] [dimensionKey=${dimensionKey}] [value=${value}]`);await keyStore.setItemWithExpiry(lastReportedKey, KeyStoreTtls.LicenseUsageLastReportedInSeconds, String(value));} catch (error) {logger.error(error,- `usage-event-queue: failed to handle usage event [orgId=${orgId}] [dimensionKey=${dimensionKey}]`+ `usage-event-queue: failed to handle usage event [orgId=${reportOrgId}] [dimensionKey=${dimensionKey}]`);throw error;}};- // Self-hosted true-up: online instances also report event-driven, so this is a periodic backstop- // for cap visibility and renewal. Cloud is event-driven only.- const flushAllOrgs = async () => {+ // Self-hosted true-up: a daily backstop for cap visibility and renewal on top of event-driven+ // reporting. Self-hosted usage is metered and reported once at the instance identity, so this just+ // re-emits each meter once (no per-org fan-out); handleUsageEvent counts instance-wide and dedups.+ // Cloud is event-driven only.+ const flushInstanceUsage = async () => {if (!usageReporter) {return;}- // Page through orgs so a large self-hosted deployment doesn't materialize the whole table.- const batchSize = 500;- let offset = 0;- for (;;) {- // eslint-disable-next-line no-await-in-loop- const orgs = await orgDAL.find({}, { limit: batchSize, offset });- for (const org of orgs) {- for (const metered of meteredFeatures) {- usageMeteringService.emit(org.id, metered.feature.key);- }- }- if (orgs.length < batchSize) {- break;- }- offset += batchSize;+ for (const metered of meteredFeatures) {+ usageMeteringService.emit(SELF_HOSTED_LICENSE_ORG_ID, metered.feature.key);}};@@ -161,14 +161,14 @@ export const usageEventQueueFactory = ({const init = () => {startWorker();- cronJob.register({- name: CronJobName.LicenseUsageFlush,- pattern: "*/30 * * * *",- runHashTtlS: 60 * 60,- enabled: !isCloud,- handler: flushAllOrgs- });+ // cronJob.register({+ // name: CronJobName.LicenseUsageFlush,+ // pattern: "0 0 * * *", // daily at midnight UTC+ // runHashTtlS: 60 * 60,+ // enabled: !isCloud && !isOffline,+ // handler: flushInstanceUsage+ // });};- return { init, handleUsageEvent, flushAllOrgs };+ return { init, handleUsageEvent, flushInstanceUsage };};diff --git a/backend/src/services/license-client/usage/usage-metering.test.ts b/backend/src/services/license-client/usage/usage-metering.test.tsindex 662047c499..486f5c5ea8 100644--- a/backend/src/services/license-client/usage/usage-metering.test.ts+++ b/backend/src/services/license-client/usage/usage-metering.test.ts@@ -295,8 +295,8 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {overrides: {usageReporter?: unknown;keyStore?: ReturnType<typeof createFakeKeyStore>;- orgFind?: unknown;isCloud?: boolean;+ isOffline?: boolean;getPlan?: (orgId: string) => Promise<{ slug: string | null }>;} = {}) => {@@ -304,22 +304,22 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {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 register = vi.fn();// Default to a billable plan so the cloud slug gate is a pass-through unless a test overrides it.const getPlan = vi.fn(overrides.getPlan ?? (async () => ({ slug: "pro" })));const queue = usageEventQueueFactory({queueService: { start: vi.fn() },- cronJob: { register: vi.fn(), start: vi.fn(), stop: vi.fn() } as never,+ cronJob: { register, start: vi.fn(), stop: vi.fn() } as never,keyStore,- orgDAL: { find } as never,licenseService: { getPlan } as never,usageMeteringService: { emit },meteredFeatures,usageReporter: usageReporter as never,isCloud: overrides.isCloud ?? false,+ isOffline: overrides.isOffline ?? false,source: "test-region"});- return { queue, reportSnapshots, keyStore, emit, find, getPlan };+ return { queue, reportSnapshots, keyStore, emit, getPlan, register };};beforeEach(() => {@@ -332,8 +332,8 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {expect(meteredFeatures[0].count).not.toHaveBeenCalled();});- test("reports a snapshot and records the value on first observation", async () => {- const { queue, reportSnapshots, keyStore } = buildQueue();+ test("reports a snapshot and records the value on first observation (cloud, per org)", async () => {+ const { queue, reportSnapshots, keyStore } = buildQueue({ isCloud: true });await queue.handleUsageEvent(ORG_ID, IdentitiesMeter.key, new Date());expect(reportSnapshots).toHaveBeenCalledTimes(1);@@ -347,6 +347,18 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {expect(keyStore.store.get(`license-usage-last-reported-${ORG_ID}-${IdentitiesMeter.key}`)).toBe("42");});+ test("self-hosted reports at the instance ('self-hosted') identity, not the triggering org", async () => {+ const { queue, reportSnapshots, keyStore } = buildQueue({ isCloud: false });+ await queue.handleUsageEvent(ORG_ID, IdentitiesMeter.key, new Date());++ expect(reportSnapshots).toHaveBeenCalledTimes(1);+ const [orgId] = reportSnapshots.mock.calls[0] as unknown as [string, TUsageSnapshot[]];+ expect(orgId).toBe("self-hosted");+ // Deduped under the instance identity, not the org that triggered the event.+ expect(keyStore.store.get(`license-usage-last-reported-self-hosted-${IdentitiesMeter.key}`)).toBe("42");+ expect(keyStore.store.get(`license-usage-last-reported-${ORG_ID}-${IdentitiesMeter.key}`)).toBeUndefined();+ });+test("on cloud, skips a free org (null slug) before counting to avoid a 404", async () => {const { queue, reportSnapshots, getPlan } = buildQueue({isCloud: true,@@ -390,7 +402,7 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {test("skips the report when the count is unchanged", async () => {const keyStore = createFakeKeyStore();keyStore.store.set(`license-usage-last-reported-${ORG_ID}-${IdentitiesMeter.key}`, "42");- const { queue, reportSnapshots } = buildQueue({ keyStore });+ const { queue, reportSnapshots } = buildQueue({ keyStore, isCloud: true });await queue.handleUsageEvent(ORG_ID, IdentitiesMeter.key, new Date());expect(reportSnapshots).not.toHaveBeenCalled();@@ -406,7 +418,7 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {const reportSnapshots = vi.fn(async () => {throw new UsageReportError(422, "dimension X is not priced by any active product on this license");});- const { queue, keyStore } = buildQueue({ usageReporter: { reportSnapshots } });+ const { queue, keyStore } = buildQueue({ usageReporter: { reportSnapshots }, isCloud: true });// Does not throw (so the job is not retried).await expect(queue.handleUsageEvent(ORG_ID, IdentitiesMeter.key, new Date())).resolves.toBeUndefined();@@ -425,26 +437,33 @@ describe("usageEventQueue.handleUsageEvent (worker)", () => {);});- 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" }];- const orgFind = vi.fn().mockResolvedValueOnce(fullPage).mockResolvedValueOnce(lastPage);- const { queue, emit } = buildQueue({ orgFind });+ test("flushInstanceUsage emits each meter once at the instance identity (no per-org fan-out)", async () => {+ const { queue, emit } = buildQueue();- await queue.flushAllOrgs();+ await queue.flushInstanceUsage();- expect(orgFind).toHaveBeenCalledTimes(2); // stops after the partial page- expect(orgFind).toHaveBeenNthCalledWith(1, {}, { limit: 500, offset: 0 });- expect(orgFind).toHaveBeenNthCalledWith(2, {}, { limit: 500, offset: 500 });- expect(emit).toHaveBeenCalledTimes(501); // 501 orgs x 1 metered feature+ expect(emit).toHaveBeenCalledTimes(meteredFeatures.length); // one emit per meter, not per org+ expect(emit).toHaveBeenCalledWith("self-hosted", IdentitiesMeter.key);});- test("flushAllOrgs no-ops when the reporter is null", async () => {- const { queue, emit, find } = buildQueue({ usageReporter: null });- await queue.flushAllOrgs();- expect(find).not.toHaveBeenCalled();+ test("flushInstanceUsage no-ops when the reporter is null", async () => {+ const { queue, emit } = buildQueue({ usageReporter: null });+ await queue.flushInstanceUsage();expect(emit).not.toHaveBeenCalled();});++ test("registers the true-up cron enabled for self-hosted, disabled for cloud/offline", async () => {+ const enabledFor = (opts: { isCloud?: boolean; isOffline?: boolean }) => {+ const { queue, register } = buildQueue(opts);+ queue.init();+ const [{ enabled }] = register.mock.calls[0] as unknown as [{ enabled: boolean }];+ return enabled;+ };++ expect(enabledFor({})).toBe(true); // self-hosted online+ expect(enabledFor({ isCloud: true })).toBe(false);+ expect(enabledFor({ isOffline: true })).toBe(false);+ });});// Demonstrates how a metered create path would gate on the new framework once enforcement is wireddiff --git a/backend/src/services/license-client/usage/usage-reporter.ts b/backend/src/services/license-client/usage/usage-reporter.tsindex 9535142f47..c06cb7f2f5 100644--- a/backend/src/services/license-client/usage/usage-reporter.ts+++ b/backend/src/services/license-client/usage/usage-reporter.ts@@ -2,6 +2,7 @@ import { TEnvConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";import { mintServiceToken } from "../license-client-backends";+import { createSelfHostedTokenProvider } from "../license-token-provider";export type TUsageSnapshot = {dimension_key: string;@@ -30,9 +31,9 @@ export class UsageReportError extends Error {}}-// getBearerToken is called per request so a cloud reporter can mint a fresh short-lived JWT each time-// (a self-hosted reporter just returns its static license key).-export const usageReporterFactory = (serverUrl: string, getBearerToken: () => string): TUsageReporter => ({+// getBearerToken is called per request so a cloud reporter can mint a fresh short-lived JWT each time,+// while a self-hosted reporter exchanges its license key for a cached JWT at the token endpoint.+export const usageReporterFactory = (serverUrl: string, getBearerToken: () => Promise<string>): TUsageReporter => ({reportSnapshots: async (orgId: string, snapshots: TUsageSnapshot[]) => {if (!snapshots.length) {return;@@ -41,7 +42,7 @@ export const usageReporterFactory = (serverUrl: string, getBearerToken: () => stconst url = new URL(`/v1/organizations/${encodeURIComponent(orgId)}/usage-snapshots`, serverUrl);const res = await fetch(url, {method: "POST",- headers: { Authorization: `Bearer ${getBearerToken()}`, "Content-Type": "application/json" },+ headers: { Authorization: `Bearer ${await getBearerToken()}`, "Content-Type": "application/json" },body: JSON.stringify({ snapshots }),redirect: "manual"});@@ -59,17 +60,19 @@ export const usageReporterFactory = (serverUrl: string, getBearerToken: () => st}});-// Mirrors SELF_HOSTED_V2_LICENSE_KEY_PREFIX in ee/license-fns; inlined to avoid a services -> ee import.-const SELF_HOSTED_V2_LICENSE_KEY_PREFIX = "infisical_lk_";-// Returns null when the v2 license server is disabled or unconfigured, which keeps usage reporting-// inert. A self-hosted v2 license reports with its own license key as the bearer; cloud mints a-// short-lived RS256 service JWT signed with the service key (the same scheme the rest of the v2-// client uses), so the raw signing key is never sent over the wire.+// inert. A self-hosted v2 license exchanges its key for a short-lived JWT at the token endpoint (on+// LICENSE_SERVER_URL) and reports with that bearer; cloud mints a short-lived RS256 service JWT signed+// with the service key (the same scheme the rest of the v2 client uses). The raw key/signing key is+// never sent as the bearer.export const buildUsageReporter = (envConfig: Pick<TEnvConfig,- "LICENSE_SERVER_V2_MODE" | "LICENSE_SERVER_V2_URL" | "LICENSE_SERVER_V2_SERVICE_KEY" | "LICENSE_KEY"+ | "LICENSE_SERVER_V2_MODE"+ | "LICENSE_SERVER_V2_URL"+ | "LICENSE_SERVER_V2_SERVICE_KEY"+ | "LICENSE_SERVER_URL"+ | "LICENSE_KEY">): TUsageReporter | null => {if (envConfig.LICENSE_SERVER_V2_MODE === "off") {@@ -95,10 +98,16 @@ export const buildUsageReporter = (return null;}- // Self-hosted: authenticate with the raw license key as the bearer.+ // Self-hosted (any license key format): exchange the key for a short-lived JWT at the token endpoint+ // and use that. Cloud sets no LICENSE_KEY, so it falls through to the service-JWT path below.const licenseKey = envConfig.LICENSE_KEY;- if (licenseKey?.startsWith(SELF_HOSTED_V2_LICENSE_KEY_PREFIX)) {- return usageReporterFactory(serverUrl, () => licenseKey);+ if (licenseKey) {+ if (!envConfig.LICENSE_SERVER_URL) {+ logger.warn("usage-reporter: self-hosted key set but LICENSE_SERVER_URL is missing; usage reporting disabled");+ return null;+ }+ const tokenProvider = createSelfHostedTokenProvider(licenseKey, { serverUrl: envConfig.LICENSE_SERVER_URL });+ return usageReporterFactory(serverUrl, () => tokenProvider.getToken());}// Cloud: mint a fresh service JWT per request signed with the service key (an RSA private key).@@ -109,5 +118,5 @@ export const buildUsageReporter = ();return null;}- return usageReporterFactory(serverUrl, () => mintServiceToken(serviceKey));+ return usageReporterFactory(serverUrl, () => Promise.resolve(mintServiceToken(serviceKey)));};diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.tsindex ce346cf68d..106e45a7a6 100644--- a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts@@ -192,7 +192,7 @@ export const commitSavingsNudge = (// Capitalize a plan tier ("pro" -> "Pro") for the badge beside a product's name.// hardcoded legacy for nowexport const tierLabel = (tier: string): string => {- const stripped = tier.replace("legacy_", "");+ const stripped = tier.replace("legacy_", "").replace(/_/g, " ");return stripped.charAt(0).toUpperCase() + stripped.slice(1);};