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
5 changes: 5 additions & 0 deletions pkgs/lab-ops-hub/container/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
20 changes: 18 additions & 2 deletions pkgs/lab-ops-hub/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,21 +214,32 @@ export function crawlArchiveKey(nowMs: number, unique: string): string {

export type ManualFetcher = (url: string) => Promise<Response>;

// 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<Response> {
const start = validateCrawlUrl(startUrl);
if (!start.ok) {
throw new Error(`refusing to crawl ${startUrl}: ${start.error}`);
}
let current = start.url;
const redirectVisits = new Map<string, number>();
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}`);
}
Expand All @@ -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);
}
}

Expand Down
62 changes: 62 additions & 0 deletions pkgs/lab-ops-hub/test/lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, { status: number; location?: string }> = {};
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<string, { status: number; location?: string }> = {};
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) => {
Expand Down
21 changes: 9 additions & 12 deletions pkgs/lab-ops-hub/test/test_container_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)

Expand Down