From 92eef61842fc60967bc2d74d48e982711420482e Mon Sep 17 00:00:00 2001 From: David Tai <8346495+davidtai@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:45:46 -0600 Subject: [PATCH 1/2] Follow only same-origin and Hugging Face CDN redirects for MiMo prompt fixtures prepare-mimo-prompt-fixtures.py let urllib follow any redirect and refused only a final plain-HTTP URL, so a download could request another host, or a plain-HTTP URL, before the check ran. It now opens each file through OriginRedirect: a redirect is followed only when the target has the scheme, host and port of the URL that answered with it and carries no credentials, or, from https://huggingface.co only, when the target is an HTTPS Hugging Face CDN host on port 443 (hf.co or a name that ends in .hf.co). The Hub answers tokenizer.json at the pinned revision with a 302 to us.aws.cdn.hf.co; the other three files take a same-origin 307. Any other redirect raises ValueError before its target is requested and is not retried. The SHA-256 pins still protect the bytes. The rule lives in scripts/fixture_redirects.py. The image fixture script's curl loop and prepare-prompt-fixtures.py's SameOriginRedirect now use it instead of their own origin comparisons; the latter still refuses a target with a query or fragment. The CI component paths, the release-cache workflow paths and the docs-impact rules name the new module. The self-test drives the script's own redirect handler through urllib with a recording fake origin: same-origin and *.hf.co redirects are followed; plain-HTTP, other-host, other-port, credentialed and suffix-trick targets (hf.co.evil.example, evilhf.co) fail at once, unrequested and unretried; a CDN host cannot redirect onward. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/provider-release-cache.yml | 1 + changelog.d/mimo-prompt-fixture-redirects.md | 10 ++ docs/developer/mimo-prompt-fixtures.md | 7 +- docs/developer/test.md | 28 +++-- scripts/ci-component-paths.py | 2 +- scripts/docs-impact-rules.json | 2 +- scripts/fixture_redirects.py | 48 ++++++++ scripts/prepare-mimo-image-http-fixtures.py | 18 +-- scripts/prepare-mimo-prompt-fixtures.py | 11 +- scripts/prepare-prompt-fixtures.py | 7 +- scripts/test-ci-component-paths.py | 1 + scripts/test-prepare-mimo-prompt-fixtures.py | 112 +++++++++++++++++-- 12 files changed, 205 insertions(+), 42 deletions(-) create mode 100644 changelog.d/mimo-prompt-fixture-redirects.md create mode 100644 scripts/fixture_redirects.py diff --git a/.github/workflows/provider-release-cache.yml b/.github/workflows/provider-release-cache.yml index 45635bcd48..109338a904 100644 --- a/.github/workflows/provider-release-cache.yml +++ b/.github/workflows/provider-release-cache.yml @@ -31,6 +31,7 @@ on: - 'scripts/verify-nemotron-prompt-parity.sh' - 'scripts/prepare-prompt-fixtures.py' - 'scripts/verified_download_cache.py' + - 'scripts/fixture_redirects.py' - 'scripts/test-prepare-prompt-fixtures.py' - 'scripts/run-provider-tests.sh' - 'provider-swift/Tests/ProviderCoreTests/Qwen4StandaloneAdmissionTests.swift' diff --git a/changelog.d/mimo-prompt-fixture-redirects.md b/changelog.d/mimo-prompt-fixture-redirects.md new file mode 100644 index 0000000000..a189e94292 --- /dev/null +++ b/changelog.d/mimo-prompt-fixture-redirects.md @@ -0,0 +1,10 @@ +### MiMo prompt fixture downloads follow only allowed redirects + +`scripts/prepare-mimo-prompt-fixtures.py` now follows a redirect only when the +target keeps the scheme, host and port of the URL that redirected, or when +`https://huggingface.co` redirects over HTTPS to a Hugging Face CDN host +(`hf.co` or a name that ends in `.hf.co`), where the Hub serves +`tokenizer.json`. Any other redirect (another host, another port or plain HTTP) +fails at once, is not retried, and its target is never requested. Before, the +script followed any redirect and refused only a final plain-HTTP URL. The +prompt fixture downloaders now share this rule in `scripts/fixture_redirects.py`. diff --git a/docs/developer/mimo-prompt-fixtures.md b/docs/developer/mimo-prompt-fixtures.md index 1c672e82a8..c8aaef43e4 100644 --- a/docs/developer/mimo-prompt-fixtures.md +++ b/docs/developer/mimo-prompt-fixtures.md @@ -1,6 +1,6 @@ # MiMo prompt fixture reproduction -> Last updated: 2026-10-18 +> Last updated: 2026-11-08 Public MiMo golden-vector checks require pinned metadata and an independent 20-case corpus. Missing inputs are failures, not silently skipped checks. No @@ -22,6 +22,11 @@ weights or executable model code. The unchanged synthetic corpus is checked in at `fixtures/prompt-contract/mimo-v26-additional20.json`; its attribution is in `fixtures/prompt-contract/README-mimo-v26.md`. An existing output directory, changed input, oversized file or checksum mismatch is a failure, not a skip. +The script follows a same-origin redirect and, from `https://huggingface.co` +only, an HTTPS redirect to a Hugging Face CDN host (`hf.co` or a name that ends +in `.hf.co`), where the Hub serves `tokenizer.json`. Any other redirect fails at +once and its target is never requested; the +[test guide](test.md#public-fixtures-and-private-qualification) states the rule. Alternatively, set `MIMO_PROMPT_ARTIFACT_DIRECTORY` to a metadata-only directory and `MIMO_PROMPT_REFERENCE_VECTORS` to the unchanged20-case JSON file. Both must diff --git a/docs/developer/test.md b/docs/developer/test.md index 055cbceba9..f4c47a0b69 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1285,16 +1285,24 @@ many it downloaded, their bytes and the seconds it took. `scripts/prepare-mimo-prompt-fixtures.py` and `scripts/prepare-mimo-image-http-fixtures.py` apply the same retry rule to each -metadata file, with these differences. The MiMo prompt script refuses a -redirect to plain HTTP but follows a redirect to a different HTTPS host: Hugging -Face serves `tokenizer.json` from its CDN host. It has no total deadline: each -connect and read has a 60 s socket timeout. The image script has a 120 s -deadline for each file, and it classifies curl's exit code: a cut transfer (for -example exit 18 or 56) retries, and an oversize body (63) or a certificate -failure does not. curl does not follow redirects for the image script. The -script follows a redirect only when its scheme, host and port are those of the -requested URL, for at most 10 redirects. A redirect to another origin, plain -HTTP included, fails at once and is not requested. Provisioning failures fail +metadata file, with these differences. The MiMo prompt script has no total +deadline: each connect and read has a 60 s socket timeout. The image script has +a 120 s deadline for each file, and it classifies curl's exit code: a cut +transfer (for example exit 18 or 56) retries, and an oversize body (63) or a +certificate failure does not. curl does not follow redirects for the image +script. + +The three downloaders share one redirect rule (`scripts/fixture_redirects.py`), +for at most 10 redirects. A download follows a redirect only when the target +has the scheme, host and port of the URL that answered with it, and the target +has no credentials. The MiMo prompt script also follows an HTTPS redirect from +`https://huggingface.co` to a Hugging Face CDN host on port 443: `hf.co` or a +name that ends in `.hf.co`. Hugging Face answers `tokenizer.json` at the pinned +revision with a 302 to `us.aws.cdn.hf.co`; the other three metadata files take a +same-origin 307. The pinned SHA-256 values still protect the bytes. Any other +redirect (another host, another port or plain HTTP) fails at once, is not +retried, and its target is never requested. The prompt-asset downloader also +refuses a redirect target with a query or fragment. Provisioning failures fail qualification; they must not silently skip vectors. Public validation means **this implementation matches those fixed expectations**. diff --git a/scripts/ci-component-paths.py b/scripts/ci-component-paths.py index 8af68bbeee..168cd24155 100644 --- a/scripts/ci-component-paths.py +++ b/scripts/ci-component-paths.py @@ -33,7 +33,7 @@ "scripts/provider-test-shard-weights.json", "scripts/cluster-test-plan.py", "scripts/cluster-stage-content-inventory.py", "scripts/swift_test_lock_retry.py", - "scripts/prepare-mimo-*-fixtures.py", "scripts/verified_download_cache.py", + "scripts/prepare-mimo-*-fixtures.py", "scripts/verified_download_cache.py", "scripts/fixture_redirects.py", "scripts/verify-*-prompt-parity.sh", "scripts/prepare-prompt-fixtures.py", "scripts/test-prepare-prompt-fixtures.py", "scripts/verify-prompt-parity.sh", "scripts/test-qwen4-packaged-resources.py", diff --git a/scripts/docs-impact-rules.json b/scripts/docs-impact-rules.json index a5228f9b8b..9a7284b1b8 100644 --- a/scripts/docs-impact-rules.json +++ b/scripts/docs-impact-rules.json @@ -70,7 +70,7 @@ }, { "name": "public fixtures and qualification", - "source_patterns": ["fixtures/**", "provider-swift/Tests/ProviderCoreTests/Fixtures/**", "scripts/verify*prompt*", "scripts/prepare-prompt-fixtures.py", "scripts/prepare-mimo*", "scripts/generate*prompt*", "scripts/qualify*", "provider-swift/Tests/test_protocol_fixture_resources.py"], + "source_patterns": ["fixtures/**", "provider-swift/Tests/ProviderCoreTests/Fixtures/**", "scripts/verify*prompt*", "scripts/prepare-prompt-fixtures.py", "scripts/prepare-mimo*", "scripts/fixture_redirects.py", "scripts/generate*prompt*", "scripts/qualify*", "provider-swift/Tests/test_protocol_fixture_resources.py"], "docs_any_of": ["docs/developer/test.md", "docs/developer/mimo-prompt-fixtures.md", "docs/developer/serving-performance-qualification.md"] }, { diff --git a/scripts/fixture_redirects.py b/scripts/fixture_redirects.py new file mode 100644 index 0000000000..595addbc7a --- /dev/null +++ b/scripts/fixture_redirects.py @@ -0,0 +1,48 @@ +"""The redirect rule of the fixture download scripts. + +A download follows a redirect only when the target has the origin (scheme, host +and port) of the URL that answered with it, and the target has no credentials. +A caller can allow one more redirect: from https://huggingface.co to an HTTPS +Hugging Face CDN host on port 443, that is `hf.co` or a name that ends in +`.hf.co`. The Hub answers a file stored with Xet or LFS with a 302 to such a +host (for example `us.aws.cdn.hf.co`, `cas-bridge.xethub.hf.co` or +`cdn-lfs-us-1.hf.co`). The pinned SHA-256 of each fixture still protects its +bytes. Every other redirect raises ValueError before its target is requested. +""" + +import urllib.parse +import urllib.request + +DEFAULT_PORTS = {"http": 80, "https": 443} +HUGGING_FACE_HUB = ("https", "huggingface.co", 443) +HUGGING_FACE_CDN_DOMAIN = "hf.co" + + +def origin(url): + parts = urllib.parse.urlsplit(url) + return parts.scheme, parts.hostname, parts.port or DEFAULT_PORTS.get(parts.scheme) + + +def redirect_allowed(source, target, hugging_face_cdn=False): + parts = urllib.parse.urlsplit(target) + if parts.username is not None or parts.password is not None: + return False + if origin(target) == origin(source): + return True + host = parts.hostname or "" + # An exact name or a dot-separated suffix: hf.co.evil.example and evilhf.co do not match. + return (hugging_face_cdn and origin(source) == HUGGING_FACE_HUB + and origin(target) == ("https", host, 443) + and (host == HUGGING_FACE_CDN_DOMAIN or host.endswith("." + HUGGING_FACE_CDN_DOMAIN))) + + +class OriginRedirect(urllib.request.HTTPRedirectHandler): + """A urllib redirect handler that applies redirect_allowed to each hop.""" + + def __init__(self, hugging_face_cdn=False): + self.hugging_face_cdn = hugging_face_cdn + + def redirect_request(self, req, fp, code, msg, headers, newurl): + if not redirect_allowed(req.full_url, newurl, self.hugging_face_cdn): + raise ValueError("fixture download redirected to another origin") + return super().redirect_request(req, fp, code, msg, headers, newurl) diff --git a/scripts/prepare-mimo-image-http-fixtures.py b/scripts/prepare-mimo-image-http-fixtures.py index 14619f643e..ebb29471c0 100644 --- a/scripts/prepare-mimo-image-http-fixtures.py +++ b/scripts/prepare-mimo-image-http-fixtures.py @@ -8,9 +8,9 @@ import subprocess import tempfile import time -import urllib.parse import zlib +from fixture_redirects import redirect_allowed from verified_download_cache import cached SPEC = importlib.util.spec_from_file_location( @@ -27,12 +27,11 @@ # (35), empty reply (52), send (55) and receive (56). Plain `--retry` skips 18 # and 56; `--retry-all-errors` would also retry 4xx and an oversize body (63). TRANSIENT_CURL_EXITS = {6, 7, 16, 18, 28, 35, 52, 55, 56, 92} -# curl itself never follows a redirect: each hop is checked against the -# requested origin before it is requested, so a fixture download never leaves -# its host. The cap is urllib's, as in prepare-prompt-fixtures.py. +# curl itself never follows a redirect: each hop is checked with +# fixture_redirects.py before it is requested, so a fixture download never +# leaves its host. The cap is urllib's, as in prepare-prompt-fixtures.py. REDIRECT_STATUSES = {"301", "302", "303", "307", "308"} MAX_REDIRECTS = 10 -DEFAULT_PORTS = {"http": 80, "https": 443} class TransientTransfer(ValueError): @@ -51,14 +50,9 @@ def chunk(kind, data): + chunk(b"IDAT", compressed) + chunk(b"IEND", b"")) -def origin(url): - parts = urllib.parse.urlsplit(url) - return parts.scheme, parts.hostname, parts.port or DEFAULT_PORTS.get(parts.scheme) - - def fetch_once(name, size, seconds): url = PINS.BASE_URL + "/" + name - requested, stop = origin(url), time.monotonic() + seconds + stop = time.monotonic() + seconds with tempfile.TemporaryDirectory() as directory: body = Path(directory) / "body" for _ in range(MAX_REDIRECTS + 1): @@ -78,7 +72,7 @@ def fetch_once(name, size, seconds): if status not in REDIRECT_STATUSES or not location: break # A plain-HTTP downgrade is a different origin too. - if origin(location) != requested: + if not redirect_allowed(url, location): raise ValueError("MiMo HTTP fixture redirected to another origin: " + name) url = location else: diff --git a/scripts/prepare-mimo-prompt-fixtures.py b/scripts/prepare-mimo-prompt-fixtures.py index 32d628744d..73b83baa2f 100644 --- a/scripts/prepare-mimo-prompt-fixtures.py +++ b/scripts/prepare-mimo-prompt-fixtures.py @@ -8,9 +8,9 @@ import stat import time import urllib.error -import urllib.parse import urllib.request +from fixture_redirects import OriginRedirect from verified_download_cache import cached REPOSITORY = "XiaomiMiMo/MiMo-V2.6-Flash-RL" @@ -25,6 +25,9 @@ MAXIMUM = 128 * 1024 * 1024 DOWNLOAD_ATTEMPTS = 3 RETRY_BACKOFF_SECONDS = (1, 3) +# The Hub answers tokenizer.json at REVISION with a 302 to its CDN +# (us.aws.cdn.hf.co); the others take a same-origin 307. See fixture_redirects.py. +OPENER = urllib.request.build_opener(OriginRedirect(hugging_face_cdn=True)) class TransientTransfer(ValueError): @@ -40,7 +43,7 @@ def checked_bytes(data, expected, maximum): def retryable(error): # Retry only a failed or cut transfer: a TLS, socket or connection error, # a timeout, an incomplete body, a short body or an HTTP 5xx. A wrong - # digest, an oversize body, an insecure redirect or a 4xx stays final. + # digest, an oversize body, a refused redirect or a 4xx stays final. # HTTPError is an OSError subclass: test it first. if isinstance(error, urllib.error.HTTPError): return error.code >= 500 @@ -49,9 +52,7 @@ def retryable(error): def fetch_once(url): request = urllib.request.Request(url, headers={"User-Agent": "darkbloom-fixture-check/1"}) - with urllib.request.urlopen(request, timeout=60) as response: - if urllib.parse.urlsplit(response.geturl()).scheme != "https": - raise ValueError("insecure fixture redirect") + with OPENER.open(request, timeout=60) as response: declared = response.headers.get("Content-Length") data = response.read(MAXIMUM + 1) # http.client returns a short body without error when the connection ends diff --git a/scripts/prepare-prompt-fixtures.py b/scripts/prepare-prompt-fixtures.py index 7fff38d944..28d2159230 100644 --- a/scripts/prepare-prompt-fixtures.py +++ b/scripts/prepare-prompt-fixtures.py @@ -21,6 +21,7 @@ import urllib.parse import urllib.request +from fixture_redirects import OriginRedirect from verified_download_cache import restore_file, store_file MAX_MANIFEST_BYTES = 1 << 20 @@ -153,11 +154,9 @@ def https_url(value): return parsed -class SameOriginRedirect(urllib.request.HTTPRedirectHandler): +class SameOriginRedirect(OriginRedirect): def redirect_request(self, req, fp, code, msg, headers, newurl): - old, new = urllib.parse.urlsplit(req.full_url), https_url(newurl) - if (old.scheme, old.netloc) != (new.scheme, new.netloc): - raise ValueError("cross-origin artifact redirect") + https_url(newurl) return super().redirect_request(req, fp, code, msg, headers, newurl) diff --git a/scripts/test-ci-component-paths.py b/scripts/test-ci-component-paths.py index 5ffad5724e..16d0c79b25 100644 --- a/scripts/test-ci-component-paths.py +++ b/scripts/test-ci-component-paths.py @@ -93,6 +93,7 @@ def test_component_and_shared_dependency_matrix(self): "scripts/run-provider-tests.sh": {"provider"}, "scripts/provider-ci-cold-retry.sh": {"provider", "cluster"}, "scripts/verified_download_cache.py": {"provider"}, + "scripts/fixture_redirects.py": {"provider"}, "scripts/provider-test-shards.py": {"provider"}, "scripts/cluster-test-plan.py": {"provider", "cluster"}, "scripts/swift_test_lock_retry.py": {"provider", "cluster"}, diff --git a/scripts/test-prepare-mimo-prompt-fixtures.py b/scripts/test-prepare-mimo-prompt-fixtures.py index aea20ce943..ec352878a7 100644 --- a/scripts/test-prepare-mimo-prompt-fixtures.py +++ b/scripts/test-prepare-mimo-prompt-fixtures.py @@ -1,13 +1,20 @@ #!/usr/bin/env python3 """Offline tests of exact-byte metadata setup; no model or credential access.""" +import copy +import email.message import hashlib import importlib.util +import io from pathlib import Path import ssl import tempfile import unittest from unittest.mock import patch import urllib.error +import urllib.request +import urllib.response + +import fixture_redirects SPEC = importlib.util.spec_from_file_location("fixture_setup", Path(__file__).with_name("prepare-mimo-prompt-fixtures.py")) SETUP = importlib.util.module_from_spec(SPEC) @@ -17,8 +24,8 @@ class Response: """A Hub response whose body may end early or fail as a cut TLS stream does.""" - def __init__(self, body, declared=None, url="https://huggingface.co/x", error=None): - self.body, self.url, self.error = body, url, error + def __init__(self, body, declared=None, error=None): + self.body, self.error = body, error self.headers = {} if declared is None else {"Content-Length": str(declared)} def __enter__(self): @@ -27,9 +34,6 @@ def __enter__(self): def __exit__(self, *_): return False - def geturl(self): - return self.url - def read(self, size): if self.error is not None: raise self.error @@ -40,6 +44,32 @@ def ssl_eof(): return ssl.SSLEOFError(8, "[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol") +class Origins(urllib.request.BaseHandler): + """Answers every HTTP and HTTPS request from a fixed route table and records it. + + The script's own redirect handler runs on these answers, as it does on the Hub's. + """ + + handler_order = 100 # Before urllib's own HTTP and HTTPS handlers. + + def __init__(self, routes): + self.routes, self.requested = routes, [] + + def answer(self, request): + self.requested.append(request.full_url) + status, value = self.routes[request.full_url] + headers = email.message.Message() + body = value if status == 200 else b"" + if status != 200: + headers["Location"] = value + headers["Content-Length"] = str(len(body)) + response = urllib.response.addinfourl(io.BytesIO(body), headers, request.full_url, status) + response.msg = "OK" if status == 200 else "Found" + return response + + http_open = https_open = answer + + class FixtureSetupTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() @@ -127,12 +157,79 @@ def test_changed_corpus_fails_before_download(self): SETUP.prepare(self.root / "metadata", self.corpus, lambda _: self.fail("network must not run")) def test_unknown_names_cannot_download_weights(self): - with patch.object(SETUP.urllib.request, "urlopen", side_effect=AssertionError("network")): + with patch.object(SETUP.OPENER, "open", side_effect=AssertionError("network")): with self.assertRaises(ValueError): SETUP.public_metadata("model.safetensors") def network(self, *outcomes): - return patch.object(SETUP.urllib.request, "urlopen", side_effect=list(outcomes)) + return patch.object(SETUP.OPENER, "open", side_effect=list(outcomes)) + + def redirected(self, location, *routes): + """Fetch the first pinned file through the script's redirect handler. + + The Hub answers its URL with a 302 to location; routes answer the later + hops. self.requested keeps every URL that was requested, in order. + """ + name = next(iter(self.payloads)) + url = f"https://huggingface.co/{SETUP.REPOSITORY}/resolve/{SETUP.REVISION}/{name}" + origins = Origins({url: (302, location), **dict(routes)}) + self.requested = origins.requested + redirects = next(h for h in SETUP.OPENER.handlers if isinstance(h, SETUP.OriginRedirect)) + opener = urllib.request.build_opener(copy.copy(redirects), origins) + with patch.object(SETUP, "OPENER", opener), patch.object(SETUP.time, "sleep") as sleep: + try: + return SETUP.public_metadata(name) + finally: + sleep.assert_not_called() + + def test_same_origin_and_hugging_face_cdn_redirects_are_followed(self): + data = next(iter(self.payloads.values())) + hub = "https://huggingface.co" + cases = { + "same-origin resolve cache": f"{hub}/api/resolve-cache/models/x/config.json?etag=1", + "same origin, explicit port": "https://huggingface.co:443/api/resolve-cache/x", + "Xet bridge CDN": "https://us.aws.cdn.hf.co/xet-bridge-us/a/b?Expires=1&Signature=s", + "Xet CAS bridge": "https://cas-bridge.xethub.hf.co/xet-bridge-us/a/b?X-Amz-Signature=s", + "LFS CDN": "https://cdn-lfs-us-1.hf.co/repos/a/b?Expires=1", + "CDN apex": "https://hf.co/a", + } + for case, location in cases.items(): + with self.subTest(case=case): + self.assertEqual(self.redirected(location, (location, (200, data))), data) + self.assertEqual(self.requested[1:], [location]) + + def test_other_redirects_fail_at_once_without_requesting_the_target(self): + cases = { + "plain-HTTP CDN": "http://us.aws.cdn.hf.co/xet-bridge-us/a", + "plain-HTTP downgrade": "http://huggingface.co/a", + "another host": "https://evil.example/a", + "another port": "https://huggingface.co:8443/a", + "CDN on another port": "https://us.aws.cdn.hf.co:8443/a", + "CDN with credentials": "https://user:secret@us.aws.cdn.hf.co/a", + "CDN name as a prefix": "https://hf.co.evil.example/a", + "CDN name without a dot": "https://evilhf.co/a", + "Hub name as a CDN": "https://huggingface.co.hf.co.evil.example/a", + } + for case, location in cases.items(): + with self.subTest(case=case): + with self.assertRaisesRegex(ValueError, "another origin"): + self.redirected(location) + # The target is never requested, and redirected() asserts no retry. + self.assertEqual(len(self.requested), 1) + + def test_the_cdn_allowance_covers_only_the_hub_hop(self): + cdn = "https://us.aws.cdn.hf.co/xet-bridge-us/a" + # A CDN host may not send the download on to another host, CDN or not. + for onward in ("https://evil.example/a", "https://cas-bridge.xethub.hf.co/a"): + with self.subTest(onward=onward): + with self.assertRaisesRegex(ValueError, "another origin"): + self.redirected(cdn, (cdn, (302, onward))) + self.assertEqual(self.requested[1:], [cdn]) + # Only a redirect from https://huggingface.co may reach a CDN host. + for source in ("http://huggingface.co/a", "https://huggingface.co:8443/a", "https://hf.co/a", + "https://models.darkbloom.ai/a"): + with self.subTest(source=source): + self.assertFalse(fixture_redirects.redirect_allowed(source, cdn, hugging_face_cdn=True)) def test_cut_transfers_are_retried_with_backoff(self): name = next(iter(self.payloads)) @@ -170,7 +267,6 @@ def test_integrity_size_redirect_and_client_failures_are_not_retried(self): cases = { "full-size wrong digest": (Response(b"x" * len(data), len(data)), SETUP.MAXIMUM), "oversize body": (Response(b"x" * 9, 20), 8), - "insecure redirect": (Response(data, len(data), url="http://huggingface.co/x"), SETUP.MAXIMUM), "HTTP 404": (urllib.error.HTTPError("https://huggingface.co/x", 404, "Not Found", {}, None), SETUP.MAXIMUM), } From f42e459f92b798261c81cdcf571c7595ffcc5dd2 Mon Sep 17 00:00:00 2001 From: David Tai <8346495+davidtai@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:49:10 -0600 Subject: [PATCH 2/2] Refactor pass: return early outside the Hub hop; compare final prompt-asset origins the same way The refactor reviewer's cleanups: redirect_allowed returns early when the CDN allowance is off or the source is not the Hub, and the constant is named HUGGING_FACE_HUB_ORIGIN; the test says why it copies the handler. prepare-prompt-fixtures.py compared the final response with (scheme, netloc) while each hop now compares (scheme, host, port with its default). It now uses fixture_redirects.origin for both, so a same-origin hop with an explicit :443 is not refused afterwards. Co-Authored-By: Claude Opus 5.5 --- scripts/fixture_redirects.py | 7 ++++--- scripts/prepare-prompt-fixtures.py | 6 +++--- scripts/test-prepare-mimo-prompt-fixtures.py | 1 + 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/scripts/fixture_redirects.py b/scripts/fixture_redirects.py index 595addbc7a..225bbccf0a 100644 --- a/scripts/fixture_redirects.py +++ b/scripts/fixture_redirects.py @@ -14,7 +14,7 @@ import urllib.request DEFAULT_PORTS = {"http": 80, "https": 443} -HUGGING_FACE_HUB = ("https", "huggingface.co", 443) +HUGGING_FACE_HUB_ORIGIN = ("https", "huggingface.co", 443) HUGGING_FACE_CDN_DOMAIN = "hf.co" @@ -29,10 +29,11 @@ def redirect_allowed(source, target, hugging_face_cdn=False): return False if origin(target) == origin(source): return True + if not hugging_face_cdn or origin(source) != HUGGING_FACE_HUB_ORIGIN: + return False host = parts.hostname or "" # An exact name or a dot-separated suffix: hf.co.evil.example and evilhf.co do not match. - return (hugging_face_cdn and origin(source) == HUGGING_FACE_HUB - and origin(target) == ("https", host, 443) + return (origin(target) == ("https", host, 443) and (host == HUGGING_FACE_CDN_DOMAIN or host.endswith("." + HUGGING_FACE_CDN_DOMAIN))) diff --git a/scripts/prepare-prompt-fixtures.py b/scripts/prepare-prompt-fixtures.py index 28d2159230..176c22d4c0 100644 --- a/scripts/prepare-prompt-fixtures.py +++ b/scripts/prepare-prompt-fixtures.py @@ -21,7 +21,7 @@ import urllib.parse import urllib.request -from fixture_redirects import OriginRedirect +from fixture_redirects import OriginRedirect, origin from verified_download_cache import restore_file, store_file MAX_MANIFEST_BYTES = 1 << 20 @@ -181,8 +181,8 @@ def download_once(opener, url, output, artifact, deadline): raise TransientTransfer("artifact request returned an HTTP server error") if response.status != 200: raise ValueError("artifact request did not return HTTP 200") - original, final = https_url(url), https_url(response.url) - if (original.scheme, original.netloc) != (final.scheme, final.netloc): + https_url(response.url) + if origin(url) != origin(response.url): raise ValueError("cross-origin artifact response") length = response.headers.get("Content-Length") if length is not None and int(length) != artifact["size_bytes"]: diff --git a/scripts/test-prepare-mimo-prompt-fixtures.py b/scripts/test-prepare-mimo-prompt-fixtures.py index ec352878a7..7e5de08a19 100644 --- a/scripts/test-prepare-mimo-prompt-fixtures.py +++ b/scripts/test-prepare-mimo-prompt-fixtures.py @@ -175,6 +175,7 @@ def redirected(self, location, *routes): origins = Origins({url: (302, location), **dict(routes)}) self.requested = origins.requested redirects = next(h for h in SETUP.OPENER.handlers if isinstance(h, SETUP.OriginRedirect)) + # A copy: build_opener rebinds a handler's parent, and the module's opener keeps its own. opener = urllib.request.build_opener(copy.copy(redirects), origins) with patch.object(SETUP, "OPENER", opener), patch.object(SETUP.time, "sleep") as sleep: try: