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
8 changes: 8 additions & 0 deletions services/drand-tools/fixtures/drand-redirect-beacon.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
8 changes: 8 additions & 0 deletions services/drand-tools/fixtures/drand-redirect-chain-info.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
2 changes: 1 addition & 1 deletion services/drand-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
142 changes: 142 additions & 0 deletions services/drand-tools/src/quicknet.test.ts
Original file line number Diff line number Diff line change
@@ -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));
});
});
65 changes: 61 additions & 4 deletions services/drand-tools/src/quicknet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -21,14 +24,68 @@ export interface Beacon {
signature: string; // compressed G1, hex (48 bytes)
}

export async function getChainInfo(): Promise<ChainInfo> {
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<Response> {
// 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<ChainInfo> {
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<Beacon> {
const res = await fetch(`${API}/${QUICKNET_HASH}/public/${round}`);
export async function getBeacon(
round: number | "latest",
fetchImpl?: FetchImpl,
): Promise<Beacon> {
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;
}
Expand Down
Loading