Repository navigation
feat: sign previews in from the dashboard with a host-bound token - #32522
DanielleMaywood wants to merge 1 commit into
Conversation
9b92249 to
24b45ed
Compare
|
/coder-agents-review |
|
Chat: Review posted | View chat Review history
deep-review v0.13.1 | Round 9 | Last posted: Round 9, 63 findings (2 P2, 19 P3, 29 P4, 13 Nit), COMMENT. Review Finding inventoryFinding inventory: PR #32522Findings
Contested and acknowledgedCRF-70 (Nit, previews_test.go:196) and CRF-72 (P4, previews_test.go:262)
CRF-66 (P4, proxy.go:43) and CRF-67 (P4, previews.go:221)
CRF-45 (P3, previews.go:74) - whole-user key scope
CRF-46 (P4, preview.go:126) - port in exact host compare
CRF-56 (P3, previews.go:224) - same-site rule in handler
CRF-57 (Nit, previews.go:209) - "response title"
CRF-60 (P4, previews.go:224) - refusal under SameSite=None
CRF-61, CRF-62 (P4, tests) - CrossSite row and proxy refusal assertion
CRF-64 (P4, previews.go:163) - cross-site refusal Detail
CRF-40 (P3, codersdk/previews.go:12) - sign-in types reused by address endpoint
CRF-41 (P4, previewhost.go:192) - unreachable url.Parse branch
CRF-42 (P4, preview.go:139) - originLocalURL copy
CRF-43 (P4, previews_test.go:305) - inline key counts
CRF-45 (P3, previews.go:74) - whole-user key scope
CRF-46 (P4, preview.go:126) - port in exact host compare
CRF-50 (P4, previews.go:109) - ActionCreate on address endpoint
CRF-53 (Nit, codersdk/previews.go:49) - previewFrame name collision
CRF-5 (Nit, codersdk/previews.go:23) - omitempty on uuid.UUID RegionID
CRF-6 (Nit, previewhost.go:136) - "__Host-" literal duplication
CRF-13 (P3, preview.go:71) - expired sign-in param ignores valid cookie
CRF-17 (Nit, token.go:100) - Validate doc restates body
CRF-18 (P3, previewhost.go:132) - __Host- comment mechanism
CRF-19 (P4, workspaceapps.go:138) - createAppConnectKey doc lifetime
CRF-21 (P4, token.go:96) - inline time.Minute
CRF-22 (P4, token.go:102) - redundant Expiry nil check
CRF-23 (Nit, provider.go:42) - PreviewSessionCookie field name
CRF-25 (P4, provider.go:42) - empty cookie name in other callers
CRF-30 (P4, preview_test.go:473) and CRF-31 (P4, previews_test.go:108) - fake http.Response
CRF-33 (P4, previews.go:143) and CRF-34 (P4, previews.go:180) - error message wording
Law analysisR1: not run. Effective additions 805, below the 1000 threshold. Round logRound 1Netero first pass: 4 P3/P4, 2 Nit, 2 Note. No P0; panel proceeded. Round type: round 1, full panel. Multi-domain (security-sensitive token and cookie code): target 9-12. Cross-check:
Round 2 updateBLOCKED. Churn guard: 19 addressed (claimed, unverified by panel), 14 silent (CRF-5, CRF-6, CRF-13, CRF-17, CRF-18, CRF-19, CRF-21, CRF-22, CRF-23, CRF-25, CRF-30, CRF-31, CRF-33, CRF-34). No author replies. No review. Reviewed against 69ee6a9..3cbebe3. Effective additions grew 805 to 1560; Law and a full restructure panel are due on the next unblocked round. Round 3Panel (restructure: new address endpoint, effective additions 805 to 1560). Churn guard PROCEED: 14 findings contested by author replies. Round 4Fix round (no added files or new goal; effective additions 1560 to 1581). Churn guard PROCEED: 6 addressed, 1 acknowledged (CRF-46), 7 contested. Round 5Fix round (doc and errors.AsType changes only). Churn guard PROCEED: CRF-45 and CRF-46 accepted by the author as an operator decision; 5 contested; 4 addressed. Round 6Fix round (comment-only commit 588ce57). Churn guard PROCEED: 2 addressed, 2 contested. Round 7Fix round (comment-only commit 7cf249d). Churn guard PROCEED: 2 addressed, nothing contested. Round 8Fix round (rebase onto 4cae110; only coderd/previews_test.go changed: refusal rows call both endpoints, three tests merged into TestPreviewRegions). Churn guard PROCEED with no open findings. Round 9Fix round (rebase onto 327e5ed; previewHostingFor reads the proxy with the caller's context instead of AsSystemRestricted; tests run as a member and add a scoped-token proxy case; CRF-73 comment). Churn guard PROCEED: 1 addressed, 2 contested. About deep-reviewCRF = Coder Review Finding (P0-P4, Nit, Note)
|
There was a problem hiding this comment.
This PR adds a dashboard sign-in endpoint that mints a host-bound, encrypted preview sign-in token, and a preview-host handler that trades it for a host-only session cookie. Findings: 2 P2, 14 P3, 12 P4, 5 Nit.
The two P2 findings are the host binding, which another user's token can pass, and the cookie's SameSite value, which breaks sign-in when the preview host is a different site from the dashboard.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/workspaceapps/provider.go:95: the signed app token cookie set on preview hosts also takes the deployment SameSite value, so a cross-site preview host would miss it on every request and re-issue a token each time.coderd/workspaceapps/proxy.go:326:handleAPIKeySmugglingalso redirects throughoriginLocalURL(r.URL.Path), so subdomain apps opened at a path with%2Fload a different path after app sign-in.coderd/workspaceapps/token.go:58:EncryptedAPIKeyPayloadis accepted for up to two minutes after minting (one-minute expiry plusjwt.DefaultLeeway), and nothing documents that window.coderd/workspaceapps/previewhost/previewhost.go:191:applyPolicydropsSet-Cookieheaders with aDomain, but preview scripts run withallow-same-originand can setdocument.cookiewithdomain=the app wildcard parent, including acoder_subdomain_app_session_token_*cookie on the user's other apps.coderd/workspaceapps.go:140:createAppConnectKeycomputes expiry withtime.Untilanddbtime.Now, notapi.Clock, so mock-clock tests cannot control the key lifetime.
Notes:
coderd/previews.go:126:payload.Subjectis set, butsignInPreviewandPreviewSignInPayload.Validatenever read it, while theAPIKeyfield doc says the key belongs to "the user in Subject".
coderd/httpapi/cookie.go:32
P3 [CRF-3] This PR makes the comment's reason false: the preview cookie's __Host- prefix now follows the hosting scheme, not the deployment host-prefix setting. (Netero)
With PreviewSessionTokenCookie removed from cookiesToPrefix, EnableHostPrefix has no effect on it. Stripping both names is still correct because both can exist after the access URL scheme changes; say that in the comment.
🤖
🤖 This review was automatically generated with Coder Agents.
| } | ||
| previewURL, err := hosting.URL(appurl.ApplicationURL{ | ||
| AppSlugOrPort: req.PreviewSlug, | ||
| AgentName: req.AgentName, |
There was a problem hiding this comment.
P2 [CRF-8] A token minted by one user passes the host check on another user's preview host. (Kurapika, Netero)
req.AgentName reaches hosting.URL unvalidated for file slugs, so AgentName = "dev--site--testuser.a.co:1" builds payload.Host = "preview--0123abcd--dev--site--testuser.a.co:1--w--atk.a.co", and appurl.HostnamesMatch runs net.SplitHostPort and drops everything after the last colon. Reproduced with a scratch test: user atk minted a token for workspace w, sent it to testuser's preview host, and got 303 with Set-Cookie: coder_preview_session_token=<atk's key>. Issue still refuses atk's key there, but a page that frames the victim's preview host with this token replaces the victim's preview cookie, and the preview returns errors until reopened. Check AgentName against the workspace's agents for every slug (or require hosting.Parse(previewURL.Host) to return the same ApplicationURL), and compare payload.Host to the request host exactly in signInPreview.
🤖
There was a problem hiding this comment.
Verified fixed in 3cbebe3321.
🤖
| // of h with apiKey. It has no Domain, so it stays on that host. Over plain | ||
| // HTTP, where browsers reject Secure from most hosts, Secure follows cfg. | ||
| func (h *Hosting) SessionCookie(apiKey string, cfg codersdk.HTTPCookieConfig) *http.Cookie { | ||
| cookie := cfg.Apply(&http.Cookie{ |
There was a problem hiding this comment.
P2 [CRF-9] The preview session cookie takes SameSite from --samesite-auth-cookie (default lax), so browsers neither store nor send it when the preview host is a different site from the dashboard. (Razor, Ryosuke, Melody, Pariston, Mafuuu, Bisky, Meruem, Hisoka)
The sign-in and every later preview request run inside the dashboard iframe (servePreview refuses Sec-Fetch-Dest: document), and previewHostingFor accepts a primary wildcard or a proxy WildcardHostname on another registrable domain. Reproduced with Playwright Chromium: a page on coder.a.test framing a host that sets a SameSite=Lax cookie and 303s gets the cookie back on p.apps.a.test and not on p.apps-b.test, so on such a deployment every preview ends at the 401 "Reopen this preview" page. The tests use Go HTTP clients and a zero cookie config, so they cannot catch this. Either refuse non-same-site regions in previewHostingFor with an error that names the requirement, or set SameSite=None; Secure; Partitioned on HTTPS and document that browsers blocking third-party cookies still fail.
🤖
There was a problem hiding this comment.
The same-site check covers workspace proxies only. The primary branch of previewHostingFor (coderd/previews.go:208) returns api.previewHosting without the registrableDomain comparison, and coderd.go:748 builds it with no site check. A scratch test with access URL https://dashboard.test.coder.com and AppHostname: *.apps.example.net got 200 from PreviewSignIn and minted a key; in the browser the cookie is dropped, the 401 page asks the dashboard to sign in again, and each retry mints another key. Run the comparison in previewhost.Strict (all three callers pass dashboardURL) so the primary records it in previewsUnavailable, and add a primary cross-site test row. (Ryosuke, Melody, Pariston, Bisky, Razor, Mafu-san, Knov, Kite, Mafuuu, Meruem, Hisoka)
🤖
There was a problem hiding this comment.
Fixed in 5421940: sign-in now refuses a primary region whose wildcard access URL is on another site with 400 "Previews need a wildcard access URL on the same site as the dashboard." from both endpoints and mints no key, and a cross-site proxy gets its own 400 "Previews need a workspace proxy on the same site as the dashboard."; TestPreviewSignInUnavailable/CrossSite and TestPreviewSignInRegions cover both.
There was a problem hiding this comment.
Verified fixed in 5421940ac8.
🤖
| return | ||
| } | ||
|
|
||
| key, err := api.createAppConnectKey(ctx, apiKey) |
There was a problem hiding this comment.
P3 [CRF-10] Every sign-in mints a new application_connect key with whole-user scope and up to Sessions.DefaultDuration lifetime, and the key it replaces in the preview cookie stays valid. (Pariston, Kurapika, Ryosuke, Mafuuu)
The dashboard cannot read the preview host's HttpOnly cookie, so it must call this endpoint each time it frames a preview, and preview hosts are per preview ID; workspaceApplicationAuth mints a key only when an app host has no session. Each open therefore adds an api_keys row that lives up to 24h by default and opens every app the owner can reach, and the one-minute token can be replayed within its window to obtain it. Give this key a lifetime bounded to preview use, or skip minting when the host already holds a valid key for the same user.
🤖
There was a problem hiding this comment.
Verified fixed in 3cbebe3321.
🤖
| } | ||
| // A preview runs agent-written code as whoever opens it, so only the | ||
| // workspace owner may, even when the workspace is shared. | ||
| if workspace.OwnerID != apiKey.UserID { |
There was a problem hiding this comment.
P3 [CRF-11] The owner-only and port forwarding checks here copy the rules Issue enforces at coderd/workspaceapps/db.go:189-195, using a different agent lookup. (Ryosuke, Meruem, Pariston)
This handler matches req.AgentName exactly against GetWorkspaceAgentsInLatestBuildByWorkspaceID and only for port slugs, while Issue resolves the agent through Request.getDatabase; the two already disagree for an unknown agent on a file slug. When a rule changes in one copy, the endpoint mints keys for previews that Issue refuses, or refuses previews Issue would serve, and no test compares them. Move the rules into one workspaceapps function and call it from both places.
🤖
There was a problem hiding this comment.
Verified fixed in 3cbebe3321.
🤖
|
|
||
| http.SetCookie(rw, s.Previews.SessionCookie(payload.APIKey, s.CookiesConfig)) | ||
|
|
||
| redirectURL := originLocalURL(r.URL.Path) |
There was a problem hiding this comment.
P3 [CRF-12] The post-sign-in redirect is built from the decoded r.URL.Path, so /files/a%2Fb.html reloads as /files/a/b.html. (Mafuuu, Hisoka, Razor)
Hosting.URL keeps RawPath in the URL it signs, but originLocalURL(r.URL.Path) drops it; verified that originLocalURL on /files/a%2Fb.html returns /files/a/b.html. A preview server that routes on escaped segments serves a different resource than the one requested. Build the redirect from r.URL.EscapedPath() with the same leading-slash trimming.
🤖
There was a problem hiding this comment.
Verified fixed in 3cbebe3321.
🤖
| hosting, err := api.previewHostingFor(ctx, req.RegionID) | ||
| if err != nil { | ||
| httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ | ||
| Message: "This region does not serve previews.", |
There was a problem hiding this comment.
P3 [CRF-1] Every previewHostingFor error becomes 400 "This region does not serve previews.", including database failures. (Netero)
A lost connection or canceled context from GetWorkspaceProxyByID answers 400 with the raw database error in Detail, while the rest of this handler answers such errors with httpapi.InternalServerError. Return 400 for sql.ErrNoRows, a deleted proxy, and a missing wildcard hostname, and 500 for every other error.
🤖
There was a problem hiding this comment.
Verified fixed in 3cbebe3321.
🤖
| return | ||
| } | ||
|
|
||
| // The direct-open redirect above already answered page loads, so a |
There was a problem hiding this comment.
P3 [CRF-2] The comment refers to "the direct-open redirect above", but the code above refuses page loads with a 403 error page. (Netero)
Say "The page-load refusal above".
🤖
There was a problem hiding this comment.
Verified fixed in 3cbebe3321.
🤖
| // Workspace proxies always host previews in strict mode. | ||
| func (api *API) previewHostingFor(ctx context.Context, regionID uuid.UUID) (*previewhost.Hosting, error) { | ||
| if regionID == uuid.Nil || regionID.String() == api.DeploymentID { | ||
| if api.previewHosting == nil { |
There was a problem hiding this comment.
P4 [CRF-4] The primary-without-wildcard branch and the deleted or no-wildcard proxy branch of previewHostingFor have no test. (Netero)
Verified with -coverprofile: blocks at previews.go:153 and :164 have count 0. If the proxy.Deleted check is removed, a deleted proxy's hostname gets a sign-in token and no test fails.
🤖
There was a problem hiding this comment.
Verified fixed in 3cbebe3321.
🤖
| URLPath string `json:"url_path,omitempty"` | ||
| // RegionID picks the primary or a workspace proxy. Empty picks the | ||
| // primary. | ||
| RegionID uuid.UUID `json:"region_id,omitempty" format:"uuid"` |
There was a problem hiding this comment.
Nit [CRF-5] omitempty on RegionID uuid.UUID has no effect: uuid.UUID is a [16]byte array, so it is always sent as the zero UUID. (Netero)
Drop omitempty, or use *uuid.UUID if the field should be omitted.
🤖
There was a problem hiding this comment.
Not a bug: the tag makes the generated TypeScript field optional (readonly region_id?: string), as it does for the other uuid.UUID fields with omitempty in codersdk.
There was a problem hiding this comment.
Defense accepted.
🤖
There was a problem hiding this comment.
New evidence against the round 3 defense: guts also marks omitzero fields optional (convert.go:816 in v1.7.0 checks omitempty || omitzero), and codersdk already uses uuid.UUID with omitzero (codersdk/agentsdk/agentsdk.go:896, codersdk/chats.go:735). json.Marshal(codersdk.PreviewSignInRequest{}) still produces "region_id":"00000000-0000-0000-0000-000000000000". Use json:"region_id,omitzero" (Go 1.24+), which keeps readonly region_id?: string and actually omits the field. (Ging-Go)
🤖
| // parent domain, such as by another preview. | ||
| func (h *Hosting) SessionCookieName() string { | ||
| if h.scheme == "https" { | ||
| return "__Host-" + codersdk.PreviewSessionTokenCookie |
There was a problem hiding this comment.
Nit [CRF-6] The literal "__Host-" duplicates codersdk.cookieHostPrefix, and coderd/httpapi/cookie.go:34 has a third copy. (Netero)
Export the codersdk constant and use it in both places.
🤖
There was a problem hiding this comment.
Declined: exporting codersdk.cookieHostPrefix widens the SDK API for one string literal; cheap to revisit.
There was a problem hiding this comment.
Defense accepted.
🤖
24b45ed to
c8d90ac
Compare
b5aeb4e to
8ef1834
Compare
8ef1834 to
d20b13b
Compare
d20b13b to
13255ec
Compare
7e0d8c7 to
c9d354e
Compare
c9d354e to
f7708c9
Compare
f7708c9 to
3cbebe3
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
The new commit addresses 19 of the 33 round 1 findings, including both P2 findings (host binding and cross-site SameSite). The panel will check those fixes in the next round. 14 findings have no fix and no reply, so further review is blocked until each one is fixed or answered on its thread (fix, a linked issue, or the reason it should not change):
- P3
coderd/workspaceapps/preview.go:71: an expired sign-in token shows "invalid or expired" even when the host already has a valid session cookie. - P3
coderd/workspaceapps/previewhost/previewhost.go:132: theSessionCookieNamecomment says__Host-makes the cookie Secure and host-only. - P4
coderd/workspaceapps.go:138: thecreateAppConnectKeycomment omits theDefaultDurationcap and the return value. - P4
coderd/workspaceapps/token.go:96: the sign-in lifetime is an inlinetime.Minute. - P4
coderd/workspaceapps/token.go:102: theExpiry == nilcheck repeatsRegisteredClaims.Validate. - P4
coderd/workspaceapps/provider.go:42: the otherResolveRequestcallers rely onr.Cookie("")failing. - P4
coderd/workspaceapps/preview_test.go:473andcoderd/previews_test.go:108: a fakehttp.Responseis built to parseSet-Cookie. - P4
coderd/previews.go:143: "Invalid preview slug" does not state the valid format. - P4
coderd/previews.go:180: "Invalid preview address." blames the request when the hostname label is too long. - Nit
codersdk/previews.go:23:omitemptyonuuid.UUIDhas no effect. - Nit
coderd/workspaceapps/previewhost/previewhost.go:136: the"__Host-"literal duplicatescodersdk.cookieHostPrefix. - Nit
coderd/workspaceapps/token.go:100: theValidatedoc comment restates the body. - Nit
coderd/workspaceapps/provider.go:42:PreviewSessionCookieholds a name; call itPreviewSessionCookieName.
🤖 This review was automatically generated with Coder Agents.
|
/coder-agents-review |
There was a problem hiding this comment.
The new commit adds a no-mint address endpoint, binds the sign-in token to the exact host, refuses cross-site proxies, and adds tests for most round 1 gaps. Findings this round: 1 P2 and 1 P4 re-raised, 2 P3, 8 P4, 2 Nit new.
Verified fixed: 17 findings, including the host binding bypass. 13 of the 14 contested findings are closed; the createAppConnectKey doc comment is re-raised because main had an inline remark, not this doc comment on a new function. The cross-site SameSite fix is incomplete: the primary region has no same-site check, so a --wildcard-access-url on another site still mints a key for a preview that never loads.
Notes:
coderd/previews.go:241: the same-site check compares registrable domains but not schemes. Under schemeful same-site, an http dashboard and an https proxy on one domain are cross-site; this is unverified in a browser.
🤖 This review was automatically generated with Coder Agents.
| return | ||
| } | ||
|
|
||
| key, err := api.createAppConnectKey(ctx, httpmw.APIKey(r)) |
There was a problem hiding this comment.
P3 [CRF-45] The key each sign-in mints opens every workspace app its owner can reach, while the preview cookie only needs one workspace. (Knov, Kurapika)
Each new preview ID or port is a new host with no cookie, so each one mints another application_connect key with the *:* allow list and up to Sessions.DefaultDuration lifetime, and any client that loads a sign-in URL within its window with Sec-Fetch-Dest: iframe gets the raw key in Set-Cookie. apikey.CreateParams.AllowList accepts {Type: "workspace", ID: <workspace ID>}, and InheritWithinCaller accepts it as a subset of the dashboard session; verified that with this allow list TestPreviewSignIn/SignsInOnlyThePreviewHost still loads the preview with 200. Pass the workspace ID from resolvePreview to createAppConnectKey for preview sign-in only.
🤖
There was a problem hiding this comment.
Declined: we kept the same application_connect key that main's subdomain app sign-in mints and cut how often it is minted instead, since the dashboard now signs in only when the preview host has no cookie, so a workspace allow list was left out of this release.
There was a problem hiding this comment.
The defense does not change what one key reaches. Main's subdomain key lives in the wildcard app cookie that every app of the user reads, so whole-user scope matches its use; this key lives in a host-only cookie on one preview host of one workspace, and that host runs agent-written code. Each new preview ID or port is a new host with no cookie, so each still mints a 24h *:* key, and anyone who reads a sign-in URL within its window can obtain it with Sec-Fetch-Dest: iframe. Passing AllowList: {workspace: <ID>} for preview sign-in was verified in round 3 to still serve the preview. With no linked issue, this needs either the allow list in this PR or a human decision to accept the gap. (Knov, Kurapika)
🤖
There was a problem hiding this comment.
Accepted for the experimental release (operator decision, no issue filed): the key matches what main's subdomain app sign-in mints, the dashboard signs in only when a preview host has no session, and the sign-in URL is host-bound and short-lived, so we are not narrowing the key's allow list in this PR.
| err := jwtutils.Decrypt(ctx, s.APIKeyEncryptionKeycache, r.URL.Query().Get(previewhost.SignInParam), &payload) | ||
| // The whole host is compared: a host:port split would read text after a | ||
| // ":" in the payload's host as a port. | ||
| if err == nil && !strings.EqualFold(payload.Host, host) { |
There was a problem hiding this comment.
P4 [CRF-46] The exact host comparison includes a non-default port, while preview routing ignores the port, so a reverse proxy that forwards Host without the port fails every sign-in. (Hisoka)
With access URL https://coder.example.com:8443 behind nginx with proxy_set_header Host $host; (docs/admin/networking/reverse-proxy-nginx.md:127), the request host has no port and the payload has :8443, so the user gets "invalid or expired" each time; inferred from the code, not run. Now that Hosting.URL refuses names that do not parse back, comparing hostnames without ports keeps the host binding. Compare without ports and update SignInForOtherPort.
🤖
There was a problem hiding this comment.
Declined: you are right that a reverse proxy on a non-default port that drops the port from Host fails every sign-in, but comparing hostnames without ports would reopen the case the SignInForHostEndingInOtherHost row guards, and the documented reverse proxy setup listens on 443, so we keep the exact host comparison for this experiment.
There was a problem hiding this comment.
The consequence and reasoning are stated, but no issue is linked, so this needs a human decision: file an issue for deployments on a non-default port behind a proxy that drops it, or accept the limitation explicitly.
🤖
There was a problem hiding this comment.
Accepted for the experimental release (operator decision, no issue filed): sign-in compares the whole host the browser sends, so a reverse proxy on a non-default port must forward Host with its port, as the documented setup on 443 already does.
| var sdkErr *codersdk.Error | ||
| require.ErrorAs(t, err, &sdkErr) | ||
| require.Equal(t, http.StatusInternalServerError, sdkErr.StatusCode()) | ||
| require.NotContains(t, sdkErr.Message, "connection reset") |
There was a problem hiding this comment.
P4 [CRF-47] require.NotContains(t, sdkErr.Message, "connection reset") cannot fail. (Bisky)
httpapi.InternalServerError always sets Message to "An internal server error occurred." and puts the error text in Detail, so the assertion reads as proof the raw error is hidden when it is not. Delete the line; the status assertion above it tests the fix.
🤖
There was a problem hiding this comment.
Fixed in 5421940: the misleading Message assertion is deleted.
There was a problem hiding this comment.
Verified fixed in 5421940ac8.
🤖
| // itself when it has none, such as an IP address or localhost. Browsers treat | ||
| // two hosts as the same site when these are equal. | ||
| func registrableDomain(host string) string { | ||
| if hostname, _, err := net.SplitHostPort(host); err == nil { |
There was a problem hiding this comment.
P4 [CRF-49] No test calls registrableDomain with an access URL that has a port, so its net.SplitHostPort branch has count 0. (Bisky)
If that branch broke, coder.example.com:8443 would compare as example.com:8443 and every same-site proxy on such a deployment would get "This region does not serve previews.". Use https://dashboard.test.coder.com:8443 as the access URL in TestPreviewSignInRegions.
🤖
There was a problem hiding this comment.
Fixed in 5421940: TestPreviewSignInRegions now uses an access URL with a port and fails when the SplitHostPort block is removed.
There was a problem hiding this comment.
Verified fixed in 5421940ac8.
🤖
| func (api *API) resolvePreview(rw http.ResponseWriter, r *http.Request) (*url.URL, *previewhost.Hosting, bool) { | ||
| ctx := r.Context() | ||
| apiKey := httpmw.APIKey(r) | ||
| if !api.Experiments.Enabled(codersdk.ExperimentOpenPreview) || !api.Authorize(r, policy.ActionCreate, apiKey) { |
There was a problem hiding this comment.
P4 [CRF-50] Both endpoints authorize policy.ActionCreate on the caller's API key, but the address endpoint creates nothing, and neither checks ActionApplicationConnect on the workspace. (Kite)
A token without api_key:create gets a 404 from the address endpoint that looks like "workspace not found", and sign-in mints a key that only Issue later refuses. Check ActionApplicationConnect on the workspace in resolvePreview, and the ActionCreate key check only in postPreviewSignIn.
🤖
There was a problem hiding this comment.
Declined: the address endpoint shares sign-in's checks on purpose so it never hands out an address the caller could not sign in to, and the owner check plus the key scope check leave no case where an owner passes and Issue then refuses, so a separate workspace check would add nothing reachable.
There was a problem hiding this comment.
Defense accepted.
🤖
|
|
||
| // PreviewSignInRequest names one preview of a workspace the caller owns, for | ||
| // the preview address and sign-in endpoints. | ||
| type PreviewSignInRequest struct { |
There was a problem hiding this comment.
P3 [CRF-40] PreviewSignInRequest and PreviewSignInResponse are now also the address endpoint's request and response, and that endpoint does not sign in. (Netero)
The generated TypeScript exports these names to #32441, so renaming later touches both PRs. Rename them now, for example PreviewRequest and PreviewFrame, and update the swagger annotations.
🤖
There was a problem hiding this comment.
Declined: both endpoints take the same request and return the same frame, and the type comment says so, so renaming an experimental API's types across two stacked PRs for no behavior change is not worth the churn here.
There was a problem hiding this comment.
Defense accepted.
🤖
| return nil, err | ||
| } | ||
| ref, err := url.Parse(urlPath) | ||
| if err != nil { |
There was a problem hiding this comment.
P4 [CRF-41] The url.Parse error branch in Hosting.URL cannot run, because CheckURLPath already rejects paths that fail to parse. (Netero)
Verified with -coverprofile: the block has count 0. Share one parse between CheckURLPath and URL, or drop the branch.
🤖
There was a problem hiding this comment.
Declined: you are right that CheckURLPath parses the same string first so the branch never fires today, but the error still has to be handled, and sharing one parse would add a helper only to remove three lines with no behavior change.
There was a problem hiding this comment.
Defense accepted.
🤖
|
|
||
| // Like originLocalURL, but RawPath keeps the request's escaping, such as | ||
| // a %2F inside a name, so the preview reloads at exactly its path. | ||
| redirectURL := &url.URL{ |
There was a problem hiding this comment.
P4 [CRF-42] signInPreview copies the slash trimming of originLocalURL instead of making originLocalURL keep RawPath. (Netero)
The two copies must now stay in step, and originLocalURL still decodes %2F for its three other callers in proxy.go. Giving originLocalURL the escaped path removes the copy.
🤖
There was a problem hiding this comment.
Declined: originLocalURL's other callers are main's app redirects, whose %2F decoding is pre-existing and out of scope for this stack, so the preview redirect keeps its own escaping instead of changing their behavior.
There was a problem hiding this comment.
Defense accepted.
🤖
| require.Equal(t, http.StatusInternalServerError, sdkErr.StatusCode()) | ||
| require.NotContains(t, sdkErr.Message, "connection reset") | ||
|
|
||
| keys, err := db.GetAPIKeysByUserID(ctx, database.GetAPIKeysByUserIDParams{LoginType: database.LoginTypePassword, UserID: owner.ID}) |
There was a problem hiding this comment.
P4 [CRF-43] Two tests count application_connect keys inline for LoginTypePassword only, instead of using the appConnectKeys helper in the same file. (Netero)
The helper also counts LoginTypeToken keys. If either test's caller becomes a token client, the inline count is zero and the test still passes. Use the helper.
🤖
There was a problem hiding this comment.
Declined: both tests sign in with password sessions, so every key they could mint has the password login type and the inline count already sees it; the helper's token branch only matters for the scoped-token test that uses it.
There was a problem hiding this comment.
Defense accepted.
🤖
| return e.RegisteredClaims.Validate(ex) | ||
| } | ||
|
|
||
| // PreviewSignInPayload signs a browser in to one preview host. The |
There was a problem hiding this comment.
Nit [CRF-44] "The coderd mints it" has an extra article. (Netero)
Say "coderd mints it".
🤖
There was a problem hiding this comment.
Fixed in 5421940: the comment now says coderd mints it.
There was a problem hiding this comment.
Verified fixed in 5421940ac8.
🤖
3cbebe3 to
5421940
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
This commit adds the same-site check for the primary region and fixes five round 3 findings. Findings this round: 1 P3 re-raised; new 2 P3, 5 P4, 2 Nit.
Verified fixed: the primary same-site check (CRF-9) and five others. Accepted defenses: six contested findings are closed. Re-raised: the workspace allow list on the preview key, because the defense covers how often keys are minted, not what one key reaches; it has no linked issue.
The exact host comparison including a non-default port (coderd/workspaceapps/preview.go:126) was acknowledged without an issue. That needs a human decision: file an issue or accept the limitation explicitly.
CI: the failed jobs for this head that were checked (7 of 19, including lint, gen, and test-go-pg) show conclusion cancelled with no failed step, so 5421940ac8 has no completed CI result yet.
🤖 This review was automatically generated with Coder Agents.
| if api.previewHosting == nil { | ||
| return nil, xerrors.Errorf("the deployment has no wildcard app hostname: %w", errRegionWithoutPreviews) | ||
| } | ||
| if registrableDomain(strings.Replace(api.AppHostname, "*", "preview", 1)) != registrableDomain(api.AccessURL.Host) { |
There was a problem hiding this comment.
P3 [CRF-56] The same-site rule sits in the handler, which leaves two copies, a second refusal type, a doc that is now false, and no startup warning. (Netero, Ryosuke, Gon)
Lines 224 and 241 repeat registrableDomain(strings.Replace(<wildcard>, "*", "preview", 1)) != registrableDomain(api.AccessURL.Host), the refusal is a bare crossSiteError beside the errRegionWithoutPreviews sentinel, whose doc at line 204 still says it marks every region that cannot serve previews, and a cross-site primary starts without the workspace previews are unavailable warning that coderd.go:739-746 logs for the other primary-wide config problems. Have previewhost.Strict, which already receives dashboardURL from all three callers, return a same-site error that wraps the sentinel; store it in previewsUnavailable for the primary at startup, and map it the same way for proxies.
🤖
There was a problem hiding this comment.
Fixed in 99d01d9: the errRegionWithoutPreviews doc now covers only regions without preview hosts and points cross-site regions at crossSiteError; we kept the rule in previewHostingFor rather than Strict, so the chat tool still offers the preview and the tab shows the reason.
There was a problem hiding this comment.
Defense accepted.
🤖
| // reason as the user's next step. | ||
| var errRegionWithoutPreviews = xerrors.New("choose another region") | ||
|
|
||
| // crossSiteError is the response title for a region whose preview hosts are on |
There was a problem hiding this comment.
Nit [CRF-57] "crossSiteError is the response title" names a field that does not exist; the value fills codersdk.Response.Message. (Gon)
Write "is the response message".
🤖
There was a problem hiding this comment.
Declined: the comment does not name a field; the message is the title of the error alert the preview tab shows, so "response title" says what the user reads, and the next line says what the type is for.
There was a problem hiding this comment.
Defense accepted.
🤖
| strings.ContainsFunc(urlPath, unicode.IsControl) { | ||
| return xerrors.Errorf("url_path must start with a single /, contain only a path and query, have no backslashes, fragments or control characters, and be at most %d bytes", maxURLPathLength) | ||
| } | ||
| ref, err := url.Parse(urlPath) |
There was a problem hiding this comment.
P4 [CRF-58] CheckURLPath accepts a query with bad percent-encoding or a ; pair, though its doc and the PR description say url_path cannot carry bad percent-encoding. (Ging-Go)
url.Parse copies the query to RawQuery unchecked and ref.Query() drops the parse error. Reproduced: url.Parse("/?a=%zz") returns no error while url.ParseQuery on its query returns invalid URL escape "%zz", and /?a=1;coder_preview_sign_in=x passes because the ; pair is skipped. Call url.ParseQuery(ref.RawQuery) once, return its error, and check the reserved keys on its result.
🤖
There was a problem hiding this comment.
Fixed in 99d01d9: the CheckURLPath doc now limits the percent-encoding check to the path, and the PR description matches.
There was a problem hiding this comment.
Verified fixed in 99d01d9a2e.
🤖
|
|
||
| hosting, err := api.previewHostingFor(ctx, req.RegionID) | ||
| var crossSite crossSiteError | ||
| if errors.As(err, &crossSite) { |
There was a problem hiding this comment.
Nit [CRF-59] var crossSite crossSiteError; errors.As(err, &crossSite) is the pattern .claude/docs/GO.md:106 says to replace with errors.AsType (Go 1.26, go.mod declares 1.26.11). (Ging-Go)
Write if crossSite, ok := errors.AsType[crossSiteError](err); ok {, or drop it if the same-site refusal becomes a wrapped sentinel.
🤖
There was a problem hiding this comment.
Fixed in 99d01d9: now uses errors.AsType[crossSiteError].
There was a problem hiding this comment.
Verified fixed in 99d01d9a2e.
🤖
| if api.previewHosting == nil { | ||
| return nil, xerrors.Errorf("the deployment has no wildcard app hostname: %w", errRegionWithoutPreviews) | ||
| } | ||
| if registrableDomain(strings.Replace(api.AppHostname, "*", "preview", 1)) != registrableDomain(api.AccessURL.Host) { |
There was a problem hiding this comment.
P4 [CRF-60] The same-site refusal ignores --samesite-auth-cookie, so a deployment set to none is refused previews its browsers would sign in to, and the crossSiteError comment justifies the check only by the default Lax. (Melody, Leorio)
Reproduced with Playwright in Chromium and Firefox: a SameSite=None; Secure cookie set by a framed 303 on preview.localhost was sent on the next framed request from dashboard.localhost; the Lax cookie was not. Either skip the check when HTTPSameSite() is SameSiteNoneMode, or keep it and say in the comment that it is intended under none because browsers that block third-party cookies drop that cookie.
🤖
There was a problem hiding this comment.
Declined: refusing cross-site regions under none is intended, because browsers that block or partition third-party cookies (Safari, Firefox) still drop or isolate that cookie in the dashboard's frame, so we keep one rule that behaves the same in every browser.
There was a problem hiding this comment.
The behavior is accepted: refusing under none is intended. The comment above crossSiteError still gives only the default SameSite=Lax cookie as the reason, and the Safari and Firefox reason is only in this thread. A maintainer who reads "default" can add a SameSiteNoneMode exemption, after which Safari users on a cross-site none deployment get the 401 page on every open and each retry mints another key. Put the reason in the comment, for example: "Browsers do not send the preview session cookie from the dashboard's frame across sites: they never send a SameSite=Lax cookie, and browsers that block or partition third-party cookies drop or isolate a SameSite=None one. The check therefore ignores --samesite-auth-cookie." (Leorio, Melody)
🤖
There was a problem hiding this comment.
Fixed in 588ce57: the crossSiteError comment now also says browsers block or partition the preview cookie as a third-party cookie even with SameSite=None, which is why the rule applies under --samesite-auth-cookie=none too.
There was a problem hiding this comment.
The new clause says browsers "block or partition it as a third-party cookie even with SameSite=None", which reads as every browser. The round 4 Playwright probe showed Chromium and Firefox with default settings sending a framed SameSite=None; Secure cookie, and Firefox's partitioning stores it under the dashboard's site, where the same frame reads it, so only blocking breaks the flow (Safari by default, Chrome with third-party cookies off). A maintainer who tests in Chromium sees the cookie arrive and has no true reason left to keep the refusal under none. Suggested: "and Safari, or any browser set to block third-party cookies, drops it even with SameSite=None, so the check ignores --samesite-auth-cookie." (Melody, Leorio, Gon)
🤖
There was a problem hiding this comment.
Fixed in 7cf249d: you are right that Chromium and Firefox send the framed SameSite=None cookie by default and Firefox's partition still serves the frame, so our earlier wording (and our reply naming Firefox) was wrong. The comment now says Safari, or any browser set to block third-party cookies, drops it even with SameSite=None; we keep the refusal under none so the rule does not depend on the browser.
There was a problem hiding this comment.
Verified fixed in 7cf249d645.
🤖
| wantMessage string | ||
| }{ | ||
| {name: "NoWildcard", hostPrefix: true, wantMessage: "This region does not serve previews."}, | ||
| {name: "CrossSite", appHostname: "*.apps.example.net", hostPrefix: true, wantMessage: "Previews need a wildcard access URL on the same site as the dashboard."}, |
There was a problem hiding this comment.
P4 [CRF-61] The CrossSite row of TestPreviewSignInUnavailable also passes with a same-site app hostname, because the subtest's dashboard is coderdtest's 127.0.0.1. (Bisky)
Reproduced: with appHostname changed to *.apps.test.coder.com, the row still passes. Set AccessURL to https://dashboard.test.coder.com in the subtest, as TestPreviewAddress does, so example.net versus test.coder.com is the only reason for the 400.
🤖
There was a problem hiding this comment.
Declined: 127.0.0.1 and test.coder.com are also different sites, so the row passing with that hostname is the check working; removing the primary check fails this row, and TestPreviewSignIn already shows a same-site primary signing in.
There was a problem hiding this comment.
Defense accepted.
🤖
| }) | ||
| var sdkErr *codersdk.Error | ||
| require.ErrorAs(t, err, &sdkErr) | ||
| require.Equal(t, http.StatusBadRequest, sdkErr.StatusCode()) |
There was a problem hiding this comment.
P4 [CRF-62] The proxy-region sign-in call asserts only status 400, so any refusal satisfies the step the comment at lines 67 to 69 describes. (Bisky)
An unknown agent, a bad slug, or a lookup refusal also returns 400. Assert sdkErr.Message equals "Previews need a workspace proxy on the same site as the dashboard.".
🤖
There was a problem hiding this comment.
Declined: the exact message is asserted by the CrossSite row of TestPreviewSignInRegions, which fails if the proxy refusal changes reason; this step only shows why the test mints the proxy's token itself, and removing the check fails it.
There was a problem hiding this comment.
Defense accepted.
🤖
| if api.previewHosting == nil { | ||
| return nil, xerrors.Errorf("the deployment has no wildcard app hostname: %w", errRegionWithoutPreviews) | ||
| } | ||
| if registrableDomain(strings.Replace(api.AppHostname, "*", "preview", 1)) != registrableDomain(api.AccessURL.Host) { |
There was a problem hiding this comment.
P3 [CRF-63] The PR description says only a workspace proxy is refused for being cross-site, but both endpoints now also refuse the primary when --wildcard-access-url is on another site than --access-url. (Leorio, Razor)
The squash commit uses the PR body, and #32442 (docs) is written from it, so main would not say that a deployment serving apps from a separate domain, such as *.coder-apps.com for coder.example.com, cannot use previews. Update the sentence to cover the primary wildcard and the proxy wildcard, and carry the requirement into #32442.
🤖
There was a problem hiding this comment.
Fixed in 99d01d9: the PR description now says a cross-site primary wildcard access URL is refused as well as a cross-site proxy.
There was a problem hiding this comment.
Verified fixed in 99d01d9a2e.
🤖
| hosting, err := api.previewHostingFor(ctx, req.RegionID) | ||
| var crossSite crossSiteError | ||
| if errors.As(err, &crossSite) { | ||
| httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{Message: string(crossSite)}) |
There was a problem hiding this comment.
P4 [CRF-64] A cross-site refusal returns only a Message, so it names neither of the domains that differ, and the proxy case no longer says that choosing another region works. (Leorio)
At 3cbebe3321 the cross-site proxy refusal went through errRegionWithoutPreviews and put the cause and "choose another region" in Detail. Add a Detail with both registrable domains, and wrap the sentinel for the proxy case as the other proxy refusals do.
🤖
There was a problem hiding this comment.
Declined: each cross-site case has its own message so the user reads the cause in the alert title, and the docs quote both messages and explain the site rule, which an admin needs more than the two domain names.
There was a problem hiding this comment.
Defense accepted.
🤖
5421940 to
99d01d9
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
This commit switches to errors.AsType and corrects two doc comments. Findings this round: 1 P4 re-raised (comment only); new 2 P4, 1 Nit.
Verified fixed: three findings. Accepted defenses: five contested findings are closed. The workspace allow list on the preview key and the exact host comparison with a non-default port are recorded as operator decisions for the experimental release. Still open: the crossSiteError comment should state why the refusal also applies under --samesite-auth-cookie=none.
Out of scope (needs a ticket or explicit acceptance by a human):
coderd/x/chatd/chattool/openpreview.go:150(#32440):OpenPreviewtreats anypreviewsUnavailablevalue, including a primary with no wildcard hostname, as unavailable in every region, so a same-site workspace proxy that could serve previews gets none from the tool.
CI: the failed jobs that were checked (changes, fmt, lint, test-go-pg) are cancelled runs with no failed step, so 99d01d9a2e has no completed CI result yet.
🤖 This review was automatically generated with Coder Agents.
|
|
||
| // errRegionWithoutPreviews marks a region the user chose that has no preview | ||
| // hosts, as opposed to a failure looking it up. A region on another site gets | ||
| // crossSiteError instead. Its text follows each reason as the user's next step. |
There was a problem hiding this comment.
Nit [CRF-65] "Its text follows each reason as the user's next step" now follows a sentence about crossSiteError, so "Its" reads as crossSiteError's text, which has no "choose another region" suffix. (Gon)
Move the sentence before the crossSiteError sentence, or write "The sentinel's text follows each reason as the user's next step."
🤖
There was a problem hiding this comment.
Fixed in 588ce57: the sentence about the sentinel's text now follows the first sentence, so "Its" refers to errRegionWithoutPreviews.
There was a problem hiding this comment.
Verified fixed in 588ce5718b.
🤖
| SubdomainProxyAPIKeyParam = "coder_application_connect_api_key_35e783" | ||
| // SubdomainProxyAPIKeyParam is defined in appurl, so previewhost can | ||
| // reserve it without importing this package. | ||
| SubdomainProxyAPIKeyParam = appurl.SubdomainProxyAPIKeyParam |
There was a problem hiding this comment.
P4 [CRF-66] The app sign-in query parameter now has two names, appurl.SubdomainProxyAPIKeyParam and the alias workspaceapps.SubdomainProxyAPIKeyParam, and this PR's tests use both (previewhost_test.go:41, preview_test.go:246). (Zoro)
A reader has to check that the two are the same constant, and the alias exists only so nine existing references keep compiling. Delete the alias and change those references to appurl.SubdomainProxyAPIKeyParam.
🤖
There was a problem hiding this comment.
Declined: you are right that the PR's tests reach the same constant through two names. We kept the alias so the existing references on main stay untouched, and the comment on it says where the constant now lives, so a reader who checks finds one value.
There was a problem hiding this comment.
Defense accepted.
🤖
| func (api *API) previewHostingFor(ctx context.Context, regionID uuid.UUID) (*previewhost.Hosting, error) { | ||
| if regionID == uuid.Nil || regionID.String() == api.DeploymentID { | ||
| if api.previewHosting == nil { | ||
| return nil, xerrors.Errorf("the deployment has no wildcard app hostname: %w", errRegionWithoutPreviews) |
There was a problem hiding this comment.
P4 [CRF-67] previewHostingFor writes "the deployment has no wildcard app hostname" again instead of using api.previewsUnavailable, which coderd.go:746 sets to that text for the same case. (Zoro)
resolvePreview has already returned for ErrHostPrefixCookieOff, so api.previewHosting == nil here means previewsUnavailable holds the no-wildcard error, and a change to the startup text makes the two disagree. Wrap the recorded reason: xerrors.Errorf("%w: %w", api.previewsUnavailable, errRegionWithoutPreviews).
🤖
There was a problem hiding this comment.
Declined: you are right that the startup reason and this branch spell the same text twice and could drift if one changes. Both describe the same check today, and this one is only the detail under the "choose another region" response, so we are keeping the branch self-contained.
There was a problem hiding this comment.
Defense accepted.
🤖
99d01d9 to
588ce57
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
This commit rewrites two doc comments in coderd/previews.go. Findings this round: 1 P4 re-raised; 1 Nit new.
Verified fixed: the sentence order in the errRegionWithoutPreviews doc. Accepted defenses: the SubdomainProxyAPIKeyParam alias and the duplicated no-wildcard text are closed. Still open: the new crossSiteError clause says every browser blocks or partitions a SameSite=None cookie, which Chromium and Firefox defaults contradict; only blocking browsers such as Safari break the flow.
🤖 This review was automatically generated with Coder Agents.
| return cookie | ||
| } | ||
|
|
||
| // Covers reports whether host is a preview host of h. That includes a |
There was a problem hiding this comment.
Nit [CRF-69] The Hosting.host doc says it is "the wildcard host with the serving port", but Strict now drops the port when it is the scheme's default. (Meruem)
signInPreview compares the payload host, built from h.host, with the request host exactly, so a reader who trusts the doc expects *.apps.example.com:443, the value that would fail the compare. Say "the wildcard host as browsers send it: with the serving port unless it is the scheme's default, such as "*.apps.example.com:8443"".
🤖
There was a problem hiding this comment.
Fixed in 7cf249d: the host doc now says it is the wildcard host as browsers send it, with the serving port unless it is the scheme's default.
There was a problem hiding this comment.
Verified fixed in 7cf249d645.
🤖
588ce57 to
7cf249d
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
This commit corrects the crossSiteError and Hosting.host doc comments. Both open findings are verified fixed, and this round found nothing new.
No in-scope findings remain open. The whole-user allow list on the preview sign-in key and the exact host comparison with a non-default port stand as the author's recorded operator decisions for the experimental release. The out-of-scope items listed in earlier rounds still need a ticket or explicit acceptance by a human, including the #32440 OpenPreview handling of previewsUnavailable and script-set Domain cookies on preview hosts (#32439).
CI for 7cf249d645 was still pending at review time.
🤖 This review was automatically generated with Coder Agents.
7cf249d to
9aae1d9
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
This rebase changes only coderd/previews_test.go: refusal cases now call both endpoints, and three region tests are merged into TestPreviewRegions. Findings this round: 1 P4, 2 Nit, all in test comments and names.
The merged test keeps every case from the three tests it replaces, and the primary cross-site row is now cross-site by construction. No production code changed since round 7. CI for 9aae1d9d33 has no completed result: the failed jobs that were checked (changes, Flake Check, lint, fmt) are cancelled runs with no failed step.
🤖 This review was automatically generated with Coder Agents.
| if tc.client != nil { | ||
| c = tc.client | ||
| } | ||
| // The address endpoint refuses what sign-in refuses. |
There was a problem hiding this comment.
Nit [CRF-70] "The address endpoint refuses what sign-in refuses." now restates the loop below it. (Gon)
In the old TestPreviewAddress it explained a single PreviewAddress call; here both endpoints are called with the same req and checked against the same tc.wantStatus, so the code says it. Delete the comment.
🤖
There was a problem hiding this comment.
Declined: the loop calls both endpoints, but the comment states the rule the test exists for (the address endpoint refuses what sign-in refuses), which a reader would otherwise have to infer from the shared req.
There was a problem hiding this comment.
Defense accepted.
🤖
|
|
||
| const apps = "*.apps.test.coder.com" | ||
| const regionRefused = "This region does not serve previews." | ||
| const hostPrefixOff = "Previews require --host-prefix-cookie. An administrator can enable it." |
There was a problem hiding this comment.
P4 [CRF-72] The constant hostPrefixOff holds an error message, and the table field hostPrefixOff is a bool, so rows read hostPrefixOff: true, ..., wantMessage: hostPrefixOff. (Gon)
A reader has to work out that the key is the field and the value is the constant. Rename the constants to hostPrefixRequiredMessage and regionRefusedMessage.
🤖
There was a problem hiding this comment.
Declined: the table field and the constant share a name because each row that sets the flag also expects that message, and the constant is declared three lines above the table, so a reader finds which is which immediately.
There was a problem hiding this comment.
Defense accepted.
🤖
| dv := coderdtest.DeploymentValues(t) | ||
| dv.Experiments = []string{string(codersdk.ExperimentOpenPreview)} | ||
| dv.HTTPCookies.EnableHostPrefix = !tc.hostPrefixOff | ||
| // The port checks that same-site comparisons ignore it. |
There was a problem hiding this comment.
Nit [CRF-73] "The port checks that same-site comparisons ignore it." reads as the noun phrase "the port checks", and it omits that the Primary row's wantOrigin also relies on :8443. (Leorio, Gon)
Someone simplifying the setup could drop the port and break Primary without knowing why. Say what each row needs, for example: "The dashboard's :8443 port makes the Proxy row fail if the same-site check compares ports, and the Primary row expects the port in its origin."
🤖
There was a problem hiding this comment.
Fixed in 4f68cc0: the comment now says the :8443 port makes the Proxy row fail if the same-site check compares ports, and that the Primary row expects the port in its origin.
There was a problem hiding this comment.
The Primary row also depends on the port being ignored: previewHostingFor compares registrableDomain of *.apps.test.coder.com with the :8443 access URL, so a port-comparing check fails both successful rows, not only Proxy. Say "makes the Primary and Proxy rows fail if the same-site check compares ports, and the Primary row expects the port in its origin." (Gon)
🤖
Adds POST /api/experimental/previews/sign-in, which returns the preview URL with a one-minute token bound to the exact preview host. The preview host exchanges it for a host-only session cookie and never accepts the wildcard app cookie, so a preview cannot replace the user's app sign-in. POST /api/experimental/previews/address returns the same preview address without minting a token, so the dashboard can load the preview with an existing preview session first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
9aae1d9 to
4f68cc0
Compare
|
/coder-agents-review |
There was a problem hiding this comment.
This rebase changes previewHostingFor to read the workspace proxy with the caller's context instead of AsSystemRestricted, runs the region tests as a member, and adds a scoped-token proxy case. Findings this round: 1 P3, 1 Nit new; 1 P4 and 1 Nit re-raised.
The caller-context read blocks every scoped token from every proxy region with a message that says the proxy is missing, while the regions endpoint and app sign-in read proxies as the system. The omitempty on RegionID is re-raised because omitzero keeps the TypeScript field optional and also omits it. Two contested findings are closed.
Out of scope (needs a ticket or explicit acceptance by a human):
enterprise/coderd/workspaceproxy.go:64: thefetchRegionscomment says users cannot usually access workspace proxies, butmemberRolegrants every member read on them, so a reader would wrongly expect the new caller-context read to refuse members.
CI: the failed jobs that were checked (changes, fmt, test-go-pg) are cancelled runs, so 4f68cc01bd has no completed CI result yet.
🤖 This review was automatically generated with Coder Agents.
| // such as through a token scope without workspace_proxy:read, counts as | ||
| // unknown. | ||
| proxy, err := api.Database.GetWorkspaceProxyByID(ctx, regionID) | ||
| if httpapi.Is404Error(err) { |
There was a problem hiding this comment.
P3 [CRF-74] Reading the proxy with the caller's context refuses every scoped token for every proxy region, and the response says the proxy does not exist. (Razor, Gon, Leorio, Ryosuke, Bisky, Chopper)
httpapi.Is404Error matches dbauthz denials, so a token without workspace_proxy:read gets 400 "This region does not serve previews." with Detail "no workspace proxy has ID ...: choose another region" (reproduced in the new TestPreviewSignInScopedToken case), and CreateToken rejects workspace_proxy:read as internal, so no narrower-than-all token can ever pass. The read protects no data: fetchRegions (enterprise/coderd/workspaceproxy.go:67) lists every proxy's URL and wildcard under AsSystemRestricted, and workspaceApplicationAuth looks proxies up the same way, so the same token can open ordinary apps on that proxy but not previews. Either read the proxy as fetchRegions does and expect success in the scoped case, or keep the caller read and return a distinct refusal that does not claim the proxy is missing, and assert its exact message at previews_test.go:433.
🤖
| require.NoError(t, signIn(uuid.Nil, codersdk.APIKeyScopeCoderWorkspacesAccess, codersdk.APIKeyScopeApiKeyCreate)) | ||
| require.Equal(t, 1, appConnectKeys(ctx, t, api.Database, first.UserID)) | ||
|
|
||
| // The scope cannot read workspace proxies, so a proxy region is refused. |
There was a problem hiding this comment.
Nit [CRF-75] "The scope cannot read workspace proxies" credits the scope alone, but the token's allow list also blocks the read, and either one produces the 400. (Bisky)
Verified by temporary edits: APIKeyScopeAll with this allow still gets 400, and so does the workspaces-access scope with a proxy allow target; only both together get 200. Say "Neither the scope nor the allow list grants workspace_proxy:read".
🤖
Adds two endpoints.
POST /api/experimental/previews/addressreturns a preview's URL, origin and sandbox without minting anything, so the dashboard can load a preview with an existing session.POST /api/experimental/previews/sign-insigns the workspace owner in to one preview host, and the dashboard calls it only when the preview host reports that it has no session. Coderd checks the experiment and that the caller owns the workspace, mints anapplication_connectkey, and returns the preview URL with a sign-in token encrypted under the existing workspace apps key. The token's audience iscoder_previewand it names the exact preview host. It is valid for one minute, plus up to one minute of clock leeway between coderd and the server that checks it.The preview host checks the token's host, sets a host-only session cookie (
__Host-coder_preview_session_tokenwithSecureon HTTPS, whatever--secure-auth-cookiesays, andcoder_preview_session_tokenon plain HTTP), and redirects to its own origin withReferrer-Policy: no-referrer, keeping the path's escaping, such as%2F. Workspace proxies decrypt the token with the key they already fetch, so they need no new keys or RPCs. This relies on #32439, where preview hosts refuse the app sign-in parameter, so a preview cannot replace the user's app sign-in for their other apps, and answer a preview without a session with a 401 page.Sign-in refuses a region whose preview hosts are not on the dashboard's site, the primary's wildcard access URL or a workspace proxy's, because browsers would not send the preview's
SameSite=Laxsession cookie from the dashboard's frame. A region that cannot serve previews gets a 400, and a failed region lookup a 500.url_pathmust passpreviewhost.CheckURLPath, which the tool shares, so its path cannot carry bad percent-encoding, and it cannot carry a query parameter the preview host reads itself. Both endpoints run the same checks. With the experiment off they return 404, and without--host-prefix-cookiethey return 400 "Previews require --host-prefix-cookie. An administrator can enable it." and mint nothing.Stack (review bottom-up). Replaces the closed #31282 stack. Security review: coder/security-assessments#437.
🤖 Generated with Claude Code