Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: serve HTTPS from your own certificate (--ssl-certfile / --ssl-keyfile) (#13447)
Daniel Han966a4b88da69
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex 4be29cf6542..178cbcb1336 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -1531,6 +1531,11 @@ class ResearchSupervisor:return hostdef _endpoint(self) -> str:+ from utils.studio_tls import loopback_http_port++ loopback_port = loopback_http_port(self.app.state)+ if loopback_port is not None:+ return f"http://127.0.0.1:{loopback_port}/v1/chat/completions"port = self._server_port()if port is None:raise RuntimeError("Research is waiting for the Unsloth server port")diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.pyindex f5bef95a3b1..37e501a26bb 100644--- a/studio/backend/lan_access.py+++ b/studio/backend/lan_access.py@@ -20,6 +20,7 @@ interface scope.from __future__ import annotationsimport asyncio+import functoolsimport ipaddressimport platformimport socket@@ -229,7 +230,15 @@ def _bind_listener(address: str, port: int) -> socket.socket:def _listener_config(app, host: str, port: int):from utils.uvicorn_h11_shutdown import uvicorn_http_protocol- return uvicorn.Config(++ # a TLS launch must not reopen plain HTTP on the network+ tls = getattr(getattr(app, "state", None), "studio_tls", None)+ if tls is not None:+ from utils.studio_tls import StudioTLSConfig+ config_class = functools.partial(StudioTLSConfig, tls = tls)+ else:+ config_class = uvicorn.Config+ return config_class(app,host = host,port = port,diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.pyindex ca711280320..35da05c462d 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -190,6 +190,11 @@ ViaApiKey = Annotated[bool, Depends(authenticated_via_api_key)]def _resolve_local_v1_endpoint(request: Request) -> str:"""The /v1 URL of this process's own backend, at the address it is bound to. Port order:``server_port`` (survives proxies/tunnels), the request scope, ``base_url``."""+ from utils.studio_tls import loopback_http_port++ loopback_port = loopback_http_port(request.app.state)+ if loopback_port is not None:+ return f"http://127.0.0.1:{loopback_port}/v1"server = request.scope.get("server")port: Any = getattr(request.app.state, "server_port", None)if not isinstance(port, int) or port <= 0:diff --git a/studio/backend/run.py b/studio/backend/run.pyindex d67329f01df..dc4a32d93d8 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -292,9 +292,9 @@ def _working_local_url(port: int) -> "str | None":"""A working loopback URL on this machine, or None if neither 127.0.0.1 nor::1 responds. Fallback when external reachability fails."""if _local_port_open("127.0.0.1", port):- return f"http://127.0.0.1:{port}"+ return f"{_url_scheme}://127.0.0.1:{port}"if _local_port_open("::1", port):- return f"http://[::1]:{port}"+ return f"{_url_scheme}://[::1]:{port}"return None@@ -307,7 +307,7 @@ def _localhost_ipv6_mismatch_url(bind_host: str, port: int) -> "str | None":if bind_host != "127.0.0.1" or not port or port <= 0:return None- ipv4_url = f"http://127.0.0.1:{port}"+ ipv4_url = f"{_url_scheme}://127.0.0.1:{port}"# Only warn once Unsloth is confirmed answering on IPv4 loopback.if _working_local_url(port) != ipv4_url:@@ -358,7 +358,7 @@ def _print_localhost_ipv6_mismatch_warning(local_url: str, port: int) -> None:print(f"{warn_c} Warning: localhost resolves to IPv6 (::1), but Unsloth "f"Unsloth is listening on 127.0.0.1 only. Open {local_url} instead of "- f"http://localhost:{port}.{reset}",+ f"{_url_scheme}://localhost:{port}.{reset}",flush = True,)@@ -393,7 +393,7 @@ def _verify_global_reachability(local_url_c = "\033[38;5;108;1m" if use_color else ""reset = "\033[0m" if use_color else ""- url = f"http://{_url_host(display_host)}:{port}"+ url = f"{_url_scheme}://{_url_host(display_host)}:{port}"# Private/loopback/link-local addresses aren't globally routable.try:@@ -502,7 +502,7 @@ def _verify_global_reachability(flush = True,)print(- f"{dim} then open http://localhost:{port}/ in your browser.{reset}",+ f"{dim} then open {_url_scheme}://localhost:{port}/ in your browser.{reset}",flush = True,)local_url = _working_local_url(port)@@ -574,7 +574,7 @@ def _print_wsl_windows_hint(port: int) -> None:dim = "\033[38;5;245m" if _stdout_color_ok() else ""reset = "\033[0m" if dim else ""print(- f"{dim} WSL2: open http://localhost:{port} in a Windows browser. Other devices on your "+ f"{dim} WSL2: open {_url_scheme}://localhost:{port} in a Windows browser. Other devices on your "f"network can't reach WSL's NAT address; set networkingMode=mirrored in "f"%UserProfile%\\.wslconfig for LAN access.{reset}",flush = True,@@ -590,12 +590,13 @@ def _direct_server_url(host: str, port: int) -> "Optional[str]":frontend prefers any non-null server_url over the origin the client reached, so publishing``http://0.0.0.0:<port>`` (a wildcard bind with no LAN address: WSL behind NAT, loopback-only) wouldput an unroutable address in the API examples, the desktop agent command and a copied preview link."""- if not port or port <= 0:+ # A TLS certificate usually names a DNS host, not the LAN IP; the frontend then falls back to its own origin.+ if not port or port <= 0 or _url_scheme == "https":return Noneshare_host = _network_share_host_for_bind(host)if is_wildcard_host(share_host):return None- return f"http://{_url_host(share_host)}:{port}"+ return f"{_url_scheme}://{_url_host(share_host)}:{port}"def _tool_policy_notice(host: str, secure: bool, enable_tools: "Optional[bool]") -> str:@@ -669,6 +670,7 @@ def _emit_startup_output(network_host = _network_share_host_for_bind(host),include_stop_hint = False,lan_addresses = lan_addresses,+ scheme = _url_scheme,)if localhost_mismatch_url:_print_localhost_ipv6_mismatch_warning(localhost_mismatch_url, port)@@ -677,7 +679,8 @@ def _emit_startup_output(if wsl_nat:_print_wsl_windows_hint(port)_verify_global_reachability(display_host, port, wsl_nat = wsl_nat)- _print_cloudflare_line(loopback_host = _loopback_bind_host_for(host))+ if _url_scheme == "http": # --cloudflare is refused alongside --ssl-certfile+ _print_cloudflare_line(loopback_host = _loopback_bind_host_for(host))_emit_tool_policy_notice(lan_addresses[0] if lan_addresses else host, False, enable_tools)print_studio_stop_hint()@@ -1650,6 +1653,8 @@ def _wait_for_server_shutdown(timeout: Optional[float] = _SERVER_SHUTDOWN_JOIN_T_server = None_server_thread = None+# "https" for an --ssl-certfile launch, used by every URL the launch prints for itself+_url_scheme = "http"_shutdown_event = None@@ -2440,6 +2445,8 @@ def run_server(password: "Optional[str]" = None,emit_tauri_port: bool = True,abort_if_own_studio: "Optional[bool]" = None,+ ssl_certfile: "Optional[str]" = None,+ ssl_keyfile: "Optional[str]" = None,):"""Start the FastAPI server. Public entry point: colab.py and other embedders import it.@@ -2449,12 +2456,12 @@ def run_server(when a Tauri-owned backend has a live tunnel. ``emit_tauri_port`` prints the machine-readableTAURI_PORT line the desktop app parses; ``run --api-only`` turns it off so it does not pollutethe URL and API-key banner. ``enable_tools`` of None leaves the default on, honouring a- request's own ``enable_tools: false``.+ request's own ``enable_tools: false``. ``ssl_certfile`` + ``ssl_keyfile`` serve HTTPS from that pair.Signal handlers are NOT registered here, so embedders keep their own interrupt semantics;standalone callers register them afterwards."""- global _server, _server_thread, _shutdown_event+ global _server, _server_thread, _shutdown_event, _url_schemeif not isinstance(host, str) or not host.strip():raise SystemExit("--host cannot be empty; use 0.0.0.0 to bind every IPv4 interface.")@@ -2468,6 +2475,15 @@ def run_server(raise SystemExit("--secure requires the Cloudflare tunnel; do not combine it with --no-cloudflare.")+ from utils.studio_tls import resolve_studio_tls++ tls = resolve_studio_tls(ssl_certfile, ssl_keyfile)+ if tls is not None and (secure or cloudflare):+ # The tunnel dials the origin over plain HTTP.+ raise SystemExit(+ "--ssl-certfile/--ssl-keyfile serve HTTPS directly; do not combine them with --secure or --cloudflare."+ )+ _url_scheme = "https" if tls is not None else "http"if not secure:try:host = normalize_wildcard_bind_host(host)@@ -2643,7 +2659,7 @@ def run_server(else:print(f"Port {original_port} is already in use.")print(f"Unsloth Studio will use port {port} instead.")- print(f"Open http://localhost:{port} in your browser.")+ print(f"Open {_url_scheme}://localhost:{port} in your browser.")print("=" * 50)print("")@@ -2727,8 +2743,12 @@ def run_server(startup_errors = []class _ReadyServer(uvicorn.Server):+ loopback_http = None+async def startup(self, *args, **kwargs):await super().startup(*args, **kwargs)+ if tls is not None and getattr(self, "started", False) and not self.should_exit:+ await self._start_loopback_http()if getattr(self, "started", False) and not self.should_exit:logger.info("Uvicorn startup hook completed in %.1fms",@@ -2736,6 +2756,29 @@ def run_server()ready_event.set()+ async def _start_loopback_http(self):+ # Plain HTTP on an ephemeral loopback port for Studio's own /v1 self-calls (utils/studio_tls.py). Kept out+ # of self.servers: _final_bound_port and _bound_request_host read the user's listener from there.+ config = self.config++ def _protocol(_loop = None):+ return config.http_protocol_class(+ config = config,+ server_state = self.server_state,+ app_state = self.lifespan.state,+ _loop = _loop,+ )++ self.loopback_http = await asyncio.get_running_loop().create_server(+ _protocol, host = "127.0.0.1", port = 0, backlog = config.backlog+ )+ app.state.loopback_http_port = self.loopback_http.sockets[0].getsockname()[1]++ async def shutdown(self, *args, **kwargs):+ if self.loopback_http is not None:+ self.loopback_http.close()+ await super().shutdown(*args, **kwargs)+# server_header=False suppresses uvicorn's "Server: uvicorn"; SecurityHeadersMiddleware sets its own.# http=... is uvicorn's own h11 protocol unless we are on the plain-h11 path, where it becomes a subclass# that ignores socket reads delivered after the connection was already closed. Without it every clean@@ -2756,7 +2799,13 @@ def run_server(if _IS_COLAB:config_kwargs["proxy_headers"] = Trueconfig_kwargs["forwarded_allow_ips"] = "*"- config = uvicorn.Config(app, **config_kwargs)+ if tls is not None:+ from utils.studio_tls import StudioTLSConfig+ config = StudioTLSConfig(app, tls = tls, **config_kwargs)+ else:+ config = uvicorn.Config(app, **config_kwargs)+ app.state.studio_tls = tls+ app.state.loopback_http_port = None_server = _ReadyServer(config)_shutdown_event = Event()@@ -3176,6 +3225,16 @@ def _build_arg_parser():"(Parallel Slots) override it per load."),)+ parser.add_argument(+ "--ssl-certfile",+ default = None,+ help = "Serve HTTPS with this certificate (PEM, full chain). Needs --ssl-keyfile.",+ )+ parser.add_argument(+ "--ssl-keyfile",+ default = None,+ help = "Private key (PEM) for --ssl-certfile.",+ )return parser@@ -3218,6 +3277,8 @@ if __name__ == "__main__":secure = args.secure,enable_tools = args.enable_tools,password = args.password,+ ssl_certfile = args.ssl_certfile,+ ssl_keyfile = args.ssl_keyfile,)if args.frontend is not None:kwargs["frontend_path"] = Path(args.frontend)diff --git a/studio/backend/startup_banner.py b/studio/backend/startup_banner.pyindex 45339fc84ce..8fbeb1ba31b 100644--- a/studio/backend/startup_banner.py+++ b/studio/backend/startup_banner.py@@ -79,6 +79,7 @@ def print_studio_access_banner(network_host: str = "",include_stop_hint: bool = True,lan_addresses: "tuple[str, ...]" = (),+ scheme: str = "http",) -> None:"""Pretty-print URLs once the server is listening. Set ``include_stop_hint=False`` to omit thetrailing stop block; pair with :func:`print_studio_stop_hint` after inserting your own content.@@ -102,22 +103,22 @@ def print_studio_access_banner(listen_all = is_wildcard_host(bind_host)ipv6_bind = bind_host == "::1" or wildcard_loopback_host(bind_host) == "::1"if ipv6_bind:- loopback_url = f"http://[::1]:{port}"- alt_local = f"http://localhost:{port}"+ loopback_url = f"{scheme}://[::1]:{port}"+ alt_local = f"{scheme}://localhost:{port}"else:- loopback_url = f"http://127.0.0.1:{port}"- alt_local = f"http://localhost:{port}"+ loopback_url = f"{scheme}://127.0.0.1:{port}"+ alt_local = f"{scheme}://localhost:{port}"if ":" in display_host:- external_url = f"http://[{display_host}]:{port}"+ external_url = f"{scheme}://[{display_host}]:{port}"else:- external_url = f"http://{display_host}:{port}"+ external_url = f"{scheme}://{display_host}:{port}"# Falls back to display_host for a caller with only one address to give.resolved_network_host = network_host or display_hostif ":" in resolved_network_host:- network_url = f"http://[{resolved_network_host}]:{port}"+ network_url = f"{scheme}://[{resolved_network_host}]:{port}"else:- network_url = f"http://{resolved_network_host}:{port}"+ network_url = f"{scheme}://{resolved_network_host}:{port}"# The exact aliases the canned loopback_url is valid for; any other bind (e.g. a specific LAN IP)# must show its real address, not http://127.0.0.1.loopback_bind = bind_host in ("127.0.0.1", "localhost", "::1")@@ -174,7 +175,7 @@ def print_studio_access_banner(lines.append(style(" LAN access is on -- also reachable on your network at:", secondary))- lines.extend(style(f" http://{a}:{port}", secondary) for a in lan_addresses)+ lines.extend(style(f" {scheme}://{a}:{port}", secondary) for a in lan_addresses)lines.append(style(" Turn it off in Settings > Remote & LAN > LAN access.", secondary))else:lines.extend(diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.pyindex 45df3fbb651..1a4b626a921 100644--- a/studio/backend/tests/test_cloudflare_tunnel.py+++ b/studio/backend/tests/test_cloudflare_tunnel.py@@ -1420,6 +1420,7 @@ def test_verify_global_reachability_marks_private_address_unreachable():captured = []ns = {"_public_reachable": None,+ "_url_scheme": "http","_stdout_color_ok": lambda: False,"is_wildcard_host": lambda _host: False,"_url_host": lambda host: host,diff --git a/studio/backend/tests/test_native_tls_entrypoints.py b/studio/backend/tests/test_native_tls_entrypoints.pyindex b03463f65f3..f6251fd4e8a 100644--- a/studio/backend/tests/test_native_tls_entrypoints.py+++ b/studio/backend/tests/test_native_tls_entrypoints.py@@ -95,19 +95,42 @@ def test_prebuilt_core_gate_matches_the_generated_source():)+# Builds the server context with truststore's peer-chain hook removed; test_studio_tls.py proves the handshake.+_TLS_SERVER_MODULE = Path("utils") / "studio_tls.py"+_UVICORN_SERVERS = {"Config", "run"}+++def _builds_tls_server(tree) -> bool:+ for node in ast.walk(tree):+ if isinstance(node, ast.Attribute) and node.attr in (+ "PROTOCOL_TLS_SERVER",+ "load_cert_chain",+ ):+ return True+ if isinstance(node, ast.Call):+ func = node.func+ name = getattr(func, "id", None) or getattr(func, "attr", None)+ if name in _UVICORN_SERVERS and any(+ kw.arg in ("ssl_certfile", "ssl_keyfile") for kw in node.keywords+ ):+ return True+ return False++def test_backend_serves_no_tls_in_process():"""truststore's injection is client-side: a context built after it cannot serve TLS.- Unsloth serves plain HTTP on loopback, but an in-process HTTPS listener added- later would fail at handshake wherever activation is default-on.+ Any in-process HTTPS listener must go through utils/studio_tls.py, or it+ fails 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:+ if "tests" in path.parts or "vendor" in path.parts:+ continue+ if path.relative_to(_BACKEND) == _TLS_SERVER_MODULE:continuetext = path.read_text(encoding = "utf-8", errors = "ignore")- if any(marker in text for marker in server_side):+ if _builds_tls_server(ast.parse(text)):offenders.append(str(path.relative_to(_BACKEND)))assert not offenders, ("in-process TLS server found, which the native TLS injection breaks: "diff --git a/studio/backend/tests/test_studio_tls.py b/studio/backend/tests/test_studio_tls.pynew file mode 100644index 00000000000..708767e39be--- /dev/null+++ b/studio/backend/tests/test_studio_tls.py@@ -0,0 +1,268 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""--ssl-certfile / --ssl-keyfile: validation, the HTTPS handshake under native TLS, and the URLs Studio prints."""++from __future__ import annotations++import datetime+import socket+import ssl+import subprocess+import sys+import textwrap+import types+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+++def _write_pair(tmp_path: Path, name: str = "studio.example.ts.net") -> tuple[Path, Path]:+ from cryptography import x509+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import ec+ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID++ key = ec.generate_private_key(ec.SECP256R1())+ subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])+ now = datetime.datetime.now(datetime.timezone.utc)+ cert = (+ x509.CertificateBuilder()+ .subject_name(subject)+ .issuer_name(subject)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now - datetime.timedelta(minutes = 5))+ .not_valid_after(now + datetime.timedelta(days = 1))+ .add_extension(x509.SubjectAlternativeName([x509.DNSName(name)]), critical = False)+ .add_extension(x509.BasicConstraints(ca = True, path_length = None), critical = True)+ # macOS's verifier (truststore in the client too) refuses a TLS server cert without serverAuth+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical = False)+ .add_extension(+ x509.KeyUsage(+ digital_signature = True,+ content_commitment = False,+ key_encipherment = False,+ data_encipherment = False,+ key_agreement = False,+ key_cert_sign = True,+ crl_sign = False,+ encipher_only = False,+ decipher_only = False,+ ),+ critical = True,+ )+ .sign(key, hashes.SHA256())+ )+ crt, key_path = tmp_path / f"{name}.crt", tmp_path / f"{name}.key"+ crt.write_bytes(cert.public_bytes(serialization.Encoding.PEM))+ key_path.write_bytes(+ key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ )+ )+ return crt, key_path+++def test_no_flags_is_plain_http():+ from utils.studio_tls import resolve_studio_tls+ assert resolve_studio_tls(None, None) is None+ assert resolve_studio_tls("", " ") is None+++def test_valid_pair_resolves_to_absolute_paths(tmp_path, monkeypatch):+ from utils.studio_tls import resolve_studio_tls++ crt, key = _write_pair(tmp_path)+ monkeypatch.chdir(tmp_path)+ tls = resolve_studio_tls(crt.name, key.name)+ assert tls.certfile == str(crt) and tls.keyfile == str(key)++[email protected]("which", ["cert", "key"])+def test_half_a_pair_is_refused(tmp_path, which):+ from utils.studio_tls import resolve_studio_tls+ crt, key = _write_pair(tmp_path)+ with pytest.raises(SystemExit, match = "must be passed together"):+ resolve_studio_tls(+ str(crt) if which == "cert" else None, str(key) if which == "key" else None+ )+++def test_missing_and_mismatched_files_fail_before_binding(tmp_path):+ from utils.studio_tls import resolve_studio_tls++ crt, key = _write_pair(tmp_path)+ with pytest.raises(SystemExit, match = "--ssl-keyfile: file not found"):+ resolve_studio_tls(str(crt), str(tmp_path / "absent.key"))+ other = tmp_path / "other"+ other.mkdir()+ _, other_key = _write_pair(other, "other.example")+ with pytest.raises(SystemExit, match = "Could not load the TLS certificate and key"):+ resolve_studio_tls(str(crt), str(other_key))+++_SERVE = textwrap.dedent(+ """+ import socket, sys, threading, time+ backend, crt, key, mode = sys.argv[1:5]+ sys.path[:0] = [backend]+ sys.path.append(backend + "/vendor")+ import truststore+ if sys.platform not in ("darwin", "win32"):+ # Linux truststore verifies inside OpenSSL; reproduce the macOS / Windows hook, which raises on an+ # empty peer chain (truststore/_windows.py), so this cell fails the same way they do.+ import ssl+ import truststore._api as api+ def _no_chain(ctx, chain, server_hostname = None):+ if not chain:+ raise ssl.SSLCertVerificationError("Peer sent no certificates to verify")+ api._verify_peercerts_impl = _no_chain+ truststore.inject_into_ssl()+ import uvicorn+ from utils.studio_tls import StudioTLS, StudioTLSConfig++ async def app(scope, receive, send):+ if scope["type"] != "http":+ return+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b"ok"})++ sock = socket.socket()+ sock.bind(("127.0.0.1", 0))+ kwargs = dict(log_level = "error", lifespan = "off")+ if mode == "studio":+ config = StudioTLSConfig(app, tls = StudioTLS(crt, key), **kwargs)+ else:+ config = uvicorn.Config(app, ssl_certfile = crt, ssl_keyfile = key, **kwargs)+ server = uvicorn.Server(config)+ thread = threading.Thread(target = server.run, kwargs = {"sockets": [sock]}, daemon = True)+ thread.start()+ while not server.started:+ if not thread.is_alive():+ sys.exit(1)+ time.sleep(0.05)+ print(sock.getsockname()[1], flush = True)+ sys.stdin.read()+ """+)+++def _handshake(tmp_path, mode: str) -> "bytes | Exception":+ crt, key = _write_pair(tmp_path)+ proc = subprocess.Popen(+ [sys.executable, "-c", _SERVE, str(_BACKEND), str(crt), str(key), mode],+ stdin = subprocess.PIPE,+ stdout = subprocess.PIPE,+ text = True,+ )+ try:+ line = proc.stdout.readline()+ assert line.strip(), f"TLS test server exited during startup (rc={proc.poll()})"+ port = int(line)+ client = ssl.create_default_context(cafile = str(crt))+ try:+ with socket.create_connection(("127.0.0.1", port), timeout = 10) as raw:+ with client.wrap_socket(raw, server_hostname = "studio.example.ts.net") as tls:+ tls.sendall(+ b"GET / HTTP/1.1\r\nHost: studio.example.ts.net\r\nConnection: close\r\n\r\n"+ )+ data = b""+ while chunk := tls.recv(4096):+ data += chunk+ return data+ except (OSError, ssl.SSLError) as exc:+ return exc+ finally:+ proc.stdin.close()+ proc.kill()+ proc.wait(timeout = 10)+++def _served(reply) -> bool:+ return (+ isinstance(reply, bytes)+ and reply.startswith(b"HTTP/1.1 200")+ and b"\r\n2\r\nok\r\n" in reply+ )+++def test_https_handshake_survives_native_tls_injection(tmp_path):+ reply = _handshake(tmp_path, "studio")+ assert _served(reply), reply+++def test_plain_uvicorn_tls_fails_under_injection(tmp_path):+ """Negative control: the hook really breaks a context truststore owns. Under TLS 1.3 the client finishes first,+ so the server's rejection reads as a closed connection, not a client-side error."""+ reply = _handshake(tmp_path, "uvicorn")+ # the client accepting the certificate is what makes this the server's failure+ assert not isinstance(reply, ssl.SSLCertVerificationError), reply+ assert not _served(reply), reply+++def test_banner_uses_https_only_when_asked(capsys):+ from startup_banner import print_studio_access_banner++ print_studio_access_banner(port = 8888, bind_host = "0.0.0.0", display_host = "192.168.1.5")+ plain = capsys.readouterr().out+ print_studio_access_banner(+ port = 8888, bind_host = "0.0.0.0", display_host = "192.168.1.5", scheme = "https"+ )+ tls = capsys.readouterr().out+ assert "http://127.0.0.1:8888" in plain and "https://" not in plain+ assert "https://127.0.0.1:8888" in tls and "https://192.168.1.5:8888" in tls+ assert "http://" not in tls+++def test_lan_listener_serves_tls_when_the_launch_does(tmp_path):+ from lan_access import _listener_config+ from utils.studio_tls import StudioTLSConfig, resolve_studio_tls++ tls = resolve_studio_tls(*map(str, _write_pair(tmp_path)))+ plain_app = types.SimpleNamespace(state = types.SimpleNamespace())+ tls_app = types.SimpleNamespace(state = types.SimpleNamespace(studio_tls = tls))+ assert type(_listener_config(plain_app, "192.168.1.5", 8888)) is not StudioTLSConfig+ config = _listener_config(tls_app, "192.168.1.5", 8888)+ assert isinstance(config, StudioTLSConfig) and config.is_ssl+++def test_self_calls_use_the_loopback_listener():+ from utils.studio_tls import loopback_http_port++ assert loopback_http_port(types.SimpleNamespace()) is None+ assert loopback_http_port(types.SimpleNamespace(loopback_http_port = None)) is None+ assert loopback_http_port(types.SimpleNamespace(loopback_http_port = 41234)) == 41234+++def test_tls_launch_publishes_no_ip_server_url(monkeypatch):+ """A Tailscale / Let's Encrypt cert names a DNS host, so an https://<LAN IP> base would fail verification."""+ import run++ monkeypatch.setattr(run, "_network_share_host_for_bind", lambda host: "192.168.1.5")+ monkeypatch.setattr(run, "_url_scheme", "http")+ assert run._direct_server_url("0.0.0.0", 8888) == "http://192.168.1.5:8888"+ monkeypatch.setattr(run, "_url_scheme", "https")+ assert run._direct_server_url("0.0.0.0", 8888) is None++[email protected]("bind_host", ["192.168.1.5", "studio.example.ts.net"])+def test_tls_launch_on_a_specific_host_still_lists_its_lan_url(tmp_path, bind_host):+ from utils.lan_access_settings import _launch_urls+ from utils.studio_tls import resolve_studio_tls++ tls = resolve_studio_tls(*map(str, _write_pair(tmp_path)))+ state = types.SimpleNamespace(+ lan_access_wildcard_bind = False,+ server_url = None,+ studio_tls = tls,+ lan_access_bind_host = bind_host,+ lan_access_port = 8888,+ )+ assert _launch_urls(state) == [f"https://{bind_host}:8888"]+ state.studio_tls = None+ assert _launch_urls(state) == []diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.pyindex 024d9552583..36d523445fd 100644--- a/studio/backend/utils/lan_access_settings.py+++ b/studio/backend/utils/lan_access_settings.py@@ -402,18 +402,34 @@ def _launch_urls(app_state) -> list[str]:return _listener_urls(addresses,getattr(app_state, "lan_access_port", None),+ _url_scheme(app_state),)url = getattr(app_state, "server_url", None)+ if url is None and _url_scheme(app_state) == "https":+ # run.py publishes no server_url for TLS; the bound host is still where LAN peers reach it+ return _listener_urls(+ (getattr(app_state, "lan_access_bind_host", ""),),+ getattr(app_state, "lan_access_port", None),+ "https",+ )return [url] if url else []-def _listener_urls(addresses, port: Optional[int]) -> list[str]:+def _url_scheme(app_state) -> str:+ return "https" if getattr(app_state, "studio_tls", None) is not None else "http"+++def _listener_urls(+ addresses,+ port: Optional[int],+ scheme: str = "http",+) -> list[str]:if not port:return []urls = []for address in addresses:url_host = f"[{address}]" if ":" in address else address- urls.append(f"http://{url_host}:{port}")+ urls.append(f"{scheme}://{url_host}:{port}")return urls@@ -501,7 +517,7 @@ def lan_access_status(app) -> dict:elif running:state, urls, managed_by = ("online",- _listener_urls(listener["addresses"], listener["port"]),+ _listener_urls(listener["addresses"], listener["port"], _url_scheme(app_state)),"settings",)active_port = listener["port"]diff --git a/studio/backend/utils/remote_access_settings.py b/studio/backend/utils/remote_access_settings.pyindex aa3ddfc79c0..fc6f1bbd3d9 100644--- a/studio/backend/utils/remote_access_settings.py+++ b/studio/backend/utils/remote_access_settings.py@@ -270,6 +270,11 @@ def start_remote_access(app_state) -> dict:origin_host = getattr(app_state, "server_request_host", None)if not isinstance(origin_host, str) or not origin_host:raise RuntimeError("server_address_unavailable")+ from utils.studio_tls import loopback_http_port++ # cloudflared dials the origin over plain HTTP, so a TLS launch hands it the loopback self-call listener+ if loopback_http_port(app_state) is not None:+ port, origin_host = loopback_http_port(app_state), "127.0.0.1"if get_studio_tunnel_control_token() != admission:raise RuntimeError("server_lifecycle_changed")diff --git a/studio/backend/utils/studio_tls.py b/studio/backend/utils/studio_tls.pynew file mode 100644index 00000000000..4112910a930--- /dev/null+++ b/studio/backend/utils/studio_tls.py@@ -0,0 +1,74 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""HTTPS served by Studio itself from a user-supplied certificate and key (``--ssl-certfile`` / ``--ssl-keyfile``).++Studio still calls its own ``/v1`` (data recipes, research runs) from children that cannot be told to trust a+private certificate, so a TLS launch also serves plain HTTP on an ephemeral ``127.0.0.1`` port for those+self-calls; :func:`loopback_http_port` names it.+"""++from __future__ import annotations++import os+import ssl+from dataclasses import dataclass+from typing import Optional++import uvicorn+++@dataclass(frozen = True)+class StudioTLS:+ certfile: str+ keyfile: str+++def resolve_studio_tls(certfile: Optional[str], keyfile: Optional[str]) -> Optional[StudioTLS]:+ """The validated pair, or None for a plain HTTP launch. Exits with a readable message before anything binds."""+ certfile = (certfile or "").strip()+ keyfile = (keyfile or "").strip()+ if not certfile and not keyfile:+ return None+ if not (certfile and keyfile):+ raise SystemExit("--ssl-certfile and --ssl-keyfile must be passed together.")+ tls = StudioTLS(+ certfile = os.path.abspath(os.path.expanduser(certfile)),+ keyfile = os.path.abspath(os.path.expanduser(keyfile)),+ )+ for flag, path in (("--ssl-certfile", tls.certfile), ("--ssl-keyfile", tls.keyfile)):+ if not os.path.isfile(path):+ raise SystemExit(f"{flag}: file not found: {path}")+ try:+ server_ssl_context(tls)+ except (OSError, ssl.SSLError) as exc:+ raise SystemExit(+ f"Could not load the TLS certificate and key ({tls.certfile}, {tls.keyfile}): {exc}"+ ) from None+ return tls+++def server_ssl_context(tls: StudioTLS) -> ssl.SSLContext:+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)+ # Native TLS (utils/native_tls.py) injects truststore, whose handshake hook verifies the PEER chain: a browser sends+ # none, so macOS / Windows fail every handshake. Keep truststore's class, uvloop isinstance-checks it.+ inner = getattr(ctx, "_ctx", None)+ if inner is not None and hasattr(inner, "sslobject_class"):+ inner.sslobject_class = ssl.SSLObject+ ctx.load_cert_chain(tls.certfile, tls.keyfile)+ return ctx+++class StudioTLSConfig(uvicorn.Config):+ def __init__(self, app, *, tls: StudioTLS, **kwargs):+ super().__init__(app, ssl_certfile = tls.certfile, ssl_keyfile = tls.keyfile, **kwargs)+ self.studio_tls = tls++ def load(self) -> None:+ super().load()+ self.ssl = server_ssl_context(self.studio_tls)+++def loopback_http_port(app_state) -> Optional[int]:+ port = getattr(app_state, "loopback_http_port", None)+ return port if isinstance(port, int) and port > 0 else Nonediff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 5258f926278..a173bf6867e 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -385,6 +385,41 @@ def _openable_host_for_bind(run_mod, host: str) -> str:return share_host+def _require_valid_tls_flags(+ ssl_certfile: Optional[Path],+ ssl_keyfile: Optional[Path],+ *,+ secure: bool,+ cloudflare: Optional[bool],+) -> None:+ """Fail on a bad --ssl-certfile/--ssl-keyfile launch before the password gate can change or strip credentials.+ run_server re-checks the same rules (utils/studio_tls.py) for direct `run.py` callers."""+ if ssl_certfile is None and ssl_keyfile is None:+ return+ if ssl_certfile is None or ssl_keyfile is None:+ typer.echo("Error: --ssl-certfile and --ssl-keyfile must be passed together.", err = True)+ raise typer.Exit(2)+ if secure or cloudflare:+ typer.echo(+ "Error: --ssl-certfile/--ssl-keyfile serve HTTPS directly; do not combine them "+ "with --secure or --cloudflare.",+ err = True,+ )+ raise typer.Exit(2)+ import ssl++ try:+ ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER).load_cert_chain(+ str(ssl_certfile.expanduser()), str(ssl_keyfile.expanduser())+ )+ except (OSError, ssl.SSLError) as exc:+ typer.echo(+ f"Error: could not load the TLS certificate and key ({ssl_certfile}, {ssl_keyfile}): {exc}",+ err = True,+ )+ raise typer.Exit(2)++def _require_bind_host(host: str) -> None:if isinstance(host, str) and host.strip():return@@ -1913,6 +1948,17 @@ def studio_default("`--password -` to read one line from stdin. A literal value is visible in the ""process list and shell history. Rotate later with `unsloth studio reset-password`.",),+ ssl_certfile: Optional[Path] = typer.Option(+ None,+ "--ssl-certfile",+ help = "Serve HTTPS with this certificate (PEM, full chain), e.g. a Tailscale or "+ "Let's Encrypt .crt. Needs --ssl-keyfile. Not combinable with --secure / --cloudflare.",+ ),+ ssl_keyfile: Optional[Path] = typer.Option(+ None,+ "--ssl-keyfile",+ help = "Private key (PEM) for --ssl-certfile.",+ ),models_dir: Optional[List[Path]] = typer.Option(None,"--models-dir",@@ -2003,9 +2049,17 @@ def studio_default(err = True,)raise typer.Exit(2)+ if ssl_certfile is not None or ssl_keyfile is not None:+ typer.echo(+ "Error: --ssl-certfile/--ssl-keyfile apply to `unsloth studio` itself, "+ f"not to `unsloth studio {ctx.invoked_subcommand}`.",+ err = True,+ )+ raise typer.Exit(2)return_require_bind_host(host)+ _require_valid_tls_flags(ssl_certfile, ssl_keyfile, secure = secure, cloudflare = cloudflare)runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()runtime_gate_acquire = _studio_runtime_gate.consume_runtime_gate_acquire()_preserve_cloudflare_intent(cloudflare, secure)@@ -2119,6 +2173,10 @@ def studio_default(args.append("--enable-tools")elif enable_tools is False:args.append("--disable-tools")+ if ssl_certfile is not None:+ args.extend(["--ssl-certfile", str(ssl_certfile)])+ if ssl_keyfile is not None:+ args.extend(["--ssl-keyfile", str(ssl_keyfile)])# On Windows os.execvp keeps the parent alive and Ctrl+C would orphan the child.if sys.platform == "win32":import subprocess as _sp@@ -2162,7 +2220,8 @@ def studio_default(if not silent:launch_host = _openable_host_for_bind(run_mod, host)- typer.echo(f"Starting Unsloth Studio on http://{_url_host(launch_host)}:{port}")+ scheme = "https" if ssl_certfile is not None else "http"+ typer.echo(f"Starting Unsloth Studio on {scheme}://{_url_host(launch_host)}:{port}")run_kwargs = dict(host = host,@@ -2174,6 +2233,9 @@ def studio_default(secure = secure,enable_tools = enable_tools,)+ if ssl_certfile is not None or ssl_keyfile is not None:+ run_kwargs["ssl_certfile"] = str(ssl_certfile) if ssl_certfile else None+ run_kwargs["ssl_keyfile"] = str(ssl_keyfile) if ssl_keyfile else Noneif resolved_frontend is not None:run_kwargs["frontend_path"] = resolved_frontendrun_server(**run_kwargs)diff --git a/unsloth_cli/tests/test_studio_tls_flags.py b/unsloth_cli/tests/test_studio_tls_flags.pynew file mode 100644index 00000000000..75dc57dfd95--- /dev/null+++ b/unsloth_cli/tests/test_studio_tls_flags.py@@ -0,0 +1,114 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`unsloth studio --ssl-certfile/--ssl-keyfile`: a bad pair fails before the password gate, a good one is forwarded."""++from __future__ import annotations++import sys+from pathlib import Path++import pytest+from typer.testing import CliRunner+++class _ExecCaptured(Exception):+ pass+++def _pair(tmp_path: Path) -> tuple[Path, Path]:+ import datetime++ from cryptography import x509+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import ec+ from cryptography.x509.oid import NameOID++ key = ec.generate_private_key(ec.SECP256R1())+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "host.example.ts.net")])+ now = datetime.datetime.now(datetime.timezone.utc)+ cert = (+ x509.CertificateBuilder()+ .subject_name(name)+ .issuer_name(name)+ .public_key(key.public_key())+ .serial_number(x509.random_serial_number())+ .not_valid_before(now - datetime.timedelta(minutes = 5))+ .not_valid_after(now + datetime.timedelta(days = 1))+ .sign(key, hashes.SHA256())+ )+ crt, key_path = tmp_path / "host.crt", tmp_path / "host.key"+ crt.write_bytes(cert.public_bytes(serialization.Encoding.PEM))+ key_path.write_bytes(+ key.private_bytes(+ serialization.Encoding.PEM,+ serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption(),+ )+ )+ return crt, key_path+++def _invoke(monkeypatch, args):+ import typer as _typer+ from unsloth_cli.commands import studio as studio_mod++ calls = {"exec": [], "auth": []}+ monkeypatch.setattr(sys, "prefix", "/nonexistent/outer/venv")+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setattr(studio_mod, "_ensure_studio_env_exported", lambda: None)+ monkeypatch.setattr(studio_mod, "_studio_venv_python", lambda: Path("/fake/venv/bin/python"))+ monkeypatch.setattr(studio_mod, "_find_run_py", lambda: Path("/fake/studio/run.py"))+ monkeypatch.setattr(studio_mod, "_find_frontend_dist", lambda: Path("/fake/frontend/dist"))+ for name in (+ "_apply_supplied_password_before_launch",+ "_enforce_password_change_before_exposure",+ ):+ monkeypatch.setattr(studio_mod, name, lambda *a, _n = name, **k: calls["auth"].append(_n))++ def fake_execvp(file, argv):+ calls["exec"].append(list(argv))+ raise _ExecCaptured(argv)++ monkeypatch.setattr(studio_mod.os, "execvp", fake_execvp)+ app = _typer.Typer()+ app.command()(studio_mod.studio_default)+ result = CliRunner().invoke(app, args, catch_exceptions = True)+ return result, calls+++ "case",+ ["cert_only", "key_only", "mismatched_key", "missing_file", "with_cloudflare", "with_secure"],+)+def test_bad_tls_launch_fails_before_touching_credentials(monkeypatch, tmp_path, case):+ crt, key = _pair(tmp_path)+ other = tmp_path / "other"+ other.mkdir()+ _, other_key = _pair(other)+ args = ["-H", "0.0.0.0"] + {+ "cert_only": ["--ssl-certfile", str(crt)],+ "key_only": ["--ssl-keyfile", str(key)],+ "mismatched_key": ["--ssl-certfile", str(crt), "--ssl-keyfile", str(other_key)],+ "missing_file": ["--ssl-certfile", str(crt), "--ssl-keyfile", str(tmp_path / "absent.key")],+ "with_cloudflare": ["--cloudflare", "--ssl-certfile", str(crt), "--ssl-keyfile", str(key)],+ "with_secure": ["--secure", "--ssl-certfile", str(crt), "--ssl-keyfile", str(key)],+ }[case]+ result, calls = _invoke(monkeypatch, args)+ assert result.exit_code == 2, result.output+ assert calls == {"exec": [], "auth": []}+++def test_valid_pair_is_forwarded_to_the_server(monkeypatch, tmp_path):+ crt, key = _pair(tmp_path)+ _, calls = _invoke(+ monkeypatch, ["-H", "0.0.0.0", "--ssl-certfile", str(crt), "--ssl-keyfile", str(key)]+ )+ assert len(calls["exec"]) == 1, calls+ argv = calls["exec"][0]+ assert argv[argv.index("--ssl-certfile") + 1] == str(crt)+ assert argv[argv.index("--ssl-keyfile") + 1] == str(key)+ assert calls["auth"] == [+ "_apply_supplied_password_before_launch",+ "_enforce_password_change_before_exposure",+ ]