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
Prev Previous commit
Next Next commit
Verify scoped sandbox downloads and retry a moved path
  • Loading branch information
NilayYadav committed Nov 26, 2026
commit 0259e07a5ee3227b8b6bc9132ee896f953af9abb
21 changes: 13 additions & 8 deletions studio/backend/routes/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -39049,14 +39049,19 @@ def _sandbox_regular_file(session_id: str, filename: str) -> tuple[str, str]:
"""(sandbox_dir, contained path) of a regular (not linked) file in the sandbox, or a 404."""
import stat as _stat

sandbox_dir, path = _contained_sandbox_path(session_id, filename)
try:
entry = os.lstat(path)
except OSError:
raise HTTPException(status_code = 404, detail = "Not found") from None
if not _stat.S_ISREG(entry.st_mode):
raise HTTPException(status_code = 404, detail = "Not found")
return sandbox_dir, path
for _attempt in range(2):
sandbox_dir, path = _contained_sandbox_path(session_id, filename)
try:
entry = os.lstat(path)
except FileNotFoundError:
# The legacy sandbox move can finish between resolution and lstat.
continue
except OSError:
break
if _stat.S_ISREG(entry.st_mode):
return sandbox_dir, path
break
raise HTTPException(status_code = 404, detail = "Not found")


def _unmoved_sandbox_file(root: str, path: str) -> str:
Expand Down
26 changes: 13 additions & 13 deletions studio/backend/tests/test_sandbox_files_and_storage_roots.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ def test_sandbox_listing_route_exists():
sandbox_routes = sorted(r.path for r in router.routes if "sandbox" in r.path)
print(f"\nsandbox routes = {sandbox_routes}")
assert sandbox_routes == [
"/sandbox-download-link",
"/sandbox/{session_id}",
"/sandbox/{session_id}/open",
"/sandbox/{session_id}/reveal",
Expand Down Expand Up @@ -2936,11 +2937,9 @@ def test_a_large_file_is_streamed_rather_than_buffered():
"""Streaming avoids a Blob and an IPC copy of a multi-gigabyte artifact in the renderer."""
view, save = _sandbox_file_save_sources()

assert "downloadUrlStreaming(" in save
assert "downloadShortLivedUrl(saveAs," in save
assert "response.blob()" not in save
assert "response.blob()" not in view
# The streaming path sends no headers, so the bearer travels as a query parameter.
assert "token=" in save


def test_a_same_size_overwrite_is_still_reported(tmp_path, monkeypatch):
Expand Down Expand Up @@ -3364,9 +3363,9 @@ def test_a_native_download_gets_an_absolute_url():
"""Native download rejects relative URLs, so a bare /api path failed before the request."""
_, save = _sandbox_file_save_sources()

url = save[save.index("const url = ") + len("const url = ") :]
assert url.startswith("apiUrl(")
assert url.index("apiUrl(") < url.index("downloadUrlStreaming(url")
assert (
"return apiUrl(`${path}${separator}download_token=${encodeURIComponent(token)}`);" in save
)


def _forget_sandbox_state(tools):
Expand Down Expand Up @@ -5658,16 +5657,17 @@ def test_a_file_outside_the_hash_budget_is_not_reported_as_written(tmp_path, mon
assert "z-report.csv" not in sentinels, sentinels


def test_the_file_download_button_refreshes_the_session_first():
"""The URL carries the bearer, so an expired token would save a 401 body as the file."""
def test_the_file_download_button_requests_an_authenticated_scoped_link():
_, save = _sandbox_file_save_sources()
assert 'authFetch(apiUrl(path), { method: "HEAD" })' in save
assert save.index("authFetch(apiUrl(path)") < save.index("const token = getAuthToken()")
# A refused probe stops the save, rather than streaming the error body to disk.
assert save.index("if (!probe.ok) throw") < save.index("downloadUrlStreaming(")
assert "new URLSearchParams({ session_id: sessionId, filename: name })" in save
request = "authFetch(apiUrl(`/api/inference/sandbox-download-link?${query}`),"
assert save.index("downloadShortLivedUrl(saveAs,") < save.index(request)
assert 'method: "POST"' in save
assert save.index("if (!response.ok) throw") < save.index("await response.json()")
assert "getAuthToken()" not in save


def test_the_download_route_answers_the_probe_the_button_sends(tmp_path, monkeypatch):
def test_the_download_route_still_answers_legacy_head_requests(tmp_path, monkeypatch):
"""The download route must answer HEAD: FastAPI does not add it to a GET route."""
asyncio, inference = _shared_setup_15(monkeypatch, tmp_path)

Expand Down
19 changes: 19 additions & 0 deletions studio/backend/tests/test_sandbox_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,25 @@ async def download():
assert inference._sandbox_download_account(token, session, name) is None


def test_sandbox_download_link_follows_a_concurrent_legacy_move(monkeypatch, tmp_path):
from routes import inference

legacy = tmp_path / "legacy"
legacy.mkdir()
(legacy / "report.txt").write_text("report", encoding = "utf-8")
migrated = tmp_path / "migrated"

def resolve(_session, filename):
if legacy.exists():
legacy.rename(migrated)
return str(legacy), str(legacy / filename)
return str(migrated), str(migrated / filename)

monkeypatch.setattr(inference, "_contained_sandbox_path", resolve)
link = asyncio.run(inference.create_sandbox_download_link("thread", "report.txt", "u"))
assert link.status_code == 200


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