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: let the owner allow managed accounts private provider base URLs (#11436)
Daniel Han9ceb26347ef2
diff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.pyindex cce87bb17d3..214a8309a73 100644--- a/studio/backend/core/data_recipe/service.py+++ b/studio/backend/core/data_recipe/service.py@@ -139,17 +139,41 @@ def _apply_data_designer_image_context_patch() -> None:def _require_public_provider_endpoint(endpoint: str) -> None:"""The recipe engine dials providers itself, so a managed account's endpoint cannot use the pinnedtransport: require HTTPS, which binds the peer to its certificate rather than to a DNS answer that- may rebind to loopback or the LAN after this public-address check."""+ may rebind to loopback or the LAN after this public-address check.++ With the switch on, the HTTPS and public-address rules stand down so a saved connection is one+ a recipe can run on. The metadata rule does not: this path has no validator behind it."""if not managed_account():returnfrom urllib.parse import urlsplit- from core.inference.providers import public_provider_address+ from core.inference.providers import (+ managed_private_url_hint,+ provider_address_excluding_metadata,+ public_provider_address,+ )+ from utils.managed_provider_url_settings import get_managed_private_provider_urls_allowedurl = str(endpoint or "")+ if get_managed_private_provider_urls_allowed():+ try:+ # The switch lifts HTTPS-only and public-only, not http(s)-only: everywhere else a+ # provider URL is one of those two schemes, and this gate has no validator behind it.+ if urlsplit(url).scheme not in ("http", "https"):+ raise ValueError("Provider endpoints must use http or https.")+ provider_address_excluding_metadata(url)+ except ValueError as exc:+ raise HTTPException(+ status_code = 403, detail = f"Recipe provider endpoint refused: {exc}"+ ) from exc+ return+try:if urlsplit(url).scheme != "https":- raise ValueError("Managed accounts may only use HTTPS provider endpoints.")+ raise ValueError(+ "Managed accounts may only use HTTPS provider endpoints."+ + managed_private_url_hint()+ )public_provider_address(url)except ValueError as exc:raise HTTPException(@@ -160,18 +184,32 @@ def _require_public_provider_endpoint(endpoint: str) -> None:def install_public_egress_guard() -> None:"""Managed recipe workers: the engine dials providers itself, so every name resolves through thisguard and a host that rebinds to loopback or the LAN after the endpoint check is refused at connect- time rather than dialled. Process-wide, so it is installed only in the job subprocess."""+ time rather than dialled. Process-wide, so it is installed only in the job subprocess.++ With the switch on the guard narrows to the metadata services rather than standing down: a+ worker whose engine dials for itself has nothing else between it and that address."""if not managed_account():return+ from utils.managed_provider_url_settings import get_managed_private_provider_urls_allowed+import ipaddressimport socket+ from core.inference.providers import _metadata_address+resolve = socket.getaddrinfodef guarded_getaddrinfo(host, port, *args, **kwargs):+ # Per lookup, not captured at install: a worker outlives the switch it started under.+ private_allowed = get_managed_private_provider_urls_allowed()infos = resolve(host, port, *args, **kwargs)for info in infos:- if not ipaddress.ip_address(str(info[4][0]).split("%", 1)[0]).is_global:+ address = str(info[4][0]).split("%", 1)[0]+ if _metadata_address(address):+ raise socket.gaierror(+ f"Managed accounts may not reach cloud metadata services: {host!r}"+ )+ if not private_allowed and not ipaddress.ip_address(address).is_global:raise socket.gaierror(f"Managed accounts may only reach public-network addresses: {host!r}")diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 39e9fa9a08a..5eaea65e7ac 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -13,6 +13,7 @@ import randomimport reimport threadingimport time+import weakrefimport wavefrom typing import Any, AsyncGenerator, Literal, NamedTuple, Optional, Unionfrom urllib.parse import urlparse, urlsplit, urlunsplit@@ -852,21 +853,116 @@ class _PinnedPublicTransport(httpx.AsyncBaseTransport):await transport.aclose()-_managed_http_client: Optional[httpx.AsyncClient] = None+class _PinnedNonMetadataTransport(_PinnedPublicTransport):+ """Managed-account egress once the owner has allowed private addresses.++ The public pin, one rule looser: the dialled address may be private, never metadata. The+ re-resolve stays, or a name that validated as public could answer 169.254.169.254 by connect+ time, which is the one destination this switch may not open.+ """++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ from core.inference.providers import (+ _public_registry_hostname,+ provider_address_excluding_metadata,+ )++ host = request.url.host+ if _public_registry_hostname(host):+ return await self._pool(("registry",)).handle_async_request(request)+ try:+ address = await asyncio.to_thread(provider_address_excluding_metadata, str(request.url))+ except ValueError as exc:+ raise httpx.ConnectError(str(exc), request = request) from exc+ pinned = httpx.Request(+ method = request.method,+ url = request.url.copy_with(host = address),+ headers = request.headers,+ stream = request.stream,+ extensions = {**request.extensions, "sni_hostname": host},+ )+ origin = (request.url.scheme, host, request.url.port)+ return await self._pool(origin).handle_async_request(pinned)+++# (account_id, private allowed) -> client. Keyed by account because an AsyncClient persists cookies+# across requests (python-httpx.org/advanced/clients): one shared client crosses a gateway session+# from the account that collected it to the next account calling the same host.+_managed_clients: dict[tuple[str, bool], httpx.AsyncClient] = {}+_managed_clients_lock = threading.Lock()+# Retired accounts. Bounded: it only outlives requests in flight when the account went away.+_retired_accounts: set[str] = set()+_RETIRED_ACCOUNTS_MAX = 1024+# client -> the loop it was created on. Weak, so it never keeps a client alive by itself.+_client_loops: "weakref.WeakKeyDictionary[httpx.AsyncClient, asyncio.AbstractEventLoop]" = (+ weakref.WeakKeyDictionary()+)+++def retire_account_clients(account_id: str) -> int:+ """Drop and close a retired account's provider clients, returning how many were held.++ Without it the cache is bounded by accounts ever CREATED, and a deleted account's cookie jar+ and idle sockets outlive it for the life of the process.+ """+ with _managed_clients_lock:+ retired = [+ _managed_clients.pop(key) for key in list(_managed_clients) if key[0] == account_id+ ]+ # Tombstoned: a request that authenticated before deactivation can reach `_client()` after+ # this sweep, and would otherwise re-insert an entry nothing sweeps again.+ _retired_accounts.add(account_id)+ while len(_retired_accounts) > _RETIRED_ACCOUNTS_MAX:+ _retired_accounts.pop()+ for client in retired:+ loop = _client_loops.get(client)+ try:+ running = asyncio.get_running_loop()+ except RuntimeError:+ running = None+ if running is not None and (loop is None or loop is running):+ running.create_task(client.aclose())+ elif loop is not None and not loop.is_closed():+ # Deletion is a sync route with no loop of its own, and dropping the reference does+ # not close a pool.+ asyncio.run_coroutine_threadsafe(client.aclose(), loop)+ return len(retired)+++def restore_account_clients(account_id: str) -> None:+ """Lift the retirement tombstone: a failed delete leaves the account reactivatable, and one+ reactivated under a tombstone would never be cached again, so no pooling and no cookies."""+ with _managed_clients_lock:+ _retired_accounts.discard(account_id)def _client() -> httpx.AsyncClient:- """The shared client for the owner; a pinning client for a managed account."""- from utils.account_context import is_owner_context+ """The shared client for the owner; a screening client of its own for each managed account."""+ from utils.account_context import current_account_id, is_owner_context+ from utils.managed_provider_url_settings import get_managed_private_provider_urls_allowedif is_owner_context():return _http_client- global _managed_http_client- if _managed_http_client is None:- _managed_http_client = httpx.AsyncClient(- transport = _PinnedPublicTransport(), trust_env = False- )- return _managed_http_client+ # Read per call, so a flip takes effect without a restart.+ allowed = get_managed_private_provider_urls_allowed()+ account_id = current_account_id()+ key = (account_id, allowed)+ with _managed_clients_lock:+ client = _managed_clients.get(key)+ if client is not None:+ return client+ transport = _PinnedNonMetadataTransport() if allowed else _PinnedPublicTransport()+ client = httpx.AsyncClient(transport = transport, trust_env = False)+ # Its pool holds streams bound to this loop, so closing from a different one is not+ # equivalent.+ try:+ _client_loops[client] = asyncio.get_running_loop()+ except RuntimeError:+ pass+ # Served but not cached for a retired account: nothing sweeps an entry made after the sweep.+ if account_id not in _retired_accounts:+ _managed_clients[key] = client+ return client# Cap per-image fetch well below Gemini's ~20 MB total request budget.diff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.pyindex f36eafa3ae7..8e0233083b0 100644--- a/studio/backend/core/inference/providers.py+++ b/studio/backend/core/inference/providers.py@@ -609,6 +609,21 @@ _METADATA_NETWORK = ipaddress.ip_network("169.254.0.0/16")# LAN endpoints are the normal case (Ollama, llama.cpp, vLLM, custom gateways)._BLOCK_PRIVATE_ENV = "UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS"+# Named in one place: a managed account meets this refusal from save, send and recipe alike.+MANAGED_PRIVATE_URL_HINT = (+ " The installation owner can allow private and LAN addresses in Settings > General."+)+MANAGED_PUBLIC_ONLY_TEXT = "Managed accounts may only use public-network provider base URLs."+++def managed_private_url_hint() -> str:+ """The hint, omitted when the environment lock means the owner cannot act on it either."""+ return "" if os.environ.get(_BLOCK_PRIVATE_ENV) == "1" else MANAGED_PRIVATE_URL_HINT+++def managed_public_only_reason() -> str:+ return MANAGED_PUBLIC_ONLY_TEXT + managed_private_url_hint()+# An all-numeric host is an IPv4 literal to the resolver, in decimal, octal or# hex. `ipaddress` parses only the dotted quad, so 2852039166, 0xA9FEA9FE and@@ -858,6 +873,16 @@ def _managed_account_caller() -> bool:return not is_owner_context()+def _managed_private_urls_allowed() -> bool:+ """True when the owner has opened private provider addresses to managed accounts.++ Imported here, not at module scope: tests/test_provider_base_url_validation.py loads this+ module standalone.+ """+ from utils.managed_provider_url_settings import get_managed_private_provider_urls_allowed+ return get_managed_private_provider_urls_allowed()++def _reject_non_public(hostname: str, port: int | None, scheme: str, reason: str) -> None:"""Raise when ``hostname`` is, or resolves to, a non-public address."""try:@@ -901,7 +926,7 @@ def public_provider_address(url: str) -> str:hostname = (parts.hostname or "").rstrip(".")if not hostname:raise ValueError("Provider URL must contain a hostname.")- reason = "Managed accounts may only use public-network provider base URLs."+ reason = managed_public_only_reason()try:addresses = [ipaddress.ip_address(_canonical_host(hostname))]except ValueError:@@ -919,6 +944,47 @@ def public_provider_address(url: str) -> str:return str(addresses[0])+METADATA_REFUSED_REASON = "Cloud metadata endpoints cannot be used as a provider base URL."+++def provider_address_excluding_metadata(url: str) -> str:+ """Resolve ``url``'s host now and return one address to dial, refusing only metadata services.++ For a caller the owner has allowed private addresses. Re-resolving rather than trusting the+ save-time check is the point: a name is free to answer 169.254.169.254 afterwards.+ """+ import socket++ parts = urlsplit(url)+ hostname = (parts.hostname or "").rstrip(".")+ if not hostname:+ raise ValueError("Provider URL must contain a hostname.")+ literal = True+ try:+ addresses = [ipaddress.ip_address(_canonical_host(hostname))]+ except ValueError:+ literal = False+ try:+ infos = socket.getaddrinfo(+ _transport_host(hostname),+ parts.port or (443 if parts.scheme == "https" else 80),+ type = socket.SOCK_STREAM,+ )+ except (OSError, UnicodeError) as exc:+ raise ValueError("Provider base URL hostname could not be resolved.") from exc+ addresses = [ipaddress.ip_address(str(info[4][0]).split("%", 1)[0]) for info in infos]+ if not addresses:+ raise ValueError("Provider base URL hostname could not be resolved.")+ # The same split the validator makes, so a URL that saves is one that dials. A typed literal+ # gets `_metadata_host`, which reads all of 169.254.0.0/16 as the metadata service; a DNS+ # answer gets `_metadata_address`, which does not, because that range is also where a+ # self-assigned host or an mDNS name lands.+ refuses = _metadata_host if literal else _metadata_address+ if any(refuses(str(ip)) for ip in addresses):+ raise ValueError(METADATA_REFUSED_REASON)+ return str(addresses[0])++def validate_provider_base_url(base_url: str) -> str:"""Return a normalized provider base URL, or raise ``ValueError``.@@ -930,7 +996,9 @@ def validate_provider_base_url(base_url: str) -> str:stay valid -- Ollama, llama.cpp, vLLM and custom gateways rely on them. Acaller-supplied hostname is resolved far enough to apply the metadata blockto DNS aliases of it; rejecting other private addresses stays opt-in for the- owner, and is always on for a managed account (as managed MCP servers are).+ owner, and is on for a managed account until the owner turns it off for the+ installation (``utils.managed_provider_url_settings``), which is how a team+ sharing one LAN model server gets to use it from more than one account.Normalization is strip + trailing-slash removal only (what the client didbefore), so validating an already-validated URL returns it unchanged.@@ -969,14 +1037,13 @@ def validate_provider_base_url(base_url: str) -> str:"Provider base URL points at a private address, which is disabled on this "f"server ({_BLOCK_PRIVATE_ENV}=1).",)- elif _managed_account_caller() and not _public_registry_hostname(hostname):- # Caller-controlled egress must not reach the owner's loopback models or LAN.- _reject_non_public(- hostname,- port,- scheme,- "Managed accounts may only use public-network provider base URLs.",- )+ elif (+ _managed_account_caller()+ and not _public_registry_hostname(hostname)+ and not _managed_private_urls_allowed()+ ):+ # Caller-controlled egress: the owner's loopback and LAN, unless the owner opened them.+ _reject_non_public(hostname, port, scheme, managed_public_only_reason())return raw.rstrip("/")diff --git a/studio/backend/routes/accounts.py b/studio/backend/routes/accounts.pyindex ebd852fa4b1..a507acf2e0a 100644--- a/studio/backend/routes/accounts.py+++ b/studio/backend/routes/accounts.py@@ -48,6 +48,11 @@ def retire_account_roots(account: AccountContext):active_generations.fence(account.account_id)active_generations.cancel_all(account.account_id)account_access.retire_resident_shares(account.account_id)+ from core.inference.external_provider import retire_account_clients++ # Its provider clients hold a cookie jar and idle sockets, and the cache they sit in is+ # keyed by account, so nothing else would ever drop them.+ retire_account_clients(account.account_id)from core.inference.mcp_client import close_mcp_sessions, invalidate_tool_cachefrom core.training.account_jobs import retire_account_jobs@@ -141,8 +146,11 @@ def set_account_active(account_id: str, payload: AccountActiveRequest):result = storage.set_account_active(account_id, payload.is_active)if payload.is_active:# A delete that failed after retiring the jobs left the id tombstoned in-process.+ from core.inference.external_provider import restore_account_clientsfrom core.training.account_jobs import restore_account_jobs+restore_account_jobs(account_id)+ restore_account_clients(account_id)active_generations.lift_fence(account_id)else:from routes.inference import retire_account_loadsdiff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex ff3cd526d50..3e9c5f4e9be 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -138,6 +138,12 @@ from utils.preview_sharing_settings import (get_preview_sharing_enabled,set_preview_sharing_enabled,)+from utils.managed_provider_url_settings import (+ DEFAULT_MANAGED_PRIVATE_PROVIDER_URLS_ALLOWED,+ get_managed_private_provider_urls_allowed,+ private_urls_locked_by_environment,+ set_managed_private_provider_urls_allowed,+)from utils.current_date_prompt_settings import (DEFAULT_CURRENT_DATE_PROMPT_ENABLED,get_current_date_prompt_enabled,@@ -3042,6 +3048,18 @@ class PreviewSharingResponse(BaseModel):default_enabled: bool = DEFAULT_PREVIEW_SHARING_ENABLED+class ManagedProviderUrlsPayload(BaseModel):+ allowed: StrictBool+++class ManagedProviderUrlsResponse(BaseModel):+ allowed: bool+ default_allowed: bool = DEFAULT_MANAGED_PRIVATE_PROVIDER_URLS_ALLOWED+ # UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 holds the answer: the UI says why rather than+ # showing a switch that silently reverts.+ locked_by_environment: bool = False++class CurrentDatePromptPayload(BaseModel):enabled: StrictBool@@ -3276,6 +3294,53 @@ def update_preview_sharing(return PreviewSharingResponse(enabled = enabled)+def _managed_provider_urls_response() -> ManagedProviderUrlsResponse:+ # The EFFECTIVE answer, not the stored preference: a switch reading back on while every save+ # is refused would be the worst of the three things this could say.+ return ManagedProviderUrlsResponse(+ allowed = get_managed_private_provider_urls_allowed(),+ locked_by_environment = private_urls_locked_by_environment(),+ )+++@_shared_settings_router.get("/managed-provider-urls", response_model = ManagedProviderUrlsResponse)+def get_managed_provider_urls(+ current_subject: str = Depends(get_current_subject),+) -> ManagedProviderUrlsResponse:+ """Readable by any account: a managed one has to be able to tell a refusal the owner can lift+ from one nobody on this installation can, and it learns the same bit by trying to save a URL."""+ return _managed_provider_urls_response()+++@_owner_settings_router.put("/managed-provider-urls", response_model = ManagedProviderUrlsResponse)+def update_managed_provider_urls(+ payload: ManagedProviderUrlsPayload,+ current_subject: str = Depends(get_current_subject),+ # Installation policy: set at the console, not from a remote key that happens to be owned.+ _ui_session: None = Depends(_require_ui_session),+) -> ManagedProviderUrlsResponse:+ """Allow or refuse private and LAN provider base URLs for the installation's managed accounts.++ Off by default. The preference is stored either way, so removing+ ``UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS`` later restores what the owner chose here rather+ than a default.+ """+ try:+ allowed = set_managed_private_provider_urls_allowed(payload.allowed)+ except ValueError as exc:+ raise log_and_http_error(+ exc,+ 400,+ safe_error_detail(exc, fallback = "Invalid managed provider URL setting."),+ event = "settings.update_managed_provider_urls_failed",+ log = logger,+ ) from exc+ logger.info(+ "settings.managed_provider_urls_updated subject=%s allowed=%s", current_subject, allowed+ )+ return _managed_provider_urls_response()++@_account_settings_router.get("/current-date-prompt", response_model = CurrentDatePromptResponse)def get_current_date_prompt(current_subject: str = Depends(get_current_subject),diff --git a/studio/backend/tests/test_account_provider_lan_optin.py b/studio/backend/tests/test_account_provider_lan_optin.pynew file mode 100644index 00000000000..90739c8efa0--- /dev/null+++ b/studio/backend/tests/test_account_provider_lan_optin.py@@ -0,0 +1,241 @@+# 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 owner's opt-in for managed-account LAN provider URLs, end to end.++Companion to test_account_provider_network_scope.py, which pins the default: a+managed account may not reach owner-local or LAN endpoints. This pins what the+opt-in changes and, more importantly, what it must NOT change -- the cloud+metadata refusal and the operator's BLOCK_PRIVATE kill switch both survive it.+"""++import http.server+import threading+from contextlib import nullcontext++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import (+ authenticated_via_api_key,+ get_current_credential,+ get_current_subject,+)+from core.inference import providers as providers_core+from routes import providers+from storage import credential_secrets, providers_db, studio_db+from utils import managed_provider_url_settings as mpu+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+OWNER_LOCAL_MODEL = "owner-local-secret-model"+BLOCK_PRIVATE_ENV = providers_core._BLOCK_PRIVATE_ENV++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.delenv(BLOCK_PRIVATE_ENV, raising = False)+ # Each test is a fresh installation; in production the home is fixed at startup.+ mpu.forget_cached_setting()+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ for module in (credential_secrets, providers_db, studio_db):+ monkeypatch.setattr(module, "_schema_ready", set(), raising = False)+ monkeypatch.setattr(+ credential_secrets, "get_or_create_credential_encryption_key", lambda: b"k" * 32+ )+ monkeypatch.setattr(providers, "current_credential_write", lambda credential: nullcontext())+ providers_core._dns_cache.clear()+ yield+ providers_core._dns_cache.clear()+++def local_provider():+ """A loopback OpenAI-compatible server standing in for the shared llama-server."""++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ body = ('{"data": [{"id": "%s"}]}' % OWNER_LOCAL_MODEL).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target = server.serve_forever, daemon = True).start()+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}/v1"+ finally:+ server.shutdown()+ server.server_close()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[get_current_credential] = lambda: (account.username, None)+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.include_router(providers.router, prefix = "/providers")+ return TestClient(app)+++def allow_lan(value: bool):+ mpu.set_managed_private_provider_urls_allowed(value)+++# --- the opt-in does what it says ------------------------------------------------+++def test_managed_account_lists_models_from_a_loopback_provider_when_allowed(local_provider):+ allow_lan(True)+ with client_for(ALICE) as client:+ response = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert response.status_code == 200, response.text+ assert [m["id"] for m in response.json()] == [OWNER_LOCAL_MODEL]+++def test_managed_account_saves_a_lan_provider_when_allowed(local_provider):+ allow_lan(True)+ with client_for(ALICE) as client:+ for base_url in (local_provider, "http://10.0.0.7:8080/v1", "http://192.168.1.50:11434/v1"):+ created = client.post(+ "/providers/",+ json = {+ "provider_type": "custom",+ "display_name": "LAN",+ "base_url": base_url,+ },+ )+ assert created.status_code == 201, f"{base_url}: {created.text}"+++def test_default_still_refuses(local_provider):+ """Regression guard: the switch is off unless the owner turns it on."""+ with client_for(ALICE) as client:+ response = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert response.status_code == 400, response.text+ assert OWNER_LOCAL_MODEL not in response.text+++def test_turning_it_back_off_refuses_again(local_provider):+ allow_lan(True)+ with client_for(ALICE) as client:+ assert (+ client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ ).status_code+ == 200+ )+ allow_lan(False)+ with client_for(ALICE) as client:+ refused = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert refused.status_code == 400, refused.text+ assert OWNER_LOCAL_MODEL not in refused.text+++def test_owner_is_unaffected_either_way(local_provider):+ for value in (False, True, False):+ allow_lan(value)+ with client_for(OWNER) as client:+ listed = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert listed.status_code == 200, f"allowed={value}: {listed.text}"+++# --- what the opt-in must NOT relax ----------------------------------------------+++ "metadata_url",+ [+ "http://169.254.169.254/latest/meta-data/",+ "http://metadata.google.internal/computeMetadata/v1/",+ "http://[fd00:ec2::254]/latest/meta-data/",+ # Legacy numeric spellings of the same address.+ "http://2852039166/v1",+ "http://0251.0376.0251.0376/v1",+ ],+)+def test_cloud_metadata_is_still_refused_with_the_switch_on(metadata_url):+ allow_lan(True)+ with client_for(ALICE) as client:+ created = client.post(+ "/providers/",+ json = {"provider_type": "custom", "display_name": "md", "base_url": metadata_url},+ )+ assert created.status_code == 400, created.text+ assert "metadata" in created.text.lower(), created.text+++def test_block_private_env_overrides_the_switch_for_a_managed_account(monkeypatch, local_provider):+ allow_lan(True)+ monkeypatch.setenv(BLOCK_PRIVATE_ENV, "1")+ with client_for(ALICE) as client:+ created = client.post(+ "/providers/",+ json = {"provider_type": "custom", "display_name": "LAN", "base_url": local_provider},+ )+ assert created.status_code == 400, created.text+ assert BLOCK_PRIVATE_ENV in created.text+++def test_block_private_env_overrides_the_switch_for_the_owner(monkeypatch, local_provider):+ allow_lan(True)+ monkeypatch.setenv(BLOCK_PRIVATE_ENV, "1")+ with client_for(OWNER) as client:+ created = client.post(+ "/providers/",+ json = {"provider_type": "custom", "display_name": "LAN", "base_url": local_provider},+ )+ assert created.status_code == 400, created.text+++def test_a_row_saved_while_allowed_is_refused_after_the_switch_is_off(local_provider):+ """The saved row keeps its LAN base URL; the choke point in ExternalProviderClient+ re-validates on every outbound use, so turning the switch off takes effect at once."""+ allow_lan(True)+ with client_for(ALICE) as client:+ created = client.post(+ "/providers/",+ json = {"provider_type": "custom", "display_name": "LAN", "base_url": local_provider},+ )+ assert created.status_code == 201, created.text+ provider_id = created.json()["id"]++ allow_lan(False)+ with client_for(ALICE) as client:+ used = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert used.status_code == 400, used.text+ # The row itself survives; only its use is refused.+ listed = client.get("/providers/")+ assert any(row["id"] == provider_id for row in listed.json()), listed.textdiff --git a/studio/backend/tests/test_account_provider_network_scope.py b/studio/backend/tests/test_account_provider_network_scope.pyindex 9f0a41b20fc..4c37a43d7a6 100644--- a/studio/backend/tests/test_account_provider_network_scope.py+++ b/studio/backend/tests/test_account_provider_network_scope.py@@ -111,6 +111,64 @@ def test_managed_account_cannot_save_a_private_provider_base_url(local_provider)assert created.status_code == 400, f"{base_url}: {created.text}"+def owner_allows_private_urls(monkeypatch):+ """The installation owner has opened private addresses to managed accounts (#11382)."""+ from core.inference import external_provider+ from utils import managed_provider_url_settings++ monkeypatch.setattr(+ managed_provider_url_settings, "get_managed_private_provider_urls_allowed", lambda: True+ )+ # The pinning client is a module-level singleton; drop it so the choice is made fresh.+ monkeypatch.setattr(external_provider, "_managed_clients", {}, raising = False)+++def test_managed_account_may_save_a_private_base_url_once_the_owner_allows_it(+ local_provider, owner_allows_private_urls+):+ with client_for(ALICE) as client:+ created = client.post(+ "/providers/",+ json = {+ "provider_type": "custom",+ "display_name": "Shared LAN llama-server",+ "base_url": local_provider,+ },+ )+ assert created.status_code == 201, created.text+ assert created.json()["base_url"] == local_provider+++def test_managed_account_may_list_models_from_a_private_url_once_the_owner_allows_it(+ local_provider, owner_allows_private_urls+):+ """The save and the send have to agree, or the connection saves and then never works."""+ with client_for(ALICE) as client:+ listed = client.post(+ "/providers/models",+ json = {"provider_type": "custom", "base_url": local_provider},+ )+ assert listed.status_code == 200, listed.text+ assert [m["id"] for m in listed.json()] == [OWNER_LOCAL_MODEL]+++def test_cloud_metadata_stays_refused_even_when_the_owner_allows_private_urls(+ owner_allows_private_urls,+):+ with client_for(ALICE) as client:+ created = client.post(+ "/providers/",+ json = {+ "provider_type": "custom",+ "display_name": "metadata",+ "base_url": "http://169.254.169.254/v1",+ },+ )+ assert created.status_code == 400, created.text+ assert "metadata" in created.text.lower()++def test_owner_keeps_local_providers(local_provider):with client_for(OWNER) as client:created = client.post(diff --git a/studio/backend/tests/test_account_provider_rebind_pin.py b/studio/backend/tests/test_account_provider_rebind_pin.pyindex 06a234e3255..627e823f48b 100644--- a/studio/backend/tests/test_account_provider_rebind_pin.py+++ b/studio/backend/tests/test_account_provider_rebind_pin.py@@ -63,7 +63,7 @@ def rebinding_dns(monkeypatch, owner_local):monkeypatch.setattr(socket, "getaddrinfo", fake)monkeypatch.setattr(providers, "_dns_cache", {})- monkeypatch.setattr(external_provider, "_managed_http_client", None, raising = False)+ monkeypatch.setattr(external_provider, "_managed_clients", {}, raising = False)return answersdiff --git a/studio/backend/tests/test_account_provider_transport_optin.py b/studio/backend/tests/test_account_provider_transport_optin.pynew file mode 100644index 00000000000..2d4cbed36a6--- /dev/null+++ b/studio/backend/tests/test_account_provider_transport_optin.py@@ -0,0 +1,263 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Which httpx client a managed account gets, and that the choice follows the switch live.++The pin is not merely an optimisation: with the switch on it would refuse the very+connection the owner allowed, so the selection has to move with the setting rather+than being decided once at import.+"""++from pathlib import Path+import sys++import time++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import external_provider+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def fresh_singleton(monkeypatch):+ monkeypatch.setattr(external_provider, "_managed_clients", {}, raising = False)+ monkeypatch.setattr(external_provider, "_retired_accounts", set(), raising = False)+ yield+ external_provider._managed_clients = {}+ external_provider._retired_accounts = set()+++def switch(monkeypatch):+ state = {"allowed": False}+ from utils import managed_provider_url_settings++ # Patched on the settings module: `_client` imports the helper per call, so a caller-side+ # patch would miss.+ monkeypatch.setattr(+ managed_provider_url_settings,+ "get_managed_private_provider_urls_allowed",+ lambda: state["allowed"],+ )+ return state+++def client_as(account):+ token = bind_account(account)+ try:+ return external_provider._client()+ finally:+ reset_account(token)+++def is_pinned(client) -> bool:+ """Public-only. Exact type: the allowed-private screen subclasses this, so isinstance would+ call that pinned too and every assertion below would stop meaning anything."""+ return type(getattr(client, "_transport", None)) is external_provider._PinnedPublicTransport+++def test_owner_always_gets_the_shared_client(switch):+ for allowed in (False, True):+ switch["allowed"] = allowed+ assert client_as(OWNER) is external_provider._http_client+++def test_managed_account_is_pinned_by_default(switch):+ assert is_pinned(client_as(ALICE))+++def test_managed_account_stops_being_held_to_public_when_allowed(switch):+ """The public pin comes off; a screen that still refuses metadata replaces it."""+ switch["allowed"] = True+ client = client_as(ALICE)+ assert not is_pinned(client)+ assert isinstance(client._transport, external_provider._PinnedNonMetadataTransport)+ assert client is not external_provider._http_client+++def test_the_choice_follows_a_live_flip(switch):+ """A stale module-level singleton must not outlive the setting that selected it."""+ assert is_pinned(client_as(ALICE))+ switch["allowed"] = True+ assert isinstance(client_as(ALICE)._transport, external_provider._PinnedNonMetadataTransport)+ switch["allowed"] = False+ assert is_pinned(client_as(ALICE))+++def test_the_pinning_client_is_reused_not_rebuilt(switch):+ """Rebuilding per call would drop every pooled connection."""+ assert client_as(ALICE) is client_as(ALICE)+++def test_two_managed_accounts_never_share_a_client(switch):+ """httpx persists cookies per client, so one shared by two accounts carries a gateway+ session from one to the other. https://www.python-httpx.org/advanced/clients/"""+ for allowed in (False, True):+ switch["allowed"] = allowed+ alice, bob = client_as(ALICE), client_as(BOB)+ assert alice is not bob++ alice.cookies.set("gateway_session", "ALICE", domain = "gw.example")+ try:+ assert bob.cookies.get("gateway_session", domain = "gw.example") is None+ finally:+ alice.cookies.clear()+++def test_an_unbound_thread_defaults_to_owner(switch):+ """The account ContextVar fails open: a worker thread that forgot run_as reads as the owner.+ Unchanged by the switch, and load-bearing for any _client() caller off the request path."""+ import threading++ seen = []++ def worker():+ seen.append(external_provider._client())++ token = bind_account(ALICE)+ try:+ thread = threading.Thread(target = worker)+ thread.start()+ thread.join()+ finally:+ reset_account(token)+ assert seen[0] is external_provider._http_client+++def test_the_allowed_client_is_never_the_owners_object(switch):+ """An httpx client carries a cookie jar, so sharing the object shares Set-Cookie across accounts."""+ switch["allowed"] = True+ managed = client_as(ALICE)+ assert managed is not external_provider._http_client+ assert managed.cookies is not external_provider._http_client.cookies++ external_provider._http_client.cookies.set("owner_session", "SECRET", domain = "gw.example")+ try:+ assert managed.cookies.get("owner_session", domain = "gw.example") is None+ finally:+ external_provider._http_client.cookies.clear()+++def test_the_allowed_client_still_screens_every_connection(switch):+ """The switch opens private addresses, not the host's credentials endpoint."""+ switch["allowed"] = True+ managed = client_as(ALICE)+ transport = managed._transport+ assert isinstance(transport, external_provider._PinnedNonMetadataTransport)++ from core.inference.providers import provider_address_excluding_metadata++ # Private is now fine, metadata never is, whichever spelling it arrives in.+ assert provider_address_excluding_metadata("http://127.0.0.1:11434/v1") == "127.0.0.1"+ assert provider_address_excluding_metadata("http://192.168.1.50:8000/v1") == "192.168.1.50"+ for metadata in (+ "http://169.254.169.254/v1",+ "http://2852039166/v1",+ "http://[fd00:ec2::254]/v1",+ ):+ with pytest.raises(ValueError) as refusal:+ provider_address_excluding_metadata(metadata)+ assert "metadata" in str(refusal.value).lower()+++def test_a_retired_account_stops_being_held(switch):+ """Deleting an account has to drop its clients, or the cache is bounded by accounts ever+ created rather than accounts that exist, and a deleted one's cookie jar outlives it."""+ for allowed in (False, True):+ switch["allowed"] = allowed+ client_as(ALICE)+ client_as(BOB)+ assert sum(1 for key in external_provider._managed_clients if key[0] == ALICE.account_id) == 2++ assert external_provider.retire_account_clients(ALICE.account_id) == 2+ assert not [key for key in external_provider._managed_clients if key[0] == ALICE.account_id]+ # Another account's client is untouched.+ assert [key for key in external_provider._managed_clients if key[0] == BOB.account_id]+ # A second retirement is a no-op rather than an error.+ assert external_provider.retire_account_clients(ALICE.account_id) == 0+++def test_account_retirement_calls_it(switch):+ """The route is where it has to happen; a helper nobody calls fixes nothing."""+ import inspect++ import routes.accounts as accounts_routes++ source = inspect.getsource(accounts_routes.retire_account_roots)+ assert "retire_account_clients" in source+++def test_a_request_after_retirement_is_served_but_not_cached(switch):+ """A request that authenticated before deletion can reach _client() after the sweep; it+ gets a working client, and nothing is left behind for an account nothing sweeps again."""+ client_as(ALICE)+ external_provider.retire_account_clients(ALICE.account_id)++ late = client_as(ALICE)+ assert late is not None+ assert not [key for key in external_provider._managed_clients if key[0] == ALICE.account_id]+ # And it is a fresh object each time rather than a cached one.+ assert client_as(ALICE) is not late+++def test_retirement_from_a_worker_thread_closes_on_the_owning_loop(switch):+ """Deletion is a synchronous route, so it runs with no loop of its own. Dropping the last+ reference does not close an httpx pool; the close has to reach the loop that opened it."""+ import asyncio+ import threading++ loop = asyncio.new_event_loop()+ ready = threading.Event()++ def run_loop():+ asyncio.set_event_loop(loop)+ loop.call_soon(ready.set)+ loop.run_forever()++ thread = threading.Thread(target = run_loop, daemon = True)+ thread.start()+ ready.wait(5)+ try:+ # Built ON the loop, as a request would be.+ client = asyncio.run_coroutine_threadsafe(_make_client_as(ALICE), loop).result(timeout = 10)+ assert not client.is_closed++ # Retired from a thread with no running loop, like the delete route.+ assert external_provider.retire_account_clients(ALICE.account_id) == 1+ deadline = time.time() + 10+ while time.time() < deadline and not client.is_closed:+ time.sleep(0.05)+ assert client.is_closed, "the client was dropped rather than closed"+ finally:+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout = 5)+++async def _make_client_as(account):+ return client_as(account)+++def test_reactivation_lifts_the_tombstone(switch):+ """A delete that failed leaves the account disabled and reactivatable; a tombstone left+ behind would mean a fresh client per request forever after."""+ client_as(ALICE)+ external_provider.retire_account_clients(ALICE.account_id)+ assert client_as(ALICE) is not client_as(ALICE)++ external_provider.restore_account_clients(ALICE.account_id)+ assert client_as(ALICE) is client_as(ALICE)+++def test_reactivation_route_calls_it(switch):+ import inspect++ import routes.accounts as accounts_routes+ assert "restore_account_clients" in inspect.getsource(accounts_routes.set_account_active)diff --git a/studio/backend/tests/test_managed_provider_url_policy.py b/studio/backend/tests/test_managed_provider_url_policy.pynew file mode 100644index 00000000000..01665731a52--- /dev/null+++ b/studio/backend/tests/test_managed_provider_url_policy.py@@ -0,0 +1,292 @@+# 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 owner's switch for managed-account provider base URLs on private addresses (#11382).++Default off, so every installation keeps the refusal that shipped. Turned on, the three places that+enforce it -- the validator, the pinned transport and the recipe egress guard -- all stand down+together, because a connection that saves and then fails at send time is worse than one that never+saved. Cloud metadata endpoints stay refused either way, and the shared-host environment opt-in+outranks the switch.+"""++import threading++import pytest++from core.inference import external_provider, providers+from storage import studio_db+from utils import managed_provider_url_settings as setting+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")++PRIVATE_URLS = [+ "http://127.0.0.1:11434/v1",+ "http://192.168.1.50:8000/v1",+ "http://10.1.2.3:8000/v1",+]+METADATA_URLS = [+ "http://169.254.169.254/v1",+ "http://metadata.google.internal/v1",+]++[email protected](autouse = True)+def _clean_resolver_state(monkeypatch, tmp_path):+ # Isolated per test: the real setter would otherwise write to the machine's own installation.+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.delenv(setting.BLOCK_PRIVATE_ENV, raising = False)+ setting.forget_cached_setting()+ providers._dns_cache.clear()+ providers._dns_in_flight = threading.BoundedSemaphore(providers._DNS_MAX_IN_FLIGHT)+ yield+ setting.forget_cached_setting()+ providers._dns_cache.clear()+++def as_alice():+ token = bind_account(ALICE)+ try:+ yield+ finally:+ reset_account(token)+++def _allow(monkeypatch, allowed: bool) -> None:+ """Answer the setting without a DB; the round trip through one is tested separately."""+ monkeypatch.setattr(+ setting, "get_managed_private_provider_urls_allowed", lambda: allowed, raising = True+ )++[email protected]("url", PRIVATE_URLS)+def test_a_managed_account_is_refused_by_default(monkeypatch, as_alice, url):+ _allow(monkeypatch, False)+ with pytest.raises(ValueError) as refusal:+ providers.validate_provider_base_url(url)+ assert "public-network provider base URLs" in str(refusal.value)+ # The person reading this cannot lift it themselves, so it says who can.+ assert "Settings > General" in str(refusal.value)++[email protected]("url", PRIVATE_URLS)+def test_a_managed_account_may_use_a_private_url_once_the_owner_allows_it(+ monkeypatch, as_alice, url+):+ _allow(monkeypatch, True)+ assert providers.validate_provider_base_url(url) == url++[email protected]("url", PRIVATE_URLS)+def test_the_owner_is_unaffected_either_way(monkeypatch, url):+ for allowed in (False, True):+ _allow(monkeypatch, allowed)+ assert providers.validate_provider_base_url(url) == url++[email protected]("url", METADATA_URLS)+def test_cloud_metadata_stays_refused_with_the_setting_on(monkeypatch, as_alice, url):+ """The switch is about the owner's LAN, never about the host's credentials endpoint."""+ _allow(monkeypatch, True)+ with pytest.raises(ValueError) as refusal:+ providers.validate_provider_base_url(url)+ assert "metadata" in str(refusal.value).lower()++[email protected]("url", PRIVATE_URLS)+def test_the_environment_opt_in_outranks_the_setting(monkeypatch, as_alice, url):+ """A shared host says no for everyone, and a settings page does not undo the environment."""+ monkeypatch.setenv(setting.BLOCK_PRIVATE_ENV, "1")+ setting.set_managed_private_provider_urls_allowed(True)+ assert setting.get_managed_private_provider_urls_allowed() is False+ with pytest.raises(ValueError):+ providers.validate_provider_base_url(url)+++def test_the_owner_never_pays_for_the_setting_read(monkeypatch):+ """The owner path answers before the store is touched, so a single-user install reads nothing."""++ def _explode():+ raise AssertionError("the owner path must not read the setting")++ monkeypatch.setattr(setting, "get_managed_private_provider_urls_allowed", _explode)+ assert external_provider._client() is external_provider._http_client+++def settings_client():+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ import routes.settings as settings_routes++ app = FastAPI()+ app.include_router(settings_routes.router)+ app.dependency_overrides[settings_routes.get_current_subject] = lambda: "unsloth"+ # An interactive owner at the console, which is what the write requires.+ app.dependency_overrides[settings_routes.authenticated_via_api_key] = lambda: False+ with TestClient(app, raise_server_exceptions = False) as client:+ yield client+++def test_the_owner_route_reads_and_writes_the_real_store(settings_client):+ """The route module is unit-tested against a stub elsewhere; this is the round trip."""+ body = settings_client.get("/managed-provider-urls").json()+ assert body["allowed"] is False+ assert body["default_allowed"] is False+ assert body["locked_by_environment"] is False++ updated = settings_client.put("/managed-provider-urls", json = {"allowed": True})+ assert updated.status_code == 200, updated.text+ assert updated.json()["allowed"] is True+ assert settings_client.get("/managed-provider-urls").json()["allowed"] is True+ assert setting.get_managed_private_provider_urls_allowed() is True+++def test_the_route_reports_the_environment_lock(monkeypatch, settings_client):+ """Stored on, held off by the environment: the UI needs to say why, not show a switch that lies."""+ settings_client.put("/managed-provider-urls", json = {"allowed": True})+ monkeypatch.setenv(setting.BLOCK_PRIVATE_ENV, "1")+ body = settings_client.get("/managed-provider-urls").json()+ assert body["allowed"] is False+ assert body["locked_by_environment"] is True+++def test_the_recipe_endpoint_check_stands_down_with_the_setting_on(monkeypatch, as_alice):+ from core.data_recipe import service++ _allow(monkeypatch, False)+ with pytest.raises(Exception) as refusal:+ service._require_public_provider_endpoint("http://192.168.1.50:8000/v1")+ assert "Settings > General" in str(getattr(refusal.value, "detail", refusal.value))++ _allow(monkeypatch, True)+ service._require_public_provider_endpoint("http://192.168.1.50:8000/v1")+++ "url", ["http://169.254.169.254/latest/meta-data/", "http://2852039166/v1"]+)+def test_the_recipe_endpoint_check_still_refuses_metadata_with_the_setting_on(+ monkeypatch, as_alice, url+):+ """The recipe path has no validator behind it, so what it waves through is dialled."""+ from core.data_recipe import service++ _allow(monkeypatch, True)+ with pytest.raises(Exception) as refusal:+ service._require_public_provider_endpoint(url)+ assert "metadata" in str(getattr(refusal.value, "detail", refusal.value)).lower()+++def test_the_recipe_egress_guard_narrows_rather_than_standing_down(monkeypatch, as_alice):+ """With the setting on the guard stays installed and keeps refusing the metadata service."""+ import socket++ from core.data_recipe import service++ original = socket.getaddrinfo+ monkeypatch.setattr(socket, "getaddrinfo", original)+ _allow(monkeypatch, True)+ try:+ service.install_public_egress_guard()+ guarded = socket.getaddrinfo+ assert guarded is not original++ # A LAN answer is what the switch bought; the metadata answer is not.+ monkeypatch.setattr(+ service.socket if hasattr(service, "socket") else socket,+ "getaddrinfo",+ guarded,+ raising = False,+ )+ assert guarded("192.168.1.50", 8000, type = socket.SOCK_STREAM)+ with pytest.raises(socket.gaierror) as refusal:+ guarded("169.254.169.254", 80, type = socket.SOCK_STREAM)+ assert "metadata" in str(refusal.value).lower()+ finally:+ socket.getaddrinfo = original+++def test_the_recipe_guard_follows_a_later_flip(monkeypatch, as_alice):+ """A worker outlives the switch it started under, so the guard asks per lookup."""+ import socket++ from core.data_recipe import service++ original = socket.getaddrinfo+ monkeypatch.setattr(socket, "getaddrinfo", original)+ # The real store: the guard closed over the function it imported, so rebinding that name+ # proves nothing about a running worker.+ setting.set_managed_private_provider_urls_allowed(True)+ try:+ service.install_public_egress_guard()+ guarded = socket.getaddrinfo+ assert guarded("192.168.1.50", 8000, type = socket.SOCK_STREAM)++ # The owner turns it off while this worker is still running.+ setting.set_managed_private_provider_urls_allowed(False)+ with pytest.raises(socket.gaierror) as refusal:+ guarded("192.168.1.50", 8000, type = socket.SOCK_STREAM)+ assert "public-network" in str(refusal.value)+ finally:+ socket.getaddrinfo = original++[email protected]("url", PRIVATE_URLS)+def test_the_refusal_stops_naming_the_switch_when_the_environment_holds_it(+ monkeypatch, as_alice, url+):+ """Sending someone to a control their owner cannot use either is worse than saying nothing."""+ monkeypatch.setenv(setting.BLOCK_PRIVATE_ENV, "1")+ with pytest.raises(ValueError) as refusal:+ providers.validate_provider_base_url(url)+ assert "Settings > General" not in str(refusal.value)++ monkeypatch.delenv(setting.BLOCK_PRIVATE_ENV)+ _allow(monkeypatch, False)+ with pytest.raises(ValueError) as refusal:+ providers.validate_provider_base_url(url)+ assert "Settings > General" in str(refusal.value)++[email protected]("url", ["ftp://192.168.1.50/model", "file:///etc/passwd"])+def test_the_recipe_endpoint_check_still_requires_http_with_the_setting_on(+ monkeypatch, as_alice, url+):+ """The switch lifts HTTPS-only and public-only, not http(s)-only."""+ from core.data_recipe import service++ _allow(monkeypatch, True)+ with pytest.raises(Exception) as refusal:+ service._require_public_provider_endpoint(url)+ assert "http" in str(getattr(refusal.value, "detail", refusal.value)).lower()+++def test_a_link_local_provider_that_saves_can_also_be_dialled(monkeypatch, as_alice):+ """Save and dial have to agree. 169.254.0.0/16 is also where a self-assigned host and an+ mDNS name land, so a DNS answer there is an ordinary LAN provider, not the metadata service.+ A typed literal in that range stays refused at both ends, which is what the validator does."""+ import socket++ from core.inference.providers import provider_address_excluding_metadata++ _allow(monkeypatch, True)++ def fake_getaddrinfo(host, port, *args, **kwargs):+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("169.254.3.7", port or 80))]++ # providers.py imports socket inside each function, so patching the stdlib module reaches it.+ monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)++ saved = providers.validate_provider_base_url("http://printer.local:8000/v1")+ assert saved == "http://printer.local:8000/v1"+ assert provider_address_excluding_metadata(saved) == "169.254.3.7"++ # The metadata service itself, and a literal anywhere in the range, still refused.+ for literal in ("http://169.254.169.254/v1", "http://169.254.3.7/v1"):+ with pytest.raises(ValueError):+ provider_address_excluding_metadata(literal)diff --git a/studio/backend/tests/test_managed_provider_url_store.py b/studio/backend/tests/test_managed_provider_url_store.pynew file mode 100644index 00000000000..b41049188da--- /dev/null+++ b/studio/backend/tests/test_managed_provider_url_store.py@@ -0,0 +1,252 @@+# 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 installation-wide switch for managed-account private provider URLs.++The switch lives in the owner's app_settings, but every interesting read happens+while a MANAGED account is bound: ``workspace_root`` sends a managed caller to+``accounts/<id>/`` and ``account_path`` raises on anything outside it, so the+read has to cross back into the owner's tree deliberately. If it did not, the+feature would fail closed forever and the owner's switch would do nothing.+"""++from pathlib import Path+import sys++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from storage import studio_db+from utils import managed_provider_url_settings as mpu+from utils.account_context import OWNER, AccountContext, bind_account, reset_account+from utils.paths import storage_roots++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")++[email protected](autouse = True)+def isolated_home(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ # The helper holds its answer briefly, and each test has its own home.+ mpu.forget_cached_setting()+ yield+ mpu.forget_cached_setting()+++def as_account():+ tokens = []++ def _bind(account):+ tokens.append(bind_account(account))++ yield _bind+ for token in reversed(tokens):+ reset_account(token)+++def test_default_is_off():+ assert mpu.get_managed_private_provider_urls_allowed() is False+++def test_owner_write_then_owner_read():+ assert mpu.set_managed_private_provider_urls_allowed(True) is True+ assert mpu.get_managed_private_provider_urls_allowed() is True+++def test_managed_account_can_read_the_owners_switch(as_account):+ """The load-bearing one: a managed caller must see what the owner set."""+ mpu.set_managed_private_provider_urls_allowed(True)+ as_account(ALICE)+ assert mpu.get_managed_private_provider_urls_allowed() is True+++def test_managed_read_does_not_create_a_per_account_copy(as_account, tmp_path):+ """A read from Alice must not land in, or be answered by, Alice's own DB."""+ mpu.set_managed_private_provider_urls_allowed(True)+ as_account(ALICE)+ assert mpu.get_managed_private_provider_urls_allowed() is True+ alice_db = tmp_path / "accounts" / ALICE.account_id / "studio.db"+ assert not alice_db.exists(), "the managed read opened a per-account settings DB"+++def test_two_managed_accounts_see_one_installation_wide_answer(as_account):+ mpu.set_managed_private_provider_urls_allowed(True)+ for account in (ALICE, BOB):+ token = bind_account(account)+ try:+ assert mpu.get_managed_private_provider_urls_allowed() is True+ finally:+ reset_account(token)+++def test_managed_account_write_still_targets_the_owner_db(as_account):+ """The route is owner-only, but the setter must not silently write the wrong DB+ if it is ever called from a managed context."""+ as_account(ALICE)+ mpu.set_managed_private_provider_urls_allowed(True)+ reset_account(bind_account(OWNER))+ token = bind_account(OWNER)+ try:+ assert mpu.get_managed_private_provider_urls_allowed() is True+ finally:+ reset_account(token)+++def test_read_failure_fails_closed(monkeypatch):+ mpu.set_managed_private_provider_urls_allowed(True)++ def boom(*args, **kwargs):+ raise sqlite_error()++ def sqlite_error():+ import sqlite3+ return sqlite3.OperationalError("unable to open database file")++ monkeypatch.setattr(studio_db, "get_app_setting", boom)+ assert mpu.get_managed_private_provider_urls_allowed() is False+++def test_account_path_would_have_raised_without_the_owner_hop(as_account):+ """Documents why the run_as hop exists: the owner's DB path is not reachable+ from a managed context by the ordinary accessor."""+ as_account(ALICE)+ with pytest.raises(ValueError):+ storage_roots.account_path("../../studio.db")+++ "stored,expected",+ [+ (True, True),+ (False, False),+ ("true", True),+ ("off", False),+ ("", False),+ (None, False),+ # Junk is not a yes.+ ("maybe", False),+ (1, False),+ ],+)+def test_stored_value_coercion(monkeypatch, stored, expected):+ monkeypatch.setattr(studio_db, "get_app_setting", lambda key, fallback = None: stored)+ assert mpu.get_managed_private_provider_urls_allowed() is expected++[email protected]("value", ["maybe", 1, 0, None, [], {}])+def test_setter_rejects_non_boolean(value):+ if isinstance(value, str) and value in {"1", "true", "yes", "on"}:+ pytest.skip("accepted spelling")+ with pytest.raises(ValueError):+ mpu.set_managed_private_provider_urls_allowed(value)+++def test_the_held_answer_is_dropped_by_a_write(as_account):+ """Turning the switch off has to bite the next request, not the next second."""+ as_account(OWNER)+ mpu.set_managed_private_provider_urls_allowed(True)+ assert mpu.get_managed_private_provider_urls_allowed() is True++ mpu.set_managed_private_provider_urls_allowed(False)+ # No sleep: if this read came from the held answer it would still say True.+ assert mpu.get_managed_private_provider_urls_allowed() is False+++def test_the_environment_lock_is_not_answered_from_the_cache(monkeypatch, as_account):+ """The strict answer must never be the held one, whatever was read a moment ago."""+ as_account(OWNER)+ mpu.set_managed_private_provider_urls_allowed(True)+ assert mpu.get_managed_private_provider_urls_allowed() is True++ monkeypatch.setenv(mpu.BLOCK_PRIVATE_ENV, "1")+ assert mpu.get_managed_private_provider_urls_allowed() is False+ monkeypatch.delenv(mpu.BLOCK_PRIVATE_ENV)+ assert mpu.get_managed_private_provider_urls_allowed() is True+++def test_a_read_failure_is_never_remembered(monkeypatch, as_account):+ """A transient error fails closed per call; remembering it would pin the refusal."""+ as_account(OWNER)+ mpu.set_managed_private_provider_urls_allowed(True)+ mpu.forget_cached_setting()++ def _explode(*args, **kwargs):+ raise OSError("settings db is gone")++ import storage.studio_db as studio_db_module++ real = studio_db_module.get_app_setting+ studio_db_module.get_app_setting = _explode+ try:+ assert mpu.get_managed_private_provider_urls_allowed() is False+ assert mpu._remembered() is None+ finally:+ # By hand: monkeypatch.undo() would also undo the isolated-home fixture.+ studio_db_module.get_app_setting = real+ assert mpu.get_managed_private_provider_urls_allowed() is True+++def test_the_held_answer_expires(monkeypatch, as_account):+ """A flip made in another process converges within the TTL rather than never."""+ as_account(OWNER)+ mpu.set_managed_private_provider_urls_allowed(False)+ assert mpu.get_managed_private_provider_urls_allowed() is False++ # Written behind this module's back, the way a second process would.+ from storage.studio_db import upsert_app_settings+ from utils.account_context import run_as++ run_as(+ OWNER,+ upsert_app_settings,+ {mpu.MANAGED_PRIVATE_PROVIDER_URLS_SETTING_KEY: True},+ )+ assert mpu.get_managed_private_provider_urls_allowed() is False # still held++ # Age the entry, not the clock: patching time.monotonic recurses through the cache's own call.+ with mpu._cache_lock:+ expiry, value = mpu._cached+ mpu._cached = (expiry - mpu._CACHE_TTL_SECONDS - 1.0, value)+ assert mpu.get_managed_private_provider_urls_allowed() is True+++def test_a_read_in_flight_cannot_republish_what_a_write_replaced(as_account):+ """The owner disabling the switch is not undone by a read that started before it.++ The losing interleaving is: a managed request finds nothing held and goes to+ the store, the owner's PUT commits False and drops the cache, and only then+ does the older read hand back the True it saw. Without the generation check+ that True is held for the whole TTL, so private egress keeps working after+ the owner switched it off. The write is driven from inside the store read,+ which is that interleaving exactly rather than a sleep hoping to hit it.+ """+ as_account(OWNER)+ mpu.set_managed_private_provider_urls_allowed(True)+ mpu.forget_cached_setting()++ import storage.studio_db as studio_db_module++ real = studio_db_module.get_app_setting++ def _write_lands_mid_read(*args, **kwargs):+ stored = real(*args, **kwargs)+ studio_db_module.get_app_setting = real # the setter must not re-enter this+ mpu.set_managed_private_provider_urls_allowed(False)+ return stored++ studio_db_module.get_app_setting = _write_lands_mid_read+ try:+ # The stale value is still what THIS call returns: it is the answer the+ # caller was already committed to. What must not happen is it outliving+ # the call.+ assert mpu.get_managed_private_provider_urls_allowed() is True+ assert mpu._remembered() is None+ assert mpu.get_managed_private_provider_urls_allowed() is False+ finally:+ studio_db_module.get_app_setting = realdiff --git a/studio/backend/tests/test_managed_provider_urls_route.py b/studio/backend/tests/test_managed_provider_urls_route.pynew file mode 100644index 00000000000..3b7d4920082--- /dev/null+++ b/studio/backend/tests/test_managed_provider_urls_route.py@@ -0,0 +1,125 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Route policy for /api/settings/managed-provider-urls.++Writing it is owner-only and UI-session-only: an sk-unsloth key must not be able+to widen the installation's egress policy. Reading it is deliberately shared, so+a managed account can tell "ask your owner" from "this is not allowed here".+"""++from pathlib import Path+import sys+import types as _types++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.settings as settings+from utils.account_context import OWNER, AccountContext, bind_account, reset_account++ALICE = AccountContext("a" * 32, "alice")+++def make_client(monkeypatch):+ state: dict = {"allowed": False}++ monkeypatch.setattr(+ settings, "get_managed_private_provider_urls_allowed", lambda: state["allowed"]+ )++ def _set(value):+ if not isinstance(value, bool):+ raise ValueError("Managed private provider URLs must be true or false.")+ state["allowed"] = value+ return value++ monkeypatch.setattr(settings, "set_managed_private_provider_urls_allowed", _set)++ def _build(account, via_api_key = False):+ app = FastAPI()+ app.include_router(settings.router)++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[settings.get_current_subject] = subject+ app.dependency_overrides[settings.authenticated_via_api_key] = lambda: via_api_key+ return TestClient(app, raise_server_exceptions = False)++ return _build, state+++def test_owner_reads_and_writes(make_client):+ build, state = make_client+ with build(OWNER) as client:+ assert client.get("/managed-provider-urls").json()["allowed"] is False+ put = client.put("/managed-provider-urls", json = {"allowed": True})+ assert put.status_code == 200, put.text+ assert put.json()["allowed"] is True+ assert state["allowed"] is True+ assert client.get("/managed-provider-urls").json()["allowed"] is True+++def test_response_reports_the_default_and_the_env_override(make_client, monkeypatch):+ from core.inference.providers import _BLOCK_PRIVATE_ENV++ build, _ = make_client+ monkeypatch.delenv(_BLOCK_PRIVATE_ENV, raising = False)+ with build(OWNER) as client:+ body = client.get("/managed-provider-urls").json()+ assert body["default_allowed"] is False+ assert body["locked_by_environment"] is False++ monkeypatch.setenv(_BLOCK_PRIVATE_ENV, "1")+ with build(OWNER) as client:+ assert client.get("/managed-provider-urls").json()["locked_by_environment"] is True+++def test_managed_account_may_read(make_client):+ build, state = make_client+ state["allowed"] = True+ with build(ALICE) as client:+ response = client.get("/managed-provider-urls")+ assert response.status_code == 200, response.text+ assert response.json()["allowed"] is True+++def test_managed_account_may_not_write(make_client):+ build, state = make_client+ with build(ALICE) as client:+ response = client.put("/managed-provider-urls", json = {"allowed": True})+ assert response.status_code == 403, response.text+ assert state["allowed"] is False+++def test_api_key_session_may_not_write(make_client):+ """An sk-unsloth key is owner-authenticated but not a UI session."""+ build, state = make_client+ with build(OWNER, via_api_key = True) as client:+ response = client.put("/managed-provider-urls", json = {"allowed": True})+ assert response.status_code == 403, response.text+ assert state["allowed"] is False++[email protected]("body", [{"allowed": "maybe"}, {"allowed": 1}, {"allowed": "true"}, {}])+def test_non_boolean_body_is_refused(make_client, body):+ build, state = make_client+ with build(OWNER) as client:+ response = client.put("/managed-provider-urls", json = body)+ assert response.status_code == 422, response.text+ assert state["allowed"] is Falsediff --git a/studio/backend/utils/managed_provider_url_settings.py b/studio/backend/utils/managed_provider_url_settings.pynew file mode 100644index 00000000000..c6d6e5a49b7--- /dev/null+++ b/studio/backend/utils/managed_provider_url_settings.py@@ -0,0 +1,110 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Owner-held switch for whether managed accounts may point a provider connection at a private address."""++from __future__ import annotations++import os+import threading+import time+from typing import Any++MANAGED_PRIVATE_PROVIDER_URLS_SETTING_KEY = "managed_private_provider_urls_allowed"+DEFAULT_MANAGED_PRIVATE_PROVIDER_URLS_ALLOWED = False++# Refuses private addresses for EVERY account, owner included, and outranks the stored preference:+# what an operator set in the environment is not undone from a settings page.+BLOCK_PRIVATE_ENV = "UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS"++# Asked by every managed outbound request; uncached it costs a fresh SQLite connection (~600us) on+# the shared loop. A write drops the entry, so the TTL only bounds staleness in ANOTHER process.+_CACHE_TTL_SECONDS = 1.0+_cache_lock = threading.Lock()+_cached: tuple[float, bool] | None = None+# Bumped by every write: a read that started earlier must not publish what it saw, or a disable+# keeps allowing private egress for the rest of the TTL.+_generation = 0+++def _remembered() -> bool | None:+ with _cache_lock:+ if _cached is not None and _cached[0] > time.monotonic():+ return _cached[1]+ return None+++def _remember(value: bool, generation: int) -> None:+ global _cached+ with _cache_lock:+ if generation != _generation:+ return+ _cached = (time.monotonic() + _CACHE_TTL_SECONDS, value)+++def forget_cached_setting() -> None:+ """Drop the held answer and retire any read already in flight. Called on write."""+ global _cached, _generation+ with _cache_lock:+ _cached = None+ _generation += 1+++def _coerce_bool(value: Any) -> bool | None:+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ normalized = value.strip().lower()+ if normalized in {"1", "true", "yes", "on"}:+ return True+ if normalized in {"0", "false", "no", "off", ""}:+ return False+ return None+++def private_urls_locked_by_environment() -> bool:+ """True when the shared-host environment opt-in decides this, whatever the stored preference."""+ return os.environ.get(BLOCK_PRIVATE_ENV) == "1"+++def get_managed_private_provider_urls_allowed() -> bool:+ """Whether a managed account may use a provider base URL that resolves to a private address.++ Installation-wide, so it is read from the owner's store whoever is asking. A missing setting+ keeps the refusal that shipped, and a read failure fails closed: an unreadable settings DB must+ not quietly widen what a managed account can dial.+ """+ # Before the cache: the strict answer is never the held one.+ if private_urls_locked_by_environment():+ return False+ held = _remembered()+ if held is not None:+ return held+ with _cache_lock:+ generation = _generation+ try:+ from storage.studio_db import get_app_setting+ from utils.account_context import OWNER, run_as+ stored = run_as(OWNER, get_app_setting, MANAGED_PRIVATE_PROVIDER_URLS_SETTING_KEY, None)+ except Exception: # noqa: BLE001 - an unreadable settings DB keeps the stricter answer+ return False+ parsed = _coerce_bool(stored)+ allowed = parsed if parsed is not None else DEFAULT_MANAGED_PRIVATE_PROVIDER_URLS_ALLOWED+ _remember(allowed, generation)+ return allowed+++def set_managed_private_provider_urls_allowed(value: Any) -> bool:+ """Persist whether managed accounts may dial private provider addresses."""+ parsed = _coerce_bool(value)+ if parsed is None:+ raise ValueError("The managed-account private provider URL setting must be true or false.")++ from storage.studio_db import upsert_app_settings+ from utils.account_context import OWNER, run_as++ # Owner-bound like the read: the two halves have to name one store.+ run_as(OWNER, upsert_app_settings, {MANAGED_PRIVATE_PROVIDER_URLS_SETTING_KEY: parsed})+ # Dropped, not replaced with `parsed`: a write that did not land must not be believed.+ forget_cached_setting()+ return parseddiff --git a/studio/frontend/src/features/settings/api/managed-provider-urls.ts b/studio/frontend/src/features/settings/api/managed-provider-urls.tsnew file mode 100644index 00000000000..fc46d3b4e74--- /dev/null+++ b/studio/frontend/src/features/settings/api/managed-provider-urls.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++import { SettingsRouteAbsentError } from "./settings-route-absent";++const ROUTE = "/api/settings/managed-provider-urls";++export type ManagedProviderUrlSettings = {+ allowed: boolean;+ defaultAllowed: boolean;+ // UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 refuses private addresses for+ // every account, so the switch cannot take effect while it is set.+ lockedByEnvironment: boolean;+};++type ApiManagedProviderUrlSettings = {+ allowed: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ default_allowed?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ locked_by_environment?: boolean;+};++function fromApi(+ settings: ApiManagedProviderUrlSettings,+): ManagedProviderUrlSettings {+ return {+ allowed: settings.allowed,+ defaultAllowed: settings.default_allowed ?? false,+ lockedByEnvironment: settings.locked_by_environment ?? false,+ };+}++export async function loadManagedProviderUrls(): Promise<ManagedProviderUrlSettings> {+ const res = await authFetch(ROUTE);+ // A backend older than this bundle does not serve the route. Told apart from a+ // failed read so the row can be hidden rather than shown with a red error the+ // owner cannot act on.+ if (res.status === 404) {+ throw new SettingsRouteAbsentError(ROUTE);+ }+ if (!res.ok) {+ throw new Error(+ await readFastApiError(+ res,+ "Failed to load managed account connection settings",+ ),+ );+ }+ return fromApi(await res.json());+}++export async function updateManagedProviderUrls(+ allowed: boolean,+): Promise<ManagedProviderUrlSettings> {+ const res = await authFetch(ROUTE, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ allowed }),+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(+ res,+ "Failed to save managed account connection settings",+ ),+ );+ }+ return fromApi(await res.json());+}diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex bc6db1bb46b..66460bc26bd 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -23,6 +23,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.general.previewSharing.sectionTitle","settings.general.previewSharing.enableLabel","settings.general.previewSharing.revokeLabel",+ "settings.general.managedProviderUrls.sectionTitle",+ "settings.general.managedProviderUrls.enableLabel","settings.general.rag.sectionTitle","settings.general.rag.embeddingModel","settings.general.helperLlm.sectionTitle",diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 085fdec8df6..29482dda2d1 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -46,6 +46,12 @@ import {loadHelperPrecacheSettings,updateHelperPrecacheSettings,} from "../api/helper-precache";+import {+ type ManagedProviderUrlSettings,+ loadManagedProviderUrls,+ updateManagedProviderUrls,+} from "../api/managed-provider-urls";+import { isSettingsRouteAbsent } from "../api/settings-route-absent";import {type PreviewSharingSettings,loadPreviewSharing,@@ -216,6 +222,16 @@ export function GeneralTab() {null,);const [isSavingPreviewSharing, setIsSavingPreviewSharing] = useState(false);+ const [managedProviderUrls, setManagedProviderUrls] =+ useState<ManagedProviderUrlSettings | null>(null);+ const [managedProviderUrlsError, setManagedProviderUrlsError] = useState<+ string | null+ >(null);+ const [isSavingManagedProviderUrls, setIsSavingManagedProviderUrls] =+ useState(false);+ // A backend that does not serve the route has no such setting to show.+ const [managedProviderUrlsAbsent, setManagedProviderUrlsAbsent] =+ useState(false);const [revokePreviewOpen, setRevokePreviewOpen] = useState(false);const [isRevokingPreview, setIsRevokingPreview] = useState(false);const launchAtLoginSetting = useDesktopBooleanSetting({@@ -335,6 +351,31 @@ export function GeneralTab() {};}, [t, isOwner]);+ useEffect(() => {+ if (!isOwner) return;+ let cancelled = false;+ void loadManagedProviderUrls()+ .then((settings) => {+ if (cancelled) return;+ setManagedProviderUrls(settings);+ setManagedProviderUrlsError(null);+ })+ .catch((error) => {+ if (cancelled) return;+ if (isSettingsRouteAbsent(error)) {+ setManagedProviderUrlsAbsent(true);+ return;+ }+ setManagedProviderUrlsError(+ error instanceof Error+ ? error.message+ : t("settings.general.managedProviderUrls.loadError"),+ );+ });+ return () => {+ cancelled = true;+ };+ }, [t, isOwner]);const saveHelperPrecache = async (enabled: boolean) => {setIsSavingHelperPrecache(true);@@ -372,6 +413,23 @@ export function GeneralTab() {}};+ const saveManagedProviderUrls = async (allowed: boolean) => {+ setIsSavingManagedProviderUrls(true);+ setManagedProviderUrlsError(null);+ try {+ const settings = await updateManagedProviderUrls(allowed);+ setManagedProviderUrls(settings);+ } catch (error) {+ setManagedProviderUrlsError(+ error instanceof Error+ ? error.message+ : t("settings.general.managedProviderUrls.saveError"),+ );+ } finally {+ setIsSavingManagedProviderUrls(false);+ }+ };+const revokePreviewLinks = async () => {setIsRevokingPreview(true);try {@@ -667,6 +725,43 @@ export function GeneralTab() {</SettingsRow></SettingsSection>+ {managedProviderUrlsAbsent ? null : (+ <SettingsSection+ title={t("settings.general.managedProviderUrls.sectionTitle")}+ >+ <SettingsRow+ label={t("settings.general.managedProviderUrls.enableLabel")}+ description={t(+ "settings.general.managedProviderUrls.enableDescription",+ )}+ >+ <div className="flex flex-col items-end gap-1">+ <Switch+ checked={managedProviderUrls?.allowed ?? false}+ disabled={+ !managedProviderUrls ||+ isSavingManagedProviderUrls ||+ managedProviderUrls.lockedByEnvironment+ }+ onCheckedChange={(allowed) =>+ void saveManagedProviderUrls(allowed)+ }+ />+ {managedProviderUrls?.lockedByEnvironment ? (+ <span className="max-w-[260px] text-right text-xs text-muted-foreground">+ {t("settings.general.managedProviderUrls.lockedByEnvironment")}+ </span>+ ) : null}+ {managedProviderUrlsError ? (+ <span className="max-w-[260px] text-right text-xs text-destructive">+ {managedProviderUrlsError}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ </SettingsSection>+ )}+<DocumentsRagSection /><SettingsSection title={t("settings.general.downloads.sectionTitle")}>diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 7238a01ed44..6ac92ff610e 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -888,6 +888,16 @@ export const ar = {revoked: "تم إلغاء جميع روابط المعاينة",revokeError: "تعذّر إلغاء روابط المعاينة",},+ managedProviderUrls: {+ sectionTitle: "الحسابات المُدارة",+ enableLabel: "الاتصالات المحلية والشبكية",+ enableDescription:+ "اسمح للحسابات المُدارة بتوجيه اتصالاتها إلى عناوين محلية أو عناوين على الشبكة، مثل خادم Ollama أو llama.cpp على هذا الجهاز أو على شبكتك المحلية. معطّل افتراضيًا، لأنه يتيح لتلك الحسابات الوصول إلى الخدمات التي تعمل على جهازك وعلى شبكتك.",+ lockedByEnvironment:+ "محدَّد عبر UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 على هذا الخادم، وهو يرفض العناوين الخاصة لكل الحسابات.",+ loadError: "تعذّر تحميل إعدادات اتصال الحسابات المُدارة.",+ saveError: "تعذّر حفظ إعدادات اتصال الحسابات المُدارة.",+ },notifications: {sectionTitle: "الإشعارات",showLlamaUpdates: "إشعارات تحديث llama.cpp",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex d68d2d04961..43330e2cfcc 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -907,6 +907,18 @@ export const de = {revoked: "Alle Vorschaulinks widerrufen",revokeError: "Vorschaulinks konnten nicht widerrufen werden",},+ managedProviderUrls: {+ sectionTitle: "Verwaltete Konten",+ enableLabel: "Lokale und Netzwerkverbindungen",+ enableDescription:+ "Verwaltete Konten dürfen ihre Verbindungen auf lokale oder Netzwerkadressen richten, etwa einen Ollama- oder llama.cpp-Server auf diesem Computer oder in Ihrem LAN. Standardmäßig aus, denn damit erreichen diese Konten Dienste, die auf Ihrem Computer und in Ihrem Netzwerk laufen.",+ lockedByEnvironment:+ "Durch UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 auf diesem Server festgelegt, das private Adressen für alle Konten ablehnt.",+ loadError:+ "Verbindungseinstellungen für verwaltete Konten konnten nicht geladen werden.",+ saveError:+ "Verbindungseinstellungen für verwaltete Konten konnten nicht gespeichert werden.",+ },notifications: {sectionTitle: "Benachrichtigungen",showLlamaUpdates: "llama.cpp-Update-Benachrichtigungen",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 06d5f12b37b..76c1564da66 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -887,6 +887,16 @@ export const en = {revoked: "All preview links revoked",revokeError: "Couldn't revoke preview links",},+ managedProviderUrls: {+ sectionTitle: "Managed accounts",+ enableLabel: "Local and network connections",+ enableDescription:+ "Let managed accounts point their connections at local or network addresses, such as an Ollama or llama.cpp server on this computer or your LAN. Off by default, because it lets those accounts reach services running on your computer and your network.",+ lockedByEnvironment:+ "Set by UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 on this server, which refuses private addresses for every account.",+ loadError: "Failed to load managed account connection settings.",+ saveError: "Failed to save managed account connection settings.",+ },permissions: {sectionTitle: "Permissions",bypassLabel: "Tool permissions",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex c6978e4e7f9..52a63eada5d 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -903,6 +903,18 @@ export const es = {revoked: "Todos los enlaces de vista previa revocados",revokeError: "No se pudieron revocar los enlaces de vista previa",},+ managedProviderUrls: {+ sectionTitle: "Cuentas gestionadas",+ enableLabel: "Conexiones locales y de red",+ enableDescription:+ "Permite que las cuentas gestionadas apunten sus conexiones a direcciones locales o de red, como un servidor Ollama o llama.cpp en este equipo o en tu red local. Desactivado de forma predeterminada, porque permite a esas cuentas alcanzar servicios que se ejecutan en tu equipo y en tu red.",+ lockedByEnvironment:+ "Definido por UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 en este servidor, que rechaza las direcciones privadas para todas las cuentas.",+ loadError:+ "No se pudo cargar la configuración de conexiones de las cuentas gestionadas.",+ saveError:+ "No se pudo guardar la configuración de conexiones de las cuentas gestionadas.",+ },notifications: {sectionTitle: "Notificaciones",showLlamaUpdates: "Notificaciones de actualización de llama.cpp",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex fe47b57bfd2..0e93d23c612 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -905,6 +905,18 @@ export const fr = {revoked: "Tous les liens d'aperçu ont été révoqués",revokeError: "Impossible de révoquer les liens d'aperçu",},+ managedProviderUrls: {+ sectionTitle: "Comptes gérés",+ enableLabel: "Connexions locales et réseau",+ enableDescription:+ "Autorise les comptes gérés à pointer leurs connexions vers des adresses locales ou réseau, comme un serveur Ollama ou llama.cpp sur cet ordinateur ou sur votre réseau local. Désactivé par défaut, car cela permet à ces comptes d'atteindre les services exécutés sur votre ordinateur et sur votre réseau.",+ lockedByEnvironment:+ "Défini par UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 sur ce serveur, qui refuse les adresses privées pour tous les comptes.",+ loadError:+ "Impossible de charger les paramètres de connexion des comptes gérés.",+ saveError:+ "Impossible d'enregistrer les paramètres de connexion des comptes gérés.",+ },notifications: {sectionTitle: "Notifications",showLlamaUpdates: "Notifications de mise à jour de llama.cpp",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 0114af5f9b5..e09bc1019a0 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -891,6 +891,16 @@ export const hi = {revoked: "सभी पूर्वावलोकन लिंक रद्द किए गए",revokeError: "पूर्वावलोकन लिंक रद्द नहीं किए जा सके",},+ managedProviderUrls: {+ sectionTitle: "प्रबंधित खाते",+ enableLabel: "स्थानीय और नेटवर्क कनेक्शन",+ enableDescription:+ "प्रबंधित खातों को अपने कनेक्शन स्थानीय या नेटवर्क पतों की ओर इंगित करने दें, जैसे इस कंप्यूटर या आपके लोकल नेटवर्क पर चल रहा Ollama या llama.cpp सर्वर। डिफ़ॉल्ट रूप से बंद, क्योंकि इससे वे खाते आपके कंप्यूटर और नेटवर्क पर चल रही सेवाओं तक पहुँच सकते हैं।",+ lockedByEnvironment:+ "इस सर्वर पर UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 द्वारा तय, जो सभी खातों के लिए निजी पतों को अस्वीकार करता है।",+ loadError: "प्रबंधित खाता कनेक्शन सेटिंग्स लोड नहीं हो सकीं।",+ saveError: "प्रबंधित खाता कनेक्शन सेटिंग्स सहेजी नहीं जा सकीं।",+ },notifications: {sectionTitle: "सूचनाएं",showLlamaUpdates: "llama.cpp अपडेट सूचनाएं",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 9d6240498a7..d2210881637 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -872,6 +872,18 @@ export const it = {revoked: "Tutti i link di anteprima sono stati revocati",revokeError: "Impossibile revocare i link di anteprima",},+ managedProviderUrls: {+ sectionTitle: "Account gestiti",+ enableLabel: "Connessioni locali e di rete",+ enableDescription:+ "Consente agli account gestiti di puntare le proprie connessioni a indirizzi locali o di rete, come un server Ollama o llama.cpp su questo computer o sulla tua rete locale. Disattivato per impostazione predefinita, perché consente a quegli account di raggiungere i servizi in esecuzione sul tuo computer e sulla tua rete.",+ lockedByEnvironment:+ "Impostato da UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 in questo server, che rifiuta gli indirizzi privati per tutti gli account.",+ loadError:+ "Impossibile caricare le impostazioni di connessione degli account gestiti.",+ saveError:+ "Impossibile salvare le impostazioni di connessione degli account gestiti.",+ },permissions: {sectionTitle: "Autorizzazioni",bypassLabel: "Autorizzazioni degli strumenti",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex cd692e190a3..25d2c37fd66 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -880,6 +880,16 @@ export const ja = {revoked: "すべてのプレビューリンクを失効させました",revokeError: "プレビューリンクを失効させることができませんでした",},+ managedProviderUrls: {+ sectionTitle: "管理対象アカウント",+ enableLabel: "ローカルおよびネットワーク接続",+ enableDescription:+ "管理対象アカウントが、このコンピューターや LAN 上の Ollama や llama.cpp サーバーなど、ローカルまたはネットワークのアドレスに接続を向けられるようにします。既定ではオフです。オンにすると、これらのアカウントがお使いのコンピューターやネットワークで動作しているサービスに到達できるようになるためです。",+ lockedByEnvironment:+ "このサーバーの UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 によって決まります。すべてのアカウントでプライベートアドレスが拒否されます。",+ loadError: "管理対象アカウントの接続設定を読み込めませんでした。",+ saveError: "管理対象アカウントの接続設定を保存できませんでした。",+ },notifications: {sectionTitle: "通知",showLlamaUpdates: "llama.cpp のアップデート通知",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 66b7c64397c..c0b40d0b020 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -885,6 +885,16 @@ export const ko = {revoked: "모든 미리보기 링크가 취소되었습니다",revokeError: "미리보기 링크를 취소하지 못했습니다",},+ managedProviderUrls: {+ sectionTitle: "관리 계정",+ enableLabel: "로컬 및 네트워크 연결",+ enableDescription:+ "관리 계정이 이 컴퓨터나 LAN의 Ollama 또는 llama.cpp 서버처럼 로컬 또는 네트워크 주소로 연결을 지정할 수 있도록 합니다. 기본적으로 꺼져 있으며, 켜면 해당 계정이 사용자의 컴퓨터와 네트워크에서 실행 중인 서비스에 접근할 수 있기 때문입니다.",+ lockedByEnvironment:+ "이 서버의 UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 설정에 따릅니다. 모든 계정에서 사설 주소가 거부됩니다.",+ loadError: "관리 계정 연결 설정을 불러오지 못했습니다.",+ saveError: "관리 계정 연결 설정을 저장하지 못했습니다.",+ },notifications: {sectionTitle: "알림",showLlamaUpdates: "llama.cpp 업데이트 알림",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 459f669593e..9acb541a101 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -894,6 +894,18 @@ export const ptBR = {revoked: "Todos os links de pré-visualização foram revogados",revokeError: "Não foi possível revogar os links de pré-visualização",},+ managedProviderUrls: {+ sectionTitle: "Contas gerenciadas",+ enableLabel: "Conexões locais e de rede",+ enableDescription:+ "Permite que contas gerenciadas apontem suas conexões para endereços locais ou de rede, como um servidor Ollama ou llama.cpp neste computador ou na sua rede local. Desativado por padrão, porque permite que essas contas alcancem serviços em execução no seu computador e na sua rede.",+ lockedByEnvironment:+ "Definido por UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 neste servidor, que recusa endereços privados para todas as contas.",+ loadError:+ "Não foi possível carregar as configurações de conexão das contas gerenciadas.",+ saveError:+ "Não foi possível salvar as configurações de conexão das contas gerenciadas.",+ },notifications: {sectionTitle: "Notificações",showLlamaUpdates: "Notificações de atualização do llama.cpp",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 911147c8e06..39ace7d6c79 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -891,6 +891,18 @@ export const ru = {revoked: "Все ссылки предпросмотра отозваны",revokeError: "Не удалось отозвать ссылки предпросмотра",},+ managedProviderUrls: {+ sectionTitle: "Управляемые учётные записи",+ enableLabel: "Локальные и сетевые подключения",+ enableDescription:+ "Разрешить управляемым учётным записям указывать в подключениях локальные или сетевые адреса, например сервер Ollama или llama.cpp на этом компьютере или в вашей локальной сети. По умолчанию выключено, так как это открывает таким записям доступ к службам, работающим на вашем компьютере и в вашей сети.",+ lockedByEnvironment:+ "Задано переменной UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 на этом сервере: приватные адреса отклоняются для всех учётных записей.",+ loadError:+ "Не удалось загрузить настройки подключений управляемых учётных записей.",+ saveError:+ "Не удалось сохранить настройки подключений управляемых учётных записей.",+ },notifications: {sectionTitle: "Уведомления",showLlamaUpdates: "Уведомления об обновлениях llama.cpp",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 5251dd1ec4f..c0396e3a039 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -869,6 +869,16 @@ export const zhCN = {revoked: "所有预览链接已撤销",revokeError: "无法撤销预览链接",},+ managedProviderUrls: {+ sectionTitle: "受管账户",+ enableLabel: "本地和网络连接",+ enableDescription:+ "允许受管账户将连接指向本地或网络地址,例如本机或局域网中的 Ollama 或 llama.cpp 服务器。默认关闭,因为开启后这些账户可以访问在你的计算机和网络中运行的服务。",+ lockedByEnvironment:+ "由本服务器上的 UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 决定,该设置会对所有账户拒绝私有地址。",+ loadError: "无法加载受管账户的连接设置。",+ saveError: "无法保存受管账户的连接设置。",+ },notifications: {sectionTitle: "通知",showLlamaUpdates: "llama.cpp 更新通知",