Repository navigation
feat: serve agent previews on strict preview hosts - #32439
DanielleMaywood wants to merge 10 commits 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.
🤖
There was a problem hiding this comment.
Yes. It's accepted for the experiment: with allow-same-origin, page script can set Domain= cookies, and no header filter can stop that while previews share a site with apps. Two things limit it. --host-prefix-cookie is required (coderd refuses preview tickets without it), so a preview can't replace the Coder session cookie. And the ApplyPolicy comment and the docs state that a preview can still overwrite cookies of the user's other apps.
🤖 This reply was drafted by an AI agent (Claude Code) and posted with my approval.
| // 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 |
|
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 <noreply@anthropic.com>
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.
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: 327e5edcc3
ℹ️ 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".
| var cookiesToPrefix = map[string]struct{}{ | ||
| SessionTokenCookie: {}, | ||
| SessionTokenCookie: {}, | ||
| PreviewSessionTokenCookie: {}, |
There was a problem hiding this comment.
Preserve preview authentication on HTTP localhost
When previews run on the explicitly supported plain-HTTP localhost setup, adding this cookie to cookiesToPrefix makes authentication impossible: previews require EnableHostPrefix, so Apply emits a __Host-coder_preview_session_token, but a __Host- cookie requires Secure and cannot normally be used over HTTP; meanwhile the middleware deletes the only usable plain-name cookie before ResolveRequest can read it. Consequently localhost previews remain on the 401 sign-in page. The preview cookie needs scheme-aware naming/normalization rather than unconditional host-prefix handling.
Useful? React with 👍 / 👎.
mafredri
left a comment
There was a problem hiding this comment.
Feels like this change enables a lot of behavior irrespective of the experiment being enabled or not?
| ) | ||
|
|
||
| // PreviewSlugPrefix starts the app slug of every preview. | ||
| const PreviewSlugPrefix = "preview--" |
There was a problem hiding this comment.
Considering apps use -- as a separator for other things where we have [foo]--[bar]--[qux]. Isn't this adding one more dimension between foo and bar: [foo](--[thing])--[bar]--[qux]. This adds a new gotcha into the parsing, where we can't trust the positional arguments unless we always check "is this a preview".
Just a thought, but is there an alternative character we could use, that is otherwise illegal as a positional argument? Like preview+thing--[bar]--?
There was a problem hiding this comment.
I don't believe you can have + in a domain. https://www.rfc-editor.org/info/rfc1035/#section-2.3
There was a problem hiding this comment.
Yeah, I figured + wasn't allowed, it was a lazy example. But indeed, it looks like there aren't any options outside of --.
There was a problem hiding this comment.
We could possibly do --preview at the very end? That might resolve your worry about positional arguments.
There was a problem hiding this comment.
Would that not possibly match a user named preview?
|
|
||
| // The owner sharing level still lets site owners and users the | ||
| // workspace is shared with connect, but a preview runs agent-written | ||
| // code as whoever opens it, so only the workspace owner may. |
There was a problem hiding this comment.
Perhaps ASD-STE100 would be helpful here. I get that "may" refers to "opens it", but this doesn't read well.
| @@ -0,0 +1,214 @@ | |||
| // Package previewhost decides how a Coder server hosts agent-authored | |||
There was a problem hiding this comment.
Makes sense, moved it under that
| return &responseWriter{ResponseWriter: rw, hosting: h} | ||
| } | ||
|
|
||
| type responseWriter struct { |
There was a problem hiding this comment.
I think the bots are kind of right about this name (CRF-34). It has a more important role than just being a responseWriter. And it sounds weird if it's being described in other packages..
| // Previews decides which hosts serve agent-authored previews and the | ||
| // policy their responses carry. It is nil when the server serves no | ||
| // previews: without Hostname, or on coderd without --host-prefix-cookie. | ||
| Previews *previewhost.Hosting |
There was a problem hiding this comment.
This naming feels a bit confusing. previewhost.Hosting, called as Previews. Especially the Hosting doesn't tell me much about the type behind it.
| // writes goes through the preview policy writer, and proxyWorkspaceApp | ||
| // applies the same policy to proxied responses, WebSocket upgrades included. | ||
| func (s *Server) servePreview(rw http.ResponseWriter, r *http.Request, host string, middlewares []func(http.Handler) http.Handler) { | ||
| rw = s.Previews.Wrap(rw) |
There was a problem hiding this comment.
I wonder if workspaceapps.Server is being granted too much knowledge of preview internals here? Would s.Previews.Serve(…) be potentially better? The token issuing should probably stay here, and that could be solved by either passing the token issuing as an inline func or making rw, …, ok = s.Previews.Prepare(…) do more.
Further if we move to /x/ then it'd be more clear that even this validation is part of the experimental code that should be vetted before promotion.
| proxy.ModifyResponse = func(r *http.Response) error { | ||
| // ReverseProxy writes a WebSocket upgrade response to the hijacked | ||
| // connection, so the preview policy writer never sees it. | ||
| if isPreview { |
There was a problem hiding this comment.
Not sure if this would be a better design, but before serving the proxy we could do something like this:
if isPreview {
proxy = s.Previews.WrapProxy(proxy)
}It'd contain the experimental code, and allow the previewhost package to ensure the proxy is invoked correctly.
| 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.
Is this exposing the experiment in normal requests?
| } | ||
|
|
||
| // This runs before the app's CORS setting, so it also refuses | ||
| // requests that a passthru template would let through. |
There was a problem hiding this comment.
Saying "passthru tempalte" is wrong here, no such template exists.
|
|
||
| // This runs before the app's CORS setting, so it also refuses | ||
| // requests that a passthru template would let through. | ||
| if s.isFromOtherPreview(r, host) { |
There was a problem hiding this comment.
I think "other preview" is confusing terminology here.
6f16128 to
ab51e38
Compare
Previews are experimental, so the package that decides how they are hosted lives with the other experimental code under coderd/x. Only the package path and its imports change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Without the experiment, coderd builds no preview hosting, so a preview-shaped host gets the same "Invalid Application URL" response as main instead of the preview path. A server without preview hosting no longer mentions previews in that response. The cross-preview Origin refusal stays on: a preview page already open in a browser keeps running after the experiment is switched off. Workspace proxies are not gated, because they do not learn coderd's experiments; coderd's ticket check still refuses every preview there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ab51e38 to
e36c635
Compare
Brings in the agent review changes (#32438) without rewriting the commits already under review here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The checks that only preview hosts need now live in the experimental previewhost package, so the code to vet before previews leave the experiment is in one place. Hosting.Prepare wraps the writer and decides whether to refuse service workers, requests from other previews and top-level loads, and returns the app the host names. It returns a Refusal rather than writing the page, so previewhost does not import the site package. Hosting.WrapProxy applies the policy to proxied responses before the proxy's own ModifyResponse, which replaces the isPreview branch inside it. workspaceapps keeps what needs its own state: error pages, the smuggled API key refusal, the ticket, and the proxy. The cross-preview Origin check stays a package function, because ordinary app requests run it even when the server has no preview hosting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comments elsewhere already call it the preview policy writer, and the name now says what it does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The type is the set of preview hostnames under one wildcard and the policy their responses carry, so call sites now read as s.PreviewHosts.Covers(host) and hosts.URL(app, path). The workspaceapps field Previews becomes PreviewHosts, and coderd's previewHosting becomes previewHosts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in main through the agent branch, so this PR no longer conflicts with its base, without rewriting the commits already under review here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- db.go: state the owner-only rule in short sentences. - proxy.go: name the template setting, cors_behavior set to passthru. - previewhost.FromOtherPreview: say exactly what it checks. Comments only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in the junction test fix from #32438. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-written pages are untrusted, because a prompt-injected agent can write any HTML. The security review (coder/security-assessments#437) showed that serving them like ordinary apps lets them reach the user's apps in every workspace. Previews therefore get their own strict host mode instead of the app path: a sandboxing CSP, framing only by the dashboard, no shared app cookie, and no top-level loads.
Preview hosts sit under the existing wildcard app hostname, so operators need no new DNS or certificates. The experiment stays out of the safe experiments, so
--experiments='*'does not enable it, until we have more experience running previews. That is a rollout choice, not a known safety problem.Implementation details
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/x/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