Skip to content

fix(coderd/httpmw): anchor CSRF exemption patterns - #31125

Merged
BobbyHo merged 8 commits into
mainfrom
bobby/plat-733-anchor-csrf-exemption-patterns
Oct 28, 2026
Merged

BobbyHo merged 8 commits into
mainfrom
bobby/plat-733-anchor-csrf-exemption-patterns

Conversation

@BobbyHo

@BobbyHo BobbyHo commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

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 letters derp and api/v2/workspaceagents/* exempted every route under that prefix, including ones users call from the dashboard. A member whose username contains derp could 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
  • Two files. About 20 lines of production code in coderd/httpmw/csrf.go and 130 lines of tests in coderd/httpmw/csrf_test.go. Read the production change closely; the tests are a table.
  • Reading order:
    1. coderd/httpmw/csrf.go, the block of ExemptRegexp calls. Check that every pattern starts with ^ and ends with $ or (/|$), and that the only entry removed with no replacement is the old api/v2/workspaceagents/*.
    2. coderd/httpmw/csrf.go, the ExemptFunc below the block. It is unchanged. Note that it already exempts any request with no session cookie, which is why non-browser clients are unaffected.
    3. coderd/httpmw/csrf_test.go, the new rows in TestCSRFExemptList. Each row is a path, with a session cookie attached, and whether it must be exempt.
    4. coderd/httpmw/csrf_test.go, the NoSessionCookie sub-test and the FormerlyExemptPath sub-test in TestCSRFError.
  • Nothing outside the middleware changes. No route, handler, SDK or dashboard change.
Implementation
  • coderd/httpmw/csrf.go
    • The seven unanchored patterns are replaced by six anchored ones: the first-user route, the agent's own routes under /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.
    • The old 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.
    • The duplicate /api/v2/users/first entry, and the "This should not be required?" comment above it, are removed. One anchored entry remains.
    • The old api/v2/scim/* entry is dropped rather than anchored. SCIM is mounted at /scim in enterprise/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.
    • Patterns use raw string literals so they read as written.
    • A short comment above the block says why anchoring matters, since nosurf's ExemptRegexp name does not make it obvious.
  • coderd/httpmw/csrf_test.go
    • Eighteen rows added to TestCSRFExemptList, a NoSessionCookie sub-test, and a FormerlyExemptPath sub-test in TestCSRFError. Details under Testing.
  • Why anchor rather than delete the list. Every client the list names authenticates with a header and sends no session cookie, so the middleware's own function already exempts them before the patterns run. Deleting the list would also be safe. Anchoring keeps the diff a line-for-line replacement that is easy to review on each backport branch, and keeps behaviour identical for any client that might send a cookie alongside its header.
  • Backports. The affected block is identical on release/2.29, 2.34, 2.35, 2.36, 2.37 and 2.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 only release/2.38 has, so that one row should be left out on the older branches.
Expected Output
  • A request that carries a session cookie and no CSRF token to PUT /api/v2/users/derp-x/roles is 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.
  • The same for 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} and PATCH /api/v2/workspaceproxies/me-east.
  • The dashboard keeps working on all of those routes, because it sends X-CSRF-TOKEN on every request and the middleware accepts a valid token before the pattern list is consulted.
  • POST /api/v2/users/first stays exempt, and only that exact path.
  • Agent routes under /api/v2/workspaceagents/me/, the three *-instance-identity routes, proxy routes under /api/v2/workspaceproxies/me/, /derp, /derp/latency-check and /api/v2/organizations/{org}/provisionerdaemons/serve stay exempt.
  • Any request with no session cookie stays exempt whatever its path, so agents, workspace proxies, provisioner daemons and SCIM providers are unaffected.
  • /scim/v2/Users stays exempt because it is outside /api. /api/v2/scim/v2/Users, which does not exist as a route, is no longer exempt.
  • A path with a doubled leading slash such as //api/v2/workspaceagents/me/rpc matches no pattern and is checked. Odd paths fail closed.
  • Error messages, the CSP report exemption and everything in ExemptFunc are unchanged.
Testing
  • TestCSRFExemptList in coderd/httpmw/csrf_test.go, eighteen new rows. Every row sends a POST with a session cookie and asserts nosurf's IsExempt answer.
    • Must stay exempt: /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.
    • Must be checked: /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/roles with the session cookie, the CSRF cookie, Content-Type: text/plain, a foreign Origin and no header, as a browser would send from an attacker's page. Asserts 400 and the CSRF message.
  • Coverage. Every bullet in Expected Output has a row except the dashboard one, which needs a browser. The dashboard sends the token from the page's csrf-token meta tag through the axios defaults in site/src/api/api.ts, which this PR does not touch.
  • Run with go test ./coderd/httpmw/ -count=1. Passes, as does go vet and golangci-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 of main that day and contains the squash commit 0fd07754f5), as bobby, 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 curl with bobby's session cookie (__Host-coder_session_token, because dogfood sets host_prefix), a foreign Origin, Content-Type: text/plain and no X-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 matching Coder-Session-Token header, 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 is text/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.

# Scenario Result
1 Environment: dogfood contains the merge, the list on that commit is anchored, the cookie prefix is on, the test user exists with no roles Pass
2 The disclosed derp username attack: a forged role change on a user named derp-plat733 is refused with a foreign and with a same-site Origin, and the with-header copy changes the roles Pass
3 The disclosed dev container attack: forged recreate and delete under a workspace agent are refused; the with-header copy reaches the agent lookup Pass
4 The other substring matches: firstx, a proxy named me-east, a POST under the provisioner daemon prefix, instance identity with a suffix, a doubled leading slash, all refused Pass
5 The routes that must stay exempt, with a cookie present: first user, agent /me, instance identity, proxy /me, DERP, SCIM, CSP reports, all reach their handlers Pass
6 Dogfood's own clients: the workspace starts from the dashboard on a dogfood daemon, the agent connects and posts logs, SSH and ping work, five proxies and seventeen daemons healthy Pass
7 The dashboard changes the test user's roles and changes them back; the browser holds only HttpOnly cookies and the page carries the CSRF token Pass
8 The dashboard starts a dev container through the recreate route; the forged request with the same real ids is refused and starts nothing Pass
9 The PR's own tests at the squash commit: 39 pass, 0 fail, no unanchored pattern Pass
10 Cleanup: test user deleted, token expired and removed, no log holds the token Pass

Facts worth knowing from the run:

  1. The dashboard never relied on the substring exemptions. Its role change and dev container requests use UUIDs in the path, so derp never appeared in them, and it passes the check by X-CSRF-TOKEN from 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.
  2. The dev container route was exercised both ways on the same ids within twelve seconds. Cookie only: 400 and the container stayed stopped. Dashboard with the token: 202 and the container came up running (scenario 8). Before this PR the cookie-only request would have answered 202.
  3. The cookie name is a trap for anyone repeating this on dogfood. With host_prefix on, a curl that sends coder_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 delete Set-Cookie.
  4. Two handler answers differed from what was expected, neither a problem. A POST to /api/v2/workspaceagents/aws-instance-identity/extra with 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 is dormant, not active, until it signs in.
1. Environment
curl -sS https://dogfood.cdr.dev/api/v2/buildinfo | jq -r '.version, .external_url'
cd ~/work/coder-upstream-1 && git fetch -q origin main && git log --oneline -1 origin/main
git merge-base --is-ancestor 0fd07754f509544df6f8e9e1c12e0e64c68557af 7801f13692 && echo "dogfood contains 0fd07754f5"
git show 0fd07754f5:coderd/httpmw/csrf.go | grep -n 'ExemptRegexp\|ExemptPath'
git show 0fd07754f5:coderd/httpmw/csrf.go | grep -n 'ExemptRegexp(regexp.MustCompile(' | grep -vF 'MustCompile(`^' || echo "every pattern is anchored"

coder tokens create --lifetime 4h --name plat733-run > /tmp/plat733/token     # read by the helpers, never printed
api /users/me | jq -r .username
api /deployment/config | jq -c '.config.http_cookies'
cookieonly GET /api/v2/users/me __Host-coder_session_token
cookieonly GET /api/v2/users/me coder_session_token
coder users create --username derp-plat733 --email [email protected] --full-name "PLAT-733 test user" --password "$(openssl rand -base64 24)"
roles derp-plat733
api /users/derp-plat733 | jq -c '{username, login_type, status, organization_ids}'
v2.38.5-devel+7801f13692
https://github.com/coder/coder/commit/7801f1369237e3421fea6c87619ee8aaa45cb4af
7801f13692 fix(site/src): mark table name cells as row headers (#31575)
dogfood contains 0fd07754f5
45:		mw.ExemptPath("/api/v2/csp/reports")
52:		mw.ExemptRegexp(regexp.MustCompile(`^/api/v2/users/first$`))
54:		mw.ExemptRegexp(regexp.MustCompile(`^/api/v2/workspaceagents/me(/|$)`))
55:		mw.ExemptRegexp(regexp.MustCompile(`^/api/v2/workspaceagents/(aws|azure|google)-instance-identity$`))
57:		mw.ExemptRegexp(regexp.MustCompile(`^/api/v2/workspaceproxies/me(/|$)`))
59:		mw.ExemptRegexp(regexp.MustCompile(`^/derp(/|$)`))
every pattern is anchored
bobby
{"secure_auth_cookie":true,"same_site":"lax","host_prefix":true}
[17:26:31] cookieonly GET /api/v2/users/me as __Host-coder_session_token
HTTP/2 200 
content-type: application/json; charset=utf-8
{"id":"671b17eb-0c5c-45c3-be51-e1f447c93378","username":"bobby","name"…
[17:26:31] cookieonly GET /api/v2/users/me as coder_session_token
HTTP/2 401 
content-type: application/json; charset=utf-8
set-cookie: coder_session_token=<value>; Path=/; Max-Age=0
{"message":"You are signed out or your session has expired. Please sign in again to continue.","detail":"Cookie \"coder_session_token\" or query parameter must be provided."}
[]
{"username":"derp-plat733","login_type":"password","status":"dormant","organization_ids":["703f72a1-76f6-4f89-9de6-8a3989693fe5"]}

The helpers are thin curl wrappers. forged sends the prefixed session cookie, Origin: https://evil.example, Content-Type: text/plain and no header. sameorigin is the same with Origin: https://dogfood.cdr.dev. withheader adds Coder-Session-Token equal to the cookie. nocookie sends no credentials. api is a header-authenticated GET and roles prints a user's site roles.

2. The derp username attack is refused, and the with-header copy shows what it used to reach
roles derp-plat733
forged PUT /api/v2/users/derp-plat733/roles '{"roles":["owner"]}'
roles derp-plat733
sameorigin PUT /api/v2/users/derp-plat733/roles '{"roles":["owner"]}'
roles derp-plat733
withheader PUT /api/v2/users/derp-plat733/roles '{"roles":["auditor"]}'
roles derp-plat733
withheader PUT /api/v2/users/derp-plat733/roles '{"roles":[]}'
roles derp-plat733
nocookie PUT /api/v2/users/derp-plat733/roles '{"roles":["owner"]}'
forged PUT /api/v2/organizations/703f72a1-76f6-4f89-9de6-8a3989693fe5/members/derpy/roles '{"roles":["organization-admin"]}'
withheader PUT /api/v2/organizations/703f72a1-76f6-4f89-9de6-8a3989693fe5/members/derpy/roles '{"roles":["organization-admin"]}'
[]
[17:32:17] forged PUT /api/v2/users/derp-plat733/roles
HTTP/2 400 
content-type: text/plain; charset=utf-8
Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies.
[]
[17:32:18] sameorigin PUT /api/v2/users/derp-plat733/roles
HTTP/2 400 
content-type: text/plain; charset=utf-8
Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies.
[]
[17:32:18] withheader PUT /api/v2/users/derp-plat733/roles
HTTP/2 200 
content-type: application/json; charset=utf-8
{"id":"b0e1d6db-e481-4f91-8b1b-f2d0b94a8cf9","username":"derp-plat733","name":"PLAT-733 test user",…
["auditor"]
[17:32:19] withheader PUT /api/v2/users/derp-plat733/roles
HTTP/2 200 
[]
[17:32:19] nocookie PUT /api/v2/users/derp-plat733/roles
HTTP/2 401 
content-type: application/json; charset=utf-8
{"message":"You are signed out or your session has expired. Please sign in again to continue.","detail":"Cookie \"coder_session_token\" or query parameter must be provided."}
[17:34:49] forged PUT /api/v2/organizations/703f72a1-…/members/derpy/roles
HTTP/2 400 
content-type: text/plain; charset=utf-8
Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies.
[17:34:49] withheader PUT /api/v2/organizations/703f72a1-…/members/derpy/roles
HTTP/2 404 
content-type: application/json; charset=utf-8
{"message":"Resource not found or you do not have access to this resource"}

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 auditor rather than owner because 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
Z=00000000-0000-0000-0000-000000000000
forged POST /api/v2/workspaceagents/$Z/containers/devcontainers/$Z/recreate
forged DELETE /api/v2/workspaceagents/$Z/containers/devcontainers/$Z
withheader POST /api/v2/workspaceagents/$Z/containers/devcontainers/$Z/recreate
[17:39:03] forged POST /api/v2/workspaceagents/00000000-…/containers/devcontainers/00000000-…/recreate
HTTP/2 400 
content-type: text/plain; charset=utf-8
Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies.
[17:39:03] forged DELETE /api/v2/workspaceagents/00000000-…/containers/devcontainers/00000000-…
HTTP/2 400 
content-type: text/plain; charset=utf-8
Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies.
[17:39:04] withheader POST /api/v2/workspaceagents/00000000-…/containers/devcontainers/00000000-…/recreate
HTTP/2 404 
content-type: application/json; charset=utf-8
{"message":"Agent doesn't exist with that id, or you do not have access to it."}

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
forged PUT /api/v2/users/firstx/roles '{"roles":["owner"]}'
withheader PUT /api/v2/users/firstx/roles '{"roles":["owner"]}'
forged PATCH /api/v2/workspaceproxies/me-east '{"display_name":"x"}'
withheader PATCH /api/v2/workspaceproxies/me-east '{"display_name":"x"}'
forged POST /api/v2/organizations/703f72a1-76f6-4f89-9de6-8a3989693fe5/provisionerdaemons/serve
withheader POST /api/v2/organizations/703f72a1-76f6-4f89-9de6-8a3989693fe5/provisionerdaemons/serve
forged POST /api/v2/workspaceagents/aws-instance-identity/extra '{}'
withheader POST /api/v2/workspaceagents/aws-instance-identity/extra '{}'
forged PATCH //api/v2/workspaceagents/me/logs '{}'
withheader PATCH //api/v2/workspaceagents/me/logs '{}'
[17:41:36] forged PUT /api/v2/users/firstx/roles
HTTP/2 400   content-type: text/plain; charset=utf-8   Something is wrong with your CSRF token. …
[17:41:37] withheader PUT /api/v2/users/firstx/roles
HTTP/2 404   content-type: application/json; charset=utf-8   {"message":"Resource not found or you do not have access to this resource"}
[17:46:30] forged PATCH /api/v2/workspaceproxies/me-east
HTTP/2 400   content-type: text/plain; charset=utf-8   Something is wrong with your CSRF token. …
[17:46:31] withheader PATCH /api/v2/workspaceproxies/me-east
HTTP/2 404   content-type: application/json; charset=utf-8   {"message":"Resource not found or you do not have access to this resource"}
[17:47:19] forged POST /api/v2/organizations/703f72a1-…/provisionerdaemons/serve
HTTP/2 400   content-type: text/plain; charset=utf-8   Something is wrong with your CSRF token. …
[17:47:19] withheader POST /api/v2/organizations/703f72a1-…/provisionerdaemons/serve
HTTP/2 405   (no content type, no body: chi has only a GET on /serve)
[17:51:40] forged POST /api/v2/workspaceagents/aws-instance-identity/extra
HTTP/2 400   content-type: text/plain; charset=utf-8   Something is wrong with your CSRF token. …
[17:51:40] withheader POST /api/v2/workspaceagents/aws-instance-identity/extra
HTTP/2 400   content-type: application/json; charset=utf-8   {"message":"Invalid UUID \"aws-instance-identity\".","detail":"invalid UUID length: 21"}
[17:55:48] forged PATCH //api/v2/workspaceagents/me/logs
HTTP/2 400   content-type: text/plain; charset=utf-8   Something is wrong with your CSRF token. …
[17:55:49] withheader PATCH //api/v2/workspaceagents/me/logs
HTTP/2 401   content-type: application/json; charset=utf-8   {"message":"Workspace agent token invalid.","detail":"An agent token must be a valid UUIDv4. (len 33)"}

Each pair is one row of TestCSRFExemptList sent to a live server. The forged half is always text/plain with 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 named me…, no user firstx, 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.

forged POST /api/v2/users/first '{"email":"[email protected]","username":"plat733-first","password":"<random, never printed>"}'
forged PATCH /api/v2/workspaceagents/me/logs '{}'
forged POST /api/v2/workspaceagents/me/log-source '{}'
forged POST /api/v2/workspaceagents/aws-instance-identity '{}'
forged POST /api/v2/workspaceproxies/me/register '{}'
curl -sS -i https://dogfood.cdr.dev/derp | show
curl -sS -i https://dogfood.cdr.dev/derp/latency-check | show
forged POST /scim/v2/Users '{}'
forged POST /api/v2/csp/reports '{"csp-report":{"document-uri":"https://dogfood.cdr.dev/plat733"}}'
[17:57:16] forged POST /api/v2/users/first
HTTP/2 409   content-type: application/json; charset=utf-8   {"message":"The initial user has already been created."}
[17:57:52] forged PATCH /api/v2/workspaceagents/me/logs
HTTP/2 401   content-type: application/json; charset=utf-8   {"message":"Workspace agent token invalid.","detail":"An agent token must be a valid UUIDv4. (len 33)"}
[17:57:52] forged POST /api/v2/workspaceagents/me/log-source
HTTP/2 401   content-type: application/json; charset=utf-8   {"message":"Workspace agent token invalid.","detail":"An agent token must be a valid UUIDv4. (len 33)"}
[17:58:32] forged POST /api/v2/workspaceagents/aws-instance-identity
HTTP/2 400   content-type: application/json; charset=utf-8   {"message":"Validation failed.","validations":[{"field":"signature","detail":"Validation failed for tag \"required\" with value: \"\""},{"field":"document",…}]}
[18:00:18] forged POST /api/v2/workspaceproxies/me/register
HTTP/2 401   content-type: application/json; charset=utf-8   {"message":"Missing required external proxy token"}
[18:00:42] GET /derp
HTTP/2 426   content-type: text/plain; charset=utf-8   DERP requires connection upgrade
[18:00:42] GET /derp/latency-check
HTTP/2 200 
[18:01:23] forged POST /scim/v2/Users
HTTP/2 404   content-type: application/json; charset=utf-8   {"message":"SCIM is disabled, please contact your administrator if you believe this is an error","detail":"SCIM endpoints are disabled if no SCIM is configured. Configure 'CODER_SCIM_AUTH_HEADER' to enable."}
[18:01:59] forged POST /api/v2/csp/reports
HTTP/2 200   content-type: application/json; charset=utf-8   "ok"

The instance identity answer is also a 400, so the content type is what tells it from the middleware: JSON with a validations list is the handler. The /derp 426 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 dropped api/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-Relay was 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.

# after clicking Start in the dashboard
build Bobby-Agent-Relay           # 14 s after the click
build Bobby-Agent-Relay           # 65 s after the click
api /users/me/workspace/Bobby-Agent-Relay | jq -c '.latest_build | {build_number, status, job: {status: .job.status, worker_id: .job.worker_id, completed_at: .job.completed_at}, initiator_name}'
coder list | grep 'bobby/Bobby-Agent-Relay '
agentlogs ab7e4027-8dee-4dac-9dc1-6ead649c4189
api /workspaceagents/ab7e4027-8dee-4dac-9dc1-6ead649c4189/containers | jq -c '{containers: (.containers|length), devcontainers: [.devcontainers[]? | {id, name, status}]}'
coder ssh bobby/Bobby-Agent-Relay -- uptime
coder ping -n 3 bobby/Bobby-Agent-Relay
proxies
coder provisioner list | awk 'NR==1 || /tagged|provisioner/'
api /organizations/703f72a1-76f6-4f89-9de6-8a3989693fe5/provisionerdaemons | jq -r '.[] | select(.id=="a304fb17-131c-482c-9449-d6a383295c80") | [.name, .version, .status] | @tsv'
[18:17:53] Start clicked in the dashboard
[18:18:07] {"build_number":9,"transition":"start","status":"running","worker":"a304fb17-131c-482c-9449-d6a383295c80","agents":[{"name":"dev","id":"ab7e4027-8dee-4dac-9dc1-6ead649c4189","status":"connected"}]}
[18:18:58] {"build_number":9,"transition":"start","status":"running","worker":"a304fb17-131c-482c-9449-d6a383295c80","agents":[{"name":"dev","id":"ab7e4027-8dee-4dac-9dc1-6ead649c4189","status":"connected"}]}
[18:19:09] {"build_number":9,"status":"running","job":{"status":"succeeded","worker_id":"a304fb17-131c-482c-9449-d6a383295c80","completed_at":"2026-11-02T18:18:06.080559Z"},"initiator_name":"bobby"}
  bobby/Bobby-Agent-Relay              coder     Started  true     1m          fbdf21c          false                8h
2026-11-02T18:18:33.56314Z info Note: If you see "shared library" errors when running, use:
2026-11-02T18:18:33.56314Z info   agent-browser install --with-deps
2026-11-02T18:18:33.651551Z info Dashboard started at http://localhost:4848
2026-11-02T18:18:33.651551Z info Success
{"containers":0,"devcontainers":[{"id":"bdb3c179-809d-43bf-ad6d-3174283f6dcc","name":"","status":"stopped"}]}
 18:20:34 up 2 min,  0 users,  load average: 6.67, 7.12, 6.21
pong from bobby/Bobby-Agent-Relay p2p via 64.130.54.176:33227 in 68ms
pong from bobby/Bobby-Agent-Relay p2p via 64.130.54.176:33227 in 71ms
pong from bobby/Bobby-Agent-Relay p2p via 64.130.54.176:33227 in 66ms
primary         ok            2026-11-02T18:22:13.318235Z
unregistered    unregistered  2026-11-02T18:22:11.766160014Z
unhealthy       unreachable   2026-11-02T18:22:11.766160014Z
us-east-2       ok            2026-11-02T18:22:11.766160014Z
af-south-1      ok            2026-11-02T18:22:11.766160014Z
eu-central-1    ok            2026-11-02T18:22:11.766160014Z
ap-southeast-7  ok            2026-11-02T18:22:11.766160014Z
ap-southeast-2  ok            2026-11-02T18:22:11.766160014Z
(17 provisioner daemon rows: 15 idle, 2 busy, none offline, every LAST SEEN AT within the last minute)
coder-provisioner-tagged-7569c59b55-5s7g2	v2.38.5-devel+7801f13692	idle

The job succeeded 13 seconds after the click on a daemon that took it over the provisioner daemon /serve route, whose exemption entry this PR removed; the daemon sends a pre-shared key header and no cookie. The agent's five startup lines arrived by PATCH /api/v2/workspaceagents/me/logs with its own token. The unhealthy and unregistered proxies are other people's test entries and looked the same before the run. The dashboard's POST …/builds was 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 the X-CSRF-TOKEN line on that request is inferred the same way as in scenario 7.

Screen capture: the workspace stopped, before Start

4a-stopped-before-start

Screen capture: the build running after Start

4a-build-running

Screen capture: the agent dev ready, with its apps and gauges

4a-agent-connected

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.

roles derp-plat733            # after the first Confirm
roles derp-plat733            # after the second Confirm
# on the workspace tab, the page's own JavaScript
({ documentCookieNames: document.cookie.split(';').map(c=>c.trim().split('=')[0]).filter(Boolean),
   csrfMetaPresent: !!document.querySelector('meta[property="csrf-token"]'),
   csrfMetaLength: document.querySelector('meta[property="csrf-token"]').content.length })
[18:26:06] Confirm clicked
network log: PUT https://dogfood.cdr.dev/api/v2/users/b0e1d6db-e481-4f91-8b1b-f2d0b94a8cf9/roles  status 200
[18:26:16] ["auditor"]
[18:27:1x] Confirm clicked
network log: PUT https://dogfood.cdr.dev/api/v2/users/b0e1d6db-e481-4f91-8b1b-f2d0b94a8cf9/roles  status 200
[18:27:19] []
documentCookieNames: []
csrfMetaPresent: true
csrfMetaLength: 88

The path carries the UUID, so derp never 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 valid X-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

5a-users-page-filtered

Screen capture: the Edit roles dialog with Auditor ticked, before Confirm

5a-edit-roles-dialog

Screen capture: the row after the first Confirm, Auditor

5a-roles-auditor

Screen capture: the row after the second Confirm, Member again

5a-roles-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.

AGENT=ab7e4027-8dee-4dac-9dc1-6ead649c4189; DC=bdb3c179-809d-43bf-ad6d-3174283f6dcc
dc() { api /workspaceagents/$AGENT/containers | jq -c '.devcontainers[] | {id, name, status, container: (.container.id // null)}'; }
dc
forged POST /api/v2/workspaceagents/$AGENT/containers/devcontainers/$DC/recreate
sleep 5; dc
# click Start on the dev container card, then watch every 5 s until running
[18:30:05] {"id":"bdb3c179-809d-43bf-ad6d-3174283f6dcc","name":"","status":"stopped"}
[18:30:05] forged POST /api/v2/workspaceagents/ab7e4027-…/containers/devcontainers/bdb3c179-…/recreate
HTTP/2 400 
content-type: text/plain; charset=utf-8
Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies.
[18:30:11] {"id":"bdb3c179-809d-43bf-ad6d-3174283f6dcc","name":"","status":"stopped"}
[18:30:23] Start clicked on the dev container card
network log: POST https://dogfood.cdr.dev/api/v2/workspaceagents/ab7e4027-8dee-4dac-9dc1-6ead649c4189/containers/devcontainers/bdb3c179-809d-43bf-ad6d-3174283f6dcc/recreate  status 202
[18:30:31] {"id":"bdb3c179-…","name":"","status":"starting","container":null}
[18:32:47] running container=f35bdc907ac2f90476ac6a90598b0d59dab8895a5247da8bb3f8b266611b5118 running

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

5c-devcontainer-before-start

Screen capture: the card right after Start, spinner on the button

5c-devcontainer-starting

Screen capture: the dev container running, with its own apps and a Rebuild button

5c-devcontainer-running

9. The PR's own tests at the squash commit
cd ~/work/coder-upstream-1 && git status --porcelain
git checkout -q 0fd07754f509544df6f8e9e1c12e0e64c68557af && git log -1 --format='%h %s'
go test ./coderd/httpmw/ -run 'TestCSRFExemptList|TestCSRFError' -count=1 -v 2>&1 | grep -cE '^\s*--- PASS'
go test ./coderd/httpmw/ -run 'TestCSRFExemptList|TestCSRFError' -count=1 -v 2>&1 | grep -cE '^\s*--- FAIL'
go test ./coderd/httpmw/ -run 'TestCSRFExemptList|TestCSRFError' -count=1 2>&1 | tail -1
grep -n 'ExemptRegexp(regexp.MustCompile(' coderd/httpmw/csrf.go | grep -vF 'MustCompile(`^' || echo "no unanchored pattern"
git checkout -q main
0fd07754f5 fix(coderd/httpmw): anchor CSRF exemption patterns (#31125)
39
0
ok  	github.com/coder/coder/v2/coderd/httpmw	1.660s
no unanchored pattern

The 39 are the 33 TestCSRFExemptList sub-tests, the 4 TestCSRFError sub-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, CSPReports and FormerlyExemptPath.

10. Cleanup
roles derp-plat733
coder users delete derp-plat733
api /users/derp-plat733 | jq -c '{message}'
coder tokens remove plat733-run
coder tokens list | grep -c plat733 || echo "no plat733 token listed"
api /users/me | jq -r '.username // .message'
rm -P /tmp/plat733/token
grep -rl "<first 10 characters of the token>" /tmp/plat733/logs && echo "TOKEN ID IN A LOG" || echo "no token id in any log"
[]
{"message":"Resource not found or you do not have access to this resource"}
Token has been expired.
0
no plat733 token listed
You are signed out or your session has expired. Please sign in again to continue.
no token id in any log

The workspace was left running with its dev container up.

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.
@linear-code

linear-code Bot commented Oct 21, 2026

Copy link
Copy Markdown

PLAT-733

@BobbyHo

BobbyHo commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review Please limit the review to P0, P1, and P2 issues only.

@coder-agents-review

coder-agents-review Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Chat: Review posted | View chat
Requested: 2026-10-21 16:06 UTC by @BobbyHo

Review history
  • R1 (2026-10-21): 12 reviewers, 1 P2, COMMENT. Review
  • R2 (2026-10-21): 8 reviewers, 1 P2, APPROVE. Review

deep-review v0.13.0 | Round 2 | 7253bd1..87bbc89

Last posted: Round 2, 1 findings (1 P2), APPROVE. Review

Finding inventory

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P3 Dropped by orchestrator (below requester's P0-P2 limit) csrf.go:59 `^/derp(/ $)` regexp never changes the exempt result R1 Netero
CRF-2 Note Dropped by orchestrator (below requester's P0-P2 limit) csrf.go:55 No test rows for azure/google identity, bare /me, bare /provisionerdaemons R1 Netero No
CRF-3 P2 Author fixed (73c57c7) csrf.go:61 provisionerdaemons prefix exemption covers a cookie-authenticated subtree; future mutations silently exempt R1 Meruem P3, Hisoka P3, Kite P3, Bisky P3, Mafuuu P4, Pariston Note, Ryosuke Note Yes
CRF-4 P3 Dropped by orchestrator (below requester's P0-P2 limit) csrf.go:47 Anchoring rule enforced only by comment; most anchor removals pass tests R1 Ryosuke P3, Bisky P3, Pariston P4, Mafuuu Note No
CRF-5 P3 Dropped by orchestrator (empirically disproved: singleSlashMW routes chi on decoded Path, scratch test returned 404) csrf.go:61 Regex on decoded Path vs chi routing on RawPath R1 Kurapika P3, Bisky P3, Meruem P4, Melody Note, Hisoka Note No
CRF-6 P3 Dropped by orchestrator (below requester's P0-P2 limit) csrf_test.go:303 Description and FormerlyExemptPath model a cross-origin PUT that CORS preflight blocks; real vector is same-site POST R1 Pariston P3, Leorio P3 No
CRF-7 P3 Dropped by orchestrator (below requester's P0-P2 limit) csrf.go:53 "Agent authenticated routes" label now covers unauthenticated instance-identity routes R1 Gon P2 No
CRF-8 P3 Dropped by orchestrator (below requester's P0-P2 limit) csrf.go:47 Anchoring comment omits when patterns apply; past-tense derp example R1 Leorio P3, Gon P2, Leorio Nit No
CRF-9 OOS Dropped by orchestrator (pre-existing unchanged labels; requester limited review to P0-P2) csrf.go:56 Restating labels for proxy, derp, provisioner entries R1 Gon P2 No
CRF-10 Nit Dropped by orchestrator (below requester's P0-P2 limit) csrf_test.go:140 Test comments reference removed patterns or list untested clients R1 Gon P2, Leorio Nit No
CRF-11 Nit Dropped by orchestrator (below requester's P0-P2 limit) csrf_test.go:106 Row naming and repeated UUID literal R1 Gon Nit No
CRF-12 P4 Dropped by orchestrator (below requester's P0-P2 limit) csrf_test.go:300 FormerlyExemptPath duplicates a row; rejection comes from origin check R1 Bisky No
CRF-13 Nit Dropped by orchestrator (below requester's P0-P2 limit) csrf.go:52 Exact paths written as regexps instead of ExemptPaths R1 Mafuuu No
CRF-14 Note Dropped by orchestrator (below requester's P0-P2 limit) PR body "Refs PLAT-733" vs commit "Fixes" with SEC tickets R1 Leorio No
CRF-15 OOS Dropped by orchestrator (requester limited review to P0-P2) csrf.go:17 CSRF doc comment names nonexistent enforce parameter R1 Mafuuu, Gon No
CRF-16 OOS Dropped by orchestrator (requester limited review to P0-P2) csrf.go:43 Comment now annotates only the ExemptPath call R1 Gon No
CRF-17 OOS Dropped by orchestrator (requester limited review to P0-P2) csrf.go:23 Failure message tells users to refresh on origin rejection R1 Kite No
CRF-18 P3 Dropped by orchestrator (below requester's P0-P2 limit) PR body Description still lists the removed provisioner daemon exemption as kept R2 Netero No
CRF-19 Nit Dropped by orchestrator (below requester's P0-P2 limit; comment wording, no behavior consequence) csrf_test.go:135 Test comment second sentence restates Exempt: false R2 Gon P2 No

Contested and acknowledged

Round log

Round 1

Netero 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:

  • CRF-5 dropped. Keep-argument: five reviewers reproduced exempt=true with a decoded-path match routed elsewhere. Drop reason: all repros used a bare chi router. Production coderd runs singleSlashMW (coderd.go:2673) on the root router, which sets rctx.RoutePath from decoded r.URL.Path; a scratch test with singleSlashMW and PUT /api/v2/organizations/x%2Fprovisionerdaemons/members/derp/roles returned 404. wsproxy has no cookie-authenticated non-GET /api routes.
  • CRF-3 raised to P2 on convergence. Seven reviewers flagged the same line. The PR rewrote this line, anchored it, and added a test row asserting POST under the prefix stays exempt, which pins a prefix exemption over a session-cookie subtree (apiKeyMiddleware at coderd.go:1557). The same mechanism produced the dev container exemption this PR fixes. Wrong but survivable today: P2.
  • CRF-6: CORS preflight claim confirmed in cors.go (standardCors allows only GET/OPTIONS; AllowAllCors keeps the same methods). P3, documentation and test realism; code fix is unaffected.
  • CRF-7, CRF-8, CRF-10 downgraded from Gon's P2. Keep-argument: comments in a security exemption list are the only record of why each entry is safe. Downgrade reason: none of the comment errors leads a reader to an unsafe change; instance-identity routes read no session cookie.

Reviewed against c61d842..6ec1986.

Round 2

Churn 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 ProvisionerDaemonsServe.

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.

Reviewed against 7253bd1..87bbc89.

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Komugi flake/determinism
Kurapika security
Law decomposition
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread coderd/httpmw/csrf.go Resolved
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.
@BobbyHo

BobbyHo commented Oct 21, 2026

Copy link
Copy Markdown
Collaborator Author

/coder-agents-review Please limit the review to P0, P1, and P2 issues only.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@BobbyHo
BobbyHo marked this pull request as ready for review October 21, 2026 16:19
@BobbyHo
BobbyHo requested review from a team and Emyrk October 21, 2026 16:19

@Emyrk Emyrk left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@BobbyHo
BobbyHo marked this pull request as draft October 23, 2026 16:21
@BobbyHo

BobbyHo commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator Author

I'm going to hold off on merging this PR until after the next release. Please leave it unmerged for now. Thanks!

@BobbyHo
BobbyHo marked this pull request as ready for review October 28, 2026 18:08
@BobbyHo
BobbyHo merged commit 0fd0775 into main Oct 28, 2026
51 of 53 checks passed
@BobbyHo
BobbyHo deleted the bobby/plat-733-anchor-csrf-exemption-patterns branch October 28, 2026 18:16
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 28, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants