Repository navigation
fix(coderd/httpmw): anchor CSRF exemption patterns - #31125
Conversation
The exemption list was written like shell globs but nosurf matches it as unanchored regular expressions. "derp/*" exempted every path that contained "derp", including usernames, and "api/v2/workspaceagents/*" exempted the user-facing dev container routes. An exempt request skips the origin check as well as the token check, so a page in a workspace app could forge cookie-authenticated requests such as a role change to Owner or a dev container recreate. Each pattern now matches only the route it was written for. The duplicate "/api/v2/users/first" entry is removed. The "api/v2/scim/*" entry is dropped because SCIM is mounted at "/scim", outside "/api", where it is already exempt. Agents, workspace proxies, SCIM and provisioner daemons authenticate with headers and send no session cookie, so they were already exempt before the patterns were tried. The dashboard sends X-CSRF-TOKEN on every request. Fixes PLAT-733, SEC-1093, SEC-421, SEC-788.
|
/coder-agents-review Please limit the review to P0, P1, and P2 issues only. |
|
Chat: Review posted | View chat Review historydeep-review v0.13.0 | Round 2 | Last posted: Round 2, 1 findings (1 P2), APPROVE. Review Finding inventoryFindings
Contested and acknowledgedRound logRound 1Netero first pass: 1 P3, 1 Note. No P0, panel proceeds. Full panel (round 1). Multi-domain size because the change is security-sensitive (CSRF). Panel: ging-go, kurapika, ryosuke, melody, pariston, mafuuu, bisky, hisoka, gon, leorio, kite, wildcard meruem. Requester comment (IC_kwDOGkVX1s8AAAABeKY8Tg) limited the review to P0-P2; findings below P2 and OOS items are recorded here and not posted. Cross-check:
Reviewed against c61d842..6ec1986. Round 2Churn guard PROCEED: CRF-3 addressed in 73c57c7. Netero (post-panel, advisory): 1 P3 (CRF-18). Fix round (not a restructure: one pattern deleted, one test row flipped, one test comment added). Panel: meruem, bisky, kurapika, mafuuu, kite (raised CRF-3), ging-go, ryosuke (Go specialists), gon (comment touched), wildcard kite drawn and already selected as a CRF-3 raiser. Seven of eight verified the CRF-3 fix; bisky confirmed by mutation that restoring the pattern fails Cross-check: Gon rated CRF-19 P2. Keep-argument: test comments in a security exemption list are the record of why an entry is safe. Downgrade reason: the sentence restates the assertion and misleads no reader; Nit, below the requester's limit. About deep-reviewCRF = Coder Review Finding (P0-P4, Nit, Note)
|
There was a problem hiding this comment.
This PR anchors the CSRF exemption patterns in coderd/httpmw/csrf.go and adds regression rows that fail against the old patterns. 1 P2 finding. As requested, findings below P2 are not posted.
🤖 This review was automatically generated with Coder Agents.
The daemon authenticates with a header and sends no session cookie, so ExemptFunc already exempts it. The path pattern only affected cookie requests, and every route under the prefix is a GET today, so it changed nothing. It would have exempted the first mutating route added under the organization subtree from both the token and origin checks. The test row for the serve path now asserts a cookie request is checked.
|
/coder-agents-review Please limit the review to P0, P1, and P2 issues only. |
There was a problem hiding this comment.
Re-review of 73c57c7: the provisioner daemon exemption is removed and the ProvisionerDaemonsServe row now asserts the subtree is checked. Restoring the old pattern makes that row fail, and go test ./coderd/httpmw/ -run TestCSRF passes at 87bbc89. No new P0 to P2 findings.
🤖 This review was automatically generated with Coder Agents.
Emyrk
left a comment
There was a problem hiding this comment.
LG, I do not know the full set of routes this was supposed to catch. I assume we will trigger in dogfood.
@BobbyHo, we might want to merge this after code freeze to give us a month to validate we didn't block a route we previously permitted and needed to.
This stuff is really hard to test without manual confirmation in a browser
|
I'm going to hold off on merging this PR until after the next release. Please leave it unmerged for now. Thanks! |
TL;DR
Coder's CSRF guard stops a web page from making a logged-in user's browser send requests to the API as that user. The guard has a short list of routes it does not check, meant for agents, workspace proxies and other clients that never use a browser cookie. The list was written like shell wildcards, but it is matched as unanchored regular expressions, so
derp/*exempted any path containing the lettersderpandapi/v2/workspaceagents/*exempted every route under that prefix, including ones users call from the dashboard. A member whose username containsderpcould get an Owner's browser to promote them, and any page could reset another user's dev container. This PR makes each entry match only the route it was written for, and adds tests so it cannot drift back.Refs https://linear.app/codercom/issue/PLAT-733
How to navigate this PR
coderd/httpmw/csrf.goand 130 lines of tests incoderd/httpmw/csrf_test.go. Read the production change closely; the tests are a table.coderd/httpmw/csrf.go, the block ofExemptRegexpcalls. Check that every pattern starts with^and ends with$or(/|$), and that the only entry removed with no replacement is the oldapi/v2/workspaceagents/*.coderd/httpmw/csrf.go, theExemptFuncbelow the block. It is unchanged. Note that it already exempts any request with no session cookie, which is why non-browser clients are unaffected.coderd/httpmw/csrf_test.go, the new rows inTestCSRFExemptList. Each row is a path, with a session cookie attached, and whether it must be exempt.coderd/httpmw/csrf_test.go, theNoSessionCookiesub-test and theFormerlyExemptPathsub-test inTestCSRFError.Implementation
coderd/httpmw/csrf.go/api/v2/workspaceagents/me, the three cloud instance identity routes, the workspace proxy's own routes under/api/v2/workspaceproxies/me,/derp, and/api/v2/organizations/{org}/provisionerdaemons.api/v2/workspaceagents/*entry is removed with no replacement. That prefix holds routes users call with a cookie, such as recreating or deleting a dev container, and those must be checked./api/v2/users/firstentry, and the "This should not be required?" comment above it, are removed. One anchored entry remains.api/v2/scim/*entry is dropped rather than anchored. SCIM is mounted at/sciminenterprise/coderd/coderd.go, outside/api, where the middleware already exempts it by prefix. An entry for a route that does not exist would only matter if something were later mounted there, and then it would exempt it silently.ExemptRegexpname does not make it obvious.coderd/httpmw/csrf_test.goTestCSRFExemptList, aNoSessionCookiesub-test, and aFormerlyExemptPathsub-test inTestCSRFError. Details under Testing.release/2.29,2.34,2.35,2.36,2.37and2.38, so the production hunk applies cleanly. The test row for a doubled leading slash depends on fix(coderd/httpmw): normalize repeated slashes before CSRF exemption check #29798, which onlyrelease/2.38has, so that one row should be left out on the older branches.Expected Output
PUT /api/v2/users/derp-x/rolesis rejected with 400 and the message "Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies." Before this change it was accepted.PUT /api/v2/organizations/{org}/members/derpy/roles,PUT /api/v2/users/firstx/roles,POST /api/v2/workspaceagents/{agent}/containers/devcontainers/{dc}/recreate,DELETE /api/v2/workspaceagents/{agent}/containers/devcontainers/{dc}andPATCH /api/v2/workspaceproxies/me-east.X-CSRF-TOKENon every request and the middleware accepts a valid token before the pattern list is consulted.POST /api/v2/users/firststays exempt, and only that exact path./api/v2/workspaceagents/me/, the three*-instance-identityroutes, proxy routes under/api/v2/workspaceproxies/me/,/derp,/derp/latency-checkand/api/v2/organizations/{org}/provisionerdaemons/servestay exempt./scim/v2/Usersstays exempt because it is outside/api./api/v2/scim/v2/Users, which does not exist as a route, is no longer exempt.//api/v2/workspaceagents/me/rpcmatches no pattern and is checked. Odd paths fail closed.ExemptFuncare unchanged.Testing
TestCSRFExemptListincoderd/httpmw/csrf_test.go, eighteen new rows. Every row sends a POST with a session cookie and asserts nosurf'sIsExemptanswer./api/v2/csp/reports,/api/v2/users/first,/api/v2/workspaceagents/me/rpc,/api/v2/workspaceagents/me/logs,/api/v2/workspaceagents/aws-instance-identity,/api/v2/workspaceproxies/me/register,/derp,/scim/v2/Users,/api/v2/organizations/default/provisionerdaemons/serve./api/v2/users/derp-x/roles,/api/v2/users/firstx/roles,/api/v2/organizations/{org}/members/derpy/roles, the dev container recreate and delete paths,/api/v2/workspaceproxies/me-east,/api/v2/workspaceagents/aws-instance-identity/extra,/api/v2/scim/v2/Users, and//api/v2/workspaceagents/me/rpc.TestCSRFExemptList/NoSessionCookie. The agent, proxy, provisioner, first-user and dev container recreate paths are all exempt when no session cookie is sent.TestCSRFError/FormerlyExemptPath. A full round trip through the middleware: a PUT to/api/v2/users/derp-x/roleswith the session cookie, the CSRF cookie,Content-Type: text/plain, a foreignOriginand no header, as a browser would send from an attacker's page. Asserts 400 and the CSRF message.csrf-tokenmeta tag through the axios defaults insite/src/api/api.ts, which this PR does not touch.go test ./coderd/httpmw/ -count=1. Passes, as doesgo vetandgolangci-lint run ./coderd/httpmw/...with 0 issues.Manual Test
Run on 2026-11-02, 17:16 to 18:34 UTC, against dogfood (
https://dogfood.cdr.dev,v2.38.5-devel+7801f13692, which is the head ofmainthat day and contains the squash commit0fd07754f5), asbobby, a site owner. There is no PR branch to build: the thing under test is the middleware inside the coderd dogfood runs. Nothing in dogfood was changed except one test user,derp-plat733, and one API token, both removed at the end.The run answers the review worry that a route someone depended on, called with a cookie and no token, might now be refused. Each forged request is a
curlwith bobby's session cookie (__Host-coder_session_token, because dogfood setshost_prefix), a foreignOrigin,Content-Type: text/plainand noX-CSRF-TOKEN, which is what a page in another origin can make a logged-in browser send. Each forged request is paired with a with-header copy: the same request with a matchingCoder-Session-Tokenheader, which the exemption function lets through before any pattern is tried. The with-header copy's answer is what the forged request reached before this PR, so the run has a "before" without an unfixed server. The CSRF failure text istext/plain; every handler on dogfood answers JSON, so content type alone tells a refusal from a handler's answer. Every log line was written through a helper that replaces the token with<token>.All 27 steps passed. No findings.
derpusername attack: a forged role change on a user namedderp-plat733is refused with a foreign and with a same-site Origin, and the with-header copy changes the rolesfirstx, a proxy namedme-east, a POST under the provisioner daemon prefix, instance identity with a suffix, a doubled leading slash, all refused/me, instance identity, proxy/me, DERP, SCIM, CSP reports, all reach their handlersFacts worth knowing from the run:
derpnever appeared in them, and it passes the check byX-CSRF-TOKENfrom the page's meta tag. Scenarios 6 to 8 show three dashboard writes (start a workspace, change roles, start a dev container) answered 201, 200 and 202.host_prefixon, acurlthat sendscoder_session_token=looks to coderd like a request with no cookie, takes the no-cookie exemption and reaches the handler, which looks like "the fix blocks nothing". Scenario 1 shows the unprefixed name getting a 401 with a deleteSet-Cookie./api/v2/workspaceagents/aws-instance-identity/extrawith the header gets 400 "Invalid UUID" rather than 404 "Route not found", because chi enters the/{workspaceagent}subrouter and its id middleware runs before the not-found handler. A new user isdormant, notactive, until it signs in.1. Environment
The helpers are thin
curlwrappers.forgedsends the prefixed session cookie,Origin: https://evil.example,Content-Type: text/plainand no header.sameoriginis the same withOrigin: https://dogfood.cdr.dev.withheaderaddsCoder-Session-Tokenequal to the cookie.nocookiesends no credentials.apiis a header-authenticated GET androlesprints a user's site roles.2. The derp username attack is refused, and the with-header copy shows what it used to reach
The same-site request is sent separately because nosurf's origin check and token check end in the same text. With dogfood's own Origin the origin check passes, so that 400 can only be the token check, which is the one a page served from a workspace app would have to beat. The with-header copy asks for
auditorrather thanownerbecause a second owner on dogfood, even for a minute, was not needed. The no-cookie request shows the no-cookie exemption that agents and daemons depend on is intact.3. The dev container attack is refused with placeholder ids
The with-header copy's 404 is the agent lookup, the first middleware on the route, so it went past the CSRF check where the forged requests stopped. Scenario 8 repeats this with a real agent and container id.
4. The other substring matches are refused
Each pair is one row of
TestCSRFExemptListsent to a live server. The forged half is alwaystext/plainwith the sentence. The with-header half is whatever sits behind the path, which shows the path is routed and the 400 was the middleware. No proxy on dogfood is namedme…, no userfirstx, and the provisioner daemon entry that the bot's review found over-broad is gone (the forged POST there is now checked). The doubled slash is checked because nosurf matches the anchored^/api…against the raw path while the router collapses it, so the with-header copy still reaches the agent's log route.5. The routes that must stay exempt still are
Each is sent with the cookie and no token, the request form with the least proof of origin. A JSON answer means nosurf called the handler.
The instance identity answer is also a 400, so the content type is what tells it from the middleware: JSON with a
validationslist is the handler. The/derp426 is the DERP server's own text, not the CSRF sentence. SCIM is mounted at/scim, outside/api, so it is exempt before any pattern and the droppedapi/v2/scim/*entry never covered it; dogfood has SCIM disabled, which is why the handler answers 404.6. Dogfood's own clients keep working
The workspace
bobby/Bobby-Agent-Relaywas stopped at the start and started from the dashboard. Every client here sends a header and no cookie, which is the no-cookie exemption, and every path involved is one the old list named.The job succeeded 13 seconds after the click on a daemon that took it over the provisioner daemon
/serveroute, whose exemption entry this PR removed; the daemon sends a pre-shared key header and no cookie. The agent's five startup lines arrived byPATCH /api/v2/workspaceagents/me/logswith its own token. Theunhealthyandunregisteredproxies are other people's test entries and looked the same before the run. The dashboard'sPOST …/buildswas accepted (build 9 exists, initiated by bobby); the browser tool used for the run lists requests by URL, method and status and not by header, so theX-CSRF-TOKENline on that request is inferred the same way as in scenario 7.Screen capture: the workspace stopped, before Start
Screen capture: the build running after Start
Screen capture: the agent dev ready, with its apps and gauges
7. The dashboard changes roles, and what the browser holds
On the Users page, filtered to
derp-plat733: Edit roles, tick Auditor, Confirm; then again, untick, Confirm. The tab's network log was read before and after each Confirm.The path carries the UUID, so
derpnever appears in it. Scenario 2 showed a cookie-bearing PUT to a roles path with no token gets the 400 text, and the browser sends the cookie on every request, so a 200 here can only come through the last rule of the exemption function, a validX-CSRF-TOKEN. Script can read no cookie at all, so every cookie the browser holds for dogfood is HttpOnly; the dashboard's writes reached their handlers and scenario 1 showed coderd drops an unprefixed session cookie, so the one the browser sends is__Host-coder_session_token. The page holds the 88-character token the dashboard sends as the header.Screen capture: the Users page filtered to the test user, Member only
Screen capture: the Edit roles dialog with Auditor ticked, before Confirm
Screen capture: the row after the first Confirm, Auditor
Screen capture: the row after the second Confirm, Member again
8. The dashboard starts a dev container, and the forged request with the same ids starts nothing
The workspace page showed one dev container, stopped, with a Start button. The forged request was sent first, then the button was clicked.
This is the disclosed route used both ways on the same ids. Before this PR the cookie-only request would have answered 202 and started the container.
Screen capture: the dev container card, Disconnected, before Start
Screen capture: the card right after Start, spinner on the button
Screen capture: the dev container running, with its own apps and a Rebuild button
9. The PR's own tests at the squash commit
The 39 are the 33
TestCSRFExemptListsub-tests, the 4TestCSRFErrorsub-tests and the two parents, on Go 1.26.9. Among them are the rows scenarios 2 to 5 sent to dogfood:UsernameContainingDerp,OrgMemberContainingDerp,UsernameWithFirstPrefix,WorkspaceAgentsDevcontainerRecreate,WorkspaceAgentsDevcontainerDelete,ProvisionerDaemonsServe,WorkspaceProxyNameStartingWithMe,InstanceIdentityWithSuffix,WorkspaceAgentsMeRepeatedLeadingSlash,FirstUser,WorkspaceAgentsMeLogs,AWSInstanceIdentity,WorkspaceProxiesMe,DERP,SCIM,CSPReportsandFormerlyExemptPath.10. Cleanup
The workspace was left running with its dev container up.