Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Scope file download links and mint them after native save selection
  • Loading branch information
NilayYadav committed Nov 26, 2026
commit 5ad49c816d39adafaa49808b2f663e6fa72f30bd
66 changes: 60 additions & 6 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -39218,13 +39218,56 @@ def _chunks():
return saved


_SANDBOX_DOWNLOAD_SECRET = _secrets.token_bytes(32)
_SANDBOX_DOWNLOAD_TTL = 300


def _sandbox_download_id(session_id: str, filename: str) -> str:
return _hashlib.sha256(json.dumps([session_id, filename]).encode()).hexdigest()


def _sandbox_download_signature(payload: str) -> str:
return _hmac.new(_SANDBOX_DOWNLOAD_SECRET, payload.encode(), _hashlib.sha256).hexdigest()


def _sandbox_download_account(token: str, session_id: str, filename: str):
try:
target, expiration, signature = token.rsplit(".", 2)
payload = f"{target}.{expiration}"
if int(expiration) <= int(time.time()) or not _hmac.compare_digest(
signature.encode(), _sandbox_download_signature(payload).encode()
):
return None
except ValueError:
return None
return media_link_account(target, _sandbox_download_id(session_id, filename))


@router.post("/sandbox-download-link")
async def create_sandbox_download_link(
session_id: str = Query(max_length = 4096),
filename: str = Query(max_length = 4096),
current_subject: str = Depends(get_current_subject),
):
from starlette.concurrency import run_in_threadpool

await run_in_threadpool(_sandbox_regular_file, session_id, filename)
target = media_link_target(_sandbox_download_id(session_id, filename))
payload = f"{target}.{int(time.time()) + _SANDBOX_DOWNLOAD_TTL}"
return JSONResponse(
{"token": f"{payload}.{_sandbox_download_signature(payload)}"},
headers = {"Cache-Control": "no-store"},
)

Comment thread
Lyxot marked this conversation as resolved.
Resolved

@router.api_route("/sandbox/{session_id}/{filename:path}", methods = ["GET", "HEAD"])
async def serve_sandbox_file(
session_id: str,
filename: str,
request: Request,
token: Optional[str] = None,
session: Optional[str] = None,
download_token: Optional[str] = None,
):
"""
Serve a file a tool call created in this chat's sandbox.
Expand All @@ -39234,17 +39277,24 @@ async def serve_sandbox_file(
or image/svg+xml would be same-origin script execution. nosniff plus a
Content-Disposition filename is what makes serving them safe.

Accepts auth via an Authorization header or a query token. Unsloth uses an
authenticated fetch and object URL; query auth remains for older clients.
Accepts authenticated fetches, older query auth, and file-scoped download links.
"""
from starlette.concurrency import run_in_threadpool

# ── Authentication (header or query param) ──────────────────
await _authenticate_header_or_query(request, token)
account = None
if download_token is None:
await _authenticate_header_or_query(request, token)
else:
account = await run_in_threadpool(
_sandbox_download_account, download_token, session or session_id, filename
)
if account is None:
raise HTTPException(status_code = 401, detail = "Invalid or expired download link")

# ── Filename sanitization + path containment ────────────────
import stat as _stat

from starlette.concurrency import run_in_threadpool

safe_filename = os.path.basename(filename)

# Runs in a worker like the listing: resolving the sandbox and opening the file both touch disk.
Expand Down Expand Up @@ -39273,7 +39323,11 @@ def _open_checked() -> "tuple[int, int]":
raise
return handle, info.st_size

handle, size = await run_in_threadpool(_open_checked)
handle, size = (
await run_in_threadpool(_open_checked)
if account is None
else await run_in_threadpool(run_as, account, _open_checked)
)
head_only = getattr(request, "method", "GET").upper() == "HEAD"
if head_only:
# FastAPI adds no HEAD to GET routes; nothing is read since artifacts can be huge.
Expand Down
50 changes: 50 additions & 0 deletions studio/backend/tests/test_sandbox_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,53 @@ def link_refused(src, dst, **kwargs):
)
assert tools.save_sandbox_upload(session, "report.xlsx", [b"upload"])["replaced"] is False
assert (workdir / "report.xlsx").read_bytes() == b"upload"


def test_sandbox_download_link_is_bound_to_the_session_file_and_expiry(tools, monkeypatch):
import json
from types import SimpleNamespace

from routes import inference

session = "legacy/download/thread"
name = "résumé.txt"
tools.save_sandbox_upload(session, name, [b"test"])
monkeypatch.setattr(inference.time, "time", lambda: 1000)
link = asyncio.run(inference.create_sandbox_download_link(session, name, "u"))
assert link.headers["cache-control"] == "no-store"
token = json.loads(link.body)["token"]
assert inference._sandbox_download_account(token, session, "other.txt") is None
assert inference._sandbox_download_account(token, "other-thread", name) is None

async def download():
response = await inference.serve_sandbox_file(
"_", name, SimpleNamespace(method = "GET"), session = session, download_token = token
)
assert response.status_code == 200
assert response.headers["content-length"] == "4"
return b"".join([chunk async for chunk in response.body_iterator])

assert asyncio.run(download()) == b"test"
monkeypatch.setattr(inference.time, "time", lambda: 1000 + inference._SANDBOX_DOWNLOAD_TTL)
assert inference._sandbox_download_account(token, session, name) is None


@pytest.mark.parametrize("token", [None, "older-client-token"])
def test_sandbox_download_keeps_existing_authentication(tools, monkeypatch, token):
from types import SimpleNamespace

from routes import inference

request = SimpleNamespace(method = "HEAD")
tools.save_sandbox_upload("thread-download", "report.txt", [b"test"])
authenticated = []

