Repository navigation
feat: serve published file previews from the workspace agent over tailnet - #31282
DanielleMaywood wants to merge 1 commit into
Conversation
ibetitsmike
left a comment
There was a problem hiding this comment.
Adversarial security review — stack summary (#31282 → #31287) + agent-server findings
This is the roll-up for the whole stack; each PR also has its own review with PR-local findings. Line numbers refer to the stack head 678b80103 (feat/agents-open-preview-docs).
Method. 8 independent reviewers (one per PR + two whole-stack reviewers with different attacker focus), then 3 independent voters assigned severity, then every finding voted ≥P2 was re-reproduced from scratch by a separate validator against a real coderd + in-process agent + Postgres. Severity = voter majority. P3/nit items below were not independently re-validated and should be read as unverified single-reviewer observations.
S1 — P1 (contested: 2 voters P1, 1 voter + both validators P2) — validated
A prompt-injected model can choose both the content and the moment the dashboard renders it, on the wildcard app domain with the owner's ambient application_connect cookie; the one containment added by the stack (deny preview-- origins in CORS) covers only path mode, only response reads, and only cors_behavior=simple.
Chain (all hops verified):
open_previewresult →site/src/pages/AgentsPage/components/ChatConversation/useChatToolInvalidations.ts:173(effect, no gesture) →AgentChatPageView.tsx:427showSingletonTab("preview")→RightPanel/PreviewPanel.tsx:174<WorkspaceIframe src>→site/src/modules/apps/WorkspaceAppFrame.tsx:166: nosandbox,allow="clipboard-read; clipboard-write",loading="eager". This is the only effect-driven tab activation in the Agents UI; every other activation is anonClick.- The frame runs on
<slug>--<agent>--<ws>--<owner>.<wildcard>and carriescoder_subdomain_app_session_token_<hash>(coderd/workspaceapps/proxy.go:277Domain=.<wildcard suffix>,SameSite=Lax,strictnot selectable —codersdk/deployment.go:3665). That key isapplication_connect-scoped (coderd/workspaceapps.go:103-118), so the blast radius is every owner-level app and port in every workspace of the owner (code-server etc.), not the dashboard API. - Port mode escapes the mitigation.
open_preview(port)(coderd/x/chatd/chattool/openpreview.go:52, the mode the tool description recommends first) yields an ordinary<port>--…origin.WorkspaceAppCors(coderd/httpmw/cors.go:126) only deniespreview--origins and otherwise allows any same-username origin withAllowCredentials: true(cors.go:140). Validator transcript (fresh test, real proxy, two workspaces of the same user):Port-mode "previews" also go through the port-share branch (GET victim--agent--w2--testuser Origin: http://34979--agent--w1--testuser.<wildcard> -> 200 ACAO: http://34979--agent--w1--testuser.<wildcard> ACAC: true GET victim--agent--w2--testuser Origin: http://preview--0123456789abcdef--agent--w1--testuser.<wildcard> -> 200 (no ACAO / ACAC) <- request still delivered to upstreamrequest.go:357-400): with a public share the LLM-authored page is served unauthenticated (validated:303→200afterPOST /workspaces/{w1}/port-share). This contradicts "Previews are always owner-only; port shares do not apply" in #31283. - CORS does not stop requests, only reads. A simple
POST(form content-type) from apreview--…Origincarrying only the subdomain cookie was token-issued and delivered to a sibling app with its body (validator:UPSTREAM RECEIVED: POST /do Origin="https://preview--…" Cookie="" body="action=delete&csrf_case=0").grep Origin|Sec-Fetch|Referer coderd/workspaceapps/*.go→ no request-origin gating anywhere. The #31283 PR body /cors.go:124comment ("cannot make credentialed requests") is therefore inaccurate. cors_behavior=passthruskips the check entirely (proxy.go:406); validated: a reflecting upstream'sACAO: http://preview--…+ACAC: truereach the browser unchanged.- Validator calibration: browser preflights are uncredentialed and
ResolveRequestruns before CORS, so non-simple cross-origin requests fail at the auth redirect; the readable primitive is simpleGET/HEAD/POSTwithcredentials: "include"— still a credentialed cross-workspace read of any GET-able page/file of a sibling app. - Browser-side behaviours (top-navigation after a click in the frame, clipboard write, popups, cookie tossing onto
.<wildcard>) follow from the missingsandboxand are UNVERIFIED (no browser in the harness).
Why it is new vs. main: the unsandboxed app iframe, the domain-wide app cookie and the same-username CORS allowance all pre-exist; on main the model would need to social-engineer a click on a port tab. The stack makes it zero-click, brands the pane "Preview", and ships a mitigation that doesn't cover the recommended mode.
Suggested fixes (split across PRs; details in each PR review): (1) #31286 — do not auto-src a fresh preview; require a click; render previews in a dedicated frame with sandbox="allow-scripts allow-same-origin allow-forms" (no top-nav/popups), no clipboard allow, referrerpolicy="no-referrer"; only mount while visible. (2) #31284/#31283 — make the trust decision follow content provenance, not hostname shape: either drop port mode or give port-mode previews a preview---class origin (e.g. preview--p<port>--…) so appurl.PreviewID covers both modes and forces AppSharingLevelOwner. (3) #31283 — move the preview-origin rule out of WorkspaceAppCors into an unconditional step in determineCORSBehavior (strip ACAO/ACAC for preview origins in passthru too) and consider a hard 403 in HandleSubdomain when Origin parses as a preview host ≠ request host; fix the wording.
S2 — P2 (unanimous) — validated
Anyone who can read the chat and holds application_connect on the workspace — the site owner role by default — renders the victim's LLM-authored page in their own browser with their own app cookie.
-
Catalog is gated on chat
ActionReadonly (coderd/database/dbauthz/dbauthz.go:3739); preview fetch is gated onActionApplicationConnect(coderd/workspaceapps/db.go:370), not onOwnerID == actor. The UI builds the URL fromworkspace.owner_name(the victim) and never compares viewer tochat.owner_id(AgentChatPageView.tsx:408-434,PreviewPanel.tsx:63-77,Tool.tsxOpenPreviewRenderer). -
Validator matrix (fresh end-to-end test, victim = plain member):
principal GET /chats/{id}/previewspreview--<id>--main--<ws>--<victim>/victim 200 200, file body (proxied to agent :5) site owner 200 200, victim's file body org admin 200 (title + absolute path leak) coderd 404 page same-org member / chat-ACL readsharee404 / 200 coderd 404 page unauthenticated — 303 login --disable-owner-workspace-accessfully closes the site-owner path. Viewing another user's chat is a supported flow (isOtherUserReadOnlybanner; Workspaces page "Agent" badge →/agents/<chatId>). -
Impact is the S1 primitive turned against an admin (no confidentiality gain — the site owner already has SSH). Fix: #31286 only build/iframe the URL when the viewer is the chat owner and never auto-open for a non-owner; #31285 defence-in-depth: return
[](or 403) fromgetChatPreviewswhenactor != chat.owner_id; #31283 optionally make preview authz literallyWorkspace.OwnerID == roles.ID.
Verified negatives (so nobody re-spends effort)
- Catalog poisoning is unreachable: no user API writes
role='tool'parts; MCP tools are<server>__<tool>+ taggedmcp_server_config_id; built-inopen_previewshadows dynamic tools;IsPreviewIDis anchored. - Hostname parsing: 104,868-hostname corpus diff vs the pre-PR parser → zero meaning changes;
coder_appslugs can't contain--;0005/00004leading-zero ports still hit the reserved-port 400; signed token bound to slug/agent/prefix; path/terminal access can't reach port 5; traversal variants (..,%2e%2e,//,\,;) all 404 at the agent; Coder cookies stripped before proxying. os.Root+Lstat+SameFileholds against symlink/FIFO/TOCTOU (checked against Go 1.26.9os/root_unix.go);go test -raceclean; lock ordering is cycle-free.- Port 4/5 are reachable by exactly the population that can already use
/api/v0/files(ActionSSH), so publication itself is not an escalation.
#31282-specific findings (agent preview server) — unverified (single reviewer; not independently re-validated)
P3
- fd per path component, no depth cap —
agent/agentpreview/preview.go:241keeps one*os.Rootfd per component untilopenFilereturns. Reviewer test: a 2,000-deep request peaked at ~2,009 fds; atulimit -n 1024unrelatedos.Opencalls in the agent process hitEMFILEduring the request (no leak afterwards). Request line allows ~500k components. Fix: close the parent after verifying the child, cap component count (e.g. 64). open()/Close()holdapi.muwhile waiting onrootMu.Lock()—preview.go:100-127,api.go:45. A pending republish of preview A blocksGETon unrelated preview B (reviewer-tested). Fix: swap the root outsideapi.mu.- No unpublish/TTL; 16-slot cap per agent lifetime (
preview.go:21). 16open_preview(path)calls lock out previews for all chats on that agent until restart; file-mode previews pin the parent dir fd (e.g.$HOME) for the daemon lifetime. - Preview ID is an unsalted
sha256("<isDir>:<canonical>")[:8](preview.go:71) — validated:/home/coder/project/dist→dc5e6154dd7948f4offline and from two independent agent instances. Combined withapplication_connect-only principals (constructible via a premium custom org roleworkspace:{read,application_connect}; validated they are refused at/coordinatebut get200on the publishedindex.html/config.json), the URL is guessable. Voted P3 because that principal already reaches owner-levelcoder_apps (code-server → file read) through the sameauthorizeRequestbranch. Still worth salting per agent process (the catalog storespathso the model can republish).
nit
- Hardlinks inside the published tree are served (reviewer: hardlink to
~/.ssh/id_rsa→ 200). PR text "symlinks, dot paths and FIFOs are never served" should not be read as "links"; a same-UID process couldcpanyway. - Served HTML carries no
Referrer-Policy/CSP;handleOpenreturns raw OS error strings inDetail;WriteTimeout: time.Minuteis absolute (assets slower than 60s truncate); stale catalog after agent restart shows a bare404 page not foundinside the frame.
fdb11aa to
fbfcc95
Compare
ibetitsmike
left a comment
There was a problem hiding this comment.
Follow-up (re-checked at 2c52e96)
Most of the agent-side items from the earlier review are addressed here (one fd at a time in openFile, root swap outside api.mu, Nlink > 1 rejection, cap 64) — thanks.
One item is worth revisiting because it now composes with a new vector: preview IDs are still an unsalted sha256("<isDir>:<canonical>")[:8] (agent/agentpreview/preview.go:80). Besides the earlier guessability point (P3), a stable origin is what lets a service worker registered by an agent-authored page survive daemon restarts and observe the next app-auth handoff on that origin (details on #31283). Salting per agent process — e.g. sha256(processSecret || key)[:8] — makes the origin rotate on restart; the catalog already stores path, so the model can republish and the UI can re-key. If stable URLs are a hard requirement, pair it with worker-src 'none' on preview responses and a single-use, host-bound smuggling payload instead.
fbfcc95 to
f92c4a3
Compare
|
@codex review
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
DanielleMaywood
left a comment
There was a problem hiding this comment.
This review was performed by ai-review, an automated review bot.
1 inline finding.
Coverage
Coverage: 10 of 11 files reviewed, 1 generated; 35 rules.
Candidates: 360 found, 331 outside changed lines, 0 already discussed, 29 evaluated.
Findings: 1 (1 sites, 0 pre-existing sites), 0 over budget, 0 failed.
Model: deepseek/deepseek-v4.1-flash; 28 questions, 25 answered, 3 abstained (truncated 3), 22 cached; 0 uncalibrated findings held back; 4402 input and 7621 output tokens.
9854951 to
cc4d20b
Compare
bc7408d to
57dfcfb
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
Re-review of 57dfcfb. All 8 findings from the previous review are fixed and verified, including random preview IDs and the HFS+ dot-name check. This round adds 2 P3, 2 P4 and 1 Nit: the new request-log reason covers only the last path component, and two of the new behaviors (random IDs across restarts, the .html-only rule) have no test that fails if they regress.
The directory-swap SameFile branch in openFile is still untested and needs explicit acceptance by a human. The two out-of-scope items from the first review (chat and tool-call headers on preview requests for #31283, and the open_preview tool description for #31284) still need a ticket or explicit acceptance by a human.
🤖 This review was automatically generated with Coder Agents.
57dfcfb to
1c0b3d4
Compare
|
Responses to the items in the round 2 review body:
|
|
/coder-agents-review |
There was a problem hiding this comment.
Re-review of 1c0b3d4. All 5 findings from the previous review are fixed and verified, including a symlinked parent directory now logging its reason. This round adds 3 P4 and 1 Nit, all about the reason that reaches the agent's log: one rejection rule still logs "file does not exist", no test checks which error is returned, and publish still discards the cause.
The directory-swap SameFile branch in openFile is still untested and needs explicit acceptance by a human. The two out-of-scope items from the first review (chat and tool-call headers on preview requests for #31283, and the open_preview tool description for #31284) still need a ticket or explicit acceptance by a human.
🤖 This review was automatically generated with Coder Agents.
1c0b3d4 to
6541ef4
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
Re-review of 6541ef4. All 4 findings from the previous review are fixed and verified. This round adds 5 P4 findings: two rejection branches whose errNotServed return no test checks, one name check that still logs "file does not exist", publish error text that lists rules publish never applies, and an untested write deadline.
Rounds 2 to 5 have each fixed the cited branch of the same problem (which reason a refused request logs, and whether a test pins it) and the next round has found a sibling. One pass that lists every return in openServed and openFile, picks its error, and adds an ErrorIs assertion for each would likely close the class.
The directory-swap SameFile branch in openFile is still untested and needs explicit acceptance by a human. The two out-of-scope items from the first review (chat and tool-call headers on preview requests for #31283, and the open_preview tool description for #31284) still need a ticket or explicit acceptance by a human.
🤖 This review was automatically generated with Coder Agents.
6541ef4 to
2d9f1f6
Compare
|
The CRF-52 to CRF-55 fixes are in 2d9f1f6, and CRF-56 is not being changed; each is answered in its thread. @DanielleMaywood accepts the untested
|
|
/coder-agents-review |
There was a problem hiding this comment.
Re-review of 2d9f1f6. CRF-52 to CRF-55 are fixed and verified, and the panel accepts the reasons for not testing the write deadline. This round adds 3 P4 findings, all in the same area as the last four rounds: a file preview's refusal still logs "file does not exist", the errNotServed rewording reverted the earlier fix for a regular-file parent, and the errNameNotServed text omits invalid UTF-8.
This is the third round in a row where the fix covered the cited lines and the next pass found a sibling. One way to close it: make every refusal a value of one unexported type, check it in handleServe with errors.As instead of listing sentinels (a new refusal then cannot become a 500 by omission), and add an ErrorIs/ErrorAs assertion for each return in openServed and openFile.
The directory-swap SameFile branch in openFile is still untested and needs explicit acceptance by a human. The two out-of-scope items from the first review (chat and tool-call headers on preview requests for #31283, and the open_preview tool description for #31284) still need a ticket or explicit acceptance by a human.
🤖 This review was automatically generated with Coder Agents.
2d9f1f6 to
5537640
Compare
|
On the review body:
|
|
/coder-agents-review |
There was a problem hiding this comment.
Re-review of 5537640. The regular-file parent and the invalid UTF-8 message are fixed and verified, and Netero accepts the reason for keeping "file does not exist" for other names in a file preview, since a file preview contains only one name. No in-scope findings remain open.
Three items still need a human decision because the author cannot accept them on the project's behalf: the directory-swap SameFile branch in openFile has no test (it needs a race or a test hook); chat and tool-call headers on preview requests must be stripped by #31283; and the open_preview tool description in #31284 must tell the model to publish a directory or a self-contained file. Each needs a ticket or explicit acceptance.
🤖 This review was automatically generated with Coder Agents.
5537640 to
f85cc0d
Compare
|
@DanielleMaywood accepts the untested directory-swap |
|
/coder-agents-review |
There was a problem hiding this comment.
Re-review of f85cc0d, a rebase onto bf47fc6. The PR diff is identical to 5537640, the six base commits touch none of the packages this PR uses, and the preview tests pass on the new head. No findings.
The three items left for a human decision are settled: the untested directory-swap SameFile branch and the open_preview tool description are accepted without a ticket, and #31283 removes Coder-Chat-Id, Coder-Tool-Call-Id and Coder-Ancestor-Chat-Ids from file-preview requests (coderd/workspaceapps/proxy.go:825-827, FilePreviewDropsChatHeaders in proxy_test.go).
🤖 This review was automatically generated with Coder Agents.
f85cc0d to
8088000
Compare
8088000 to
e59b454
Compare
…lnet
Add the agentpreview package. POST /api/v0/previews publishes an absolute
HTML file or a directory containing index.html and returns its preview ID.
Publishing a path again keeps its ID and serves the path's current
contents. IDs count up from 1 and last until the agent restarts. The agent
API serves each preview under /api/v0/previews/{id}/. Files are opened
through os.Root with per-component Lstat and SameFile checks, so symlinks,
hidden paths and FIFOs are never served.
Add AgentConn.OpenPreview to the workspace SDK.
e59b454 to
02b9591
Compare
The workspace agent can publish an absolute
.htmlfile, or a directory containingindex.html, and serve it from the existing agent API (AgentHTTPAPIServerPort, 4) under/api/v0/previews/{id}/. Publishing returns the path's preview ID, a random eight-hex-digit value; publishing a path again keeps its ID and serves its current contents. AddsAgentConn.OpenPreviewto the workspace SDK.Files are served through
os.Root: each path component isLstated, opened as its own root and compared withSameFile, so symlinks, hard-linked files and FIFOs are never served, nor are names inside a published directory that start with a dot (after any leading format characters such as U+200C, which HFS+ ignores), and a directory swapped mid-request cannot escape the published root. Only the current directory stays open during a lookup, so deep paths use a constant number of handles. Responses areno-storeandnosniff. Publications and their IDs last until the agent restarts, capped at 64. Path previews work on Linux, macOS and Windows. Requested names containing\,:or~are rejected on every platform, because Windows reads them as a path separator, an alternate data stream, or a short name such asHIDDEN~1for.hidden. On Windows the published directory is opened from its parent so it can still be renamed or deleted, and hard links are detected from the open file handle.OpenPreviewreturns the canonical path it serves.Decision log
127.0.0.1:<random port>. Those ports were reachable by every workspace process and inherited numeric port shares, so a public share on a reused port could expose published files. The agent API is only reachable over tailnet and sits in the reserved range belowAgentMinimumListeningPort...,%2e%2e,%2fand backslash variants stay inside/api/v0/previews/{id}/and return 404: neither the proxy nor chi resolves dot segments, so preview requests cannot reach other agent API routes. The chat and tool-call middleware are no-ops without their headers, which coderd drops from preview requests (feat: route preview app hostnames to agent previews #31283), and the preview handler extends its own write deadline per request.application_connecton the workspace.index.htmland there are no listings.rm -rf dist && buildfollowed byopen_previewserves the new tree. Requests that are opening a file hold a read lock, so the old root is not closed under them.os.Rootalone would still serve in-root symlinks such asindex.html -> .env.Stack (proof of concept for the embedded previews RFC, review bottom-up):
coder_apptabs