Skip to content

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

feat: added better error format for license client and license request id

=84a7ee05cee3
diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.ts
index 3381680930..7a8345ec1f 100644
--- a/backend/src/services/license-client/license-client-backends.ts
+++ b/backend/src/services/license-client/license-client-backends.ts
@@ -3,6 +3,7 @@ import jwt from "jsonwebtoken";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import { LICENSE_SERVER_ERROR_NAME, licenseErrorMessage, readLicenseRequestId } from "./license-client-errors";
import {
billingProfileResponseSchema,
catalogResponseSchema,
@@ -86,6 +87,7 @@ const throwIfResponseError = async (res: Response): Promise<void> => {
if (res.ok) {
return;
}
+ const requestId = readLicenseRequestId(res);
if (res.status >= 400 && res.status < 500) {
const body = (await res.json().catch(() => null)) as {
error?: string;
@@ -97,12 +99,18 @@ const throwIfResponseError = async (res: Response): Promise<void> => {
// `error`; older servers used `message`, so read both as the fallback.
const code = body?.details?.code;
const message = (code && BILLING_ERROR_MESSAGES[code]) || body?.error || body?.message;
+ logger.warn(licenseErrorMessage(requestId, `request rejected [status=${res.status}] [code=${code ?? "none"}]`));
throw new BadRequestError({
- message,
+ name: LICENSE_SERVER_ERROR_NAME,
+ message: licenseErrorMessage(requestId, message ?? "Billing request failed"),
details: code ? { code } : undefined
});
}
- throw new InternalServerError({ message: "Billing service error" });
+ logger.error(licenseErrorMessage(requestId, `request failed [status=${res.status}]`));
+ throw new InternalServerError({
+ name: LICENSE_SERVER_ERROR_NAME,
+ message: licenseErrorMessage(requestId, "Billing service error")
+ });
};
export const licenseServerBackend = (
@@ -163,7 +171,10 @@ export const licenseServerBackend = (
if (!parsed.success) {
// A schema mismatch must NOT be silently read as "no subscription" — that hides a real (often
// paid) subscription behind the free state. Log it so contract drift is visible, then degrade.
- logger.error({ err: parsed.error }, `license-client: /subscription failed schema validation [orgId=${orgId}]`);
+ logger.error(
+ { err: parsed.error },
+ licenseErrorMessage(readLicenseRequestId(res), `/subscription failed schema validation [orgId=${orgId}]`)
+ );
return null;
}
if (!parsed.data.status) {
@@ -359,8 +370,9 @@ export const licenseServerBackend = (
// Stripe-backed billing (checkout, portal, subscription mutations, cloud plan, billing profile) does
// not exist for self-hosted licenses; the license is managed out-of-band. These reject so a caller
// never silently no-ops.
+// No request is made, so there is no license request id to carry — only the shared prefix.
const notSupportedOnSelfHosted = (operation: string) => (): Promise<never> =>
- Promise.reject(new Error(`license operation "${operation}" is not supported for self-hosted licenses`));
+ Promise.reject(new Error(`license-client: operation "${operation}" is not supported for self-hosted licenses`));
// 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
@@ -417,7 +429,10 @@ export const licenseServerSelfHostedBackend = (
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)");
+ logger.error(
+ { err: parsed.error },
+ licenseErrorMessage(readLicenseRequestId(res), "/subscription failed schema validation (self-hosted)")
+ );
return null;
}
if (!parsed.data.status) {
diff --git a/backend/src/services/license-client/license-client-errors.ts b/backend/src/services/license-client/license-client-errors.ts
new file mode 100644
index 0000000000..9a860f1ec8
--- /dev/null
+++ b/backend/src/services/license-client/license-client-errors.ts
@@ -0,0 +1,14 @@
+// Every error raised from a license-server interaction is formatted through here, so one grep on
+// licenseRequestId ties a failure in our logs to the exact request in the license server's. The id
+// falls back to "unknown" rather than being omitted, so the field is always there to match on.
+const LICENSE_REQUEST_ID_HEADER = "x-request-id";
+
+// Carried as the thrown error's name instead of the default "BadRequest"/"InternalServerError", so a
+// failure that originated at the license server is attributable without matching on message text (the
+// error handler logs error.name and labels the error metrics with it).
+export const LICENSE_SERVER_ERROR_NAME = "LicenseServerError";
+
+export const readLicenseRequestId = (res: Response): string => res.headers.get(LICENSE_REQUEST_ID_HEADER) ?? "unknown";
+
+export const licenseErrorMessage = (requestId: string, message: string): string =>
+ `license-client: [licenseRequestId=${requestId}] ${message}`;
diff --git a/backend/src/services/license-client/license-token-provider.test.ts b/backend/src/services/license-client/license-token-provider.test.ts
index e894241e3f..c2614c4441 100644
--- a/backend/src/services/license-client/license-token-provider.test.ts
+++ b/backend/src/services/license-client/license-token-provider.test.ts
@@ -21,6 +21,7 @@ const nowSeconds = () => Math.floor(Date.now() / 1000);
const mockFetchReturning = (token: string) =>
vi.fn(async () => ({
ok: true,
+ headers: new Headers(),
json: async () => ({ token })
})) as unknown as typeof fetch;
@@ -70,7 +71,11 @@ describe("createSelfHostedTokenProvider", () => {
});
test("single-flights concurrent exchanges", async () => {
- let resolveFetch: (value: { ok: boolean; json: () => Promise<{ token: string }> }) => void = () => {};
+ let resolveFetch: (value: {
+ ok: boolean;
+ headers: Headers;
+ json: () => Promise<{ token: string }>;
+ }) => void = () => {};
const fetchMock = vi.fn(
() =>
new Promise((resolve) => {
@@ -84,7 +89,7 @@ describe("createSelfHostedTokenProvider", () => {
const [a, b] = await Promise.all([
(async () => {
const p = provider.getToken();
- resolveFetch({ ok: true, json: async () => ({ token }) });
+ resolveFetch({ ok: true, headers: new Headers(), json: async () => ({ token }) });
return p;
})(),
provider.getToken()
@@ -99,11 +104,12 @@ describe("createSelfHostedTokenProvider", () => {
const fetchMock = vi.fn(async () => ({
ok: false,
status: 401,
+ headers: new Headers({ "x-request-id": "req-abc" }),
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/);
+ await expect(provider.getToken()).rejects.toThrow(/\[licenseRequestId=req-abc\] token exchange failed/);
});
});
diff --git a/backend/src/services/license-client/license-token-provider.ts b/backend/src/services/license-client/license-token-provider.ts
index 6fc76dfd12..94716a10b2 100644
--- a/backend/src/services/license-client/license-token-provider.ts
+++ b/backend/src/services/license-client/license-token-provider.ts
@@ -1,5 +1,7 @@
import { logger } from "@app/lib/logger";
+import { licenseErrorMessage, readLicenseRequestId } from "./license-client-errors";
+
export type TLicenseTokenProvider = {
// Exchanges the license key for a JWT (cached until near expiry) and returns it as a bearer.
getToken: () => Promise<string>;
@@ -48,13 +50,14 @@ export const createSelfHostedTokenProvider = (
body: "{}",
redirect: "manual"
});
+ const requestId = readLicenseRequestId(res);
if (!res.ok) {
const detail = await res.text().catch(() => "");
- throw new Error(`license-client: token exchange failed [status=${res.status}] ${detail}`.trim());
+ throw new Error(licenseErrorMessage(requestId, `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");
+ throw new Error(licenseErrorMessage(requestId, "token exchange returned no token"));
}
return body.token;
};
diff --git a/backend/src/services/license-client/usage/usage-reporter.ts b/backend/src/services/license-client/usage/usage-reporter.ts
index cf88940d75..1ce793be98 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 { licenseErrorMessage, readLicenseRequestId } from "../license-client-errors";
import { createSelfHostedTokenProvider } from "../license-token-provider";
export type TUsageSnapshot = {
@@ -23,8 +24,13 @@ export class UsageReportError extends Error {
readonly serverMessage: string;
- constructor(status: number, serverMessage: string) {
- super(`usage snapshot report failed with ${status}${serverMessage ? `: ${serverMessage}` : ""}`);
+ constructor(status: number, serverMessage: string, requestId?: string) {
+ super(
+ licenseErrorMessage(
+ requestId || "unknown",
+ `usage snapshot report failed with ${status}${serverMessage ? `: ${serverMessage}` : ""}`
+ )
+ );
this.name = "UsageReportError";
this.status = status;
this.serverMessage = serverMessage;
@@ -55,7 +61,7 @@ export const usageReporterFactory = (serverUrl: string, getBearerToken: () => Pr
} catch {
// non-JSON body; leave the message empty
}
- throw new UsageReportError(res.status, serverMessage);
+ throw new UsageReportError(res.status, serverMessage, readLicenseRequestId(res));
}
}
});