Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

fix(common): redact credentials in response diagnostic URLs

ajnart777e43b8f2e2
diff --git a/packages/api/src/test/nzbget-privacy.spec.ts b/packages/api/src/test/nzbget-privacy.spec.ts
index d497bdd7e..c5d012332 100644
--- a/packages/api/src/test/nzbget-privacy.spec.ts
+++ b/packages/api/src/test/nzbget-privacy.spec.ts
@@ -31,6 +31,7 @@ const fixture = vi.hoisted(() => {
return {
agent: null as MockAgent | null,
console: [] as string[],
+ requests: [] as string[],
history,
live,
redis: { options: {}, on: vi.fn(), multi: vi.fn(() => pipeline) },
@@ -53,7 +54,7 @@ vi.mock("@homarr/core/infrastructure/http", async (importActual) => {
};
});
-const input = {
+const nzbget = {
id: "owned-nzbget",
kind: "nzbGet" as const,
name: "Owned NZBGet",
@@ -65,8 +66,23 @@ const input = {
],
};
+const sabnzbd = {
+ id: "owned-sabnzbd",
+ kind: "sabNzbd" as const,
+ name: "Owned SABnzbd",
+ url: "https://sabnzbd.example.com",
+ externalUrl: null,
+ decryptedSecrets: [{ kind: "apiKey" as const, value: "fixture-sab-query-key/:?&=" }],
+};
+const clients = [
+ { input: nzbget, method: "POST", expectedUrl: "https://nzbget.example.com/jsonrpc" },
+ { input: sabnzbd, method: "GET", expectedUrl: "https://sabnzbd.example.com/api?limit=10&output=json&mode=queue" },
+];
+const rejectedRequests = clients.flatMap((client) => [401, 403, 500].map((status) => ({ ...client, status })));
+
beforeEach(() => {
fixture.console.length = 0;
+ fixture.requests.length = 0;
fixture.history.length = 0;
fixture.live.length = 0;
fixture.agent = new UndiciMockAgent();
@@ -91,10 +107,20 @@ afterAll(() => {
vi.unstubAllEnvs();
});
-test.each([401, 403, 500])(
- "keeps rejected RPC credentials out of original errors, Console and Redis history/live messages (HTTP %i)",
- async (status) => {
- fixture.agent?.get(input.url).intercept({ path: /.*/, method: "POST" }).reply(status, "").persist();
+test.each(rejectedRequests)(
+ "keeps $input.name rejected credentials out of errors and Console/Redis messages (HTTP $status)",
+ async ({ input, method, expectedUrl, status }) => {
+ fixture.agent
+ ?.get(input.url)
+ .intercept({
+ path: (path) => {
+ fixture.requests.push(path);
+ return true;
+ },
+ method,
+ })
+ .reply(status, "")
+ .persist();
const client = await createIntegrationAsync(input);
let failure: unknown;
const results = await settleIntegrationQueries(
@@ -111,12 +137,17 @@ test.each([401, 403, 500])(
);
expect(results).toEqual(["INTEGRATION_REQUEST_FAILED"]);
expect(failure).toBeInstanceOf(Error);
- expect((failure as Error).cause).toMatchObject({ statusCode: status, url: "https://nzbget.example.com/jsonrpc" });
await vi.waitFor(() => {
expect(fixture.console.some((line) => line.includes("Integration query failed"))).toBe(true);
expect(fixture.history.some((line) => line.includes("Integration query failed"))).toBe(true);
expect(fixture.live.some((line) => line.includes("Integration query failed"))).toBe(true);
});
+ if (input.kind === "sabNzbd") {
+ expect(fixture.requests.length).toBeGreaterThan(0);
+ for (const path of fixture.requests) {
+ expect(new URL(path, input.url).searchParams.get("apikey")).toBe("fixture-sab-query-key/:?&=");
+ }
+ }
const decoded = [fixture.history, fixture.live].map((messages) =>
messages.map((value) => loggerMessageSchema.parse(parse(value))),
);
@@ -125,12 +156,12 @@ test.each([401, 403, 500])(
expect(messages.some((message) => message.message === consoleFailure)).toBe(true);
}
const destinations = [
- JSON.stringify(failure),
- JSON.stringify((failure as Error).cause),
...fixture.console,
...fixture.history,
...fixture.live,
...decoded.flatMap((messages) => messages.map((message) => message.message)),
+ JSON.stringify(failure),
+ JSON.stringify((failure as Error).cause),
];
for (const destination of destinations) {
for (const credential of input.decryptedSecrets) {
@@ -142,5 +173,6 @@ test.each([401, 403, 500])(
);
expect(destination).not.toContain("Authorization");
}
+ expect((failure as Error).cause).toMatchObject({ statusCode: status, url: expectedUrl });
},
);
diff --git a/packages/common/src/errors/http/credential-url.ts b/packages/common/src/errors/http/credential-url.ts
new file mode 100644
index 000000000..7b3f85332
--- /dev/null
+++ b/packages/common/src/errors/http/credential-url.ts
@@ -0,0 +1,43 @@
+// SABnzbd/Jackett: apikey; Custom Widgets: api_key; Pi-hole v5: auth;
+// Technitium: token/user/pass; Navidrome: u/p. Keep protocol selectors and actions.
+const credentialQueryParameters = new Set(["apikey", "api_key", "auth", "token", "user", "pass", "u", "p"]);
+
+/** Sanitizes a diagnostic copy; request URLs and responses stay unchanged. */
+export function redactCredentialUrl(value: string | undefined): string | undefined {
+ if (value === undefined || value === "") return value;
+
+ let url: URL;
+ let absolute = false;
+ try {
+ url = new URL(value);
+ absolute = true;
+ } catch {
+ try {
+ url = new URL(value, "http://diagnostic.invalid");
+ } catch {
+ return undefined;
+ }
+ }
+
+ let changed = false;
+ if (url.username !== "" || url.password !== "") {
+ url.username = "";
+ url.password = "";
+ changed = true;
+ }
+ for (const name of new Set(url.searchParams.keys())) {
+ if (credentialQueryParameters.has(name.toLowerCase())) {
+ url.searchParams.delete(name);
+ changed = true;
+ }
+ }
+ if (!changed) return value;
+
+ const trimmed = value.trim();
+ if (absolute) return url.toString();
+ if (trimmed.slice(0, 2).replaceAll("\\", "/") === "//") {
+ return `//${url.host}${url.pathname}${url.search}${url.hash}`;
+ }
+ const path = trimmed.split(/[?#]/, 1)[0] ?? "";
+ return `${path}${url.search}${url.hash}`;
+}
diff --git a/packages/common/src/errors/http/handlers/http-error-handler.ts b/packages/common/src/errors/http/handlers/http-error-handler.ts
index 4a661199f..53e9d3aae 100644
--- a/packages/common/src/errors/http/handlers/http-error-handler.ts
+++ b/packages/common/src/errors/http/handlers/http-error-handler.ts
@@ -3,6 +3,7 @@ import { createLogger } from "@homarr/core/infrastructure/logs";
import type { AnyRequestError } from "../request-error";
import type { ResponseError } from "../response-error";
+import { redactCredentialUrl } from "../credential-url";
export abstract class HttpErrorHandler {
protected logger: ILogger;
@@ -16,7 +17,7 @@ export abstract class HttpErrorHandler {
}
protected logResponseError<T extends { status: number; url: string | undefined }>(metadata: T) {
- this.logger.debug("Received response error", metadata);
+ this.logger.debug("Received response error", { ...metadata, url: redactCredentialUrl(metadata.url) });
}
abstract handleRequestError(error: unknown): AnyRequestError | undefined;
diff --git a/packages/common/src/errors/http/response-error.ts b/packages/common/src/errors/http/response-error.ts
index a0b381c37..e28e0f061 100644
--- a/packages/common/src/errors/http/response-error.ts
+++ b/packages/common/src/errors/http/response-error.ts
@@ -1,3 +1,5 @@
+import { redactCredentialUrl } from "./credential-url";
+
export class ResponseError extends Error {
public readonly statusCode: number;
public readonly url?: string;
@@ -7,6 +9,6 @@ export class ResponseError extends Error {
this.name = ResponseError.name;
this.statusCode = response.status;
- this.url = response.url;
+ this.url = redactCredentialUrl(response.url);
}
}
diff --git a/packages/common/src/test/response-error-privacy.spec.ts b/packages/common/src/test/response-error-privacy.spec.ts
new file mode 100644
index 000000000..9ddf0367d
--- /dev/null
+++ b/packages/common/src/test/response-error-privacy.spec.ts
@@ -0,0 +1,82 @@
+// @vitest-environment node
+
+import { AxiosError, AxiosHeaders } from "axios";
+import { beforeEach, expect, test, vi } from "vitest";
+
+import { AxiosHttpErrorHandler, ResponseError } from "@homarr/common/server";
+
+const logs = vi.hoisted(() => {
+ process.env.SKIP_ENV_VALIDATION = "true";
+ return { debug: vi.fn() };
+});
+vi.mock("@homarr/core/infrastructure/logs", () => ({ createLogger: () => logs }));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+test.each([
+ {
+ url: "https://fixture-diag-user:[email protected]:9443/base/api?mode=queue&APIKEY=fixture-one&apikey=fixture-two&output=json#summary",
+ expected: "https://example.com:9443/base/api?mode=queue&output=json#summary",
+ },
+ {
+ url: "https://example.com/api?%61pi%6bey=fixture-key&action=status&token=fixture-token&AUTH=fixture-auth",
+ expected: "https://example.com/api?action=status",
+ },
+ {
+ url: "https://example.com/api/user/login?user=fixture-user&pass=fixture-pass&includeInfo=true",
+ expected: "https://example.com/api/user/login?includeInfo=true",
+ },
+ {
+ url: "https://example.com/rest/ping.view?u=fixture-user&p=fixture-pass&v=1.16.1&c=homarr&f=json",
+ expected: "https://example.com/rest/ping.view?v=1.16.1&c=homarr&f=json",
+ },
+ { url: "/api?ApiKey=fixture-key&method=list&version=1", expected: "/api?method=list&version=1" },
+ {
+ url: "https://example.com/api?API_KEY=fixture-custom-key&action=list&output=json",
+ expected: "https://example.com/api?action=list&output=json",
+ },
+ { url: "api?TOKEN=fixture-token&action=get", expected: "api?action=get" },
+ { url: "//fixture-user:[email protected]/api?mode=status", expected: "//example.com/api?mode=status" },
+ { url: "/\\fixture-user:[email protected]/api?apikey=fixture-key", expected: "//example.com/api" },
+ {
+ url: "ht\ttp://fixture-user:[email protected]/api?mode=status",
+ expected: "http://example.com/api?mode=status",
+ },
+ { url: "https://fixture-user:fixture-pass@bad host/api?apikey=fixture-key", expected: undefined },
+])("keeps useful response diagnostics without credential authority (%#)", ({ url, expected }) => {
+ const response = Object.freeze({ status: 403, url });
+ const error = new ResponseError(response);
+ expect(error.statusCode).toBe(403);
+ expect(error.url).toBe(expected);
+ expect(response.url).toBe(url);
+});
+
+test.each([undefined, "", "?", "https://example.com", "https://example.com/api?mode=queue&action=apikey&output=json"])(
+ "preserves credential-free diagnostic values exactly (%s)",
+ (url) => {
+ expect(new ResponseError({ status: 500, url }).url).toBe(url);
+ },
+);
+
+test("redacts the common handler's debug diagnostic before the response error is constructed", () => {
+ const url = "https://fixture-handler-user:[email protected]/api?ApiKey=fixture-handler-key&mode=queue";
+ const config = { url, method: "get", headers: new AxiosHeaders() };
+ const response = { status: 401, statusText: "Unauthorized", config, headers: {}, data: null };
+ const upstream = new AxiosError(
+ "Request failed with status code 401",
+ "ERR_BAD_REQUEST",
+ config,
+ undefined,
+ response,
+ );
+ const error = new AxiosHttpErrorHandler().handleResponseError(upstream);
+ expect(error?.url).toBe("https://example.com/api?mode=queue");
+ expect(logs.debug).toHaveBeenCalledWith("Received response error", {
+ status: 401,
+ url: "https://example.com/api?mode=queue",
+ message: "Request failed with status code 401",
+ });
+ expect(upstream.response?.config.url).toBe(url);
+});