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
Desktop: block HTTP loopback requests from untrusted images (#8046)
oobabooga0ca37e57adcb
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex cbcf7af8c4d..ad62c59c134 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -13174,8 +13174,8 @@ async def serve_sandbox_file("""Serve image files created by Python tool execution.- Accepts auth via Authorization header OR ?token= query param (needed- because <img src> cannot send custom headers).+ Accepts auth via an Authorization header or a query token. Studio uses an+ authenticated fetch and object URL; query auth remains for older clients."""from fastapi.responses import FileResponsediff --git a/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts b/studio/frontend/src/components/assistant-ui/python-tool-image-path.tsnew file mode 100644index 00000000000..fdf43f1fe6f--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/python-tool-image-path.ts@@ -0,0 +1,9 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export function pythonToolImagePath(+ sessionId: string,+ filename: string,+): string {+ return `/api/inference/sandbox/${encodeURIComponent(sessionId)}/${encodeURIComponent(filename)}`;+}diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsxindex f090eccfc83..db6aff62149 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx@@ -3,28 +3,28 @@"use client";-import { getAuthToken } from "@/features/auth/session";-import { apiUrl } from "@/lib/api-base";+import { Spinner } from "@/components/ui/spinner";+import { authFetch } from "@/features/auth";+import {+ preferFullToolOutput,+ useChatRuntimeStore,+ useToolAwaitingApproval,+ useToolOutputFor,+ useToolPaneScope,+} from "@/features/chat";import type { ToolCallMessagePartComponent } from "@assistant-ui/react";import { useToolArgsStatus } from "@assistant-ui/react";import { CodeIcon } from "lucide-react";-import { Spinner } from "@/components/ui/spinner";-import { memo } from "react";+import { memo, useEffect, useRef, useState } from "react";+import { pythonToolImagePath } from "./python-tool-image-path";+import { CopyBtn, ToolCodeCell } from "./tool-code-cell";import {ToolFallbackContent,ToolFallbackRoot,ToolFallbackTrigger,} from "./tool-fallback";-import { CopyBtn, ToolCodeCell } from "./tool-code-cell";import { ToolLiveOutput } from "./tool-live-output";import { ToolResultOutput } from "./tool-result-output";-import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";-import {- preferFullToolOutput,- useToolAwaitingApproval,- useToolOutputFor,- useToolPaneScope,-} from "@/features/chat";interface StructuredResult {text: string;@@ -42,6 +42,91 @@ function isStructuredResult(val: unknown): val is StructuredResult {);}+function PythonToolImage({+ sessionId,+ filename,+}: {+ sessionId: string;+ filename: string;+}) {+ const imageKey = `${sessionId}\0${filename}`;+ const [image, setImage] = useState<{ key: string; url: string } | null>(null);+ const imageRef = useRef<HTMLImageElement>(null);+ const [nearViewport, setNearViewport] = useState(+ () => typeof IntersectionObserver === "undefined",+ );++ useEffect(() => {+ if (nearViewport) {+ return;+ }+ const element = imageRef.current;+ if (!element) {+ return;+ }++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries.some((entry) => entry.isIntersecting)) {+ setNearViewport(true);+ observer.disconnect();+ }+ },+ { rootMargin: "200px" },+ );+ observer.observe(element);+ return () => observer.disconnect();+ }, [nearViewport]);++ useEffect(() => {+ if (!nearViewport) {+ return;+ }+ const controller = new AbortController();+ let objectUrl: string | null = null;++ const load = async () => {+ const response = await authFetch(+ pythonToolImagePath(sessionId, filename),+ {+ signal: controller.signal,+ },+ );+ if (!response.ok) {+ return;+ }++ const blob = await response.blob();+ if (controller.signal.aborted) {+ return;+ }++ objectUrl = URL.createObjectURL(blob);+ setImage({ key: imageKey, url: objectUrl });+ };+ load().catch(() => {+ // A failed or cancelled image stays as its accessible alt text.+ });++ return () => {+ controller.abort();+ if (objectUrl) {+ URL.revokeObjectURL(objectUrl);+ }+ };+ }, [filename, imageKey, nearViewport, sessionId]);++ return (+ <img+ ref={imageRef}+ src={image?.key === imageKey ? image.url : undefined}+ alt={filename}+ loading="lazy"+ className="max-w-full rounded border border-border"+ />+ );+}+const PythonToolUIImpl: ToolCallMessagePartComponent = ({toolCallId,args,@@ -81,7 +166,6 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({);const displayOutput = preferFullToolOutput(fullOutput, output);- const authToken = getAuthToken();// The gate only opens once the call parsed, so a pending approval means the script is// written even while the args status still reads as streaming.const awaitingApproval = useToolAwaitingApproval(toolCallId);@@ -130,7 +214,9 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({) : displayOutput ? (<div className="mt-2 border-t border-dashed pt-2"><div className="flex items-center justify-between">- <span className="text-xs font-medium text-muted-foreground">output</span>+ <span className="text-xs font-medium text-muted-foreground">+ output+ </span><CopyBtn text={displayOutput} /></div><ToolResultOutput text={displayOutput} />@@ -141,12 +227,10 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({{images.length > 0 && sessionId && (<div className="mt-2 flex flex-col gap-2">{images.map((filename) => (- <img+ <PythonToolImagekey={filename}- src={apiUrl(`/api/inference/sandbox/${encodeURIComponent(sessionId)}/${encodeURIComponent(filename)}${authToken ? `?token=${encodeURIComponent(authToken)}` : ""}`)}- alt={filename}- loading="lazy"- className="max-w-full rounded border border-border"+ sessionId={sessionId}+ filename={filename}/>))}</div>diff --git a/studio/frontend/tests/python-tool-image-path.test.ts b/studio/frontend/tests/python-tool-image-path.test.tsnew file mode 100644index 00000000000..b79c23b7a46--- /dev/null+++ b/studio/frontend/tests/python-tool-image-path.test.ts@@ -0,0 +1,22 @@+// 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 assert from "node:assert/strict";+import test from "node:test";++import { pythonToolImagePath } from "../src/components/assistant-ui/python-tool-image-path.ts";++test("escapes Python tool image path segments", () => {+ assert.equal(+ pythonToolImagePath("session/id", "loss curve #1.png"),+ "/api/inference/sandbox/session%2Fid/loss%20curve%20%231.png",+ );+});++test("keeps authentication out of the Python tool image URL", () => {+ const path = pythonToolImagePath("session", "plot.png");++ assert.equal(path, "/api/inference/sandbox/session/plot.png");+ assert.ok(!path.includes("token"));+ assert.ok(!path.startsWith("http"));+});diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.jsonindex 08e9e3fa2d2..2f9aafbbe7b 100644--- a/studio/src-tauri/tauri.conf.json+++ b/studio/src-tauri/tauri.conf.json@@ -16,7 +16,7 @@"app": {"withGlobalTauri": true,"security": {- "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: blob: https: http://localhost:* http://127.0.0.1:*; media-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src 'self' http://localhost:* http://127.0.0.1:*"+ "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: blob: https:; media-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src 'self' http://localhost:* http://127.0.0.1:*"},"windows": [{diff --git a/tests/studio/playwright_tauri_python_tool_images.py b/tests/studio/playwright_tauri_python_tool_images.pynew file mode 100644index 00000000000..45f87908b35--- /dev/null+++ b/tests/studio/playwright_tauri_python_tool_images.py@@ -0,0 +1,222 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Browser regression for the desktop Python tool image boundary.++Runs as a standalone script. It serves a page with the exact Tauri CSP, then+checks that trusted code can fetch an authenticated sandbox image into a blob+URL while an allowed HTTPS image redirect cannot reach the HTTP Studio backend.+The same policy intentionally continues to allow ordinary HTTPS images,+including HTTPS loopback, which is outside this PR's HTTP-backend boundary.+"""++from __future__ import annotations++import base64+import json+import os+import sys+import threading+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Iterator++from playwright.sync_api import sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import chromium_launch_args # noqa: E402+++REPO = Path(__file__).resolve().parents[2]+TAURI_CONFIG = REPO / "studio/src-tauri/tauri.conf.json"+REDIRECT_URL = "https://redirect.invalid/attacker.png"+HTTPS_LOOPBACK_URL = "https://127.0.0.1:9443/sensitive/direct.png"+SANDBOX_PATH = "/api/inference/sandbox/session%20id/loss%20curve.png"+SENSITIVE_PATH = "/sensitive/redirect.png"+AUTHORIZATION = "Bearer browser-test-token"+PNG = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="+)+++class ProbeState:+ def __init__(self) -> None:+ self.paths: list[str] = []+ self.authorization: str | None = None+++class ProbeServer(ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, handler: type[BaseHTTPRequestHandler], state: ProbeState):+ super().__init__(("127.0.0.1", 0), handler)+ self.state = state+++class TargetHandler(BaseHTTPRequestHandler):+ server: ProbeServer++ def log_message(self, format: str, *args: object) -> None:+ del format, args++ def _cors(self) -> None:+ self.send_header("Access-Control-Allow-Origin", "*")+ self.send_header("Access-Control-Allow-Headers", "Authorization")+ self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")++ def do_OPTIONS(self) -> None:+ self.send_response(204)+ self._cors()+ self.end_headers()++ def do_GET(self) -> None:+ self.server.state.paths.append(self.path)+ if self.path == SANDBOX_PATH:+ self.server.state.authorization = self.headers.get("Authorization")+ self.send_response(200)+ self.send_header("Content-Type", "image/png")+ self.send_header("Content-Length", str(len(PNG)))+ self._cors()+ self.end_headers()+ self.wfile.write(PNG)+ return++ self.send_response(204)+ self.end_headers()+++def page_handler(csp: str, target_origin: str) -> type[BaseHTTPRequestHandler]:+ class PageHandler(BaseHTTPRequestHandler):+ def log_message(self, format: str, *args: object) -> None:+ del format, args++ def do_GET(self) -> None:+ if self.path == "/app.js":+ script = f"""+const image = document.querySelector("#sandbox");+window.sandboxResult = (async () => {{+ const response = await fetch("{target_origin}{SANDBOX_PATH}", {{+ headers: {{ Authorization: "{AUTHORIZATION}" }},+ }});+ if (!response.ok) throw new Error(`sandbox fetch failed: ${{response.status}}`);+ const blob = await response.blob();+ window.sandboxObjectUrl = URL.createObjectURL(blob);+ await new Promise((resolve, reject) => {{+ image.addEventListener("load", resolve, {{ once: true }});+ image.addEventListener("error", reject, {{ once: true }});+ image.src = window.sandboxObjectUrl;+ }});+ return {{ width: image.naturalWidth, height: image.naturalHeight }};+}})();+window.revokeSandbox = () => URL.revokeObjectURL(window.sandboxObjectUrl);+"""+ body = script.encode("utf-8")+ self.send_response(200)+ self.send_header("Content-Type", "text/javascript; charset=utf-8")+ else:+ body = f"""<!doctype html>+<html>+ <body>+ <img id="redirect" src="{REDIRECT_URL}" alt="remote">+ <img id="https-loopback" src="{HTTPS_LOOPBACK_URL}" alt="https loopback">+ <img id="sandbox" alt="loss curve.png">+ <script src="/app.js"></script>+ </body>+</html>+""".encode("utf-8")+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.send_header("Content-Security-Policy", csp)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ return PageHandler+++@contextmanager+def running_server(server: ThreadingHTTPServer) -> Iterator[ThreadingHTTPServer]:+ thread = threading.Thread(target = server.serve_forever, daemon = True)+ thread.start()+ try:+ yield server+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout = 5)+++def main() -> None:+ config = json.loads(TAURI_CONFIG.read_text(encoding = "utf-8"))+ csp = config["app"]["security"]["csp"]+ state = ProbeState()+ target = ProbeServer(TargetHandler, state)+ target_origin = f"http://127.0.0.1:{target.server_port}"+ page_server = ProbeServer(page_handler(csp, target_origin), ProbeState())+ page_origin = f"http://127.0.0.1:{page_server.server_port}"++ with running_server(target), running_server(page_server), sync_playwright() as p:+ launch_options: dict[str, object] = {+ "headless": True,+ "args": chromium_launch_args(),+ }+ channel = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL")+ if channel:+ launch_options["channel"] = channel+ browser = p.chromium.launch(**launch_options)+ try:+ context = browser.new_context()+ redirect_requests = 0+ https_loopback_requests = 0++ def redirect(route) -> None:+ nonlocal redirect_requests+ redirect_requests += 1+ route.fulfill(+ status = 302,+ headers = {"Location": f"{target_origin}{SENSITIVE_PATH}"},+ )++ def https_loopback(route) -> None:+ nonlocal https_loopback_requests+ https_loopback_requests += 1+ route.fulfill(status = 200, content_type = "image/png", body = PNG)++ context.route(REDIRECT_URL, redirect)+ context.route(HTTPS_LOOPBACK_URL, https_loopback)+ page = context.new_page()+ page.goto(page_origin, wait_until = "domcontentloaded")+ dimensions = page.evaluate("window.sandboxResult")+ page.wait_for_timeout(500)++ assert dimensions == {"width": 1, "height": 1}+ assert state.authorization == AUTHORIZATION+ assert SANDBOX_PATH in state.paths+ assert redirect_requests == 1+ assert SENSITIVE_PATH not in state.paths+ assert https_loopback_requests == 1+ assert page.locator("#https-loopback").evaluate(+ "image => image.complete && image.naturalWidth === 1"+ )+ assert page.locator("#sandbox").get_attribute("src").startswith("blob:")++ object_url = page.evaluate("window.sandboxObjectUrl")+ image_loads = """url => new Promise((resolve) => {+ const image = new Image();+ image.addEventListener("load", () => resolve(true), { once: true });+ image.addEventListener("error", () => resolve(false), { once: true });+ image.src = url;+ })"""+ assert page.evaluate(image_loads, object_url)++ page.evaluate("window.revokeSandbox()")+ assert not page.evaluate(image_loads, object_url)+ finally:+ browser.close()++ print("desktop Python tool image browser regression: PASS")+++if __name__ == "__main__":+ main()diff --git a/tests/studio/test_tauri_python_tool_images.py b/tests/studio/test_tauri_python_tool_images.pynew file mode 100644index 00000000000..db62a6075ab--- /dev/null+++ b/tests/studio/test_tauri_python_tool_images.py@@ -0,0 +1,61 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Packaged desktop routing contract for Python tool images."""++import json+from pathlib import Path+++REPO = Path(__file__).resolve().parents[2]+PYTHON_TOOL_UI = REPO / "studio/frontend/src/components/assistant-ui/tool-ui-python.tsx"+TAURI_CONFIG = REPO / "studio/src-tauri/tauri.conf.json"+PLAYWRIGHT_TEST = REPO / "tests/studio/playwright_tauri_python_tool_images.py"+++def test_python_tool_images_use_authenticated_blob_urls() -> None:+ source = PYTHON_TOOL_UI.read_text(encoding = "utf-8")++ assert 'import { authFetch } from "@/features/auth";' in source+ assert "authFetch(" in source+ assert "pythonToolImagePath(sessionId, filename)" in source+ assert "new AbortController()" in source+ assert "new IntersectionObserver(" in source+ assert "URL.createObjectURL(blob)" in source+ assert "URL.revokeObjectURL(objectUrl)" in source+ assert "controller.abort()" in source+ assert "apiUrl(`/api/inference/sandbox/" not in source+++def test_desktop_csp_has_no_explicit_http_loopback_image_source() -> None:+ config = json.loads(TAURI_CONFIG.read_text(encoding = "utf-8"))+ csp = config["app"]["security"]["csp"]+ directives = {+ parts[0]: parts[1:] for directive in csp.split(";") if (parts := directive.strip().split())+ }++ loopback = [+ source for source in directives["img-src"] if "127.0.0.1" in source or "localhost" in source+ ]+ assert loopback == []+ assert "blob:" in directives["img-src"]+ # The boundary is the HTTP Studio backend regression. Ordinary remote+ # HTTPS images remain supported, including HTTPS loopback if its certificate+ # is trusted by the host.+ assert "https:" in directives["img-src"]++ # Trusted frontend fetches and artifact frames still use their existing+ # backend channels. Only ordinary image elements lose loopback access.+ assert "http://127.0.0.1:*" in directives["connect-src"]+ assert "http://127.0.0.1:*" in directives["frame-src"]+++def test_redirect_regression_has_a_real_browser_probe() -> None:+ source = PLAYWRIGHT_TEST.read_text(encoding = "utf-8")++ assert "sync_playwright" in source+ assert "https://redirect.invalid/attacker.png" in source+ assert '"/sensitive/redirect.png"' in source+ assert '"https://127.0.0.1:9443/sensitive/direct.png"' in source+ assert "https_loopback_requests == 1" in source+ assert "URL.createObjectURL" in source