async def authenticate(actual_request, actual_token):
authenticated.append((actual_request, actual_token))

monkeypatch.setattr(inference, "_authenticate_header_or_query", authenticate)
response = asyncio.run(
inference.serve_sandbox_file("thread-download", "report.txt", request, token = token)
)
assert response.status_code == 200
assert authenticated == [(request, token)]
26 changes: 13 additions & 13 deletions studio/frontend/src/components/assistant-ui/sandbox-download.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
// 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, getAuthToken } from "@/features/auth";
import { authFetch } from "@/features/auth";
import { apiUrl } from "@/lib/api-base";
import { downloadUrlStreaming } from "@/lib/native-files";
import { downloadShortLivedUrl } from "@/lib/native-files";

import { sandboxFilePath, sandboxRoutePrefix } from "./sandbox-files";

// Streamed to disk rather than buffered: artifacts can be gigabytes. The bearer goes in the query.
// Stream directly to disk: artifacts can be gigabytes.
export async function saveSandboxFile(
sessionId: string,
name: string,
saveAs = name,
): Promise<void> {
const path = sandboxFilePath(sessionId, name);
// The URL bearer is never refreshed, so authFetch refreshes first; the HEAD confirms the file.
const probe = await authFetch(apiUrl(path), { method: "HEAD" });
if (!probe.ok) throw new Error(`Download refused (${probe.status})`);
const token = getAuthToken();
const separator = path.includes("?") ? "&" : "?";
// Absolute: the native command rejects a relative URL.
const url = apiUrl(
token ? `${path}${separator}token=${encodeURIComponent(token)}` : path,
);
await downloadUrlStreaming(url, saveAs);
await downloadShortLivedUrl(saveAs, async () => {
Comment thread
Lyxot marked this conversation as resolved.
Resolved
const query = new URLSearchParams({ session_id: sessionId, filename: name });
const response = await authFetch(apiUrl(`/api/inference/sandbox-download-link?${query}`), {
method: "POST",
});
if (!response.ok) throw new Error(`Download refused (${response.status})`);
const { token } = (await response.json()) as { token: string };
const separator = path.includes("?") ? "&" : "?";
return apiUrl(`${path}${separator}download_token=${encodeURIComponent(token)}`);
});
}

/** Relative names in this chat's folder; [] when nothing has been written yet. */
Expand Down
23 changes: 23 additions & 0 deletions studio/frontend/src/lib/native-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,29 @@ export async function downloadUrlStreaming(
return savedFileName;
}

/** Mint a short-lived download URL only once the native save chooser has closed. */
export async function downloadShortLivedUrl(
filename: string,
getUrl: () => Promise<string>,
): Promise<string | undefined> {
if (!isTauri) {
browserUrlDownload(await getUrl(), filename);
return;
}
const { invoke } = await import("@tauri-apps/api/core");
const token = await invoke<string | null>("begin_native_file_save", {
fileName: filename,
});
if (token === null) throw new DownloadCancelledError();
try {
const url = await getUrl();
return await invoke<string>("finish_native_file_save_from_url", { token, url });
} catch (error) {
await invoke<void>("cancel_native_file_save", { token }).catch(() => undefined);
throw error;
}
}

export async function downloadUrl(
url: string,
filename: string,
Expand Down
39 changes: 39 additions & 0 deletions studio/frontend/tests/native-file-save.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,45 @@ test("a streamed URL save reports the basename the dialog wrote", async () => {
assert.equal(await files.downloadUrlStreaming("/clip.mp4", "clip.mp4"), "renamed-clip.mp4");
});

test("a native short-lived URL is minted after the save chooser", async () => {
const calls: string[] = [];
const url = "http://127.0.0.1:8888/api/inference/sandbox/thread/file.csv?download_token=scoped";
const files = loadNativeFiles(true, async (command, args) => {
calls.push(command);
if (command === "begin_native_file_save") {
assert.deepEqual(args, { fileName: "file.csv" });
return "destination";
}
assert.equal(command, "finish_native_file_save_from_url");
assert.deepEqual(args, { token: "destination", url });
return "renamed.csv";
});
const result = await files.downloadShortLivedUrl("file.csv", async () => {
calls.push("mint URL");
return url;
});
assert.deepEqual(calls, [
"begin_native_file_save", "mint URL", "finish_native_file_save_from_url",
]);
assert.equal(result, "renamed.csv");
});

test("a failed link request releases the native save destination", async () => {
const calls: string[] = [];
const files = loadNativeFiles(true, async (command, args) => {
calls.push(command);
if (command === "begin_native_file_save") return "destination";
assert.equal(command, "cancel_native_file_save");
assert.deepEqual(args, { token: "destination" });
});
const failure = new Error("File no longer exists.");
await assert.rejects(
files.downloadShortLivedUrl("file.csv", async () => { throw failure; }),
(error: unknown) => error === failure,
);
assert.deepEqual(calls, ["begin_native_file_save", "cancel_native_file_save"]);
});

test("a native URL save reports the basename the dialog wrote", async (t) => {
t.mock.method(globalThis, "fetch", () =>
Promise.resolve(new Response("wav", { headers: { "content-type": "audio/wav" } })),
Expand Down
1 change: 1 addition & 0 deletions studio/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2620,6 +2620,7 @@ fn main() {
native_file_dialogs::finish_native_file_save,
native_file_dialogs::cancel_native_file_save,
native_file_dialogs::save_native_file_from_url,
native_file_dialogs::finish_native_file_save_from_url,
native_file_dialogs::pick_native_download_directory,
native_file_dialogs::save_native_file_in_directory,
native_file_dialogs::release_native_download_directory,
Expand Down
Loading