From 7307ab56dc5237b7ccaa0a2aad4a8f3fdbbdc93f Mon Sep 17 00:00:00 2001 From: repo-worker-code-g Date: Sat, 7 Nov 2026 19:09:43 -0600 Subject: [PATCH] fix(lab-ops-hub): validate the container crawler response shape before archiving or binding (#7018) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit crawlWithContainer returned res.json() under a cast; the crawl route archived the spread result to R2 and bound its fields into the crawls INSERT unvalidated. A JSON null body 500d after the archive write, a JSON string stored an all-null row reported as success, and wrong-typed fields bound as-is — and the designed Worker fallback never triggered, because nothing threw until the damage was done. parseCrawlResult in lib.ts now validates the cross-service response (plain object; string title/excerpt/text, finite-number links/status_code when present). A malformed result throws in crawlWithContainer, so the route falls back to the Worker crawler with container_error set, like any other container failure. Tests: 3 new lib.test.ts cases (well-formed passthrough, non-object bodies, wrong-typed fields); TS suite 106/106 on the branch; the new tests fail against pre-fix lib.ts. Probe replay (~/git/fleet/probe-labops-crawl, real index.ts): control unchanged, all malformed shapes now fall back with sane binds. (Python suite: 2 import errors from a missing idna module, identical on clean main — pre-existing baseline.) --- pkgs/lab-ops-hub/src/index.ts | 15 +++++------ pkgs/lab-ops-hub/src/lib.ts | 41 +++++++++++++++++++++++++++++++ pkgs/lab-ops-hub/test/lib.test.ts | 41 +++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 7 deletions(-) diff --git a/pkgs/lab-ops-hub/src/index.ts b/pkgs/lab-ops-hub/src/index.ts index 3c23f0794d..45b3c45903 100644 --- a/pkgs/lab-ops-hub/src/index.ts +++ b/pkgs/lab-ops-hub/src/index.ts @@ -14,6 +14,7 @@ import { validateMachineBody, validateNoteBody, validateTaskBody, + parseCrawlResult, fileResponseForKey, } from "./lib"; @@ -183,13 +184,13 @@ async function crawlWithContainer(env: Env, url: string) { }), ); if (!res.ok) throw new Error(`container returned ${res.status}: ${(await res.text()).slice(0, 300)}`); - return res.json() as Promise<{ - title?: string; - excerpt?: string; - links?: number; - status_code?: number; - text?: string; - }>; + // The response crosses a service boundary, so validate its shape before + // anything is archived or bound (#7018): a malformed result throws here + // and the route falls back to the Worker crawler, like any other + // container failure. + const parsed = parseCrawlResult(await res.json()); + if (!parsed.ok) throw new Error(`container returned a malformed crawl result: ${parsed.error}`); + return parsed.values; } async function crawlFallback(url: string) { diff --git a/pkgs/lab-ops-hub/src/lib.ts b/pkgs/lab-ops-hub/src/lib.ts index 10bb271ec2..1566003d68 100644 --- a/pkgs/lab-ops-hub/src/lib.ts +++ b/pkgs/lab-ops-hub/src/lib.ts @@ -214,6 +214,47 @@ export function crawlArchiveKey(nowMs: number, unique: string): string { return `crawls/${nowMs}-${unique}.json`; } +// --- Container crawl result validation (#7018) ------------------------------ +// The container crawler is a separate service with its own release cadence +// (CrawlerContainerV2 exists because the original container application +// broke), so its 200 response is a cross-service boundary, not a trusted +// internal value. crawlWithContainer used to return res.json() under a +// type cast, and the route archived and bound the result unvalidated: a +// JSON null body 500'd on the first field read (after the R2 archive was +// already written), a JSON string was archived spread by character index +// and stored as an all-null crawls row, and wrong-typed fields bound +// as-is. A malformed result must instead read as a container failure, so +// the route's existing catch falls back to the Worker crawler. + +export interface CrawlResult { + title?: string; + excerpt?: string; + links?: number; + status_code?: number; + text?: string; +} + +const CRAWL_RESULT_STRING_FIELDS = ["title", "excerpt", "text"] as const; +const CRAWL_RESULT_NUMBER_FIELDS = ["links", "status_code"] as const; + +export function parseCrawlResult(value: unknown): Validated { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return { ok: false, error: "crawl result must be a JSON object" }; + } + const body = value as Record; + for (const field of CRAWL_RESULT_STRING_FIELDS) { + if (body[field] !== undefined && typeof body[field] !== "string") { + return { ok: false, error: `crawl result field ${field} must be a string` }; + } + } + for (const field of CRAWL_RESULT_NUMBER_FIELDS) { + if (body[field] !== undefined && (typeof body[field] !== "number" || !Number.isFinite(body[field]))) { + return { ok: false, error: `crawl result field ${field} must be a number` }; + } + } + return { ok: true, values: body as CrawlResult }; +} + export type ManualFetcher = (url: string) => Promise; // Keep this policy in sync with container/app.py's _ValidatingRedirectHandler: diff --git a/pkgs/lab-ops-hub/test/lib.test.ts b/pkgs/lab-ops-hub/test/lib.test.ts index 9ea11b5a44..95e2a878ad 100644 --- a/pkgs/lab-ops-hub/test/lib.test.ts +++ b/pkgs/lab-ops-hub/test/lib.test.ts @@ -10,6 +10,7 @@ import { fetchFollowingValidatedRedirects, MAX_CRAWL_BODY_BYTES, parseJsonObjectBody, + parseCrawlResult, readResponseTextCapped, uploadKey, validateCrawlUrl, @@ -984,6 +985,46 @@ test("crawlArchiveKey: same-millisecond derivations with distinct uniques never } }); +test("parseCrawlResult passes a well-formed container result through unchanged (#7018)", () => { + const result = { title: "T", excerpt: "E", links: 3, status_code: 200, text: "hello" }; + const parsed = parseCrawlResult(result); + assert.equal(parsed.ok, true); + if (parsed.ok) assert.deepEqual(parsed.values, result); + // Absent optional fields are fine: the route binds ?? null for them. + assert.equal(parseCrawlResult({}).ok, true); + assert.equal(parseCrawlResult({ title: "only a title" }).ok, true); +}); + +test("parseCrawlResult rejects non-object container bodies (#7018)", () => { + // A JSON null used to 500 the route on result.title (after the R2 + // archive write); a JSON string was archived spread by character index + // and stored as an all-null crawls row reported as success. + for (const body of [null, "hello", 42, true, [1, 2, 3]]) { + const parsed = parseCrawlResult(body); + assert.equal(parsed.ok, false, JSON.stringify(body)); + } +}); + +test("parseCrawlResult rejects wrong-typed container fields (#7018)", () => { + // Object values used to throw the raw D1 bind TypeError as a 500; + // wrong-typed scalars (numeric title, string links/status_code) bound + // as-is into the crawls row. + for (const body of [ + { links: { bad: 1 } }, + { title: ["T"] }, + { title: 123 }, + { excerpt: null }, + { text: 42 }, + { links: "3" }, + { status_code: "200" }, + { links: Number.NaN }, + ]) { + const parsed = parseCrawlResult(body); + assert.equal(parsed.ok, false, JSON.stringify(body)); + if (!parsed.ok) assert.match(parsed.error, /crawl result/); + } +}); + test("isMachineNameConflict recognises only the machines.name UNIQUE violation (#2631)", () => { assert.equal(isMachineNameConflict(new Error("UNIQUE constraint failed: machines.name")), true); assert.equal(isMachineNameConflict(new Error("D1_ERROR: UNIQUE constraint failed: machines.name")), true);