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: bind the Data Recipe export link to the account that minted it (#11401)
Daniel Han5ac616f73d8c
diff --git a/studio/backend/routes/data_recipe/jobs.py b/studio/backend/routes/data_recipe/jobs.pyindex cef96a3d6ba..ca711280320 100644--- a/studio/backend/routes/data_recipe/jobs.py+++ b/studio/backend/routes/data_recipe/jobs.py@@ -5,7 +5,13 @@from __future__ import annotations-from utils.account_context import current_account+from utils.account_context import (+ OWNER,+ AccountContext,+ bind_account,+ current_account,+ reset_account,+)from core.training.account_jobs import account_event_streamimport copyimport hashlib@@ -31,6 +37,7 @@ from auth.authentication import (from auth.storage import CredentialRotatedfrom fastapi.responses import FileResponse, JSONResponse, StreamingResponsefrom pydantic import ValidationError+from starlette.concurrency import run_in_threadpoolfrom core.data_recipe.export import (ExportFormat,@@ -69,30 +76,67 @@ _DOWNLOAD_LINK_SECRET = secrets.token_bytes(32)def _download_link_payload(- *, job_id: str, export_format: str, artifact_path: str | None, filename: str | None+ *,+ job_id: str,+ export_format: str,+ artifact_path: str | None,+ filename: str | None,+ account_id: str,) -> str:- # Every parameter the export reads, or the holder could swap artifact_path for another run's.- parts = [job_id, export_format, artifact_path or "", filename or ""]- return "\x1f".join(parts)+ # Every parameter the export reads, or the holder could swap artifact_path for another run's,+ # plus the account whose roots it will be read from: recipe roots are derived from the account+ # ContextVar, so the tenant is part of the object this capability names.+ # Length-prefixed, because a bare separator join is not injective: artifact_path "a" with+ # filename "b\x1fc" and artifact_path "a\x1fb" with filename "c" share one payload, so one+ # signature would authorize both.+ parts = [account_id, job_id, export_format, artifact_path or "", filename or ""]+ return "\x1f".join(f"{len(part)}:{part}" for part in parts)def _sign_download_link(**parts: Any) -> str:+ account = current_account()+ account_id = "" if account.is_owner else account.account_idexpires_at = int(time.time()) + _DOWNLOAD_LINK_TTL- payload = f"{_download_link_payload(**parts)}\x1f{expires_at}"+ payload = f"{_download_link_payload(account_id = account_id, **parts)}\x1f{expires_at}"signature = hmac.new(_DOWNLOAD_LINK_SECRET, payload.encode(), hashlib.sha256).hexdigest()- return f"{expires_at}.{signature}"+ return f"{expires_at}.{account_id}.{signature}"-def _download_link_authorizes(token: str, **parts: Any) -> bool:+def _download_link_account(token: str, **parts: Any) -> AccountContext | None:+ """The account this link was minted for, or None once it is invalid or deactivated.++ Same shape as the signed RAG document link: expiry, account id, signature, with an empty+ account id meaning the owner.+ """try:- expires_at, signature = token.rsplit(".", 1)- if int(expires_at) < int(time.time()):- return False+ expires_at, account_id, signature = token.split(".", 2)except ValueError:- return False- payload = f"{_download_link_payload(**parts)}\x1f{expires_at}"+ return None+ if "." in signature:+ return None+ # Compare as bytes: compare_digest on two str raises TypeError for a non-ASCII signature, which+ # a %-encoded query value can carry, and that is a 500 where an invalid token owes a 401. The+ # preview share link guards the same way.+ try:+ provided = signature.encode("ascii")+ except UnicodeEncodeError:+ return None+ payload = f"{_download_link_payload(account_id = account_id, **parts)}\x1f{expires_at}"expected = hmac.new(_DOWNLOAD_LINK_SECRET, payload.encode(), hashlib.sha256).hexdigest()- return hmac.compare_digest(signature, expected)+ if not hmac.compare_digest(provided, expected.encode("ascii")):+ return None+ try:+ if int(expires_at) < int(time.time()):+ return None+ except ValueError:+ return None+ if not account_id:+ return OWNER+ from auth.storage import get_account_by_id++ # None once the account is deactivated or deleted: the link dies with it.+ account = get_account_by_id(account_id)+ return None if account is None or account.is_owner else accountasync def _authorize_dataset_download(@@ -102,18 +146,35 @@ async def _authorize_dataset_download(artifact_path: str | None = Query(default = None),filename: str | None = Query(default = None),token: str | None = Query(default = None),-) -> None:+):"""A signed link for exactly this export, or the ordinary Authorization header for an APIclient. The session bearer is deliberately not read from the query."""- if token and _download_link_authorizes(- token,- job_id = job_id,- export_format = export_format,- artifact_path = artifact_path,- filename = filename,- ):+ # In a threadpool: get_account_by_id is synchronous SQLite under a 5s busy timeout, and this+ # dependency is async, so on the loop a contended auth database would stall every other request.+ # The sibling RAG link gets this for free by being a sync def, which FastAPI offloads itself.+ account = (+ await run_in_threadpool(+ _download_link_account,+ token,+ job_id = job_id,+ export_format = export_format,+ artifact_path = artifact_path,+ filename = filename,+ )+ if token+ else None+ )+ if account is not None:+ # This route has no auth dependency behind the link, so without this bind every read+ # resolves under the owner's recipe root rather than the minter's.+ marker = bind_account(account)+ try:+ yield+ finally:+ reset_account(marker)returnawait subject_for_header_or_query_token(request, None)+ yielddownload_router = APIRouter(dependencies = [Depends(_authorize_dataset_download)])diff --git a/studio/backend/tests/test_data_recipe_download_link_account_binding.py b/studio/backend/tests/test_data_recipe_download_link_account_binding.pynew file mode 100644index 00000000000..c38ff6d8458--- /dev/null+++ b/studio/backend/tests/test_data_recipe_download_link_account_binding.py@@ -0,0 +1,156 @@+# 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 Data Recipe export link must name the account that minted it.++The four sibling signed links in this backend all bind the tenant: preview shares and+the RAG document link carry an account id and re-bind it at redemption, and gallery+images and video use media_link_account plus run_as. This one did not, so a link minted+by a managed account was redeemed with the account ContextVar at its OWNER default.+Every recipe root is derived from that ContextVar, so the artifact_path the link carries+was validated under the minter's root and then resolved under the owner's.+"""++from __future__ import annotations++import asyncio+import time++from utils.account_context import (+ OWNER,+ AccountContext,+ bind_account,+ current_account,+ reset_account,+)++from routes.data_recipe import jobs++ALICE = AccountContext("a1b2c3d4e5f6a7b8", "alice", "user")++PARTS = dict(+ job_id = "job-42",+ export_format = "jsonl",+ artifact_path = "recipe_my_run",+ filename = None,+)+++def _mint_as(account):+ marker = bind_account(account)+ try:+ return jobs._sign_download_link(**PARTS)+ finally:+ reset_account(marker)+++def _redeem(+ token,+ account_lookup = None,+ monkeypatch = None,+):+ """Run the dependency and report the account in force inside the handler's scope."""+ if account_lookup is not None:+ import auth.storage+ monkeypatch.setattr(auth.storage, "get_account_by_id", account_lookup)++ async def drive():+ generator = jobs._authorize_dataset_download(request = None, token = token, **PARTS)+ seen = None+ async for _ in generator:+ seen = current_account()+ break+ await generator.aclose()+ return seen++ return asyncio.run(drive())+++def test_a_managed_account_link_is_redeemed_as_that_account(monkeypatch):+ """The regression: this used to redeem as OWNER, under the owner's recipe root."""+ token = _mint_as(ALICE)+ seen = _redeem(+ token, lambda account_id: ALICE if account_id == ALICE.account_id else None, monkeypatch+ )+ assert seen == ALICE, "the link was redeemed under a different account than it was minted by"+++def test_an_owner_link_is_redeemed_as_the_owner(monkeypatch):+ token = _mint_as(OWNER)+ seen = _redeem(token, lambda account_id: None, monkeypatch)+ assert seen == OWNER+++def test_a_managed_link_dies_with_its_account(monkeypatch):+ """get_account_by_id returning None means deactivated or deleted.++ Asserted on the resolver rather than by driving the dependency with request = None: a bare+ pytest.raises(Exception) there passes on the AttributeError that the None request raises+ before the fallback is ever consulted, which is true of the unpatched tree too.+ """+ token = _mint_as(ALICE)+ import auth.storage++ monkeypatch.setattr(auth.storage, "get_account_by_id", lambda account_id: None)+ assert jobs._download_link_account(token, **PARTS) is None+++def test_one_accounts_link_does_not_verify_for_another(monkeypatch):+ """The account id is inside the signed payload, so it cannot be swapped."""+ token = _mint_as(ALICE)+ expiry, _account_id, signature = token.split(".", 2)+ forged = f"{expiry}.{'f' * 16}.{signature}"+ assert jobs._download_link_account(forged, **PARTS) is None+++def test_the_owner_token_shape_is_not_accepted_for_a_managed_payload():+ """An owner-shaped token must not open a managed account's artifact."""+ owner_token = _mint_as(OWNER)+ expiry, _empty, signature = owner_token.split(".", 2)+ forged = f"{expiry}.{ALICE.account_id}.{signature}"+ assert jobs._download_link_account(forged, **PARTS) is None+++def test_a_tampered_artifact_path_still_fails_the_mac():+ token = _mint_as(OWNER)+ other = dict(PARTS, artifact_path = "recipe_someone_elses_run")+ assert jobs._download_link_account(token, **other) is None+++def test_the_account_lookup_is_offloaded_to_the_threadpool():+ """get_account_by_id is synchronous SQLite under a 5s busy timeout, and the dependency that+ redeems the link is async, so on the loop a contended auth database stalls unrelated requests.+ The sibling RAG link avoids this by being a sync def that FastAPI offloads for us."""+ import inspect++ source = inspect.getsource(jobs._authorize_dataset_download)+ assert "run_in_threadpool(" in source+ assert "_download_link_account(\n" not in source+++def test_a_non_ascii_signature_is_rejected_rather_than_raising():+ """compare_digest on two str raises TypeError for non-ASCII, which would be a 500 on a route+ whose whole job is to answer 401. Both token shapes reach the comparison, because the MAC is+ checked before the expiry is parsed."""+ for token in (f"{int(time.time()) + 60}.acct.ééé", "notanumber.acct.ééé"):+ assert jobs._download_link_account(token, **PARTS) is None+++def test_the_signed_payload_is_injective_across_field_boundaries():+ """A bare separator join lets one signature authorize two different parameter sets: the+ separator is legal inside artifact_path and filename, so the boundary can be moved."""+ shifted_left = jobs._download_link_payload(+ account_id = ALICE.account_id,+ job_id = "j",+ export_format = "jsonl",+ artifact_path = "a",+ filename = "b\x1fc",+ )+ shifted_right = jobs._download_link_payload(+ account_id = ALICE.account_id,+ job_id = "j",+ export_format = "jsonl",+ artifact_path = "a\x1fb",+ filename = "c",+ )+ assert shifted_left != shifted_right