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): allow loopback CORS origins and custom origin overrides in desktop mode (#10084)
Harsha2215bbed707c
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 792318834a2..c93c754f839 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1629,7 +1629,10 @@ async def _recipes_redirect(rest: str = ""):return _RedirectResponse(url = target, status_code = 308)-from utils.host_policy import cors_origins_for_mode # noqa: E402+from utils.host_policy import (+ cors_origin_regex_for_mode,+ cors_origins_for_mode,+) # noqa: E402class RemoteAccessCORSMiddleware(CORSMiddleware):@@ -1656,11 +1659,16 @@ _cors_origins = cors_origins_for_mode(api_only = os.environ.get("UNSLOTH_API_ONLY") == "1",secure = os.environ.get("UNSLOTH_SECURE") == "1",)+_cors_origin_regex = cors_origin_regex_for_mode(+ api_only = os.environ.get("UNSLOTH_API_ONLY") == "1",+ secure = os.environ.get("UNSLOTH_SECURE") == "1",+)app.add_middleware(RemoteAccessCORSMiddleware,remote_access_state = app.state,allow_origins = _cors_origins,+ allow_origin_regex = _cors_origin_regex,allow_credentials = True,allow_methods = ["*"],allow_headers = ["*"],diff --git a/studio/backend/tests/test_cors_origins.py b/studio/backend/tests/test_cors_origins.pynew file mode 100644index 00000000000..2d2d28595b7--- /dev/null+++ b/studio/backend/tests/test_cors_origins.py@@ -0,0 +1,212 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""CORS origin policy: the desktop lockdown, its two opt-ins, and issue #9880."""++from __future__ import annotations++import sys+from pathlib import Path+from types import SimpleNamespace++import pytest+from starlette.datastructures import Headers++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++from utils.host_policy import (+ _LOOPBACK_ORIGIN_REGEX,+ _TAURI_CORS_ORIGINS,+ cors_origin_regex_for_mode,+ cors_origins_for_mode,+)+++def _middleware(+ *,+ api_only = True,+ secure = False,+ cloudflare_url = None,+):+ from main import RemoteAccessCORSMiddleware+ return RemoteAccessCORSMiddleware(+ lambda *_: None,+ remote_access_state = SimpleNamespace(cloudflare_url = cloudflare_url),+ allow_origins = cors_origins_for_mode(api_only = api_only, secure = secure),+ allow_origin_regex = cors_origin_regex_for_mode(api_only = api_only, secure = secure),+ allow_credentials = True,+ allow_methods = ["*"],+ allow_headers = ["*"],+ )+++def _preflight(middleware, origin):+ return middleware.preflight_response(+ Headers(+ {+ "origin": origin,+ "access-control-request-method": "POST",+ "access-control-request-headers": "authorization,content-type",+ }+ )+ )+++ "api_only,secure,expected",+ [+ (False, False, ["*"]),+ (False, True, ["*"]),+ (True, True, ["*"]),+ ],+)+def test_cors_origins_for_mode_wildcard(api_only, secure, expected):+ origins = cors_origins_for_mode(api_only = api_only, secure = secure)+ assert origins == expected+++def test_cors_origins_for_mode_desktop_default():+ origins = cors_origins_for_mode(api_only = True, secure = False)+ assert origins == list(_TAURI_CORS_ORIGINS)+++def test_cors_origins_for_mode_env_override(monkeypatch):+ monkeypatch.setenv("UNSLOTH_CORS_ORIGINS", "https://foo.example, http://localhost:9999")+ origins = cors_origins_for_mode(api_only = True, secure = False)+ assert origins == list(_TAURI_CORS_ORIGINS) + ["https://foo.example", "http://localhost:9999"]++[email protected]("api_only,secure", [(False, False), (False, True), (True, True)])+def test_cors_origins_env_never_narrows_any_origin_modes(monkeypatch, api_only, secure):+ monkeypatch.setenv("UNSLOTH_CORS_ORIGINS", "http://localhost:8080")+ assert cors_origins_for_mode(api_only = api_only, secure = secure) == ["*"]++ middleware = _middleware(api_only = api_only, secure = secure)+ assert _preflight(middleware, "tauri://localhost").status_code == 200+++ "api_only,secure",+ [+ (True, False),+ (True, True),+ (False, False),+ (False, True),+ ],+)+def test_cors_origin_regex_for_mode_default_none(api_only, secure):+ regex = cors_origin_regex_for_mode(api_only = api_only, secure = secure)+ assert regex is None+++def test_cors_origin_regex_for_mode_opt_in(monkeypatch):+ monkeypatch.setenv("UNSLOTH_CORS_ALLOW_LOOPBACK", "1")+ assert cors_origin_regex_for_mode(api_only = True, secure = False) == _LOOPBACK_ORIGIN_REGEX++[email protected]("api_only,secure", [(False, False), (False, True), (True, True)])+def test_cors_origin_regex_only_applies_to_the_desktop_lockdown(monkeypatch, api_only, secure):+ monkeypatch.setenv("UNSLOTH_CORS_ALLOW_LOOPBACK", "1")+ assert cors_origin_regex_for_mode(api_only = api_only, secure = secure) is None+++def test_no_env_var_can_put_an_operator_regex_in_front_of_origin(monkeypatch):+ for name in ("UNSLOTH_CORS_ORIGIN_REGEX", "UNSLOTH_CORS_REGEX", "UNSLOTH_CORS_ALLOW_REGEX"):+ monkeypatch.setenv(name, r"^https?://(a+)+\.example$")+ assert cors_origin_regex_for_mode(api_only = True, secure = False) is None++ monkeypatch.setenv("UNSLOTH_CORS_ALLOW_LOOPBACK", "1")+ assert cors_origin_regex_for_mode(api_only = True, secure = False) == _LOOPBACK_ORIGIN_REGEX+++def test_the_built_in_loopback_regex_is_linear_on_a_hostile_origin():+ import re+ import time++ pattern = re.compile(_LOOPBACK_ORIGIN_REGEX)+ hostile = "http://" + ("a" * 200_000) + "!"+ started = time.perf_counter()+ assert pattern.fullmatch(hostile) is None+ assert time.perf_counter() - started < 0.5+++def test_main_passes_the_origin_regex_to_the_mounted_middleware():+ src = (_BACKEND / "main.py").read_text(encoding = "utf-8")+ assert "allow_origin_regex = _cors_origin_regex" in src+++ "origin,should_allow",+ [+ ("tauri://localhost", True),+ ("http://tauri.localhost", True),+ ("http://localhost:5173", True),+ ("http://localhost:3000", False),+ ("http://localhost:8080", False),+ ("http://127.0.0.1:3000", False),+ ("http://127.0.0.1:8888", False),+ ("http://[::1]:3000", False),+ ("https://localhost:8443", False),+ ("https://127.0.0.1:8443", False),+ ("http://malicious-site.com", False),+ ("https://evil.org", False),+ ],+)+def test_desktop_cors_default_locked_down(origin, should_allow):+ response = _preflight(_middleware(), origin)++ if should_allow:+ assert response.status_code == 200+ assert response.headers.get("access-control-allow-origin") == origin+ else:+ assert response.status_code == 400+ assert "access-control-allow-origin" not in response.headers+++def test_desktop_cors_opt_in_origins(monkeypatch):+ monkeypatch.setenv("UNSLOTH_CORS_ORIGINS", "http://localhost:3000, http://127.0.0.1:8080")+ middleware = _middleware()++ for origin in ("http://localhost:3000", "http://127.0.0.1:8080", "tauri://localhost"):+ resp = _preflight(middleware, origin)+ assert resp.status_code == 200+ assert resp.headers.get("access-control-allow-origin") == origin++ for origin in ("http://localhost:9000", "http://evil.com"):+ resp = _preflight(middleware, origin)+ assert resp.status_code == 400+ assert "access-control-allow-origin" not in resp.headers+++ "origin,should_allow",+ [+ ("tauri://localhost", True),+ ("http://tauri.localhost", True),+ ("http://localhost:5173", True),+ ("http://localhost:3000", True),+ ("http://localhost:8080", True),+ ("http://127.0.0.1:3000", True),+ ("http://127.0.0.1:8888", True),+ ("http://[::1]:3000", True),+ ("https://localhost:8443", True),+ ("https://127.0.0.1:8443", True),+ ("http://malicious-site.com", False),+ ("https://evil.org", False),+ ("http://localhost.attacker.com", False),+ ("http://attackerlocalhost.com", False),+ ("http://127.0.0.1.attacker.com", False),+ ],+)+def test_desktop_cors_loopback_flag_opt_in(monkeypatch, origin, should_allow):+ monkeypatch.setenv("UNSLOTH_CORS_ALLOW_LOOPBACK", "1")+ response = _preflight(_middleware(), origin)++ if should_allow:+ assert response.status_code == 200+ assert response.headers.get("access-control-allow-origin") == origin+ else:+ assert response.status_code == 400+ assert "access-control-allow-origin" not in response.headersdiff --git a/studio/backend/utils/host_policy.py b/studio/backend/utils/host_policy.pyindex 70b9b18141a..24664fbc553 100644--- a/studio/backend/utils/host_policy.py+++ b/studio/backend/utils/host_policy.py@@ -220,12 +220,34 @@ _TAURI_CORS_ORIGINS = ("http://127.0.0.1:5173",)+_LOOPBACK_ORIGIN_REGEX = r"^https?://(localhost|127\.0\.0\.1|\[::1\])(:[0-9]{1,5})?$"+++def _is_desktop_cors_lockdown(api_only: bool, secure: bool) -> bool:+ """Secure mode publishes the API over Cloudflare, so only plain api-only is locked down."""+ return api_only and not secure+def cors_origins_for_mode(*, api_only: bool, secure: bool) -> list[str]:- """Allowed CORS origins. Default is any-origin (["*"]); api-only locks down to the Tauri desktop app, except in secure mode where the API is published over Cloudflare and must stay reachable from remote browser origins."""- if api_only and not secure:- return list(_TAURI_CORS_ORIGINS)- return ["*"]+ """Tauri origins plus UNSLOTH_CORS_ORIGINS under lockdown, else ["*"] (never narrowed: the webview would lose access when a tunnel drops)."""+ if not _is_desktop_cors_lockdown(api_only, secure):+ return ["*"]+ custom = [+ origin.strip()+ for origin in os.environ.get("UNSLOTH_CORS_ORIGINS", "").split(",")+ if origin.strip()+ ]+ return list(dict.fromkeys(list(_TAURI_CORS_ORIGINS) + custom))+++def cors_origin_regex_for_mode(*, api_only: bool, secure: bool) -> str | None:+ """Loopback-any-port regex, only with UNSLOTH_CORS_ALLOW_LOOPBACK=1 under lockdown.+ Never an operator regex: Origin is matched pre-auth, so a nested quantifier is a ReDoS."""+ if not _is_desktop_cors_lockdown(api_only, secure):+ return None+ if os.environ.get("UNSLOTH_CORS_ALLOW_LOOPBACK") == "1":+ return _LOOPBACK_ORIGIN_REGEX+ return Nonedef apply_stdio_mcp_loopback_default(host: str, *, is_colab: bool = False) -> None: