Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: protect authenticated release redirects (#11339)
Maheswar Kumar76042c0aa354
diff --git a/studio/backend/tests/test_llama_cpp_changelog.py b/studio/backend/tests/test_llama_cpp_changelog.pyindex 597f0ff6e05..d3ffb31b30c 100644--- a/studio/backend/tests/test_llama_cpp_changelog.py+++ b/studio/backend/tests/test_llama_cpp_changelog.py@@ -146,7 +146,7 @@ def test_invalid_repo_never_reaches_github(monkeypatch):nonlocal calledcalled = True- monkeypatch.setattr(changes.urllib.request, "urlopen", fail)+ monkeypatch.setattr(changes, "auth_safe_open", fail)assert changes._fetch_release("owner/repository/extra", "b1") is Noneassert called is False@@ -166,7 +166,7 @@ def test_repo_with_a_dot_segment_never_reaches_github(monkeypatch):nonlocal calledcalled = True- monkeypatch.setattr(changes.urllib.request, "urlopen", fail)+ monkeypatch.setattr(changes, "auth_safe_open", fail)for repo in ("../etc", "owner/..", "..", "../rate_limit"):assert changes._fetch_release(repo, "b1") is None@@ -361,7 +361,7 @@ def test_a_truncated_response_does_not_escape_to_the_caller(monkeypatch):def read(self, size = -1):raise http.client.IncompleteRead(b"partial")- monkeypatch.setattr(changes.urllib.request, "urlopen", lambda *_a, **_k: _Response())+ monkeypatch.setattr(changes, "auth_safe_open", lambda *_a, **_k: _Response())# IncompleteRead is an HTTPException, not an OSError.assert changes._fetch_release_blocking("unslothai/llama.cpp", "b1", 5.0) is None@@ -378,6 +378,6 @@ def test_an_oversized_release_body_is_rejected(monkeypatch):def read(self, size = -1):return b"x" * (changes.MAX_RELEASE_BYTES + 1)- monkeypatch.setattr(changes.urllib.request, "urlopen", lambda *_a, **_k: _Response())+ monkeypatch.setattr(changes, "auth_safe_open", lambda *_a, **_k: _Response())assert changes._fetch_release_blocking("unslothai/llama.cpp", "b1", 5.0) is Nonediff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.pyindex 9171f19bf5f..e5fc64fde4d 100644--- a/studio/backend/tests/test_llama_cpp_freshness.py+++ b/studio/backend/tests/test_llama_cpp_freshness.py@@ -45,6 +45,7 @@ sys.modules.setdefault("structlog", _structlog_stub)import pytestfrom utils import llama_cpp_freshness as fr+from utils.prebuilt import freshness_flow# Helpers.@@ -504,8 +505,6 @@ def test_check_prebuilt_freshness_downgrade_guard(monkeypatch, tmp_path):def test_fetch_latest_release_tag_uses_publish_time(monkeypatch):# Resolves newest by published_at (like the installer), skips drafts/prereleases,# and does NOT just take GitHub's first/`/releases/latest` item.- import urllib.request-class _Resp:def __init__(self, payload):self._p = json.dumps(payload).encode()@@ -539,7 +538,7 @@ def test_fetch_latest_release_tag_uses_publish_time(monkeypatch):"published_at": "2026-06-12T00:00:00Z",},]- monkeypatch.setattr(urllib.request, "urlopen", lambda req, timeout = 5.0: _Resp(payload))+ monkeypatch.setattr(freshness_flow, "auth_safe_open", lambda req, timeout = 5.0: _Resp(payload))assert fr._fetch_latest_release_tag("unslothai/llama.cpp") == "b9596-mix-e6f2453"@@ -746,13 +745,12 @@ def test_release_fetch_cannot_outlive_its_deadline(monkeypatch, fetch):"""urllib applies its timeout per address, so /api/inference/status inherits thatmultiplication without a wall-clock deadline; one stalled connect stands in for thewalk. Both entry points, since they share the fetch."""- import urllib.requestdef _stalls(req, timeout = 5.0):time.sleep(30) # never returns within the deadlineraise AssertionError("deadline did not cut the fetch short")- monkeypatch.setattr(urllib.request, "urlopen", _stalls)+ monkeypatch.setattr(freshness_flow, "auth_safe_open", _stalls)started = time.monotonic()assert getattr(fr, fetch)("unslothai/llama.cpp", timeout = 0.25) is None# Pins the implemented timeout + 1, not merely "faster than the 30s stall".diff --git a/studio/backend/tests/test_sd_cpp_install.py b/studio/backend/tests/test_sd_cpp_install.pyindex 81dbd91f21e..43201d72495 100644--- a/studio/backend/tests/test_sd_cpp_install.py+++ b/studio/backend/tests/test_sd_cpp_install.py@@ -346,7 +346,7 @@ def test_fetch_release_falls_back_to_latest_on_404(monkeypatch):raise urllib.error.HTTPError(url, 404, "not found", None, None)return _Resp()- monkeypatch.setattr(sdmod.urllib.request, "urlopen", fake_urlopen)+ monkeypatch.setattr(sdmod, "auth_safe_open", fake_urlopen)rel = _fetch_release("gone-tag", repo = "leejet/stable-diffusion.cpp")assert rel["tag_name"] == "latest-xyz"assert any("/tags/gone-tag" in c for c in calls) and any(c.endswith("/latest") for c in calls)@@ -357,7 +357,7 @@ def test_fetch_release_propagates_non_404(monkeypatch):url = getattr(req, "full_url", req)raise urllib.error.HTTPError(url, 403, "rate limited", None, None)- monkeypatch.setattr(sdmod.urllib.request, "urlopen", fake_urlopen)+ monkeypatch.setattr(sdmod, "auth_safe_open", fake_urlopen)with pytest.raises(urllib.error.HTTPError):_fetch_release("any-tag")diff --git a/studio/backend/utils/auth_safe.py b/studio/backend/utils/auth_safe.pynew file mode 100644index 00000000000..36983cb3ad7--- /dev/null+++ b/studio/backend/utils/auth_safe.py@@ -0,0 +1,41 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Credential-safe urllib redirects. Stdlib-only: the standalone installers import it+without reaching the rest of the backend."""++import urllib.parse+import urllib.request+++class AuthSafeRedirectHandler(urllib.request.HTTPRedirectHandler):+ """Keep credentials on their original origin and refuse TLS downgrades."""++ @staticmethod+ def _origin(url):+ parts = urllib.parse.urlsplit(url)+ scheme = parts.scheme.lower()+ try:+ port = parts.port+ except ValueError:+ # A fresh object(), never a constant: an unreadable port must compare unequal+ # to every origin including itself, and no caller here catches ValueError.+ return scheme, (parts.hostname or "").lower(), object()+ if port is None:+ port = 443 if scheme == "https" else 80+ return scheme, (parts.hostname or "").lower(), port++ def redirect_request(self, req, fp, code, msg, headers, newurl):+ old = self._origin(req.full_url)+ new = self._origin(newurl)+ if old[0] == "https" and new[0] == "http":+ return None+ result = super().redirect_request(req, fp, code, msg, headers, newurl)+ if result is not None and new != old:+ result.headers.pop("Authorization", None)+ return result+++def auth_safe_open(req, timeout):+ """Open a request without forwarding credentials to another origin."""+ return urllib.request.build_opener(AuthSafeRedirectHandler()).open(req, timeout = timeout)diff --git a/studio/backend/utils/llama_cpp_changelog.py b/studio/backend/utils/llama_cpp_changelog.pyindex e50cb88fac4..c8ab96844cd 100644--- a/studio/backend/utils/llama_cpp_changelog.py+++ b/studio/backend/utils/llama_cpp_changelog.py@@ -17,6 +17,7 @@ from typing import Optionalimport structlog+from utils.auth_safe import auth_safe_openfrom utils.prebuilt.freshness_flow import (RELEASE_CACHE_TTL_SECONDS,RELEASE_FAILURE_CACHE_TTL_SECONDS,@@ -92,7 +93,7 @@ def _fetch_release_blocking(repo: str, tag: str, timeout: float) -> Optional[dicheaders = headers,)try:- with urllib.request.urlopen(request, timeout = timeout) as response:+ with auth_safe_open(request, timeout = timeout) as response:# One byte past the cap: reject an oversized body without buffering it.raw = response.read(MAX_RELEASE_BYTES + 1)if len(raw) > MAX_RELEASE_BYTES:diff --git a/studio/backend/utils/prebuilt/freshness_flow.py b/studio/backend/utils/prebuilt/freshness_flow.pyindex fc6517f3f94..d0458f0291d 100644--- a/studio/backend/utils/prebuilt/freshness_flow.py+++ b/studio/backend/utils/prebuilt/freshness_flow.py@@ -13,6 +13,7 @@ from typing import Any, Callable, Optionalimport structlog+from utils.auth_safe import auth_safe_openfrom utils.update_status import update_checks_disabledlogger = structlog.get_logger(__name__)@@ -130,7 +131,7 @@ def _fetch_newest_published_release_blocking(headers["Authorization"] = f"Bearer {token}"req = urllib.request.Request(url, headers = headers)try:- with urllib.request.urlopen(req, timeout = timeout) as resp:+ with auth_safe_open(req, timeout = timeout) as resp:data = json.loads(resp.read().decode("utf-8"))except (urllib.error.URLError,diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.pyindex a753f2a782e..cf15409f5bc 100644--- a/studio/backend/utils/utils.py+++ b/studio/backend/utils/utils.py@@ -5,8 +5,6 @@import osimport structlog-import urllib.parse-import urllib.requestimport threadingfrom contextvars import ContextVarimport time@@ -17,6 +15,10 @@ from typing import Optionalimport shutilimport tempfilefrom utils.paths.path_utils import is_appledouble_metadata+from . import auth_safe++AuthSafeRedirectHandler = auth_safe.AuthSafeRedirectHandler+auth_safe_open = auth_safe.auth_safe_openlogger = get_logger(__name__)@@ -119,40 +121,6 @@ def hf_proxy_configured() -> bool:return hf_proxy_for_endpoint() is not None-class AuthSafeRedirectHandler(urllib.request.HTTPRedirectHandler):- """Redirect policy for a urllib request carrying a Hub token.-- urllib's default handler copies request headers onto the redirect target, so a- mirror's cross-host 302 hands the token to a host the operator never configured.- Pass this to ``build_opener``, which then leaves out the default. A refusal- surfaces as ``HTTPError`` on the 3xx, which every probe here reads as reachable.- """-- @staticmethod- def _origin(url):- parts = urllib.parse.urlsplit(url)- scheme = parts.scheme.lower()- port = parts.port or (443 if scheme == "https" else 80)- return scheme, (parts.hostname or "").lower(), port-- def redirect_request(self, req, fp, code, msg, headers, newurl):- old = self._origin(req.full_url)- new = self._origin(newurl)- if old[0] == "https" and new[0] == "http":- return None # no TLS downgrade, whatever the target is- result = super().redirect_request(req, fp, code, msg, headers, newurl)- if result is not None and new != old:- # The redirected request, not the caller's: urllib copied req.headers into a- # fresh dict, so the original stays reusable.- result.headers.pop("Authorization", None)- return result---def auth_safe_open(req, timeout):- """The single seam: tests patch THIS, never ``urllib.request.urlopen``."""- return urllib.request.build_opener(AuthSafeRedirectHandler()).open(req, timeout = timeout)--def call_with_deadline(fn,timeout_s: float,diff --git a/studio/install_sd_cpp_prebuilt.py b/studio/install_sd_cpp_prebuilt.pyindex 709a7e45b48..782fd0df5fa 100644--- a/studio/install_sd_cpp_prebuilt.py+++ b/studio/install_sd_cpp_prebuilt.py@@ -26,6 +26,15 @@ import zipfilefrom pathlib import Path, PurePosixPath, PureWindowsPathfrom typing import Optional, Sequence+# Same bootstrap as prebuilt_core.py: today only sd_cpp_backend.py prepares the path.+if __package__:+ from .backend.utils.auth_safe import auth_safe_open+else:+ _STUDIO_DIR = os.path.dirname(os.path.abspath(__file__))+ if _STUDIO_DIR not in sys.path:+ sys.path.insert(0, _STUDIO_DIR)+ from backend.utils.auth_safe import auth_safe_open+# Default source: the Unsloth mirror's CPU/Apple prebuilts (override with UNSLOTH_SD_CPP_REPO). GPU hosts run diffusers, so only CPU/Apple assets are needed.DEFAULT_REPO = "unslothai/stable-diffusion.cpp"UPSTREAM_FALLBACK_REPO = "leejet/stable-diffusion.cpp"@@ -237,7 +246,7 @@ def _fetch_release(req = urllib.request.Request(url, headers = {"Accept": "application/vnd.github+json"})if token:req.add_header("Authorization", f"Bearer {token}")- with urllib.request.urlopen(req, timeout = timeout) as resp: # noqa: S310 (fixed https host)+ with auth_safe_open(req, timeout = timeout) as resp:return json.loads(resp.read().decode("utf-8"))base = f"https://api.github.com/repos/{repo}/releases"diff --git a/studio/prebuilt_core.py b/studio/prebuilt_core.pyindex ed9d9bd5372..c04e2bfc4a7 100644--- a/studio/prebuilt_core.py+++ b/studio/prebuilt_core.py@@ -51,6 +51,16 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Callable, Iterable, Iterator+# Bootstrap studio/ like install_llama_prebuilt.py: an importlib spec load prepares no+# path, so the absolute branch cannot rely on the caller. auth_safe imports only urllib.+if __package__:+ from .backend.utils.auth_safe import AuthSafeRedirectHandler+else:+ _STUDIO_DIR = os.path.dirname(os.path.abspath(__file__))+ if _STUDIO_DIR not in sys.path:+ sys.path.insert(0, _STUDIO_DIR)+ from backend.utils.auth_safe import AuthSafeRedirectHandler+try:from filelock import FileLock, Timeout as FileLockTimeoutexcept ImportError:@@ -389,23 +399,8 @@ def auth_headers(ops: ModuleOps, url: str | None = None) -> dict[str, str]:return headers-class _CrossHostAuthStrippingRedirectHandler(urllib.request.HTTPRedirectHandler):- """Drop Authorization when a redirect leaves the original host.-- huggingface.co redirects downloads to CDN hosts whose signed URLs can reject- a foreign Authorization header; urllib forwards headers across redirects by- default (requests/huggingface_hub strip them).- """-- def redirect_request(self, req, fp, code, msg, headers, newurl):- new_request = super().redirect_request(req, fp, code, msg, headers, newurl)- if new_request is not None and parsed_hostname(newurl) != parsed_hostname(req.full_url):- new_request.headers.pop("Authorization", None)- new_request.unredirected_hdrs.pop("Authorization", None)- return new_request---_URL_OPENER = urllib.request.build_opener(_CrossHostAuthStrippingRedirectHandler())+_CrossHostAuthStrippingRedirectHandler = AuthSafeRedirectHandler+_URL_OPENER = urllib.request.build_opener(AuthSafeRedirectHandler())def github_api_headers(ops: ModuleOps, url: str | None = None) -> dict[str, str]:diff --git a/tests/studio/install/test_auth_safe_redirects.py b/tests/studio/install/test_auth_safe_redirects.pynew file mode 100644index 00000000000..ed904733a80--- /dev/null+++ b/tests/studio/install/test_auth_safe_redirects.py@@ -0,0 +1,334 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exercise authenticated release fetches through real loopback redirects."""++import json+import os+import shutil+import ssl+import subprocess+import sys+import threading+import urllib.error+import urllib.request+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++import pytest++STUDIO = Path(__file__).resolve().parents[3] / "studio"+sys.path.insert(0, str(STUDIO))+sys.path.insert(0, str(STUDIO / "backend"))++import install_sd_cpp_prebuilt as sd+import prebuilt_core+from utils import llama_cpp_changelog+from utils.prebuilt import freshness_flow++TOKEN = "Bearer issue-11103-test-token"++[email protected](scope = "module")+def tls_certificate(tmp_path_factory):+ openssl = shutil.which("openssl")+ if openssl is None:+ pytest.skip("loopback TLS tests need openssl to generate a test certificate")+ root = tmp_path_factory.mktemp("redirect-tls")+ cert, key = root / "cert.pem", root / "key.pem"+ subprocess.run(+ [+ openssl,+ "req",+ "-x509",+ "-newkey",+ "rsa:2048",+ "-nodes",+ "-days",+ "1",+ "-subj",+ "/CN=localhost",+ "-addext",+ "subjectAltName=DNS:localhost,IP:127.0.0.1",+ "-keyout",+ str(key),+ "-out",+ str(cert),+ ],+ check = True,+ capture_output = True,+ )+ return cert, key+++def stdlib_ssl():+ """Run on the stdlib ``ssl``: importing ``prebuilt_core`` injects truststore on+ macOS and Windows, whose SSLContext ignores SSL_CERT_FILE and cannot wrap a+ server-side socket (``get_unverified_chain`` on None in ``_verify_peercerts``).+ """+ injected = ssl.SSLContext.__module__.startswith("truststore")+ if injected:+ import truststore+ truststore.extract_from_ssl()+ try:+ yield+ finally:+ if injected:+ truststore.inject_into_ssl()+++def servers(stdlib_ssl, tls_certificate, monkeypatch):+ cert, key = tls_certificate+ monkeypatch.setenv("SSL_CERT_FILE", str(cert))+ monkeypatch.setenv("NO_PROXY", "127.0.0.1,localhost")+ monkeypatch.setenv("no_proxy", "127.0.0.1,localhost")+ for handler in prebuilt_core._URL_OPENER.handlers:+ if isinstance(handler, urllib.request.HTTPSHandler):+ monkeypatch.setattr(handler, "_context", ssl.create_default_context(cafile = str(cert)))+ running = []++ def start(*, tls = True, payload = None):+ class Handler(BaseHTTPRequestHandler):+ timeout = 3++ def do_GET(self):+ self.server.seen.append((self.path, self.headers.get("Authorization")))+ location = self.server.redirects.get(self.path)+ self.send_response(self.server.code if location else 200)+ if location:+ self.send_header("Location", location)+ body = json.dumps(payload).encode()+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ if self.command != "HEAD":+ self.wfile.write(body)++ do_HEAD = do_GET # without it the stdlib 501s and HEAD tests the error path++ def log_message(self, *args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.seen, server.redirects, server.code = [], {}, 302+ if tls:+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ context.load_cert_chain(cert, key)+ server.socket = context.wrap_socket(server.socket, server_side = True)+ server.url = f"{'https' if tls else 'http'}://127.0.0.1:{server.server_port}"+ thread = threading.Thread(target = server.serve_forever, kwargs = {"poll_interval": 0.01})+ thread.start()+ running.append((server, thread))+ return server++ yield start+ for server, thread in reversed(running):+ server.shutdown()+ server.server_close()+ thread.join(timeout = 5)+ assert not thread.is_alive()+++def fetch(client, url, monkeypatch):+ monkeypatch.setenv("GH_TOKEN", TOKEN.removeprefix("Bearer "))+ monkeypatch.delenv("GITHUB_TOKEN", raising = False)+ original_request = urllib.request.Request++ class LocalRequest(original_request):+ def __init__(self, request_url, *args, **kwargs):+ if request_url.startswith("https://api.github.com/"):+ request_url = url+ super().__init__(request_url, *args, **kwargs)++ monkeypatch.setattr(urllib.request, "Request", LocalRequest)+ if client == "prebuilt":+ request = original_request(url, headers = {"Authorization": TOKEN})+ with prebuilt_core._URL_OPENER.open(request, timeout = 3) as response:+ return json.load(response)+ if client == "freshness":+ return freshness_flow._fetch_newest_published_release_blocking(+ "owner/repo", 3, log_message = "redirect test"+ )+ if client == "changelog":+ return llama_cpp_changelog._fetch_release_blocking("owner/repo", "v1", 3)+ return sd._fetch_release("v1", repo = "owner/repo", timeout = 3)++[email protected]("client", ["prebuilt", "freshness", "changelog", "sd"])[email protected]("code", [301, 302, 303, 307, 308])+ "target", ["same_origin", "other_host", "other_port", "return", "downgrade"]+)+def test_release_redirect_credentials(client, code, target, servers, monkeypatch):+ release = {"tag_name": "v1", "published_at": "2026-01-01T00:00:00Z"}+ payload = [release] if client == "freshness" else release+ source = servers(payload = payload)+ source.code = code+ destination = (+ source if target == "same_origin" else servers(tls = target != "downgrade", payload = payload)+ )+ destination_url = destination.url+ if target == "other_host":+ destination_url = destination_url.replace("127.0.0.1", "localhost")+ source.redirects["/start"] = destination_url + "/final"+ if target == "return":+ destination.redirects["/final"] = source.url + "/back"+ if target == "downgrade" or (code == 308 and sys.version_info < (3, 11)):+ if client in ("prebuilt", "sd"):+ with pytest.raises(urllib.error.HTTPError) as error:+ fetch(client, source.url + "/start", monkeypatch)+ assert error.value.code == code+ error.value.close()+ else:+ assert fetch(client, source.url + "/start", monkeypatch) is None+ assert all(path != "/final" for path, _ in destination.seen)+ else:+ assert fetch(client, source.url + "/start", monkeypatch) == release+ expected_token = TOKEN if target == "same_origin" else None+ assert ("/final", expected_token) in destination.seen+ if target == "return":+ assert ("/back", None) in source.seen+ assert source.seen[0] == ("/start", TOKEN)+++ "start,target,expected",+ [+ ("https://hub.example/a", "https://hub.example:443/b", TOKEN),+ ("http://hub.example/a", "http://hub.example:80/b", TOKEN),+ ("https://HUB.example/a", "https://hub.example/b", TOKEN),+ ("http://hub.example:8443/a", "https://hub.example:8443/b", None),+ ("https://hub.example/a", "https://hub.example:0/b", None),+ ],+)+def test_prebuilt_origin_comparison(start, target, expected):+ request = urllib.request.Request(+ start,+ headers = {+ "Authorization": TOKEN,+ "Accept": "application/json",+ "User-Agent": "redirect-test",+ },+ )+ result = prebuilt_core._CrossHostAuthStrippingRedirectHandler().redirect_request(+ request, None, 302, "Found", {}, target+ )+ assert result.get_header("Authorization") == expected+ assert request.get_header("Authorization") == TOKEN+ assert result.get_header("Accept") == "application/json"+ assert result.get_header("User-agent") == "redirect-test"++[email protected]("name", ["prebuilt_core", "install_sd_cpp_prebuilt"])[email protected]("mode", ["script", "package"])+def test_installer_import_without_backend_dependencies(name, mode, tmp_path):+ env = dict(os.environ)+ env.pop("PYTHONPATH", None)+ env["PYTHONDONTWRITEBYTECODE"] = "1"+ env["UNSLOTH_STUDIO_NATIVE_TLS"] = "0"+ if mode == "script":+ args = [str(STUDIO / f"{name}.py"), "--help"]+ else:+ args = [+ "-c",+ f"import sys; sys.path.insert(0, {str(STUDIO.parent)!r}); import studio.{name}",+ ]+ result = subprocess.run(+ [sys.executable, "-S", *args],+ cwd = tmp_path,+ env = env,+ capture_output = True,+ text = True,+ timeout = 10,+ )+ assert result.returncode == 0, result.stderr+++ "start,target",+ [+ ("https://hub.example/a", "https://hub.example:99999/b"),+ ("https://hub.example/a", "https://hub.example:abc/b"),+ # Both ends unreadable: the sentinel must not compare equal to itself.+ ("https://hub.example:abc/a", "https://hub.example:abc/b"),+ ],+)+def test_an_unparseable_redirect_port_strips_rather_than_raising(start, target):+ """No client catches ValueError, so raising turns a soft "no release info" into an+ uncaught exception on an update check. Unreadable target, other origin, strip."""+ request = urllib.request.Request(+ start, headers = {"Authorization": TOKEN, "Accept": "application/json"}+ )+ result = prebuilt_core._CrossHostAuthStrippingRedirectHandler().redirect_request(+ request, None, 302, "Found", {}, target+ )+ assert result.get_header("Authorization") is None+ assert result.get_header("Accept") == "application/json"+ assert request.get_header("Authorization") == TOKEN++[email protected]("client", ["prebuilt", "freshness", "changelog", "sd"])+def test_an_unparseable_redirect_port_stays_soft_for_every_client(client, servers, monkeypatch):+ """The same case end to end: no ValueError reaches the caller."""+ release = {"tag_name": "v1", "published_at": "2026-01-01T00:00:00Z"}+ source = servers(payload = [release] if client == "freshness" else release)+ source.redirects["/start"] = "https://127.0.0.1:99999/final"+ # No ValueError arm: it must not be raised, so letting it escape fails the test.+ try:+ fetch(client, source.url + "/start", monkeypatch)+ except (urllib.error.HTTPError, urllib.error.URLError, OSError) as error:+ getattr(error, "close", lambda: None)()+ assert source.seen[0] == ("/start", TOKEN)+++def test_a_downgrade_is_refused_part_way_down_a_chain(servers):+ """https -> https -> http. Every other case here is one hop from the request, so a+ policy comparing only the ORIGINAL request URL would pass them all and still leak."""+ source = servers(payload = {"tag_name": "v1"})+ plaintext = servers(tls = False, payload = {"tag_name": "v1"})+ source.redirects["/start"] = source.url + "/two"+ source.redirects["/two"] = plaintext.url + "/final"++ request = urllib.request.Request(source.url + "/start", headers = {"Authorization": TOKEN})+ with pytest.raises(urllib.error.HTTPError) as error:+ prebuilt_core._URL_OPENER.open(request, timeout = 3)+ error.value.close()+ assert [path for path, _ in source.seen] == ["/start", "/two"]+ assert plaintext.seen == []++[email protected]("method", ["GET", "HEAD"])[email protected]("cross_origin", [False, True])+def test_the_method_and_a_signed_query_survive_the_hop(method, cross_origin, servers):+ """routes/training.py preflights with HEAD, and GitHub and Hugging Face redirect to+ a CDN URL whose credentials are in the query: mangling it reads as an auth failure."""+ source = servers(payload = {"tag_name": "v1"})+ destination = servers(payload = {"tag_name": "v1"}) if cross_origin else source+ target = destination.url+ if cross_origin:+ target = target.replace("127.0.0.1", "localhost")+ source.redirects["/start"] = f"{target}/final?sig=abc123&exp=99"++ request = urllib.request.Request(+ source.url + "/start", headers = {"Authorization": TOKEN}, method = method+ )+ with prebuilt_core._URL_OPENER.open(request, timeout = 3) as response:+ assert response.status == 200+ landed = [(path, token) for path, token in destination.seen if path.startswith("/final")]+ assert landed, "the redirect was not followed"+ path, token = landed[0]+ assert path == "/final?sig=abc123&exp=99"+ assert token == (None if cross_origin else TOKEN)++[email protected]("unredirected", [False, True])+def test_cross_origin_does_not_copy_unredirected_auth(unredirected):+ request = urllib.request.Request("https://hub.example/a")+ if unredirected:+ request.add_unredirected_header("Authorization", TOKEN)+ result = prebuilt_core._CrossHostAuthStrippingRedirectHandler().redirect_request(+ request, None, 302, "Found", {}, "https://other.example/b"+ )+ assert result.get_header("Authorization") is None+ assert request.get_header("Authorization") == (TOKEN if unredirected else None)diff --git a/tests/studio/install/test_pr10648_legacy_marker_compat.py b/tests/studio/install/test_pr10648_legacy_marker_compat.pyindex f67f3dd90e3..b3ce9ee1efe 100644--- a/tests/studio/install/test_pr10648_legacy_marker_compat.py+++ b/tests/studio/install/test_pr10648_legacy_marker_compat.py@@ -222,6 +222,15 @@ def _extract_legacy_tree(tag: str, destination: Path) -> "Path | None":destination.mkdir(parents = True, exist_ok = True)wanted = [f"studio/{name}" for name in _LEGACY_MODULES]wanted += ["studio/backend/__init__.py", "studio/backend/utils/__init__.py"]+ # prebuilt_core imports this too, and PYTHONPATH below is REPLACED with this tree.+ # ls-tree, not a bare append: the tags predating it must resolve rather than skip.+ optional = git("ls-tree", "-r", "--name-only", tag, "studio/backend/utils/auth_safe.py")+ if optional.returncode == 0:+ wanted += [+ line+ for line in optional.stdout.decode("utf-8", "replace").split()+ if line.endswith(".py")+ ]listing = git("ls-tree", "-r", "--name-only", tag, "studio/backend/utils/prebuilt")if listing.returncode != 0:return None