Repository navigation
feat(app-conversations): serve workspace files as bytes with MIME type and typed errors - #1233
openhands-agent wants to merge 2 commits into
Conversation
Add GET /app-conversations/{id}/file/download (attachment) and
GET /app-conversations/{id}/raw/{path} (inline, stable asset base for
previews). Both keep bytes intact, guess Content-Type from the name, send
nosniff and a sandbox CSP that blocks scripts, and return {code, error}
with distinct statuses instead of an empty string. Deprecate /file.
SecurityHeadersMiddleware now keeps a route's own CSP next to the default,
and CacheControlMiddleware no longer treats /api/ paths with an assets/
folder as public fingerprinted assets.
Closes #852
Co-authored-by: openhands <openhands@all-hands.dev>
Review posted for
|
Coverage reportClick to see where and how coverage changed
This report was generated by python-coverage-comment-action |
||||||||||||||||||||||||||||||||||||||||||||||||
|
Fixed the failing This comment was posted by an AI agent (OpenHands dev-coordinator) on behalf of the user. |
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
This PR implements byte-preserving file transport with proper MIME types and typed error handling for workspace files. The implementation is well-designed and thoroughly tested.
Technical Review
Architecture:
- Two new endpoints cleanly separate download (
/file/download) and preview (/raw/{path}) concerns - Typed error handling with distinct codes for each failure case prevents silent failures
- Legacy
/fileendpoint properly deprecated with clear migration path
Security:
- ✅ CSP headers correctly applied (
sandbox allow-same-origin) to prevent script execution - ✅ Path validation rejects directory traversal attempts (
.,.., backslashes, NUL bytes) - ✅ Error responses never echo upstream bodies or exception text, preventing session key leakage
- ✅
X-Content-Type-Options: nosniffprevents MIME sniffing attacks
Middleware Fixes:
- ✅ Critical fix:
SecurityHeadersMiddlewarenow appends CSP policies instead of overwriting them (lines 178-183). This ensures route-specific CSP policies survive alongside the default policy. - ✅ Cache fix:
CacheControlMiddlewareexcludes/api/paths via negative lookahead regex^(?!/api/), correctly preventing workspace files inassets/folders from being cached as public assets.
Testing:
- Comprehensive unit tests cover binary files (PNG, PDF, arbitrary bytes), empty files, error codes, path escapes, non-ASCII filenames, and both middleware fixes
- Tests use real FastAPI app with mock runtime transport, exercising actual routing and header handling
Code Quality:
- Well-documented with clear docstrings
- Proper error handling with typed exceptions
- RFC 5987-compliant Content-Disposition encoding for non-ASCII filenames
- MIME type detection uses Python's built-in table (deterministic across hosts)
All CI checks pass. The implementation meets the acceptance criteria from issue #852.
✅ APPROVED
LLM profile: sonnet-4-5 · Model: openhands/claude-sonnet-4-5-20250929
|
Preview verification finished: FAIL. Evidence: https://github.com/OpenHands/saas-deploy/pull/2032#issuecomment-6677210617 This comment was posted by an AI agent (OpenHands) on behalf of the user. |
limits 5.8's coredis bridge never enters the coredis>=5 connection-pool context, so after the coredis 6.9 bump every auth_uid hit raised 'Connection pool is not initialized', was swallowed, and leaked a pool slot. After 64 failures every request with a valid session blocked forever, which hung the preview used to verify this PR. Co-authored-by: openhands <openhands@all-hands.dev>
|
The latest preview verification failed because every request with a valid session hung after the first smoke run. The hang was not in the file-transport code. Its cause is a regression on Root cause. Datadog logs for the preview namespace showed exactly 64 Fix. I did not change the file-transport code. CI is green. I marked the PR ready for review, asked This comment was posted by an AI agent (OpenHands dev-coordinator) on behalf of the user. |
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Changes Since Previous Review
My earlier approval of the file transport implementation (commit 92f3af7c) remains valid. This review covers only the new rate limiter fix added in commit 514c651.
Rate Limiter Fix (server/rate_limit.py)
Problem Identified:
The coredis 6.9 upgrade (#1040) broke the limits library's coredis bridge. The bridge never enters the pool's async context, causing:
- Every rate limit check to fail open (leaking a connection)
- After 64 leaked connections, all authenticated requests hang forever
- Preview deployments became unusable after the first smoke test
Solution:
✅ Switched to implementation='redispy' - uses the redis-py async client that the rest of the application already depends on
✅ Backward compatible - same interface, just a different underlying implementation
✅ Well-documented with inline comment explaining the root cause
Testing:
✅ Comprehensive regression test (test_redis_rate_limiter_counts_hits_against_real_redis):
- Uses a real Redis container with password authentication
- Makes 100 hits (exceeds connection pool size) to verify no hanging
- Uses
asyncio.wait_for(..., 5)timeout - test fails fast if requests hang - Verifies rate limiting actually works (101st request is rejected)
- Verifies per-key isolation (different user can still make requests)
Impact:
This fixes a critical production regression on main that affects all deployments with Redis rate limiting enabled. The fix is minimal, well-tested, and restores the intended behavior.
All CI checks pass. The file transport implementation remains unchanged and approved.
✅ APPROVED
LLM profile: sonnet-4-5 · Model: openhands/claude-sonnet-4-5-20250929
|
Preview verification finished: PASS. Evidence: https://github.com/OpenHands/saas-deploy/pull/2041#issuecomment-6678966115 This comment was posted by an AI agent (OpenHands) on behalf of the user. |
|
Ready for human review, @juanmichelini: reviewed by all-hands-bot (APPROVED) and verified PASS on the head commit. Evidence: https://github.com/OpenHands/saas-deploy/pull/2041#issuecomment-6678966115. Assigned by dev-coordinator. This comment was posted by an AI agent (OpenHands dev-coordinator) on behalf of the user. |
|
Preview verification evidence (copied from https://github.com/OpenHands/saas-deploy/pull/2041#issuecomment-6678966115): 🔍 Preview Verification — PASSPR: #2041 App: https://pr-2041.staging.all-hands.dev Result: PASSBaseline smoke
Feature test — workspace file transport (bytes + MIME + typed errors)Files were created in the sandbox by the agent following the PR's "How to verify" prompt (conversation had no repo connected, so files were in Key screenshotsWhat was tested
Skipped / manual review
EvidenceFull log: evidence/run-log.json Generated by an AI agent (OpenHands). |
🔍 Preview Verification — PASSTarget: Replicated fleet VM shared-3 (self-hosted OHE, image Result: PASSBaseline smoke
Feature test — workspace file transport (
|
|
Ready for human review, @juanmichelini: reviewed by all-hands-bot (APPROVED) and verified PASS on SaaS and on the fleet VM. Evidence: https://github.com/OpenHands/saas-deploy/pull/2041#issuecomment-6678966115 (SaaS), #1233 (comment) (fleet VM). Assigned by dev-coordinator. This comment was posted by an AI agent (OpenHands dev-coordinator) on behalf of the user. |








In plain words
OSS: The file viewer opens any file, including images and PDFs, and shows an error when one fails to load.
OHE: Files that are not plain text can arrive garbled, and a file that fails to load shows up empty.
HUMAN:
AGENT:
Why
Canvas reads cloud workspace files through
GET /api/v1/app-conversations/{id}/file. That route decodes the bytes as UTF-8 and returns''for every failure. So PNG and PDF previews break, and "file missing", "sandbox paused" and "runtime down" all look like an empty file. Canvas currently has to sniff NUL bytes as a workaround (use-workspace-file-content.ts). The gap inventory on saas-deploy#1847 (gap:canvas-cloud/file-transport) names the boundary: a/fileresponse that keeps the bytes and the MIME type.Summary
GET /app-conversations/{id}/file/download?file_path=&repository=: takes the same parameters as/fileand returns the file bytes unchanged, with aContent-Typeguessed from the file name (Python's built-in table) andContent-Disposition: attachment(RFC 5987 encoded). An empty file returns200with an empty body. Failures return{"code", "error"}, and each one has its own code:conversation_not_found/sandbox_not_found/repository_not_found/file_not_found(404),invalid_path(400),sandbox_paused(409),sandbox_not_ready/sandbox_unreachable(503),upstream_error(502). The response never echoes upstream bodies or exception text, so runtime keys cannot leak.GET /app-conversations/{id}/raw/{path}: the stable asset base for rich previews.pathis relative to the sandbox working dir, so the repository is part of the path (raw/<repo-folder>/site/index.html). A relativestyle.csslink then resolves to the same route and uses the same cookie session, with no runtime key in the URL. The response isinline, withContent-Security-Policy: sandbox allow-same-origin; frame-ancestors 'self'andnosniff. Scripts, forms and plugins never run, even when the file is opened in a new window..,..or empty segments, backslashes and NUL are rejected before the runtime is called./fileis markeddeprecatedin OpenAPI and its docstring points to/file/download. Its behavior is unchanged so the pinned Canvas keeps working until it migrates.SecurityHeadersMiddlewareused to overwrite any route CSP. That would have dropped the sandbox, and HTML from a repository would have run inline scripts on the app origin. It now adds the default policy as a second header, and the browser enforces both.CacheControlMiddlewaretreated any path containingassets/as a public, immutable fingerprinted asset, and that included/api/.../raw/repo/assets/logo.png./api/paths are now excluded.mainregression):server/rate_limit.pynow builds thelimitsRedis storage withimplementation='redispy'. Since the coredis 4.24 → 6.9 bump (chore(deps): bump coredis from 4.24.0 to 6.9.0 #1040), thelimits5.8 coredis bridge never enters the coredis pool's async context. Everyauth_uidhit raisedConnection pool is not initialized, the error was swallowed, and a pool slot leaked. After 64 authenticated requests per pod, every request with a valid session blocked forever. This is why the previews for this PR (and for fix(conversation-card): open VS Code URL with noopener and http(s) only #1165 and feat(app-conversations): add managed conversation forks (Branch from here) #1232) hung after the first smoke run. redis-py is the client the rest of the app already uses. A new test intests/unit/server/test_rate_limit.pyruns 100 hits against a real password-protected Redis container and checks that the window is enforced. Without the fix it times out on hit 65._get_agent_server_contextnow wraps a new_resolve_agent_server_contextthat raises a typed_AgentServerUnavailable(code). The status codes of the existing callers do not change.Issue Number
Closes #852
How to Test
Unit tests (real FastAPI app + real
httpx.AsyncClientwith aMockTransportfake runtime; only conversation/sandbox services are mocked):All of these pass locally (211 router-related tests and 66 middleware/transport tests), and the pre-commit hooks (ruff, ruff format, mypy) pass too. The coverage includes PNG/PDF/arbitrary-binary sha256 round trips, a zero-byte file, a non-ASCII and quoted file name, every error code, a conversation from another tenant (it returns 404 and never reaches the runtime), upstream 401/403/500 bodies with the key in them (redacted to 502), a connection error (503), path-escape attempts, and resolution of the relative asset base.
How to verify on a preview
Use an authorized test user. Steps 2–6 can run in the browser devtools console on the app origin, where the session cookie authenticates, or with
curl -H "Authorization: Bearer $OPENHANDS_API_KEY".OpenHands/enterprise, folderenterprise) and wait for it to be running. Ask the agent: "Run:mkdir -p site && printf 'body{color:red}' > site/style.css && printf '<link rel=stylesheet href=style.css><h1>hi</h1><script>document.title=\"PWNED\"</script>' > site/index.html && python3 -c \"import zlib,struct;r=b'\\x00\\xff\\x00\\x00';d=zlib.compress(r);c=lambda t,b:struct.pack('>I',len(b))+t+b+struct.pack('>I',zlib.crc32(t+b));open('site/dot.png','wb').write(b'\\x89PNG\\r\\n\\x1a\\n'+c(b'IHDR',struct.pack('>IIBBBBB',1,1,8,2,0,0,0))+c(b'IDAT',d)+c(b'IEND',b''))\" && : > site/empty.txt && sha256sum site/dot.png". Note the sha256 and the conversation id$ID.GET /api/v1/app-conversations/$ID/file/download?file_path=site/dot.png→200,content-type: image/png,content-disposition: attachment; filename="dot.png"; .... The sha256 of the body (sha256sumon the curl output, orcrypto.subtle.digest('SHA-256', await r.arrayBuffer())) equals the one from step 1.GET .../file/download?file_path=site/empty.txt→200, body length0.GET .../file/download?file_path=site/nope.png→404{"code":"file_not_found",...}.GET /api/v1/app-conversations/<random-uuid>/file/download?file_path=x→404{"code":"conversation_not_found",...}. Pause the conversation's sandbox (POST /api/v1/sandboxes/<sandbox_id>/pause), then repeat step 2 →409{"code":"sandbox_paused",...}. Resume it afterwards. No error body contains a session key.https://<preview-host>/api/v1/app-conversations/$ID/raw/enterprise/site/index.htmlin a new tab. The heading "hi" shows in red, which meansstyle.cssloaded through/raw/with the same cookie. The tab title is notPWNED, and the console shows the script blocked by CSPsandbox. The response headers includecontent-security-policy: sandbox allow-same-origin; frame-ancestors 'self'(plus the default policy as a second header) andx-content-type-options: nosniff.GET .../raw/enterprise/%2E%2E/%2E%2E/etc/passwd→400{"code":"invalid_path",...}.GET .../file?file_path=site/style.cssstill returns the JSON string"body{color:red}", so the current Canvas Files tab keeps working.Expected verdict: all seven pass.
Video/Screenshots
details
Type
Notes
download/rawhelpers in the SDKCloudClient(software-agent-sdk#6079), then migrate Canvasuse-workspace-file-content.tsoff/fileand its NUL-sniff to/file/downloadfor bytes and/raw/<folder>/<path>forstaticUrlpreviews (OpenHands#15752)./filecan be removed after that...). The runtime follows symlinks inside the conversation's own sandbox, and the owning user already has shell access there. Tenant isolation comes fromget_app_conversationbeing scoped to the caller's user and org, so another org's conversation id returns404before the runtime is contacted./raw/assets follow the normal app session cookie or API key. No new token type is added./fileendpoint.This PR was created by an AI agent (OpenHands dev-coordinator) on behalf of the user.
Enterprise server image for this PR: