Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

πŸ”Š Distinguish network failures when validating a license key (#2885)

Luke Vellacc29eea150ab
diff --git a/apps/web/src/features/licensing/mutations.test.ts b/apps/web/src/features/licensing/mutations.test.ts
index e23f909b5..2b64b57a7 100644
--- a/apps/web/src/features/licensing/mutations.test.ts
+++ b/apps/web/src/features/licensing/mutations.test.ts
@@ -75,3 +75,80 @@ describe("setInstanceLicense", () => {
});
});
});
+
+/**
+ * A thrown fetch skips the response-status branch entirely, so before this was
+ * handled a TLS failure behind a corporate proxy logged nothing and surfaced as
+ * a bare "internal server error" β€” indistinguishable from the licensing service
+ * being down. The codes below are the real ones Node reports; they were
+ * captured by calling the corresponding badssl.com endpoints.
+ */
+describe("validateLicenseKey network failures", () => {
+ const fetchError = (code: string) =>
+ Object.assign(new TypeError("fetch failed"), { cause: { code } });
+
+ async function attempt(thrown: unknown) {
+ const { LicenseManager } = await import("./mutations");
+ vi.spyOn(globalThis, "fetch").mockRejectedValue(thrown);
+ const manager = new LicenseManager({ apiUrl: "https://example.test/v1" });
+
+ return manager
+ .validateLicenseKey({ key: "RLYV4-AAAA-BBBB-CCCC-DDDD-00199" })
+ .then(
+ () => null,
+ (error: Error) => error,
+ );
+ }
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ ["DEPTH_ZERO_SELF_SIGNED_CERT"],
+ ["SELF_SIGNED_CERT_IN_CHAIN"],
+ ["CERT_HAS_EXPIRED"],
+ ["ERR_TLS_CERT_ALTNAME_INVALID"],
+ ])("names the certificate as the cause for %s", async (code) => {
+ const error = await attempt(fetchError(code));
+
+ // The remedy has to reach the operator: the toast is generic, so the
+ // message is the only place the CA hint can live.
+ expect(error?.message).toContain("NODE_EXTRA_CA_CERTS");
+ });
+
+ it("does not blame certificates for a DNS failure", async () => {
+ const error = await attempt(fetchError("ENOTFOUND"));
+
+ expect(error?.message).toContain("Could not reach");
+ expect(error?.message).not.toContain("NODE_EXTRA_CA_CERTS");
+ });
+
+ it("reports a timeout distinctly", async () => {
+ const timeout = new DOMException("aborted due to timeout", "TimeoutError");
+ const error = await attempt(timeout);
+
+ expect(error?.message).toContain("did not respond");
+ expect(error?.message).not.toContain("NODE_EXTRA_CA_CERTS");
+ });
+
+ it("rethrows errors it cannot classify rather than mislabelling them", async () => {
+ const bug = new RangeError("something else entirely");
+ const error = await attempt(bug);
+
+ expect(error).toBe(bug);
+ });
+
+ it("rethrows a TypeError that isn't a transport failure", async () => {
+ // A malformed LICENSE_API_URL throws this exact shape. Treating it as a
+ // network failure would send an operator to debug connectivity when the
+ // problem is their configuration.
+ const badUrl = Object.assign(
+ new TypeError("Failed to parse URL from not-a-url/v1"),
+ { cause: { code: "ERR_INVALID_URL" } },
+ );
+ const error = await attempt(badUrl);
+
+ expect(error).toBe(badUrl);
+ });
+});
diff --git a/apps/web/src/features/licensing/mutations.ts b/apps/web/src/features/licensing/mutations.ts
index 26f789e27..4724e3af1 100644
--- a/apps/web/src/features/licensing/mutations.ts
+++ b/apps/web/src/features/licensing/mutations.ts
@@ -22,6 +22,53 @@ const logger = createLogger("licensing/manager");
const REQUEST_TIMEOUT_MS = 30_000;
+/**
+ * TLS failures reach us as `TypeError: fetch failed` with the real reason on
+ * `cause.code` β€” the same shape DNS and connection-refused failures take. The
+ * message alone is identical in every case, so the code is the only signal
+ * worth logging: a self-hosted instance behind a TLS-intercepting proxy is
+ * indistinguishable from a dead DNS entry without it.
+ */
+const TLS_ERROR_CODE_PATTERN =
+ /^(CERT_|DEPTH_ZERO_|SELF_SIGNED_|UNABLE_TO_(GET|VERIFY)_|ERR_TLS_)/;
+
+function describeFetchFailure(error: unknown) {
+ if (error instanceof DOMException && error.name === "TimeoutError") {
+ return {
+ reason: "timeout" as const,
+ code: "TIMEOUT",
+ message: `Licensing service did not respond within ${REQUEST_TIMEOUT_MS}ms.`,
+ };
+ }
+
+ // Only "fetch failed" carries a transport fault. Other TypeErrors are
+ // programming or configuration faults β€” a malformed LICENSE_API_URL throws
+ // "Failed to parse URL from ..." β€” and reporting those as connectivity would
+ // send an operator to debug a network that is working fine.
+ if (error instanceof TypeError && error.message === "fetch failed") {
+ const code = (error.cause as { code?: string } | undefined)?.code;
+
+ if (code && TLS_ERROR_CODE_PATTERN.test(code)) {
+ return {
+ reason: "tls" as const,
+ code,
+ message:
+ "TLS verification failed when contacting the licensing service. " +
+ "If this instance is behind a proxy that intercepts HTTPS, point " +
+ "NODE_EXTRA_CA_CERTS at your root CA certificate and restart.",
+ };
+ }
+
+ return {
+ reason: "network" as const,
+ code: code ?? "UNKNOWN",
+ message: "Could not reach the licensing service.",
+ };
+ }
+
+ return null;
+}
+
export class LicenseManager {
apiUrl: string;
authToken?: string;
@@ -57,14 +104,37 @@ export class LicenseManager {
return createLicenseResponseSchema.parse(await res.json());
}
async validateLicenseKey(input: ValidateLicenseInputKeySchema) {
- const res = await fetch(`${this.apiUrl}/licenses/actions/validate-key`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(input),
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
- });
+ let res: Response;
+ try {
+ res = await fetch(`${this.apiUrl}/licenses/actions/validate-key`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(input),
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ });
+ } catch (error) {
+ // A thrown fetch never reaches the !res.ok branch below, so without this
+ // the request failed with nothing logged at all and the operator saw a
+ // bare "internal server error".
+ const failure = describeFetchFailure(error);
+
+ if (!failure) {
+ throw error;
+ }
+
+ logger.error(
+ { reason: failure.reason, code: failure.code, apiUrl: this.apiUrl },
+ failure.message,
+ );
+
+ throw new AppError({
+ code: "INTERNAL_SERVER_ERROR",
+ cause: error,
+ message: failure.message,
+ });
+ }
if (!res.ok) {
const text = await res.text();