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: added declare usage in trial and marker on cache
=79e1f9cc07bf
diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.tsindex a617afed1b..ed277060ca 100644--- a/backend/src/ee/services/license-v2/license-v2-service.ts+++ b/backend/src/ee/services/license-v2/license-v2-service.ts@@ -53,7 +53,7 @@ type TLicenseV2ServiceFactoryDep = {licenseClient: Pick<TLicenseClientFactory,| "getEntitlements"- | "invalidateEntitlements"+ | "markEntitlementsStale"| "refreshEntitlements"| "getCatalog"| "getSubscription"@@ -866,7 +866,7 @@ export const licenseV2ServiceFactory = ({});if (result.outcome === "subscription_updated") {- await licenseClient.invalidateEntitlements(orgId);+ await licenseClient.markEntitlementsStale(orgId);return { outcome: "subscription_updated" as const, subscriptionId: result.subscriptionId };}@@ -953,7 +953,7 @@ export const licenseV2ServiceFactory = ({productId,dimensions: changes.map((change) => ({ dimensionKey: change.dimensionKey, quantity: change.quantity }))});- await licenseClient.invalidateEntitlements(orgId);+ await licenseClient.markEntitlementsStale(orgId);if (result.outcome === "checkout_created") {if (!result.checkoutUrl) {throw new InternalServerError({ message: "Checkout session did not return a URL" });@@ -970,15 +970,24 @@ export const licenseV2ServiceFactory = ({// The trial has no Stripe customer yet, so the server creates one from the org's own name + the// authenticated user's email; neither is client-supplied.const organization = await orgDAL.findById(orgId);++ // Seed the trial with the org's present usage so it opens showing current quantities, exactly as+ // checkout does. A trial converts to a monthly usage-based line, so derive declaredUsage at the+ // monthly cadence; skip it silently if the product/plan can't be resolved (server floors it).+ const catalog = await licenseClient.getCatalog(orgId);+ const product = catalog?.products.find((candidate) => candidate.id === productId);+ const resolved = product ? await buildProductLineItem(product, "monthly", orgId, plan) : null;+const result = await licenseClient.startTrial(orgId, {productKey: productId,planKey: plan,email,name: organization?.name,+ declaredUsage: resolved?.declaredUsage,// The trial's card-setup checkout redirects here; built server-side from SITE_URL like checkout.returnUrl: buildReturnUrl(orgId)});- await licenseClient.invalidateEntitlements(orgId);+ await licenseClient.markEntitlementsStale(orgId);return { outcome: result.outcome, cardSetupUrl: result.cardSetupUrl };};@@ -987,7 +996,7 @@ export const licenseV2ServiceFactory = ({const cancelTrial = async ({ orgId, actor, productId }: TCancelBillingV2TrialDTO) => {await ensureManageBilling(orgId, actor);const result = await licenseClient.cancelTrial(orgId, { productKey: productId });- await licenseClient.invalidateEntitlements(orgId);+ await licenseClient.markEntitlementsStale(orgId);return { outcome: result.outcome };};@@ -996,21 +1005,21 @@ export const licenseV2ServiceFactory = ({const removeProduct = async ({ orgId, actor, productId }: TRemoveBillingV2ProductDTO) => {await ensureManageBilling(orgId, actor);const result = await licenseClient.removeProduct(orgId, productId);- await licenseClient.invalidateEntitlements(orgId);+ await licenseClient.markEntitlementsStale(orgId);return { subscriptionId: result.subscriptionId };};const cancelSubscription = async ({ orgId, actor }: TBillingV2SubscriptionLifecycleDTO) => {await ensureManageBilling(orgId, actor);const result = await licenseClient.cancelSubscription(orgId);- await licenseClient.invalidateEntitlements(orgId);+ await licenseClient.markEntitlementsStale(orgId);return { subscriptionId: result.subscriptionId };};const resumeSubscription = async ({ orgId, actor }: TBillingV2SubscriptionLifecycleDTO) => {await ensureManageBilling(orgId, actor);const result = await licenseClient.resumeSubscription(orgId);- await licenseClient.invalidateEntitlements(orgId);+ await licenseClient.markEntitlementsStale(orgId);return { subscriptionId: result.subscriptionId };};diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.tsindex c88756aa85..27fc81f433 100644--- a/backend/src/ee/services/license/license-service.ts+++ b/backend/src/ee/services/license/license-service.ts@@ -69,7 +69,7 @@ type TLicenseServiceFactoryDep = {orgDAL: Pick<TOrgDALFactory, "findRootOrgDetails" | "countAllOrgMembers" | "findById">;permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;licenseDAL: TLicenseDALFactory;- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "deleteItem">;+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "setItemWithExpiryNX" | "getItem" | "deleteItem">;projectDAL: TProjectDALFactory;licenseClient?: Pick<TLicenseClientFactory, "getEntitlements" | "getSubscription" | "refreshEntitlements">;licenseDualRead?: Pick<TDualReadServiceFactory, "compareInBackground">;@@ -292,12 +292,44 @@ export const licenseServiceFactory = ({}};+ // Stale-while-revalidate refresh fired (fire-and-forget) when a cache hit carries the passThrough+ // marker a billing mutation set. Single-flight via a self-expiring NX lock, which doubles as a+ // throttle (at most one refresh per org per lock window). Drops the projected plan cache and rebuilds+ // it via getPlan, which fetches the (now reconciled) entitlements fresh from the license server. Never+ // throws — it runs detached from the request.+ const revalidatePlanInBackground = async (orgId: string) => {+ try {+ const acquired = await keyStore.setItemWithExpiryNX(+ KeyStorePrefixes.LicenseCacheRevalidateLock(orgId),+ KeyStoreTtls.LicenseCacheRevalidateLockInSeconds,+ "1"+ );+ if (acquired !== "OK") {+ return;+ }++ await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));+ // eslint-disable-next-line @typescript-eslint/no-use-before-define -- mutual recursion; getPlan rebuilds the plan cache+ await getPlan(orgId);+ } catch (error) {+ logger.error(error, `getPlan: background revalidation failed [orgId=${orgId}]`);+ }+ };+const getPlan = async (orgId: string, projectId?: string) => {logger.info(`getPlan: attempting to fetch plan for [orgId=${orgId}] [projectId=${projectId}]`);try {if (instanceType === InstanceType.Cloud) {- const cachedPlan = await keyStore.getItem(KeyStorePrefixes.LicenseCloudPlan(orgId));+ const [cachedPlan, passThrough] = await Promise.all([+ keyStore.getItem(KeyStorePrefixes.LicenseCloudPlan(orgId)),+ keyStore.getItem(KeyStorePrefixes.LicenseCachePassThrough(orgId))+ ]);if (cachedPlan) {+ // A billing mutation flagged this org: serve the cached plan now but kick a background refresh+ // so the cache converges as the license server reconciles, instead of waiting out the TTL.+ if (passThrough) {+ void revalidatePlanInBackground(orgId);+ }logger.info(`getPlan: plan fetched from cache [orgId=${orgId}] [projectId=${projectId}]`);return JSON.parse(cachedPlan) as TFeatureSet;}diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 709e435365..088f78f8a4 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -150,8 +150,10 @@ export const KeyStorePrefixes = {SecretManagerCachePattern: "secret-manager:*",AuditLogMigrationAlert: "audit-log-migration-alert-last-row-count",LicenseCloudPlan: (orgId: string) => `infisical-cloud-plan-${orgId}` as const,- LicenseEntitlements: (orgId: string) => `license-entitlements-${orgId}` as const,- LicenseEntitlementsIdentitySynced: (orgId: string) => `license-entitlements-identity-synced-${orgId}` as const,+ // Set after a billing mutation to flag the org's plan cache for stale-while-revalidate reads.+ LicenseCachePassThrough: (orgId: string) => `license-cache-passthrough-${orgId}` as const,+ // Single-flight guard so only one background revalidation runs per org per lock window.+ LicenseCacheRevalidateLock: (orgId: string) => `license-cache-revalidate-lock-${orgId}` as const,LicenseUsageLastReported: (orgId: string, featureKey: string) =>`license-usage-last-reported-${orgId}-${featureKey}` as const,IdentityLockoutState: (identityId: string, authMethod: string, slug: string) =>@@ -196,9 +198,12 @@ export const KeyStoreTtls = {UpdateCheckLatestVersionInSeconds: 1209600, // 14 days (survives one missed weekly check)InvalidatingCacheInSeconds: 1800, // 30 minutes max lock for cache invalidation jobAuditLogMigrationAlertInSeconds: 604800, // 7 days- LicenseCloudPlanInSeconds: 300, // 5 minutes+ LicenseCloudPlanInSeconds: 900, // 15 minutesPamDefaultProjectInSeconds: 300, // 5 minutes- LicenseEntitlementsInSeconds: 1800, // 30 minutes+ // How long reads stay in stale-while-revalidate mode after a billing mutation (covers Stripe reconciliation).+ LicenseCachePassThroughInSeconds: 180, // 3 minutes+ // Throttle window for the single-flight background revalidation.+ LicenseCacheRevalidateLockInSeconds: 10,LicenseUsageLastReportedInSeconds: 604800, // 7 daysAiMcpEndpointOAuthFlowInSeconds: 300, // 5 minutesOauthAuthorizationCodeInSeconds: 600, // 10 minutesdiff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.tsindex c2066dd442..5342d40eab 100644--- a/backend/src/services/license-client/license-client-backends.ts+++ b/backend/src/services/license-client/license-client-backends.ts@@ -298,6 +298,7 @@ export const licenseServerBackend = (plan_key: payload.planKey,email: payload.email,name: payload.name,+ declaredUsage: payload.declaredUsage,returnUrl: payload.returnUrl}),redirect: "manual"diff --git a/backend/src/services/license-client/license-client-cache.ts b/backend/src/services/license-client/license-client-cache.tsindex f7dbea3ed2..13536e0bdc 100644--- a/backend/src/services/license-client/license-client-cache.ts+++ b/backend/src/services/license-client/license-client-cache.ts@@ -1,5 +1,4 @@import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";-import { withCache } from "@app/lib/cache/with-cache";import { logger } from "@app/lib/logger";import { TEntitlementOrg, TEntitlementsResponse, TLicenseClientBackend } from "./license-client-types";@@ -12,62 +11,47 @@ type TEntitlementResolverDep = {export type TEntitlementResolver = ReturnType<typeof entitlementResolverFactory>;export const entitlementResolverFactory = ({ keyStore, backend }: TEntitlementResolverDep) => {- const ttlSeconds = KeyStoreTtls.LicenseEntitlementsInSeconds;- const entitlementsCacheKey = (orgId: string) => KeyStorePrefixes.LicenseEntitlements(orgId);- const identitySyncedKey = (orgId: string) => KeyStorePrefixes.LicenseEntitlementsIdentitySynced(orgId);-- // The license server learns an org's name/slug from whatever identity a request carries. Entitlement- // reads are cached per org and most callers (feature checks) send no identity, so a cached read would- // usually answer without reaching the server and the name/slug would never get there. So the first- // identity-carrying read in a cache window is sent uncached (delivering the identity); this marker then- // records that the window's identity has been delivered so later reads can serve from the cache again.- const identityNeedsSync = async (org: TEntitlementOrg): Promise<boolean> => {- if (!org.name && !org.slug) {- return false;- }- const alreadySynced = await keyStore.getItem(identitySyncedKey(org.id));- return !alreadySynced;- };-- // One uncached read that carries the org's identity to the server, then primes the entitlement cache- // with the response and marks this window's identity as delivered.- const fetchForwardingIdentity = async (org: TEntitlementOrg): Promise<TEntitlementsResponse> => {- const entitlements = await backend.fetchEntitlements(org);- await keyStore.setItemWithExpiry(entitlementsCacheKey(org.id), ttlSeconds, JSON.stringify(entitlements));- await keyStore.setItemWithExpiry(identitySyncedKey(org.id), ttlSeconds, "1");- return entitlements;- };-- // Returns null on total failure so the caller falls back to the feature's declared fallback.+ // Entitlements are not cached here: the only hot reader is licenseService.getPlan, which caches its+ // projection in LicenseCloudPlan and so only reaches this on an L1 miss. The remaining callers+ // (billing overview, self-hosted sync) are low frequency and want fresh reads, so a direct fetch is+ // simpler and avoids a second cache to keep coherent. Returns null on failure so the caller falls back+ // to the feature's declared default. The org's name/slug ride along on the query params, keeping the+ // license server's copy current.const getEntitlements = async (org: TEntitlementOrg): Promise<TEntitlementsResponse | null> => {try {- if (await identityNeedsSync(org)) {- return await fetchForwardingIdentity(org);- }-- return await withCache({- keyStore,- key: entitlementsCacheKey(org.id),- ttlSeconds,- fetcher: () => backend.fetchEntitlements(org)- });+ return await backend.fetchEntitlements(org);} catch (error) {logger.error(error, `license-client: failed to resolve entitlements [orgId=${org.id}]`);return null;}};- // Drop the cached entitlements so the next read reflects a just-committed subscription change- // instead of waiting out the 30-minute TTL. The license server reconciles asynchronously via- // its Stripe webhook, so a stale read here is what otherwise makes a removed product linger.+ // Flag the org's license caches for stale-while-revalidate instead of dropping them. After a billing+ // mutation the license server reconciles asynchronously (Stripe webhook), so an immediate hard bust+ // would just re-cache the pre-reconciliation value for a full TTL. With the marker set, reads keep+ // serving the cached value while a background refresh converges the cache once reconciliation lands.+ const markPassThrough = async (orgId: string): Promise<void> => {+ try {+ await keyStore.setItemWithExpiry(+ KeyStorePrefixes.LicenseCachePassThrough(orgId),+ KeyStoreTtls.LicenseCachePassThroughInSeconds,+ "1"+ );+ } catch (error) {+ logger.error(error, `license-client: failed to mark entitlements for revalidation [orgId=${orgId}]`);+ }+ };++ // Hard-drop the projected plan cache so the next read reflects a just-committed change instead of+ // waiting out the TTL. Used by the explicit refresh path (refreshEntitlements); billing mutations use+ // markPassThrough for stale-while-revalidate instead.const invalidateEntitlements = async (orgId: string): Promise<void> => {try {await keyStore.deleteItem(KeyStorePrefixes.LicenseCloudPlan(orgId));- await keyStore.deleteItem(KeyStorePrefixes.LicenseEntitlements(orgId));} catch (error) {logger.error(error, `license-client: failed to invalidate entitlements [orgId=${orgId}]`);}};- return { getEntitlements, invalidateEntitlements };+ return { getEntitlements, invalidateEntitlements, markPassThrough };};diff --git a/backend/src/services/license-client/license-client-types.ts b/backend/src/services/license-client/license-client-types.tsindex 3a8db605de..03b4e983d3 100644--- a/backend/src/services/license-client/license-client-types.ts+++ b/backend/src/services/license-client/license-client-types.ts@@ -407,6 +407,9 @@ export type TStartTrialPayload = {// A trial starts with no Stripe customer yet, so the server needs an email + org name to create one.email?: string;name?: string;+ // Present actual usage per per_resource dimension, so the trial opens with the org's current+ // quantities on display instead of zero (same shape checkout sends; the server floors omitted ones).+ declaredUsage?: Record<string, number>;returnUrl?: string;};diff --git a/backend/src/services/license-client/license-client.test.ts b/backend/src/services/license-client/license-client.test.tsindex ae9cb683bd..ba6b2b2f15 100644--- a/backend/src/services/license-client/license-client.test.ts+++ b/backend/src/services/license-client/license-client.test.ts@@ -62,7 +62,9 @@ const createStubBackend = (response: TEntitlementsResponse, opts: { fail?: boole};describe("entitlementResolverFactory", () => {- test("fetches once then serves subsequent reads from the cache", async () => {+ // Entitlements are no longer cached here — the hot reader (getPlan) caches its projection upstream —+ // so every read hits the backend directly.+ test("fetches from the backend on every read", async () => {const keyStore = createFakeKeyStore();const { backend, getCalls } = createStubBackend(makeEntitlements({ identities: { value: 100, source: "plan" } }));const resolver = entitlementResolverFactory({ keyStore, backend });@@ -72,7 +74,7 @@ describe("entitlementResolverFactory", () => {expect(getCalls()).toBe(1);await resolver.getEntitlements({ id: ORG_ID });- expect(getCalls()).toBe(1); // served from the cache+ expect(getCalls()).toBe(2); // no cache — fetched again});test("returns null when the server is unreachable", async () => {@@ -83,32 +85,13 @@ describe("entitlementResolverFactory", () => {expect(await resolver.getEntitlements({ id: ORG_ID })).toBeNull();});- test("forwards org identity to the backend even after an identity-less call seeded the cache", async () => {+ test("forwards the org identity to the backend so the license server stays current", async () => {const keyStore = createFakeKeyStore();- const { backend, getCalls, getOrgs } = createStubBackend(- makeEntitlements({ identities: { value: 100, source: "plan" } })- );+ const { backend, getOrgs } = createStubBackend(makeEntitlements({ identities: { value: 100, source: "plan" } }));const resolver = entitlementResolverFactory({ keyStore, backend });- await resolver.getEntitlements({ id: ORG_ID }); // feature-check style, identity-less- expect(getCalls()).toBe(1);- expect(getOrgs()[0]).toEqual({ id: ORG_ID });-- await resolver.getEntitlements({ id: ORG_ID, name: "Acme Corp", slug: "acme" });- expect(getCalls()).toBe(2); // bypassed the identity-less cache entry- expect(getOrgs()[1]).toEqual({ id: ORG_ID, name: "Acme Corp", slug: "acme" });- });-- 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 resolver = entitlementResolverFactory({ keyStore, backend });-- await resolver.getEntitlements({ id: ORG_ID, name: "Acme Corp", slug: "acme" });- expect(getCalls()).toBe(1);-await resolver.getEntitlements({ id: ORG_ID, name: "Acme Corp", slug: "acme" });- expect(getCalls()).toBe(1); // identity already synced, served from the cache+ expect(getOrgs()[0]).toEqual({ id: ORG_ID, name: "Acme Corp", slug: "acme" });});});diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.tsindex 2931af2635..9a4dfb203a 100644--- a/backend/src/services/license-client/license-client.ts+++ b/backend/src/services/license-client/license-client.ts@@ -95,6 +95,15 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFactawait resolver.invalidateEntitlements(orgId);};+ // Flag the org's license caches for stale-while-revalidate after a billing mutation instead of a hard+ // bust, so reads keep serving cached data while a background refresh converges once Stripe reconciles.+ const markEntitlementsStale = async (orgId: string) => {+ if (!resolver) {+ return;+ }+ await resolver.markPassThrough(orgId);+ };+// Ask the license server to recompute its cached entitlements (used after a license change), then// drop the local cache so the next read reflects them. No-op when the backend is dormant.const refreshEntitlements = async (org: TEntitlementOrg) => {@@ -208,6 +217,7 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact...featureReaderFactory({ getEntitlements }),getEntitlements,invalidateEntitlements,+ markEntitlementsStale,refreshEntitlements,getCatalog,getSubscription,