Repository navigation
fix(studio): verify TLS against the OS trust store at runtime (corporate TLS-inspection proxies) - #8108
Conversation
On macOS/Windows behind a TLS-inspecting proxy (Cisco Umbrella, Zscaler, ...), every huggingface.co request from the Studio backend fails with CERTIFICATE_VERIFY_FAILED: Python verifies against certifi's bundled Mozilla roots and ignores the OS trust store where the proxy CA lives. A terminal user can export SSL_CERT_FILE, but macOS .app / desktop-shortcut launches never read shell profiles, so GUI-launched Studio has no workaround. Inject truststore into ssl at each network-touching entry point (server, HF download worker, STT download worker, training worker) — injection is per-process and does not survive spawns. Default-on for macOS/Windows, opt-in on Linux, opt-out anywhere via UNSLOTH_STUDIO_NATIVE_TLS=0, mirroring UV_NATIVE_TLS in install.sh (#6671), whose runtime counterpart this is. Co-Authored-By: Claude Fable 5 <[email protected]>
Review follow-ups: the inference worker resolves remote LoRA bases and the export worker pushes/loads from the Hub, both in fresh spawned interpreters that missed the injection; and pyproject's studio extra must mirror requirements/studio.txt (test_studio_extra_matches_requirements), so truststore is added there too for `pip install "unsloth[studio]"`. Co-Authored-By: Claude Fable 5 <[email protected]>
Second review round: the data-recipe jobs worker and the transformers -c config probe are further fresh interpreters with Hub/provider traffic, so activate in the worker and inline the gated injection in the probe script (it cannot import backend modules). uv/pip child installers do their own TLS (rustls ignores in-process injection), so activation now exports UV_SYSTEM_CERTS/UV_NATIVE_TLS, mirroring install.sh. truststore requires Python >=3.10 while the project floor is 3.9, so the dependency gets a python_version marker on both sides of the requirements mirror; activate_native_tls() already falls back to certifi where the import is unavailable. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Note on the failing checks — both groups reproduce on
|
|
I addressed the remaining spawned-worker gap in a05c8c5. Diffusion LoRA training uses its own spawn target, so it now activates native TLS before importing diffusers and calling |
- native_tls: mirror one resolved value across UV_SYSTEM_CERTS/UV_NATIVE_TLS. uv takes either variable as an opt-in, so UV_SYSTEM_CERTS=0 alone was re-enabled by the legacy name defaulting to 1. Matches install.sh. - native_tls: warn instead of debug when injection fails, and document that explicit CA bundles become additive rather than exclusive under truststore. - model_config: activate in the _VISION_CHECK_SCRIPT child, which calls AutoConfig.from_pretrained and fails quiet, so VLM detection silently degraded behind a proxy. - prebuilt_core: activate at import so the llama.cpp / whisper.cpp installers and the resolve-prebuilt probe verify their urllib downloads the same way. - mlx_repair: forward the UV cert variables through the allowlisted child env, the one uv installer that did not inherit them. - diffusion_training_service: activate inside run_without_native_path_secret so truststore imports after the lease secret is scrubbed, and scrub the parent env before the child starts, like the other orchestrators. - tests: pin the uv mirror both ways, stop leaking the UV vars into the pytest process, assert the diffusion ordering, and add static coverage that every spawned entry point still activates.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 63cdb4a211
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| # Fresh interpreter: main.py's truststore injection does not survive the spawn. | ||
| from utils.native_tls import activate_native_tls | ||
|
|
||
| activate_native_tls() |
There was a problem hiding this comment.
Scrub lease secret before activating download TLS
When this worker is spawned from download_lifecycle.spawn_worker, its environment is built with get_hf_cache_paths().child_env() (a copy of os.environ) and is not passed through child_env_without_native_path_secret; the same pattern is used by the dictation download worker. In desktop sessions that have UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET, this new module-level activation imports and runs third-party truststore while the signing secret is still present in the child environment. Scrub the env before Popen, or wrap these subprocess entrypoints like the mp workers before activating TLS.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The env does carry the secret, but no boundary is crossed here. The lease is a signed grant the frontend forwards and the backend verifies before a native read (verify_native_path_lease, consumed only by routes/rag.py, routes/inference.py and hub/services/datasets/local.py); it exists to stop the webview forging a path. A backend-spawned child already runs as the same user with the same filesystem access, so the key grants it nothing open() does not. The inheritance is also pre-existing and unchanged by this PR, and scrubbing only ahead of truststore would be cosmetic: the same child then imports huggingface_hub, urllib3, requests and hf_xet with the secret still set, since nothing scrubs it in-child. Neither download worker touches the lease API.
| _flag = os.environ.get("UNSLOTH_STUDIO_NATIVE_TLS", "").strip().lower() | ||
| if _flag in {"1", "true", "yes"} or ( | ||
| _flag not in {"0", "false", "no"} and sys.platform in ("darwin", "win32") | ||
| ): |
There was a problem hiding this comment.
Honor installer TLS opt-outs in prebuilt downloads
Fresh evidence is that the standalone prebuilt inline gate added here never reads the installer opt-out variables: when setup.sh invokes install_llama_prebuilt.py/install_whisper_prebuilt.py, it inherits install.sh's documented UV_SYSTEM_CERTS=0 opt-out, but this branch still enables truststore on macOS/Windows unless UNSLOTH_STUDIO_NATIVE_TLS=0 is also set. Users opting out because their system store/proxy setup breaks downloads can still have these urllib prebuilt downloads verified against that store; treat false UV_SYSTEM_CERTS/UV_NATIVE_TLS values as disabling here or export the Studio opt-out before spawning.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
These knobs govern different TLS stacks on purpose. UV_SYSTEM_CERTS / UV_NATIVE_TLS configure uv's rustls, which is why install.sh sets them and the README scopes that opt-out to uv; UNSLOTH_STUDIO_NATIVE_TLS governs Python's ssl. utils/native_tls.py encodes exactly that: it writes the uv variables and never reads them as an input, so UV_SYSTEM_CERTS=0 still injects there too. Honouring them in the vendored copy alone would diverge it from the helper it is required to mirror, and would take away the ability to keep uv on certifi while Python uses the OS store. The documented Studio opt-out works here: UNSLOTH_STUDIO_NATIVE_TLS=0 leaves prebuilt downloads on certifi, which I verified by importing prebuilt_core with the flag set each way.
| import truststore | ||
| truststore.inject_into_ssl() |
There was a problem hiding this comment.
Scrub lease secret before prebuilt TLS activation
The in-app llama/whisper update paths spawn these installer scripts with env = dict(os.environ, ...), and the read-only resolver inherits the parent environment too, so desktop sessions carrying UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET now run this new truststore import/injection before the child has scrubbed a secret it never needs. Use child_env_without_native_path_secret() (while preserving the required installer vars) for the prebuilt installer subprocesses, or otherwise remove the lease secret before importing this module.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same reasoning as the download-worker item, plus the ordering premise does not hold: truststore is not the first third-party import in this module, filelock is imported at prebuilt_core.py:53-56, above the new block. The installer children never touch the lease API, the inheritance predates this PR, and a child spawned by the backend runs as the same user, so the signing key grants it nothing it could not do directly. Scrubbing at those spawn sites would be a reasonable tidy-up of a pre-existing pattern gap, but it belongs in its own change rather than this one.
test_vision_subprocess_unions_sidecar_registry slices the embedded script at its first 'try:' to exec the inlined helpers, so putting the TLS activation above them left that slice empty. Move it below the helpers, still ahead of AutoConfig.from_pretrained.
…#8108 Simulation findings on the branch: - A failed injection logged a full traceback at warning level. On Python 3.9, where truststore is excluded by the dependency marker on purpose, that is one stack per worker start. Now one line carrying the reason. - truststore's injection is client-side: an SSLContext built after it verifies a peer chain on every handshake, so it cannot serve TLS. Studio serves plain HTTP on loopback so nothing breaks today, but an in-process HTTPS listener added later would fail at handshake on the default-on platforms. Documented, and test_native_tls_entrypoints.py now fails if one appears.
|
I simulated this end to end rather than reasoning about it, since the unit tests stub Reproducing the actual bug, then the fix. On a Linux box the corporate case is faithful: put the proxy CA in the OS store only ( So the issue is real, and the fix is what flips it. 19 checks in that harness, all passing: hostname mismatch still rejected, a CA absent from the OS store still rejected, Nothing old breaks. 32 more checks over the environment matrix: the platform default for darwin, win32, linux, cygwin and freebsd; every spelling of the flag including junk values falling back to the platform default; the full uv variable matrix; and the fail-open paths. An old Studio install whose venv predates this PR has no [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU], 18 cells, all passing: the gate resolves per platform and the spawned workers still import under each accelerator environment, including the training worker where the activation sits between the ROCDXG block and the hardware helpers. WSL reports Browsers. Studio serves plain HTTP on loopback, so no browser ever negotiates TLS with it, but I checked rather than assumed. I booted the real FastAPI app twice, injection off and on, and the HTTP surface is identical across The whole backend suite with injection actually live, Two things I changed as a result:
Two behaviours worth stating rather than fixing, both consequences of the mechanism:
One upstream note for the record: truststore has an open issue about a race on context configuration (#209). My 64-thread test passes, and on Linux the OpenSSL backend never lowers |
truststore is pre-1.0 and 0.x minors are where it has changed verification behaviour (0.9 to 0.10), while fixes land as patches inside a minor (0.10.1, 0.10.3, 0.10.4). Since activation applies process-wide to every TLS connection, a semantic change should get a human look rather than arrive on the next install. 0.10.4 has been the current release for a year, so nothing is held back today. Mirrored in both declarations.
|
Measured the performance cost before and after, on the same box, each configuration in its own process so the irreversible global patch cannot contaminate the control. Steady state is unchanged. Once a connection is up, there is no per-request cost: That is the shape that matters for a model download: one connection carrying many MB. The cost is per new connection, and on Linux I can attribute it exactly: truststore's OpenSSL backend calls Startup cost per spawned worker, which is the other place activation shows up:
So: tens of milliseconds once per worker spawn, ~16 ms per new TLS connection on opt-in Linux, and nothing at all in steady state. Reasonable for the failure it fixes, but worth having the numbers on record rather than assumed. One upstream observation, not actionable here: re-parsing the full system bundle on every handshake looks like something truststore could cache. Worth an issue against truststore if anyone wants to chase it. |
The python -c probes and prebuilt_core.py cannot import backend modules, so each carried its own hand-written copy of the UNSLOTH_STUDIO_NATIVE_TLS gate. Three copies of the same platform defaults drift silently: a child would keep downloading against certifi while everything else used the OS store. native_tls.inline_gate_source() now renders the gate from the same constants native_tls_enabled() reads. The probes concatenate it, and prebuilt_core.py keeps a paste that test_native_tls_entrypoints.py asserts verbatim against the generated text.
ruff-format restyles the pasted gate in prebuilt_core.py (quote style, line wrapping), so a substring assertion against inline_gate_source() fails the moment the formatter runs, as it did on 668cd9f. Compare the parsed statements instead: still catches a real edit to the platform defaults, and ignores formatting that cannot change behaviour.
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
truststore was a new third-party dependency for every Studio user, added to fix CERTIFICATE_VERIFY_FAILED for the few behind a TLS-inspecting proxy. Nothing in Unsloth required it before, directly or transitively. It is MIT, six pure-Python files, no dependencies of its own, so vendor it at studio/backend/vendor/ and drop both declarations. pip vendors it for the same reason. utils/third_party_source.py is not an option here: it downloads over urllib at first use, which behind the very proxy this fixes would itself fail to verify. The copy has to exist before the network does. Consumers append the vendor directory to sys.path and import the top-level name, so a truststore the user installed themselves still wins. The directory is deliberately not a package: a dotted import would load the same files under a second module name, and each would wrap ssl again. test_vendored_truststore.py pins the tree against the published 0.10.4 wheel and scripts/sync_vendored_truststore.py re-syncs it, since vendored code is invisible to the dependency scanners.
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Nothing in Studio ever ran it: it only re-downloaded a wheel for a maintainer bumping the pin, which implies a refresh story this repo does not have. The vendored files are a static copy. truststore_manifest.json and test_vendored_truststore.py stay, since they are what makes them static: they pin the tree to the published 0.10.4 hashes and fail if anything edits it. A version bump now means replacing the tree and updating the manifest in the same commit, deliberately, which the README spells out.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Problem
Follow-up to #6671. That PR fixed install-time TLS behind corporate TLS-inspecting proxies (Cisco Umbrella, Zscaler, Netskope) by switching uv to native TLS. The runtime has the same defect: Python verifies against certifi's bundled Mozilla roots and ignores the OS trust store where the proxy CA lives, so every huggingface.co call from the Studio backend fails:
Model downloads, repo metadata and LoRA base resolution are all broken. A terminal user can export
SSL_CERT_FILE, but launching Studio from the macOS.appor a desktop shortcut never reads shell profiles, so GUI launches have no workaround at all. Install succeeds (thanks to #6671), then the installed app cannot download anything.Fix
Verify TLS against the OS trust store with truststore, the same mechanism pip has enabled by default since 24.2 and the runtime counterpart of
UV_NATIVE_TLS.truststore.inject_into_ssl()is process-wide but does not survive a spawn, soutils/native_tls.pyis called once at each interpreter that touches the network:activate_native_tls()at module level:main.pyplus the HF download, STT download, inference, export, training and data-recipe workers, and the diffusion training child (inside its own spawn target, after the lease-secret scrub).python -cAutoConfig and vision probes, andprebuilt_core.py, which ships standalone for the llama.cpp / whisper.cpp installers. Rather than three hand-written copies drifting apart,native_tls.inline_gate_source()renders the gate from the same constantsnative_tls_enabled()reads; the probes concatenate it, and the one true paste inprebuilt_core.pyis asserted against it by AST intests/test_native_tls_entrypoints.py.UV_SYSTEM_CERTS(uv >= 0.11) andUV_NATIVE_TLS(older) are mirrored from one resolved value rather than defaulted independently, because uv treats either as an opt-in: an opt-out in one spelling has to carry to the other.utils/mlx_repair.pypasses both through its env allowlist.truststore is vendored at
studio/backend/vendor/, not depended on. Nothing in Unsloth required it before, directly or transitively, so declaring it would have added a package to every Studio install to fix a proxy most users do not have. It is MIT, six pure-Python files, no dependencies of its own, and pip vendors it for the same reason.The repo's usual mechanism for pinned third-party source,
utils/third_party_source.py, is not an option here: it downloads overurllibat first use, so behind the very proxy this PR fixes, fetching truststore would itself fail withCERTIFICATE_VERIFY_FAILED. The copy has to exist before the network does.Consumers append the vendor directory to
sys.pathand import the top-level name, so a truststore the user installed themselves still wins. The directory is deliberately not a package: a dottedstudio.backend.vendor.truststoreimport would load the same files under a second module name, and each copy would wrapsslagain. The copy is static: nothing refreshes it, andtests/test_vendored_truststore.pypins it to the published 0.10.4 wheel hashes so a formatter or a stray edit fails rather than silently changing how certificates are verified. A version bump means replacing the tree and updating the manifest in the same commit. That check matters because vendored code is invisible to the dependency scanners.Behaviour
Default on for macOS (Security framework) and Windows (CertStore), which answers the Windows-uniformity question raised in #6671. Linux stays opt-in via
UNSLOTH_STUDIO_NATIVE_TLS=1, since distro OpenSSL and cert layouts vary.0opts out anywhere.Two things worth stating plainly:
SSL_CERT_FILEandREQUESTS_CA_BUNDLEkeep working, but they become additive rather than exclusive: truststore keeps the OS anchors alongside the supplied bundle (macOS viaSecTrustSetAnchorCertificatesOnly(trust, False), Windows by trying the system engine first). If a bundle was being used to narrow trust,UNSLOTH_STUDIO_NATIVE_TLS=0is the way back. This matches pip's behaviour under the same injection.truststore.SSLContextfor outbound connections instead of the process-wide injection.If truststore is missing or injection fails, the helper logs one warning line and falls back to certifi, which is the pre-existing and strictly less permissive behaviour. Python 3.9 is unaffected either way: truststore refuses to import below 3.10 by design, vendored or not.
Verification
tests/test_native_tls.py,tests/test_native_tls_entrypoints.pyandtests/test_vendored_truststore.py, no network: platform defaults, env tri-state, uv mirroring, idempotency, fail-open recovery, a check that every spawned entry point still activates before its first Hub call so a future worker cannot quietly skip it, and a digest of the vendored tree that fails if a formatter or an edit moves it off upstream 0.10.4..appwith no shell environment: startup model-list refresh, HF metadata and LoRA base checks all succeed where they previously loggedSSLErrorretry walls. A spawned worker verifies the same way.UNSLOTH_STUDIO_NATIVE_TLS=0reproduces the originalCERTIFICATE_VERIFY_FAILED, confirming the injection is what does the work.python -cprobe child andprebuilt_core.pyall resolve the vendored copy and inject; with a real truststore installed, all three resolve site-packages instead, which is what append-rather-than-prepend buys. Wheel and sdist both ship the six modules,py.typedand the MITLICENSE, and the wheel METADATA no longer declares truststore.requests,httpxsync and async,urllib3andhuggingface_hub, over the [Windows, Linux, WSL, macOS] x [NVIDIA, AMD, CPU] gate matrix, plus a before and after benchmark: no steady-state regression (pooled request latency unchanged), around 16 ms per new TLS connection on Linux from truststore's per-handshakeset_default_verify_paths(), and around 27 ms and 4.5 MB per spawned worker for the extra imports.Workaround (until merged)
Terminal launches only, which is exactly what the
.appcannot do.