Skip to content
Merged
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
15 changes: 8 additions & 7 deletions pkgs/lab-ops-hub/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
validateMachineBody,
validateNoteBody,
validateTaskBody,
parseCrawlResult,
fileResponseForKey,
} from "./lib";

Expand Down Expand Up @@ -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) {
Expand Down
41 changes: 41 additions & 0 deletions pkgs/lab-ops-hub/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<CrawlResult> {
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<string, unknown>;
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<Response>;

// Keep this policy in sync with container/app.py's _ValidatingRedirectHandler:
Expand Down
41 changes: 41 additions & 0 deletions pkgs/lab-ops-hub/test/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
fetchFollowingValidatedRedirects,
MAX_CRAWL_BODY_BYTES,
parseJsonObjectBody,
parseCrawlResult,
readResponseTextCapped,
uploadKey,
validateCrawlUrl,
Expand Down Expand Up @@ -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);
Expand Down
Loading