From 83c8b639b48d4d8ffc00058983fb684697a97bda Mon Sep 17 00:00:00 2001 From: bywura Date: Wed, 25 Nov 2026 14:08:16 +0100 Subject: [PATCH] fix(tlock): bound Quicknet beacon response size MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Quicknet responses were parsed without a byte limit because drand-client reads response bodies in full before JSON parsing. Route chain-info and beacon requests through a streaming 64 KiB cap so an oversized response is aborted before parsing, while keeping the existing response validation and cryptographic checks unchanged. Adds offline boundary tests with an injected fake fetch for exactly-at-limit, one-byte-over, declared Content-Length, and chunked bodies. Closes #664 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- docs/LIMITATIONS.md | 1 + packages/tlock/package.json | 6 +- packages/tlock/src/http.test.ts | 119 ++++++++++++++++++++++++++++++++ packages/tlock/src/http.ts | 118 +++++++++++++++++++++++++++++++ packages/tlock/src/index.ts | 6 ++ packages/tlock/src/quicknet.ts | 58 ++++++++++++++-- 6 files changed, 301 insertions(+), 7 deletions(-) create mode 100644 packages/tlock/src/http.test.ts create mode 100644 packages/tlock/src/http.ts diff --git a/docs/LIMITATIONS.md b/docs/LIMITATIONS.md index ca72aa3c..3507a1f7 100644 --- a/docs/LIMITATIONS.md +++ b/docs/LIMITATIONS.md @@ -40,6 +40,7 @@ Round receipts (`docs/RECEIPTS.md`) are **offline only** — the verifier checks ## Operational - Drand quicknet must publish round R for reveal to open; keeper can void after grace if R never arrives. +- Quicknet HTTP responses are capped at 64 KiB (`MAX_DRAND_RESPONSE_BYTES`); an oversized response is aborted before JSON parsing. - Temporary storage expires after the reveal window — seals are not kept forever by design. - Mainnet wasm upload requires substantial XLM for resource fees (~30+ XLM observed). diff --git a/packages/tlock/package.json b/packages/tlock/package.json index ba82bb3b..71aea3c1 100644 --- a/packages/tlock/package.json +++ b/packages/tlock/package.json @@ -20,9 +20,9 @@ }, "main": "src/index.ts", "scripts": { - "test": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/seal.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts", - "test:quicknet": "node --import tsx --test src/quicknet.test.ts", - "test:unit": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/freshness.test.ts src/quicknet.test.ts src/validate.test.ts src/window.test.ts", + "test": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/seal.test.ts src/freshness.test.ts src/quicknet.test.ts src/http.test.ts src/validate.test.ts src/window.test.ts", + "test:quicknet": "node --import tsx --test src/quicknet.test.ts src/http.test.ts", + "test:unit": "node --import tsx --test src/commitment.test.ts src/payload.test.ts src/auditor.test.ts src/auditor-recovery-cli.test.ts src/bls.test.ts src/freshness.test.ts src/quicknet.test.ts src/http.test.ts src/validate.test.ts src/window.test.ts", "test:seal": "node --import tsx --test src/seal.test.ts", "recover:identities": "node --import tsx src/recover-identities.cli.ts", "typecheck": "tsc --noEmit -p tsconfig.json" diff --git a/packages/tlock/src/http.test.ts b/packages/tlock/src/http.test.ts new file mode 100644 index 00000000..d974aecd --- /dev/null +++ b/packages/tlock/src/http.test.ts @@ -0,0 +1,119 @@ +// Copyright (c) 2026 Sub Rosa contributors +// Boundary tests for the bounded Quicknet HTTP layer. No network: every test +// supplies a fake `fetch`, so the exact byte ceiling can be exercised offline. + +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + DrandResponseTooLargeError, + MAX_DRAND_RESPONSE_BYTES, + fetchDrandJson, + type FetchLike, +} from "./http.js"; +import { chainInfo, quicknet } from "./quicknet.js"; + +/** A JSON document whose UTF-8 encoding is exactly `bytes` long. */ +function jsonOfSize(bytes: number): string { + const empty = JSON.stringify({ data: "" }); + return JSON.stringify({ data: "x".repeat(bytes - empty.length) }); +} + +function fakeFetch(response: Response | (() => Response)): FetchLike { + return async () => (typeof response === "function" ? response() : response); +} + +test("fetchDrandJson accepts a body exactly at the byte ceiling", async () => { + const body = jsonOfSize(MAX_DRAND_RESPONSE_BYTES); + assert.equal(new TextEncoder().encode(body).byteLength, MAX_DRAND_RESPONSE_BYTES); + + const parsed = await fetchDrandJson<{ data: string }>( + "https://api.drand.sh/test", + fakeFetch(new Response(body)), + ); + assert.equal(parsed.data.length, MAX_DRAND_RESPONSE_BYTES - JSON.stringify({ data: "" }).length); +}); + +test("fetchDrandJson rejects a body one byte over the ceiling", async () => { + const body = jsonOfSize(MAX_DRAND_RESPONSE_BYTES + 1); + + await assert.rejects( + fetchDrandJson("https://api.drand.sh/test", fakeFetch(new Response(body))), + (error: unknown) => { + assert.ok(error instanceof DrandResponseTooLargeError); + assert.match(error.message, new RegExp(`${MAX_DRAND_RESPONSE_BYTES}-byte limit`)); + return true; + }, + ); +}); + +test("fetchDrandJson aborts on an oversized Content-Length before reading a body", async () => { + const response = new Response(null, { + headers: { "content-length": String(MAX_DRAND_RESPONSE_BYTES + 1) }, + }); + + await assert.rejects( + fetchDrandJson("https://api.drand.sh/test", fakeFetch(response)), + DrandResponseTooLargeError, + ); +}); + +test("fetchDrandJson stops a chunked body before JSON parsing", async () => { + const encoder = new TextEncoder(); + const chunk = encoder.encode("x".repeat(8 * 1024)); + const stream = new ReadableStream({ + start(controller) { + for (let i = 0; i < 16; i += 1) controller.enqueue(chunk); + controller.close(); + }, + }); + + await assert.rejects( + fetchDrandJson("https://api.drand.sh/test", fakeFetch(new Response(stream))), + (error: unknown) => { + assert.ok(error instanceof DrandResponseTooLargeError); + assert.doesNotMatch(error.message, /JSON/i, "parsing must not be attempted"); + return true; + }, + ); +}); + +test("fetchDrandJson preserves non-2xx handling", async () => { + await assert.rejects( + fetchDrandJson( + "https://api.drand.sh/test", + fakeFetch(new Response("nope", { status: 503 })), + ), + /HTTP 503/, + ); +}); + +test("quicknet bounds chain-info responses too", async () => { + const client = quicknet( + fakeFetch(new Response(jsonOfSize(MAX_DRAND_RESPONSE_BYTES + 1))), + ); + + await assert.rejects(chainInfo(client), DrandResponseTooLargeError); +}); + +test("quicknet keeps chain-info validation after the size check", async () => { + const malformed = JSON.stringify({ period: 3 }); + const client = quicknet(fakeFetch(new Response(malformed))); + + await assert.rejects(chainInfo(client), /malformed drand chain-info/); +}); + +test("quicknet requests the beacon for the requested round", async () => { + const urls: string[] = []; + const client = quicknet(async (input) => { + urls.push(String(input)); + return new Response( + JSON.stringify({ round: 42, randomness: "00", signature: "00" }), + ); + }); + + await client.get(42); + assert.deepEqual(urls, [ + "https://api.drand.sh/52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971/public/42", + ]); +}); diff --git a/packages/tlock/src/http.ts b/packages/tlock/src/http.ts new file mode 100644 index 00000000..d8dbc8c2 --- /dev/null +++ b/packages/tlock/src/http.ts @@ -0,0 +1,118 @@ +// Copyright (c) 2026 Sub Rosa contributors +// Bounded HTTP access for the public Drand beacon endpoint. +// +// Drand responses are small (a quicknet beacon is a few hundred bytes), but the +// endpoint is public and a proxy or replica can return an arbitrarily large +// body. Reading such a body in full before JSON-parsing it would let a remote +// peer exhaust memory in the sealer, keeper, or browser. Every Quicknet +// response therefore goes through `fetchDrandJson`, which enforces a fixed byte +// ceiling *while streaming* and aborts before the body is parsed. + +/** Maximum bytes accepted from any Quicknet HTTP response (64 KiB). */ +export const MAX_DRAND_RESPONSE_BYTES = 64 * 1024; + +/** The subset of `fetch` used by the Drand client; injectable for tests. */ +export type FetchLike = ( + input: string | URL | Request, + init?: RequestInit, +) => Promise; + +/** Thrown when a Drand response exceeds {@link MAX_DRAND_RESPONSE_BYTES}. */ +export class DrandResponseTooLargeError extends Error { + constructor(readonly maxBytes: number, readonly receivedBytes?: number) { + const received = + receivedBytes === undefined ? "" : ` (received at least ${receivedBytes} bytes)`; + super(`drand response exceeds the ${maxBytes}-byte limit${received}`); + this.name = "DrandResponseTooLargeError"; + } +} + +/** + * Fetch a JSON document from `url`, rejecting any response whose body exceeds + * `maxBytes`. The limit is checked against `Content-Length` when present and + * enforced on the streamed body otherwise, so an oversized response is aborted + * before `JSON.parse` ever runs. + */ +export async function fetchDrandJson( + url: string, + fetchImpl: FetchLike = fetch, + maxBytes: number = MAX_DRAND_RESPONSE_BYTES, +): Promise { + const response = await fetchImpl(url, { + headers: { "User-Agent": "sub-rosa-tlock" }, + }); + + if (!response.ok) { + throw new Error(`drand request failed: HTTP ${response.status}`); + } + + const declared = parseContentLength(response.headers.get("content-length")); + if (declared !== undefined && declared > maxBytes) { + await discardBody(response); + throw new DrandResponseTooLargeError(maxBytes, declared); + } + + const text = await readBoundedText(response, maxBytes); + return JSON.parse(text) as T; +} + +function parseContentLength(value: string | null): number | undefined { + if (value === null) return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined; +} + +async function discardBody(response: Response): Promise { + try { + await response.body?.cancel(); + } catch { + // The response may already be consumed or not cancellable; the size error + // is the actionable failure, so cancellation problems are ignored. + } +} + +async function readBoundedText(response: Response, maxBytes: number): Promise { + if (!response.body) { + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength > maxBytes) { + throw new DrandResponseTooLargeError(maxBytes, bytes.byteLength); + } + return new TextDecoder().decode(bytes); + } + + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + + total += value.byteLength; + if (total > maxBytes) { + throw new DrandResponseTooLargeError(maxBytes, total); + } + chunks.push(value); + } + } catch (error) { + await reader.cancel().catch(() => undefined); + throw error; + } finally { + reader.releaseLock(); + } + + return new TextDecoder().decode(concat(chunks, total)); +} + +function concat(chunks: Uint8Array[], total: number): Uint8Array { + if (chunks.length === 1) return chunks[0]; + const out = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + out.set(chunk, offset); + offset += chunk.byteLength; + } + return out; +} diff --git a/packages/tlock/src/index.ts b/packages/tlock/src/index.ts index 57690243..17895c23 100644 --- a/packages/tlock/src/index.ts +++ b/packages/tlock/src/index.ts @@ -46,6 +46,12 @@ export { type OpenedIdentity, } from "./auditor.js"; +export { + MAX_DRAND_RESPONSE_BYTES, + DrandResponseTooLargeError, + type FetchLike, +} from "./http.js"; + export { quicknet, chainInfo, diff --git a/packages/tlock/src/quicknet.ts b/packages/tlock/src/quicknet.ts index a11be6ec..04c0acef 100644 --- a/packages/tlock/src/quicknet.ts +++ b/packages/tlock/src/quicknet.ts @@ -4,11 +4,16 @@ import { fetchBeacon, - quicknetClient, roundAt as drandRoundAt, + type Chain, + type ChainClient, + type ChainInfo, + type ChainOptions, + type RandomnessBeacon, } from "drand-client"; import { drandSignatureToSoroban, verifyDrandSignature } from "./bls.js"; +import { fetchDrandJson, type FetchLike } from "./http.js"; import { assertBeacon, assertChainInfo } from "./validate.js"; import { systemClock, type Clock } from "@sub-rosa/time"; @@ -47,10 +52,55 @@ export function assertQuicknetFixture(info: { } } -export type DrandClient = ReturnType; +export type DrandClient = ChainClient; -export function quicknet(): DrandClient { - return quicknetClient(); +const QUICKNET_CHAIN_URL = `https://api.drand.sh/${QUICKNET_HASH}`; + +const QUICKNET_CHAIN_OPTIONS: ChainOptions = { + disableBeaconVerification: false, + noCache: false, + chainVerificationParams: { + chainHash: QUICKNET_HASH, + publicKey: QUICKNET_FIXTURE.public_key, + }, +}; + +/// A Drand chain client whose HTTP layer caps every response at +/// `MAX_DRAND_RESPONSE_BYTES` (see `http.ts`) before parsing it. +class BoundedQuicknetClient implements ChainClient { + readonly options = QUICKNET_CHAIN_OPTIONS; + + constructor(private readonly fetchImpl: FetchLike = fetch) {} + + chain(): Chain { + return { + baseUrl: QUICKNET_CHAIN_URL, + info: () => + fetchDrandJson(`${QUICKNET_CHAIN_URL}/info`, this.fetchImpl), + }; + } + + get(roundNumber: number): Promise { + return fetchDrandJson( + `${QUICKNET_CHAIN_URL}/public/${roundNumber}`, + this.fetchImpl, + ); + } + + latest(): Promise { + return fetchDrandJson( + `${QUICKNET_CHAIN_URL}/public/latest`, + this.fetchImpl, + ); + } +} + +/** + * The quicknet client used by the sealer, keeper and web app. `fetchImpl` is + * injectable so tests can exercise the response-size ceiling offline. + */ +export function quicknet(fetchImpl: FetchLike = fetch): DrandClient { + return new BoundedQuicknetClient(fetchImpl); } export async function chainInfo(client: DrandClient) {