From 536316c348eddb384faf917233cb641a48e836e9 Mon Sep 17 00:00:00 2001 From: Samet Date: Tue, 24 Nov 2026 22:09:21 +0300 Subject: [PATCH] feat(drand-tools): reject redirected chain-info and beacon requests --- .../fixtures/drand-redirect-beacon.json | 8 + .../fixtures/drand-redirect-chain-info.json | 8 + services/drand-tools/package.json | 2 +- services/drand-tools/src/quicknet.test.ts | 142 ++++++++++++++++++ services/drand-tools/src/quicknet.ts | 65 +++++++- 5 files changed, 220 insertions(+), 5 deletions(-) create mode 100644 services/drand-tools/fixtures/drand-redirect-beacon.json create mode 100644 services/drand-tools/fixtures/drand-redirect-chain-info.json create mode 100644 services/drand-tools/src/quicknet.test.ts diff --git a/services/drand-tools/fixtures/drand-redirect-beacon.json b/services/drand-tools/fixtures/drand-redirect-beacon.json new file mode 100644 index 00000000..ad05c263 --- /dev/null +++ b/services/drand-tools/fixtures/drand-redirect-beacon.json @@ -0,0 +1,8 @@ +{ + "description": "HTTP redirect from the Drand beacon endpoint", + "resource": "beacon", + "status": 307, + "headers": { + "Location": "https://evil.example/steal?beacon=secret-round" + } +} diff --git a/services/drand-tools/fixtures/drand-redirect-chain-info.json b/services/drand-tools/fixtures/drand-redirect-chain-info.json new file mode 100644 index 00000000..697c6355 --- /dev/null +++ b/services/drand-tools/fixtures/drand-redirect-chain-info.json @@ -0,0 +1,8 @@ +{ + "description": "HTTP redirect from the Drand chain-info endpoint", + "resource": "chain-info", + "status": 302, + "headers": { + "Location": "https://attacker.example/exfiltrate?token=secret-chain" + } +} diff --git a/services/drand-tools/package.json b/services/drand-tools/package.json index b0c1d6f1..0a101713 100644 --- a/services/drand-tools/package.json +++ b/services/drand-tools/package.json @@ -11,7 +11,7 @@ }, "scripts": { "validate": "tsx src/index.ts", - "test": "node --import tsx --test src/encode.test.ts src/parity.test.ts", + "test": "node --import tsx --test src/encode.test.ts src/parity.test.ts src/quicknet.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { diff --git a/services/drand-tools/src/quicknet.test.ts b/services/drand-tools/src/quicknet.test.ts new file mode 100644 index 00000000..6475556b --- /dev/null +++ b/services/drand-tools/src/quicknet.test.ts @@ -0,0 +1,142 @@ +// Copyright (c) 2026 Sub Rosa contributors +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { normalizeError } from "@sub-rosa/logging/errors"; +import { createLogger } from "@sub-rosa/logging"; + +import { + DRAND_HTTP_REDIRECT_CATEGORY, + DrandRedirectError, + getBeacon, + getChainInfo, + isHttpRedirectStatus, +} from "./quicknet.js"; + +const FIXTURES_DIR = join(dirname(fileURLToPath(import.meta.url)), "../fixtures"); + +interface RedirectFixture { + description: string; + resource: "chain-info" | "beacon"; + status: number; + headers: { Location: string }; +} + +function loadRedirectFixture(name: string): RedirectFixture { + return JSON.parse(readFileSync(join(FIXTURES_DIR, name), "utf8")) as RedirectFixture; +} + +function redirectFetch(fixture: RedirectFixture): typeof fetch { + return async (_url, init) => { + assert.equal(init?.redirect, "manual"); + return new Response("", { + status: fixture.status, + headers: fixture.headers, + }); + }; +} + +describe("Drand HTTP redirect rejection", () => { + it("disables automatic redirects for chain-info fetches", async () => { + let seenRedirect: RequestRedirect | undefined; + await getChainInfo(async (_url, init) => { + seenRedirect = init?.redirect; + return new Response( + JSON.stringify({ + public_key: "ab", + period: 3, + genesis_time: 1, + hash: "h", + schemeID: "bls-unchained-g1-rfc9380", + }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }); + assert.equal(seenRedirect, "manual"); + }); + + it("disables automatic redirects for beacon fetches", async () => { + let seenRedirect: RequestRedirect | undefined; + await getBeacon(1, async (_url, init) => { + seenRedirect = init?.redirect; + return new Response( + JSON.stringify({ round: 1, randomness: "aa", signature: "bb" }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }); + assert.equal(seenRedirect, "manual"); + }); + + it("rejects chain-info redirects with one stable error category and no Location", async () => { + const fixture = loadRedirectFixture("drand-redirect-chain-info.json"); + await assert.rejects( + () => getChainInfo(redirectFetch(fixture)), + (error: unknown) => { + assert.ok(error instanceof DrandRedirectError); + assert.equal(error.category, DRAND_HTTP_REDIRECT_CATEGORY); + assert.equal(error.category, "http_redirect"); + assert.equal(error.resource, "chain-info"); + assert.equal(error.status, fixture.status); + assert.ok(isHttpRedirectStatus(error.status)); + assert.ok(!error.message.includes(fixture.headers.Location)); + assert.ok(!error.message.includes("attacker.example")); + assert.ok(!error.message.includes("secret-chain")); + assert.ok(!JSON.stringify(error).includes(fixture.headers.Location)); + assert.ok(!("location" in error)); + assert.ok(!("Location" in error)); + return true; + }, + ); + }); + + it("rejects beacon redirects with the same stable category and no Location", async () => { + const fixture = loadRedirectFixture("drand-redirect-beacon.json"); + await assert.rejects( + () => getBeacon("latest", redirectFetch(fixture)), + (error: unknown) => { + assert.ok(error instanceof DrandRedirectError); + assert.equal(error.category, DRAND_HTTP_REDIRECT_CATEGORY); + assert.equal(error.resource, "beacon"); + assert.equal(error.status, fixture.status); + assert.ok(!error.message.includes(fixture.headers.Location)); + assert.ok(!error.message.includes("evil.example")); + assert.ok(!error.message.includes("secret-round")); + assert.ok(!JSON.stringify(error).includes("evil.example")); + return true; + }, + ); + }); + + it("uses one category for every 3xx status", () => { + const categories = [301, 302, 303, 307, 308].map( + (status) => new DrandRedirectError("beacon", status).category, + ); + assert.ok(categories.every((c) => c === DRAND_HTTP_REDIRECT_CATEGORY)); + }); + + it("does not include Location headers in diagnostic logs", () => { + const fixture = loadRedirectFixture("drand-redirect-beacon.json"); + const error = DrandRedirectError.fromResponse( + "beacon", + new Response("", { status: fixture.status, headers: fixture.headers }), + ); + const lines: string[] = []; + const diagnostics = createLogger("services.drand-tools.src.quicknet.test", { + sink: (line) => { + lines.push(line); + }, + }); + diagnostics.error(error.category, "drand fetch redirected", { + err: normalizeError(error), + }); + const joined = lines.join("\n"); + assert.ok(joined.includes(DRAND_HTTP_REDIRECT_CATEGORY)); + assert.ok(!joined.includes(fixture.headers.Location)); + assert.ok(!joined.includes("evil.example")); + assert.ok(!joined.includes("secret-round")); + assert.ok(!/location/i.test(joined)); + }); +}); diff --git a/services/drand-tools/src/quicknet.ts b/services/drand-tools/src/quicknet.ts index 768a4c52..c27ca522 100644 --- a/services/drand-tools/src/quicknet.ts +++ b/services/drand-tools/src/quicknet.ts @@ -7,6 +7,9 @@ export const QUICKNET_HASH = const API = process.env.DRAND_API_URL ?? "https://api.drand.sh"; +/** Stable error category for every HTTP 3xx / opaque redirect from Drand HTTP. */ +export const DRAND_HTTP_REDIRECT_CATEGORY = "http_redirect" as const; + export interface ChainInfo { public_key: string; // compressed G2, hex (96 bytes) period: number; // seconds @@ -21,14 +24,68 @@ export interface Beacon { signature: string; // compressed G1, hex (48 bytes) } -export async function getChainInfo(): Promise { - const res = await fetch(`${API}/${QUICKNET_HASH}/info`); +/** True for HTTP 3xx statuses that would otherwise trigger a redirect. */ +export function isHttpRedirectStatus(status: number): boolean { + return status >= 300 && status < 400; +} + +/** + * Raised when a Drand chain-info or beacon fetch receives a redirect instead of + * following it. The `Location` header value is never included in the message, + * on the error object, or in any diagnostic payload derived from it. + */ +export class DrandRedirectError extends Error { + readonly name = "DrandRedirectError"; + /** One stable category for every 3xx / opaque redirect response. */ + readonly category = DRAND_HTTP_REDIRECT_CATEGORY; + readonly status: number; + readonly resource: "chain-info" | "beacon"; + + constructor(resource: "chain-info" | "beacon", status: number) { + const label = status === 0 ? "opaque" : String(status); + super(`drand ${resource} request redirected (${label})`); + this.status = status; + this.resource = resource; + } + + /** Build an error from a redirect response without echoing Location. */ + static fromResponse(resource: "chain-info" | "beacon", res: Response): DrandRedirectError { + const status = res.type === "opaqueredirect" && res.status === 0 ? 0 : res.status; + return new DrandRedirectError(resource, status); + } +} + +type FetchImpl = typeof fetch; + +async function fetchDrand( + url: string, + resource: "chain-info" | "beacon", + fetchImpl: FetchImpl = globalThis.fetch, +): Promise { + // Never follow redirects: trust only the configured endpoint, not an + // intermediary-selected Location destination. + const res = await fetchImpl(url, { redirect: "manual" }); + if (res.type === "opaqueredirect" || isHttpRedirectStatus(res.status)) { + throw DrandRedirectError.fromResponse(resource, res); + } + return res; +} + +export async function getChainInfo(fetchImpl?: FetchImpl): Promise { + const res = await fetchDrand(`${API}/${QUICKNET_HASH}/info`, "chain-info", fetchImpl); if (!res.ok) throw new Error(`info HTTP ${res.status}`); return (await res.json()) as ChainInfo; } -export async function getBeacon(round: number | "latest"): Promise { - const res = await fetch(`${API}/${QUICKNET_HASH}/public/${round}`); +export async function getBeacon( + round: number | "latest", + fetchImpl?: FetchImpl, +): Promise { + const res = await fetchDrand( + `${API}/${QUICKNET_HASH}/public/${round}`, + "beacon", + fetchImpl, + ); if (!res.ok) throw new Error(`beacon ${round} HTTP ${res.status}`); return (await res.json()) as Beacon; }