Repository navigation
feat: serve published HTML previews from the workspace agent - #32438
DanielleMaywood wants to merge 1 commit into
Conversation
|
Chat: Review posted | View chat Review history
deep-review v0.13.1 | Round 10 | Last posted: Round 10, 43 findings (13 P3, 23 P4, 7 Nit), COMMENT. Review Finding inventoryFinding inventory: PR #32438Findings
Law analysisR3: effective +1190 at head d156c13. Verdict: Don't split. Enforcement: Advisory. One reviewable idea (agent publish/serve); no valid vertical slice; horizontal cuts produce caller-less types or move about 35 lines. Contested and acknowledgedCRF-8 (P3, agent/agentpreview/preview.go:59) - index.html required at publish only
CRF-10 (P3 -> P4, codersdk/workspacesdk/agentconn.go:119) - open vs publish naming
CRF-11 (Nit, codersdk/workspacesdk/agentconn.go:1516) - File bool / json "file"
CRF-12 (P4, coderd/workspaceapps/appurl/preview.go:22) - ID length literals
CRF-14 (Nit, coderd/workspaceapps/appurl/preview.go:18) - NewPreviewID doc duplication
CRF-17 (Nit, agent/agentpreview/preview.go:59) - variable
|
| Reviewer | Focus |
|---|---|
| Bisky | tests |
| Chopper | ops/errors |
| Churn-guard | change verification |
| Ging | language modernization |
| Gon | naming |
| Hisoka | edge cases |
| Killua | perf |
| Kite | change integrity |
| Knov | contracts |
| Knuckle | SQL |
| Komugi | flake/determinism |
| Kurapika | security |
| Law | decomposition |
| Leorio | docs |
| Luffy | product |
| Mafu-san | process |
| Mafuuu | contracts |
| Melody | dispatch/pairing |
| Meruem | structural |
| Nami | frontend |
| Netero | mechanical checks |
| Pariston | premise testing |
| Pen-botter | product gaps |
| Razor | verification |
| Robin | duplication |
| Ryosuke | Go arch |
| Takumi | concurrency |
| Zoro | shape |
🤖 Managed by Coder Agents.
There was a problem hiding this comment.
This PR adds an agent route that publishes an .html file or a directory and serves it under /api/v0/previews/{id}/, plus AgentConn.OpenPreview. 12 P3, 10 P4 and 5 Nit findings are inline. The P3s that change behavior are in path containment (a symlinked published directory, the Lstat-then-open gap, Windows junctions), the missing trailing-slash redirect, and republishing a path whose type changed.
The PR description says the /debug/logs write deadline "is now one extendWriteDeadline middleware that wraps both routes". The diff does not contain that middleware; see the inline comment on preview.go:100.
Out of scope (needs a ticket or explicit acceptance by a human):
agent/debuglogs.go:24: the comment writes the server's20s WriteTimeoutas a literal copy ofagent/agent.go:1910, so changing the server timeout leaves the comment wrong.
Notes:
coderd/workspaceapps/appurl/preview.go:20: a preview ID is the truncated SHA-256 of a path, so anyone who knows the path can compute the ID. #32439 and #32522 must authorize preview access by workspace and user, not by possession of the ID.coderd/workspaceapps/appurl/preview.go:20: the same path in two workspaces gets the same ID. An origin, cookie scope or cache key built from the ID must also include the workspace or agent.agent/agentpreview/preview.go:131: the dot-prefix rule is the only content filter, so a directory preview serves files such asterraform.tfstateorsecrets.yaml. Port 4 callers can already read these through/read-file; HTML in a browser-hosted preview (#32439) can fetch them from its own origin.codersdk/workspacesdk/agentconn_test.go:445:TestAgentConnOpenPreviewOnOutdatedAgentserves a barehttp.ServeMux. It matches today's old-agent 404 from theagentfilesrouter at/api/v0, but a future catch-all route under/api/v0would break theErrPreviewsUnsupportedmapping without a test failing.agent/agentpreview/preview.go:87: the name is cut from the fullr.URL.Pathat the first/{id}/, which assumes no mount-prefix segment equals an ID.url.PathUnescape(chi.URLParam(r, "*"))does not depend on the prefix.agent/agentpreview/preview.go:89:appurl.PreviewID(id)converts an unvalidated URL segment, so the type does not guarantee the formatUnmarshalTextchecks. It is only a map key here.agent/agentpreview/preview_windows_test.go:37:TestPreviewRejectsShortNamesskips on volumes without 8.3 short names. Whether the Windows CI job runs or skips it is unverified.
🤖 This review was automatically generated with Coder Agents.
| defer f.Close() | ||
|
|
||
| // Serving a large file can outlast the agent server's 20s WriteTimeout. | ||
| if err := http.NewResponseController(rw).SetWriteDeadline(time.Now().Add(5 * time.Minute)); err != nil { |
There was a problem hiding this comment.
P3 [CRF-1] The PR description says the /debug/logs write deadline is now one extendWriteDeadline middleware wrapping both routes, but the diff adds no middleware and copies the deadline call into handleServe. (Netero)
grep -rn extendWriteDeadline agent returns nothing, and agent/debuglogs.go:63 still calls SetWriteDeadline itself with debugLogsWriteTimeout. Here the same 5-minute value is a second, unnamed literal, so changing one leaves the other. Add the middleware the description describes, or remove that paragraph and give the preview deadline a named constant.
🤖
| } | ||
|
|
||
| first, err := p.servedName("") | ||
| if err != nil { |
There was a problem hiding this comment.
P4 [CRF-2] The error branch after p.servedName("") in publish cannot run. (Netero)
For a file preview servedName returns p.file, nil before any check, and for a directory "" becomes index.html, which passes every check. The coverage profile shows this block with count 0. Use the known name (p.file, or index.html when it is empty) instead of the call, or drop the error check.
🤖
| // os.Root follows symlinks that stay inside dir, which could alias a hidden | ||
| // or unpublished file. | ||
| func openServed(dir, name string) (*os.File, error) { | ||
| root, err := os.OpenRoot(dir) |
There was a problem hiding this comment.
P3 [CRF-3] openServed calls os.OpenRoot(p.dir) without checking that p.dir is not a symlink, so a published directory replaced by a symlink serves the target's whole tree. (Kurapika, Pariston)
Reproduced: publish parent/dist, replace dist with a symlink to parent/home, and GET /{id}/project/terraform.tfstate returns 200 with that file. Publishing a path that is already a symlinked directory also returns 200, while a symlinked .html file returns 400, so the description's "no path element may be a symlink" holds only for files. agentfiles.openRootDir (agent/agentfiles/files.go:151) already refuses this by comparing r.Stat(".") with os.Lstat(root) through os.SameFile; do the same here and add the swap case to TestPreviewRebuiltDirectory.
🤖
|
|
||
| // O_NONBLOCK keeps a FIFO that replaced the file after the Lstat above | ||
| // from blocking the open. | ||
| return root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK, 0) |
There was a problem hiding this comment.
P3 [CRF-4] The Lstat walk and root.OpenFile resolve name separately, and os.Root follows in-root symlinks, so a path element swapped for a symlink between the two calls opens a file the walk would refuse. (Meruem, Kurapika, Melody, Pariston)
For example, if assets becomes a symlink to .git after the walk, /{id}/assets/config serves .git/config. The O_NONBLOCK comment already assumes the file can change after the Lstat, but only the FIFO case is handled. After OpenFile, call f.Stat() and return errNotServed unless os.SameFile(info, opened) and opened.Mode().IsRegular(); that one check covers a swapped final element, a swapped intermediate directory, and the FIFO case.
🤖
| if err != nil { | ||
| return nil, err | ||
| } | ||
| if info.Mode()&fs.ModeSymlink != 0 { |
There was a problem hiding this comment.
P3 [CRF-5] On Windows, a directory junction inside the published directory passes the ModeSymlink check, and os.Root follows it into a dot-prefixed or unpublished directory. (Hisoka)
Since Go 1.23, os/types_windows.go sets ModeSymlink only for IO_REPARSE_TAG_SYMLINK; a junction gets ModeDir|ModeIrregular, while os.Root follows any name-surrogate reparse point (isLink in os/root_windows.go:425). So a junction pub -> .git lets GET /{id}/pub/config serve .git/config, and junctions need no admin rights (mklink /J; pnpm creates them under node_modules). This is from reading the Go 1.26 source and was not run on Windows. Reject fs.ModeSymlink|fs.ModeIrregular on every element, and add a Windows test that creates a junction, since TestPreviewSymlinks skips Windows.
🤖
|
|
||
| func (api *API) publish(name string) (workspacesdk.OpenPreviewResponse, error) { | ||
| if !filepath.IsAbs(name) { | ||
| return workspacesdk.OpenPreviewResponse{}, xerrors.New("preview path must be absolute") |
There was a problem hiding this comment.
Nit [CRF-23] preview path must be absolute omits the value the caller sent. (Leorio)
Use xerrors.Errorf("preview path %q must be absolute", name), like the os.Stat errors that include the path.
🤖
| handler := agentpreview.NewAPI().Routes() | ||
| for _, name := range []string{ | ||
| "page.html", | ||
| filepath.Join(root, "missing.html"), |
There was a problem hiding this comment.
P3 [CRF-24] The relative-path row in TestPreviewInvalidPublications passes without the filepath.IsAbs guard. (Bisky)
Every row asserts only 400, and os.Stat("page.html") also returns 400 because the package directory has no page.html. Verified: with the IsAbs block deleted, go test ./agent/agentpreview/ -count=1 passes, and a regression would resolve relative paths against the agent's working directory. Assert the error Detail per row, for example preview path must be absolute here.
🤖
| defer f.Close() | ||
|
|
||
| // Serving a large file can outlast the agent server's 20s WriteTimeout. | ||
| if err := http.NewResponseController(rw).SetWriteDeadline(time.Now().Add(5 * time.Minute)); err != nil { |
There was a problem hiding this comment.
P3 [CRF-25] No test checks that handleServe extends the write deadline, so deleting the call leaves the suite green. (Bisky)
httptest.ResponseRecorder does not implement SetWriteDeadline, and the integration test serves 16 bytes well inside the 20s WriteTimeout. Verified: replacing the call with error(nil) leaves ./agent/agentpreview and TestAgentOpenPreviewIntegration passing; a regression truncates any preview that takes more than 20s to send. agent/agentfiles/uploadchatfile_test.go:423 has a deadlineRecorder; use the same kind of recorder and assert a deadline at least 5 minutes out.
🤖
|
|
||
| "github.com/coder/coder/v2/coderd/workspaceapps/appurl" | ||
| ) | ||
|
|
There was a problem hiding this comment.
P4 [CRF-26] No test pins the output of NewPreviewID, so "the same ID after the agent restarts" is checked only within one process. (Bisky)
TestPreviewIDsAcrossRestarts builds two API values in one process, so a per-process salt or changed digest would still pass while every agent upgrade changes published IDs. Assert that NewPreviewID("/home/coder/page.html") equals its current value.
🤖
| // NewPreviewID returns the ID of the file preview of cleanedPath: the first | ||
| // 8 hex digits of its SHA-256. Publishing a path again, even after the agent | ||
| // restarts, yields the same ID. | ||
| func NewPreviewID(cleanedPath string) PreviewID { |
There was a problem hiding this comment.
P4 [CRF-27] NewPreviewID is the agent's rule for deriving an ID from a filesystem path, but it is exported from a coderd URL package. (Ryosuke)
coderd needs only PreviewID and its format check; only agent/agentpreview and tests call NewPreviewID, including in the stacked PRs. Exporting it from appurl makes the derivation rule part of the shared API. Move NewPreviewID into agentpreview and keep PreviewID and UnmarshalText in appurl.
🤖
There was a problem hiding this comment.
Declined: keeping NewPreviewID beside PreviewID and its format check keeps the ID rules in one file; cheap to move later.
There was a problem hiding this comment.
Accepted: the doc now ties the ID length to the hostname label, which appurl owns, so keeping derivation, length and format check in one file is a reasonable trade.
🤖
3b0e50f to
d156c13
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
Round 2. The new commits change 19 of the 27 round 1 findings, including the symlink, swap, junction, redirect, republish and unknown-ID findings. Eight findings have no code change and no reply, so the panel did not review this round. It will review once each of these has a fix or a reply on its thread: a fix in this PR, a linked issue, or a reason it should not change.
- P3,
agent/agentpreview/preview.go:59: publishing a directory still requiresindex.html, but serving does not require it. The description now calls this a publish rule; the thread has no reply on whether the check should stay. - P3,
codersdk/workspacesdk/agentconn.go:119: the SDK still calls registration "open" (OpenPreview, "Could not open preview.") while the agent calls it "publish", andapi.openis a different operation. - P4,
codersdk/workspacesdk/agentconn.go:1504: theOpenPreviewRequestdoc still says hidden paths are not served, but a published dot file is served. - P4,
coderd/workspaceapps/appurl/preview.go:22: the ID length is still written as two unrelated literals,sum[:4]and{8}. - P4,
coderd/workspaceapps/appurl/preview.go:20:NewPreviewIDis still exported from the coderd URL package although only the agent derives IDs. - Nit,
codersdk/workspacesdk/agentconn.go:1516:File bool/json:"file"is unchanged. - Nit,
coderd/workspaceapps/appurl/preview.go:18: theNewPreviewIDdoc still repeats the republish behavior documented onOpenPreviewRequest. - Nit,
agent/agentpreview/preview.go:59: the variablefirstis unchanged.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
Round 3 reviews d156c13. New findings: 1 P3, 9 P4 and 1 Nit. Re-raised: 1 P3, 2 P4 and 1 Nit. The P3 is that removing the write deadline from handleServe lets the agent's 20s WriteTimeout cut off large preview assets after a 200.
Verified fixed: the description mismatch, the unreachable servedName branch, the symlinked published directory, the Lstat-then-open swap, Windows junctions, the trailing-slash redirect, republishing after a file/directory change, the unknown-ID 404, the UnmarshalText, preview and openServed docs, the four error texts, the relative-path test row and the NewPreviewID golden test. Five defenses were accepted (replies on those threads); index.html, the api.open name, the file JSON key and the ID-length comment are re-raised on their threads.
Out of scope (needs a ticket or explicit acceptance by a human):
agent/agentfiles/files.go:222:read-filecopies whole files under the same 20sWriteTimeoutwith no deadline extension, so a large read over a slow link is truncated after its 200.
Notes:
agent/agentpreview/preview.go:295: refusingModeIrregularalso refuses OneDrive placeholder files (IO_REPARSE_TAG_CLOUD_*), so a preview of a file in a OneDrive-synced folder on a Windows workspace returns "is not a regular file". Inferred from the Go source, not run on Windows.
🤖 This review was automatically generated with Coder Agents.
| } | ||
| defer f.Close() | ||
|
|
||
| http.ServeContent(rw, r, served, time.Time{}, f) |
There was a problem hiding this comment.
P3 [CRF-42] With the 5-minute SetWriteDeadline removed, http.ServeContent runs under the agent server's 20s WriteTimeout (agent/agent.go:1910), so any preview file that takes longer than 20s to send arrives truncated after a 200 with the full Content-Length. (Melody, Hisoka, Meruem, Mafuuu, Ryosuke, Killua, Komugi, Knov)
The round 2 change removed the call that the deadline findings asked to name and test. Reproduced by several reviewers with the real handler behind an http.Server with a short WriteTimeout and a slow reader: for example status=200 content-length=67108864 read=5442688 err=unexpected EOF. A directory preview serves JS bundles, wasm, video and report traces over tailnet and the coderd proxy, so the browser runs a partial script with no error from the agent. Restore the extension with a named constant as agent/agentfiles/bundlefiles.go:63 and agent/debuglogs.go:63 do, and test it with a recorder like deadlineRecorder in agent/agentfiles/uploadchatfile_test.go:423.
🤖
There was a problem hiding this comment.
Declined: the operator chose to serve previews under the agent API server's 20s write timeout for this experiment, since previews are mostly small HTML pages; you are right that a slow download of a large asset is cut off after a 200, and the deadline can be raised if users hit it.
|
|
||
| // Swapping a path element for a symlink while requests run must never serve | ||
| // the symlink's target. | ||
| func TestPreviewSwappedElement(t *testing.T) { |
There was a problem hiding this comment.
P4 [CRF-39] TestPreviewSwappedElement fails only 3 of 20 runs when both os.SameFile checks are removed, so a regression shows up as a flake. (Netero)
With the same mutation, TestOpenServedRefusesSwappedElement fails on every run for both the parent and the last element, because the beforeOpen hook places the swap in the window deterministically. Delete the racing test and its 10000 requests and keep the hook-based one.
🤖
There was a problem hiding this comment.
Declined: removing the SameFile checks is already caught on every run by TestOpenServedRefusesSwappedElement, while this test checks the end-to-end property under real concurrent renames without the hook, and it is what caught the earlier prefix-Lstat design leaking, so its partial detection of that mutation costs nothing.
There was a problem hiding this comment.
Accepted: the test exercises real concurrent renames without the hook at about 0.7s per run.
🤖
| const unpublishedPage = `<!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head><meta charset="utf-8"><title>Preview unavailable</title></head> | ||
| <body><p>This preview is no longer available because the workspace agent restarted. Ask the agent to open it again.</p></body> |
There was a problem hiding this comment.
P4 [CRF-40] The unpublished-preview page says "the workspace agent restarted" for every ID missing from api.previews, and then tells the user to "Ask the agent", where "agent" now means the chat assistant. (Netero, Leorio)
TestPreviewFile requests /ffffffff/, which was never published, and gets this page; so does an ID from another workspace or a mistyped ID. State only what the agent knows, with one meaning of "agent", for example: This preview is not published on this workspace. Previews are forgotten when the workspace agent restarts. Open the file from the chat again to publish it.
🤖
There was a problem hiding this comment.
Declined: preview URLs are only produced by publishing on the agent named in the hostname, so an unknown ID in practice means that agent restarted, and a hand-edited ID is not a case the page needs to explain.
There was a problem hiding this comment.
P4 [CRF-40] The restart claim is accepted: nothing removes a publication, so an unknown ID on the agent that published it means a restart. The second sentence is still open: Ask the agent to open it again. follows a sentence that names the workspace agent, which takes no requests from a person, so the user has to guess that the chat is meant. Change it to Ask the chat to open it again. (Leorio)
🤖
There was a problem hiding this comment.
Declined: the page is shown inside Coder Agents, where the user talks to the agent in the chat, and the first sentence already says workspace agent for the other one, so we are keeping this wording.
There was a problem hiding this comment.
Accepted: inside Coder Agents "the agent" is the chat assistant the user is talking to, and the first sentence already qualifies the workspace agent.
🤖
| // the preview host's, and keeps the request's escaping of the last segment. | ||
| func redirectToDirectory(rw http.ResponseWriter, r *http.Request) { | ||
| location := path.Base(r.URL.EscapedPath()) + "/" | ||
| if strings.Contains(location, ":") { |
There was a problem hiding this comment.
P4 [CRF-41] The ./ prefix branch in redirectToDirectory, for a directory name containing a colon, has no test. (Netero)
The coverage profile shows preview.go:159.37,162.3 with count 0. Without the prefix a browser reads a:b/ as scheme a:, so a regression breaks relative links under that directory. Add a /a:b row expecting ./a:b/ to TestPreviewDirectoryRedirect.
🤖
There was a problem hiding this comment.
Fixed in e68cd8b: TestPreviewDirectoryRedirect now covers a name containing a colon and fails when the colon branch is disabled.
There was a problem hiding this comment.
Verified fixed in e68cd8b865: removing the ./ prefix fails the new /a:b row.
🤖
| } | ||
| _ = f.Close() | ||
|
|
||
| id := appurl.NewPreviewID(resolved) |
There was a problem hiding this comment.
P4 [CRF-44] The commit body says the ID is "derived from the cleaned path" and that each request "refuses symlinks", but publish hashes the path after filepath.EvalSymlinks on its parent and follows a symlinked parent. (Leorio)
On macOS /tmp/x/index.html gets the ID of /private/tmp/x/index.html, so a reader of git log finds the opposite of the behavior. The PR description already states it correctly; bring the commit body in line, for example "an ID derived from the path after resolving symlinks in its parent directories ... refuses symlinks below it".
🤖
There was a problem hiding this comment.
Declined: coder/coder squash-merges with the PR description as the commit message, and the description already says the ID hashes the path after resolving parent symlinks, so this commit body never lands on main.
There was a problem hiding this comment.
Accepted: git log -1 f2b60844c5 shows the squash commit body is the PR description, and this description is correct.
🤖
| // symlinked directory from its real location, where a later swap for a | ||
| // symlink is still 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.
P4 [CRF-46] Replacing the resolved parent with a symlink after publishing is refused for a file preview but followed for a directory preview, although the comment says a later swap "is still refused". (Pariston)
For a file preview p.dir is the resolved parent, so openRoot checks it; for a directory preview p.dir is parent plus base, so only the base is checked and os.OpenRoot follows the swapped parent. Reproduced: publish actual/page.html and actual/site, move actual away and symlink actual -> other; the file preview returns 404, the directory preview returns 200 "other site". Open the root at the resolved parent for both kinds and walk the directory's base as the first element, or narrow the comment to the published directory itself.
🤖
There was a problem hiding this comment.
Fixed in e68cd8b: the publish comment now says a swapped parent is refused for file previews only.
There was a problem hiding this comment.
Verified fixed in e68cd8b865: the comment now claims only the two cases openRoot and lstatElement refuse.
🤖
| return nil, err | ||
| } | ||
| opened, err := f.Stat() | ||
| if err == nil && !os.SameFile(info, opened) { |
There was a problem hiding this comment.
P4 [CRF-47] A regular file replaced by a FIFO between its Lstat and its open is answered with 500 seeker can't seek when the FIFO reuses the file's inode, because os.SameFile then passes. (Bisky)
Reproduced with an internal test whose beforeOpen hook removes data.txt and calls unix.Mkfifo: same inode on 3 of 3 runs, response 500. TestPreviewRejectsFIFOs never reaches the open, so replacing syscall.O_NONBLOCK with 0 leaves the suite green. Add || !opened.Mode().IsRegular() to the check after f.Stat() and keep that test, bounded by testutil.WaitShort, under a unix build tag.
🤖
There was a problem hiding this comment.
Declined: you are right that a FIFO swapped in with a reused inode gets a 500 instead of a 404 and that no test pins O_NONBLOCK, but the swap needs someone who can already write the published directory, O_NONBLOCK keeps the open from hanging, and nothing is read from the FIFO, so we are not adding a platform-specific test file to change the status code.
There was a problem hiding this comment.
Confirmed for the experimental release (operator decision, no ticket): a FIFO swapped in with a reused inode gets a 500 instead of a 404; nothing is read from it and the swap needs write access to the published directory.
| // 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.
P4 [CRF-48] No test on any platform requests a name containing :, so removing it from windowsUnsafeNameChars leaves every test green. (Bisky)
TestPreviewDirectory has Windows rows for ~ and \ but none for the alternate data stream character. Add a Windows row that writes index.html:secret and asserts 404 for /{id}/index.html:secret.
🤖
There was a problem hiding this comment.
Declined: on Windows os.Root already refuses any name containing a colon (filepathlite.IsLocal in rootCleanPath), so the proposed row would pass with or without : in windowsUnsafeNameChars and could not catch the mutation.
There was a problem hiding this comment.
Accepted: rootCleanPath (os/root_windows.go:73) rejects a colon outside a drive letter through filepathlite.IsLocal, so the row could not detect the mutation.
🤖
|
|
||
| // 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.
P4 [CRF-49] TestCheckElementRefusesJunctions passes a hand-built fs.ModeDir|fs.ModeIrregular to checkElement, so nothing shows that Root.Lstat reports a real junction that way. (Bisky, Hisoka)
If a Go release changes how Lstat maps mount points, this test stays green while a junction into .git is served. Creating a junction needs no admin rights: in preview_windows_test.go, run cmd /c mklink /J <root>\assets <root>\.git, publish the root, and assert 404 for /{id}/assets/config.
🤖
There was a problem hiding this comment.
Declined: dropping the ModeIrregular case fails this test, and Go documents that junctions map to ModeIrregular in os/types_windows.go, so a real mklink /J test would guard Go rather than this code.
There was a problem hiding this comment.
Accepted: Go pins the mapping in os/os_windows_test.go:141, and the pre-1.23 mapping (winsymlink=0) reports ModeSymlink, which checkElement also refuses. The test's input mode is a separate Nit on this round.
🤖
| // preview is a published path. A directory preview has file == "" and dir | ||
| // set to the directory; a file preview has dir set to the file's parent. | ||
| type preview struct { | ||
| path string |
There was a problem hiding this comment.
P4 [CRF-51] preview stores the published path three ways (path, dir, file), and only the struct comment keeps them consistent. (Meruem)
path always equals dir for a directory and filepath.Join(dir, file) for a file. A later preview built with only dir and file leaves existing.path empty, and every republish of that ID returns 409 "already used by ". Replace the field with a path() method derived from dir and file.
🤖
There was a problem hiding this comment.
Declined: publish is the only place a preview is built and it sets path from the same resolved value as dir and file, so the 409 described needs a second constructor that does not exist.
There was a problem hiding this comment.
Accepted: publish at preview.go:79 is the only place a preview is built.
🤖
d156c13 to
e68cd8b
Compare
|
/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)
🤖
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 <[email protected]>
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.
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 resolves symlinks in the path's parent directories once, so a path under a symlinked directory such as macOS/tmpserves from its real location, 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. Below the resolved parent, no path element may be a symlink, 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