Skip to content

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

feat: addressed LLM review

=fe01ec92a7c1
diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.ts
index 98ee8f9c93..8c328c73ac 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -874,7 +874,7 @@ export const licenseV2ServiceFactory = ({
if (!result.checkoutUrl) {
throw new InternalServerError({ message: "Checkout session did not return a URL" });
}
- await licenseClient.markEntitlementsStale(orgId);
+ await licenseClient.markEntitlementsStale(orgId, { checkout: true });
return { outcome: "checkout_created" as const, checkoutUrl: result.checkoutUrl };
};
@@ -954,13 +954,15 @@ export const licenseV2ServiceFactory = ({
productId,
dimensions: changes.map((change) => ({ dimensionKey: change.dimensionKey, quantity: change.quantity }))
});
- await licenseClient.markEntitlementsStale(orgId);
if (result.outcome === "checkout_created") {
if (!result.checkoutUrl) {
throw new InternalServerError({ message: "Checkout session did not return a URL" });
}
+ // Longer window: the change only applies once the customer completes the hosted checkout.
+ await licenseClient.markEntitlementsStale(orgId, { checkout: true });
return { outcome: "checkout_created" as const, checkoutUrl: result.checkoutUrl };
}
+ await licenseClient.markEntitlementsStale(orgId);
return { outcome: "subscription_updated" as const, subscriptionId: result.subscriptionId };
};
@@ -988,7 +990,9 @@ export const licenseV2ServiceFactory = ({
// The trial's card-setup checkout redirects here; built server-side from SITE_URL like checkout.
returnUrl: buildReturnUrl(orgId)
});
- await licenseClient.markEntitlementsStale(orgId);
+ // awaiting_card redirects to a Stripe card-setup checkout; the trial is granted by webhook only
+ // after it's completed, so hold the revalidation window open longer than an immediate trial_started.
+ await licenseClient.markEntitlementsStale(orgId, { checkout: result.outcome === "awaiting_card" });
return { outcome: result.outcome, cardSetupUrl: result.cardSetupUrl };
};
diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.ts
index f900c29d33..f211a397f4 100644
--- a/backend/src/ee/services/license/license-service.ts
+++ b/backend/src/ee/services/license/license-service.ts
@@ -18,7 +18,6 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { UserIdentities } from "@app/services/license-client";
-import { TDualReadServiceFactory } from "@app/services/license-client/dual-read/dual-read-service";
import { projectV2ToFeatureSet } from "@app/services/license-client/dual-read/entitlement-projection";
import { TLicenseClientFactory } from "@app/services/license-client/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
@@ -72,9 +71,6 @@ type TLicenseServiceFactoryDep = {
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "setItemWithExpiryNX" | "getItems" | "deleteItem">;
projectDAL: TProjectDALFactory;
licenseClient?: Pick<TLicenseClientFactory, "getEntitlements" | "getSubscription" | "refreshEntitlements">;
- licenseDualRead?: Pick<TDualReadServiceFactory, "compareInBackground">;
- // Fire-and-forget v2 usage meter for org user seats + demand-driven reconciliation; both no-op when
- // the v2 license server is disabled.
usageMeteringService?: Pick<TUsageMeteringServiceFactory, "emit" | "reconcile">;
};
@@ -95,7 +91,6 @@ export const licenseServiceFactory = ({
projectDAL,
envConfig,
licenseClient,
- licenseDualRead,
usageMeteringService
}: TLicenseServiceFactoryDep) => {
let isValidLicense = false;
@@ -293,11 +288,76 @@ export const licenseServiceFactory = ({
}
};
+ // Fetches the org's cloud plan fresh (v2 entitlements projected into the v1 shape, or the v1 plan),
+ // enriches it with live usage counts, writes it to the plan cache, and returns it. Throws on any
+ // failure — it never persists the free-tier fallback itself, so callers control that decision.
+ const fetchAndCacheCloudPlan = async (orgId: string): Promise<TFeatureSet> => {
+ const org = await requestMemoize(requestMemoKeys.orgFindRootOrgDetails(orgId), () =>
+ orgDAL.findRootOrgDetails(orgId)
+ );
+ if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
+ const rootOrgId = org.id;
+
+ 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({ id: rootOrgId, name: org.name, slug: org.slug });
+ 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);
+
+ // 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,
+ quantityIdentities: identityUsed
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `Update seats used: encountered an error when updating plan for customer [customerId=${org.customerId}]`
+ );
+ }
+ }
+ currentPlan.identitiesUsed = identityUsed;
+
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.LicenseCloudPlan(org.id),
+ KeyStoreTtls.LicenseCloudPlanInSeconds,
+ JSON.stringify(currentPlan)
+ );
+
+ return currentPlan;
+ };
+
// 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.
+ // throttle (at most one refresh per org per lock window). Recomputes and overwrites the plan cache
+ // only on success — it never deletes the existing valid plan first, so a transient License Server / DB
+ // failure can't downgrade a paid org to the free-tier fallback mid-refresh. Never throws.
const revalidatePlanInBackground = async (orgId: string) => {
try {
const acquired = await keyStore.setItemWithExpiryNX(
@@ -309,9 +369,7 @@ export const licenseServiceFactory = ({
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);
+ await fetchAndCacheCloudPlan(orgId);
} catch (error) {
logger.error(error, `getPlan: background revalidation failed [orgId=${orgId}]`);
}
@@ -350,67 +408,7 @@ export const licenseServiceFactory = ({
return plan;
}
- const org = await orgDAL.findRootOrgDetails(orgId);
- if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
- const rootOrgId = org.id;
-
- 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({ id: rootOrgId, name: org.name, slug: org.slug });
- 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);
-
- // 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,
- quantityIdentities: identityUsed
- });
- } catch (error) {
- logger.error(
- error,
- `Update seats used: encountered an error when updating plan for customer [customerId=${org.customerId}]`
- );
- }
- }
- currentPlan.identitiesUsed = identityUsed;
-
- await keyStore.setItemWithExpiry(
- KeyStorePrefixes.LicenseCloudPlan(org.id),
- KeyStoreTtls.LicenseCloudPlanInSeconds,
- 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);
- }
-
+ const currentPlan = await fetchAndCacheCloudPlan(orgId);
maybeReconcile(currentPlan);
return currentPlan;
}
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index acb8e0e71d..66c2cf9011 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -204,6 +204,9 @@ export const KeyStoreTtls = {
PamDefaultProjectInSeconds: 300, // 5 minutes
// How long reads stay in stale-while-revalidate mode after a billing mutation (covers Stripe reconciliation).
LicenseCachePassThroughInSeconds: 180, // 3 minutes
+ // Longer window for redirect-to-Stripe-checkout paths, where the purchase applies via webhook only
+ // after the customer finishes the hosted checkout/card-setup (which can take a few minutes).
+ LicenseCachePassThroughCheckoutInSeconds: 900, // 15 minutes
// Throttle window for the single-flight background revalidation.
LicenseCacheRevalidateLockInSeconds: 10,
// How often a billable org's usage is re-emitted for reconciliation (demand-driven from getPlan).
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 2506d9ba4b..7bb6248bd5 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -380,7 +380,6 @@ 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,
@@ -802,9 +801,6 @@ export const registerRoutes = async (
// 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 });
-
// Created before licenseService so the latter can emit the v2 user-seat meter from its
// updateSubscriptionOrgMemberCount chokepoint.
const usageMeteringService = usageMeteringServiceFactory({ queueService, projectDAL, keyStore, envConfig });
@@ -817,7 +813,6 @@ export const registerRoutes = async (
projectDAL,
envConfig,
licenseClient,
- licenseDualRead,
usageMeteringService
});
diff --git a/backend/src/services/license-client/license-client-cache.ts b/backend/src/services/license-client/license-client-cache.ts
index 13536e0bdc..5a4634dba7 100644
--- a/backend/src/services/license-client/license-client-cache.ts
+++ b/backend/src/services/license-client/license-client-cache.ts
@@ -30,11 +30,15 @@ export const entitlementResolverFactory = ({ keyStore, backend }: TEntitlementRe
// 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> => {
+ // checkout uses a longer window because the change only applies once the customer finishes the
+ // Stripe-hosted checkout/card-setup, which can take several minutes.
+ const markPassThrough = async (orgId: string, opts?: { checkout?: boolean }): Promise<void> => {
try {
await keyStore.setItemWithExpiry(
KeyStorePrefixes.LicenseCachePassThrough(orgId),
- KeyStoreTtls.LicenseCachePassThroughInSeconds,
+ opts?.checkout
+ ? KeyStoreTtls.LicenseCachePassThroughCheckoutInSeconds
+ : KeyStoreTtls.LicenseCachePassThroughInSeconds,
"1"
);
} catch (error) {
diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.ts
index a1f4c128e6..3e3af953b3 100644
--- a/backend/src/services/license-client/license-client.ts
+++ b/backend/src/services/license-client/license-client.ts
@@ -97,11 +97,11 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFact
// 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) => {
+ const markEntitlementsStale = async (orgId: string, opts?: { checkout?: boolean }) => {
if (!resolver) {
return;
}
- await resolver.markPassThrough(orgId);
+ await resolver.markPassThrough(orgId, opts);
};
// Drop the local plan cache so the next read reflects a change immediately. The license server no