Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/sdk/fixtures/status-redirect-cross-origin.json
Original file line number Diff line number Diff line change
@@ -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
}
9 changes: 9 additions & 0 deletions packages/sdk/fixtures/status-redirect-same-origin.json
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 2 additions & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,9 @@ export {
KeeperStatusClient,
StatusApiError,
StatusJsonParseError,
StatusRedirectError,
KeeperStatusTimeoutError,
isHttpRedirectStatus,
redactUrlUserinfo,
type KeeperReadiness,
type KeeperNotReadyReason,
Expand Down
2 changes: 2 additions & 0 deletions packages/sdk/src/public-api-snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const EXPECTED_EXPORTS = [
"RoundErrors",
"StatusApiError",
"StatusJsonParseError",
"StatusRedirectError",
"SubRosaAssetValidationError",
"SubRosaClient",
"SubRosaClientConfigError",
Expand Down Expand Up @@ -77,6 +78,7 @@ const EXPECTED_EXPORTS = [
"isActiveRoundStatus",
"isErrorRoundStatus",
"isEscrowConserved",
"isHttpRedirectStatus",
"isKeeperRoundActive",
"isKeeperRoundSettlementPending",
"isKeeperRoundTerminal",
Expand Down
107 changes: 107 additions & 0 deletions packages/sdk/src/status-client.test.ts
Original file line number Diff line number Diff line change
@@ -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",
Expand Down Expand Up @@ -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,
Expand Down
58 changes: 57 additions & 1 deletion packages/sdk/src/status-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
Expand Down Expand Up @@ -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);
Expand Down
Loading