diff --git a/packages/sdk/fixtures/status-redirect-cross-origin.json b/packages/sdk/fixtures/status-redirect-cross-origin.json new file mode 100644 index 00000000..9b0e72c0 --- /dev/null +++ b/packages/sdk/fixtures/status-redirect-cross-origin.json @@ -0,0 +1,9 @@ +{ + "description": "Cross-origin HTTP redirect that must not be followed", + "requestUrl": "http://keeper.test/status", + "status": 307, + "headers": { + "Location": "https://attacker.example/exfiltrate?token=secret" + }, + "sameOrigin": false +} diff --git a/packages/sdk/fixtures/status-redirect-same-origin.json b/packages/sdk/fixtures/status-redirect-same-origin.json new file mode 100644 index 00000000..eab65036 --- /dev/null +++ b/packages/sdk/fixtures/status-redirect-same-origin.json @@ -0,0 +1,9 @@ +{ + "description": "Same-origin HTTP redirect from the keeper status endpoint", + "requestUrl": "http://keeper.test/status", + "status": 302, + "headers": { + "Location": "http://keeper.test/status/moved" + }, + "sameOrigin": true +} diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index bbf99fee..7e19f5f2 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -226,7 +226,9 @@ export { KeeperStatusClient, StatusApiError, StatusJsonParseError, + StatusRedirectError, KeeperStatusTimeoutError, + isHttpRedirectStatus, redactUrlUserinfo, type KeeperReadiness, type KeeperNotReadyReason, diff --git a/packages/sdk/src/public-api-snapshot.test.ts b/packages/sdk/src/public-api-snapshot.test.ts index 0a9e6df6..ea178235 100644 --- a/packages/sdk/src/public-api-snapshot.test.ts +++ b/packages/sdk/src/public-api-snapshot.test.ts @@ -33,6 +33,7 @@ const EXPECTED_EXPORTS = [ "RoundErrors", "StatusApiError", "StatusJsonParseError", + "StatusRedirectError", "SubRosaAssetValidationError", "SubRosaClient", "SubRosaClientConfigError", @@ -77,6 +78,7 @@ const EXPECTED_EXPORTS = [ "isActiveRoundStatus", "isErrorRoundStatus", "isEscrowConserved", + "isHttpRedirectStatus", "isKeeperRoundActive", "isKeeperRoundSettlementPending", "isKeeperRoundTerminal", diff --git a/packages/sdk/src/status-client.test.ts b/packages/sdk/src/status-client.test.ts index 2f01c13a..ce850031 100644 --- a/packages/sdk/src/status-client.test.ts +++ b/packages/sdk/src/status-client.test.ts @@ -1,15 +1,33 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; import { KeeperStatusClient, StatusApiError, StatusJsonParseError, + StatusRedirectError, type StatusClientOptions, } from "./status-client.js"; import { createFakeTime } from "@sub-rosa/time"; import type { KeeperStatusResponse } from "./status.js"; +const FIXTURES_DIR = join(dirname(fileURLToPath(import.meta.url)), "../fixtures"); + +interface RedirectFixture { + description: string; + requestUrl: string; + status: number; + headers: { Location: string }; + sameOrigin: boolean; +} + +function loadRedirectFixture(name: string): RedirectFixture { + return JSON.parse(readFileSync(join(FIXTURES_DIR, name), "utf8")) as RedirectFixture; +} + const SAMPLE_STATUS: KeeperStatusResponse = { contractId: "C123", network: "testnet", @@ -110,6 +128,95 @@ describe("KeeperStatusClient non-success responses", () => { }); }); +describe("KeeperStatusClient redirects", () => { + it("disables automatic redirects on every status request", async () => { + let seenRedirect: RequestRedirect | undefined; + const client = new KeeperStatusClient({ + baseURL: "http://keeper.test", + fetchImpl: async (_url, init) => { + seenRedirect = init?.redirect; + return new Response(JSON.stringify(SAMPLE_STATUS), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }, + }); + await client.getStatus(); + assert.equal(seenRedirect, "manual"); + }); + + it("rejects same-origin redirect fixtures with a typed error and redacts Location", async () => { + const fixture = loadRedirectFixture("status-redirect-same-origin.json"); + const client = new KeeperStatusClient({ + baseURL: "http://keeper.test", + fetchImpl: async () => + new Response("", { + status: fixture.status, + headers: fixture.headers, + }), + }); + await assert.rejects( + () => client.getStatus(), + (error: unknown) => { + assert.ok(error instanceof StatusRedirectError); + assert.equal(error.status, fixture.status); + assert.equal(error.sameOrigin, true); + assert.equal(error.sameOrigin, fixture.sameOrigin); + assert.ok(!error.message.includes(fixture.headers.Location)); + assert.ok(!JSON.stringify(error).includes(fixture.headers.Location)); + assert.match(error.message, /refused redirect/i); + return true; + }, + ); + }); + + it("rejects cross-origin redirect fixtures with a typed error and redacts Location", async () => { + const fixture = loadRedirectFixture("status-redirect-cross-origin.json"); + const client = new KeeperStatusClient({ + baseURL: "http://keeper.test", + fetchImpl: async () => + new Response("", { + status: fixture.status, + headers: fixture.headers, + }), + }); + await assert.rejects( + () => client.getStatus(), + (error: unknown) => { + assert.ok(error instanceof StatusRedirectError); + assert.equal(error.status, fixture.status); + assert.equal(error.sameOrigin, false); + assert.equal(error.sameOrigin, fixture.sameOrigin); + assert.ok(!error.message.includes(fixture.headers.Location)); + assert.ok(!error.message.includes("attacker.example")); + assert.ok(!error.message.includes("secret")); + assert.ok(!JSON.stringify(error).includes("attacker.example")); + return true; + }, + ); + }); + + it("treats redirect failures as not-ready without leaking Location", async () => { + const fixture = loadRedirectFixture("status-redirect-cross-origin.json"); + const time = createFakeTime(1_700_000_000_000); + const client = new KeeperStatusClient({ + baseURL: "http://keeper.test", + timeoutMs: 5_000, + scheduler: time.scheduler, + fetchImpl: async () => + new Response("", { + status: fixture.status, + headers: fixture.headers, + }), + }); + const verdict = await client.readiness(); + assert.equal(verdict.ready, false); + assert.equal(verdict.ready === false && verdict.reason, "unavailable"); + assert.ok(verdict.ready === false && !verdict.error.includes(fixture.headers.Location)); + assert.ok(verdict.ready === false && !verdict.error.includes("attacker.example")); + }); +}); + describe("KeeperStatusClient readiness", () => { const ROUND = { roundId: "7", status: "Open", phase: "awaiting-drand", nextAction: "wait", commitDeadline: 1, diff --git a/packages/sdk/src/status-client.ts b/packages/sdk/src/status-client.ts index 90a736ba..f60dd440 100644 --- a/packages/sdk/src/status-client.ts +++ b/packages/sdk/src/status-client.ts @@ -77,6 +77,52 @@ export class StatusJsonParseError extends Error { } } +/** True for HTTP 3xx statuses that would otherwise trigger a redirect. */ +export function isHttpRedirectStatus(status: number): boolean { + return status >= 300 && status < 400; +} + +/** + * Raised when the status client receives a redirect (or an opaque redirect) + * instead of following it. The `Location` header value is never included in + * the message or on the error object. + */ +export class StatusRedirectError extends Error { + readonly name = "StatusRedirectError"; + readonly status: number; + /** + * Whether `Location` targets the same origin as the request URL. + * `null` when Location is missing or unparseable; `false` for opaque redirects. + */ + readonly sameOrigin: boolean | null; + + constructor(status: number, sameOrigin: boolean | null = null) { + const label = status === 0 ? "opaque" : String(status); + super(`status api refused redirect (${label})`); + this.status = status; + this.sameOrigin = sameOrigin; + } + + /** Build an error from a redirect response without echoing Location. */ + static fromResponse(requestUrl: string, res: Response): StatusRedirectError { + if (res.type === "opaqueredirect") { + return new StatusRedirectError(res.status === 0 ? 0 : res.status, false); + } + const location = res.headers.get("Location") ?? res.headers.get("location"); + let sameOrigin: boolean | null = null; + if (location) { + try { + const request = new URL(requestUrl); + const destination = new URL(location, requestUrl); + sameOrigin = request.origin === destination.origin; + } catch { + sameOrigin = null; + } + } + return new StatusRedirectError(res.status, sameOrigin); + } +} + function fullURL(base: string, path: string): string { const trimmed = base.replace(/\/+$/, ""); const clean = path.startsWith("/") ? path : `/${path}`; @@ -199,7 +245,17 @@ export class KeeperStatusClient { const forwardAbort = () => controller.abort(callerSignal?.reason); callerSignal?.addEventListener("abort", forwardAbort, { once: true }); const request = (async () => { - const res = await this.fetchImpl(url, { method: "GET", headers: { Accept: "application/json", ...this.headers }, signal: controller.signal }); + // Never follow redirects: a 3xx would otherwise resend the request (and + // any future auth headers) to an unreviewed Location origin. + const res = await this.fetchImpl(url, { + method: "GET", + headers: { Accept: "application/json", ...this.headers }, + signal: controller.signal, + redirect: "manual", + }); + if (res.type === "opaqueredirect" || isHttpRedirectStatus(res.status)) { + throw StatusRedirectError.fromResponse(url, res); + } if (!res.ok) { const body = await parseErrorBody(res); throw new StatusApiError(res.status, body);