Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(workspace): only the owner may upload, never into the shared workspace
trohitg0bdae5cb224b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1db5abf2..9654d355 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -715,7 +715,9 @@ Node groups (palette categories) are registered in [`server/nodes/groups.py`](./envelope for no gain.- `POST /api/workspace/{workflow_id}/uploads` - Streamed multipart upload (the first in the repo oneither side of the wire). Chunked read with a running total — `Content-Length` is never trusted —- 413 past `MEDIA_MAX_UPLOAD_BYTES`. Returns an `AudioRef`, which `coerce_file_param` accepts.+ 413 past `MEDIA_MAX_UPLOAD_BYTES`. Owner-only, and never falls back to the shared anonymous+ workspace (both refusals are 404). Returns an `AudioRef` for audio (probed) and otherwise a+ `FileRef` whose kind follows `preview_kind`; `coerce_file_param` accepts both.- **The URL carries `workflow_id`; the directory is named by `Workflow.slug`.** The router owns thatlookup because it needs the database, while `services.media` stays synchronous. See[Media Transport](./docs-internal/media_transport.md).diff --git a/client/src/lib/workspaceUpload.ts b/client/src/lib/workspaceUpload.tsindex 01eda1f7..f0a9d2e4 100644--- a/client/src/lib/workspaceUpload.ts+++ b/client/src/lib/workspaceUpload.ts@@ -1,5 +1,6 @@import { buildApiUrl } from '../config/api';import type { AudioRef } from '../components/output/AudioPreview';+import type { WorkspaceFileRef } from '../types/workspaceFiles';/*** Mirrors `MEDIA_MAX_UPLOAD_BYTES` in `server/services/media/limits.py`.@@ -19,12 +20,14 @@ export class UploadError extends Error {}* every connected client, and then dies at Temporal's 2 MiB payload limit,* burning three retries on the way. A ~1.5 MB clip is already ~2 MB of base64.*- * The reference that comes back is ~400 bytes.+ * The reference that comes back is ~400 bytes: an `AudioRef` for audio, whose+ * container the server probed, otherwise a plain file reference whose kind+ * (image, video, document, file) is only a rendering hint.*/export async function uploadToWorkspace(file: File,workflowId: string-): Promise<AudioRef> {+): Promise<AudioRef | WorkspaceFileRef> {if (!workflowId) {throw new UploadError('Save the workflow before uploading a file to it.');}diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex b6a16aa3..c6889330 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -443,7 +443,8 @@ dispatch is what removes the whole class of it.`case 'file'` POSTs to `/api/workspace/{workflow_id}/uploads` via[`lib/workspaceUpload.ts`](../client/src/lib/workspaceUpload.ts) and stores the-returned `AudioRef` (~400 bytes). Do **not** set `Content-Type` on that fetch —+returned reference (~400 bytes: an `AudioRef` for audio, otherwise a file+reference). Do **not** set `Content-Type` on that fetch —the browser must set it so the multipart boundary is generated.The legacy base64 envelope (`{type: 'upload', data: '<base64>'}`) survives onlydiff --git a/docs-internal/media_transport.md b/docs-internal/media_transport.mdindex d0d6b273..00d711c1 100644--- a/docs-internal/media_transport.md+++ b/docs-internal/media_transport.md@@ -242,7 +242,17 @@ The first multipart endpoint in the repo, on either side of the wire.never trust `Content-Length`, which is attacker-controlled. The cap isenforced on bytes **actually read**, so an oversize body aborts before it hasall arrived.-- Returns a serialized `AudioRef`, which `coerce_file_param` already accepts.+- A write, so stricter than the file route: only the workflow's owner may+ upload (the saved graph's `owner_id` against the caller the auth middleware+ resolved), and an id that does not resolve is a 404 rather than a write into+ the shared anonymous workspace (`resolve_workspace_root(...,+ allow_default=False)`). Both refusals are 404, like the file route's.+- Audio comes back as a serialized `AudioRef` (`write_audio` probes the+ container). Anything else comes back as a `FileRef` from `write_media`,+ whose kind follows `preview_kind`: `image`, `video`, `document` for a PDF,+ otherwise `file`, so script-bearing types such as SVG and HTML are plain+ files. The media type comes from the stored filename, the same signal the+ file route serves by. `coerce_file_param` accepts both.### Authdiff --git a/server/routers/workspace.py b/server/routers/workspace.pyindex 0f527877..1aa59152 100644--- a/server/routers/workspace.py+++ b/server/routers/workspace.py@@ -18,6 +18,10 @@ Containment is delegated to ``resolve_within``, which rejects ``..`` / ``~``/ drive-prefixed input before touching the filesystem and re-checkscontainment after resolution so a symlink or Windows junction cannotredirect the result outside the root.++An upload is a write, so it is stricter than the file route: only the+workflow's owner may upload, and an id that does not resolve is a 404 rather+than a write into the shared anonymous workspace."""from __future__ import annotations@@ -26,16 +30,18 @@ import hashlibimport mimetypesfrom pathlib import Pathfrom types import SimpleNamespace+from typing import Any, Union-from fastapi import APIRouter, Depends, File, HTTPException, Path as PathParam, UploadFile+from fastapi import APIRouter, Depends, File, HTTPException, Path as PathParam, Request, UploadFilefrom fastapi.responses import FileResponsefrom core.container import containerfrom core.database import Databasefrom core.logging import get_loggerfrom services.media import MEDIA_MAX_UPLOAD_BYTES, AudioRef, write_audio-from services.media.preview import serves_inline-from services.media.workspace import UPLOAD_SUBDIR+from services.media.preview import preview_kind, serves_inline+from services.media.refs import FileRef+from services.media.workspace import UPLOAD_SUBDIR, write_medialogger = get_logger(__name__)@@ -54,15 +60,61 @@ async def _workspace_root(workflow_id: str, database: Database) -> Path:"""Resolve a workflow id to its on-disk workspace directory.Delegates to :mod:`services.workspace_locator`, which owns the id->slug- translation for every consumer. Both routes here are reads, so the- ``"default"`` fallback (the anonymous workspace a one-off run without a- saved row writes into) stays enabled.+ translation for every consumer. Only the file route uses this: it is a+ read, so the ``"default"`` fallback (the anonymous workspace a one-off run+ without a saved row writes into) stays enabled. Uploads go through+ :func:`_writable_workspace_root`."""from services.workspace_locator import resolve_workspace_rootreturn await resolve_workspace_root(workflow_id, database)+def _owner_of(saved: Any) -> str:+ """The workflow's owner from its saved graph, or "" when none is recorded."""+ data = getattr(saved, "data", None)+ if data is None and isinstance(saved, dict):+ data = saved.get("data", saved)+ return str(data.get("owner_id") or "") if isinstance(data, dict) else ""+++async def _writable_workspace_root(workflow_id: str, request: Request, database: Database) -> Path:+ """Resolve the workspace an upload writes into, or 404.++ Unlike reads, a write never falls back to the shared anonymous workspace:+ an id that does not resolve (a stale tab, a deleted workflow) would+ otherwise drop the file into a different context than the caller+ believes. And only the workflow's owner may write into it. Both answer+ 404, like the read route, so a refusal does not confirm what exists.+ """+ from constants import OWNER_PRINCIPAL_ID+ from services.plugin import NodeUserError+ from services.workspace_locator import resolve_workspace_root++ owner = _owner_of(await database.get_workflow(workflow_id))+ principal = str(getattr(request.state, "user_id", None) or OWNER_PRINCIPAL_ID)+ if owner and owner != principal:+ raise HTTPException(status_code=404, detail="Not found")+ try:+ return await resolve_workspace_root(workflow_id, database, allow_default=False)+ except NodeUserError:+ raise HTTPException(status_code=404, detail="Not found")+++def _upload_mime(name: str, declared: str | None) -> str:+ """The upload's media type, from its stored name first.++ The serve route decides how a file is displayed from its name, so the+ reference reports the same type; the client's declared type only fills+ in for an unknown extension.+ """+ guessed = mimetypes.guess_type(name)[0]+ if guessed:+ return guessed+ declared = (declared or "").split(";", 1)[0].strip().lower()+ return declared or "application/octet-stream"++def _resolve(root: Path, rel_path: str) -> Path:"""Contain ``rel_path`` under ``root`` or 404.@@ -115,10 +167,11 @@ async def serve_workspace_file(@router.post("/{workflow_id}/uploads")async def upload_workspace_file(+ request: Request,workflow_id: str = PathParam(..., min_length=1, max_length=128),file: UploadFile = File(...),database: Database = Depends(_db),-) -> AudioRef:+) -> Union[AudioRef, FileRef]:"""Accept a file into the workflow's workspace and return a reference.Read in bounded chunks with a running total rather than@@ -127,11 +180,12 @@ async def upload_workspace_file(read. Exceeding the cap aborts immediately, before the whole body hasbeen received.- Returns an ``AudioRef`` — the shape ``coerce_file_param`` already- documents as "what the upload route now returns", so the file parameter- on a node accepts it with no further plumbing.+ Audio comes back as an ``AudioRef``, its container probed; anything else+ as a ``FileRef`` whose kind is only a rendering hint (image, video, a PDF+ as a document, otherwise file). ``coerce_file_param`` accepts both, so+ the file parameter on a node takes either with no further plumbing."""- root = await _workspace_root(workflow_id, database)+ root = await _writable_workspace_root(workflow_id, request, database)digest = hashlib.sha256()chunks: list[bytes] = []@@ -158,21 +212,33 @@ async def upload_workspace_file(payload = b"".join(chunks)name = Path(file.filename or "upload.bin").namestem, _, ext = name.rpartition(".")-- # write_audio owns filename sanitization (Windows reserved device names,- # slugging, a random suffix so nothing collides or overwrites) and the- # atomic write. Reimplementing any of that here would be a second, worse- # copy.- ref = write_audio(- payload,- ctx=SimpleNamespace(- workspace_dir=str(root), node_id="upload", workflow_id=workflow_id- ),- stem=stem or name,- ext=ext or "bin",- mime_type=file.content_type or None,- subdir=UPLOAD_SUBDIR,- )+ mime_type = _upload_mime(name, file.content_type)+ shown_as = preview_kind(mime_type)+ ctx = SimpleNamespace(workspace_dir=str(root), node_id="upload", workflow_id=workflow_id)++ # write_audio / write_media own filename sanitization (Windows reserved+ # device names, slugging, a random suffix so nothing collides or+ # overwrites) and the atomic write. Reimplementing any of that here would+ # be a second, worse copy.+ if shown_as == "audio":+ ref: FileRef = write_audio(+ payload,+ ctx=ctx,+ stem=stem or name,+ ext=ext or "bin",+ mime_type=mime_type,+ subdir=UPLOAD_SUBDIR,+ )+ else:+ ref = write_media(+ payload,+ ctx=ctx,+ stem=stem or name,+ ext=ext or "bin",+ kind={"image": "image", "video": "video", "pdf": "document"}.get(shown_as, "file"),+ mime_type=mime_type,+ subdir=UPLOAD_SUBDIR,+ )logger.info("workspace upload stored",diff --git a/server/tests/routers/test_workspace.py b/server/tests/routers/test_workspace.pyindex 96595794..eb7bffcd 100644--- a/server/tests/routers/test_workspace.py+++ b/server/tests/routers/test_workspace.py@@ -230,6 +230,63 @@ class TestUpload:assert stored.parts[0] == "uploads"assert ".." not in stored.parts+ @pytest.mark.parametrize(+ ("name", "declared", "kind"),+ [+ ("cover.png", "image/png", "image"),+ ("clip.mp4", "video/mp4", "video"),+ ("price list.pdf", "application/pdf", "document"),+ # Script-bearing types are never shown in place, so they are plain files.+ ("vector.svg", "image/svg+xml", "file"),+ ("page.html", "image/png", "file"),+ ("notes.txt", "text/plain", "file"),+ ],+ )+ async def test_non_audio_uploads_are_not_claimed_as_audio(self, client, workspace, name, declared, kind):+ """kind="audio" asserts a probed container; other files say only what they are."""+ async with client as http:+ response = await http.post(+ f"/api/workspace/{WORKFLOW_ID}/uploads",+ files={"file": (name, b"not really media", declared)},+ )++ assert response.status_code == 200+ ref = response.json()+ assert ref["kind"] == kind+ assert "duration_seconds" not in ref++ async def test_an_unknown_workflow_is_404_not_the_shared_workspace(self, workspace, monkeypatch):+ app = FastAPI()+ app.include_router(workspace_router.router)+ database = AsyncMock()+ database.get_workflow.return_value = None+ app.dependency_overrides[workspace_router._db] = lambda: database++ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as http:+ response = await http.post(+ f"/api/workspace/{WORKFLOW_ID}/uploads",+ files={"file": ("clip.wav", _wav(), "audio/wav")},+ )++ assert response.status_code == 404+ assert not (workspace.parent / "default").exists()++ @pytest.mark.parametrize(("owner", "status"), [("someone-else", 404), ("owner", 200), ("", 200)])+ async def test_only_the_owner_may_upload(self, workspace, owner, status):+ app = FastAPI()+ app.include_router(workspace_router.router)+ database = AsyncMock()+ database.get_workflow.return_value = SimpleNamespace(slug=SLUG, data={"owner_id": owner})+ app.dependency_overrides[workspace_router._db] = lambda: database++ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as http:+ response = await http.post(+ f"/api/workspace/{WORKFLOW_ID}/uploads",+ files={"file": ("clip.wav", _wav(), "audio/wav")},+ )++ assert response.status_code == status+class TestInlineDispositionHasOneDefinition:"""The route and the gallery listing must agree on what renders inline.