Repository navigation
feat: serve agent previews on strict preview hosts - #32439
DanielleMaywood wants to merge 1 commit into
Conversation
3b5316e to
f0bc2f2
Compare
|
/coder-agents-review |
|
Chat: Review posted | View chat Review history
deep-review v0.13.1 | Round 9 | Last posted: Round 9, 49 findings (2 P1, 1 P2, 15 P3, 17 P4, 14 Nit), APPROVE. Review Finding inventoryFinding inventory: PR #32439Findings
Contested and acknowledgedCRF-7 (Nit, cookie.go:34) - "__Host-" literal duplicates codersdk.cookieHostPrefix
CRF-17 (P3, proxy.go:805) - Chat-header denylist is a hand copy of what agentchat trusts
CRF-18 (P3, db_test.go:785) - Public port share setup is not checked by any assertion
CRF-19 (P3, wsproxy.go:324) - No test for previews served by a workspace proxy
CRF-20 (P4, preview.go:92) - "Back to site" link on in-frame error pages cannot navigate the tab
CRF-21 (P4, previewhost.go:41) - Build Hosting inside NewServer
CRF-25 (P4, request.go:320) - Agent route string is a third copy
CRF-36 (Nit, db.go:478) - Panic text no longer matches the Unwrap-chain condition
CRF-28 (Nit, db.go:162) - "wrapper" and "hop" undefined in comments
CRF-29 (Nit, preview.go:15) - servePreview doc opens by restating the name
CRF-30 (Nit, previewhost.go:33) - sandbox field comment duplicates the Sandbox() doc
CRF-31 (Nit, previewhost.go:97) - URL doc repeats the value of maxHostnameLabelLength
CRF-33 (Nit, proxy.go:805) - removeCoderdAgentHeaders removes only chat headers
CRF-34 (Nit, previewhost.go:132) - responseWriter is called "preview policy writer" elsewhere
CRF-35 (Nit, coderd.go:2269) - One Hosting value has three names
CRF-18 (P4, db_test.go:785) - R5 defense after re-raise
CRF-21 (P4, previewhost.go:41) - R5 defense after re-raise
CRF-25 (P4, request.go:320) - R5 defense after re-raise
CRF-27 (Nit, coderd.go:2267) - R5 defense after re-raise
CRF-28 (Nit, db.go:162) - R5 defense on "hop"
CRF-49 (P3, wsproxy.go:324) - Proxy does not check its own host-prefix flag
CRF-51 (P3, proxy.go:533) - Cause-less "does not serve previews" page
CRF-52 (P3, db.go:165) - Generic 404 for the proxy host-prefix refusal
CRF-53 (P4, preview.go:51) - HTTPS message unreachable on plain-HTTP coderd
CRF-54 (P4, cookie.go:32) - Comment describes #32522's naming rule
CRF-56 (P4, previewhost.go:193) - Hijack doc "its writer"
CRF-57 (Nit, previewhost.go:136) - ApplyPolicy comment
CRF-58 (Nit, previewhost.go:34) - CheckCookieConfig name
CRF-53 (P4, previewhost.go:30) - R6 defense after narrowed re-raise
CRF-61 (Nit, preview.go:143) - isFromOtherPreview doc wording
CRF-60 (Note, previewhost.go:138) - Page-script Domain cookies across the app wildcard
Law analysisRound 1. Effective LOC +1248 -10. Head f0bc2f2. Verdict: Don't split. Enforcement: Advisory. Round logRound 1Netero (1 P1, 2 P3, 3 P4, 1 Nit, 1 Note) and Law (Don't split, advisory). No P0, so panel proceeds. Round 2 updateBLOCKED. Churn guard: 20 addressed in 69ee6a9 (CRF-1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 22, 23, 24, 26, 27, 32), 16 silent (CRF-6, 7, 17, 18, 19, 20, 21, 25, 28, 29, 30, 31, 33, 34, 35, 36). No reviewers ran; the fixes are author claims and are not verified by the panel. Round 1 post receipt was restored by the orchestrator from the existing GitHub review 6057764685 after the CLI got a 502 on a review that GitHub had created. Reviewed against d156c13..69ee6a9. Round 3 updateBLOCKED. Head unchanged (69ee6a9). Author replied on all 16 round 2 silent findings. Churn guard: CRF-6 acknowledged (description edit), CRF-19 deferred to #32522, 7 contested (CRF-7, 17, 18, 20, 21, 25, 36), 7 silent because the replies are bare severity labels (CRF-28, 29, 30, 31: "Declined: wording nit."; CRF-33, 34, 35: "Declined: naming preference."). No reviewers ran. The round 2 fixes, including CRF-1 and CRF-9 (P1), are still unverified by the panel. Reviewed against d156c13..69ee6a9. Round 4Churn guard PROCEED: 14 contested (CRF-7, 17, 18, 20, 21, 25, 28, 29, 30, 31, 33, 34, 35, 36), CRF-19 deferred to #32522. Round type: restructure (exported signatures changed since R1: Round 5Head e919721. Churn guard PROCEED: CRF-47, 50, 55 fixed in code, CRF-48 by description; 13 contested; CRF-19 deferred. Round type: fix round (interdiff +8 -6 in preview.go, proxy.go, proxy_test.go; comment and test edits only, no signature change). Panel: dispute check-in (previous agents) bisky, luffy, gon, leorio, kurapika, hisoka, kite, mafuuu; melody (CRF-55 code touched); ging-go and ryosuke (changed Go files); wildcard (random from meruem, chopper, zoro, knov, razor): meruem. Netero runs (new head). CI: the failed jobs (changes, lint, gen, check-build and dependents) were cancelled, not failed. Round 6Head 6747c02: rebase onto c6e31cc; Round 7Head unchanged (6747c02). New author comment IC_kwDOGkVX1s8AAAABrKbwDg records a human operator decision accepting CRF-60 for the experimental release, no ticket. Churn guard PROCEED: CRF-60 acknowledged, CRF-19 deferred, nothing else open. Round type: fix round with no code change since the R6 panel. Panel at the 3-reviewer minimum: pariston, mafuuu, kurapika; wildcard (random from meruem, chopper, zoro, knov, razor, kite): zoro. Netero runs (prior round was not Netero-only). Round 8Head 4cae110: rebase onto c78dfe7; Round 9Head 327e5ed: rebase onto 5e517bd; About deep-reviewCRF = Coder Review Finding (P0-P4, Nit, Note)
|
There was a problem hiding this comment.
This PR adds the hidden open-preview experiment and serves file and port previews on preview-- hosts with a CSP and header-filtering response writer, owner-only issuance and Origin refusal. Findings: 2 P1, 1 P2, 11 P3, 11 P4, 11 Nit.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/httpapi/cookie.go:23:StripCoderCookiesmatches only the exact namecoder_session_token, so after a deployment turns the host prefix off,__Host-coder_session_tokenis still forwarded to path apps on the dashboard host, which then receive the user's session token.agent/api.go:20: the agent's preview file route sits behindagentchat.Middleware, which trustsCoder-Chat-Idand related request headers, so every caller that reaches a preview must strip them first.coderd/workspaceapps/request.go:312: preview tokens carry the template'sCorsBehavior, so a later change that readstoken.CORSBehavioron preview hosts would apply passthru CORS to agent-written pages.coderd/workspaceapps/appurl/appurl.go:175: the"---"prefix separator is an unnamed literal, and this PR adds two more copies.
Notes:
Hosting.Coversandappurl.IsPreviewHostnamedefine "preview host" differently (anypreview--prefix versus a valid slug and five segments); a caller choosing one for a security check has to read both bodies.- The commit subject and PR title use "strict", which a
git logreader cannot interpret without readingpreviewhost.Strict. - With this PR alone, every preview request gets the 401 "Reopen this preview from Coder to sign in again.", because the sign-in that sets
coder_preview_session_tokenarrives in #32522. The experiment is hidden, so only deployments that name it are affected. - Nothing in this PR stops a preview frame from navigating itself to another app host; the dashboard wrapper's
frame-srcin #32441 carries that containment.
coderd/httpmw/cors.go:109
P4 [CRF-8] The PR description says WorkspaceAppCors refuses preview origins, but this PR does not change cors.go. (Netero)
What refuses those origins is isFromOtherPreview in HandleSubdomain, which runs before the CORS middleware, and WorkspaceAppCors would still allow a same-user preview origin because ParseSubdomainAppURL now parses preview hosts. If the isFromOtherPreview check moves, CORS will not refuse these origins. Correct the description, or add the refusal to WorkspaceAppCors.
🤖
🤖 This review was automatically generated with Coder Agents.
| if i := strings.LastIndex(subdomain, "---"); i >= 0 { | ||
| subdomain = subdomain[i+len("---"):] | ||
| } | ||
| return strings.HasPrefix(subdomain, appurl.PreviewSlugPrefix) |
There was a problem hiding this comment.
P1 [CRF-1] Covers claims every host whose label starts with preview--, which includes every existing subdomain app with slug preview, so those apps break on every deployment with a wildcard app hostname, with the experiment off. (Netero)
preview matches provisioner.AppSlugRegex, and coderd.go and wsproxy.go build Hosting whenever AppHostname is set, so preview--agent--workspace--user goes to servePreview, where Parse fails and the user gets a 400 "This is not a valid preview address." with the sandbox CSP. A scratch test with newPreviewServer reproduced status=400 for both the agent and agentless forms, and PreviewWithoutAgentIsAppSlug in appurl_test.go shows the host still parses as app preview. Make Covers require that the first two -- segments form a valid preview slug (as IsPreviewHostname does), or reserve the preview slug at template import, and add a regression case for an app named preview.
🤖
There was a problem hiding this comment.
Verified fixed in 69ee6a9acf: Covers uses ParsePreviewHostname. The regression test written for this fix does not reach Covers; see the TestHandleSubdomainAppNamedPreview comment.
🤖
|
|
||
| // Hijack hands over the connection for WebSocket upgrades, whose 101 | ||
| // response does not load a page. | ||
| func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
There was a problem hiding this comment.
P1 [CRF-9] A preview server's WebSocket 101 response reaches the browser with Set-Cookie: ...; Domain= and Clear-Site-Data intact, because applyPolicy runs only from WriteHeader and httputil.ReverseProxy never calls it for a 101. (Melody, Pariston, Mafuuu, Ryosuke, Meruem, Hisoka, Kurapika)
handleUpgradeResponse calls Hijack, copies the upstream headers into rw.Header(), and writes them with res.Write(brw) on the hijacked connection (net/http/httputil/reverseproxy.go:853-882); a scratch test with Strict(...).Wrap around a ReverseProxy returned status=101 set-cookie=["x=1; Domain=apps.example.com"] clear-site-data="\"cookies\"". A port preview page can run new WebSocket(location.href) against its own server, which can then set an HttpOnly cookie for the whole app wildcard, including one named like the hashed coder_subdomain_app_session_token. Browser storage of handshake cookies is inferred from RFC 6455 and was not run in a browser. ReverseProxy calls ModifyResponse before handleUpgradeResponse, so apply the cookie, Link and Clear-Site-Data filter to res.Header in ModifyResponse for preview tokens, and assert the 101 headers in the WebSocket case of TestServePreviewPolicy.
🤖
There was a problem hiding this comment.
Verified fixed in 69ee6a9acf: ModifyResponse applies the policy before ReverseProxy writes the 101, and TestServePreviewPolicy/WebSocket fails when that call is removed.
🤖
|
|
||
| const ( | ||
| maxHostnameLabelLength = 63 | ||
| strictSandbox = "allow-scripts allow-same-origin allow-forms allow-modals allow-downloads" |
There was a problem hiding this comment.
P2 [CRF-10] The strict sandbox keeps allow-same-origin, so preview script can write Domain= cookies through document.cookie, which the Set-Cookie filter in applyPolicy never sees. (Kurapika, Mafuuu)
A page on preview--0123abcd--main--ws--alice.apps.example.com can run document.cookie = "x=1; Domain=apps.example.com; Path=/", and no CSP directive blocks it; when the wildcard is under the access URL host and EnableHostPrefix is off (the default), it can plant coder_session_token with Path=/api for the dashboard. This is inferred from browser cookie rules, not run in a browser. Header filtering cannot enforce the property the applyPolicy comment states while previews share a registrable domain with apps and the dashboard. Either drop allow-same-origin (previews lose same-origin storage and credentialed fetches to their own host), serve previews on a separate site, or state in the comment and the security review that preview script can still set cookies across the wildcard.
🤖
| // so a request without it is treated as a page load. Chromium sends no | ||
| // fetch metadata with a WebSocket handshake, which never loads a page. | ||
| dest := r.Header.Get("Sec-Fetch-Dest") | ||
| if dest == "document" || (dest == "" && !httpapi.IsWebsocketUpgrade(r)) { |
There was a problem hiding this comment.
P3 [CRF-11] On a deployment whose app hostname is plain HTTP and not localhost, every framed preview gets the 403 "Previews open only inside a Coder chat. Open this preview from its chat.", even when opened from the chat. (Pariston, Kite, Luffy, Leorio)
Browsers send Sec-Fetch-Dest only to potentially trustworthy origins, as the comment above states, so dest == "" holds for every iframe and fetch request on http://*.apps.example.com. The user is told to do what they already did, and the operator gets no log line naming the cause, because previewhost.Strict accepts an http access URL. Have Strict refuse or log for http with a non-localhost host so previews are reported as unavailable, or show a page that says previews need an HTTPS app hostname when no fetch metadata is present and r.TLS == nil.
🤖
| // of a link's ping attribute. | ||
| func isFromOtherPreview(r *http.Request, host string) bool { | ||
| origin, err := url.Parse(r.Header.Get(httpmw.OriginHeader)) | ||
| if err != nil || origin.Host == "" || appurl.HostnamesMatch(origin.Host, host) { |
There was a problem hiding this comment.
P3 [CRF-12] isFromOtherPreview returns false for Origin: null, which a preview page can produce by framing one of its own pages with <iframe sandbox="allow-scripts" src="/p.html">. (Hisoka, Melody)
url.Parse("null") gives an empty Host, so the request passes on every app host and on path-based apps, and the nested frame passes frame-src 'self' and the Sec-Fetch-Dest: iframe check. The doc comment says the check covers <a ping>, but the Fetch spec puts pings under connect-src, so either CSP already blocks pings or, in a browser that does not, a null-origin ping reaches the user's other apps (with cookies when --samesite-auth-cookie=none). Not run in a browser. Refuse Origin: null on app hosts, or at minimum correct the comment so it does not claim the ping case.
🤖
| } | ||
|
|
||
| parts := strings.Split(label, "--") | ||
| if len(parts) < 5 { |
There was a problem hiding this comment.
Nit [CRF-32] len(parts) < 5 is an unnamed count of hostname segments (preview, target, agent, workspace, user). (Gon)
Name it, for example const previewHostnameSegments = 5, so the check is tied to the ParseSubdomainAppURL grammar.
🤖
| proxy.ServeHTTP(rw, r) | ||
| } | ||
|
|
||
| func removeCoderdAgentHeaders(h http.Header) { |
There was a problem hiding this comment.
Nit [CRF-33] removeCoderdAgentHeaders deletes only the three chat headers, which the test calls "chat headers". (Gon)
Rename to removeChatHeaders.
🤖
There was a problem hiding this comment.
Declined: naming preference.
There was a problem hiding this comment.
Still open. The name says "agent headers", but the function removes only the three chat headers, and a reader deciding whether some other agent header is stripped will trust the name. Rename it, or say why the broader name is accurate.
🤖
There was a problem hiding this comment.
Declined: the function removes the headers coderd sets for its own agent requests, which today are the chat headers; removeCoderdAgentHeaders names who owns them, so a future coderd-to-agent header added there still fits the name.
There was a problem hiding this comment.
Defense accepted.
🤖
| return &responseWriter{ResponseWriter: rw, csp: h.csp} | ||
| } | ||
|
|
||
| type responseWriter struct { |
There was a problem hiding this comment.
Nit [CRF-34] The type responseWriter is called "the preview policy writer" in preview.go, db.go and db_test.go. (Gon)
Rename the type to policyWriter so code and comments use one name.
🤖
There was a problem hiding this comment.
Declined: naming preference.
There was a problem hiding this comment.
Still open. Comments in preview.go, db.go, db_test.go and proxy.go call this type "the preview policy writer", but the code names it responseWriter, so a search for one name misses the other. Use one name in both, or say why two names do not mislead.
🤖
There was a problem hiding this comment.
Declined: responseWriter is unexported inside previewhost, where it is the only writer, and the comments in other packages describe its role (the preview policy writer) because those readers never see the type name.
There was a problem hiding this comment.
Defense accepted.
🤖
| mcpHTTPClient *http.Client | ||
| // previewHosting is how this server hosts agent-authored previews. It is | ||
| // nil without a wildcard app hostname. | ||
| previewHosting *previewhost.Hosting |
There was a problem hiding this comment.
Nit [CRF-35] The same *previewhost.Hosting value is previewHosting in API, Previews in ServerOptions, and previews in wsproxy.New. (Gon)
Rename API.previewHosting to previews to match the ServerOptions field.
🤖
There was a problem hiding this comment.
Declined: naming preference.
There was a problem hiding this comment.
Still open. The same value is previewHosting, Previews and previews across coderd.go, ServerOptions and wsproxy.go, so a grep for one misses the others. Use one name, or say why each needs its own.
🤖
There was a problem hiding this comment.
Declined: API already has many fields, and previewHosting says the value is a previewhost.Hosting there, while ServerOptions.Previews reads as an option; matching the names would rename a field used across coderd.go for no behavior change.
There was a problem hiding this comment.
Defense accepted: each name is read only in its own file.
🤖
| sw, ok := w.(*tracing.StatusWriter) | ||
| sw, ok := statusWriterOf(w) | ||
| if !ok { | ||
| panic("dev error: http.ResponseWriter is not *tracing.StatusWriter") |
There was a problem hiding this comment.
Nit [CRF-36] The panic text "http.ResponseWriter is not *tracing.StatusWriter" no longer describes the failed condition. (Leorio)
statusWriterOf walks the Unwrap chain, so the panic fires when no writer in the chain is a *tracing.StatusWriter. Change it to "dev error: http.ResponseWriter does not wrap a *tracing.StatusWriter".
🤖
There was a problem hiding this comment.
Declined: the panic marks a programming error and its text still identifies the missing writer; cheap to revisit.
There was a problem hiding this comment.
Defense accepted: the panic names the type missing from the chain, and statusWriterOf is three lines above.
🤖
f0bc2f2 to
2063d45
Compare
6fbdd00 to
484b76a
Compare
484b76a to
29111a6
Compare
29111a6 to
1f72355
Compare
29e1864 to
db7a486
Compare
db7a486 to
69ee6a9
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
The new head (69ee6a9) changes code or the PR description for 20 of the 36 round 1 findings, including both P1s (the 101 policy bypass and Covers claiming apps named preview). The panel has not yet checked these fixes. 16 findings have no code change and no reply, so further review is blocked until each one gets a fix or a reply on its thread: fix in this PR, a linked issue, or a reason it should not be fixed.
Unaddressed:
- P3: chat-header denylist in
removeCoderdAgentHeadersis a hand copy of whatagentchattrusts (proxy.go:810). - P3: the public port share setup in
PreviewSubdomainis not checked by any assertion (db_test.go:786). - P3: no test for previews served by a workspace proxy (
wsproxy.go:324). - P4:
Hosting.Sandbox,Hosting.URLandPreviewID.Slughave no production caller in this PR. The description now names #32522 and #32440 as callers; a reply on the thread closes it. - P4: "Back to site" on in-frame error pages cannot navigate the tab, and the new signed-out page adds another (
preview.go:111,preview.go:132). - P4:
coderd.goandwsproxy.goeach buildHostinginstead ofNewServerbuilding it (previewhost.go:58). - P4:
/api/v0/previews/is a third copy of the agent route string (request.go:322). - Nit:
"__Host-"literal duplicatescodersdk.cookieHostPrefix(cookie.go:34). - Nit: "wrapper" and "hop" are undefined in comments (
db.go:170,preview.go:43). - Nit: the
servePreviewdoc opens by restating the name. - Nit: the
sandboxfield comment duplicates theSandbox()doc (previewhost.go:50). - Nit: the
URLdoc repeats the value ofmaxHostnameLabelLength(previewhost.go:101). - Nit:
removeCoderdAgentHeadersremoves only chat headers (proxy.go:810). - Nit:
responseWriteris called "the preview policy writer" elsewhere (previewhost.go:159). - Nit: one
Hostingvalue has three names (previewHosting,Previews,previews). - Nit: the panic text no longer matches the
Unwrapchain condition (db.go:481).
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
No new commits since the last review. The thread replies answer 9 of the 16 findings that were open: one handled in the description, the proxy test deferred to #32522, and 7 declined with reasons, which the panel will judge when it next runs. Seven Nits still block the panel because their replies give only a label ("wording nit", "naming preference") and not a reason the code should stay. Each one needs a code change or one sentence on why the current text does not mislead a reader. The fixes pushed for round 1, including both P1s, have not yet been checked by the panel.
Still open:
- "wrapper" and "hop" undefined in comments (
db.go:170,preview.go:43). servePreviewdoc opens by restating the name.sandboxfield comment duplicates theSandbox()doc.URLdoc repeats the value ofmaxHostnameLabelLength.removeCoderdAgentHeadersremoves only chat headers.responseWriteris called "the preview policy writer" elsewhere.- One
Hostingvalue has three names (previewHosting,Previews,previews).
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
The panel checked the round 1 fixes at 69ee6a9. Both P1 fixes hold: the 101 policy filter in ModifyResponse and Covers using ParsePreviewHostname were confirmed with mutation tests. The regression test for the Covers fix does not reach Covers, though (below). Of the 14 contested findings, 10 are closed and 4 are re-raised in their threads. New findings: 5 P3, 5 P4, 2 Nit; re-raised: 3 P4, 2 Nit.
Five findings share one cause: coderd leaves Previews nil without --host-prefix-cookie, and the workspace proxy always builds it and never checks its own cookie config. The five are the stale Previews doc, the unread previewsUnavailable, the cause-less "does not serve previews" page, the unreachable HTTPS message, and the proxy gap. One construction in NewServer that checks the serving process's own cookie config could address all five.
CI: the Flake Check job on this head was cancelled, not failed, and its log is no longer available.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/workspaceapps/proxy.go:541: WebSocket handshakes to subdomain apps and port previews are refused only whenOriginis another preview host, so a page on any same-site non-preview app (for example another user's public app) can open a credentialed WebSocket to the user's port app or port preview. Port URLs already allow this through the wildcard app cookie.
Notes:
- Preview page script can still set
Domain=cookies on the app wildcard (for example tossingcoder_subdomain_app_session_tokenor other apps' cookies). TheApplyPolicycomment records this as accepted. Accepting it for the experiment is a human decision for the security review (coder/security-assessments#437), not one the code comment can make.
🤖 This review was automatically generated with Coder Agents.
|
|
||
| var previews *previewhost.Hosting | ||
| if opts.AppHostname != "" { | ||
| previews, err = previewhost.Strict(opts.AppHostname, opts.AccessURL, opts.DashboardURL) |
There was a problem hiding this comment.
P3 [CRF-49] A workspace proxy serves previews whether or not its own --host-prefix-cookie is on, so the cookie-tossing fix holds only on coderd. (Kurapika, Hisoka)
Issue checks p.DeploymentValues.HTTPCookies, which is coderd's config, but the proxy reads cookies with its own cfg.HTTPCookies (enterprise/cli/proxyserver.go:267), and that flag defaults to off. With it off, HTTPCookieConfig.Middleware keeps unprefixed cookies, so a page on any app or preview host of the proxy can set coder_preview_session_token=x; Domain=<proxy wildcard>, and the user's previews on that proxy get the 401 page or the owner 404 until it expires (inferred from the cookie code paths, not run in a browser). Gate previews on the proxy's own cookie config here, in the same place coderd does.
🤖
There was a problem hiding this comment.
Declined: the proxy's own --host-prefix-cookie never applies to the preview cookie, since from #32522 the preview host reads only __Host-coder_preview_session_token over HTTPS, which a sibling host cannot set with Domain, and a tossed plain cookie gets the same result through a real proxy with that flag on or off.
There was a problem hiding this comment.
Defense accepted, checked against #32522: the preview host reads only __Host-coder_preview_session_token over HTTPS, and the cookie leaves cookiesToPrefix, so the proxy's flag does not affect it and a sibling host cannot set it with Domain. At this head nothing sets a preview cookie.
🤖
| })) | ||
| t.Cleanup(upstream.Close) | ||
|
|
||
| dv := coderdtest.DeploymentValues(t) |
There was a problem hiding this comment.
P3 [CRF-50] TestHandleSubdomainAppNamedPreview never runs Hosting.Covers, so it cannot catch a regression of the fix for apps named preview. (Bisky)
dv does not set HTTPCookies.EnableHostPrefix, so coderd leaves previewHosting nil and HandleSubdomain skips Covers in both subtests. Putting the old prefix check back into Covers still passes; with dv.HTTPCookies.EnableHostPrefix = true, the unmutated test passes and the mutated one fails at line 277 (reproduced). Set EnableHostPrefix, and loop over it alongside the experiment, because it, not the experiment, decides whether coderd builds Hosting.
🤖
There was a problem hiding this comment.
Fixed in e919721: TestHandleSubdomainAppNamedPreview now enables the host prefix cookie so it reaches Covers, and fails when HandleSubdomain claims every preview-- host.
There was a problem hiding this comment.
Verified fixed in e919721399: with Covers replaced by the old preview-- prefix check, the test now fails at proxy_test.go:277.
🤖
| site.RenderStaticErrorPage(rw, r, site.ErrorPageData{ | ||
| Status: http.StatusNotFound, | ||
| Title: "Application Not Found", | ||
| Description: "This server does not serve previews.", |
There was a problem hiding this comment.
P3 [CRF-51] On coderd with open-preview on and --host-prefix-cookie off, every preview shows "This server does not serve previews.", which names no cause and no action. (Leorio)
This branch is now how coderd refuses previews without the host prefix, and only the startup warning names the flag. Put the cause on the page, as proxy.go:344 does for path apps, for example "Previews are off on this deployment because --host-prefix-cookie is not set. Ask an administrator to enable it."
🤖
There was a problem hiding this comment.
Declined: a user of this stack never reaches that page with the flag off, because the tool refuses with the --host-prefix-cookie reason and the dashboard shows the address endpoint's "Previews require --host-prefix-cookie. An administrator can enable it." before it loads any frame, so only a hand-typed preview URL sees this 404.
There was a problem hiding this comment.
Defense accepted: #32522's address endpoint returns "Previews require --host-prefix-cookie. An administrator can enable it." before any frame loads, so only a hand-typed URL reaches this page.
🤖
| } | ||
| // This also refuses workspace proxies' previews, whose tokens coderd | ||
| // issues here. | ||
| if err := previewhost.CheckCookieConfig(p.DeploymentValues.HTTPCookies); isPreview && err != nil { |
There was a problem hiding this comment.
P3 [CRF-52] The same --host-prefix-cookie refusal, reached through a workspace proxy, renders "The application or workspace you are trying to access does not exist or you do not have permission to access it." (Leorio)
The proxy builds Hosting without the cookie check, so its preview requests reach this line, and WriteWorkspaceApp404 sends ErrHostPrefixCookieOff only to a debug log. One setting then shows two different pages, and the proxy one tells the owner the workspace may not exist. Use writePreviewError with a 403 and the same text as the coderd page.
🤖
There was a problem hiding this comment.
Declined: the dashboard asks the address endpoint before it frames a proxy preview, and that endpoint refuses every region without --host-prefix-cookie and names the cause, so this 404 is only reachable by framing a preview URL by hand, and Issue keeps the generic page it uses for every refusal.
There was a problem hiding this comment.
Defense accepted, for the same reason as the coderd page. Whether the dashboard in #32441 always asks the endpoint before framing was not checked here.
🤖
| dest := r.Header.Get("Sec-Fetch-Dest") | ||
| if dest == "document" || (dest == "" && !httpapi.IsWebsocketUpgrade(r)) { | ||
| description := "Previews open only inside a Coder chat. Open this preview from its chat." | ||
| if dest == "" && s.AccessURL.Scheme == "http" && !isLocalhostName(host) { |
There was a problem hiding this comment.
P4 [CRF-53] On a plain-HTTP deployment where users can sign in, "Previews need an HTTPS access URL." is never shown, and the startup warning tells the operator to set a flag that breaks dashboard sign-in over HTTP. (Kite)
Coderd builds Hosting only with --host-prefix-cookie, which names the session cookie __Host-coder_session_token, and browsers refuse __Host- cookies from a non-secure origin (inferred from the cookie prefix rules, not run in a browser). With the flag off, as on every working HTTP deployment, the user gets the cause-less "does not serve previews" page instead. TestServePreviewPolicy/PlainHTTP builds Hosting directly, so it passes on a configuration coderd never builds. Check for HTTPS in the same gate as the host prefix and name both in its error, then drop this branch.
🤖
There was a problem hiding this comment.
Declined: you are right that coderd with the flag off shows the 404 instead of the HTTPS page, but every plain-HTTP workspace proxy and coderd with the flag on still show the HTTPS page, which is the configuration that test builds, and the docs list HTTPS as a requirement next to --host-prefix-cookie, so an operator on plain HTTP is told both.
There was a problem hiding this comment.
Partly accepted: a plain-HTTP workspace proxy behind HTTPS coderd with the flag on does reach the HTTPS page, so the "unreachable" part is withdrawn. Still open, narrowed (P4, previewhost.go:30): the only guidance this PR gives is ErrHostPrefixCookieOff's text, "previews require --host-prefix-cookie", and #32522 shows users the same requirement. On a plain-HTTP coderd, an admin who follows it turns on the flag, HTTPCookieConfig.Middleware then drops coder_session_token, and browsers refuse the non-Secure __Host-coder_session_token that replaces it, so every user is signed out until the flag is turned off (inferred from the __Host- rules, not run in a browser). The HTTPS requirement is documented in #32442, not next to this message. Make the error name both, for example "previews require an HTTPS access URL and --host-prefix-cookie".
🤖
There was a problem hiding this comment.
Declined: thanks for withdrawing the unreachable part. Signing users out when the flag is on over plain HTTP is how --host-prefix-cookie already behaves on main, and the previews page lists HTTPS as a requirement next to the flag, so the error keeps naming only the setting it checks.
There was a problem hiding this comment.
Defense accepted: the sign-out over plain HTTP is how --host-prefix-cookie behaves on main by any route, so the warning belongs in that flag's description, which is listed as out of scope in the review body.
🤖
| _ = http.NewResponseController(w.ResponseWriter).Flush() | ||
| } | ||
|
|
||
| // Hijack hands over the connection for WebSocket upgrades. A response |
There was a problem hiding this comment.
P4 [CRF-56] The Hijack doc says "its writer applies the policy", and a reader can take "its writer" to be responseWriter, which never sees a proxied 101. (Gon)
The 101 policy is applied by ModifyResponse in proxy.go:745. A reader who believes this writer covers upgrades could remove that call, which reopens the WebSocket cookie bypass. Trim this doc to point at Wrap, which already states the fact, and drop the repeat from the servePreview doc.
🤖
There was a problem hiding this comment.
Declined: "its writer" is the writer of the response sent on the hijacked connection, the Wrap doc just above names the proxy and ApplyPolicy for upgrades, and TestServePreviewPolicy/WebSocket fails if that ModifyResponse call is removed.
There was a problem hiding this comment.
Defense accepted: the Wrap doc names ApplyPolicy for upgrades, and the WebSocket test fails if the ModifyResponse call is removed.
🤖
| HostnameRegex *regexp.Regexp | ||
| RealIPConfig *httpmw.RealIPConfig | ||
| // Previews decides which hosts serve agent-authored previews and the | ||
| // policy their responses carry. It is nil when Hostname is empty. |
There was a problem hiding this comment.
P3 [CRF-47] The ServerOptions.Previews doc says "It is nil when Hostname is empty", but coderd now also leaves it nil when Hostname is set and --host-prefix-cookie is off. (Netero)
TestPreviewsNeedHostPrefixCookie depends on that state. A reader who trusts the doc and treats Hostname != "" as Previews != nil could remove the s.Previews != nil check in HandleSubdomain and dereference nil on deployments without the host prefix. Update the doc to cover both cases.
🤖
There was a problem hiding this comment.
Fixed in e919721: the ServerOptions.Previews doc now covers the nil case.
There was a problem hiding this comment.
Verified fixed in e919721399: the doc's two nil cases match the New switch in coderd.go and wsproxy.New.
🤖
| options.Logger.Warn(ctx, "workspace previews are unavailable", slog.Error(api.previewsUnavailable)) | ||
| } | ||
| case options.AppHostname == "": | ||
| api.previewsUnavailable = xerrors.New("the deployment has no wildcard app hostname") |
There was a problem hiding this comment.
P4 [CRF-48] API.previewsUnavailable is written and read only by the warning log in the same switch, and nothing compares against the exported previewhost.ErrHostPrefixCookieOff. (Netero)
The PR description names the later PRs that use Sandbox, URL and Slug, but not these two. Name the PR that reads them, or move them there.
🤖
| header.Del("Link") | ||
| // Clear-Site-Data clears cookies for the whole registrable domain. | ||
| header.Del("Clear-Site-Data") | ||
| // A cookie with a Domain attribute is sent to the user's other apps. This |
There was a problem hiding this comment.
Nit [CRF-57] "This strips the ones the preview's server sets" restates the Del/Add loop below it. (Gon)
Keep the reason and the page-script caveat, and drop the restatement.
🤖
There was a problem hiding this comment.
Declined: the sentence says the strip covers only cookies the preview's server sends, which the loop cannot show and which the next sentence contrasts with cookies that page script sets.
There was a problem hiding this comment.
Defense accepted.
🤖
|
|
||
| // CheckCookieConfig returns ErrHostPrefixCookieOff unless cfg gives the | ||
| // session cookie the __Host- prefix. | ||
| func CheckCookieConfig(cfg codersdk.HTTPCookieConfig) error { |
There was a problem hiding this comment.
Nit [CRF-58] CheckCookieConfig returns ErrHostPrefixCookieOff exactly when EnableHostPrefix is false, but its name and both call sites read as a general cookie validation. (Gon)
Name it for the one condition it checks, for example RequireHostPrefixCookie.
🤖
There was a problem hiding this comment.
Declined: the doc comment states the one condition and the returned error names --host-prefix-cookie, so callers see the rule at both call sites, and the name says which config previews check, which stays true if that rule grows.
There was a problem hiding this comment.
Defense accepted.
🤖
69ee6a9 to
e919721
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
The panel checked e919721. The fixes for the ServerOptions.Previews doc, the TestHandleSubdomainAppNamedPreview host prefix, the isFromOtherPreview doc and the previewsUnavailable description hold; the test fix was confirmed by mutation. 12 of the 13 contested findings are closed by the reviewers that raised them. One is re-raised in its thread, narrowed to the text of ErrHostPrefixCookieOff. One new Nit. Nothing at P3 or above is open.
CI: the jobs marked failed on this head (changes, lint, gen, check-build and those that depend on them) were cancelled, not failed.
Notes:
proxyWorkspaceAppcallss.Previews.ApplyPolicyfor every preview token, so a preview token reaching a server whosePreviewsis nil would panic. No server reaches it today, because checks indb.go,proxy.go,coderd.goandwsproxy.goagree, but no type enforces the rule.
🤖 This review was automatically generated with Coder Agents.
| // isFromOtherPreview reports whether a page on a preview host other than host | ||
| // sent r. The browser sets Origin, so a preview page cannot forge it, and it | ||
| // adds the user's cookies for the target, so the request would act as the user. | ||
| // The preview CSP already blocks such requests; refusing them here also blocks |
There was a problem hiding this comment.
Nit [CRF-61] The rewritten isFromOtherPreview doc says the check "also blocks those whose Origin names another preview host", which repeats the doc's first sentence, and "it" in "where a browser does not enforce it" can mean the CSP, the Origin or the block. (Gon)
For example: // Where a browser does not enforce the preview CSP, this still refuses requests whose Origin is another preview host of s.
🤖
There was a problem hiding this comment.
Declined: the doc already says what the function refuses and why the server check backs up the CSP, and "it" reads as the preview CSP, so we are leaving the wording as it is.
There was a problem hiding this comment.
Defense accepted: a misread costs one look at a five-line function whose code shows what it refuses.
🤖
e919721 to
6747c02
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
The PR's commit is unchanged since the last review (git range-diff shows e919721399 = 6747c02d09); the head moved because the base PR changed a test. The last two contested findings, the ErrHostPrefixCookieOff text and the isFromOtherPreview doc wording, are closed by the reviewers that raised them, and the panel found nothing new. No finding is open. The workspace proxy preview test is tracked in #32522.
CI: the jobs marked failed on this head are cancelled jobs (for example check-build and sqlc-vet), not test failures, so the PR still needs a completed CI run.
Out of scope (needs a ticket or explicit acceptance by a human):
codersdk/deployment.go:3701: the--host-prefix-cookiedescription says "Recommended to be enabled" but not that over plain HTTP (other than localhost) browsers reject the non-Secure__Host-coder_session_token, so turning it on signs every user out. Previews now point admins at this flag.
Notes:
- Still a human decision for the security review (coder/security-assessments#437): preview page script can set
Domain=cookies on the app wildcard, which theApplyPolicycomment records as accepted.
🤖 This review was automatically generated with Coder Agents.
|
CRF-60 (review body note: preview scripts can set cookies on other apps' domains): Confirmed for the experimental release (operator decision, no ticket). This matches ordinary workspace apps on the same wildcard, preview hosts strip Domain cookies their servers set, and the docs page lists it under what previews do not protect. |
|
/coder-agents-review |
There was a problem hiding this comment.
No code change since the last review (head 6747c02). The author's PR comment records an operator decision accepting, for the experimental release, that preview page script can set Domain= cookies on the app wildcard; that closes the last item that needed a human decision. The panel found nothing new. No finding is open; the workspace proxy preview test is tracked in #32522.
CI on this head: the Storybook job failed in the Pixel visual-diff step ("pixel: build finished with status failed", with no per-story diff in the log), and this PR's only site/ change is the generated typesGenerated.ts, so the cause is unverified. The prepare-linkspector-browser failure is a runner that lost contact with the server, and the other failed checks are cancelled duplicates of jobs that passed in run 45805005859.
Notes:
- The
Domain=cookie acceptance covers the experiment only. Taking previews out of the experiment needs a new decision, and no ticket records that condition. - The round 1 "changes requested" review is still active because this account cannot dismiss it; a maintainer needs to dismiss it.
🤖 This review was automatically generated with Coder Agents.
6747c02 to
4cae110
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
No change to this PR's commit since the last review: git range-diff shows 6747c02d09 = 4cae110787, and the head moved because base PR #32438 added a test. The panel re-ran the preview tests at this head and found nothing new. No finding is open; the workspace proxy preview test is tracked in #32522.
CI on this head: the failed checks are cancelled zero-duration runs. In the second run, fmt, gen, lint, check-build, test-js and the docs jobs have passed, and the test-go-* jobs, Storybook, test-e2e and Flake Check were still running when this review was written.
Notes:
- The round 1 "changes requested" review is still active because this account cannot dismiss it; a maintainer needs to dismiss it.
🤖 This review was automatically generated with Coder Agents.
Adds the hidden open-preview experiment and serves file and port previews on preview hosts under the wildcard app hostname, with the hosting mode chosen by the new previewhost package. Every preview response carries a sandboxing CSP, cross-preview origins and top-level opens are refused, and token issuance requires the experiment, a subdomain request and workspace ownership. Co-Authored-By: Claude Opus 5.5 <[email protected]>
4cae110 to
327e5ed
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
No change to this PR's commit since the last review: git range-diff shows 4cae110787 = 327e5edcc3, and the head moved because base PR #32438 edited a test comment. The panel re-ran the preview tests at this head and found nothing new. No finding is open; the workspace proxy preview test is tracked in #32522.
CI on this head: the failed checks are the first run's cancelled zero-duration jobs and its required aggregate. In the second run, required and every test, lint, gen and build job have passed; Storybook was still running when this review was written.
Notes:
- The round 1 "changes requested" review is still active because this account cannot dismiss it; a maintainer needs to dismiss it.
🤖 This review was automatically generated with Coder Agents.
Adds the
open-previewexperiment, which is hidden from--experiments='*'and must be named explicitly, and serves agent previews on preview hosts under the existing wildcard app hostname in a strict mode. A security review (coder/security-assessments#437) showed that agent-written pages served like ordinary apps can reach the user's apps in every workspace, so preview hosts are locked down:preview--<id>--<agent>--<workspace>--<owner>serves a file preview from the agent API (port 4), andpreview--<port>--…serves a port. Both use the owner sharing level and ignore port shares. The port forwarding display app only hides the dashboard's ports UI, so it does not gate port previews, just as it does not gate port URLs. Connection logs record file previews asworkspace_appand port previews asport_forwarding, under thepreview--slug.coderd/workspaceapps/previewhostdecides how previews are hosted. Coderd and workspace proxies build oneHostingat startup withpreviewhost.Strict, and every preview host request goes throughservePreview. A later preview domain on another site would add a second constructor.Hosting.Sandbox,Hosting.URLandPreviewID.Slugare used by the sign-in (feat: sign previews in from the dashboard with a host-bound token #32522) and tool (feat(coderd): add the open_preview chat tool #32440) PRs.API.previewsUnavailableandpreviewhost.ErrHostPrefixCookieOffhave no reader here beyond the startup log; the sign-in (feat: sign previews in from the dashboard with a host-bound token #32522) and tool (feat(coderd): add the open_preview chat tool #32440) PRs read them.Hosting.ApplyPolicyadds the CSP (sandbox,default-src 'self',form-action 'self',frame-ancestorsthe dashboard) and dropsLinkheaders,Clear-Site-Dataand cookies with aDomainattribute. A response writer applies it to every response coderd writes on a preview host, including its own sign-in, error and 403 pages, atWriteHeader, because Go'sReverseProxyclears response headers after a 1xx. The writer drops 1xx responses other than 101.ReverseProxywrites a WebSocket 101 to the hijacked connection instead, so the proxy also applies the policy to every proxied response inModifyResponse.Originis another preview host of the same server get a 403, before CORS is applied.DBTokenProvider.Issuerefuses previews unless the experiment is on,--host-prefix-cookieis enabled, the request is a subdomain request, and the caller owns the workspace. The host-prefix requirement keeps a preview's script from replacing the user's Coder session cookie; without it, coderd still starts and logs a warning.coder-preview-sign-in-neededmessage to the dashboard, which then signs the user in once (see feat: sign previews in from the dashboard with a host-bound token #32522).Stack (review bottom-up). Replaces the closed #31282 stack. Security review: coder/security-assessments#437.
🤖 Generated with Claude Code