From 45c9d54772e1d92fc82ecf3f260f96840cd107e8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 10:06:57 -0600 Subject: [PATCH] fix(lab-ops-hub): align redirect policies --- pkgs/lab-ops-hub/container/app.py | 5 ++ pkgs/lab-ops-hub/src/lib.ts | 20 +++++- pkgs/lab-ops-hub/test/lib.test.ts | 62 +++++++++++++++++++ .../test/test_container_validate.py | 21 +++---- 4 files changed, 94 insertions(+), 14 deletions(-) diff --git a/pkgs/lab-ops-hub/container/app.py b/pkgs/lab-ops-hub/container/app.py index f7363742f2..56b892ed39 100644 --- a/pkgs/lab-ops-hub/container/app.py +++ b/pkgs/lab-ops-hub/container/app.py @@ -1178,6 +1178,11 @@ def _apply_userinfo_auth(req): class _ValidatingRedirectHandler(urllib.request.HTTPRedirectHandler): + # Keep in sync with src/lib.ts's fetchFollowingValidatedRedirects: + # max_redirections=10, max_repeats=4, and only 301/302/303/307/308. + max_redirections = 10 + max_repeats = 4 + def redirect_request(self, req, fp, code, msg, headers, newurl): # Follow the validated form, not the raw Location: a redirect # target is validated raw (no Worker normalisation in between), diff --git a/pkgs/lab-ops-hub/src/lib.ts b/pkgs/lab-ops-hub/src/lib.ts index b2de2b3c42..bff219455e 100644 --- a/pkgs/lab-ops-hub/src/lib.ts +++ b/pkgs/lab-ops-hub/src/lib.ts @@ -214,21 +214,32 @@ export function crawlArchiveKey(nowMs: number, unique: string): string { export type ManualFetcher = (url: string) => Promise; +// Keep this policy in sync with container/app.py's _ValidatingRedirectHandler: +// urllib max_redirections=10, max_repeats=4, and only 301/302/303/307/308. +const FOLLOWABLE_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); +const MAX_REDIRECT_REPEATS = 4; + export async function fetchFollowingValidatedRedirects( startUrl: string, fetchFn: ManualFetcher, - maxRedirects = 5, + maxRedirects = 10, ): Promise { const start = validateCrawlUrl(startUrl); if (!start.ok) { throw new Error(`refusing to crawl ${startUrl}: ${start.error}`); } let current = start.url; + const redirectVisits = new Map(); for (let hop = 0; ; hop++) { const res = await fetchFn(current); if (res.status < 300 || res.status >= 400) return res; + if (!FOLLOWABLE_REDIRECT_STATUSES.has(res.status)) { + throw new Error(`unsupported redirect status ${res.status} while crawling ${startUrl}`); + } const location = res.headers.get("location"); - if (!location) return res; + if (!location) { + throw new Error(`redirect response ${res.status} has no Location while crawling ${startUrl}`); + } if (hop >= maxRedirects) { throw new Error(`too many redirects (more than ${maxRedirects}) while crawling ${startUrl}`); } @@ -243,6 +254,11 @@ export async function fetchFollowingValidatedRedirects( throw new Error(`refusing to follow redirect from ${current}: ${target.error}`); } current = target.url; + const visits = redirectVisits.get(current) ?? 0; + if (visits >= MAX_REDIRECT_REPEATS) { + throw new Error(`redirect target repeated more than ${MAX_REDIRECT_REPEATS} times while crawling ${startUrl}`); + } + redirectVisits.set(current, visits + 1); } } diff --git a/pkgs/lab-ops-hub/test/lib.test.ts b/pkgs/lab-ops-hub/test/lib.test.ts index 0844b2b907..5feca00ce2 100644 --- a/pkgs/lab-ops-hub/test/lib.test.ts +++ b/pkgs/lab-ops-hub/test/lib.test.ts @@ -677,6 +677,68 @@ test("fetchFollowingValidatedRedirects bounds the hop count (#460)", async () => await assert.rejects(fetchFollowingValidatedRedirects("https://example.com/loop", fetchFn, 3), /too many redirects/); }); +test("fetchFollowingValidatedRedirects matches urllib's ten-hop boundary", async () => { + const tenHopRoutes: Record = {}; + for (let hop = 0; hop < 10; hop++) { + tenHopRoutes[`https://example.com/hop/${hop}`] = { + status: 302, + location: `/hop/${hop + 1}`, + }; + } + tenHopRoutes["https://example.com/hop/10"] = { status: 200 }; + const tenHop = stubFetcher(tenHopRoutes); + assert.equal((await fetchFollowingValidatedRedirects("https://example.com/hop/0", tenHop.fetchFn)).status, 200); + assert.equal(tenHop.seen.length, 11); + + const elevenHopRoutes: Record = {}; + for (let hop = 0; hop < 11; hop++) { + elevenHopRoutes[`https://example.com/hop/${hop}`] = { + status: 302, + location: `/hop/${hop + 1}`, + }; + } + elevenHopRoutes["https://example.com/hop/11"] = { status: 200 }; + const elevenHop = stubFetcher(elevenHopRoutes); + await assert.rejects( + fetchFollowingValidatedRedirects("https://example.com/hop/0", elevenHop.fetchFn), + /too many redirects/, + ); + assert.equal(elevenHop.seen.length, 11); +}); + +test("fetchFollowingValidatedRedirects follows only urllib redirect statuses", async () => { + for (const status of [301, 302, 303, 307, 308]) { + const { fetchFn } = stubFetcher({ + "https://example.com/start": { status, location: "/final" }, + "https://example.com/final": { status: 200 }, + }); + assert.equal((await fetchFollowingValidatedRedirects("https://example.com/start", fetchFn)).status, 200, `${status}`); + } + + for (const status of [300, 304]) { + const { fetchFn, seen } = stubFetcher({ + "https://example.com/start": { status, location: "/final" }, + "https://example.com/final": { status: 200 }, + }); + await assert.rejects( + fetchFollowingValidatedRedirects("https://example.com/start", fetchFn), + /unsupported redirect status/, + `${status}`, + ); + assert.deepEqual(seen, ["https://example.com/start"], `${status}`); + } +}); + +test("fetchFollowingValidatedRedirects enforces urllib's per-URL repeat limit", async () => { + const { fetchFn, seen } = stubFetcher({ + "https://example.com/a": { status: 302, location: "/b" }, + "https://example.com/b": { status: 302, location: "/a" }, + }); + await assert.rejects(fetchFollowingValidatedRedirects("https://example.com/a", fetchFn), /repeated/); + // urllib permits four redirects to a URL and refuses the fifth. + assert.equal(seen.length, 9); +}); + test("crawlFetcher attaches a fresh AbortSignal, manual redirect and the crawler UA to every hop (#524)", async () => { const seen: RequestInit[] = []; const fetchFn = crawlFetcher(60_000, async (_u, init) => { diff --git a/pkgs/lab-ops-hub/test/test_container_validate.py b/pkgs/lab-ops-hub/test/test_container_validate.py index 7deeaadc93..f83069fde4 100644 --- a/pkgs/lab-ops-hub/test/test_container_validate.py +++ b/pkgs/lab-ops-hub/test/test_container_validate.py @@ -1607,8 +1607,8 @@ def do_GET(self): self.end_headers() self.wfile.write(body) return - if self.path == "/choices": - self.send_response(300) + if self.path in ("/choices", "/not-modified"): + self.send_response(300 if self.path == "/choices" else 304) self.send_header("Location", "/ok") self.send_header("content-length", str(len(body))) self.end_headers() @@ -1660,22 +1660,19 @@ def test_redirect_failures_raise_not_a_302_result(self): # non-followed 3xx). Those are crawl failures, not results — # they must propagate so do_POST returns 502 and the Worker # fallback runs, instead of recording a successful 302 crawl. - # The plain opener stands in for the validating one here: the - # validating handler refuses 127.0.0.1 targets by design, which - # would mask the HTTPError handling under test; the redirect - # mechanics are urllib's either way. import urllib.error - import urllib.request from unittest import mock - plain = urllib.request.build_opener() - with mock.patch.object(app, "_OPENER", plain): - for path in ("/loop", "/hop0", "/choices"): + # Exercise the validating handler and its explicit urllib limits, + # allowing this test server's loopback targets through validation. + with mock.patch.object(app, "validate_crawl_url", side_effect=lambda url: url): + for path in ("/loop", "/hop1", "/choices", "/not-modified"): with self.assertRaises(urllib.error.HTTPError, msg=path) as ctx: self.fetch(path) self.assertTrue(300 <= ctx.exception.code < 400, path) - # Control: a short chain under the limit still succeeds. - status, raw = self.fetch("/hop10") + + # urllib allows exactly ten redirects and rejects the eleventh. + status, raw = self.fetch("/hop2") self.assertEqual(status, 200) self.assertIn(b"Missing Thing", raw)