Repository navigation
feat: serve published HTML previews from the workspace agent - #32438
DanielleMaywood wants to merge 5 commits into
Conversation
|
/coder-agents-review |
There was a problem hiding this comment.
Round 4 reviews e68cd8b. Nine of the ten contested findings are closed after re-checking against the code (replies on each thread), and the colon-redirect test and the narrowed publish comment are verified. One P4 remains open, the wording half of the unpublished-page finding, and there is one new Nit on the junction test's input.
The file JSON key and the FIFO 500 were accepted on their threads without an issue; this needs a human decision: accept each gap or file an issue. The 20s write timeout is recorded as the operator's choice for the experiment.
🤖 This review was automatically generated with Coder Agents.
|
|
||
| // Go reports a Windows junction as a directory with ModeIrregular, not | ||
| // ModeSymlink, and os.Root follows it. | ||
| func TestCheckElementRefusesJunctions(t *testing.T) { |
There was a problem hiding this comment.
Nit [CRF-57] TestCheckElementRefusesJunctions passes fs.ModeDir|fs.ModeIrregular, and its comment says Go reports a junction "as a directory with ModeIrregular", but Go 1.26 does not set ModeDir for a junction. (Bisky)
In $GOROOT/src/os/types_windows.go, mode() sets ModeDir only when !fs.isReparseTagNameSurrogate(), and IO_REPARSE_TAG_MOUNT_POINT is a name surrogate, so a junction gets only ModeIrregular. The test still fails if the ModeIrregular arm is removed, but its input describes a mode Lstat never returns. Pass fs.ModeIrregular and say "as ModeIrregular, not ModeSymlink or ModeDir" in the comment.
🤖
There was a problem hiding this comment.
Fixed in c6e31cc: the test input is now fs.ModeIrregular and the comment says Go reports a Windows junction as ModeIrregular.
There was a problem hiding this comment.
Verified fixed in c6e31cc913: the test passes fs.ModeIrregular alone, and deleting the ModeIrregular case in checkElement fails it.
🤖
e68cd8b to
c6e31cc
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
Round 5 reviews c6e31cc. The junction test fix is verified, and the "Ask the agent" wording is accepted (reply on its thread). One new P3 is inline: serve refusals other than an unpublished ID all return a bare 404, and their cause is logged only at Debug.
The file JSON key and the FIFO 500 from round 4 still have no issue and no recorded human acceptance; this needs a human decision.
🤖 This review was automatically generated with Coder Agents.
| if errors.Is(err, errUnpublished) { | ||
| rw.Header().Set("Content-Type", "text/html; charset=utf-8") | ||
| rw.WriteHeader(http.StatusNotFound) | ||
| if _, err := io.WriteString(rw, unpublishedPage); err != nil && requestLogger != nil { |
There was a problem hiding this comment.
P3 [CRF-58] handleServe answers a symlinked, unreadable, non-regular or mid-rewrite file with the same 404 page not found as a missing one, and the cause is logged only at Debug. (Chopper)
Reproduced: a published directory with locked.css (mode 000), link.css -> real.css, no missing.css, and .env returns the identical 404 body for all four, so a user whose page loads without its stylesheet cannot tell a refused file from a missing one. loggermw.WriteLog (coderd/httpmw/loggermw/logger.go:208) logs status < 500 at Debug, and cli/agent.go runs the agent at Info with a flight recorder that writes Debug lines only after an error is logged, which a 404 never does. Keep the bare 404 for fs.ErrNotExist and errNameNotServed, and write the refusal text (errSymlink, errNotRegular, errChanged, permission denied) in the 404 body, or log those cases at Info or Warn.
🤖
There was a problem hiding this comment.
Declined: you are right that a refused file and a missing one look identical from the browser, and that the agent logs the cause only at Debug. We chose to keep every 404 inside a live preview plain and give the explanatory page only to an unknown preview ID; publishing already names the reason when the published path itself is refused, and the Debug level is the agent's shared request logger, not something this preview route sets.
There was a problem hiding this comment.
Confirmed for the experimental release (operator decision, no ticket): only an unknown preview ID gets the explanatory page, and other 404s inside a live preview stay plain.
|
/coder-agents-review |
There was a problem hiding this comment.
Round 6 reviews c6e31cc, unchanged since round 5. The panel found nothing new, and no finding remains open in the code.
Three gaps were accepted on their threads without an issue; this needs a human decision, accepting each gap or filing an issue:
codersdk/workspacesdk/agentconn.go:1516:filestays the permanent JSON key of an agent-to-coderd response.agent/agentpreview/preview.go:262: a FIFO that reuses a swapped file's inode is answered with 500 instead of 404.agent/agentpreview/preview.go:140: refused files (symlink, unreadable, non-regular, mid-rewrite) get the same bare 404 as missing ones, and the cause is logged only at Debug, so it does not reachcoder-agent.logat the default level.
The 20s write timeout on preview responses is recorded as the operator's choice for the experiment.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
Round 7 reviews c6e31cc, unchanged since round 5. One new P4 is inline. The operator decisions recorded on the file key, FIFO 500 and plain-404 threads are noted; no human decision remains open from earlier rounds.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/httpapi/httpapi.go:273: the agent API decodes JSON without checkingContent-Typeand does not check theHostheader. A user on Coder Connect can reachhttp://<agent>.<workspace>.<owner>.coder:4/, so a page on any website could send a CORS-simpletext/plainPOST to/api/v0/processesor/api/v0/write-file, or use DNS rebinding to read responses. Browser reachability of port 4 over Coder Connect and Chrome Private Network Access behavior for tailnet addresses are unverified.agent/agentfiles/files.go:217:read-fileserves an.htmlfile with its extension's MIME type and nonosniffor CSP, so its scripts run on the same origin as the whole agent API. The preview route in this PR serves HTML on that same origin, which adds a second URL for that capability.
🤖 This review was automatically generated with Coder Agents.
| // a file preview's parent is refused. A parent that cannot be resolved, as on | ||
| // some Windows volumes, is used as given, so a missing path fails at os.Stat. | ||
| parent, err := filepath.EvalSymlinks(filepath.Dir(cleaned)) | ||
| if err != nil { |
There was a problem hiding this comment.
P4 [CRF-60] The filepath.EvalSymlinks fallback in publish has no test, so the behavior its comment states ("a parent that cannot be resolved ... is used as given, so a missing path fails at os.Stat") is not pinned. (Mafuuu)
The coverage profile shows block preview.go:69.16,71.3 with count 0, because no test publishes a path whose parent does not exist. If the fallback is removed or changed to return the error, every test still passes, while on the Windows volumes the comment names every publish would fail with the EvalSymlinks error. Add a TestPreviewInvalidPublications row for filepath.Join(root, "missing", "page.html") and assert that the Detail is the os.Stat error for the full path.
🤖
There was a problem hiding this comment.
Declined: the Windows test-go-pg job covers this branch. TestPreviewInvalidPublications failed there with "The system cannot find the path specified" until the fallback was added, because EvalSymlinks fails on the runner's temp volume; reverting the fallback fails it again. Linux never takes this branch, so the Linux coverage profile cannot show it.
There was a problem hiding this comment.
Accepted: the required windows-2022 test-go-pg lane runs ./agent/... on RAM disks (ci.yaml:602-604, ci.yaml:750), where EvalSymlinks fails, so removing the fallback fails a required job.
🤖
|
/coder-agents-review |
There was a problem hiding this comment.
Round 8 reviews c6e31cc, unchanged since round 5. The EvalSymlinks fallback defense is accepted (reply on its thread). One new P4 is inline.
🤖 This review was automatically generated with Coder Agents.
|
|
||
| f, served, err := api.open(appurl.PreviewID(id), name) | ||
| if err != nil { | ||
| if errors.Is(err, errIsDirectory) && name != "" && !strings.HasSuffix(name, "/") { |
There was a problem hiding this comment.
P4 [CRF-63] No test covers the name != "" and !strings.HasSuffix(name, "/") guards on the redirect, and deleting either one leaves go test ./agent/agentpreview/ -count=1 passing. (Bisky)
The guards decide between a 404 and a 301 when index.html was appended. With the suffix guard removed, a directory containing trap/index.html/x requested as /{id}/trap/ gets 301 Location: trap/, which resolves to /{id}/trap/trap/ and then 404s. Add a TestPreviewDirectoryRedirect case for that layout asserting 404 with no Location, or replace both conditions with served == name, which the same case covers.
🤖
There was a problem hiding this comment.
Fixed in c78dfe7: TestPreviewDirectoryRedirect now publishes, then replaces the root index.html and trap/index.html with directories, and asserts / and /trap/ get a 404 with no Location. Removing either the name != "" guard or the trailing-slash guard fails it.
There was a problem hiding this comment.
Verified fixed in c78dfe7350: removing name != "" fails the test on /, and removing the trailing-slash guard fails it on /trap/.
🤖
c6e31cc to
c78dfe7
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
Round 9 reviews c78dfe7. The redirect-guard test is verified: removing either guard fails it. One P4 is inline on the new test comment.
🤖 This review was automatically generated with Coder Agents.
| } | ||
|
|
||
| // A request that already ends in a slash, or names the root, gets no | ||
| // redirect when its index.html is a directory, which would loop. |
There was a problem hiding this comment.
P4 [CRF-65] The new comment says the unguarded redirect "would loop", but without the guards the redirect points one level deeper and that request returns 404. (Gon)
redirectToDirectory builds path.Base(r.URL.EscapedPath()) + "/", and path.Base drops the trailing slash, so the Location repeats the last segment. With both guards removed: path=/trap/ code=301 location="trap/", which resolves to /{id}/trap/trap/ and returns 404. Replace both lines with // Without the guards, the redirect repeats the last segment: /{id}/trap/ goes to /{id}/trap/trap/.
🤖
There was a problem hiding this comment.
Fixed in 5e517bd: you are right, the redirect points one level deeper and that request gets a 404. The comment now says the request gets a 404 because a redirect would point at a path that does not exist.
There was a problem hiding this comment.
Nit [CRF-66] The second sentence is accurate now. The first sentence restates what the loop below already shows (index.html as a directory at / and /trap/, then 404 and no Location), so the comment can be just // A redirect here would point one level deeper, at a path that does not exist. (Gon)
🤖
There was a problem hiding this comment.
Declined: the first sentence says what the setup checks (a 404 when index.html is a directory at / or /trap/), and the second says why no redirect is right, so a reader learns the purpose before the loop.
There was a problem hiding this comment.
Accepted: the first sentence names which guard each request exercises (the root for /, the trailing slash for /trap/), which the path literals do not say.
🤖
The workspace agent publishes an absolute .html file, or a directory
containing index.html, and serves it from its HTTP API under
/api/v0/previews/{id}/ with an ID derived from the cleaned path. Each
request reopens the directory through os.Root and refuses symlinks,
dotfiles and non-regular files. AgentConn.OpenPreview exposes publishing
in the workspace SDK.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
c78dfe7 to
5e517bd
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
Round 10 reviews 5e517bd. The rewritten redirect comment is accurate. One Nit remains on the same comment (reply on its thread); nothing else is open.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
Round 11 reviews 5e517bd. The last open finding, the restating test comment, is closed (reply on its thread), and the panel found nothing new. No in-scope finding is open; the accepted gaps are recorded as operator decisions for the experimental release.
Out of scope, still needing a ticket or explicit acceptance by a human:
agent/agentfiles/files.go:222:read-filestreams whole files under the same 20sWriteTimeoutwith no deadline extension.coderd/httpapi/httpapi.go:273: the agent API decodes JSON without aContent-Typecheck and has noHostcheck, which matters if a browser can reach port 4 over Coder Connect (unverified).agent/agentfiles/files.go:217:read-fileserves.htmlwith nonosniffor CSP on the agent API origin.agent/debuglogs.go:24: the comment copies the server's 20sWriteTimeoutas a literal.
🤖 This review was automatically generated with Coder Agents.
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5e517bdb30
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
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".
| _ = root.Close() | ||
| return nil, err | ||
| } | ||
| if !os.SameFile(opened, named) { |
There was a problem hiding this comment.
Reject symlinks in ancestor directories
When any ancestor of dir is renamed and replaced by a symlink after publication, both os.OpenRoot(dir) and os.Lstat(dir) traverse that ancestor and observe the same target, so this SameFile check succeeds. Subsequent requests can therefore serve files from the symlink target despite the preview's no-symlink guarantee; validate the complete directory path on each open rather than only the final component.
Useful? React with 👍 / 👎.
| return OpenPreviewResponse{}, ErrPreviewsUnsupported | ||
| } | ||
| if res.StatusCode != http.StatusOK { | ||
| return OpenPreviewResponse{}, codersdk.ReadBodyAsError(res) |
There was a problem hiding this comment.
Use the bounded agent error reader
When workspace code impersonates the agent API and returns a non-404 error, codersdk.ReadBodyAsError may consume the full 32 MiB general response limit instead of the established 64 KiB agent-error limit. Repeated OpenPreview calls can consequently create avoidable control-plane memory pressure; use readAgentError(res) like the other agent API methods.
Useful? React with 👍 / 👎.
| // another file on Windows: a backslash is a path separator, a colon names an | ||
| // alternate data stream, and a tilde appears in short names such as HIDDEN~1 | ||
| // for .hidden. | ||
| const windowsUnsafeNameChars = `\:~` |
There was a problem hiding this comment.
Regarding the review-bot comments, if we don't need a test, and os.Root rejects, why is : needed here at all? To me this qualifies for a rejection test, but the cause of the rejection doesn't matter (whether it's this filter or os.Root).
| // directory from its real location, and a later symlink swap of the path or of | ||
| // a file preview's parent is refused. A parent that cannot be resolved, as on | ||
| // some Windows volumes, is used as given, so a missing path fails at os.Stat. | ||
| parent, err := filepath.EvalSymlinks(filepath.Dir(cleaned)) |
There was a problem hiding this comment.
This seems to me like it could be problematic in one scenario: /tmp/foo gets served, /tmp is a symlink. On re-start, /tmp/foo (new symlink) would get served under a different preview hash (new location) so the user gets a new preview tab each attempt?
I'm just starting to read the code, so may be wrong.
|
|
||
| p := preview{path: resolved, dir: resolved} | ||
| if !info.IsDir() { | ||
| if !strings.EqualFold(filepath.Ext(resolved), ".html") { |
There was a problem hiding this comment.
The .htm also exists, although not sure how likely it's to be used (it's considered legacy).
There was a problem hiding this comment.
.htm was originally supported but given its legacy i decided to not include it. I can re-introduce it if you want?
| } | ||
| _ = f.Close() | ||
|
|
||
| id := appurl.NewPreviewID(resolved) |
There was a problem hiding this comment.
I'm a bit vary about re-using the variable resolved throughout the code, especially since we've already defined p. Would it make sense to have p.previewID() instead?
| id := appurl.NewPreviewID(resolved) | ||
| api.mu.Lock() | ||
| defer api.mu.Unlock() | ||
| if existing, ok := api.previews[id]; ok && existing.path != resolved { |
There was a problem hiding this comment.
Similar to above p.previewID() => p.equals(other) or something like that? This centralizes the knowledge about what a matching preview is, rather than exposing the internals in all calling code.
| } | ||
|
|
||
| // redirectToDirectory sends a directory requested without its trailing slash | ||
| // to the slash, so relative links in its index.html resolve inside it. The |
There was a problem hiding this comment.
without its trailing slash to the slash? 😵💫
| if err := checkElement(info.Mode()); err != nil { | ||
| return nil, err | ||
| } | ||
| if api.beforeOpen != nil { |
There was a problem hiding this comment.
Why do we have hooks that can be omitted? Just for unit-testing? We could at least make sure to use a no-op function during construction instead so the conditional isn't needed.
| // that stay inside dir, which could alias a hidden or unpublished file. So | ||
| // openServed refuses a dir that is a symlink, then resolves name one element | ||
| // at a time from the directory opened before it, refusing an element that is | ||
| // a symlink or junction or whose opened file is not the one its Lstat checked. |
There was a problem hiding this comment.
This whole thing kind of confused me, what use-case are we supporting with this?
os.Root already keeps every request, and every symlink or junction it passes through, inside the published path. The extra walk refused symlinks inside it, a published path that is itself a symlink, and a file swapped between its check and its open. Only something running in the workspace can create those, and the agent can read the files directly, so the walk protected little for its cost. Serving now opens the name through os.Root and checks the opened file, so there is no check-then-open race. Names that start with a dot below a published directory are still refused by name. The preview ID is the hash of the cleaned path the agent asked for, so it stays the same when a symlink in that path points somewhere else, and the Windows fallback for unresolvable parents goes with the resolution. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Drop the colon from windowsUnsafeNameChars: os.Root already refuses it on Windows. A directory test row asserts that an alternate data stream name is not served there, whichever layer refuses it. - Reword the redirectToDirectory comment. - Name what makes two publications match: preview.id and preview.samePath. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main conflicted with this PR, which kept GitHub from running its pull_request workflows. The only conflict was in codersdk/workspacesdk/agentconn_test.go, where main and this PR each added a test at the same place; both are kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Windows CI showed that os.Root refuses a junction even when it points inside the published directory: a junction always stores an absolute target, which os.Root reads as leaving the root. The test now expects both junctions to return 404, with a regular file as the control. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Previews are served by the workspace agent because the files the agent writes live in the workspace, and the agent already has an HTTP API that coderd and workspace proxies can reach. Serving from disk on each request makes a file preview a live view: edits show on reload, and coderd stores nothing.
The ID is a hash of the path the agent asked for, so a stored
open_previewresult keeps pointing at the same preview after a republish, an agent restart, or a change to a symlink in that path. The model chooses the path, soos.Rootkeeps every request inside it, and names that start with a dot below it are refused.Implementation details
The workspace agent can publish an absolute
.htmlfile, or a directory containingindex.html, and serve it from its existing HTTP API (port 4) under/api/v0/previews/{id}/. Publishing does not resolve symlinks, so a path under a symlinked directory such as macOS/tmppublishes as given, which the response returns. The preview ID is the first eight hex digits of the SHA-256 of that path, so publishing a path again, even after the agent restarts, returns the same ID. A different path whose ID is already taken gets a 409. AddsAgentConn.OpenPreviewto the workspace SDK, which decodes the ID asappurl.PreviewIDand returnsErrPreviewsUnsupportedwhen the agent predates the route.Each request opens the published directory again through
os.Root, so a directory that is deleted and rebuilt keeps serving without publishing it again. Symlinks and junctions are followed only while they stay inside the published path, only regular files are served, and names that start with a dot below a published directory, such as.gitand.env, are refused. Publishing a directory requiresindex.htmlat its root, and there are no listings. On Windows, names containing\,:or~are refused, because Windows reads them as a path separator, an alternate data stream or a short name such asHIDDEN~1. Responses areno-storeandnosniff.Stack (review bottom-up). Replaces the closed #31282 stack. Security review: coder/security-assessments#437.
🤖 Generated with Claude Code