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
fix(studio): verify TLS against the OS trust store at runtime (corporate TLS-inspection proxies) (#8108)
Luca Cesarano16fac7b1e614
diff --git a/.github/workflows/lint-ci.yml b/.github/workflows/lint-ci.ymlindex 32e1a5d8443..ff2b089bf71 100644--- a/.github/workflows/lint-ci.yml+++ b/.github/workflows/lint-ci.yml@@ -236,9 +236,10 @@ jobs:"Licensed under the Apache License", # Apache-2.0 long form"General Public License", # GPL / LGPL / AGPL long form)+ # "vendor" is upstream third-party source: it carries its own licence.SKIP_PARTS = {".venv", "venv", "build", "dist", ".git","unsloth_compiled_cache", "node_modules",- "unsloth.egg-info"}+ "unsloth.egg-info", "vendor"}studio_missing = []other_missing = []diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 8dcb9130b35..25000dd6e9b 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -15,8 +15,9 @@ repos:language: pythontypes: [python]# Mirror ruff's [tool.ruff] extend-exclude so this hook does not- # half-process files ruff itself skips (which produced churn).- exclude: '(chat_templates|ollama_template_mappers|_auto_install|mapper)\.py$'+ # half-process files ruff itself skips (which produced churn). vendor/ is+ # repeated here because this hook does not read ruff's config.+ exclude: '(chat_templates|ollama_template_mappers|_auto_install|mapper)\.py$|^studio/backend/vendor/'additional_dependencies:- ruff==0.6.9# Re-pins allowScripts entries after dependency bumps. pre-commit.cidiff --git a/pyproject.toml b/pyproject.tomlindex 066e7943587..92a43c681a3 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -69,6 +69,8 @@ studio = ["frontend/*.yaml","frontend/.git*","backend/requirements/**/*",+ # Vendored truststore: not a package (no __init__.py), so it ships as data.+ "backend/vendor/**/*","backend/plugins/**/*","backend/assets/**/*.jinja","backend/assets/**/*.html",@@ -1434,6 +1436,8 @@ extend-exclude = ["*ollama_template_mappers.py","*_auto_install.py","*mapper.py",+ # Vendored upstream source: reformatting it would break the digest test.+ "studio/backend/vendor/",][tool.ruff.lint]diff --git a/studio/backend/core/data_recipe/jobs/worker.py b/studio/backend/core/data_recipe/jobs/worker.pyindex 4073288cb3e..402caebe094 100644--- a/studio/backend/core/data_recipe/jobs/worker.py+++ b/studio/backend/core/data_recipe/jobs/worker.py@@ -20,6 +20,11 @@ from .constants import EVENT_JOB_COMPLETED, EVENT_JOB_ERROR, EVENT_JOB_STARTEDfrom ..service import build_config_builder, create_data_designerfrom utils.paths import ensure_dir, recipe_datasets_root+# Fresh spawned interpreter: re-apply main.py's OS-trust-store injection.+from utils.native_tls import activate_native_tls++activate_native_tls()+_ARTIFACT_ROOT = recipe_datasets_root()_RE_GITHUB_CURSOR = re.compile(r"\bcursor=[^\s,]+")_RE_SECRET_TOKEN = re.compile(diff --git a/studio/backend/core/export/worker.py b/studio/backend/core/export/worker.pyindex e18b7fee849..c4a352a6a47 100644--- a/studio/backend/core/export/worker.py+++ b/studio/backend/core/export/worker.py@@ -27,6 +27,11 @@ from typing import Anylogger = get_logger(__name__)+# Fresh spawned interpreter: re-apply the OS-trust-store injection.+from utils.native_tls import activate_native_tls++activate_native_tls()+# Gate controlling whether captured stdout/stderr lines are forwarded to the# parent's resp_queue (and on to the export-dialog SSE stream). Closed by defaultdiff --git a/studio/backend/core/inference/stt_download_worker.py b/studio/backend/core/inference/stt_download_worker.pyindex cf35d374e2f..23c3de45549 100644--- a/studio/backend/core/inference/stt_download_worker.py+++ b/studio/backend/core/inference/stt_download_worker.py@@ -21,6 +21,11 @@ import timefrom pathlib import Pathfrom typing import Optional, Sequence+# Fresh spawned interpreter: re-apply the OS-trust-store injection.+from utils.native_tls import activate_native_tls++activate_native_tls()+# How long a cancelled worker gets to exit on SIGTERM before it is killed.TERMINATE_GRACE_SECONDS = 15.0diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 375d26d68fc..0c2c3beed85 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -27,6 +27,11 @@ from typing import Anylogger = get_logger(__name__)from utils.hardware import apply_gpu_ids, is_apple_silicon+# Fresh spawned interpreter: re-apply the OS-trust-store injection.+from utils.native_tls import activate_native_tls++activate_native_tls()+_SHARE_OBJECT_MAX_BYTES = 1 << 20_SHARE_OBJECT_ERROR_SIZE = -1diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.pyindex 5f2ff78c19f..2c634a0e360 100644--- a/studio/backend/core/training/diffusion_training_service.py+++ b/studio/backend/core/training/diffusion_training_service.py@@ -51,8 +51,15 @@ def _finite_or_none(value: Any) -> Optional[float]:def _run_diffusion_child(*, event_queue: Any, stop_queue: Any, config: dict) -> None:+ # Fresh spawned interpreter: re-apply the OS-trust-store injection, inside+ # the secret scrub and before the trainer imports diffusers.+ from utils.native_tls import activate_native_tls++ activate_native_tls()+# Imported lazily so this module (and the route layer) stays torch-free at import.from .diffusion_lora_trainer import run_diffusion_training_process+run_diffusion_training_process(event_queue = event_queue, stop_queue = stop_queue, config = config)@@ -375,7 +382,11 @@ class DiffusionTrainingService:},daemon = True,)- self._proc.start()+ # Keep the lease secret out of the child's env, as other orchestrators do.+ from utils.native_path_leases import native_path_secret_removed_for_child_start++ with native_path_secret_removed_for_child_start():+ self._proc.start()try:from utils.process_lifetime import adopt_pidadopt_pid(self._proc.pid) # bind to parent lifetime (no zombie on exit)diff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 854153636d1..3c684850257 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -45,6 +45,12 @@ if sys.platform.startswith("linux") and "HSA_ENABLE_DXG_DETECTION" not in os.envlogger = get_logger(__name__)from utils.child_stdio import utf8_child_env++# Fresh spawned interpreter: re-apply the OS-trust-store injection.+from utils.native_tls import activate_native_tls++activate_native_tls()+from utils.hardware import apply_gpu_idsfrom utils.hf_dataset_options import hf_dataset_split_instruction_namesfrom utils.training_runs import build_default_output_dir_namediff --git a/studio/backend/hub/workers/hf_download.py b/studio/backend/hub/workers/hf_download.pyindex a8a4ad7d221..29f456280df 100644--- a/studio/backend/hub/workers/hf_download.py+++ b/studio/backend/hub/workers/hf_download.py@@ -39,6 +39,11 @@ _BACKEND = _HERE.parent.parentif str(_BACKEND) not in sys.path:sys.path.insert(0, str(_BACKEND))+# Fresh interpreter: main.py's truststore injection does not survive the spawn.+from utils.native_tls import activate_native_tls++activate_native_tls()+from hub.utils.snapshot_filters import (SNAPSHOT_IGNORE_PATTERNS,)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 0bca224f89e..4a13504a71f 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -178,6 +178,12 @@ _backend_dir = str(_Path(__file__).parent)if _backend_dir not in sys.path:sys.path.insert(0, _backend_dir)+# OS trust store for TLS before anything opens a connection: behind a+# TLS-inspecting proxy certifi alone rejects every Hub request.+from utils.native_tls import activate_native_tls++activate_native_tls()+# `uvicorn main:app` bypasses run.py; seed thread caps here too.from utils.cpu_threads import configure_cpu_threadsdiff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txtindex 9366d781d02..4633c125aa9 100644--- a/studio/backend/requirements/studio.txt+++ b/studio/backend/requirements/studio.txt@@ -11,6 +11,7 @@ datasets==4.3.0pyjwt# gradio>=4.0.0 # 148 MB - Unsloth uses React + FastAPI, not Gradiohuggingface-hub==0.36.2+# truststore is vendored at backend/vendor/, deliberately not a dependency.structlog>=24.1.0dicewareddgsdiff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.pyindex 242f507e0b3..1a226ad4c7d 100644--- a/studio/backend/tests/test_diffusion_training.py+++ b/studio/backend/tests/test_diffusion_training.py@@ -125,6 +125,50 @@ def _crashing_target(*, event_queue, stop_queue, config):# Exits without a terminal event, so the pump must mark it as an error.+def test_default_target_activates_native_tls_before_diffusion_trainer(monkeypatch):+ """TLS activation runs inside the scrub wrapper, and before diffusers imports."""+ import os+ import sys+ import types+ import core.training.diffusion_training_service as service+ import utils.native_path_leases as leases++ calls = []+ monkeypatch.setenv(leases.LEASE_SECRET_ENV, "secret")++ def _activate():+ calls.append("native_tls")+ assert leases.LEASE_SECRET_ENV not in os.environ++ monkeypatch.setattr("utils.native_tls.activate_native_tls", _activate)++ trainer = types.ModuleType("core.training.diffusion_lora_trainer")+ trainer.run_diffusion_training_process = lambda **kwargs: calls.append("trainer")+ monkeypatch.setitem(sys.modules, "core.training.diffusion_lora_trainer", trainer)++ def _run_without_native_path_secret(target, **kwargs):+ calls.append("native_path_secret")+ assert target is service._run_diffusion_child+ assert kwargs == {+ "event_queue": "events",+ "stop_queue": "stop",+ "config": {"base_model": "example/model"},+ }+ os.environ.pop(leases.LEASE_SECRET_ENV, None) # what the real wrapper does first+ return target(**kwargs)++ monkeypatch.setattr(+ "utils.native_path_leases.run_without_native_path_secret",+ _run_without_native_path_secret,+ )++ service._default_target(+ event_queue = "events", stop_queue = "stop", config = {"base_model": "example/model"}+ )++ assert calls == ["native_path_secret", "native_tls", "trainer"]++_CFG = {"base_model": "b", "data_dir": "d", "output_dir": "/tmp/out", "train_steps": 2}diff --git a/studio/backend/tests/test_native_tls.py b/studio/backend/tests/test_native_tls.pynew file mode 100644index 00000000000..1cd848627ff--- /dev/null+++ b/studio/backend/tests/test_native_tls.py@@ -0,0 +1,156 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the OS-trust-store TLS activation (utils/native_tls.py).++truststore is stubbed: these assert only Unsloth's seam -- the platform defaults,+the UNSLOTH_STUDIO_NATIVE_TLS tri-state, idempotency, and the fail-open-to-certifi+behaviour when truststore is unavailable. CPU-only, no network.+"""++from __future__ import annotations++import sys+import types as _types+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from utils import native_tls++[email protected](autouse = True)+def _reset_activation(monkeypatch):+ import os++ monkeypatch.setattr(native_tls, "_activated", False)+ for key in ("UNSLOTH_STUDIO_NATIVE_TLS", "UV_SYSTEM_CERTS", "UV_NATIVE_TLS"):+ monkeypatch.delenv(key, raising = False)+ yield+ # monkeypatch cannot undo vars that were absent, so drop what setdefault added.+ for key in ("UV_SYSTEM_CERTS", "UV_NATIVE_TLS"):+ os.environ.pop(key, None)+++def _fake_truststore(monkeypatch):+ calls = []+ fake = _types.ModuleType("truststore")+ fake.inject_into_ssl = lambda: calls.append("inject")+ monkeypatch.setitem(sys.modules, "truststore", fake)+ return calls+++ ("platform", "expected"),+ [("darwin", True), ("win32", True), ("linux", False)],+)+def test_platform_defaults(monkeypatch, platform, expected):+ monkeypatch.setattr(sys, "platform", platform)+ assert native_tls.native_tls_enabled() is expected++[email protected]("value", ["0", "false", "NO", " 0 "])+def test_env_opt_out_wins_on_default_on_platform(monkeypatch, value):+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setenv("UNSLOTH_STUDIO_NATIVE_TLS", value)+ assert native_tls.native_tls_enabled() is False++[email protected]("value", ["1", "true", "YES"])+def test_env_opt_in_wins_on_default_off_platform(monkeypatch, value):+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setenv("UNSLOTH_STUDIO_NATIVE_TLS", value)+ assert native_tls.native_tls_enabled() is True+++def test_activate_injects_once(monkeypatch):+ monkeypatch.setattr(sys, "platform", "darwin")+ calls = _fake_truststore(monkeypatch)++ assert native_tls.activate_native_tls() is True+ assert native_tls.activate_native_tls() is True+ assert calls == ["inject"]+++def test_activate_exports_uv_native_tls(monkeypatch):+ import os++ monkeypatch.setattr(sys, "platform", "darwin")+ _fake_truststore(monkeypatch)++ assert native_tls.activate_native_tls() is True+ assert os.environ["UV_SYSTEM_CERTS"] == "1"+ assert os.environ["UV_NATIVE_TLS"] == "1"+++def test_activate_keeps_explicit_uv_override(monkeypatch):+ import os++ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setenv("UV_SYSTEM_CERTS", "0")+ _fake_truststore(monkeypatch)++ assert native_tls.activate_native_tls() is True+ assert os.environ["UV_SYSTEM_CERTS"] == "0"+ # uv takes either var as an opt-in, so the legacy name must mirror the opt-out.+ assert os.environ["UV_NATIVE_TLS"] == "0"+++def test_activate_mirrors_legacy_uv_override(monkeypatch):+ import os++ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setenv("UV_NATIVE_TLS", "0")+ _fake_truststore(monkeypatch)++ assert native_tls.activate_native_tls() is True+ assert os.environ["UV_NATIVE_TLS"] == "0"+ assert os.environ["UV_SYSTEM_CERTS"] == "0"+++def test_disabled_does_not_touch_uv_env(monkeypatch):+ import os++ monkeypatch.setattr(sys, "platform", "linux")+ _fake_truststore(monkeypatch)++ assert native_tls.activate_native_tls() is False+ assert "UV_SYSTEM_CERTS" not in os.environ+ assert "UV_NATIVE_TLS" not in os.environ+++def test_activate_noop_when_disabled(monkeypatch):+ monkeypatch.setattr(sys, "platform", "linux")+ calls = _fake_truststore(monkeypatch)++ assert native_tls.activate_native_tls() is False+ assert calls == []+++def test_activate_fails_open_without_truststore(monkeypatch):+ monkeypatch.setattr(sys, "platform", "darwin")+ # None in sys.modules makes `import truststore` raise ImportError.+ monkeypatch.setitem(sys.modules, "truststore", None)++ assert native_tls.activate_native_tls() is False+ # A later call with truststore available recovers.+ calls = _fake_truststore(monkeypatch)+ assert native_tls.activate_native_tls() is True+ assert calls == ["inject"]+++def test_activate_fails_open_when_injection_raises(monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")+ fake = _types.ModuleType("truststore")++ def _boom():+ raise OSError("no cert store")++ fake.inject_into_ssl = _boom+ monkeypatch.setitem(sys.modules, "truststore", fake)++ assert native_tls.activate_native_tls() is Falsediff --git a/studio/backend/tests/test_native_tls_entrypoints.py b/studio/backend/tests/test_native_tls_entrypoints.pynew file mode 100644index 00000000000..c2e214c00e9--- /dev/null+++ b/studio/backend/tests/test_native_tls_entrypoints.py@@ -0,0 +1,122 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Every spawned interpreter that talks HTTPS activates the OS trust store.++Injection is process-local and does not survive a spawn, so a missing call is+invisible until someone behind a TLS-inspecting proxy hits that one code path.+No network: module-level calls are checked by AST, probe scripts by reading the+assembled source off the module.+"""++from __future__ import annotations++import ast+import importlib+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent++# Modules whose fresh interpreter must activate at import, before any Hub call.+_ENTRYPOINTS = [+ "main.py",+ "hub/workers/hf_download.py",+ "core/inference/stt_download_worker.py",+ "core/inference/worker.py",+ "core/export/worker.py",+ "core/training/worker.py",+ "core/data_recipe/jobs/worker.py",+]++# `python -c` children carry the gate as source. Read the assembled script off+# the module: it is concatenated, so scraping AST literals would miss the+# generated part.+_PROBE_SCRIPTS = [+ ("utils.transformers_version", "_PROBE_CONFIG_SCRIPT"),+ ("utils.models.model_config", "_VISION_CHECK_SCRIPT"),+]+++def _import_time_calls(body):+ """Call names reachable at import: module level, including if/try/with bodies."""+ names = set()+ for node in body:+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ continue+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):+ func = node.value.func+ names.add(getattr(func, "id", None) or getattr(func, "attr", None))+ for field in ("body", "orelse", "finalbody"):+ names |= _import_time_calls(getattr(node, field, []) or [])+ for handler in getattr(node, "handlers", []) or []:+ names |= _import_time_calls(handler.body)+ return names++[email protected]("relative", _ENTRYPOINTS)+def test_entrypoint_activates_native_tls_at_module_level(relative):+ tree = ast.parse((_BACKEND / relative).read_text(encoding = "utf-8"))+ assert "activate_native_tls" in _import_time_calls(+ tree.body+ ), f"{relative} spawns a fresh interpreter but never calls activate_native_tls()"++[email protected](("module", "attr"), _PROBE_SCRIPTS)+def test_probe_script_activates_before_it_downloads(module, attr):+ script = getattr(importlib.import_module(module), attr)+ ast.parse(script) # it is real source; a paste error only shows up in the child+ # The shared helper, or the generated gate, which honours the opt-out itself.+ activate = max(script.find("activate_native_tls"), script.find("inject_into_ssl"))+ assert activate != -1, f"{attr} lost its native TLS activation"+ if "inject_into_ssl" in script:+ assert "UNSLOTH_STUDIO_NATIVE_TLS" in script, f"{attr} injects without the opt-out"+ assert activate < script.find(".from_pretrained("), f"{attr} downloads before activating"+++def test_prebuilt_core_gate_matches_the_generated_source():+ """The one copy that cannot be generated at runtime, so assert it here.++ prebuilt_core.py is vendored beside the backend and imports nothing from it,+ so its gate is a paste. Drift here is silent: the installers would keep+ downloading against certifi while everything else used the OS store.+ Compare parsed statements, not text: ruff-format rewrites the paste (quote+ style, line wrapping) without changing what it does.+ """+ from utils.native_tls import inline_gate_source++ source = (_BACKEND.parent / "prebuilt_core.py").read_text(encoding = "utf-8")+ gate = [ast.dump(node) for node in ast.parse(inline_gate_source()).body]+ body = [ast.dump(node) for node in ast.parse(source).body]+ assert any(body[i : i + len(gate)] == gate for i in range(len(body) - len(gate) + 1)), (+ "prebuilt_core.py's gate has drifted from native_tls.inline_gate_source(); "+ "paste the current output of that function over it"+ )+++def test_backend_serves_no_tls_in_process():+ """truststore's injection is client-side: a context built after it cannot serve TLS.++ Studio serves plain HTTP on loopback, but an in-process HTTPS listener added+ later would fail at handshake wherever activation is default-on.+ """+ server_side = ("PROTOCOL_TLS_SERVER", "ssl_certfile", "ssl_keyfile")+ offenders = []+ for path in _BACKEND.rglob("*.py"):+ if "tests" in path.parts:+ continue+ text = path.read_text(encoding = "utf-8", errors = "ignore")+ if any(marker in text for marker in server_side):+ offenders.append(str(path.relative_to(_BACKEND)))+ assert not offenders, (+ "in-process TLS server found, which the native TLS injection breaks: "+ + ", ".join(offenders)+ )+++def test_prebuilt_installer_core_injects_at_import():+ """The llama.cpp / whisper.cpp installers are vendored standalone: no backend import."""+ source = (_BACKEND.parent / "prebuilt_core.py").read_text(encoding = "utf-8")+ assert "UNSLOTH_STUDIO_NATIVE_TLS" in source+ assert "inject_into_ssl" in _import_time_calls(ast.parse(source).body)diff --git a/studio/backend/tests/test_vendored_truststore.py b/studio/backend/tests/test_vendored_truststore.pynew file mode 100644index 00000000000..047904c0351--- /dev/null+++ b/studio/backend/tests/test_vendored_truststore.py@@ -0,0 +1,130 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The vendored truststore stays byte-identical to the release it came from.++It is a static copy: nothing refreshes it, so any change to these bytes is either+a deliberate version bump that must update the manifest with it, or an accident.+The accident is the dangerous one, since it means Studio verifies certificates+with code no upstream release ever shipped.+"""++from __future__ import annotations++import ast+import hashlib+import json+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+_VENDOR = _BACKEND / "vendor"+_MANIFEST = json.loads((_VENDOR / "truststore_manifest.json").read_text(encoding = "utf-8"))++# Everything the vendor directory is allowed to hold, beyond the package itself.+_SIDECARS = {"LICENSE", "README.md", "truststore_manifest.json"}+# Ours, not upstream's: prose we may reword, and the manifest cannot hash itself.+_UNPINNED = {"README.md", "truststore_manifest.json"}+++def _tracked_files() -> dict[str, Path]:+ """The real tree, enumerated, so an *added* file is caught and not just an edit."""+ return {+ path.relative_to(_VENDOR).as_posix(): path+ for path in sorted(_VENDOR.rglob("*"))+ if path.is_file() and "__pycache__" not in path.parts and path.name not in _UNPINNED+ }+++def test_vendored_tree_matches_the_manifest():+ found = _tracked_files()+ recorded = _MANIFEST["files"]+ assert set(found) == set(recorded), (+ "the vendored tree gained or lost a file; it is a static copy of upstream "+ f"{_MANIFEST['version']}, so update truststore_manifest.json in the same commit"+ )+ drifted = [+ name+ for name, path in found.items()+ if hashlib.sha256(path.read_bytes()).hexdigest() != recorded[name]+ ]+ assert not drifted, (+ f"vendored files no longer match upstream {_MANIFEST['version']}: {', '.join(drifted)}. "+ "A formatter most likely rewrote them; check the vendor excludes in pyproject.toml "+ "and .pre-commit-config.yaml"+ )+++def test_no_symlinks_or_special_files():+ """A symlink would let the digest check pass while the imported bytes differ."""+ offenders = [+ str(path.relative_to(_VENDOR))+ for path in _VENDOR.rglob("*")+ if path.is_symlink() or (path.exists() and not path.is_file() and not path.is_dir())+ ]+ assert not offenders, f"vendor tree must be plain files: {offenders}"+++def test_vendor_holds_nothing_but_truststore():+ """The gate appends this directory to sys.path, so anything else here is importable."""+ top_level = {path.name for path in _VENDOR.iterdir()} - _SIDECARS+ assert top_level == {"truststore"}, (+ f"unexpected entries in the vendor directory: {sorted(top_level - {'truststore'})}. "+ "Appending it to sys.path would make them importable as top-level modules"+ )+++def test_vendor_is_not_a_package():+ """No __init__.py: a dotted import would load these files under a second name.++ `import truststore` and `import studio.backend.vendor.truststore` are two+ sys.modules entries, each with its own _original_SSLContext, so injecting+ from both wraps ssl twice.+ """+ assert not (_VENDOR / "__init__.py").exists(), (+ "studio/backend/vendor must not be a package; it ships via the "+ "backend/vendor/**/* package-data glob instead"+ )+++def test_nothing_imports_the_vendor_path_directly():+ studio = _BACKEND.parent+ offenders = []+ for path in studio.rglob("*.py"):+ if "vendor" in path.parts or "node_modules" in path.parts:+ continue+ try:+ tree = ast.parse(path.read_text(encoding = "utf-8", errors = "ignore"))+ except SyntaxError:+ continue+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom) and "vendor" in (node.module or ""):+ offenders.append(f"{path.relative_to(studio)}:{node.lineno}")+ elif isinstance(node, ast.Import):+ if any("vendor" in alias.name.split(".") for alias in node.names):+ offenders.append(f"{path.relative_to(studio)}:{node.lineno}")+ assert not offenders, (+ "import the vendored package as top-level `truststore` after appending the vendor "+ f"directory to sys.path, never by its dotted path: {offenders}"+ )+++def test_vendored_version_is_the_one_recorded():+ from utils.native_tls import vendor_dir++ spec = Path(vendor_dir()) / "truststore" / "__init__.py"+ version = next(+ line.split("=")[1].strip().strip('"')+ for line in spec.read_text(encoding = "utf-8").splitlines()+ if line.startswith("__version__")+ )+ assert (+ version == _MANIFEST["version"]+ ), f"vendored truststore is {version} but the manifest records {_MANIFEST['version']}"++[email protected]("relative", ["LICENSE", "README.md"])+def test_provenance_files_are_present(relative):+ """MIT requires the licence to travel with the copy."""+ assert (_VENDOR / relative).read_text(encoding = "utf-8").strip()diff --git a/studio/backend/utils/mlx_repair.py b/studio/backend/utils/mlx_repair.pyindex 3912923ff0a..78890bd308c 100644--- a/studio/backend/utils/mlx_repair.py+++ b/studio/backend/utils/mlx_repair.py@@ -105,6 +105,9 @@ _MLX_ENV_ALLOWLIST = frozenset("SSL_CERT_DIR","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE",+ # uv's rustls reads these, not the CA bundle vars above (native_tls.py)+ "UV_SYSTEM_CERTS",+ "UV_NATIVE_TLS",})_REPAIR_TIMEOUT_S = 900diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex aec15bad6ad..ee4207fcc8e 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -760,6 +760,13 @@ if backend_dir not in sys.path:"""+ _build_vision_check_inline_helpers()+ r"""+# Fresh interpreter, and AutoConfig.from_pretrained below may hit the Hub.+try:+ from utils.native_tls import activate_native_tls+ activate_native_tls()+except Exception:+ pass+try:from transformers import AutoConfigdiff --git a/studio/backend/utils/native_tls.py b/studio/backend/utils/native_tls.pynew file mode 100644index 00000000000..d48d5dcf8d3--- /dev/null+++ b/studio/backend/utils/native_tls.py@@ -0,0 +1,132 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Verify TLS against the OS trust store (corporate TLS-inspection proxies).++Python's ``ssl`` trusts only certifi's roots, so behind a TLS-inspecting proxy+(Cisco Umbrella, Zscaler, Netskope) every huggingface.co request fails with+``CERTIFICATE_VERIFY_FAILED``: the proxy re-signs traffic with a corporate CA+that lives only in the OS store. A shell user can export ``SSL_CERT_FILE``, but+GUI launches (macOS ``.app``, desktop shortcuts) never read shell profiles.++``truststore.inject_into_ssl()`` makes ``ssl.SSLContext`` verify against the OS+store instead, the runtime counterpart of ``UV_NATIVE_TLS`` in install.sh.+Injection is process-wide but does not survive a spawn, so every+network-touching entry point calls :func:`activate_native_tls` before its first+TLS connection; the ``python -c`` probes and the standalone prebuilt installers+carry an inline copy of the gating because they cannot import backend modules.++truststore is vendored at ``backend/vendor/`` rather than depended on, so no+Studio user gains a package for a proxy they do not have; see the README there.+Every consumer appends that directory to ``sys.path`` and imports the top-level+name, which keeps a truststore the user installed themselves in front of ours.++Defaults mirror install.sh: on for macOS and Windows, opt-in on Linux via+``UNSLOTH_STUDIO_NATIVE_TLS=1`` (distro OpenSSL configurations vary), opt-out+anywhere with ``0``. Explicit ``SSL_CERT_FILE``/``REQUESTS_CA_BUNDLE`` keep+working, but become additive rather than exclusive, since truststore keeps the+OS anchors alongside them; ``0`` is the way back to a bundle being the only+trust root.++Client side only: the injected class verifies a peer chain on every handshake,+so an ``SSLContext`` built after activation cannot serve TLS. Studio serves+plain HTTP on loopback and ``test_native_tls_entrypoints.py`` keeps it that way;+a future in-process HTTPS listener needs ``truststore.SSLContext`` for outbound+connections instead of this process-wide injection.+"""++from __future__ import annotations++import logging+import os+import sys+from pathlib import Path++_NATIVE_TLS_ENV = "UNSLOTH_STUDIO_NATIVE_TLS"+_DEFAULT_ON_PLATFORMS = ("darwin", "win32")+_TRUTHY = ("1", "true", "yes")+_FALSEY = ("0", "false", "no")++# Resolved from this file so it is right in a checkout and an installed wheel+# alike. Never build it from the cwd or a hardcoded "studio/backend".+_VENDOR_DIR = str(Path(__file__).resolve().parent.parent / "vendor")++_logger = logging.getLogger(__name__)+_activated = False+++def native_tls_enabled() -> bool:+ """Resolve ``UNSLOTH_STUDIO_NATIVE_TLS`` against the platform default."""+ flag = os.environ.get(_NATIVE_TLS_ENV, "").strip().lower()+ if flag in _TRUTHY:+ return True+ if flag in _FALSEY:+ return False+ return sys.platform in _DEFAULT_ON_PLATFORMS+++# Children that cannot import this module (the `python -c` probes,+# prebuilt_core.py) carry the gate as source; generating it from the same+# constants stops it drifting from native_tls_enabled(). The child supplies os,+# sys and _TRUSTSTORE_VENDOR itself, which is what keeps the gate identical+# everywhere despite each child locating the vendor directory differently.+_INLINE_GATE = """\+_flag = os.environ.get({env!r}, '').strip().lower()+if _flag in {truthy!r} or (_flag not in {falsey!r} and sys.platform in {platforms!r}):+ try:+ if _TRUSTSTORE_VENDOR not in sys.path:+ sys.path.append(_TRUSTSTORE_VENDOR)+ import truststore+ truststore.inject_into_ssl()+ except Exception:+ pass+del _flag+"""+++def vendor_dir() -> str:+ """Where the vendored truststore lives, for a child that must be told."""+ return _VENDOR_DIR+++def inline_gate_source() -> str:+ """The gate as executable source, for a child that cannot import this module.++ The child must bind ``_TRUSTSTORE_VENDOR`` to the vendor directory first.+ """+ return _INLINE_GATE.format(+ env = _NATIVE_TLS_ENV,+ truthy = _TRUTHY,+ falsey = _FALSEY,+ platforms = _DEFAULT_ON_PLATFORMS,+ )+++def activate_native_tls() -> bool:+ """Idempotently patch ``ssl`` to verify against the OS trust store.++ Returns True when injection is active. Failure is non-fatal: falling back to+ certifi is the pre-existing, strictly less permissive behaviour.+ """+ global _activated+ if _activated:+ return True+ if not native_tls_enabled():+ return False+ # uv's rustls ignores in-process injection (uv >= 0.11 reads UV_SYSTEM_CERTS,+ # older reads UV_NATIVE_TLS). Mirror one value across both: uv takes either as+ # an opt-in, so an opt-out in one spelling must carry to the other.+ os.environ.setdefault("UV_SYSTEM_CERTS", os.environ.get("UV_NATIVE_TLS", "1"))+ os.environ.setdefault("UV_NATIVE_TLS", os.environ["UV_SYSTEM_CERTS"])+ # append, not insert(0): a user-installed truststore must win over the vendored copy.+ if _VENDOR_DIR not in sys.path:+ sys.path.append(_VENDOR_DIR)+ try:+ import truststore+ truststore.inject_into_ssl()+ except Exception as exc: # noqa: BLE001+ # Warn, no traceback: a silent certifi fallback is what this exists to prevent.+ _logger.warning("native TLS unavailable (%s); TLS keeps certifi defaults", exc)+ return False+ _activated = True+ return Truediff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 7e10f03387d..57c5b9fe2a8 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -45,6 +45,7 @@ import timefrom pathlib import Pathfrom utils.native_path_leases import child_env_without_native_path_secret+from utils.native_tls import inline_gate_source, vendor_dirfrom utils.child_stdio import utf8_child_envfrom utils.hf_cache_settings import get_hf_cache_pathsfrom utils.subprocess_compat import (@@ -1405,9 +1406,18 @@ _PROBE_TIER_ORDER = ("530", "550", "510")_PROBE_TIMEOUT_SECS = 60# config.json-only parse in a sidecar: built-in parser, no repo code, no weights, exit 0 = parses.-_PROBE_CONFIG_SCRIPT = r"""+_PROBE_CONFIG_SCRIPT = (+ r"""import sys, osos.environ["TOKENIZERS_PARALLELISM"] = "false"+# This -c child cannot import backend modules, and AutoConfig.from_pretrained+# below may download from the Hub, so it carries the gate as generated source.+# repr() the path: a Windows backslash or a space must survive into the source.+_TRUSTSTORE_VENDOR = """+ + repr(vendor_dir())+ + "\n"+ + inline_gate_source()+ + r"""target_dir, model_name = sys.argv[1], sys.argv[2]if target_dir: # empty = probe the ambient (default 4.57.x) transformers, no sidecar prependsys.path.insert(0, target_dir)@@ -1421,6 +1431,7 @@ except Exception as exc:sys.stderr.buffer.write((type(exc).__name__ + ": " + str(exc)).encode("utf-8", "replace"))sys.exit(1)"""+)# stderr fragments meaning "couldn't fetch/auth", NOT "needs a newer parser"._PROBE_TRANSIENT_MARKERS = (diff --git a/studio/backend/vendor/LICENSE b/studio/backend/vendor/LICENSEnew file mode 100644index 00000000000..7ec568c1136--- /dev/null+++ b/studio/backend/vendor/LICENSE@@ -0,0 +1,21 @@+The MIT License (MIT)++Copyright (c) 2022 Seth Michael Larson++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in+all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+THE SOFTWARE.diff --git a/studio/backend/vendor/README.md b/studio/backend/vendor/README.mdnew file mode 100644index 00000000000..414b0d4e62e--- /dev/null+++ b/studio/backend/vendor/README.md@@ -0,0 +1,49 @@+# Vendored third-party source++## truststore 0.10.4 (MIT)++- Upstream: https://github.com/sethmlarson/truststore+- Release: https://pypi.org/project/truststore/0.10.4/+- Taken from `truststore-0.10.4-py3-none-any.whl`,+ sha256 `adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981`+- Licence: `LICENSE` beside this file, copied unmodified from the wheel.++`utils/native_tls.py` uses it to verify TLS against the OS trust store, so Studio works behind a+corporate TLS-inspecting proxy. See that module's docstring for the why.++### Why the source is checked in rather than installed++`utils/third_party_source.py` is the usual way this repo consumes pinned third-party source, but it+downloads over `urllib` at first use. That cannot work here: behind the proxy this exists to fix, the+download of truststore would itself fail with `CERTIFICATE_VERIFY_FAILED`. The copy has to be present+before the network is. pip vendors truststore for the same reason.++The files are byte-identical to upstream, so they carry no Unsloth licence header. The linters and+formatters are configured to skip this directory (`[tool.ruff] extend-exclude` in `pyproject.toml`+and the `ruff-format-with-kwargs` hook's `exclude` in `.pre-commit-config.yaml`); without both,+`scripts/enforce_kwargs_spacing.py` rewrites them and they stop matching upstream.++### How it is imported++Only ever by appending this directory to `sys.path` and importing the top-level name:++```python+sys.path.append(".../studio/backend/vendor")+import truststore+```++Never `from studio.backend.vendor import truststore`. This directory has no `__init__.py` precisely+so that dotted route does not exist: it would load the same files under a second module name, and+each copy of `inject_into_ssl()` would wrap an already-wrapped `ssl.SSLContext`. Appending rather+than prepending also means a real installed truststore still wins.++### Updating++This is a static copy. There is no refresh step and nothing updates it automatically, which is the+point: the bytes that verify certificates only change when someone decides they should.++To move to another release, replace `truststore/` with that version's wheel contents, copy its+`LICENSE`, and update `version`, `wheel`, `wheel_sha256` and the per-file hashes in+`truststore_manifest.json`. `tests/test_vendored_truststore.py` fails until the manifest matches, so+a half-finished swap cannot land. Read upstream's changelog first: a 0.x minor is where truststore+has changed verification behaviour, which here applies process-wide.diff --git a/studio/backend/vendor/truststore/__init__.py b/studio/backend/vendor/truststore/__init__.pynew file mode 100644index 00000000000..0166459b40f--- /dev/null+++ b/studio/backend/vendor/truststore/__init__.py@@ -0,0 +1,36 @@+"""Verify certificates using native system trust stores"""++import sys as _sys++if _sys.version_info < (3, 10):+ raise ImportError("truststore requires Python 3.10 or later")++# Detect Python runtimes which don't implement SSLObject.get_unverified_chain() API+# This API only became public in Python 3.13 but was available in CPython and PyPy since 3.10.+if _sys.version_info < (3, 13) and _sys.implementation.name not in ("cpython", "pypy"):+ try:+ import ssl as _ssl+ except ImportError:+ raise ImportError("truststore requires the 'ssl' module")+ else:+ _sslmem = _ssl.MemoryBIO()+ _sslobj = _ssl.create_default_context().wrap_bio(+ _sslmem,+ _sslmem,+ )+ try:+ while not hasattr(_sslobj, "get_unverified_chain"):+ _sslobj = _sslobj._sslobj # type: ignore[attr-defined]+ except AttributeError:+ raise ImportError(+ "truststore requires peer certificate chain APIs to be available"+ ) from None++ del _ssl, _sslobj, _sslmem # noqa: F821++from ._api import SSLContext, extract_from_ssl, inject_into_ssl # noqa: E402++del _api, _sys # type: ignore[name-defined] # noqa: F821++__all__ = ["SSLContext", "inject_into_ssl", "extract_from_ssl"]+__version__ = "0.10.4"diff --git a/studio/backend/vendor/truststore/_api.py b/studio/backend/vendor/truststore/_api.pynew file mode 100644index 00000000000..4dada0304c4--- /dev/null+++ b/studio/backend/vendor/truststore/_api.py@@ -0,0 +1,341 @@+import contextlib+import os+import platform+import socket+import ssl+import sys+import threading+import typing++import _ssl++from ._ssl_constants import (+ _original_SSLContext,+ _original_super_SSLContext,+ _truststore_SSLContext_dunder_class,+ _truststore_SSLContext_super_class,+)++if platform.system() == "Windows":+ from ._windows import _configure_context, _verify_peercerts_impl+elif platform.system() == "Darwin":+ from ._macos import _configure_context, _verify_peercerts_impl+else:+ from ._openssl import _configure_context, _verify_peercerts_impl++if typing.TYPE_CHECKING:+ from typing_extensions import Buffer++# From typeshed/stdlib/ssl.pyi+_StrOrBytesPath: typing.TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes]+_PasswordType: typing.TypeAlias = str | bytes | typing.Callable[[], str | bytes]+++def inject_into_ssl() -> None:+ """Injects the :class:`truststore.SSLContext` into the ``ssl``+ module by replacing :class:`ssl.SSLContext`.+ """+ setattr(ssl, "SSLContext", SSLContext)+ # urllib3 holds on to its own reference of ssl.SSLContext+ # so we need to replace that reference too.+ try:+ import urllib3.util.ssl_ as urllib3_ssl++ setattr(urllib3_ssl, "SSLContext", SSLContext)+ except ImportError:+ pass++ # requests starting with 2.32.0 added a preloaded SSL context to improve concurrent performance;+ # this unfortunately leads to a RecursionError, which can be avoided by patching the preloaded SSL context with+ # the truststore patched instance+ # also see https://github.com/psf/requests/pull/6667+ try:+ import requests.adapters++ preloaded_context = getattr(requests.adapters, "_preloaded_ssl_context", None)+ if preloaded_context is not None:+ setattr(+ requests.adapters,+ "_preloaded_ssl_context",+ SSLContext(ssl.PROTOCOL_TLS_CLIENT),+ )+ except ImportError:+ pass+++def extract_from_ssl() -> None:+ """Restores the :class:`ssl.SSLContext` class to its original state"""+ setattr(ssl, "SSLContext", _original_SSLContext)+ try:+ import urllib3.util.ssl_ as urllib3_ssl++ urllib3_ssl.SSLContext = _original_SSLContext+ except ImportError:+ pass+++class SSLContext(_truststore_SSLContext_super_class): # type: ignore[misc]+ """SSLContext API that uses system certificates on all platforms"""++ @property # type: ignore[misc]+ def __class__(self) -> type:+ # Dirty hack to get around isinstance() checks+ # for ssl.SSLContext instances in aiohttp/trustme+ # when using non-CPython implementations.+ return _truststore_SSLContext_dunder_class or SSLContext++ def __init__(self, protocol: int = None) -> None: # type: ignore[assignment]+ self._ctx = _original_SSLContext(protocol)+ self._ctx_lock = threading.Lock()++ class TruststoreSSLObject(ssl.SSLObject):+ # This object exists because wrap_bio() doesn't+ # immediately do the handshake so we need to do+ # certificate verifications after SSLObject.do_handshake()++ def do_handshake(self) -> None:+ ret = super().do_handshake()+ _verify_peercerts(self, server_hostname=self.server_hostname)+ return ret++ self._ctx.sslobject_class = TruststoreSSLObject++ def wrap_socket(+ self,+ sock: socket.socket,+ server_side: bool = False,+ do_handshake_on_connect: bool = True,+ suppress_ragged_eofs: bool = True,+ server_hostname: str | None = None,+ session: ssl.SSLSession | None = None,+ ) -> ssl.SSLSocket:++ # We need to lock around the .__enter__()+ # but we don't need to lock within the+ # context manager, so we need to expand the+ # syntactic sugar of the `with` statement.+ with contextlib.ExitStack() as stack:+ with self._ctx_lock:+ stack.enter_context(_configure_context(self._ctx))++ ssl_sock = self._ctx.wrap_socket(+ sock,+ server_side=server_side,+ server_hostname=server_hostname,+ do_handshake_on_connect=do_handshake_on_connect,+ suppress_ragged_eofs=suppress_ragged_eofs,+ session=session,+ )+ try:+ _verify_peercerts(ssl_sock, server_hostname=server_hostname)+ except Exception:+ ssl_sock.close()+ raise+ return ssl_sock++ def wrap_bio(+ self,+ incoming: ssl.MemoryBIO,+ outgoing: ssl.MemoryBIO,+ server_side: bool = False,+ server_hostname: str | None = None,+ session: ssl.SSLSession | None = None,+ ) -> ssl.SSLObject:+ with _configure_context(self._ctx):+ ssl_obj = self._ctx.wrap_bio(+ incoming,+ outgoing,+ server_hostname=server_hostname,+ server_side=server_side,+ session=session,+ )+ return ssl_obj++ def load_verify_locations(+ self,+ cafile: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,+ capath: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,+ cadata: typing.Union[str, "Buffer", None] = None,+ ) -> None:+ return self._ctx.load_verify_locations(+ cafile=cafile, capath=capath, cadata=cadata+ )++ def load_cert_chain(+ self,+ certfile: _StrOrBytesPath,+ keyfile: _StrOrBytesPath | None = None,+ password: _PasswordType | None = None,+ ) -> None:+ return self._ctx.load_cert_chain(+ certfile=certfile, keyfile=keyfile, password=password+ )++ def load_default_certs(+ self, purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH+ ) -> None:+ return self._ctx.load_default_certs(purpose)++ def set_alpn_protocols(self, alpn_protocols: typing.Iterable[str]) -> None:+ return self._ctx.set_alpn_protocols(alpn_protocols)++ def set_npn_protocols(self, npn_protocols: typing.Iterable[str]) -> None:+ return self._ctx.set_npn_protocols(npn_protocols)++ def set_ciphers(self, __cipherlist: str) -> None:+ return self._ctx.set_ciphers(__cipherlist)++ def get_ciphers(self) -> typing.Any:+ return self._ctx.get_ciphers()++ def session_stats(self) -> dict[str, int]:+ return self._ctx.session_stats()++ def cert_store_stats(self) -> dict[str, int]:+ raise NotImplementedError()++ def set_default_verify_paths(self) -> None:+ self._ctx.set_default_verify_paths()++ @typing.overload+ def get_ca_certs(+ self, binary_form: typing.Literal[False] = ...+ ) -> list[typing.Any]: ...++ @typing.overload+ def get_ca_certs(self, binary_form: typing.Literal[True] = ...) -> list[bytes]: ...++ @typing.overload+ def get_ca_certs(self, binary_form: bool = ...) -> typing.Any: ...++ def get_ca_certs(self, binary_form: bool = False) -> list[typing.Any] | list[bytes]:+ raise NotImplementedError()++ @property+ def check_hostname(self) -> bool:+ return self._ctx.check_hostname++ @check_hostname.setter+ def check_hostname(self, value: bool) -> None:+ self._ctx.check_hostname = value++ @property+ def hostname_checks_common_name(self) -> bool:+ return self._ctx.hostname_checks_common_name++ @hostname_checks_common_name.setter+ def hostname_checks_common_name(self, value: bool) -> None:+ self._ctx.hostname_checks_common_name = value++ @property+ def keylog_filename(self) -> str:+ return self._ctx.keylog_filename++ @keylog_filename.setter+ def keylog_filename(self, value: str) -> None:+ self._ctx.keylog_filename = value++ @property+ def maximum_version(self) -> ssl.TLSVersion:+ return self._ctx.maximum_version++ @maximum_version.setter+ def maximum_version(self, value: ssl.TLSVersion) -> None:+ _original_super_SSLContext.maximum_version.__set__( # type: ignore[attr-defined]+ self._ctx, value+ )++ @property+ def minimum_version(self) -> ssl.TLSVersion:+ return self._ctx.minimum_version++ @minimum_version.setter+ def minimum_version(self, value: ssl.TLSVersion) -> None:+ _original_super_SSLContext.minimum_version.__set__( # type: ignore[attr-defined]+ self._ctx, value+ )++ @property+ def options(self) -> ssl.Options:+ return self._ctx.options++ @options.setter+ def options(self, value: ssl.Options) -> None:+ _original_super_SSLContext.options.__set__( # type: ignore[attr-defined]+ self._ctx, value+ )++ @property+ def post_handshake_auth(self) -> bool:+ return self._ctx.post_handshake_auth++ @post_handshake_auth.setter+ def post_handshake_auth(self, value: bool) -> None:+ self._ctx.post_handshake_auth = value++ @property+ def protocol(self) -> ssl._SSLMethod:+ return self._ctx.protocol++ @property+ def security_level(self) -> int:+ return self._ctx.security_level++ @property+ def verify_flags(self) -> ssl.VerifyFlags:+ return self._ctx.verify_flags++ @verify_flags.setter+ def verify_flags(self, value: ssl.VerifyFlags) -> None:+ _original_super_SSLContext.verify_flags.__set__( # type: ignore[attr-defined]+ self._ctx, value+ )++ @property+ def verify_mode(self) -> ssl.VerifyMode:+ return self._ctx.verify_mode++ @verify_mode.setter+ def verify_mode(self, value: ssl.VerifyMode) -> None:+ _original_super_SSLContext.verify_mode.__set__( # type: ignore[attr-defined]+ self._ctx, value+ )+++# Python 3.13+ makes get_unverified_chain() a public API that only returns DER+# encoded certificates. We detect whether we need to call public_bytes() for 3.10->3.12+# Pre-3.13 returned None instead of an empty list from get_unverified_chain()+if sys.version_info >= (3, 13):++ def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:+ unverified_chain = sslobj.get_unverified_chain() or ()+ return [+ cert if isinstance(cert, bytes) else cert.public_bytes(_ssl.ENCODING_DER)+ for cert in unverified_chain+ ]++else:++ def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:+ unverified_chain = sslobj.get_unverified_chain() or () # type: ignore[attr-defined]+ return [cert.public_bytes(_ssl.ENCODING_DER) for cert in unverified_chain]+++def _verify_peercerts(+ sock_or_sslobj: ssl.SSLSocket | ssl.SSLObject, server_hostname: str | None+) -> None:+ """+ Verifies the peer certificates from an SSLSocket or SSLObject+ against the certificates in the OS trust store.+ """+ sslobj: ssl.SSLObject = sock_or_sslobj # type: ignore[assignment]+ try:+ while not hasattr(sslobj, "get_unverified_chain"):+ sslobj = sslobj._sslobj # type: ignore[attr-defined]+ except AttributeError:+ pass++ cert_bytes = _get_unverified_chain_bytes(sslobj)+ _verify_peercerts_impl(+ sock_or_sslobj.context, cert_bytes, server_hostname=server_hostname+ )diff --git a/studio/backend/vendor/truststore/_macos.py b/studio/backend/vendor/truststore/_macos.pynew file mode 100644index 00000000000..34503077244--- /dev/null+++ b/studio/backend/vendor/truststore/_macos.py@@ -0,0 +1,571 @@+import contextlib+import ctypes+import platform+import ssl+import typing+from ctypes import (+ CDLL,+ POINTER,+ c_bool,+ c_char_p,+ c_int32,+ c_long,+ c_uint32,+ c_ulong,+ c_void_p,+)+from ctypes.util import find_library++from ._ssl_constants import _set_ssl_context_verify_mode++_mac_version = platform.mac_ver()[0]+_mac_version_info = tuple(map(int, _mac_version.split(".")))+if _mac_version_info < (10, 8):+ raise ImportError(+ f"Only OS X 10.8 and newer are supported, not {_mac_version_info[0]}.{_mac_version_info[1]}"+ )++_is_macos_version_10_14_or_later = _mac_version_info >= (10, 14)+++def _load_cdll(name: str, macos10_16_path: str) -> CDLL:+ """Loads a CDLL by name, falling back to known path on 10.16+"""+ try:+ # Big Sur is technically 11 but we use 10.16 due to the Big Sur+ # beta being labeled as 10.16.+ path: str | None+ if _mac_version_info >= (10, 16):+ path = macos10_16_path+ else:+ path = find_library(name)+ if not path:+ raise OSError # Caught and reraised as 'ImportError'+ return CDLL(path, use_errno=True)+ except OSError:+ raise ImportError(f"The library {name} failed to load") from None+++Security = _load_cdll(+ "Security", "/System/Library/Frameworks/Security.framework/Security"+)+CoreFoundation = _load_cdll(+ "CoreFoundation",+ "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",+)++Boolean = c_bool+CFIndex = c_long+CFStringEncoding = c_uint32+CFData = c_void_p+CFString = c_void_p+CFArray = c_void_p+CFMutableArray = c_void_p+CFError = c_void_p+CFType = c_void_p+CFTypeID = c_ulong+CFTypeRef = POINTER(CFType)+CFAllocatorRef = c_void_p++OSStatus = c_int32++CFErrorRef = POINTER(CFError)+CFDataRef = POINTER(CFData)+CFStringRef = POINTER(CFString)+CFArrayRef = POINTER(CFArray)+CFMutableArrayRef = POINTER(CFMutableArray)+CFArrayCallBacks = c_void_p+CFOptionFlags = c_uint32++SecCertificateRef = POINTER(c_void_p)+SecPolicyRef = POINTER(c_void_p)+SecTrustRef = POINTER(c_void_p)+SecTrustResultType = c_uint32+SecTrustOptionFlags = c_uint32++try:+ Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]+ Security.SecCertificateCreateWithData.restype = SecCertificateRef++ Security.SecCertificateCopyData.argtypes = [SecCertificateRef]+ Security.SecCertificateCopyData.restype = CFDataRef++ Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]+ Security.SecCopyErrorMessageString.restype = CFStringRef++ Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]+ Security.SecTrustSetAnchorCertificates.restype = OSStatus++ Security.SecTrustSetAnchorCertificatesOnly.argtypes = [SecTrustRef, Boolean]+ Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus++ Security.SecPolicyCreateRevocation.argtypes = [CFOptionFlags]+ Security.SecPolicyCreateRevocation.restype = SecPolicyRef++ Security.SecPolicyCreateSSL.argtypes = [Boolean, CFStringRef]+ Security.SecPolicyCreateSSL.restype = SecPolicyRef++ Security.SecTrustCreateWithCertificates.argtypes = [+ CFTypeRef,+ CFTypeRef,+ POINTER(SecTrustRef),+ ]+ Security.SecTrustCreateWithCertificates.restype = OSStatus++ Security.SecTrustGetTrustResult.argtypes = [+ SecTrustRef,+ POINTER(SecTrustResultType),+ ]+ Security.SecTrustGetTrustResult.restype = OSStatus++ Security.SecTrustEvaluate.argtypes = [+ SecTrustRef,+ POINTER(SecTrustResultType),+ ]+ Security.SecTrustEvaluate.restype = OSStatus++ Security.SecTrustRef = SecTrustRef # type: ignore[attr-defined]+ Security.SecTrustResultType = SecTrustResultType # type: ignore[attr-defined]+ Security.OSStatus = OSStatus # type: ignore[attr-defined]++ kSecRevocationUseAnyAvailableMethod = 3+ kSecRevocationRequirePositiveResponse = 8++ CoreFoundation.CFRelease.argtypes = [CFTypeRef]+ CoreFoundation.CFRelease.restype = None++ CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]+ CoreFoundation.CFGetTypeID.restype = CFTypeID++ CoreFoundation.CFStringCreateWithCString.argtypes = [+ CFAllocatorRef,+ c_char_p,+ CFStringEncoding,+ ]+ CoreFoundation.CFStringCreateWithCString.restype = CFStringRef++ CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]+ CoreFoundation.CFStringGetCStringPtr.restype = c_char_p++ CoreFoundation.CFStringGetCString.argtypes = [+ CFStringRef,+ c_char_p,+ CFIndex,+ CFStringEncoding,+ ]+ CoreFoundation.CFStringGetCString.restype = c_bool++ CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]+ CoreFoundation.CFDataCreate.restype = CFDataRef++ CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]+ CoreFoundation.CFDataGetLength.restype = CFIndex++ CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]+ CoreFoundation.CFDataGetBytePtr.restype = c_void_p++ CoreFoundation.CFArrayCreate.argtypes = [+ CFAllocatorRef,+ POINTER(CFTypeRef),+ CFIndex,+ CFArrayCallBacks,+ ]+ CoreFoundation.CFArrayCreate.restype = CFArrayRef++ CoreFoundation.CFArrayCreateMutable.argtypes = [+ CFAllocatorRef,+ CFIndex,+ CFArrayCallBacks,+ ]+ CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef++ CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]+ CoreFoundation.CFArrayAppendValue.restype = None++ CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]+ CoreFoundation.CFArrayGetCount.restype = CFIndex++ CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]+ CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p++ CoreFoundation.CFErrorGetCode.argtypes = [CFErrorRef]+ CoreFoundation.CFErrorGetCode.restype = CFIndex++ CoreFoundation.CFErrorCopyDescription.argtypes = [CFErrorRef]+ CoreFoundation.CFErrorCopyDescription.restype = CFStringRef++ CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( # type: ignore[attr-defined]+ CoreFoundation, "kCFAllocatorDefault"+ )+ CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( # type: ignore[attr-defined]+ CoreFoundation, "kCFTypeArrayCallBacks"+ )++ CoreFoundation.CFTypeRef = CFTypeRef # type: ignore[attr-defined]+ CoreFoundation.CFArrayRef = CFArrayRef # type: ignore[attr-defined]+ CoreFoundation.CFStringRef = CFStringRef # type: ignore[attr-defined]+ CoreFoundation.CFErrorRef = CFErrorRef # type: ignore[attr-defined]++except AttributeError as e:+ raise ImportError(f"Error initializing ctypes: {e}") from None++# SecTrustEvaluateWithError is macOS 10.14++if _is_macos_version_10_14_or_later:+ try:+ Security.SecTrustEvaluateWithError.argtypes = [+ SecTrustRef,+ POINTER(CFErrorRef),+ ]+ Security.SecTrustEvaluateWithError.restype = c_bool+ except AttributeError as e:+ raise ImportError(f"Error initializing ctypes: {e}") from None+++def _handle_osstatus(result: OSStatus, _: typing.Any, args: typing.Any) -> typing.Any:+ """+ Raises an error if the OSStatus value is non-zero.+ """+ if int(result) == 0:+ return args++ # Returns a CFString which we need to transform+ # into a UTF-8 Python string.+ error_message_cfstring = None+ try:+ error_message_cfstring = Security.SecCopyErrorMessageString(result, None)++ # First step is convert the CFString into a C string pointer.+ # We try the fast no-copy way first.+ error_message_cfstring_c_void_p = ctypes.cast(+ error_message_cfstring, ctypes.POINTER(ctypes.c_void_p)+ )+ message = CoreFoundation.CFStringGetCStringPtr(+ error_message_cfstring_c_void_p, CFConst.kCFStringEncodingUTF8+ )++ # Quoting the Apple dev docs:+ #+ # "A pointer to a C string or NULL if the internal+ # storage of theString does not allow this to be+ # returned efficiently."+ #+ # So we need to get our hands dirty.+ if message is None:+ buffer = ctypes.create_string_buffer(1024)+ result = CoreFoundation.CFStringGetCString(+ error_message_cfstring_c_void_p,+ buffer,+ 1024,+ CFConst.kCFStringEncodingUTF8,+ )+ if not result:+ raise OSError("Error copying C string from CFStringRef")+ message = buffer.value++ finally:+ if error_message_cfstring is not None:+ CoreFoundation.CFRelease(error_message_cfstring)++ # If no message can be found for this status we come+ # up with a generic one that forwards the status code.+ if message is None or message == "":+ message = f"SecureTransport operation returned a non-zero OSStatus: {result}"++ raise ssl.SSLError(message)+++Security.SecTrustCreateWithCertificates.errcheck = _handle_osstatus # type: ignore[assignment]+Security.SecTrustSetAnchorCertificates.errcheck = _handle_osstatus # type: ignore[assignment]+Security.SecTrustSetAnchorCertificatesOnly.errcheck = _handle_osstatus # type: ignore[assignment]+Security.SecTrustGetTrustResult.errcheck = _handle_osstatus # type: ignore[assignment]+Security.SecTrustEvaluate.errcheck = _handle_osstatus # type: ignore[assignment]+++class CFConst:+ """CoreFoundation constants"""++ kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)++ errSecIncompleteCertRevocationCheck = -67635+ errSecHostNameMismatch = -67602+ errSecCertificateExpired = -67818+ errSecNotTrusted = -67843+++def _bytes_to_cf_data_ref(value: bytes) -> CFDataRef: # type: ignore[valid-type]+ return CoreFoundation.CFDataCreate( # type: ignore[no-any-return]+ CoreFoundation.kCFAllocatorDefault, value, len(value)+ )+++def _bytes_to_cf_string(value: bytes) -> CFString:+ """+ Given a Python binary data, create a CFString.+ The string must be CFReleased by the caller.+ """+ c_str = ctypes.c_char_p(value)+ cf_str = CoreFoundation.CFStringCreateWithCString(+ CoreFoundation.kCFAllocatorDefault,+ c_str,+ CFConst.kCFStringEncodingUTF8,+ )+ return cf_str # type: ignore[no-any-return]+++def _cf_string_ref_to_str(cf_string_ref: CFStringRef) -> str | None: # type: ignore[valid-type]+ """+ Creates a Unicode string from a CFString object. Used entirely for error+ reporting.+ Yes, it annoys me quite a lot that this function is this complex.+ """++ string = CoreFoundation.CFStringGetCStringPtr(+ cf_string_ref, CFConst.kCFStringEncodingUTF8+ )+ if string is None:+ buffer = ctypes.create_string_buffer(1024)+ result = CoreFoundation.CFStringGetCString(+ cf_string_ref, buffer, 1024, CFConst.kCFStringEncodingUTF8+ )+ if not result:+ raise OSError("Error copying C string from CFStringRef")+ string = buffer.value+ if string is not None:+ string = string.decode("utf-8")+ return string # type: ignore[no-any-return]+++def _der_certs_to_cf_cert_array(certs: list[bytes]) -> CFMutableArrayRef: # type: ignore[valid-type]+ """Builds a CFArray of SecCertificateRefs from a list of DER-encoded certificates.+ Responsibility of the caller to call CoreFoundation.CFRelease on the CFArray.+ """+ cf_array = CoreFoundation.CFArrayCreateMutable(+ CoreFoundation.kCFAllocatorDefault,+ 0,+ ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),+ )+ if not cf_array:+ raise MemoryError("Unable to allocate memory!")++ for cert_data in certs:+ cf_data = None+ sec_cert_ref = None+ try:+ cf_data = _bytes_to_cf_data_ref(cert_data)+ sec_cert_ref = Security.SecCertificateCreateWithData(+ CoreFoundation.kCFAllocatorDefault, cf_data+ )+ CoreFoundation.CFArrayAppendValue(cf_array, sec_cert_ref)+ finally:+ if cf_data:+ CoreFoundation.CFRelease(cf_data)+ if sec_cert_ref:+ CoreFoundation.CFRelease(sec_cert_ref)++ return cf_array # type: ignore[no-any-return]+++def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:+ check_hostname = ctx.check_hostname+ verify_mode = ctx.verify_mode+ ctx.check_hostname = False+ _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)+ try:+ yield+ finally:+ ctx.check_hostname = check_hostname+ _set_ssl_context_verify_mode(ctx, verify_mode)+++def _verify_peercerts_impl(+ ssl_context: ssl.SSLContext,+ cert_chain: list[bytes],+ server_hostname: str | None = None,+) -> None:+ certs = None+ policies = None+ trust = None+ try:+ # Only set a hostname on the policy if we're verifying the hostname+ # on the leaf certificate.+ if server_hostname is not None and ssl_context.check_hostname:+ cf_str_hostname = None+ try:+ cf_str_hostname = _bytes_to_cf_string(server_hostname.encode("ascii"))+ ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname)+ finally:+ if cf_str_hostname:+ CoreFoundation.CFRelease(cf_str_hostname)+ else:+ ssl_policy = Security.SecPolicyCreateSSL(True, None)++ policies = ssl_policy+ if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:+ # Add explicit policy requiring positive revocation checks+ policies = CoreFoundation.CFArrayCreateMutable(+ CoreFoundation.kCFAllocatorDefault,+ 0,+ ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),+ )+ CoreFoundation.CFArrayAppendValue(policies, ssl_policy)+ CoreFoundation.CFRelease(ssl_policy)+ revocation_policy = Security.SecPolicyCreateRevocation(+ kSecRevocationUseAnyAvailableMethod+ | kSecRevocationRequirePositiveResponse+ )+ CoreFoundation.CFArrayAppendValue(policies, revocation_policy)+ CoreFoundation.CFRelease(revocation_policy)+ elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:+ raise NotImplementedError("VERIFY_CRL_CHECK_LEAF not implemented for macOS")++ certs = None+ try:+ certs = _der_certs_to_cf_cert_array(cert_chain)++ # Now that we have certificates loaded and a SecPolicy+ # we can finally create a SecTrust object!+ trust = Security.SecTrustRef()+ Security.SecTrustCreateWithCertificates(+ certs, policies, ctypes.byref(trust)+ )++ finally:+ # The certs are now being held by SecTrust so we can+ # release our handles for the array.+ if certs:+ CoreFoundation.CFRelease(certs)++ # If there are additional trust anchors to load we need to transform+ # the list of DER-encoded certificates into a CFArray.+ ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs(+ binary_form=True+ )+ if ctx_ca_certs_der:+ ctx_ca_certs = None+ try:+ ctx_ca_certs = _der_certs_to_cf_cert_array(ctx_ca_certs_der)+ Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs)+ finally:+ if ctx_ca_certs:+ CoreFoundation.CFRelease(ctx_ca_certs)++ # We always want system certificates.+ Security.SecTrustSetAnchorCertificatesOnly(trust, False)++ # macOS 10.13 and earlier don't support SecTrustEvaluateWithError()+ # so we use SecTrustEvaluate() which means we need to construct error+ # messages ourselves.+ if _is_macos_version_10_14_or_later:+ _verify_peercerts_impl_macos_10_14(ssl_context, trust)+ else:+ _verify_peercerts_impl_macos_10_13(ssl_context, trust)+ finally:+ if policies:+ CoreFoundation.CFRelease(policies)+ if trust:+ CoreFoundation.CFRelease(trust)+++def _verify_peercerts_impl_macos_10_13(+ ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any+) -> None:+ """Verify using 'SecTrustEvaluate' API for macOS 10.13 and earlier.+ macOS 10.14 added the 'SecTrustEvaluateWithError' API.+ """+ sec_trust_result_type = Security.SecTrustResultType()+ Security.SecTrustEvaluate(sec_trust_ref, ctypes.byref(sec_trust_result_type))++ try:+ sec_trust_result_type_as_int = int(sec_trust_result_type.value)+ except (ValueError, TypeError):+ sec_trust_result_type_as_int = -1++ # Apple doesn't document these values in their own API docs.+ # See: https://github.com/xybp888/iOS-SDKs/blob/master/iPhoneOS13.0.sdk/System/Library/Frameworks/Security.framework/Headers/SecTrust.h#L84+ if (+ ssl_context.verify_mode == ssl.CERT_REQUIRED+ and sec_trust_result_type_as_int not in (1, 4)+ ):+ # Note that we're not able to ignore only hostname errors+ # for macOS 10.13 and earlier, so check_hostname=False will+ # still return an error.+ sec_trust_result_type_to_message = {+ 0: "Invalid trust result type",+ # 1: "Trust evaluation succeeded",+ 2: "User confirmation required",+ 3: "User specified that certificate is not trusted",+ # 4: "Trust result is unspecified",+ 5: "Recoverable trust failure occurred",+ 6: "Fatal trust failure occurred",+ 7: "Other error occurred, certificate may be revoked",+ }+ error_message = sec_trust_result_type_to_message.get(+ sec_trust_result_type_as_int,+ f"Unknown trust result: {sec_trust_result_type_as_int}",+ )++ err = ssl.SSLCertVerificationError(error_message)+ err.verify_message = error_message+ err.verify_code = sec_trust_result_type_as_int+ raise err+++def _verify_peercerts_impl_macos_10_14(+ ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any+) -> None:+ """Verify using 'SecTrustEvaluateWithError' API for macOS 10.14+."""+ cf_error = CoreFoundation.CFErrorRef()+ sec_trust_eval_result = Security.SecTrustEvaluateWithError(+ sec_trust_ref, ctypes.byref(cf_error)+ )+ # sec_trust_eval_result is a bool (0 or 1)+ # where 1 means that the certs are trusted.+ if sec_trust_eval_result == 1:+ is_trusted = True+ elif sec_trust_eval_result == 0:+ is_trusted = False+ else:+ raise ssl.SSLError(+ f"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}"+ )++ cf_error_code = 0+ if not is_trusted:+ cf_error_code = CoreFoundation.CFErrorGetCode(cf_error)++ # If the error is a known failure that we're+ # explicitly okay with from SSLContext configuration+ # we can set is_trusted accordingly.+ if ssl_context.verify_mode != ssl.CERT_REQUIRED and (+ cf_error_code == CFConst.errSecNotTrusted+ or cf_error_code == CFConst.errSecCertificateExpired+ ):+ is_trusted = True++ # If we're still not trusted then we start to+ # construct and raise the SSLCertVerificationError.+ if not is_trusted:+ cf_error_string_ref = None+ try:+ cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error)++ # Can this ever return 'None' if there's a CFError?+ cf_error_message = (+ _cf_string_ref_to_str(cf_error_string_ref)+ or "Certificate verification failed"+ )++ # TODO: Not sure if we need the SecTrustResultType for anything?+ # We only care whether or not it's a success or failure for now.+ sec_trust_result_type = Security.SecTrustResultType()+ Security.SecTrustGetTrustResult(+ sec_trust_ref, ctypes.byref(sec_trust_result_type)+ )++ err = ssl.SSLCertVerificationError(cf_error_message)+ err.verify_message = cf_error_message+ err.verify_code = cf_error_code+ raise err+ finally:+ if cf_error_string_ref:+ CoreFoundation.CFRelease(cf_error_string_ref)diff --git a/studio/backend/vendor/truststore/_openssl.py b/studio/backend/vendor/truststore/_openssl.pynew file mode 100644index 00000000000..3e25a56773a--- /dev/null+++ b/studio/backend/vendor/truststore/_openssl.py@@ -0,0 +1,68 @@+import contextlib+import os+import re+import ssl+import typing++# candidates based on https://github.com/tiran/certifi-system-store by Christian Heimes+_CA_FILE_CANDIDATES = [+ # Alpine, Arch, Fedora 34-42, OpenWRT, RHEL 9-10, BSD+ "/etc/ssl/cert.pem",+ # Fedora 43+, RHEL 11++ "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",+ # Fedora <= 34, RHEL <= 9, CentOS <= 9+ "/etc/pki/tls/cert.pem",+ # Debian, Ubuntu (requires ca-certificates)+ "/etc/ssl/certs/ca-certificates.crt",+ # SUSE+ "/etc/ssl/ca-bundle.pem",+]++_HASHED_CERT_FILENAME_RE = re.compile(r"^[0-9a-fA-F]{8}\.[0-9]$")+++def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:+ # First, check whether the default locations from OpenSSL+ # seem like they will give us a usable set of CA certs.+ # ssl.get_default_verify_paths already takes care of:+ # - getting cafile from either the SSL_CERT_FILE env var+ # or the path configured when OpenSSL was compiled,+ # and verifying that that path exists+ # - getting capath from either the SSL_CERT_DIR env var+ # or the path configured when OpenSSL was compiled,+ # and verifying that that path exists+ # In addition we'll check whether capath appears to contain certs.+ defaults = ssl.get_default_verify_paths()+ if defaults.cafile or (defaults.capath and _capath_contains_certs(defaults.capath)):+ ctx.set_default_verify_paths()+ else:+ # cafile from OpenSSL doesn't exist+ # and capath from OpenSSL doesn't contain certs.+ # Let's search other common locations instead.+ for cafile in _CA_FILE_CANDIDATES:+ if os.path.isfile(cafile):+ ctx.load_verify_locations(cafile=cafile)+ break++ yield+++def _capath_contains_certs(capath: str) -> bool:+ """Check whether capath exists and contains certs in the expected format."""+ if not os.path.isdir(capath):+ return False+ for name in os.listdir(capath):+ if _HASHED_CERT_FILENAME_RE.match(name):+ return True+ return False+++def _verify_peercerts_impl(+ ssl_context: ssl.SSLContext,+ cert_chain: list[bytes],+ server_hostname: str | None = None,+) -> None:+ # This is a no-op because we've enabled SSLContext's built-in+ # verification via verify_mode=CERT_REQUIRED, and don't need to repeat it.+ passdiff --git a/studio/backend/vendor/truststore/_ssl_constants.py b/studio/backend/vendor/truststore/_ssl_constants.pynew file mode 100644index 00000000000..b1ee7a3cb13--- /dev/null+++ b/studio/backend/vendor/truststore/_ssl_constants.py@@ -0,0 +1,31 @@+import ssl+import sys+import typing++# Hold on to the original class so we can create it consistently+# even if we inject our own SSLContext into the ssl module.+_original_SSLContext = ssl.SSLContext+_original_super_SSLContext = super(_original_SSLContext, _original_SSLContext)++# CPython is known to be good, but non-CPython implementations+# may implement SSLContext differently so to be safe we don't+# subclass the SSLContext.++# This is returned by truststore.SSLContext.__class__()+_truststore_SSLContext_dunder_class: typing.Optional[type]++# This value is the superclass of truststore.SSLContext.+_truststore_SSLContext_super_class: type++if sys.implementation.name == "cpython":+ _truststore_SSLContext_super_class = _original_SSLContext+ _truststore_SSLContext_dunder_class = None+else:+ _truststore_SSLContext_super_class = object+ _truststore_SSLContext_dunder_class = _original_SSLContext+++def _set_ssl_context_verify_mode(+ ssl_context: ssl.SSLContext, verify_mode: ssl.VerifyMode+) -> None:+ _original_super_SSLContext.verify_mode.__set__(ssl_context, verify_mode) # type: ignore[attr-defined]diff --git a/studio/backend/vendor/truststore/_windows.py b/studio/backend/vendor/truststore/_windows.pynew file mode 100644index 00000000000..a9bf9abdfc8--- /dev/null+++ b/studio/backend/vendor/truststore/_windows.py@@ -0,0 +1,567 @@+import contextlib+import ssl+import typing+from ctypes import WinDLL # type: ignore+from ctypes import WinError # type: ignore+from ctypes import (+ POINTER,+ Structure,+ c_char_p,+ c_ulong,+ c_void_p,+ c_wchar_p,+ cast,+ create_unicode_buffer,+ pointer,+ sizeof,+)+from ctypes.wintypes import (+ BOOL,+ DWORD,+ HANDLE,+ LONG,+ LPCSTR,+ LPCVOID,+ LPCWSTR,+ LPFILETIME,+ LPSTR,+ LPWSTR,+)+from typing import TYPE_CHECKING, Any++from ._ssl_constants import _set_ssl_context_verify_mode++HCERTCHAINENGINE = HANDLE+HCERTSTORE = HANDLE+HCRYPTPROV_LEGACY = HANDLE+++class CERT_CONTEXT(Structure):+ _fields_ = (+ ("dwCertEncodingType", DWORD),+ ("pbCertEncoded", c_void_p),+ ("cbCertEncoded", DWORD),+ ("pCertInfo", c_void_p),+ ("hCertStore", HCERTSTORE),+ )+++PCERT_CONTEXT = POINTER(CERT_CONTEXT)+PCCERT_CONTEXT = POINTER(PCERT_CONTEXT)+++class CERT_ENHKEY_USAGE(Structure):+ _fields_ = (+ ("cUsageIdentifier", DWORD),+ ("rgpszUsageIdentifier", POINTER(LPSTR)),+ )+++PCERT_ENHKEY_USAGE = POINTER(CERT_ENHKEY_USAGE)+++class CERT_USAGE_MATCH(Structure):+ _fields_ = (+ ("dwType", DWORD),+ ("Usage", CERT_ENHKEY_USAGE),+ )+++class CERT_CHAIN_PARA(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("RequestedUsage", CERT_USAGE_MATCH),+ ("RequestedIssuancePolicy", CERT_USAGE_MATCH),+ ("dwUrlRetrievalTimeout", DWORD),+ ("fCheckRevocationFreshnessTime", BOOL),+ ("dwRevocationFreshnessTime", DWORD),+ ("pftCacheResync", LPFILETIME),+ ("pStrongSignPara", c_void_p),+ ("dwStrongSignFlags", DWORD),+ )+++if TYPE_CHECKING:+ PCERT_CHAIN_PARA = pointer[CERT_CHAIN_PARA] # type: ignore[misc]+else:+ PCERT_CHAIN_PARA = POINTER(CERT_CHAIN_PARA)+++class CERT_TRUST_STATUS(Structure):+ _fields_ = (+ ("dwErrorStatus", DWORD),+ ("dwInfoStatus", DWORD),+ )+++class CERT_CHAIN_ELEMENT(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("pCertContext", PCERT_CONTEXT),+ ("TrustStatus", CERT_TRUST_STATUS),+ ("pRevocationInfo", c_void_p),+ ("pIssuanceUsage", PCERT_ENHKEY_USAGE),+ ("pApplicationUsage", PCERT_ENHKEY_USAGE),+ ("pwszExtendedErrorInfo", LPCWSTR),+ )+++PCERT_CHAIN_ELEMENT = POINTER(CERT_CHAIN_ELEMENT)+++class CERT_SIMPLE_CHAIN(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("TrustStatus", CERT_TRUST_STATUS),+ ("cElement", DWORD),+ ("rgpElement", POINTER(PCERT_CHAIN_ELEMENT)),+ ("pTrustListInfo", c_void_p),+ ("fHasRevocationFreshnessTime", BOOL),+ ("dwRevocationFreshnessTime", DWORD),+ )+++PCERT_SIMPLE_CHAIN = POINTER(CERT_SIMPLE_CHAIN)+++class CERT_CHAIN_CONTEXT(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("TrustStatus", CERT_TRUST_STATUS),+ ("cChain", DWORD),+ ("rgpChain", POINTER(PCERT_SIMPLE_CHAIN)),+ ("cLowerQualityChainContext", DWORD),+ ("rgpLowerQualityChainContext", c_void_p),+ ("fHasRevocationFreshnessTime", BOOL),+ ("dwRevocationFreshnessTime", DWORD),+ )+++PCERT_CHAIN_CONTEXT = POINTER(CERT_CHAIN_CONTEXT)+PCCERT_CHAIN_CONTEXT = POINTER(PCERT_CHAIN_CONTEXT)+++class SSL_EXTRA_CERT_CHAIN_POLICY_PARA(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("dwAuthType", DWORD),+ ("fdwChecks", DWORD),+ ("pwszServerName", LPCWSTR),+ )+++class CERT_CHAIN_POLICY_PARA(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("dwFlags", DWORD),+ ("pvExtraPolicyPara", c_void_p),+ )+++PCERT_CHAIN_POLICY_PARA = POINTER(CERT_CHAIN_POLICY_PARA)+++class CERT_CHAIN_POLICY_STATUS(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("dwError", DWORD),+ ("lChainIndex", LONG),+ ("lElementIndex", LONG),+ ("pvExtraPolicyStatus", c_void_p),+ )+++PCERT_CHAIN_POLICY_STATUS = POINTER(CERT_CHAIN_POLICY_STATUS)+++class CERT_CHAIN_ENGINE_CONFIG(Structure):+ _fields_ = (+ ("cbSize", DWORD),+ ("hRestrictedRoot", HCERTSTORE),+ ("hRestrictedTrust", HCERTSTORE),+ ("hRestrictedOther", HCERTSTORE),+ ("cAdditionalStore", DWORD),+ ("rghAdditionalStore", c_void_p),+ ("dwFlags", DWORD),+ ("dwUrlRetrievalTimeout", DWORD),+ ("MaximumCachedCertificates", DWORD),+ ("CycleDetectionModulus", DWORD),+ ("hExclusiveRoot", HCERTSTORE),+ ("hExclusiveTrustedPeople", HCERTSTORE),+ ("dwExclusiveFlags", DWORD),+ )+++PCERT_CHAIN_ENGINE_CONFIG = POINTER(CERT_CHAIN_ENGINE_CONFIG)+PHCERTCHAINENGINE = POINTER(HCERTCHAINENGINE)++X509_ASN_ENCODING = 0x00000001+PKCS_7_ASN_ENCODING = 0x00010000+CERT_STORE_PROV_MEMORY = b"Memory"+CERT_STORE_ADD_USE_EXISTING = 2+USAGE_MATCH_TYPE_OR = 1+OID_PKIX_KP_SERVER_AUTH = c_char_p(b"1.3.6.1.5.5.7.3.1")+CERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000+CERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000+CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS = 0x00000007+CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG = 0x00000008+CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG = 0x00000010+CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG = 0x00000040+CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG = 0x00000020+CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG = 0x00000080+CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS = 0x00000F00+CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG = 0x00008000+CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG = 0x00004000+SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000+AUTHTYPE_SERVER = 2+CERT_CHAIN_POLICY_SSL = 4+FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000+FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200++# Flags to set for SSLContext.verify_mode=CERT_NONE+CERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS = (+ CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS+ | CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG+ | CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG+ | CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG+ | CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG+ | CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG+ | CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS+ | CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG+ | CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG+)++wincrypt = WinDLL("crypt32.dll")+kernel32 = WinDLL("kernel32.dll")+++def _handle_win_error(result: bool, _: Any, args: Any) -> Any:+ if not result:+ # Note, actually raises OSError after calling GetLastError and FormatMessage+ raise WinError()+ return args+++CertCreateCertificateChainEngine = wincrypt.CertCreateCertificateChainEngine+CertCreateCertificateChainEngine.argtypes = (+ PCERT_CHAIN_ENGINE_CONFIG,+ PHCERTCHAINENGINE,+)+CertCreateCertificateChainEngine.errcheck = _handle_win_error++CertOpenStore = wincrypt.CertOpenStore+CertOpenStore.argtypes = (LPCSTR, DWORD, HCRYPTPROV_LEGACY, DWORD, c_void_p)+CertOpenStore.restype = HCERTSTORE+CertOpenStore.errcheck = _handle_win_error++CertAddEncodedCertificateToStore = wincrypt.CertAddEncodedCertificateToStore+CertAddEncodedCertificateToStore.argtypes = (+ HCERTSTORE,+ DWORD,+ c_char_p,+ DWORD,+ DWORD,+ PCCERT_CONTEXT,+)+CertAddEncodedCertificateToStore.restype = BOOL++CertCreateCertificateContext = wincrypt.CertCreateCertificateContext+CertCreateCertificateContext.argtypes = (DWORD, c_char_p, DWORD)+CertCreateCertificateContext.restype = PCERT_CONTEXT+CertCreateCertificateContext.errcheck = _handle_win_error++CertGetCertificateChain = wincrypt.CertGetCertificateChain+CertGetCertificateChain.argtypes = (+ HCERTCHAINENGINE,+ PCERT_CONTEXT,+ LPFILETIME,+ HCERTSTORE,+ PCERT_CHAIN_PARA,+ DWORD,+ c_void_p,+ PCCERT_CHAIN_CONTEXT,+)+CertGetCertificateChain.restype = BOOL+CertGetCertificateChain.errcheck = _handle_win_error++CertVerifyCertificateChainPolicy = wincrypt.CertVerifyCertificateChainPolicy+CertVerifyCertificateChainPolicy.argtypes = (+ c_ulong,+ PCERT_CHAIN_CONTEXT,+ PCERT_CHAIN_POLICY_PARA,+ PCERT_CHAIN_POLICY_STATUS,+)+CertVerifyCertificateChainPolicy.restype = BOOL++CertCloseStore = wincrypt.CertCloseStore+CertCloseStore.argtypes = (HCERTSTORE, DWORD)+CertCloseStore.restype = BOOL+CertCloseStore.errcheck = _handle_win_error++CertFreeCertificateChain = wincrypt.CertFreeCertificateChain+CertFreeCertificateChain.argtypes = (PCERT_CHAIN_CONTEXT,)++CertFreeCertificateContext = wincrypt.CertFreeCertificateContext+CertFreeCertificateContext.argtypes = (PCERT_CONTEXT,)++CertFreeCertificateChainEngine = wincrypt.CertFreeCertificateChainEngine+CertFreeCertificateChainEngine.argtypes = (HCERTCHAINENGINE,)++FormatMessageW = kernel32.FormatMessageW+FormatMessageW.argtypes = (+ DWORD,+ LPCVOID,+ DWORD,+ DWORD,+ LPWSTR,+ DWORD,+ c_void_p,+)+FormatMessageW.restype = DWORD+++def _verify_peercerts_impl(+ ssl_context: ssl.SSLContext,+ cert_chain: list[bytes],+ server_hostname: str | None = None,+) -> None:+ """Verify the cert_chain from the server using Windows APIs."""++ # If the peer didn't send any certificates then+ # we can't do verification. Raise an error.+ if not cert_chain:+ raise ssl.SSLCertVerificationError("Peer sent no certificates to verify")++ pCertContext = None+ hIntermediateCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)+ try:+ # Add intermediate certs to an in-memory cert store+ for cert_bytes in cert_chain[1:]:+ CertAddEncodedCertificateToStore(+ hIntermediateCertStore,+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,+ cert_bytes,+ len(cert_bytes),+ CERT_STORE_ADD_USE_EXISTING,+ None,+ )++ # Cert context for leaf cert+ leaf_cert = cert_chain[0]+ pCertContext = CertCreateCertificateContext(+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, leaf_cert, len(leaf_cert)+ )++ # Chain params to match certs for serverAuth extended usage+ cert_enhkey_usage = CERT_ENHKEY_USAGE()+ cert_enhkey_usage.cUsageIdentifier = 1+ cert_enhkey_usage.rgpszUsageIdentifier = (c_char_p * 1)(OID_PKIX_KP_SERVER_AUTH)+ cert_usage_match = CERT_USAGE_MATCH()+ cert_usage_match.Usage = cert_enhkey_usage+ chain_params = CERT_CHAIN_PARA()+ chain_params.RequestedUsage = cert_usage_match+ chain_params.cbSize = sizeof(chain_params)+ pChainPara = pointer(chain_params)++ if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:+ chain_flags = CERT_CHAIN_REVOCATION_CHECK_CHAIN+ elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:+ chain_flags = CERT_CHAIN_REVOCATION_CHECK_END_CERT+ else:+ chain_flags = 0++ try:+ # First attempt to verify using the default Windows system trust roots+ # (default chain engine).+ _get_and_verify_cert_chain(+ ssl_context,+ None,+ hIntermediateCertStore,+ pCertContext,+ pChainPara,+ server_hostname,+ chain_flags=chain_flags,+ )+ except ssl.SSLCertVerificationError as e:+ # If that fails but custom CA certs have been added+ # to the SSLContext using load_verify_locations,+ # try verifying using a custom chain engine+ # that trusts the custom CA certs.+ custom_ca_certs: list[bytes] | None = ssl_context.get_ca_certs(+ binary_form=True+ )+ if custom_ca_certs:+ try:+ _verify_using_custom_ca_certs(+ ssl_context,+ custom_ca_certs,+ hIntermediateCertStore,+ pCertContext,+ pChainPara,+ server_hostname,+ chain_flags=chain_flags,+ )+ # Raise the original error, not the new error.+ except ssl.SSLCertVerificationError:+ raise e from None+ else:+ raise+ finally:+ CertCloseStore(hIntermediateCertStore, 0)+ if pCertContext:+ CertFreeCertificateContext(pCertContext)+++def _get_and_verify_cert_chain(+ ssl_context: ssl.SSLContext,+ hChainEngine: HCERTCHAINENGINE | None,+ hIntermediateCertStore: HCERTSTORE,+ pPeerCertContext: c_void_p,+ pChainPara: PCERT_CHAIN_PARA, # type: ignore[valid-type]+ server_hostname: str | None,+ chain_flags: int,+) -> None:+ ppChainContext = None+ try:+ # Get cert chain+ ppChainContext = pointer(PCERT_CHAIN_CONTEXT())+ CertGetCertificateChain(+ hChainEngine, # chain engine+ pPeerCertContext, # leaf cert context+ None, # current system time+ hIntermediateCertStore, # additional in-memory cert store+ pChainPara, # chain-building parameters+ chain_flags,+ None, # reserved+ ppChainContext, # the resulting chain context+ )+ pChainContext = ppChainContext.contents++ # Verify cert chain+ ssl_extra_cert_chain_policy_para = SSL_EXTRA_CERT_CHAIN_POLICY_PARA()+ ssl_extra_cert_chain_policy_para.cbSize = sizeof(+ ssl_extra_cert_chain_policy_para+ )+ ssl_extra_cert_chain_policy_para.dwAuthType = AUTHTYPE_SERVER+ ssl_extra_cert_chain_policy_para.fdwChecks = 0+ if ssl_context.check_hostname is False:+ ssl_extra_cert_chain_policy_para.fdwChecks = (+ SECURITY_FLAG_IGNORE_CERT_CN_INVALID+ )+ if server_hostname:+ ssl_extra_cert_chain_policy_para.pwszServerName = c_wchar_p(server_hostname)++ chain_policy = CERT_CHAIN_POLICY_PARA()+ chain_policy.pvExtraPolicyPara = cast(+ pointer(ssl_extra_cert_chain_policy_para), c_void_p+ )+ if ssl_context.verify_mode == ssl.CERT_NONE:+ chain_policy.dwFlags |= CERT_CHAIN_POLICY_VERIFY_MODE_NONE_FLAGS+ chain_policy.cbSize = sizeof(chain_policy)++ pPolicyPara = pointer(chain_policy)+ policy_status = CERT_CHAIN_POLICY_STATUS()+ policy_status.cbSize = sizeof(policy_status)+ pPolicyStatus = pointer(policy_status)+ CertVerifyCertificateChainPolicy(+ CERT_CHAIN_POLICY_SSL,+ pChainContext,+ pPolicyPara,+ pPolicyStatus,+ )++ # Check status+ error_code = policy_status.dwError+ if error_code:+ # Try getting a human readable message for an error code.+ error_message_buf = create_unicode_buffer(1024)+ error_message_chars = FormatMessageW(+ FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,+ None,+ error_code,+ 0,+ error_message_buf,+ sizeof(error_message_buf),+ None,+ )++ # See if we received a message for the error,+ # otherwise we use a generic error with the+ # error code and hope that it's search-able.+ if error_message_chars <= 0:+ error_message = f"Certificate chain policy error {error_code:#x} [{policy_status.lElementIndex}]"+ else:+ error_message = error_message_buf.value.strip()++ err = ssl.SSLCertVerificationError(error_message)+ err.verify_message = error_message+ err.verify_code = error_code+ raise err from None+ finally:+ if ppChainContext:+ CertFreeCertificateChain(ppChainContext.contents)+++def _verify_using_custom_ca_certs(+ ssl_context: ssl.SSLContext,+ custom_ca_certs: list[bytes],+ hIntermediateCertStore: HCERTSTORE,+ pPeerCertContext: c_void_p,+ pChainPara: PCERT_CHAIN_PARA, # type: ignore[valid-type]+ server_hostname: str | None,+ chain_flags: int,+) -> None:+ hChainEngine = None+ hRootCertStore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, None, 0, None)+ try:+ # Add custom CA certs to an in-memory cert store+ for cert_bytes in custom_ca_certs:+ CertAddEncodedCertificateToStore(+ hRootCertStore,+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,+ cert_bytes,+ len(cert_bytes),+ CERT_STORE_ADD_USE_EXISTING,+ None,+ )++ # Create a custom cert chain engine which exclusively trusts+ # certs from our hRootCertStore+ cert_chain_engine_config = CERT_CHAIN_ENGINE_CONFIG()+ cert_chain_engine_config.cbSize = sizeof(cert_chain_engine_config)+ cert_chain_engine_config.hExclusiveRoot = hRootCertStore+ pConfig = pointer(cert_chain_engine_config)+ phChainEngine = pointer(HCERTCHAINENGINE())+ CertCreateCertificateChainEngine(+ pConfig,+ phChainEngine,+ )+ hChainEngine = phChainEngine.contents++ # Get and verify a cert chain using the custom chain engine+ _get_and_verify_cert_chain(+ ssl_context,+ hChainEngine,+ hIntermediateCertStore,+ pPeerCertContext,+ pChainPara,+ server_hostname,+ chain_flags,+ )+ finally:+ if hChainEngine:+ CertFreeCertificateChainEngine(hChainEngine)+ CertCloseStore(hRootCertStore, 0)+++def _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:+ check_hostname = ctx.check_hostname+ verify_mode = ctx.verify_mode+ ctx.check_hostname = False+ _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)+ try:+ yield+ finally:+ ctx.check_hostname = check_hostname+ _set_ssl_context_verify_mode(ctx, verify_mode)diff --git a/studio/backend/vendor/truststore/py.typed b/studio/backend/vendor/truststore/py.typednew file mode 100644index 00000000000..e69de29bb2ddiff --git a/studio/backend/vendor/truststore_manifest.json b/studio/backend/vendor/truststore_manifest.jsonnew file mode 100644index 00000000000..09d4a103d08--- /dev/null+++ b/studio/backend/vendor/truststore_manifest.json@@ -0,0 +1,18 @@+{+ "files": {+ "LICENSE": "33be7b7e8fa4fd19b1760e1a8ed8a668bdab852c91b692dd41424bcb725a9fca",+ "truststore/__init__.py": "06eee4aa49a9ba784bb23e710aef204ffdb992da0f5dc4a7c1ef151e4d46989a",+ "truststore/_api.py": "0910c84046483677663181b1c1b9f5db1ce5baddf89b4e9ed94248d8846a232e",+ "truststore/_macos.py": "9d994b90e9accd413483aaf2470055198e423b33f2b9d72c889b4359aacce4b4",+ "truststore/_openssl.py": "cc1f9242f272764b3bb50d32230acfe860f77d035249a3e2abbcf0e321794f8d",+ "truststore/_ssl_constants.py": "3540f87d529d483d36ae2efe75bd2d9ced15a8b3fd687bb3992b5c5bbb40974f",+ "truststore/_windows.py": "ac01f22980fc33bb7e6d77c6f1580e55add3a5f85585bb78ad94253b8e58b8ff",+ "truststore/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "license": "MIT",+ "package": "truststore",+ "source": "https://pypi.org/project/truststore/0.10.4/",+ "version": "0.10.4",+ "wheel": "truststore-0.10.4-py3-none-any.whl",+ "wheel_sha256": "adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981"+}diff --git a/studio/prebuilt_core.py b/studio/prebuilt_core.pyindex d7075815d3f..8a483b34f04 100644--- a/studio/prebuilt_core.py+++ b/studio/prebuilt_core.py@@ -56,6 +56,23 @@ except ImportError:FileLock = NoneFileLockTimeout = None+# Fresh spawned interpreter, and this standalone module cannot import backend+# modules, so the gate is pasted from native_tls.py's inline_gate_source().+# test_native_tls_entrypoints.py asserts the paste still matches, by AST.+_TRUSTSTORE_VENDOR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "backend", "vendor")+_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")+):+ try:+ if _TRUSTSTORE_VENDOR not in sys.path:+ sys.path.append(_TRUSTSTORE_VENDOR)+ import truststore+ truststore.inject_into_ssl()+ except Exception:+ pass+del _flag+class PrebuiltFallback(RuntimeError):pass