mirror of
https://github.com/coder/coder.git
synced 2026-11-22 03:18:31 +08:00
25af21b5d5d86ab7d9253e1e72d33b2da170e4f8
46
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
1818844069 |
fix: ignore unrecognized parameters at the token endpoint (#29139)
fix(oauth2): ignore unrecognized token request parameters Align `/oauth2/tokens` with OAuth 2.1 §3.2 and `/oauth2/authorize` by ignoring unknown parameters and logging only their names at debug level, never values. Continue rejecting duplicate known parameters, with tests covering all nine and shared unknown-parameter inputs across both endpoints. Misspelled optional parameters are now ignored rather than returning 400. Changes are limited to `coderd/oauth2provider`, with no new endpoints or schema changes. Closes https://linear.app/codercom/issue/PLAT-577 |
||
|
|
716a3fdbfd |
fix: match OAuth2 redirect_uri against every registered redirect URI (#29014)
- Fix OAuth2 redirect validation to accept any registered URI, resolving Cursor’s rejection when using its second callback (fixes #28910; stacked on #29013). - Deduplicate primary and alternate callbacks, validate every registered entry, preserve primary-callback defaults and existing code-to-token redirect checks, and stop exposing registered URLs in errors. - Add regression tests and update documentation; defer admin removal of registered URIs (PLAT-619) and requiring redirect_uri when multiple URIs are registered (PLAT-620) to follow-ups. |
||
|
|
9f27e2b17c |
feat: let an OAuth2 refresh narrow the granted scope (#28751)
fix: honor scope narrowing on OAuth2 token refresh Allow `POST /oauth2/tokens` to mint an access token with the requested scope when covered by the consented grant. Narrowing affects only the new access token; the stored grant and rotated refresh token scope remain unchanged. Omitting `scope` uses the full grant. Validate scope names against the catalog, then compare permission coverage rather than set membership so `coder:all` grants can narrow. Reject unknown or uncovered scopes with `400 invalid_scope` without minting tokens or consuming the refresh token. Refresh still does not re-check the app's current allowlist. - Sanitize and cap token endpoint `error_description`, sharing the authorize path's length limit. - Rename the scope-coverage log field `allowlist` to `ceiling` and add `phase=refresh`. - Update provider docs for scoped refreshes, `invalid_scope`, composite scope caveats, and OAuth 2.1 draft -16. Part 1 of 3 for PLAT-481, the final phase of PLAT-470. |
||
|
|
0ad8eebbf7 |
fix: allow any port on loopback OAuth2 redirect URIs (#29013)
Fix: Allow variable ports for registered HTTP loopback redirect URIs (127.0.0.1, [::1], and localhost), enabling native apps to use dynamically assigned ports. Apply this registration-matching exception at both authorization and token endpoints while preserving the presented port. Safeguards: Keep all other URI components and non-loopback matching unchanged, and retain exact code-to-token redirect URI matching, including the port. Implementation and verification: Add shared matching logic, automated tests, and updated documentation. All 29 manual scenarios passed, although browser click-through to a listener on an OS-chosen port was not tested. |
||
|
|
96ee8d171a |
fix: make OAuth2 code redemption single-use under concurrency (#28744)
TL;DR Third PR in the PLAT-480 stack, on top of #28740. Fixes a race where the same authorization code could be redeemed twice concurrently. The redeeming delete now returns the deleted row. If another request already redeemed the code, the delete returns sql.ErrNoRows and redemption fails with invalid_grant. Each redemption runs in its own transaction, so concurrent requests serialize on the code row and only one succeeds. The test now races two concurrent redemptions to verify single-use behavior. No scope logic, new endpoints, or schema changes. Depends on #28740. Stack: #28237, #28740, this PR. |
||
|
|
07f9018c61 |
feat: re-check the app allowlist at OAuth2 code redemption (#28740)
**TL;DR** Second of the PLAT-480 stack. #28237 made the negotiated scope bound the issued token; this PR makes a narrowing of an app's registered scopes apply to codes that were already issued. | PR | What it does | |---|---| | #28237 (merged) | Mints access tokens with the negotiated scope, so a grant for one scope stops behaving as full access, and reports the granted scope per RFC 6749 §5.1. | | **#28740 (this)** | Re-checks the code's scope against the app's registered scopes at redemption, closing the ten minute window in which a narrowing was ignored. | | #28744 | Makes code redemption single-use under concurrency. Carries no scope logic and is independent of this PR. | - #28237 has merged, so this targets main. - No new endpoints and no schema change. --- An authorization code is valid for ten minutes, and its scope is checked against the app's registered scopes exactly once, when the code is issued. A registration narrowed inside that window had the narrowing ignored: the code still redeemed for a token carrying the wider scope. - The token exchange re-checks the code's scope against the registration as it stands at redemption and refuses with `invalid_grant`. RFC 6749 §5.2 reserves `invalid_scope` for the scope the client asked for, and this one comes from the stored grant. - The check is coverage rather than membership, and reuses the comparison the authorize endpoint already runs. That comparison now goes through a new `rbac.FirstScopeNotCovered`, which expands the allowlist once rather than once per granted scope. - Only the client can change its registered `scope`, through RFC 7592; no administrator surface writes the column. The re-check reflects the registration at redemption rather than constraining the client. - Refresh keeps the scope originally granted. That is a product choice, not an RFC requirement: a narrowing applies at the next authorization rather than mid-session, so tightening an app's scopes does not break integrations already running. - Codes issued before migration 000569 carry `coder:all`. For an app registered with a narrower `scope` those are refused at redemption until they expire, at most ten minutes. Stack: #28237 (merged), this PR, #28744. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
68ca033d67 |
fix: deliver the rest of the invalid_request class to the client (#28736)
**TL;DR** Fifth of the stack, split out of #28045. #28450 delivered the errors raised *after* the callback is trusted and left the parameter failures behind. This PR delivers those, and replaces the implicit ordering that decided where an answer went with an explicit classification. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. | | #28178 | The authorize endpoint negotiates the scope against the app's allowlist and persists it on the code. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's callback. | | #28450 | The same delivery for every other error raised once the callback is trusted. | | **#28736 (this)** | The parameter failures #28450 left behind, and the classification that decides where each answer goes. | - Stacked on #28450. Review that first. - Nothing about what a token can do changes here. This is delivery, not enforcement. **Contract change** A rejected parameter now arrives at the app's registered callback with `error=invalid_request`, a description naming every failing field, and the request's `state`. Both verbs. | Verb | Was | |---|---| | GET | static "Invalid Query Parameters" page, 400 | | POST | `WriteOAuth2Error`, 400 | An integrator watching for either now reads the error from its own callback instead. **Two failures still answer on Coder**, because in neither case is the callback trustworthy yet: - A `redirect_uri` that does not parse, or does not exactly match the registration. Redirecting to it would defeat the check that just rejected it. - A `client_id` sent more than once, or naming something other than the app the callback was matched against. Coder cannot tell whose registration it is about to redirect to. An absent query `client_id` is **not** in that group. `httpmw` also reads the POST form body and the §2.3.1 Basic credential, so an absent query parameter still names a client and its failure is deliverable. **Precedence change.** An app whose *registered* callback does not parse, or uses a rejected scheme, now answers 500 even when the request also carries parameter errors; that used to answer 400. Decided before any parameter is read, so the others are never detected. Only reachable for an app row that bypassed registration. `DangerousCallbackSchemeOutranksParseFailure` pins it. **Also in this PR** - **Unrecognized parameters are ignored**, as §3.1 requires, rather than rejected by `ErrorExcessParams`. An OIDC `nonce` or a vendor extension no longer fails the request. Repeats of parameters the endpoint does read are still rejected. - **Every unsupported `response_type` gets one code.** Read as text rather than through the SDK enum, so a value with no Go constant behind it answers `unsupported_response_type` like `token` does, instead of splitting on whether the SDK names it. - **A malformed `resource` answers `invalid_target`** (RFC 8707 §2), but only when nothing else failed. A client retrying on `invalid_target` would otherwise resend a request still broken in a field it never heard about. - **`error_description` is bounded and readable.** Capped at 2048 characters and marked `(truncated)` before the log field or the `Location` header is written. Entries read `field: reason` joined with `; `, not the parser's debug shape, whose details contain commas and cannot be split apart again. - **A repeated `state` is charged to the client, not the callback.** Reading `state` shares a function with the `redirect_uri` match, so it used to fall into that carve-out and answer on Coder. **Where in the OAuth Flow** <details> <summary>Diagram: the three-way dispatch, and what licenses a redirect</summary> ```mermaid flowchart TD NEW["newAuthorizeResponse<br/>parses the registered callback, checks its scheme,<br/>exact-matches any redirect_uri, reads state"] NEW -->|"registration unusable"| C500["500 on Coder<br/>server_error, value logged not echoed"] NEW --> PARSE["extractAuthorizeParams<br/>reads every parameter, collects all failures"] PARSE -->|"no failure"| OK["GET: consent page<br/>POST: authorization code"] PARSE -->|"failure"| KIND{"authorizeFailure.kind()"} KIND -->|"corrupt registration"| C500 KIND -->|"redirect_uri or client_id at fault"| CODER["400 on Coder<br/>RFC 6749 4.1.2.1 carve-out"] KIND -->|"anything else"| CLIENT["302 to the callback<br/>invalid_request or invalid_target, with state"] ``` </details> - Authorize endpoint only, both verbs. Token exchange, refresh, and revocation are untouched, and `ErrorExcessParams` still guards the token endpoint. - `validatedCallbackURL` becomes `authorizeResponse`, built only by `newAuthorizeResponse`, which runs the scheme check and the exact match in that order. Holding one is what licenses a redirect, so the ordering is structural rather than a convention each call site remembers. - The scheme is checked on the *registered* URL, since `p.RedirectURL` returns the client's URI on a mismatch and checking that would blame the app for a request it never made. - `state` moves onto the type, out of the parameter lists of `withQuery`, `errorURL`, `codeURL`, and `redirectAuthorizeError`, so no call site can emit a response the client cannot correlate. - `extractAuthorizeParams` returns one `authorizeFailure` instead of two trailing values, and both handlers dispatch on `kind()` rather than re-deriving precedence from field checks. **What it satisfies** - RFC 6749 §4.1.2.1: a failure that is not a bad redirection URI or client identifier is reported through the redirection URI. That is the whole PR. Its two exceptions "MUST NOT" be redirected to, hence the carve-outs. - RFC 6749 §3.1: unrecognized parameters MUST be ignored, and no parameter may appear more than once. Both now hold here. - RFC 6749 Appendix A: `error_description` is confined to the permitted set, on the decoded value. - RFC 8707 §2: a `resource` that is not an absolute URI without a fragment answers `invalid_target`. - RFC 7636 §4.4.1: a malformed `code_challenge` is rejected at the authorization request rather than deferred to token exchange, where the error would point at the `code_verifier`. - Not yet: CRF-26 (the `server_error` sites) and CRF-13 (fragment delivery), both as in #28450. **Docs and Swagger.** `docs/admin/integrations/oauth2-provider.md` gains entries for the redirected parameter errors, `invalid_target`, and the two failures that stay on Coder. Both authorize verbs document their 400 and 500 responses and stop advertising `response_type=token`, which meant declaring the parameter as a `string`, since `Enums` appends to what swaggo derives from the type. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Fifth of the stack, stacked on #28450. ## Manual Tests Verified by hand against a local dev deployment (`v2.37.0-devel+1145d35a47`, dev Postgres), in addition to the automated suite. The build string was checked first, because `develop.sh` builds from whatever the tree held when it started and every result below would otherwise be describing the wrong binary. Two scenario groups need state the API cannot produce. The scope allowlist is reachable only through dynamic client registration, which was enabled for the run and disabled again at the end. A registered callback that does not parse, or that uses a blocked scheme, is refused at registration, so those rows were planted directly with `psql` on a purpose-built client and restored afterwards. **28 scenarios, all passing.** No correctness or security defect was found in the code this PR changes. Seven observations came out of the run: six are consistency, documentation or diagnosability points, and one is a small defect that predates this PR. <details> <summary><b>Scenario summary, all 28</b></summary> | # | Scenario | Result | |---|----------|--------| | 1 | A well-formed request still succeeds on both verbs, and the consent page renders | Pass | | 2 | A rejected parameter now reaches the client's callback on `POST` | Pass | | 3 | The same on `GET`, and the consent page does not render first | Pass | | 4 | The description names every failing field, joined with `; ` | Pass | | 5 | A mismatched `redirect_uri` is answered on Coder with no `Location` on either verb | Pass | | 6 | An unparseable `redirect_uri` likewise, and the echoed value is HTML escaped | Pass | | 7 | A repeated `client_id` is answered on Coder although the callback was valid | Pass | | 8 | A single query `client_id` cannot disagree with the resolved app over HTTP | Pass | | 9 | A `client_id` supplied only in the `POST` form body is delivered, not withheld | Pass | | 10 | A `{UPPERCASE}` `client_id` is delivered, and also succeeds end to end | Pass | | 11 | A repeated `state` is delivered rather than charged to the redirect carve-out | Pass | | 12 | A registered callback with a blocked scheme answers 500 on both verbs | Pass | | 13 | An unparseable registered callback answers 500, indistinguishably to the caller | Pass | | 14 | Corrupt registration outranks a deliverable failure and both carve-outs | Pass | | 15 | The corrupt value is logged with the app ID and never appears in a response | Pass | | 16 | Restoring the row restores normal behaviour with no restart | Pass | | 17 | Every unsupported `response_type` gets one code; an empty one is `invalid_request` | Pass | | 18 | An unsupported `response_type` is not recast as a missing `code_challenge` | Pass | | 19 | Unrecognized parameters are ignored, including a case-variant `REDIRECT_URI` | Pass | | 20 | A misspelled `redirect_url` is ignored and cannot smuggle a destination | Pass | | 21 | Repeated known parameters are still rejected | Pass | | 22 | `resource` answers `invalid_target` alone and `invalid_request` in company | Pass | | 23 | A fragment in `resource` is rejected | Pass, with one gap | | 24 | A long description is capped at 2048 and marked `(truncated)`, on both verbs | Pass | | 25 | The description is sanitized to the RFC 6749 §4.1.2.1 character set | Pass | | 26 | The registered callback query is retained except the reserved names | Pass | | 27 | Scope rejections still reach the callback, and no consent page renders | Pass | | 28 | Declining consent carries `access_denied` and issues no code | Pass | </details> <details> <summary><b>Observations, all 7</b></summary> | # | Observation | Severity | |---|-------------|----------| | 1 | `invalid_request` is returned in three description shapes: the parser's `Invalid query params: field: reason; ...` aggregate, the PKCE validator's single message, and `scopeFailureResponse`'s. A client cannot parse all three with one rule. | Consistency, reviewer call | | 2 | The phase 2 runbook for #28045 asserts the old `field: x detail: y` message shape, which this PR replaces. That doc needs a one-line update. | Docs follow-up | | 3 | `clientIDInDoubt`'s `default` branch is unreachable over HTTP, because `httpmw` derives `app.ID` from the same query value the parser reads. Defensive rather than dead, but the comment does not say so. | Comment clarity | | 4 | A `POST` supplying `client_id` only in the form body always fails with `client_id ... is required and cannot be empty`, naming a parameter it did supply. `httpmw` reads the body, `RequiredNotEmpty` reads the query. Pre-existing. | Misleading diagnostic | | 5 | A misspelled parameter is invisible from every angle at default verbosity. The client gets a 302 with a code, its redirect is silently replaced by the registered one, and the `ignoring unrecognized authorization parameters` line is `logger.Debug` so it is not emitted. | Diagnosability | | 6 | `resource` sent twice answers `invalid_target` rather than `invalid_request`. RFC 8707 §2 frames `invalid_target` as being about the resource value; a duplicated parameter is a malformed request under RFC 6749 §3.1. | Low, error code choice | | 7 | `resource=https://api.example.com/#` (trailing `#`, empty fragment) is accepted and stored with the `#` intact, so the persisted audience is not textually equal to the fragment-free form. `url.Parse` maps empty and absent fragments both to `Fragment == ""`. Pre-existing, in `tokens.go`. | Defect, low severity | </details> **One note for anyone re-running this.** Every request below depends on `$CHALLENGE` from the most recent `new_pkce` call. Forgetting to call it sends an empty `code_challenge`, which fails with the fixed "is required and cannot be empty" message at 98 characters and looks exactly like a cap or a validator failing to fire. That cost one wrong measurement during this run before the numbers below were taken. <details> <summary><b>Shell helpers used throughout</b></summary> ```bash export BASE_URL=http://localhost:3000 export AUTH_HEADER="Coder-Session-Token: $(cat ./.coderv2/session)" export PGPASSWORD=$(cat ./.coderv2/postgres/password) export PGPORT=$(cat ./.coderv2/postgres/port) pg() { psql -h localhost -p "$PGPORT" -U coder -d coder -tAc "$1"; } plant_callback() { pg "UPDATE oauth2_provider_apps SET callback_url = '$2' WHERE id = '$1';"; } urlenc() { jq -rn --arg v "$1" '$v|@uri'; } # 43 unreserved characters every time. Base64url of the raw 32 bytes. new_pkce() { VERIFIER=$(openssl rand 32 | base64 | tr -d '\n=' | tr '+/' '-_') CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_') STATE=$(openssl rand -hex 16) } authz_url() { local url="$BASE_URL/oauth2/authorize?client_id=$1&response_type=code" url="$url&redirect_uri=$(urlenc "$2")&state=$STATE" url="$url&code_challenge=$CHALLENGE&code_challenge_method=S256" printf '%s' "$url" } # The core assertion of the whole run: what answer, delivered where. answer() { curl -s -o /dev/null -D - -X "$1" "$2" -H "$AUTH_HEADER" | grep -iE '^HTTP/|^location:'; } show_callback() { python3 - "$1" <<'PY' import sys, urllib.parse q = urllib.parse.urlparse(sys.argv[1]).query for k, v in urllib.parse.parse_qsl(q, keep_blank_values=True): print(f"{k} = {v}") PY } ``` Fixtures, all registered through DCR: ```text plat479-plain http://localhost:9876/callback plat479-query http://localhost:9876/callback?tenant=acme&error=stale plat479-corrupt http://localhost:9876/callback (overwritten by psql in 12 to 16) plat479-reserved http://localhost:9876/callback?tenant=acme&code=FAKECODE&error=stale&error_description=oldmsg&state=oldstate&keep=yes plat479-ci http://localhost:9876/callback (scope allowlist coder:workspaces.access) ``` </details> <details> <summary><b>1. Baseline: a well-formed request still succeeds</b></summary> ```bash new_pkce; answer GET "$(authz_url "$APP_ID" http://localhost:9876/callback)" new_pkce; answer POST "$(authz_url "$APP_ID" http://localhost:9876/callback)" ``` ```text === GET === HTTP/1.1 200 OK === POST === HTTP/1.1 302 Found Location: http://localhost:9876/callback?code=coder_dzvaCPf9W1_...&state=e321bd5d5b594a1fae8a2d5da654b84a ``` `GET` carries no `Location` at all, so the consent page really rendered rather than redirecting. The `state` echoed is the one sent. The code persisted as `coder:all`, this app having no allowlist, with `redirect_uri` recorded because the request supplied one. Also driven through a real browser rather than curl, so the consent form's `nosurf` token is the one submitted rather than the session-token header alone. Clicking **Allow** delivered `code` and `state` to the callback. Both request shapes agree on the success case. Not to be misread: `oauth2_provider_app_codes` holds one row after both POSTs, not two. `ProcessAuthorize` opens its transaction with `DeleteOAuth2ProviderAppCodesByAppAndUserID`, so a row count is not a count of successful authorizations. That predates this PR. </details> <details> <summary><b>2 to 4. A rejected parameter now reaches the client's callback</b></summary> ```bash new_pkce BAD="$BASE_URL/oauth2/authorize?client_id=$APP_ID&response_type=code" BAD="$BAD&redirect_uri=$(urlenc http://localhost:9876/callback)&state=$STATE" BAD="$BAD&code_challenge=short&code_challenge_method=S256" answer POST "$BAD" answer GET "$BAD" ``` ```text HTTP/1.1 302 Found Location: http://localhost:9876/callback?error=invalid_request&error_description=Invalid+query+params%3A+code_challenge%3A+must+be+43+to+128+characters+from+the+unreserved+character+set+%5BA-Za-z0-9-._~%5D&state=e89f4d98d4c8c347e5ae25175748b731 ``` Identical on both verbs. Decoded: ```text error = invalid_request error_description = Invalid query params: code_challenge: must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~] state = e89f4d98d4c8c347e5ae25175748b731 ``` The `GET` body confirms no page was rendered, against the baseline: | Request | Body size | Occurrences of "Allow" | |---|---|---| | Malformed `code_challenge` | 263 bytes | 0 | | Well formed (scenario 1) | 4928 bytes | 2 | 263 bytes is Go's redirect stub. There is no consent form in it, so there is no Allow button to press for a request the server has already refused. Multiple failures are reported together (scenario 4): ```text error_description = Invalid query params: code_challenge: must be 43 to 128 characters from the unreserved character set [A-Za-z0-9-._~]; resource: must be an absolute URI without fragment ``` The separator is `; `, and no entry uses the older `field: x detail: y` shape. The code is `invalid_request` rather than `invalid_target` even though `resource` is one of the two failures, which is the scenario 22 guard firing. The same request also carried `code_challenge_method=plain`, which is invalid and is *not* mentioned, because the method is validated after `extractAuthorizeParams` returns and a parse failure short-circuits first. Sent alone it is rejected as `code_challenge_method 'plain' is not supported; use 'S256'`, with no `Invalid query params: ` prefix. That difference is observation 1. </details> <details> <summary><b>5 and 6. The redirect_uri carve-out keeps the answer here</b></summary> ```bash new_pkce EVIL="$BASE_URL/oauth2/authorize?client_id=$APP_ID&response_type=code" EVIL="$EVIL&redirect_uri=$(urlenc http://evil.example/steal)&state=$STATE" EVIL="$EVIL&code_challenge=$CHALLENGE&code_challenge_method=S256" answer POST "$EVIL"; answer GET "$EVIL" ``` ```text HTTP/1.1 400 Bad Request HTTP/1.1 400 Bad Request ``` **The absence in that output is the assertion**: no `Location` on either verb, so nothing redirects to `evil.example`. Stronger, `evil.example` appears zero times in either full response, headers and body together, so the attacker-supplied host is not reflected into the page either. ```json {"error":"invalid_request","error_description":"Invalid query params: redirect_uri: Query param \"redirect_uri\" must exactly match http://localhost:9876/callback"} ``` The `GET` page names the *registered* callback as the value the parameter had to match, which is the app's own configuration and safe to display. An unparseable `redirect_uri` reaches the same outcome by a different route, having never parsed at all: ```json {"error":"invalid_request","error_description":"Invalid query params: redirect_uri: Query param \"redirect_uri\" must be a valid url: parse \"http://%zz\": invalid URL escape \"%zz\""} ``` That message echoes the caller's value, unlike the mismatch case, so the `GET` path was probed with markup in it: ```text input: http://%zz"><img src=x onerror=BAD> page: ...must be a valid url: parse "http://%zz\"><img src=x onerror=BAD>"... literal `<img` in body: 0 entity encoded `<img`: 1 ``` Escaped correctly by the template layer. Recorded as a negative result so a future change to the error page has something to regress against. One note for the docs: this detail contains colons, so a client splitting `field: reason` entries must split each on its **first** colon only. </details> <details> <summary><b>7 to 10. The client_id carve-out, and its negatives</b></summary> A repeated `client_id` in an otherwise perfect request: ```text HTTP/1.1 400 Bad Request (both verbs, no Location) {"error":"invalid_request","error_description":"Invalid query params: client_id: Query param \"client_id\" provided more than once, found 2 times. Only provide 1 instance of this query param."} ``` This is the one carve-out not implied by the response's shape. The `redirect_uri` matched the registration, so `canRedirect()` was true and there *was* somewhere to send the answer; it was withheld because `extractAuthorizeParams` assigns `failure.redirect` only when `clientIDInDoubt` is false. **The `default` branch of that function is unreachable over HTTP** (observation 3). `httpmw` resolves the app from `r.URL.Query().Get("client_id")`, so `app.ID` and the parsed value derive from the same string and cannot disagree. Three experiments: ```text one query client_id, bad challenge -> 302 delivered two DIFFERENT client_id values -> 400, caught by the repeated branch query names app A, form body names app B -> 302 to app A; the body is ignored ``` The negatives matter as much as the positives. An identifier absent from the query but present in the `POST` form body is **delivered**, correctly: ```text HTTP/1.1 302 Found Location: ...error=invalid_request&error_description=Invalid+query+params%3A+client_id%3A+...is+required+and+cannot+be+empty%3B+code_challenge%3A+... ``` That is observation 4: the description says `client_id` is required for a request that supplied it. With everything else valid the same shape still fails, while the identical request carrying `client_id` in the query succeeds with a code. `RequiredNotEmpty` reads the query; `httpmw` reads the body. Pre-existing, and arguably the parser is the layer in the right, since RFC 6749 §4.1.1 puts authorization parameters in the query string and §3.2.1 is the endpoint that uses a form body. A braced upper-case UUID is delivered, and succeeds end to end: ```text {UPPERCASE} client_id, bad challenge -> 302, description names ONLY code_challenge {UPPERCASE} client_id, all valid -> 302 with a real code GET, all valid -> 200, consent page, heading resolves to the app's real name ``` `uuid.Parse` accepts that spelling and `httpmw` resolved through it, so a string comparison here would withhold an answer the client is entitled to, for no reason it could diagnose. </details> <details> <summary><b>11. A repeated state is delivered, not withheld</b></summary> ```text HTTP/1.1 302 Found (both verbs) error = invalid_request error_description = Invalid query params: state: Query param 'state' provided more than once, found 2 times. Only provide 1 instance of this query param. ``` Reading `state` happens inside `newAuthorizeResponse`, the same function that runs the `redirect_uri` match. A count of errors across those two lines would charge this to the redirect carve-out and answer 400. It answered 302, so the field-specific test is doing the work. The asymmetry with scenario 7 is deliberate: a repeated `client_id` leaves the server unsure whose callback it holds, a repeated `state` leaves the callback fully settled. The response carries **no `state`**, since `parseSingle` collapsed the repeat to the empty string and `withQuery` only sets it when non-empty. Unavoidable rather than wrong: picking one of two values could satisfy a CSRF check the client meant to be strict. </details> <details> <summary><b>12 to 16. A corrupt registration outranks everything</b></summary> DCR refuses both planted values, which is why `psql` is needed and why 500 is the right answer: a stored one is not something a client did. ```json {"error":"invalid_client_metadata","error_description":"invalid redirect_uris: redirect URI at index 0: redirect URI uses dangerous scheme javascript which is not allowed"} {"error":"invalid_client_metadata","error_description":"invalid redirect_uris: redirect URI at index 0 is not a valid URL: parse \"http://%zz\": invalid URL escape \"%zz\""} ``` ```bash plant_callback "$APP_CORRUPT_ID" 'javascript:alert(1)' new_pkce CORRUPT="$BASE_URL/oauth2/authorize?client_id=$APP_CORRUPT_ID&response_type=code&state=$STATE" CORRUPT="$CORRUPT&code_challenge=$CHALLENGE&code_challenge_method=S256" answer POST "$CORRUPT"; answer GET "$CORRUPT" ``` ```text HTTP/1.1 500 Internal Server Error {"error":"server_error","error_description":"The application's registered callback URL is not usable"} GET: HTTP/1.1 500, page reads "500 - Invalid Callback URL", 3346 bytes, 0 Allow buttons ``` The unparseable callback is **indistinguishable to the caller**: same description, and a `GET` page of exactly 3346 bytes, matching byte for byte. Two different defects in stored state, one answer. Correct, since neither is actionable by the client. Note the request carried no `redirect_uri` of its own and still failed, because the scheme is checked on the *registered* URL before the client's value is consulted. Precedence was tested against all three competitors, not one: | Also wrong in the request | Would answer alone | Actually answered | |---|---|---| | `code_challenge=short` | 302 to the callback | **500** | | `client_id` repeated | 400 kept here | **500** | | `redirect_uri` mismatched | 400 kept here | **500** | Reading the source, this is stronger than precedence. `newAuthorizeResponse` runs at `authorize.go:250`, before any of `client_id`, `code_challenge`, `scope` or `resource` is read, and the early return discards whatever `p.Errors` already held. In rows two and three those failures are never detected at all, so `kind()` ranking `failureCorruptRegistration` first is belt and braces for a failure constructed some other way. **The value is logged and never echoed.** A distinctive marker was planted and five requests fired: ```text [erro] coderd: oauth2 app has an unusable registered callback URL request_id=01ca4796-c743-4923-a06b-afc1f3decc95 app_id=12f9ca3b-7a2c-4c54-8ed7-723698c62bd1 callback_url="javascript:alert(\"plat479-6d-marker\")" error= redirect URI uses dangerous scheme javascript which is not allowed: codersdk/oauth2_validation.go:116 ``` Five requests, five lines, in request order. Occurrences of the marker in the POST body, the rendered GET page, and the response headers: **0, 0, 0**. The `request_id` joins that line to the request log entry whose `response_body` field holds the vague message, so the server's own record confirms what it sent for the same request rather than a replay. The log is also where the two causes diverge, naming `validateScheme` and its source line, which the response cannot do. Restoring the row restores normal behaviour immediately, with no restart: ```text POST -> 302 with a code GET -> 200 consent page ``` That is a control rather than housekeeping: it rules out the app having been poisoned lastingly, and rules out a cached parse outliving the `UPDATE`. </details> <details> <summary><b>17 and 18. Every unsupported response_type gets one code</b></summary> | `response_type` sent | `error` | `error_description` | |---|---|---| | `token` | `unsupported_response_type` | Only response_type=code is supported | | `banana` | `unsupported_response_type` | Only response_type=code is supported | | `code token` | `unsupported_response_type` | Only response_type=code is supported | | `CODE` | `unsupported_response_type` | Only response_type=code is supported | | `code_extra` | `unsupported_response_type` | Only response_type=code is supported | | empty string | `invalid_request` | Invalid query params: response_type: Query param 'response_type' is required and cannot be empty | `token` has a Go constant behind it and `banana` does not, so their agreement is what reading the value as text bought. Three rows are more interesting than `banana`: `code token` is a legal RFC 6749 §3.1.1 space-delimited list used by OIDC's hybrid flow, `CODE` confirms the comparison is case sensitive, and `code_extra` confirms it is equality rather than a prefix match. The empty string is correctly the exception. A valueless parameter is *missing*, not unsupported, and RFC 6749 §3.1 requires it be treated as omitted. **The error is in the query, not the fragment.** `response_type=token` is the implicit grant's own value, so a fragment would be arguable, but this deployment advertises `"response_types_supported":["code"]` alone, and a fragment is never sent to the server, so it would be unreadable to the client's backend. PKCE is not recast, which the controls show: | `response_type`, no `code_challenge` sent | `error` | |---|---| | `token` | `unsupported_response_type`, zero mentions of `code_challenge` | | `banana` | `unsupported_response_type`, zero mentions of `code_challenge` | | `code` | `invalid_request`, naming `code_challenge` | Without the `if params.responseType == responseTypeCode` guard, a client sending `token` would be told its `code_challenge` was missing, add one, resend, and be told the same thing again. </details> <details> <summary><b>19 to 21. Unrecognized parameters ignored, repeats still rejected</b></summary> Eight unknown parameters, each on an otherwise valid request, every one issuing a code: | Unknown parameter | Result | |---|---| | `nonce`, `prompt`, `login_hint`, `acr_values`, `max_age`, `ui_locales` | code issued | | `code_challenge_methods=S256` | code issued | | `REDIRECT_URI=http://evil.example/steal` | code issued, **to the registered callback** | Five of those are OpenID Connect Core parameters, so an OIDC client pointed here degrades to plain OAuth2 rather than failing. The ignored parameters are **dropped, not forwarded**: the callback receives only `code` and `state`. The last two rows are the ones with teeth. Query parameter names are case sensitive, so `REDIRECT_URI` must be ignored, and a misspelled `redirect_url` likewise: ```text case variant alongside a valid redirect_uri : Location host localhost:9876 case variant as the only redirect parameter : Location host localhost:9876 redirect_url typo, no valid redirect_uri : Location host localhost:9876, code issued evil.example occurrences in any Location : 0 ``` The consent page renders for the typo case too, and even its cancel link targets the registered callback. A parser matching names case-insensitively would have redirected to `evil.example` with a valid code attached. **Observation 5.** The `ignoring unrecognized authorization parameters` line was never emitted. Three requests carrying a distinctive marker produced no new server output at all, because the call is `logger.Debug` (`authorize.go:307`) and the deployment runs with `verbose: null`. The behaviour is correct and required by RFC 6749 §3.1, but at default verbosity the misspelling is invisible from every angle: the client sees a 302 with a code, its redirect is silently replaced, and nothing is logged. The comment claiming the typo "surfaces here" is optimistic. Repeats of known parameters are still rejected, which the replacement of `ErrorExcessParams` had to leave alone: | Repeated parameter | HTTP | `error` | Answered at | |---|---|---|---| | `code_challenge` | 302 | `invalid_request`, two entries one field | client callback | | `code_challenge_method` | 302 | `invalid_request` | client callback | | `response_type` | 302 | `invalid_request` | client callback | | `redirect_uri` | 400 | withheld | **Coder** | | `scope` | 302 | `invalid_request` | client callback | | `resource` | 302 | `invalid_target` | client callback | `redirect_uri` being withheld confirms the carve-out keys on the field name rather than the kind of mistake. `code_challenge` collects two entries for one mistake, because `parseSingle` collapses the value to empty and the PKCE block then reports it missing. The `resource` row is observation 6. </details> <details> <summary><b>22 and 23. resource, its own code, and the fragment rule</b></summary> Both sides of the rule, since a check enforced too broadly would reject a valid URN: | `resource` sent | `error` | Stored `resource_uri` | |---|---|---| | `not a uri` | `invalid_target` | not stored | | `/api` relative | `invalid_target` | not stored | | `https://api.example.com` | none, code issued | as sent | | `https://api.example.com/v1?q=1` | none, code issued | as sent, query is not a fragment | | `urn:example:resource` | none, code issued | as sent | | empty string | none, code issued | `NULL`, same as omitted | `invalid_target` applies only when `resource` is the sole failure. Add any second failure in any other field and the code becomes `invalid_request` naming both, which is the retry-loop guard: ```text resource + bad code_challenge -> invalid_request, both named resource + repeated scope -> invalid_request, both named resource + repeated state -> invalid_request, both named resource alone (control) -> invalid_target ``` Fragments are rejected in all three placements, with or without a path: ```text https://api.example.com/#x -> invalid_target https://api.example.com#x -> invalid_target https://api.example.com/v1#frag -> invalid_target https://api.example.com/# -> code issued, stored as https://api.example.com/# ``` **The last row is observation 7, and it predates this PR.** Go cannot represent the distinction: ```text https://a.example.com/ Fragment="" String()="https://a.example.com/" https://a.example.com/# Fragment="" String()="https://a.example.com/" https://a.example.com/#x Fragment="x" String()="https://a.example.com/#x" ``` `url.Parse` collapses "no fragment" and "empty fragment", so `if u.Fragment != ""` in `validateResourceParameter` (`coderd/oauth2provider/tokens.go:591`) cannot see a trailing `#`. RFC 3986 §3.5 permits a zero-length fragment, which RFC 8707 §2's "MUST NOT include a fragment component" reads as forbidding. Validation parses the value but persistence stores the raw string, so the `#` reaches `resource_uri` and the stored audience is not textually equal to the fragment-free form. A client appending a harmless-looking `#` would get a token bound to an audience nothing matches. The authorize-side call to `validateResourceParameter` is context in this diff rather than an added line; this PR added the `invalid_target` code for the failure. </details> <details> <summary><b>24 and 25. The description cap and character set</b></summary> The obvious probe does not exercise the cap: a 4000-character `code_challenge` produces a 116-character description, because that message is fixed text and never quotes the offending value. The descriptions that echo caller input come from a validator's own error. | Request | `error` | Description length | Truncated | `Location` length | |---|---|---|---|---| | `code_challenge_method` = 4000 chars | `invalid_request` | 2060 | **yes** | 2176 | | `scope` = 4000 chars | `invalid_scope` | 2060 | **yes** | 2174 | | `code_challenge_method` = 2000 chars | `invalid_request` | 2035 | no | 2147 | | `code_challenge` = 4000 chars | `invalid_request` | 116 | no | 234 | 2060 is exactly `maxErrorDescription` plus `" (truncated)"`. Row three is the boundary control, so the cap fires on length rather than on the presence of echoed input. Measured from the `Location` header rather than a log line, since the stated reason for the cap is that the header must survive intermediary proxies; the longest observed was 2176 bytes. Both verbs agree, the cap living in the shared `redirectAuthorizeError`: ```text GET, long method : desc_len=2060 truncated=True GET, long scope : desc_len=2060 truncated=True ``` The character set is enforced independently, later, in `errorURL`: ```text input: pl"ain\back<newline>tab<tab>end~unicode description: unsupported code_challenge_method: pl'ainback tab end~ nicode chars outside the RFC 6749 §4.1.2.1 set: [] ``` `"` becomes `'`, `\` is dropped so it cannot escape the rewritten quote, and anything below 0x20 or above 0x7E becomes a space. Checked programmatically rather than by eye. The RFC sets no length limit, so the 2048 cap is policy; the character set is conformance. </details> <details> <summary><b>26. The registered callback query, retained except reserved names</b></summary> `plat479-reserved` registers a callback carrying all four reserved names plus two ordinary ones, and DCR stores it unchanged: ```text http://localhost:9876/callback?tenant=acme&code=FAKECODE&error=stale&error_description=oldmsg&state=oldstate&keep=yes ``` Success response, no `redirect_uri` sent: ```text code = coder_WXwBpvYR5u_... keep = yes state = 516abeea9976119eb33ddc10f0ca04ed tenant = acme ``` Failure response, same app: ```text error = invalid_request error_description = Invalid query params: code_challenge: must be 43 to 128 characters... keep = yes state = 3a17bdd75dfcf740bda36124cd161fb7 tenant = acme ``` Stale registered values in either response: `FAKECODE` 0, `stale` 0, `oldmsg` 0, `oldstate` 0. Without the deletion step a registered `error=stale` would ride out on the **success** response, and a client reading `error` before `code`, the conventional order, would discard a valid authorization code. `FAKECODE` is the mirror image on a failure response. The cancel link obeys the same rule, being built by the same `withQuery` path: ```text http://localhost:9876/callback?error=access_denied&error_description=The+resource+owner...&keep=yes&state=e15b5f0f...&tenant=acme ``` RFC 6749 §3.1.2 requires the registered query be retained when adding parameters, which is the `tenant` and `keep` half. It does not say what to do when the registered query collides with the response parameters §4.1.2 adds, so dropping the registered copies is the resolution that keeps the client's read unambiguous. </details> <details> <summary><b>27 and 28. Scope rejections, and declining consent</b></summary> `plat479-ci` carries the allowlist `coder:workspaces.access`. ```text scope=template:update (outside) -> error = invalid_scope 'template:update': scope requests permissions beyond this app's allowed scopes GET, same request -> 302, 225 bytes, 0 Allow buttons, no consent page scope=workspace:ssh (covered) -> code issued, persisted scope workspace:ssh GET, same request -> 200, 5182 bytes, consent page naming the scope ``` `workspace:ssh` is granted although the allowlist names the composite rather than that scope, which is the coverage-not-spelling rule from #28045. This run only checks that the changes here left it delivering the same answers. The consent page for a narrow scope reads differently from the unrestricted one: "to access your **admin** account with these permissions?", the scope as `<li role="listitem">workspace:ssh`, and the caution "These are technical permission names. Grant them only to an application you trust." The scope description shape differs from the parser's, coming from `scopeFailureResponse` rather than the field join, which is the third producer behind observation 1. Declining consent, clicked in a real browser: ```text error = access_denied error_description = The resource owner or authorization server denied the request state = a8bd538b365b61f54586892c73968b80 ``` The page carries exactly one `href` and it is the cancel link. The `state` matches, there is no `code`, and the code count for the app is unchanged, the link being a plain `GET` to the client's callback that never reaches `ProcessAuthorize`. The description is RFC 6749 §4.1.2.1's own definition of `access_denied`, word for word. That shared construction is what makes the `#nosec G203` annotation on `CancelURI` sound: the URL is injected as a trusted `htmltemplate.URL`, safe only because `newAuthorizeResponse` validated the registered scheme before the response object could exist. Scenario 12 is the other half, an app with a rejected scheme never reaching this page at all. </details> <details> <summary><b>Where the consent page renders, across every GET case</b></summary> Only `GET` can render anything, and body size identifies which of four renderers ran, so this is the table to check when a status code alone looks right. | Case | Status | Body bytes | Allow buttons | Rendered | |---|---|---|---|---| | well formed | 200 | 4928 | 1 | **consent page** | | bad `code_challenge` | 302 | 263 | 0 | redirect stub | | two bad fields | 302 | 319 | 0 | redirect stub | | mismatched `redirect_uri` | 400 | 3814 | 0 | 400 error page | | unparseable `redirect_uri` | 400 | 3846 | 0 | 400 error page | | repeated `client_id` | 400 | 3846 | 0 | 400 error page | | `client_id` in form body only | 400 | 77 | 0 | `httpmw` JSON, unstyled | | `{UPPERCASE}` `client_id` | 200 | 4940 | 1 | **consent page** | | repeated `state` | 302 | 239 | 0 | redirect stub | | corrupt callback, blocked scheme | 500 | 3346 | 0 | 500 error page | | corrupt callback, unparseable | 500 | 3346 | 0 | 500 error page | | `response_type=token` | 302 | 187 | 0 | redirect stub | | `banana` / `code token` / `CODE` | 302 | 187 | 0 | redirect stub | | empty `response_type` | 302 | 243 | 0 | redirect stub | | `token`, no PKCE | 302 | 187 | 0 | redirect stub | | `code`, no PKCE | 302 | 245 | 0 | redirect stub | | unknown params, valid request | 200 | 4932 | 1 | **consent page** | | `redirect_url` typo, valid request | 200 | 4932 | 1 | **consent page** | | `resource` malformed | 302 | 214 | 0 | redirect stub | | `resource` valid absolute URI | 200 | 4932 | 1 | **consent page** | | `resource=.../#` empty fragment | 200 | 4932 | 1 | **consent page**, observation 7 | | reserved params in registered callback | 200 | 4973 | 1 | **consent page** | | `scope` outside allowlist | 302 | 225 | 0 | redirect stub | | `scope` covered by allowlist | 200 | 5182 | 1 | **consent page** | The invariant: the page renders if and only if `extractAuthorizeParams` returned no failure, so no input asks the owner to approve a request the server has already refused. The `evil.example` rows are worth reading carefully rather than alarming: RFC 6749 §3.1 requires a case variant and a typo to be ignored, so from the server's view nothing was wrong with either request, and both cancel links target the registered callback. About 4930 bytes is the consent page, about 3800 the 400 page, 3346 the 500 page, 77 the unstyled `httpmw` JSON, and low hundreds is Go's redirect stub, whose length tracks the `Location` it embeds. Every `unsupported_response_type` answer is exactly 187 bytes because they share one description. Small variations within a renderer are expected: the consent page moves 4928 to 4940 with a fresh CSRF token and the app name. As a regression signal, body size is more sensitive than the status line. A change that rendered a page alongside a redirect would still report 302, but the stub would come back at thousands of bytes rather than hundreds. </details> <details> <summary><b>Cleanup</b></summary> ```bash for id in $(pg "SELECT id FROM oauth2_provider_apps WHERE name LIKE 'plat479%';"); do curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$id" -H "$AUTH_HEADER" \ -o /dev/null -w "$id -> %{http_code}\n" done pg "SELECT count(*) FROM oauth2_provider_apps WHERE name LIKE 'plat479%';" ./scripts/coder-dev.sh oauth2-provider dcr disable ``` All planted callback rows were restored before deletion, so no fixture was left holding a value DCR would refuse. </details> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
e035967ef1 |
feat: mint access tokens with the negotiated scope (#28237)
**TL;DR** First of PLAT-480, continuing the merged PLAT-479 stack. #28178 decided what the scope is and #28179 reported it; this PR is the one that makes it bind. Until now the scope negotiated at `/oauth2/authorize` was recorded on the grant but never reached the token: every OAuth2 access key was minted with `coder:all`, so a client that asked for `coder:workspaces.access` still got full API access. | PR | What it does | |---|---| | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. Merged. | | #28178 | The authorize endpoint checks the request against the scope catalog, grants it only if the app's filtered allowlist covers it, and persists the result on the code. Merged. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's own callback per RFC 6749 §4.1.2.1. Merged. | | **#28237 (this)** | The exchange mints the API key with the stored scope, and the token response states what was granted. | | #28740 | Re-checks the app allowlist at redemption, for a code whose app was narrowed after the code was issued. | | #28751 | Lets a refresh narrow the granted scope, which is the `scope` request parameter this PR still ignores. | - #28179 has merged, so this diff is against main and reviews on its own. - **This is the first PR in the stack where a token's authority actually changes.** Everything before it recorded and reported. That is the blast radius worth reviewing: a grant that negotiated a narrow scope now gets a key that is genuinely narrower, and anything that was quietly relying on `coder:all` will start seeing 403. - Grants that predate the scope columns carry what migration 000569 backfilled, `coder:all`, so they refresh unrestricted and reach what they reached before. Pinned by `BackfilledScopeRefreshesUnrestricted`, seeded the way the migration leaves a row rather than exchanged. - The actor that writes the key stays `rbac.ScopeAll`. Narrowing it to the granted scope would deny `api_key:create` and fail the exchange. The bound lives on `api_keys.scopes`, which dbauthz reads on every request, not on the actor doing the insert. **Where in the flow** <details> <summary>Diagram: where the stored scope turns into a bound on the token</summary> ```mermaid flowchart TD AZ["GET or POST /oauth2/authorize<br/>negotiates the scope and persists it on the code<br/>PR 28178, merged"] AZ --> TK["POST /oauth2/tokens"] TK --> GT{"grant_type"} GT -->|authorization_code| S1["scope read from codes.scope"] GT -->|refresh_token| S2["scope read from tokens.scope<br/>req.Scope is parsed and ignored, PR 28751"] S1 --> CV["scopeStringToAPIKeyScopes, this PR<br/>every name must be in the api_key_scope enum<br/>an empty list is an error, not coder:all"] S2 --> CV CV -->|"unknown name, or empty"| ERR["400 invalid_grant, this PR<br/>error_description names the offending value"] CV -->|mintable| GEN["apikey.Generate with Scopes, this PR<br/>was: no Scopes, so every key defaulted to coder:all"] GEN --> KEY["api_keys.scopes<br/>read by dbauthz on every later request:<br/>this is where the grant becomes a bound"] GEN --> ROW["the new tokens row carries the same scope,<br/>so the next refresh reads back the same grant"] KEY --> RESP["200 with scope in the token response, this PR<br/>RFC 6749 5.1, OAuth 2.1 1.4.1"] ROW --> RESP ``` </details> - Token endpoint only, both grants. Authorize is untouched apart from two comments that said the scope was not yet enforced. - `scopeStringToAPIKeyScopes` turns the stored scope string into `database.APIKeyScopes` for `apikey.Generate`. Names are checked there rather than inside `apikey.Generate`, whose error would surface as a 500 rather than an OAuth2 error. - An empty list is an error, not an unrestricted key. `apikey.Generate` defaults an empty scope list to `coder:all`, so an empty stored scope would silently widen the grant instead of failing it. The same reasoning is why the `expandRBACScope` comment in `modelmethods.go` was stale: that function already errored on an empty list while its comment still promised `rbac.ScopeAll`. - A stored scope outside the `api_key_scope` enum answers 400 `invalid_grant` rather than 500, with the offending name in `error_description`. Not `invalid_scope`: RFC 6749 §5.2 and OAuth 2.1 §3.2.4 both scope that code to what the client requested, and this value is server state the client cannot change by asking differently. The grant is what is unusable, and re-authorizing is the only way out. - Refresh copies the presented token's scope onto both the new API key and the rotated refresh row. `req.Scope` is parsed but ignored; #28751 is where it starts being honoured. - The swagger annotation moves from `oauth2.Token` to `codersdk.OAuth2TokenResponse`, because `oauth2.Token` has no `scope` field to document. - `EveryCatalogNameMintable` pins the catalog against the `api_key_scope` enum. The two are maintained separately, and a name negotiable at authorization but unmintable at exchange would leave a client holding a code it can never redeem. **What it satisfies** Checked against both RFC 6749 and the OAuth 2.1 draft (draft-ietf-oauth-v2-1-15). The 2.1 draft moves the scope-reporting rule from RFC 6749 §5.1 into §1.4.1 and grades it in §3.2.3, but the requirement is the same one. - RFC 6749 §5.1, OAuth 2.1 §1.4.1 — "If the issued access token scope is different from the one requested by the client, the authorization server MUST include the `scope` response parameter in the token response". OAuth 2.1 §3.2.3 grades `scope` as "RECOMMENDED, if identical to the scope requested by the client; otherwise, REQUIRED". Both grants set it unconditionally, which covers both grades. Without it, a client whose request was narrowed against the app's allowlist, or defaulted because it requested nothing, first learns its bounds from an unexplained 403. Pinned by `IssuedTokenBoundsTheAPI`, which requests no scope and asserts the response names what it got. - OAuth 2.1 §1.4.1 — "The authorization server MAY fully or partially ignore the scope requested by the client, based on the authorization server policy or the resource owner's instructions." This is what licenses ignoring `scope` on a refresh, and the licence is conditional on reporting the actual grant. Before this PR the exchange both ignored the request and said nothing, which is the half that was not defensible. - OAuth 2.1 §4.3.1, RFC 6749 §6 — the refresh `scope` parameter is OPTIONAL and "if omitted is treated as equal to the scope originally granted by the resource owner". Exactly what `refreshTokenGrant` does with `dbToken.Scope`. - OAuth 2.1 §4.3.3 — "If a new refresh token is issued, the refresh token scope MUST be identical to that of the refresh token included by the client in the request." Rotation copies `dbToken.Scope` onto the new refresh row. - OAuth 2.1 §3.2.3 — "If refresh tokens are issued, those refresh tokens MUST be bound to the scope and resource servers as consented by the resource owner. This is to prevent privilege escalation by the legitimate client". The refresh row has carried the negotiated scope since #28178; this PR is what makes the access token minted from it carry the same bound. Pinned by `RefreshDoesNotWidenTheScope`. - OAuth 2.1 §1.4.1 — a client that omits `scope` must be met with "a pre-defined default value or fail the request indicating an invalid scope", and the server "SHOULD document its scope requirements and default value". #28178 chose the default; `scopes_supported` and the integration guide document it. Unchanged here, but it is why `IssuedTokenBoundsTheAPI` can request nothing and still receive a bounded token. - Not yet: OAuth 2.1 §4.3.1 also says "The requested scope MUST NOT include any scope not originally granted by the resource owner." A refresh naming a narrower scope is ignored rather than honoured, and one naming a wider scope is ignored rather than rejected with `invalid_scope` (§3.2.4, "exceeds the scope granted by the resource owner"). Neither case widens a token, so there is no escalation, and §1.4.1's MAY plus the `scope` response parameter keep the client correctly informed in the meantime. #28751 is where narrowing lands. Documented under Limitations until then. --- First of three, [PLAT-480](https://linear.app/codercom/issue/PLAT-480). Depends on #28179, which has merged, so this reviews against main. #28178 decided the scope and #28179 reported it. This PR is the one that makes a token feel it. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
54e21f29a1 |
fix: deliver four more authorize errors to the client (#28450)
**TL;DR** Fourth of the stack, split out of #28045. #28179 sent `invalid_scope` to the client's own callback; this PR sends the rest of the errors raised after the callback has been verified, behind one URL builder they all now share. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name. | | #28178 | The authorize endpoint negotiates the scope against the app's allowlist and persists it on the code. | | #28179 | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's callback per RFC 6749 §4.1.2.1. | | **#28450 (this)** | The same delivery for every other error raised once the callback is trusted. | - #28179 has merged, so this diff is against main and reviews on its own. - Nothing about what a token can do changes here. This is delivery, not enforcement. **Contract change** Four failures now arrive at the app's registered callback instead of terminating on Coder, so an integrator with error handling on its callback starts seeing codes it never received. | Verb | Condition | Error code | Was | |------|-----------|------------|-----| | GET | `response_type != code` | `unsupported_response_type` | static "Unsupported Response Type" page, 400 | | POST | `response_type != code` | `unsupported_response_type` | `WriteOAuth2Error`, 400 | | POST | `code_challenge_method=plain` | `invalid_request` | `WriteOAuth2Error`, 400 | | GET | `code_challenge_method=plain` | `invalid_request` | consent page, 200, refused after Allow | The GET static error page loses its only caller. The last row is what review found: the method was checked on POST only, so the user approved a request that could never succeed. **Where in the OAuth Flow** <details> <summary>Diagram: where these errors are raised, and what licenses the redirect</summary> ```mermaid flowchart TD EX["GET or POST /oauth2/authorize<br/>extractAuthorizeParams exact-matches redirect_uri<br/>against the app's registered callback"] EX -->|"no match, rejected scheme, unparsable,<br/>other param failures"| CODER["Answers on Coder<br/>RFC 6749 3.1.2.4: MUST NOT redirect"] EX -->|"matched: a validatedCallbackURL,<br/>which is what licenses a redirect"| RT{"response_type == code?"} RT -->|no| E1["unsupported_response_type (this PR)"] RT -->|yes| PK{"code_challenge_method S256 or omitted?"} PK -->|no| E2["invalid_request (this PR, and newly checked on GET)"] PK -->|yes| SC{"scope negotiable?"} SC -->|no| E3["invalid_scope (previous PR)"] SC -->|yes| OK["GET: consent page, cancel link is access_denied<br/>POST: authorization code"] E1 --> OUT E2 --> OUT E3 --> OUT OK --> OUT["One builder produces every URL the flow emits:<br/>error redirect, cancel link, success code"] ``` </details> - Authorize endpoint only, both verbs. The token exchange, refresh, and revocation are untouched. - Every redirect is licensed by a `validatedCallbackURL`, a type produced only where `extractAuthorizeParams` exact-matches the URI against the app's registration. A guard, not a proof: no other package can fabricate one, this one still can. - One builder now produces every response URL, including the consent page's cancel link, which rolled its own and edited the shared URL in place rather than copying it. - Each rejection logs. The error leaves in a `Location` header, which `loggermw` does not record, so a failed authorization used to look exactly like a successful one. **Three smaller behavior changes** - A callback registered with `code`, `error`, `error_description`, or `state` in its own query no longer receives that value back. A registered `error=` rode out on the success redirect, where a client that reads `error` first discards a valid code. The rest of the registered query is kept, as §3.1.2 requires. - `error_description` is confined to the NQSCHAR set Appendix A permits. Descriptions name the offending value with `%q`, so every `invalid_scope` Coder emits today carries excluded characters. Quotes now render as apostrophes. - An unparsable `redirect_uri` returns 400 instead of 500. It reached a nil dereference in `httpapi.RedirectURL`, which `POST /oauth2/tokens` also uses, and that endpoint takes no API key. **What it satisfies** - RFC 6749 §4.1.2.1 — on a failure that is not a bad redirection URI, the server informs the client through the redirection URI. That is the whole PR. - RFC 6749 §3.1.2.4 and §4.1.2.1 — a missing, invalid, or mismatching redirection URI "MUST NOT" be redirected to. A mismatched URI, and a registered URI with a rejected scheme, still answer on Coder. Pinned by `MismatchedRedirectURINotRedirected` and `DangerousCallbackSchemeNotRedirected`. - RFC 6749 Appendix A — `error_description` is NQSCHAR, and the rule is on the decoded value, so percent-encoding on the wire does not satisfy it. - RFC 6749 §4.1.2 and §3.1.2 — the four reserved response parameters are dropped from the registered query; everything else in it is retained. - Not yet: the remaining parameter failures do have a trusted callback in hand, but the parser reports one verdict for every field at once, so the caller cannot say which field failed. A follow-up classifies them. The two `server_error` sites also stay put: sending an internal fault outbound with a Coder-written description wants its own review. **Docs and Swagger.** `docs/admin/integrations/oauth2-provider.md` gains a Common Issues entry per newly redirected code, and the implicit-grant limitation now says where the error arrives. Both authorize verbs document the 302, the GET side for the first time. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Fourth of the stack. #28179 has merged, so this reviews against main. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
9368917813 |
feat: report the negotiated scope to the user and the client (#28179)
**TL;DR** Last of the stack, split out of #28045. #28178 decided what the scope is; this PR is everything that reports it, to the user on the consent page and to the client on rejection. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. Every code is still stamped unrestricted. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name, and fails closed on any shape it does not model. Added with no production callers. | | #28178 | The authorize endpoint checks the request against the scope catalog, grants it only if the app's filtered allowlist covers it, and persists the result on the code. | | **#28179 (this)** | The consent page lists the negotiated permissions, and `invalid_scope` reaches the client's own callback per RFC 6749 §4.1.2.1 instead of a Coder error page. Retires the interim plumbing #28178 left behind. | - #28178 has merged, so this diff is against main and reviews on its own. It is still worth reading first: nothing here decides a scope, it only reports the one `negotiateScope` already returns. - **The consent page HTML is not final.** Layout and wording in `site/static/oauth2allow.html` are still being refined. It is in this branch so the scope-enforcement flow can be exercised end to end in a browser, not because the markup is settled. The reviewable part of Half A is the Go side that decides what the page states; the presentation will change. - An unrestricted grant still reads as full access, not as a scope name. Nothing about what a token can do changes in this PR either. **Where in the flow** - Authorize endpoint only, both verbs. GET decides what the consent page states; both verbs send `invalid_scope` to the callback. The token exchange, refresh, and revocation are untouched. - `negotiateScope` is unchanged from #28178, so which requests succeed is unchanged. This PR reads its result twice: once to decide what the page lists, once to decide where the rejection goes. - The endpoint sits behind `apiKeyMiddlewareRedirect`, so the user is authenticated before any of this runs. That matters for the redirect, not just for the page. - Consent page rendering moves a decision into Go rather than the template: `RenderOAuthAllowData` carries `Scopes` and `Unrestricted` separately, and the template branches on `Unrestricted` alone. **What it satisfies** - RFC 6749 §4.1.2.1 — on a failure that is not a bad redirection URI, the server "informs the client by adding the following parameters to the query component of the redirection URI". `invalid_scope` now goes there. #28178's interim delivery, a static error page on GET and an error body on POST, is what this replaces. - RFC 6749 §4.1.2.1 — `state` is "REQUIRED if a `state` parameter was present in the client authorization request", so it is echoed only when the client sent one, never synthesized. Pinned by `OmittedStateNotEchoed`. - RFC 6749 §3.1.2.4 and §4.1.2.1 — on a "missing, invalid, or mismatching redirection URI" the server "MUST NOT automatically redirect the user-agent to the invalid redirection URI". This is the whole ordering argument, and the file's other error paths keep their existing delivery precisely because several of them are where that validation fails. - RFC 9700 §2.1 — pre-registered redirection URIs "MUST utilize exact string matching". `extractAuthorizeParams` already did this before the stack; Half B depends on it rather than adding it. - RFC 9700 §4.11.2 — names this exact hazard: an attacker who registers a client can "intentionally send an erroneous authorization request, e.g., by using an invalid scope value, thus instructing the authorization server to redirect the user agent to its phishing site". The destination is still only ever a URI that client registered, so this is a phishing surface that costs an attacker a registration, not an open redirect. The precaution the section requires, authenticating the user first, is what `apiKeyMiddlewareRedirect` provides. - RFC 9700 §4.12 — a server redirecting a request that may carry credentials "MUST NOT use the HTTP 307 status code". 302, matching the success redirect beside it. - RFC 6749 §4.1.2.1 — `server_error` exists "because a 500 Internal Server Error HTTP status code cannot be returned to the client via an HTTP redirect". An unusable registered callback is the one case with nowhere to redirect, so it answers 500 on both verbs and logs the app and URL for an operator to correlate by. - Not yet: §1.4.1 still wants `scope` in the token response when the grant differs from the request. Tokens are untouched here, as in #28178, so that lands with enforcement. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). Last of three. #28178 has merged, so this reviews against main. #28178 decided what the scope is. This PR is everything that tells someone about it. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
20a41c067e |
feat: reject secret creation and fix reporting for public clients (#28097)
**TL;DR** On top of #28047, closing the last two gaps in the stack split out of #27873. A public client can now register (#28046) and exchange a code (#28047), but the admin secrets API will still issue it a secret that authenticates nothing, and the registration responses still report an auth method the token endpoint will not accept. | PR | What it does | |---|---| | #27712 | Schema: `app_secret_id` becomes nullable and tokens gain an always-populated `app_id`, so ownership checks work without a secret row. | | #28041 | Accepts bare custom-scheme redirect URIs (`vscode://`, `cursor://`) that native apps actually register. | | #28043 | Derives and stores `client_type` (public vs confidential) from the requested `token_endpoint_auth_method`, and pins it across updates. | | #28046 | Registration issues no secret for a public client and returns no `client_secret`. | | #28047 | The token endpoint accepts the exchange without a `client_secret`. Discovery advertises `none`. | | **#28097 (this)** | The admin secrets API refuses to create a secret for a public client, and registration, read, and update report the auth method the token endpoint actually enforces. | A public client can only come into existence through dynamic client registration, which is off by default, so neither guard is reachable until DCR is enabled. **Where in the flow** - `POST /oauth2-provider/apps/{app}/secrets`, the admin secrets API. The rest of the secret lifecycle is untouched: `GET` and `DELETE` are unchanged, and a confidential app behaves exactly as before. - The three RFC 7591 and 7592 responses that carry `token_endpoint_auth_method`: registration (`POST`), read (`GET`), and update (`PUT`). Only what is reported changes; the stored column is left as the client sent it. - Authorize, token exchange, refresh, and revocation are untouched. **What it satisfies** - RFC 7591 §2: `none` means the client is public and "does not have a client secret", so the secrets API should not create one for it. - RFC 7591 §3.2.1: the server MUST return all registered metadata and MAY replace a requested value with a suitable one. Reporting the enforced method in place of a stored one that contradicts `client_type` is that substitution. - RFC 7592 §2.2: an update MUST include all metadata as returned by a previous registration, read, or update. Because clients echo back what Coder reports, reporting the enforced method is what lets a legacy row heal on the client's next `PUT`. - RFC 7591 §2 default: an app with no stored method reports `client_secret_basic`, which is both the RFC default and what `ApplyDefaults` substitutes on update. - OAuth 2.1 §3.2.1: the token endpoint enforces on `client_type`, so a reported method that disagrees with it tells a client to authenticate in a way the server will reject. --- - `CreateAppSecret` returns 400 for a public client before generating anything. The secret would authenticate nothing, since the token endpoint no longer checks one for a public client. Deleting it would be worse: `oauth2_provider_app_tokens.app_secret_id` is `ON DELETE CASCADE`, so removing a confidential app's secret takes its tokens with it, but a public client's tokens carry a NULL `app_secret_id` (#27712) and survive. An admin who deleted the secret would think they had cut off the client when they had not. - `reportedAuthMethod()` replaces the raw stored value in all three registration responses. It returns the stored method when it agrees with `client_type`, `none` for a public app, and `client_secret_basic` otherwise. - The rows that can disagree are clients registered before #28043 derived the type from the method: the method was stored as sent while the type was always `confidential`. Such a client holds a secret its exchange still requires, while `GET` reported `none` and told it to drop that secret. - The stored column is deliberately not rewritten, so the response can still differ from the row. That divergence is what a read-modify-write client resolves on its next update, and the test asserts the row keeps what the client sent. - Coverage: the secrets guard asserts the 400 and that no partial secret row was left behind. A table test walks `GET` then `PUT` over six stored-method and client-type pairs: the legacy mismatch in both resend shapes, the reverse mismatch that registration cannot produce but the function still handles, an empty stored method, and the single pair that already agrees and must be reported as stored. - Docs: the client type is fixed at registration and a type-changing update is rejected with `invalid_client_metadata` (behavior from #28043 that was never written down), plus what a legacy `none` client now sees. Refs https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client ## Manual Tests Verified by hand against a local dev deployment (`v2.36.3-devel+c85e4621ef`, dev Postgres), in addition to the automated suite. Both guards are reachable only through dynamic client registration, which was confirmed off by default on this deployment and enabled for the run. Two of the scenarios need a row where `client_type` and `token_endpoint_auth_method` disagree, which registration cannot produce since #28043 derives one from the other, so those rows were seeded by updating the method column directly on a purpose-built client. | # | Scenario | Result | |---|----------|--------| | 1 | Secrets API refuses a public client, with the guard's own message | Pass | | 2 | No partial secret row is left behind by the rejection | Pass | | 3 | A confidential app's secret create, list, and delete are unchanged | Pass | | 4 | Admin-created apps are always confidential, so the guard is unreachable there | Pass | | 5 | When stored method and client type agree, the stored value is reported unchanged | Pass | | 6 | A legacy confidential row storing `none` reports `client_secret_basic` | Pass | | 7 | The reported method is the one the token endpoint enforces, in both directions | Pass | | 8 | An update resending the stored value is accepted and leaves the row alone | Pass | | 9 | An update resending the reported value heals the row | Pass | | 10 | The reverse mismatch, a public row storing a secret method, reports `none` | Pass | | 11 | An empty or unrecognized stored method falls back to `client_secret_basic` | Pass | | 12 | Type-changing updates are rejected both ways, `client_secret_basic` to `client_secret_post` is allowed | Pass | | 13 | Regression sweep of the merged stack, discovery through revocation | Pass | | 14 | Every claim in the new docs paragraphs matches observed behavior | Pass | No correctness defects found. Commands and captured output for each scenario below. **Two notes for anyone re-running this.** The previous runbook for this stack asserts the opposite of scenario 12: it flips a confidential client to public with a `PUT` and records `200`. That was correct before #28043 pinned the client type. The `400` here is the fix, not a regression. Generate the PKCE verifier with enough entropy that stripping `=+/` still leaves 43 characters. The `openssl rand -base64 32 | tr -d "=+/" | cut -c -43` recipe yields 38 to 43, so most runs are rejected by the token endpoint under RFC 7636 section 4.1 with an error that looks unrelated. Same trap noted in #28045. <details> <summary>Shell helpers used throughout</summary> ```bash export BASE_URL=http://localhost:3000 export AUTH_HEADER="Coder-Session-Token: $(cat ./.coderv2/session)" export PGURL="postgres://coder@localhost:$(cat ./.coderv2/postgres/port)/coder?sslmode=disable&password=$(cat ./.coderv2/postgres/password)" # Enable DCR; both guards are unreachable without it. curl -s -X PUT "$BASE_URL/api/v2/oauth2-provider/settings" -H "$AUTH_HEADER" \ -H "Content-Type: application/json" \ -d '{"dynamic_client_registration_enabled": true}' # Print "HTTP <code>" then the body. show() { local out; out=$(curl -s -w '\n%{http_code}' "$@") echo "HTTP $(printf '%s\n' "$out" | tail -n1)" printf '%s\n' "$out" | sed '$d' | jq . 2>/dev/null || printf '%s\n' "$out" | sed '$d' } # $1=name, $2=auth method ("" to omit the field). register() { local body if [ -z "$2" ]; then body=$(jq -nc --arg n "$1" '{client_name:$n,redirect_uris:["http://localhost:9876/callback"]}') else body=$(jq -nc --arg n "$1" --arg m "$2" '{client_name:$n,redirect_uris:["http://localhost:9876/callback"],token_endpoint_auth_method:$m}') fi curl -s -X POST "$BASE_URL/oauth2/register" -H "Content-Type: application/json" -d "$body" } # The stored row, as opposed to what the API reports. stored() { psql "$PGURL" -At -c "select client_type || ' | ' || coalesce(token_endpoint_auth_method,'<NULL>') from oauth2_provider_apps where id = '$1';" } # 43 characters from the unreserved set, always. See the note above. gen_verifier() { openssl rand -base64 96 | tr -d "=+/\n" | cut -c -43; } challenge_for() { printf '%s' "$1" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_'; } # Full PKCE authorize plus exchange. $1=client_id, $2=client_secret ("" for none). exchange() { local verifier challenge redirect code args verifier=$(gen_verifier); challenge=$(challenge_for "$verifier") redirect=$(curl -s -X POST \ "$BASE_URL/oauth2/authorize?client_id=$1&response_type=code&redirect_uri=http://localhost:9876/callback&state=$(openssl rand -hex 16)&code_challenge=$challenge&code_challenge_method=S256" \ -H "$AUTH_HEADER" -w '\n%{redirect_url}' -o /dev/null) code=$(printf '%s' "$redirect" | grep -oE 'code=[^&]+' | sed 's/code=//') args=(-d "grant_type=authorization_code" -d "code=$code" -d "client_id=$1" -d "redirect_uri=http://localhost:9876/callback" -d "code_verifier=$verifier") [ -n "$2" ] && args+=(-d "client_secret=$2") curl -s -X POST "$BASE_URL/oauth2/tokens" -H "Content-Type: application/x-www-form-urlencoded" "${args[@]}" } ``` </details> <details> <summary>1. Secrets API refuses a public client</summary> A bare non-`201` would also be produced by a request that failed on authentication, routing, or a malformed UUID before reaching the guard, so the status and the message are both asserted. ```bash PUB=$(register manual-28097-public none) PUB_ID=$(echo "$PUB" | jq -r '.client_id') stored "$PUB_ID" show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$PUB_ID/secrets" -H "$AUTH_HEADER" ``` ```text public | none HTTP 400 { "message": "Cannot create a client secret for a public OAuth2 app.", "detail": "Public clients authenticate with PKCE and have no client secret. The client type is fixed at registration, so register a new confidential client instead." } ``` The message is the guard's own, so execution reached `CreateAppSecret` and returned at the `IsPublic()` check. The detail points at registering a new confidential client, which scenario 12 confirms is the only remedy. </details> <details> <summary>2. No partial secret row is left behind</summary> The guard returns before `GenerateSecret()`, so nothing should exist at either layer. The count was already `0` at registration, and a confidential app is queried the same way as a control, so `0` is not merely what this query always returns. ```bash curl -s "$BASE_URL/api/v2/oauth2-provider/apps/$PUB_ID/secrets" -H "$AUTH_HEADER" | jq -c . psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$PUB_ID';" psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$CONF_ID';" ``` ```text [] 0 1 ``` </details> <details> <summary>3. A confidential app's secret lifecycle is unchanged</summary> ```bash CONF=$(register manual-28097-confidential "") CONF_ID=$(echo "$CONF" | jq -r '.client_id') show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets" -H "$AUTH_HEADER" curl -s "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets" -H "$AUTH_HEADER" | jq -c '[.[].id]' curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets/$SECRET_ID" \ -H "$AUTH_HEADER" -o /dev/null -w "delete: HTTP %{http_code}\n" ``` ```text HTTP 201 { "id": "da7a1029-47c4-435e-988a-557ffa4aeacf", "client_secret_full": "coder_POUtoElODM_<redacted>" } ["b2fc55b6-...","da7a1029-...","24f8f8c2-..."] delete: HTTP 204 ["b2fc55b6-...","da7a1029-..."] ``` Create, list, and delete all behave as before. The guard keys on `client_type` and nothing else on this path changed. Unrelated observation, not a finding against this PR: the listing returns two different `client_secret_truncated` formats. Secrets issued at registration are asterisk-padded (`***...TzqEOt`, from `createDisplaySecret`), while secrets issued through the admin API show the bare last six characters (`Rixs60`). Both write the same column and surface through the same field. Cosmetic and pre-existing, but a UI listing both kinds together would render them inconsistently. </details> <details> <summary>4. Admin-created apps are always confidential</summary> `postOAuth2ProviderApp` hardcodes the client type, so the guard is unreachable through the admin create path. ```bash ADMIN_APP=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps" -H "$AUTH_HEADER" \ -H "Content-Type: application/json" \ -d '{"name":"manual-28097-admin","callback_url":"http://localhost:9876/callback"}') ADMIN_ID=$(echo "$ADMIN_APP" | jq -r '.id') stored "$ADMIN_ID" show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$ADMIN_ID/secrets" -H "$AUTH_HEADER" ``` ```text confidential | client_secret_post HTTP 201 { "id": "a77ab276-ea74-4711-ba8b-955a8cb97951", "client_secret_full": "coder_eGlt04LhYg_<redacted>" } ``` Together with scenario 1 this brackets the guard: it fires for a dynamically registered public client and for nothing else. Note the admin API stores `client_secret_post`, not the RFC 7591 section 2 default, so every admin-created app is an agreement case for scenario 5. Such apps carry no registration access token, so they cannot reach the RFC 7592 endpoints where the reporting change applies at all. </details> <details> <summary>5. Agreement cases report the stored value unchanged</summary> The `client_secret_post` case is the one that matters. An implementation that substituted the type default on every call would still pass the public case, since `none` is the public default, but would rewrite this client to `client_secret_basic` and tell it to send its secret in the wrong place. ```bash curl -s "$BASE_URL/oauth2/clients/$PUB_ID" -H "Authorization: Bearer $PUB_RAT" \ | jq -c '{reported: .token_endpoint_auth_method}' POST_REG=$(register manual-28097-post client_secret_post) POST_ID=$(echo "$POST_REG" | jq -r '.client_id') echo "$POST_REG" | jq -c '{reported_on_register: .token_endpoint_auth_method}' curl -s "$BASE_URL/oauth2/clients/$POST_ID" -H "Authorization: Bearer $POST_RAT" \ | jq -c '.token_endpoint_auth_method' stored "$POST_ID" ``` ```text {"reported":"none"} {"reported_on_register":"client_secret_post"} "client_secret_post" confidential | client_secret_post ``` Registration and read both report the stored value. The update site is covered by scenarios 8 and 9. </details> <details> <summary>6. A legacy confidential row storing `none` reports `client_secret_basic`</summary> Seeded from a real confidential client so it genuinely holds the secret its exchange requires, with only the method column rewritten. This is the pre-#28043 shape and cannot be produced through the API any more. ```bash LEGACY=$(register manual-28097-legacy "") LEGACY_ID=$(echo "$LEGACY" | jq -r '.client_id') LEGACY_SECRET=$(echo "$LEGACY" | jq -r '.client_secret') stored "$LEGACY_ID" psql "$PGURL" -c "update oauth2_provider_apps set token_endpoint_auth_method = 'none' where id = '$LEGACY_ID';" stored "$LEGACY_ID" psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$LEGACY_ID';" curl -s "$BASE_URL/oauth2/clients/$LEGACY_ID" -H "Authorization: Bearer $LEGACY_RAT" \ | jq -c '{reported: .token_endpoint_auth_method}' stored "$LEGACY_ID" ``` ```text confidential | client_secret_basic UPDATE 1 confidential | none 1 {"reported":"client_secret_basic"} confidential | none ``` The response substitutes and the row is deliberately not rewritten. A read has no side effects. </details> <details> <summary>7. The reported method is the one actually enforced</summary> The token endpoint enforces on `client_type`, which is still confidential, so the secret is required regardless of what the method column says. ```bash exchange "$LEGACY_ID" "$LEGACY_SECRET" | jq -c '{has_access: has("access_token"), error, error_description}' exchange "$LEGACY_ID" "" | jq -c '{has_access: has("access_token"), error, error_description}' ``` ```text {"has_access":true,"error":null,"error_description":null} {"has_access":false,"error":"invalid_request","error_description":"Missing required parameter: client_secret"} ``` The second line is the pre-fix breakage reproduced. A client that read `"token_endpoint_auth_method": "none"` from `GET` and dropped its secret accordingly, which is what RFC 7592 tells it to do, would have hit exactly this on its next exchange. The old response was not internally inconsistent, it was actionable and wrong. Scenario 10 shows the same property in the opposite direction. </details> <details> <summary>8. An update resending the stored value is accepted and changes nothing</summary> ```bash show -X PUT "$BASE_URL/oauth2/clients/$LEGACY_ID" \ -H "Authorization: Bearer $LEGACY_RAT" -H "Content-Type: application/json" \ -d '{"client_name":"manual-28097-legacy","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}' stored "$LEGACY_ID" ``` ```text HTTP 200 "token_endpoint_auth_method": "client_secret_basic", confidential | none ``` Three things at once. The update is accepted, which is why the type-change guard requires the auth method to actually change: the requested `none` implies a public client while the row is confidential, so a guard keyed on the type mismatch alone would reject this and lock a legacy client out of managing its own registration. The `PUT` reports the same substituted value as the `GET`, covering the third call site. The row keeps what the client sent, so the divergence persists until scenario 9. </details> <details> <summary>9. An update resending the reported value heals the row</summary> ```bash show -X PUT "$BASE_URL/oauth2/clients/$LEGACY_ID" \ -H "Authorization: Bearer $LEGACY_RAT" -H "Content-Type: application/json" \ -d '{"client_name":"manual-28097-legacy","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_basic"}' stored "$LEGACY_ID" curl -s "$BASE_URL/oauth2/clients/$LEGACY_ID" -H "Authorization: Bearer $LEGACY_RAT" \ | jq -c '{reported: .token_endpoint_auth_method}' exchange "$LEGACY_ID" "$LEGACY_SECRET" | jq -c '{has_access: has("access_token")}' ``` ```text HTTP 200 "token_endpoint_auth_method": "client_secret_basic", confidential | client_secret_basic {"reported":"client_secret_basic"} {"has_access":true} ``` The row healed through an ordinary read-modify-write cycle, with no migration, backfill, or admin action. That works only because scenario 8 keeps the door open and this response gives the client a correct value to echo back; remove either and the row stays inconsistent indefinitely. </details> <details> <summary>10. The reverse mismatch reports `none`</summary> Registration cannot produce this direction either, but `reportedAuthMethod` branches on the general disagreement rather than the one shape known to exist, so it is covered. ```bash REVERSE=$(register manual-28097-reverse none) REVERSE_ID=$(echo "$REVERSE" | jq -r '.client_id') psql "$PGURL" -c "update oauth2_provider_apps set token_endpoint_auth_method = 'client_secret_basic' where id = '$REVERSE_ID';" stored "$REVERSE_ID" curl -s "$BASE_URL/oauth2/clients/$REVERSE_ID" -H "Authorization: Bearer $REVERSE_RAT" \ | jq -c '{reported: .token_endpoint_auth_method}' exchange "$REVERSE_ID" "" | jq -c '{has_access: has("access_token"), error}' ``` ```text public | client_secret_basic {"reported":"none"} {"has_access":true,"error":null} ``` This client has no secret row at all and the token endpoint does not ask for one, so `none` is what the response should say. Reporting the stored `client_secret_basic` would have instructed it to send a secret that does not exist. Both resend shapes behave symmetrically with scenarios 8 and 9: ```text resend stored (client_secret_basic) -> reported "none", row unchanged resend reported (none) -> reported "none", row now public | none ``` </details> <details> <summary>11. Empty or unrecognized stored methods fall back to the default</summary> `NULL` and `''` are indistinguishable once read into `sql.NullString`. A third case was added because the function gates on validity rather than emptiness. ```bash for v in "null" "''" "'private_key_jwt'"; do psql "$PGURL" -At -c "update oauth2_provider_apps set token_endpoint_auth_method = $v where id = '$CONF_ID';" stored "$CONF_ID" curl -s "$BASE_URL/oauth2/clients/$CONF_ID" -H "Authorization: Bearer $CONF_RAT" \ | jq -c '.token_endpoint_auth_method' done ``` ```text confidential | <NULL> "client_secret_basic" confidential | "client_secret_basic" confidential | private_key_jwt "client_secret_basic" ``` `private_key_jwt` is a real RFC 7591 method that Coder does not implement. Reporting it back would advertise an authentication scheme the token endpoint cannot honor, which is the same class of problem as the legacy `none` report in scenario 7. </details> <details> <summary>12. Type-changing updates are rejected both ways</summary> ```bash show -X PUT "$BASE_URL/oauth2/clients/$CONF_ID" \ -H "Authorization: Bearer $CONF_RAT" -H "Content-Type: application/json" \ -d '{"client_name":"manual-28097-confidential","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}' stored "$CONF_ID" show -X PUT "$BASE_URL/oauth2/clients/$PUB_ID" \ -H "Authorization: Bearer $PUB_RAT" -H "Content-Type: application/json" \ -d '{"client_name":"manual-28097-public","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_basic"}' stored "$PUB_ID" show -X PUT "$BASE_URL/oauth2/clients/$CONF_ID" \ -H "Authorization: Bearer $CONF_RAT" -H "Content-Type: application/json" \ -d '{"client_name":"manual-28097-confidential","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_post"}' stored "$CONF_ID" ``` ```text HTTP 400 { "error": "invalid_client_metadata", "error_description": "token_endpoint_auth_method cannot move an existing client between public and confidential (stored \"client_secret_basic\", requested \"none\"); the client type is fixed at registration, so register a new client instead" } confidential | client_secret_basic HTTP 400 { "error": "invalid_client_metadata", "error_description": "token_endpoint_auth_method cannot move an existing client between public and confidential (stored \"none\", requested \"client_secret_basic\"); the client type is fixed at registration, so register a new client instead" } public | none HTTP 200 "token_endpoint_auth_method": "client_secret_post", confidential | client_secret_post ``` Both rejections leave the row and its secrets untouched. A partial application would be the dangerous outcome here, a client left confidential while its caller believes it went public. The third case is the control. Two `400`s alone would be equally consistent with a guard that rejects every `token_endpoint_auth_method` change, a considerably more disruptive rule than the documented one. The `200` pins the guard to the derived client type rather than the method string. The second case is also what backs scenario 1. If public to confidential were permitted, the workaround to a refused secret request would be to flip the type and ask again. The two guards close that loop, which is why the same remedy appears in both error messages. </details> <details> <summary>13. Regression sweep of the merged stack</summary> Nothing here is new in this PR, but the guards sit on top of it. ```text discovery token_endpoint_auth_methods_supported : ["client_secret_basic","client_secret_post","none"] public registration, client_secret key present : false confidential registration, secret issued : true, method defaulted to client_secret_basic PKCE-only exchange, no client_secret sent : access + refresh issued access token against /api/v2/users/me : 200 token row app_id / app_secret_id : populated / NULL RFC 7009 revoke of own refresh token : 200, access token then 401 authorized-apps listing while a token is live : [{"name":"manual-28097-public"}] bulk DELETE /oauth2/tokens : 204, listing then [] ``` The NULL `app_secret_id` is what makes the secrets guard necessary. That column is `ON DELETE CASCADE`, so deleting a confidential app's secret takes its tokens with it, while a public client's tokens would survive. An admin who deleted such a secret would believe access was cut off when it was not. PKCE failure modes were checked separately, since the token endpoint distinguishes two the previous runbook treated as one: ```text verifier omitted : invalid_request, RFC 7636 section 4.1 bounds well-formed 43 chars but wrong : invalid_grant, "The PKCE code verifier is invalid" correct verifier, replaying that code: invalid_grant, "invalid or expired" ``` The third confirms the failed check destroys the code, so a leaked code cannot absorb repeated verifier guesses. </details> <details> <summary>14. The new docs paragraphs match observed behavior</summary> `pnpm run lint-docs` reports 0 errors across 501 files, `pnpm run format-docs` rewrites nothing, and Vale reports 0 errors with 2 warnings, both on pre-existing gerund headings that the same file on `main` also produces. The new prose is one sentence per line. | Documented claim | Verified by | |---|---| | A client's type is fixed when it registers | 12 | | A type-changing update is rejected with `invalid_client_metadata` | 12, both directions | | The client either holds a secret that would stop being required or has none and no way to be issued one | 12 (2 secrets), 1 and 12 (0 secrets, issuance refused) | | Switching between `client_secret_basic` and `client_secret_post` is allowed | 12 | | To change type, register a new client | matches the remedy in both errors and in scenario 1's detail | | Legacy `none` clients are stored as confidential and still require their `client_secret` | 6, 7 | | Coder reports `client_secret_basic` for those clients | 6 | | So that what it reports matches what it enforces | 7, both directions | | The mismatch clears itself the next time the client updates its registration | 9 | One wording note. Scenario 8 shows the mismatch does not clear on an update that resends the stored value, so strictly it clears on the next update carrying the reported value. A read-modify-write client, which is what RFC 7592 section 2.2 prescribes, always carries the reported value, so the sentence holds for the client it describes. A client that hardcodes its own metadata would not self-heal, but it would also not be following RFC 7592. </details> <details> <summary>Cleanup</summary> ```bash for id in "$PUB_ID" "$CONF_ID" "$POST_ID" "$LEGACY_ID" "$REVERSE_ID" "$ADMIN_ID"; do curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$id" -H "$AUTH_HEADER" \ -o /dev/null -w "%{http_code}\n" done curl -s -X PUT "$BASE_URL/api/v2/oauth2-provider/settings" -H "$AUTH_HEADER" \ -H "Content-Type: application/json" -d '{"dynamic_client_registration_enabled": false}' show -X POST "$BASE_URL/oauth2/register" -H "Content-Type: application/json" \ -d '{"client_name":"should-fail","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}' ``` ```text 204 (x6) {"dynamic_client_registration_enabled":false} HTTP 403 {"error":"invalid_request","error_description":"Dynamic client registration is disabled on this deployment"} ``` All six test apps deleted with no orphaned secret or token rows. Both seeded rows had already healed to a consistent state before deletion. DCR is back off, confirmed by a registration attempt rather than by reading the flag back. </details> |
||
|
|
9be61a0c65 |
feat: accept PKCE-only token exchange for public clients (#28047)
**TL;DR** Last of the stack, split out of #27873, that makes Coder usable by public OAuth2 clients (CLIs, IDE plugins, MCP clients), which cannot hold a secret and authenticate with PKCE alone. | PR | What it does | |---|---| | #27712 | Schema: `app_secret_id` becomes nullable and tokens gain an always-populated `app_id`, so ownership checks work without a secret row. | | #28041 | Accepts bare custom-scheme redirect URIs (`vscode://`, `cursor://`) that native apps actually register. | | #28043 | Derives and stores `client_type` (public vs confidential) from the requested `token_endpoint_auth_method`, and pins it across updates. | | #28046 | Registration issues no secret for a public client and returns no `client_secret`. | | **#28047 (this)** | The token endpoint accepts the exchange without a `client_secret`, so a public client can finally get a token. Discovery now advertises `none`. | Each of the earlier PRs is inert on its own: until this one, a registered public client still could not complete a flow. Dynamic client registration is off by default, so nothing here is user-visible until it is enabled. **Where in the flow** - Token endpoint only — the `authorization_code` exchange. Authorize, consent, and code issuance are untouched. - Refresh and revocation come along for free: both already bind by app_id, so a secretless token row works as-is. - Discovery starts advertising `none`. **What it satisfies** - OAuth 2.1 §3.2.1 — only *confidential* clients must authenticate at the token endpoint. A public client is no longer rejected for a missing secret. - OAuth 2.1 §4.1.3 — for a public client the server must instead ensure the code was issued to the request's client_id. That check already existed; here it becomes the sole binding. - OAuth 2.1 §4.1.3 — client_id is required when the client does not authenticate, and a code yields a token at most once: a failed PKCE comparison consumes the code, so a leaked one cannot be brute-forced. - OAuth 2.1 §2.1 + RFC 7591 §2 — `none` means public client with no secret. The type is derived at registration (#28043) and read here. - RFC 7636 §4.1 / §4.6 — a malformed verifier is `invalid_request`, a wrong one `invalid_grant`. PKCE was already mandatory for every code flow, so public clients inherit it. - RFC 8414 §2 — advertised auth methods now match what the token endpoint actually accepts. - RFC 7009 — a cross-app revoke of a public client's token still returns 200 without revoking. --- - The token endpoint stops requiring client_secret for a public client, in both the presence check and secret validation. PKCE was already mandatory for every authorization_code flow, so public clients inherit it with no new validation code. - The code ownership check (dbCode.AppID != app.ID) becomes the only binding between the exchange and the app named by client_id for a public client, where it was defense in depth for confidential ones. Retained, now covered with a public client on both sides. - Public client tokens carry a NULL app_secret_id rather than referencing a secret row that does not exist. Refresh and revocation already verify ownership via app_id, so they change only comments and coverage. - Discovery advertises `none` now that the token endpoint honors it. - Valid() derives from the single canonical auth method list, so what registration accepts and what discovery advertises cannot disagree. - Swagger marks client_secret confidential-only. Refs https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client |
||
|
|
57cbca585f |
feat: negotiate and persist authorization scope (#28178)
**TL;DR** Middle of the stack, split out of #28045, that makes an OAuth2 app's scope allowlist actually restrict what a client can be granted. The authorize endpoint has always parsed `scope` and then thrown it away. | PR | What it does | |---|---| | #28007 | Schema: `codes.scope` and `tokens.scope`, so a negotiated scope has somewhere to live. Every code is still stamped unrestricted. | | #28167 | `ScopesCover` compares an allowlist against a request by permission coverage rather than by name, and fails closed on any shape it does not model. Added with no production callers. | | **#28178 (this)** | The authorize endpoint checks the request against the scope catalog, grants it only if the app's filtered allowlist covers it, and persists the result on the code. Both GET and POST negotiate, so a doomed request fails before the consent page renders. | | #28179 | The consent page states what was negotiated, and `invalid_scope` is delivered to the client's own callback per RFC 6749 §4.1.2.1 instead of a Coder error page. | - Each earlier PR is inert alone: the columns carry a placeholder, the coverage rules have no caller. - Visible on upgrade, unlike the rest of the stack. A scope name outside the catalog, OIDC vocabulary included, now gets `invalid_scope`, on admin-created apps as well as DCR ones. - Tokens are unaffected. This changes which authorization requests succeed, not what a token can do. **Where in the flow** - Authorize endpoint only, both legs: GET before the consent page renders, POST before the code is minted. The token exchange, refresh, and revocation are untouched. - The result is persisted on the authorization code. The exchange copies it onto the token row, but the API key it mints still carries no scope, so nothing is enforced at request time yet. - Registration and discovery are unchanged. The catalog checked against is the `scopes_supported` both discovery documents already advertise. **What it satisfies** - OAuth 2.1 §1.4.1 — the server "MAY fully or partially ignore the scope requested by the client, based on the authorization server policy". The app's allowlist is that policy; until now the server ignored scope in every direction. - OAuth 2.1 §1.4.1 — on an omitted scope it "MUST either process the request using a pre-defined default value or fail the request". The filtered allowlist is that default; an allowlist filtering to nothing takes the second branch. Same rule as RFC 6749 §3.3. - OAuth 2.1 §1.4.1 — scope values "are defined by the authorization server", and OIDC is named there as an extension that defines its own. Hence `invalid_scope` for openid/profile/email rather than silent acceptance. - OAuth 2.1 §4.1.2.1 — `invalid_scope` is "invalid, unknown, or malformed", which now covers an uncatalogued name and an over-broad one alike. Delivery is interim here (static page on GET, error body on POST); §4.1.2.1 wants it redirected to the client's callback, which is #28179. - OAuth 2.1 §4.1.1 — `scope` stays OPTIONAL. Omitting it selects a default, never an error. - RFC 7591 §2 — a registered `scope` is the list "the client can use when requesting access tokens", a ceiling rather than a menu. Enforced here for the first time; a client that registered an unsupportable one repairs it via RFC 7592. - RFC 8414 §2 — `scopes_supported` is that catalog, advertised since before this stack, so a conformant client had no grounds to send a name outside it. - Not yet: §1.4.1 also requires `scope` in the token response when the grant differs from the request. Tokens are untouched here, so that lands with enforcement. --- Split out of #28045 ([PLAT-479](https://linear.app/codercom/issue/PLAT-479)). #28167 has merged, so this diff is against main and reviews on its own. The authorize endpoint parsed scope and threw it away, so an app's allowlist never restricted anything and a client asking for too much was never told no. Phase 1 added the columns that carry a negotiated scope from a code to the token, but nothing wrote one. **What changes** - Requested names must be in the external scope catalog. The app's stored allowlist is filtered through that same catalog, which only ever narrows. - The allowlist bounds authority, not spelling. A request is granted when every permission it grants is also granted by the allowlist, named or not, so an app allowed coder:workspaces.access can approve a client asking only for workspace:ssh. - Omitting scope grants the filtered allowlist (RFC 6749 §3.3). - Both handlers negotiate, so a request that cannot succeed fails before the consent page renders rather than after the user clicks Allow. - Two paths produce an empty result and stay distinct. No allowlist and no request keeps the previous unrestricted grant, written as an explicit sentinel because the column is NOT NULL with a non-empty CHECK. An allowlist filtering to nothing is rejected, since falling back would grant more than it ever permitted. **Accepted compatibility break, and it is wider than DCR.** The catalog check runs before the allowlist is consulted, so it covers admin-created apps too. - Admin-created apps store no allowlist and had scope discarded outright. A client sending OIDC vocabulary (openid, profile, email) now gets invalid_scope on upgrade. - DCR apps registered with openid, read or admin also hold allowlists this server cannot grant from, and fail in both directions. - scopes_supported has always been advertised on both discovery documents, predating this stack, so a conformant client had no grounds to send an uncatalogued name. RFC 6749 §4.1.2.1 makes invalid_scope the answer for one that does. - Grandfathering would seed the enforcement path with values it cannot evaluate: a visible error now, a silent hole later. - The rejection names the registered scopes and the remedy. Pinned in TestOAuth2AuthorizeDCRScopeCompatibility. **Interim error delivery, replaced in PR 3.** Rejections go out however each handler already reports errors: a static error page on GET, an OAuth2 error body on POST. #28179 delivers them to the client's own callback (RFC 6749 §4.1.2.1) and rewrites the requireInvalidScope helper. About 25 lines here are interim on purpose and flagged as such in that helper. **Not changed.** Issued tokens are still unrestricted. The exchange copies the negotiated scope onto the token record, but the API key it mints carries no scope. This changes which authorization requests succeed, not what a token can do. Stack: #28167 (merged), this PR, then #28179 for the consent page and the invalid_scope redirect. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: Steven Masley <Emyrk@users.noreply.github.com> |
||
|
|
2a8e390f0c |
refactor: replace most usage of ptr.Ref with new (#28282)
|
||
|
|
6348c83142 |
feat: register public clients without a secret (#28046)
Third in the stack, split out of #27873. This is where dynamic client registration first produces a public client. - A registration requesting token_endpoint_auth_method `none` issues no secret and persists the client_type derived in #28043. The response omits client_secret entirely, per RFC 7591 §3.2.1. - Discovery still advertises only the two secret-based methods. `none` is withheld until the token endpoint honors it, so a conforming client is not told to attempt an exchange that would be rejected. - The app and its secret are written in one transaction. They were two independent inserts, so a failed second one left a committed app that could never authenticate while still holding a registration access token. Pre-existing, but a public client's missing secret row makes the orphaned case unspottable by inspection. - registration_client_uri uses url.JoinPath, fixing a trailing-slash access URL producing //oauth2/clients/{id}. - Docs state both limits above, so the page does not describe a flow that returns 400 until #28047 lands. A client registered here cannot obtain a token yet; #28047 adds that. Dynamic client registration is off by default, so none of this is user-visible until then. Refs https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client |
||
|
|
663f41ffa9 |
feat: derive OAuth2 client type from token_endpoint_auth_method (#28043)
Adds an OAuth2 client type (public vs confidential, RFC 7591 §2) derived from the requested auth method instead of hardcoded confidential. The type is stored and guarded here, but no endpoint enforces on it yet; public behavior at the token endpoint follows in the next PR in the stack. - Client type is derived once and reused by both registration and redirect URI validation, so they can't disagree - IsPublic() fails closed: an unrecognized or missing value reads as confidential - RFC 7592 update (PUT) now rejects moving a client between public and confidential (400) instead of silently flipping it when the auth method is omitted - Discovery still doesn't advertise "none"; follows once the token endpoint honors it ### Behavior by client shape `client_type` is derived from `token_endpoint_auth_method` at POST and pinned at PUT. RFC 7592 GET/PUT authenticate with the registration access token, not the client secret, so neither endpoint reads a secret. | Registered with | Stored `client_type` / method | GET reports | PUT that flips the method | |------------------------------------|---------------------------------------|-----------------------|-----------------------------------------| | omitted, or `client_secret_basic` | `confidential` / `client_secret_basic` | `client_secret_basic` | `none` → 400 `invalid_client_metadata` | | `none` (new) | `public` / `none` | `none` | `client_secret_*` → 400 `invalid_client_metadata` | | `none` (before this PR) | `confidential` / `none` | `none` | either → 200, type stays `confidential` | - PUT still replaces every other RFC 7591 field. `client_type` is the only pinned one; the method may move within a type (`client_secret_basic` ↔ `client_secret_post`). - Row 3 is the only shape where the two columns disagree. The guard fires only on a method change that crosses the type line, so those clients keep managing themselves instead of being locked out of their own configuration endpoint. - The token endpoint does not consult `client_type` yet, so every client still authenticates with a secret and registration still issues one. Split out of #27873, second in the stack (on top of #28041). Refs https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client |
||
|
|
1aa3553b52 |
fix(coderd): set Cache-Control: no-store on OAuth2 responses (#28143)
No response from the `/oauth2` route tree set `Cache-Control` at all, so
an intermediary cache or customer-operated reverse proxy was free to
apply a heuristic freshness lifetime to a response carrying a live
credential. RFC 6749 §5.1 and OAuth 2.1 §3.2.3 both make an affirmative
`no-store` directive a MUST for the authorization server.
Adds `httpmw.NoStore`, mounted on the `/oauth2` and
`/api/v2/oauth2-provider` trees, setting `Cache-Control: no-store` and
`Pragma: no-cache` on every response from them. OAuth 2.1 drops `Pragma`
because RFC 9111 §5.4 deprecates it as a request-only field, so sending
both is conformant under either reading. Not operator-configurable,
since both specs say MUST.
## Scope
- **Both trees, not just `POST /oauth2/tokens`.** The mount is one line
either way, and the wider scope also covers DCR registration, client
configuration read and update, the authorize 302 whose `Location` query
carries the code, and `POST /oauth2-provider/apps/{app}/secrets`, which
returns a plaintext client secret. A route added later inherits the
headers, which matters for PLAT-449.
- **A middleware, not a hook in `httpapi.Write`.** Three write paths
never call it: `POST /oauth2/revoke` and `DELETE
/oauth2/clients/{client_id}` write a bare status, and
`writeOAuth2RegistrationError` encodes its own JSON.
- **`/.well-known/*` deliberately excluded.** Public discovery metadata,
and RFC 9728 §5 asks for the opposite treatment. Assertions pin the
exclusion so a later hoist onto a higher router fails CI.
- **Session-credential routes left alone.** `/users/login`,
`/users/otp/change-password`, and `/users/{user}/keys/*` have the same
gap, but PLAT-448 is scoped to OAuth2 and reaching into session auth
changes the risk profile.
Every credential-returning route here is a `POST`, and RFC 9111 §3 bars
heuristic caching of `POST` responses, so this is defense-in-depth
against a non-conformant intermediary rather than a live caching bug.
Both specs say MUST regardless of what caches would actually do.
## Note for PLAT-498
`DELETE /oauth2/tokens` now carries `no-store` and is wrapped in
`apiKeyMiddleware`, which is mounted inside the `/oauth2` tree and
therefore runs after this middleware. It is the one route where both can
write `Cache-Control`, and PLAT-498's write must not replace `no-store`
with something weaker such as `private`. `POST /oauth2/tokens` cannot
overlap, since it deliberately has no `apiKeyMiddleware`.
## Two assumptions testing corrected
- `GET /oauth2/does-not-exist` returns **200**, not 404. Chi runs the
subrouter's middleware chain for unmatched paths, so both headers are
present, but the request falls through to the root router's SPA handler.
The test asserts the headers and deliberately not the status.
- The experiment-disabled case is unreachable from a test binary, since
`RequireExperimentWithDevBypass` short-circuits on `buildinfo.IsDev()`.
A unit test covers the consequence against the `RequireExperiment` it
delegates to.
No schema, `codersdk`, or serpent option changes, so `make gen` produces
no diff. Rollback is a revert.
Refs PLAT-448
|
||
|
|
990d24dc42 |
feat: add oauth2 scope columns and single-use delete queries (#28007)
OAuth2 tokens issued by Coder ignore scope entirely. The authorize endpoint parses the `scope` parameter and then discards it, and both grant paths mint API keys with full API access regardless of what the client requested or what the app's allowlist permits. There is also nowhere to put a negotiated scope: nothing carries one from the authorize step to the token it produces. Schema and query groundwork for that pipeline. No behavior change on its own. - Migration `000569` adds a `scope` column to `oauth2_provider_app_codes` and `oauth2_provider_app_tokens`, so a negotiated scope can travel from a code to the token it is exchanged for, and from a token to its refreshed successor. - Existing rows are backfilled to `coder:all`, then both columns become NOT NULL with a non-empty CHECK. Every OAuth2 key is unrestricted in fact today, so the backfill only writes that down, and a caller that omits the column now fails instead of silently issuing full access. - Adds `DeleteOAuth2ProviderAppCodeByIDReturningRow` and `DeleteAPIKeyByIDReturningRow`, which return `sql.ErrNoRows` when the row is already gone. Postgres serializes concurrent deletes on the row lock, so exactly one caller gets a row back, which is what will let the grant paths enforce single use of a code or refresh token without a read-then-write race. - No callers yet. The existing blind deletes and all of their call sites are untouched, and codes and tokens record `coder:all` until a later phase negotiates a real value. Phase 1 of [PLAT-470](https://linear.app/codercom/issue/PLAT-470), tracked as [PLAT-478](https://linear.app/codercom/issue/PLAT-478/phase-1-schema-and-queries). Scope validation at authorize, applying the negotiated scope in the code grant, and refresh narrowing follow as separate PRs. Verified locally: `make gen` and `make lint` clean, the migrations suite passes both up and down, and dbauthz's `TestMethodTestSuite` passes. <details> <summary>End-to-end scope enforcement flow (green marks what this PR touches)</summary> ```mermaid flowchart TD subgraph authorize["/oauth2/authorize"] AZ1["ShowAuthorizePage (GET)<br/>renders consent page"] AZ2["ProcessAuthorize (POST)<br/>scope parsed, then discarded"] Q1["InsertOAuth2ProviderAppCode<br/>gains a Scope param"] AZ1 --> AZ2 --> Q1 end Q1 --> CODES[("oauth2_provider_app_codes<br/>new column: scope text NOT NULL")] subgraph codegrant["POST /oauth2/token, grant_type=authorization_code"] G1["authorizationCodeGrant"] Q2["GetOAuth2ProviderAppCodeByPrefix<br/>now returns Scope"] Q4["DeleteOAuth2ProviderAppCodeByIDReturningRow<br/>added, no caller yet"] G2["apikey.Generate + UserRBACSubject<br/>hardcoded to full access"] G1 --> Q2 --> G2 G1 -.-> Q4 end CODES --> G1 G2 --> Q3 Q3["InsertOAuth2ProviderAppToken<br/>gains a Scope param"] Q3 --> TOKENS[("oauth2_provider_app_tokens<br/>new column: scope text NOT NULL")] subgraph refresh["POST /oauth2/token, grant_type=refresh_token"] G3["refreshTokenGrant"] Q5["GetOAuth2ProviderAppTokenByPrefix<br/>now returns Scope"] Q6["DeleteAPIKeyByIDReturningRow<br/>added, no caller yet"] G3 --> Q5 G3 -.-> Q6 end TOKENS --> G3 Q5 --> Q3 subgraph enforce["Every authenticated API request"] E1["httpmw ExtractAPIKey"] --> E2["APIKey.ScopeSet()"] --> E3["UserRBACSubject"] --> E4["dbauthz authorize"] end TOKENS --> E1 classDef changed fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,color:#1b3c1e classDef dormant fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px,stroke-dasharray:5 3,color:#1b3c1e class Q1,Q2,Q3,Q5,CODES,TOKENS changed class Q4,Q6 dormant ``` Solid green is added or changed here. Dashed green exists but has no caller yet. Everything else is unchanged, including the enforcement engine at the bottom, which already reads a key's scopes correctly and only needs real data fed into it. </details> <details> <summary>Suggested reading order</summary> Most of the diff is generated. `dump.sql`, `models.go`, `querier.go`, `queries.sql.go`, `check_constraint.go`, and the dbmock and dbmetrics packages all come from `make gen`. 1. `migrations/000569_oauth2_scope_columns.{up,down}.sql`: additive column, backfill, NOT NULL, CHECK, and a `COMMENT ON COLUMN` on each. 2. `queries/oauth2.sql` and `queries/apikeys.sql`: `scope` added to both insert column lists, plus the two new returning-row deletes alongside the untouched originals. The `Get...ByPrefix` selects needed no edit, since they are `SELECT *`. 3. `dbauthz/dbauthz.go`: hand-written wrappers for the two new queries, each fetching by ID, authorizing delete against the fetched object, then delegating. The generic `deleteQ` helper does not fit, since it requires the delete to return only `error`. 4. `oauth2provider/authorize.go` and `oauth2provider/tokens.go`: the only production changes, all behavior-neutral. 5. `dbgen/dbgen.go` and `dbauthz/dbauthz_test.go`: seed threading, plus a case per new query. `MethodTestSuite` fails with "Method never called" for anything untested. Neither type needs to become auditable, which `make lint` confirms by not erroring on `enterprise/audit/table.go`. </details> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
209d1ca498 |
fix: reject PKCE code_verifier below RFC 7636 length floor (#28003)
The token endpoint accepted any non-empty `code_verifier`, so a one-character verifier was enough to authenticate. RFC 7636 §4.1 requires 43 to 128 characters from the unreserved set. That fix plus the related gaps review surfaced in the same path: - Enforce the length and charset floor on the verifier before the S256 comparison runs. - Validate the challenge at the authorize endpoint too. It was only checked for non-emptiness, so a malformed challenge was stored and then failed late at token exchange, blaming the wrong parameter. - A malformed verifier now returns `invalid_request` (RFC 6749 §5.2); a well-formed but wrong one still returns `invalid_grant` (RFC 7636 §4.6). Both looked identical before, so a client had no way to tell a syntax error from a hash mismatch and would retry the same bad verifier forever. - Revoke the authorization code when a PKCE check fails. Without that, a leaked code could be replayed with unlimited verifier guesses for its remaining lifetime, and RFC 6749 §10.5 requires codes to be single use. - Fix verifier generation in `scripts/oauth2/*.sh` and the docs example. They deleted reserved base64 characters instead of translating them to the URL-safe alphabet, so most runs produced verifiers under the new floor. Also carries #28041, which merged into this branch: public clients may register bare custom schemes such as `vscode://` again, with `mailto`, `tel`, and `sms` rejected. Split out of #27873 (public OAuth2 client support). PKCE is already mandatory for every client, so this stands on its own. <details> <summary>Manual verification</summary> Ran against a local dev server on this branch, using a session token and a throwaway app from `scripts/oauth2/setup-test-app.sh`. 1. Happy path unchanged: HTTP 200, verifier length 43. 2. `code_verifier=short`, and a 43-character verifier ending in `!`: both HTTP 400 `invalid_request`, so charset is enforced and not just length. 3. `code_challenge=tooshort` at authorize: HTTP 400 `invalid_request`, no code issued. An empty challenge still hits the older "required and cannot be empty" message. 4. Well-formed but wrong verifier: HTTP 400 `invalid_grant`, distinct from the cases above. 5. Retrying that same code with the correct verifier: HTTP 400, code already revoked by the failed check. 6. `generate-pkce.sh` produces a 43-character verifier (20 out of 20 runs); the docs example produces 128. 7. `scripts/oauth2/test-mcp-oauth2.sh` passes end to end. The two bearer-token failures in its output are a pre-existing script bug (`09c50559f3`, July 2025) that reuses a resource-scoped token against the real API, not a regression here. </details> |
||
|
|
16c58770f8 |
feat: constrain the OAuth2 client type column (#27931)
Extracted from #27873 so the schema change can be reviewed for migration safety on its own. #27873 will rebase onto this. `client_type` decides whether the token endpoint validates a client secret at all, and the column accepts any text: nullable, no `CHECK`, no enum. No Go path can write a bad value today, and `IsPublic` fails closed on anything unrecognized, so the read side is safe. What the schema still permits is the problem: a future migration writing `'public'` onto a row that holds a secret turns off client authentication for that app with nothing to catch it, no constraint, no log, no audit entry, no test. `000565` adds `CHECK (client_type IN ('confidential', 'public'))` and `NOT NULL`. The `UPDATE` ahead of it should touch zero rows, since migration `000344` added the column with a default of `'confidential'` and backfilled with `COALESCE`; it is there so `SET NOT NULL` cannot fail on an unexpected row. Both `ALTER`s take `ACCESS EXCLUSIVE` and scan a table holding one row per registered OAuth2 client, so the lock is brief. ## The second migration, and why it aligns the way it does Two columns describe the same fact and can currently contradict each other. `token_endpoint_auth_method` is the client's own declaration: registered client metadata under RFC 7591 §2, where `"none"` is defined to mean the client is public and has no secret. `client_type` is Coder's derived copy, and it is what the token endpoint enforces on. RFC 7591 defines no `client_type` metadata field; the column exists only as a denormalization. Registration used to persist the declaration verbatim while hardcoding `client_type` to `'confidential'`, so rows exist declaring `"none"` on a client stored confidential that was issued, and still requires, a real secret. A client that reads its own metadata and believes it is public will drop that secret and stop being able to exchange codes. `000566` aligns the declaration to what is enforced, not the reverse. Deriving enforcement from the declaration would reclassify every such client as public and stop requiring the secret it holds, which is a silent authentication downgrade. The down migration is deliberately empty: the previous values are not recorded, and restoring them would only reinstate metadata that tells a client to authenticate in a way the server rejects. ## Application changes `SET NOT NULL` changes the generated field from `sql.NullString` to `string`, so the three write sites are updated to match. That is the entire application diff and no behavior depends on it. Refs https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
d814dfad88 |
feat(coderd): support public OAuth2 client tokens at the schema layer (#27712)
Layer 1 of a multi-PR split of #27195 (public/secretless PKCE-only OAuth2 clients), broken up for easier review: **database schema (this PR)** → oauth2provider handler logic → API/e2e integration tests. ## Goal Coder's OAuth2 provider only works correctly for confidential clients today. Public clients — native apps that can't safely hold a shared secret, such as the CLI's browser-based login flow, IDE plugins (VS Code, JetBrains), desktop apps, and MCP clients — cannot complete a real OAuth2 flow against Coder, even though OAuth 2.1 §2.1 explicitly defines this client type and RFC 8252 §8.5 requires PKCE alone to be sufficient authentication for it. Every MCP client, CLI login flow, and IDE plugin is a public client by construction, and none of them can complete a secretless flow against Coder today: dynamic registration always classifies a client as confidential regardless of what it asks for, the token endpoint unconditionally requires a `client_secret`, and discovery metadata never advertises `"none"` as a supported auth method. Full write-up: [ENG-3029](https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client) ### Overall design (end state across the full PR stack) `[PR2]` marks handler-layer changes landing in the next PR in this stack. The green box is what this PR implements. ```mermaid sequenceDiagram autonumber participant C as Public Client (CLI/MCP/IDE plugin) participant S as coderd (chi router) participant H as oauth2provider handlers participant DB as PostgreSQL Note over C,S: Discovery C->>S: GET /.well-known/oauth-authorization-server S->>H: GetAuthorizationServerMetadata() Note over H: [PR2] add "none" to<br/>the returned auth methods list H-->>C: [PR2] 200 { token_endpoint_auth_methods_supported:<br/>[..., "none"] } Note over C,S: Dynamic Client Registration C->>S: POST /oauth2/register<br/>{redirect_uris, token_endpoint_auth_method: "none"} S->>H: CreateDynamicClientRegistration() Note over H: [PR2] client type now reads<br/>the request -> "public" Note over H: [PR2] skip secret generation<br/>for public clients H->>DB: [PR2] INSERT app row<br/>(client_type = 'public') DB-->>H: app row Note over H: [PR2] skip secret insert entirely H-->>C: [PR2] 201 { client_id }<br/>(no client_secret field) Note over C,S: Authorization Code + PKCE flow C->>S: GET /oauth2/authorize?client_id=...&code_challenge=... C->>S: POST /oauth2/tokens (grant_type=authorization_code)<br/>no client_secret S->>H: extractTokenRequest() Note over H: [PR2] client_secret no longer required<br/>for public clients H->>H: authorizationCodeGrant() Note over H: [PR2] skip secret lookup for public clients Note over H: PKCE verification — already mandatory, unchanged rect rgb(198, 239, 206) Note over H,DB: [THIS PR] oauth2_provider_app_tokens.app_id<br/>column added (NOT NULL, populated at insert<br/>time from app.ID) and app_secret_id loosened<br/>to nullable. Revocation now checks app_id<br/>directly. Confidential-client behavior is<br/>unchanged — no public client can be created yet. H->>DB: [PR2] INSERT refresh token row<br/>(no secret reference, for public clients) end DB-->>H: token row H-->>C: 200 { access_token, refresh_token } ``` ## This PR: database schema A public client has no `client_secret`, so it has nothing to put in `oauth2_provider_app_tokens.app_secret_id`, which was `NOT NULL`. This PR makes that column nullable and instead attributes a token to its owning app through a new, always-populated `app_id` column — so ownership checks (e.g. revocation) work identically for public and confidential clients without joining through a secret that may not exist. | Column | Before | After (this PR) | |---|---|---| | `app_secret_id` | `uuid NOT NULL` | **nullable** | | `app_id` | — | **new**: `uuid NOT NULL`, `FOREIGN KEY → oauth2_provider_apps(id) ON DELETE CASCADE`, backfilled for every existing row and populated on every new insert from that point on | This is a single, complete migration — not staged across multiple PRs. An earlier version of this branch deferred `app_secret_id`'s nullability and the insert-time population of `app_id` to a later PR, keeping this PR's diff limited to `coderd/database`. [Automated review](https://github.com/coder/coder/pull/27712#discussion_r3686851911) correctly flagged that as unsafe: the migration would backfill existing rows once, but nothing would populate `app_id` for rows written afterward, so the moment this PR merged, new tokens would start accumulating a permanently `NULL` app_id — and if a release happened to be cut before the follow-up PR landed, that gap could ship to customers and would need a second, later backfill to close. Doing the full migration now avoids that: `app_id` is correct from the first row written, and the promised `NOT NULL` constraint requires no data repair because it's already enforced. Closing that gap requires a few mechanical, non-branching touches outside `coderd/database`: - `revoke.go`'s two ownership checks now compare `dbToken.AppID` directly instead of looking up the app through `app_secret_id` — a genuine simplification (and slightly less code), not a temporary shim. - `tokens.go`'s two `InsertOAuth2ProviderAppToken` call sites supply the new `app_id` column and wrap `app_secret_id` as a `NullUUID`. - `oauth2_test.go`'s one direct-insert test fixture does the same. None of these introduce client-type branching or new capability — every client today is still confidential-only, still always presents a secret, and behavior is unchanged. The full repo builds, vets, and all existing tests pass unmodified in behavior. ## Coming next - **PR2 (handler layer)**: `codersdk`'s `DetermineClientType()` reading the requested `token_endpoint_auth_method`; `registration.go` skipping secret generation for public clients (and wrapping the app+secret insert in a single transaction, fixing a pre-existing orphan-row/visibility-race gap); `tokens.go` making the secret check conditional so PKCE alone authenticates a public client; `metadata.go` advertising `"none"` in discovery. No further migration is needed — the schema this PR ships is already final. - **PR3 (API/e2e layer)**: integration tests through the real HTTP API (`coderd/oauth2_test.go`), the MCP OAuth2 e2e flow (`coderd/mcp/mcp_e2e_test.go`), and the manual test script (`scripts/oauth2/test-mcp-oauth2.sh`). Depends on: #27195 (original combined PR, being superseded by this stack) --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
fbac602456 |
feat!: add admin-controlled dynamic client registration toggle (#27316)
`POST /oauth2/register` (RFC 7591 Dynamic Client Registration) has exactly one gate today: `ExperimentOAuth2`, a static, process-lifetime flag that wraps the entire `/oauth2/*` route tree as an all-or-nothing switch. That flag is scheduled for removal at GA, which would leave DCR with zero admin control at all once it is gone. Add a persistent, DCR-specific `oauth2_dcr_enabled` deployment setting, independent of the experiment system, so admin control over DCR survives GA. `POST /oauth2/register` checks the flag and rejects new registrations with an RFC 7591-shaped `403` when disabled; discovery metadata (`GET /.well-known/oauth-authorization-server`) conditionally omits `registration_endpoint`. A new audited `GET`/`PUT /api/v2/oauth2-provider/settings` endpoint lets an owner toggle it live, no restart required. The setting defaults to disabled, matching the canonical design proposal; disabling only stops new self-registrations, clients that already registered continue to authorize and exchange tokens normally. Address issue described in [ENG-3056](https://linear.app/codercom/issue/ENG-3056/oauth2-dcr-admin-configurable-enabledisable). ## Where this sits in the request path ```mermaid sequenceDiagram autonumber participant A as Admin participant S as coderd participant DB as site_configs<br/>(oauth2_dcr_enabled) participant C as OAuth2/MCP Client Note over A,S: Admin toggles DCR (new) A->>S: PUT /api/v2/oauth2-provider/settings<br/>{dynamic_client_registration_enabled: false} S->>S: authorizeContext(ActionUpdate, ResourceDeploymentConfig) S->>DB: UPSERT oauth2_dcr_enabled = false S-->>A: 200 OK (audited) Note over C,S: Client discovery + registration afterward C->>S: GET /.well-known/oauth-authorization-server S->>DB: GetOAuth2DCREnabled (system ctx, every request, no cache) DB-->>S: false S-->>C: 200 metadata, registration_endpoint omitted C->>S: POST /oauth2/register S->>DB: GetOAuth2DCREnabled (system ctx, every request, no cache) DB-->>S: false S-->>C: 403 invalid_request,<br/>"Dynamic client registration is disabled" Note over C,S: A client that registered before the change is unaffected C->>S: GET /oauth2/authorize?client_id=... Note over S: no DCR-enabled check on this path S-->>C: 200 (proceeds normally) C->>S: PUT/DELETE /oauth2/clients/{client_id} (RFC 7592 self-management) Note over S: no DCR-enabled check on this path either S-->>C: 200 (proceeds normally) ``` ## Files changed: manual vs. generated Reviewers should focus on the **manual** files. The **generated** ones are `make gen` output that follows mechanically from the manual changes and don't need direct review. <details> <summary><b>Manual files (26)</b> — click to expand, grouped the same way as "Suggested review order" below</summary> **1. Database** | File | What changed | |---|---| | `coderd/database/queries/siteconfig.sql` | New `GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled` query pair on the existing generic `site_configs` table. No schema change. | | `coderd/database/dbauthz/dbauthz.go` | RBAC check (`rbac.ResourceDeploymentConfig`) on the two new query methods; extends the `subjectSystemOAuth2` system-actor role with read-only `ResourceDeploymentConfig` access, needed so the public discovery/registration endpoints can read the flag via `dbauthz.AsSystemOAuth2`. | | `coderd/database/dbauthz/dbauthz_test.go` | RBAC assertion coverage for `GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled` in the method-coverage test suite. | **2. Request gating (the actual feature)** | File | What changed | |---|---| | `coderd/oauth2provider/registration.go` | The actual gate: `CreateDynamicClientRegistration` reads the flag first and returns an RFC 7591-shaped `403` when disabled (defaults disabled if never configured). | | `coderd/oauth2provider/registration_test.go` | New unit test, `TestCreateDynamicClientRegistration_DCREnabled`: calls the handler directly (no HTTP server), covering enabled / explicitly disabled / never-configured. | | `coderd/oauth2provider/metadata.go` | `GetAuthorizationServerMetadata` conditionally omits `registration_endpoint` from discovery metadata when DCR is disabled. | | `coderd/oauth2provider/metadata_test.go` | New unit test, `TestGetAuthorizationServerMetadata_DCREnabled`: same three states, for the discovery handler. | **3. Admin settings endpoint** | File | What changed | |---|---| | `codersdk/oauth2.go` | New `OAuth2ProviderSettings` SDK type plus `Client.OAuth2ProviderSettings`/`PutOAuth2ProviderSettings` methods. | | `coderd/oauth2.go` | New `oauth2ProviderSettings`/`putOAuth2ProviderSettings` admin handlers (audited via `audit.InitRequest`); updates the `GetAuthorizationServerMetadata` call site to pass `api.Database`. | | `coderd/coderd.go` | Registers `GET`/`PUT /api/v2/oauth2-provider/settings`. | | `coderd/oauth2_provider_settings_test.go` | New test file: admin `GET`/`PUT` round-trip, default-disabled-before-any-`PUT`, and `403` for a non-owner on both `GET` and `PUT`. | **4. Audit wiring** | File | What changed | |---|---| | `coderd/database/types.go` | New `database.OAuth2ProviderSettings` audit-only struct (mirrors `NotificationsSettings`). | | `coderd/audit/diff.go` | Adds the new struct to the `Auditable` type union. | | `coderd/audit/request.go` | Adds the new struct to all four dispatch switches (`ResourceTarget`, `ResourceID`, `ResourceType`, `ResourceRequiresOrgID`). | | `codersdk/audit.go` | New API-facing `ResourceTypeOAuth2ProviderSettings` constant and its `FriendlyString` case. | | `enterprise/audit/table.go` | Field-level audit action map (`ActionTrack`/`ActionIgnore`) for the new struct. | | `coderd/database/migrations/000546_audit_oauth2_provider_settings.up.sql` | Adds `oauth2_provider_settings` to the `resource_type` Postgres enum, required for the audit wiring above (`resource_type` is a real enum, not a Go-only value). | | `coderd/database/migrations/000546_audit_oauth2_provider_settings.down.sql` | No-op (`ALTER TYPE ... ADD VALUE` can't be reverted). | **5. Test-suite ripple from the disabled-by-default flip** | File | What changed | |---|---| | `coderd/oauth2provider/oauth2providertest/helpers.go` | New shared test helper, `EnableDCR`, since DCR now defaults to disabled and many pre-existing tests need it turned on to register a client. | | `coderd/oauth2_test.go` | Adds `TestOAuth2DynamicClientRegistrationDisabled` (registers a client, disables DCR, verifies new registration is rejected while the existing client's self-management, authorize, and token exchange all keep working); calls `EnableDCR` in every pre-existing test that registers a client. | | `coderd/oauth2_error_compliance_test.go` | Calls `EnableDCR` in every test that registers a client, so RFC-error-format assertions aren't masked by the new disabled-by-default gate. | | `coderd/oauth2_metadata_validation_test.go` | Same: `EnableDCR` added to every registration-dependent test. | | `coderd/oauth2_security_test.go` | Same. | | `coderd/oauth2provider/validation_test.go` | Same (near-duplicate of `oauth2_metadata_validation_test.go` in a different package). | | `coderd/oauth2provider/provider_test.go` | Same. | | `coderd/mcp/mcp_e2e_test.go` | Same, for the MCP end-to-end dynamic-registration flow test. | </details> <details> <summary><b>Generated files (12)</b> — from <code>make gen</code>, no need to review directly</summary> `coderd/apidoc/docs.go`, `coderd/apidoc/swagger.json`, `coderd/database/dbmetrics/querymetrics.go`, `coderd/database/dbmock/dbmock.go`, `coderd/database/dump.sql`, `coderd/database/models.go`, `coderd/database/querier.go`, `coderd/database/queries.sql.go`, `docs/admin/security/audit-logs.md`, `docs/reference/api/enterprise.md`, `docs/reference/api/schemas.md`, `site/src/api/typesGenerated.ts`. </details> ## Suggested review order ### 1. Database Establishes the persisted setting and its RBAC rule; everything else builds on `GetOAuth2DCREnabled`/`UpsertOAuth2DCREnabled`. 1. `coderd/database/queries/siteconfig.sql` — the two new queries. Same boolean-encoding pattern as the existing `oauth2_github_default_eligible` key right above them in the same file. 2. `coderd/database/dbauthz/dbauthz.go` — the RBAC wrapper for those two queries, plus the `subjectSystemOAuth2` role extension (search this file for `ResourceDeploymentConfig`, it appears in both spots). 3. `coderd/database/dbauthz/dbauthz_test.go` — asserts the RBAC checks from (2) actually fire. ### 2. Request gating (the actual feature) Where `POST /oauth2/register` and discovery metadata change behavior. 1. `coderd/oauth2provider/registration.go` — the primary gate. Read this first; it's the feature. 2. `coderd/oauth2provider/registration_test.go` — its new unit test, exercising the gate's three states directly against the handler. 3. `coderd/oauth2provider/metadata.go` — the same gating pattern applied to the discovery `GET` endpoint. 4. `coderd/oauth2provider/metadata_test.go` — its new unit test. ### 3. Admin settings endpoint How an owner flips the setting live. 1. `codersdk/oauth2.go` — the `OAuth2ProviderSettings` SDK type and `Client` methods first; this is the public contract everything below implements against. 2. `coderd/oauth2.go` — the `GET`/`PUT` handlers themselves. 3. `coderd/coderd.go` — route registration, to see where those handlers get wired in. 4. `coderd/oauth2_provider_settings_test.go` — round-trip and permission tests. ### 4. Audit wiring Plumbing required so step 3's `PUT` is auditable; mechanical except for (3). 1. `coderd/database/types.go` — the audit-only struct; everything else in this layer exists to plumb it through. 2. `coderd/audit/diff.go` — adds it to the `Auditable` type union (the compiler enforces this one). 3. `coderd/audit/request.go` — the four dispatch switches; the one part of this layer worth reading closely. 4. `codersdk/audit.go` — the API-facing resource type constant. 5. `enterprise/audit/table.go` — the field-action map. 6. `coderd/database/migrations/000546_audit_oauth2_provider_settings.{up,down}.sql` — read last; a consequence of needing a new `resource_type` enum value for (1)-(5), not a design decision of its own. ### 5. Test-suite ripple from the disabled-by-default flip 1. `coderd/oauth2provider/oauth2providertest/helpers.go` — the new `EnableDCR` helper. Read first to understand the fix pattern before seeing it applied repeatedly. 2. `coderd/oauth2_test.go` — next, since it also contains the new `TestOAuth2DynamicClientRegistrationDisabled`, not just `EnableDCR` call sites. 3. The rest, in any order, they're mechanical repeats of the same one-line addition: `coderd/oauth2_error_compliance_test.go`, `coderd/oauth2_metadata_validation_test.go`, `coderd/oauth2_security_test.go`, `coderd/oauth2provider/validation_test.go`, `coderd/oauth2provider/provider_test.go`, `coderd/mcp/mcp_e2e_test.go`. ## Explicitly out of scope Per the design proposal: rate limiting on `POST /oauth2/register` (tracked separately), retroactively affecting already-registered clients when DCR is disabled (this only gates new self-registration), and an Initial Access Token requirement (a separate, follow-up ticket). |
||
|
|
c650aabbef |
chore: standardize on *_internal_test.go for white-box tests (#25601)
My agent added `//nolint:testpackage` to a test file on one of my PRs. Again. This PR cleans it up across the entire repo and updates the in-repo conventions so future agents stop doing it. The repo already has a precedent for white-box tests that need to touch unexported symbols: `*_internal_test.go` (145+ existing files). The `testpackage` linter's default `skip-regexp` exempts that filename suffix, so the `//nolint:testpackage` directive is unnecessary in every case where someone reached for it. This PR renames 51 such files to `*_internal_test.go` via `git mv` so blame and history follow, and strips the dead directive from 2 files that were already correctly named (`coderd/oauth2provider/authorize_internal_test.go`, `coderd/x/chatd/advisor_internal_test.go`). `.claude/docs/TESTING.md` now documents the rule explicitly under *Test Package Naming*, which is imported into the root `AGENTS.md` via `@.claude/docs/TESTING.md`. The rule: prefer `package foo_test`; if you need internal access, rename the file to `*_internal_test.go` rather than adding a nolint directive. |
||
|
|
a8e7f329ac |
fix: redirect OAuth2 authorization page to dashboard (#24499)
Currently when a user clicks either the Cancel or Allow button on the authorization page the client app URI is executed but the page does not land to the main dashboard page, leaving the two buttons open for multiple clicks from the user. Aside from the potential problems it might cause by activating the callback URI multiple times, the page also provides poor UX because users usually expect the authorization tab to return to the dashboard. The consent page now executes the OAuth2 callback (auth code on Allow, `access_denied` on Cancel) and hides the two buttons and updates the existing description with a user instruction to close the window. Initial implementation relied on a pop-up window executing the callback while the main window was redirected to the dashboard main page. - resolves https://github.com/coder/coder/issues/20323 <!-- If you have used AI to produce some or all of this PR, please ensure you have read our [AI Contribution guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING) before submitting. --> |
||
|
|
83fd4cf5c2 |
fix: OAuth2 cancel button in the authorization page not working (#24058)
Go's html/template has a built-in security filter (urlFilter) that only allows http, https, and mailto URL schemes. Any other scheme gets replaced with #ZgotmplZ. The OAuth2 app's callback URL uses custom URI scheme which the filter considers unsafe. For example the Coder JetBrains plugin exposes a callback URI with the scheme jetbrains:// - which was effectively changed by the template engine into #ZgotmplZ. Of course this is not an actual callback. When users clicked the cancel button nothing happened. The fix was simple - we now wrap the apps registered callback URI into htmltemplate.URL. Usually this needs some validation otherwise the linter will complain about it. The callback URI used by the Cancel logic is actually validated by our backend when the client app programmatically registered via the dynamic OAuth2 registration endpoints, so we refactored the validation around that code and re-used some of it in the Cancel handling to make sure we don't allow URIs like `javascript` and `data`, even though in theory these URIs were already validated. In addition, while testing this PR with https://github.com/coder/coder-jetbrains-toolbox/pull/209 I discovered that we are also not compliant with https://www.rfc-editor.org/rfc/rfc6749#section-4.1.2.1 which requires the server to attach the local state if it was provided by the client in the original request. Also it is optional but generally a good practice to include `error_description` in the error responses. In fact we follow this pattern for the other types of error responses. So this is not a one off. - resolves #20323 <img width="1485" height="771" alt="Cancel_page_with_invalid_uri" src="https://github.com/user-attachments/assets/5539d234-9ce3-4dda-b421-d023fc9aa99e" /> <img width="486" height="746" alt="Coder Toolbox handling the Cancel button" src="https://github.com/user-attachments/assets/acab71a6-d29c-4fa9-80ba-3c0095bbdc8f" /> <!-- If you have used AI to produce some or all of this PR, please ensure you have read our [AI Contribution guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING) before submitting. --> |
||
|
|
3f55b35f68 |
refactor: replace AsSystemRestricted with narrower actors (#23712)
Replace overly-broad `AsSystemRestricted` with purpose-built actors:
- **OAuth2 provider paths** → `AsSystemOAuth2` (13 call sites across
`tokens.go`, `registration.go`, `apikey.go`)
- **Provisioner daemon health read** → `AsSystemReadProvisionerDaemons`
(1 site in `healthcheck/provisioner.go`)
- **Provisionerd file cache paths** → `AsProvisionerd` (2 sites in
`provisionerdserver.go`, matching existing usage nearby)
<details>
<summary>Implementation notes</summary>
Each replacement actor is a strict subset of `AsSystemRestricted`. Every
DB method
at each call site is already covered by the narrower actor's
permissions:
- `subjectSystemOAuth2`: OAuth2App/Secret/CodeToken (all), ApiKey (Read,
Delete), User (Read), Organization (Read)
- `subjectSystemReadProvisionerDaemons`: ProvisionerDaemon (Read)
- `subjectProvisionerd`: File (Create, Read) plus provisionerd-scoped
resources
No new permissions added. `nolint:gocritic` comments updated to reflect
the new actors.
</details>
> 🤖 Created by a Coder Agent, reviewed by me.
|
||
|
|
9e4c283370 |
test: share coderdtest instances in OAuth2 validation tests (#23455)
Consolidates invocations of `coderdtest.New` to a single shared instance per parent for the following tests: - `TestOAuth2ClientMetadataValidation` - `TestOAuth2ClientNameValidation` - `TestOAuth2ClientScopeValidation` - `TestOAuth2ClientMetadataEdgeCases` > 🤖 This PR was created with the help of Coder Agents, and was reviewed by my human. 🧑💻 |
||
|
|
b776a14b46 |
fix(coderd): harden OAuth2 provider security (#22194)
## Summary Harden the OAuth2 provider with multiple security fixes addressing `coder/security#121` (CSRF session takeover) and converge on OAuth 2.1 compliance. ### Security Fixes | Fix | Description | Commits | |-----|-------------|---------| | **CSRF on `/oauth2/authorize`** | Enforce CSRF protection on the authorize endpoint POST (consent form submission) | `ba7d646`, `b94a64e` | | **Clickjacking: `frame-ancestors` CSP** | Prevent consent page from being iframed (`Content-Security-Policy: frame-ancestors 'none'` + `X-Frame-Options: DENY`) | `597aeb2` | | **Exact redirect URI matching** | Changed from prefix matching to full string exact matching per OAuth 2.1 §4.1.2.1 | `73d64b1`, `93897f1` | | **Store & verify `redirect_uri`** | Store redirect_uri with auth code in DB, verify at token exchange matches exactly (RFC 6749 §4.1.3) | `50569b9`, `d7ca315` | | **Mandatory PKCE** | Require `code_challenge` at authorization (for `response_type=code`) + unconditional `code_verifier` verification at token exchange | `d7ca315`, `1cda1a9` | | **Reject implicit grant** | `response_type=token` now returns `unsupported_response_type` error page (OAuth 2.1 removes implicit flow) | `d7ca315`, `91b8863` | ### Changes by File **`coderd/httpmw/csrf.go`** — Extended the CSRF `ExemptFunc` to enforce CSRF on `/oauth2/authorize` in addition to `/api` routes. The consent form POST is now CSRF-protected to prevent cross-site authorization code theft. **`site/site.go`** — Added `Content-Security-Policy: frame-ancestors 'none'` and `X-Frame-Options: DENY` headers to `RenderOAuthAllowPage` (consent page only — does not affect the SPA/global CSP used by AI tasks). **`coderd/httpapi/queryparams.go`** — Changed `RedirectURL` from prefix matching (`strings.HasPrefix(v.Path, base.Path)`) to full URI exact matching (`v.String() != base.String()`), comparing scheme, host, path, and query. **`coderd/oauth2provider/authorize.go`** — Added PKCE enforcement: `code_challenge` is required when `response_type=code` (via a conditional check, not `RequiredNotEmpty`, so `response_type=token` can reach the explicit rejection path). `ShowAuthorizePage` (GET) validates `response_type` before rendering and returns a 400 error page for unsupported types. `ProcessAuthorize` (POST) stores the `redirect_uri` with the auth code when explicitly provided. **`coderd/oauth2provider/tokens.go`** — PKCE verification is now unconditional (not gated on `code_challenge` being present in DB). If the stored code has a `redirect_uri`, the token endpoint verifies it matches exactly — mismatch returns `errBadCode` → `invalid_grant`. Missing `code_verifier` returns `invalid_grant`. **`codersdk/oauth2.go`** — `OAuth2ProviderResponseTypeToken` constant and `Valid()` acceptance are **kept** so the authorize handler can parse `response_type=token` and return the proper `unsupported_response_type` error rather than failing at parameter validation. **`coderd/database/migrations/000421_*`** — Added `redirect_uri text` column to `oauth2_provider_app_codes`. ### Design Decisions **`state` parameter remains optional** — The plan initially required `state` via `RequiredNotEmpty`, but this was reverted in `376a753` to avoid breaking existing clients. The `state` is still hashed and stored when provided (via `state_hash` column), securing clients that opt in. **`response_type=token` kept in `Valid()`** — Removing it from `Valid()` would cause the parameter parser to reject the request before the authorize handler can return the proper `unsupported_response_type` error. The constant is kept for correct error handling flow. **CSP scoped to consent page only** — `frame-ancestors 'none'` is set only on the OAuth consent page renderer, not globally. The SPA/global CSP was previously changed to allow framing for AI tasks ([#18102](https://github.com/coder/coder/pull/18102)); this change does not regress that. ### Out of Scope (follow-up PRs) - Bearer tokens in query strings (needs internal caller audit) - Scope enforcement on OAuth2 tokens - Rate limiting on dynamic client registration --- <details> <summary>📋 Implementation Plan</summary> # Plan: Harden OAuth2 Provider — Security Fixes + OAuth 2.1 Compliance ## Context & Why Security issue `coder/security#121` reports a critical session takeover via CSRF on the OAuth2 provider. This plan covers all remaining security fixes from that issue **plus** convergence on OAuth 2.1 requirements. The goal is a single PR that closes all actionable gaps. ## Current State (already committed on branch `csrf-sjx1`) | Fix | Status | Commits | |-----|--------|---------| | Fix 1: CSRF on `/oauth2/authorize` | ✅ Done | `ba7d646`, `b94a64e` | | CSRF token in consent form HTML | ✅ Done | `b94a64e` | | `state_hash` column + storage | ✅ Done (hash stored, but state still optional) | `9167d83`, `b94a64e` | | Tests for CSRF + state hash | ✅ Done | `e4119b5` | ## Remaining Work ### ~~Fix 2 — Require `state` parameter~~ (DROPPED) > **Decision:** Do not enforce `state` as required. The `state` parameter is still hashed and stored when provided (via `hashOAuth2State` / `state_hash` column from prior commits), but clients are not forced to supply it. This avoids breaking existing integrations that omit state. **Rollback:** Remove `"state"` from the `RequiredNotEmpty` call in `coderd/oauth2provider/authorize.go:42`: ```go // BEFORE (current on branch) p.RequiredNotEmpty("response_type", "client_id", "state", "code_challenge") // AFTER p.RequiredNotEmpty("response_type", "client_id", "code_challenge") ``` No test changes needed — tests already pass `state` voluntarily. ### Fix 4 — Exact redirect URI matching Currently `coderd/httpapi/queryparams.go:233` uses prefix matching: ```go // CURRENT — prefix match if v.Host != base.Host || !strings.HasPrefix(v.Path, base.Path) { ``` OAuth 2.1 requires **exact string matching**. Change to: ```go // AFTER — exact match (OAuth 2.1 §4.1.2.1) if v.Host != base.Host || v.Path != base.Path { ``` **File: `coderd/httpapi/queryparams.go` — `RedirectURL` method** Also update the error message from "must be a subset of" to "must exactly match". **Additionally**, store `redirect_uri` with the auth code and verify at the token endpoint (RFC 6749 §4.1.3): 1. **New migration** (same migration file or a new `000421`): Add `redirect_uri text` column to `oauth2_provider_app_codes` 2. **Update INSERT query** in `coderd/database/queries/oauth2.sql` to include `redirect_uri` 3. **`coderd/oauth2provider/authorize.go`**: Store `params.redirectURL.String()` when inserting the code 4. **`coderd/oauth2provider/tokens.go`**: After retrieving the code from DB, verify that `redirect_uri` from the token request matches the stored value exactly. Currently `tokens.go:103` calls `p.RedirectURL(vals, callbackURL, "redirect_uri")` for prefix validation only — it must compare against the stored redirect_uri from the code, not just the app's callback URL. <details> <summary>Why both exact match AND store+verify?</summary> Exact matching at the authorize endpoint prevents open redirectors (attacker can't use a sub-path). Storing and verifying at the token endpoint prevents code injection — an attacker who steals a code can't exchange it with a different redirect_uri than was originally authorized. This is required by RFC 6749 §4.1.3 and OAuth 2.1. </details> ### Fix 7 — `frame-ancestors` CSP on consent page The consent page can be iframed by a workspace app (same-site), which is the attack vector. Add a `Content-Security-Policy` header to prevent framing. **File: `site/site.go` — `RenderOAuthAllowPage` function (~line 731)** Before writing the response, add: ```go func RenderOAuthAllowPage(rw http.ResponseWriter, r *http.Request, data RenderOAuthAllowData) { rw.Header().Set("Content-Type", "text/html; charset=utf-8") // Prevent the consent page from being framed to mitigate // clickjacking attacks (coder/security#121). rw.Header().Set("Content-Security-Policy", "frame-ancestors 'none'") rw.Header().Set("X-Frame-Options", "DENY") ... ``` Both headers for defense-in-depth (CSP for modern browsers, X-Frame-Options for legacy). ### OAuth 2.1 — Mandatory PKCE Currently PKCE is checked only when `code_challenge` was provided during authorization (`tokens.go:258`): ```go // CURRENT — conditional check if dbCode.CodeChallenge.Valid && dbCode.CodeChallenge.String != "" { // verify PKCE } ``` OAuth 2.1 requires PKCE for ALL authorization code flows. Change to: **File: `coderd/oauth2provider/authorize.go`** — Add `"code_challenge"` to required params: ```go p.RequiredNotEmpty("response_type", "client_id", "code_challenge") ``` **File: `coderd/oauth2provider/tokens.go:257-265`** — Make PKCE verification unconditional: ```go // AFTER — PKCE always required (OAuth 2.1) if req.CodeVerifier == "" { return codersdk.OAuth2TokenResponse{}, errInvalidPKCE } if !dbCode.CodeChallenge.Valid || dbCode.CodeChallenge.String == "" { // Code was issued without a challenge — should not happen // with the authorize endpoint enforcement, but defend in // depth. return codersdk.OAuth2TokenResponse{}, errInvalidPKCE } if !VerifyPKCE(dbCode.CodeChallenge.String, req.CodeVerifier) { return codersdk.OAuth2TokenResponse{}, errInvalidPKCE } ``` **File: `codersdk/oauth2.go`** — Remove `OAuth2ProviderResponseTypeToken` from the enum or reject it explicitly in the authorize handler. Currently it's defined at line 216 but the handler ignores `response_type` and always issues a code. We should either: - (a) Remove the `"token"` variant from the enum and reject it with `unsupported_response_type`, OR - (b) Add an explicit check in `ProcessAuthorize` that rejects `response_type=token` Option (b) is simpler and more backwards-compatible: ```go // In ProcessAuthorize, after extracting params: if params.responseType != codersdk.OAuth2ProviderResponseTypeCode { httpapi.WriteOAuth2Error(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeUnsupportedResponseType, "Only response_type=code is supported") return } ``` ### OAuth 2.1 — Bearer tokens in query strings `coderd/httpmw/apikey.go:743` accepts `access_token` from URL query parameters. OAuth 2.1 prohibits this. However, this may be used internally (e.g., workspace apps, DERP). Need to audit callers before removing. **Approach:** This is a larger change with potential breakage. Mark as a **separate follow-up issue** rather than including in this PR. Document the finding. ### OAuth 2.1 — Removed flows ✅ **Already compliant.** `tokens.go` only supports `authorization_code` and `refresh_token` grant types. The implicit grant (`response_type=token`) will be explicitly rejected per the PKCE section above. ### OAuth 2.1 — Refresh token rotation ✅ **Already compliant.** `tokens.go:442` deletes the old API key when a refresh token is used. ## Migration Plan All DB changes can go in a single new migration (or extend 000420 if the branch is rebased before merge). Columns to add: - `redirect_uri text` on `oauth2_provider_app_codes` The `state_hash` column is already added by migration 000420. ## Implementation Order 1. **Fix 7** — CSP headers on consent page (isolated, no deps) 2. ~~**Fix 2** — Require `state` parameter~~ (DROPPED — state stays optional) 3. **Fix 4** — Exact redirect URI matching + store/verify redirect_uri 4. **PKCE mandatory** — Require `code_challenge` + reject `response_type=token` 5. **Rollback** — Remove `"state"` from `RequiredNotEmpty` in `authorize.go` 6. **Tests** — Update/add tests for all changes 7. **`make gen`** after DB changes ## Out of Scope (separate PRs) - Bearer tokens in query strings (needs internal caller audit) - Scope enforcement on OAuth2 tokens - Rate limiting / quota on dynamic client registration </details> --- _Generated with [`mux`](https://github.com/coder/mux) • Model: `anthropic:claude-opus-4-6` • Thinking: `xhigh`_ |
||
|
|
92a6d6c2c0 |
chore: remove unnecessary loop variable captures (#22180)
Since Go 1.22, the loop variable capture issue is resolved. Variables declared by for loops are now per-iteration rather than per-loop, making the 'v := v' pattern unnecessary. |
||
|
|
a2ab7e6519 |
fix: marshal OAuth2ProviderApp into [] not null (#21992)
This pull-request makes it so that when we `json.Marshal` an empty set of responses from `ListApps(...)` we return an empty array (`[]`) instead of `null`. This ensures that the array is non-nil 🙂 | Old | New | | --- | --- | | <img width="839" height="177" alt="OAUTH2_APPS_BORKED" src="https://github.com/user-attachments/assets/c264be1a-6260-405a-bf07-50a533e48ed5" /> | <img width="839" height="177" alt="OAUTH2_APPS_WORKING" src="https://github.com/user-attachments/assets/483a46b1-f5fd-496e-bfcb-4193a3ca8ec3" /> | |
||
|
|
dd6aec04d7 | fix(coderd/oauth2provider): support client_secret_basic client auth (#21793) | ||
|
|
6683d807ac |
refactor: add RFC-compliant enum types and use SDK as source of truth (#21468)
Add comprehensive OAuth2 enum types to codersdk following RFC specifications: - OAuth2ProviderGrantType (RFC 6749) - OAuth2ProviderResponseType (RFC 6749) - OAuth2TokenEndpointAuthMethod (RFC 7591) - OAuth2PKCECodeChallengeMethod (RFC 7636) - OAuth2TokenType (RFC 6749, RFC 9449) - OAuth2RevocationTokenTypeHint (RFC 7009) - OAuth2ErrorCode (RFC 6749, RFC 7009, RFC 8707) Add OAuth2TokenRequest, OAuth2TokenResponse, OAuth2TokenRevocationRequest, and OAuth2Error structs to the SDK. Update OAuth2ClientRegistrationRequest, OAuth2ClientRegistrationResponse, OAuth2ClientConfiguration, and OAuth2AuthorizationServerMetadata to use typed enums instead of raw strings. This makes codersdk the single source of truth for OAuth2 types, eliminating duplication between SDK and server-side structs. Closes #21476 |
||
|
|
bddb808b25 |
chore: arrange imports in a standard way (#21452)
Fixes all our Go file imports to match the preferred spec that we've _mostly_ been using. For example: ``` import ( "context" "time" "github.com/prometheus/client_golang/prometheus" "golang.org/x/xerrors" "gopkg.in/natefinch/lumberjack.v2" "cdr.dev/slog/v3" "github.com/coder/coder/v2/codersdk/agentsdk" "github.com/coder/serpent" ) ``` 3 groups: standard library, 3rd partly libs, Coder libs. This PR makes the change across the codebase. The PR in the stack above modifies our formatting to maintain this state of affairs, and is a separate PR so it's possible to review that one in detail. |
||
|
|
49b34a716a |
fix: fix slog to always use array of Fields (#21426)
Upgrades to slog v3 which includes a small, but backward incompatible API change to the acceptible call arguments when logging. This change allows us to verify via compile time type checking that arguments are correct and won't cause a panic, as was possible in slog v1, which this replaces (v2 was tagged but never used in coder/coder). It also updates dependencies that also use slog and were updated. I've left the `aibridge` dependency as a commit SHA, under the assumption that the team there (cc @pawbana @dannykopping ) will tag and update the dependency soon and on their own schedule. Other dependencies, I pushed new tags. |
||
|
|
3a0e8af6e3 |
feat: add view workspace button to app error page (#20960)
Closes #19984 As part of this, I refactored the error template to take in a slice of actions rather than using individual booleans and strings to control the behavior. We decided a link resolves the issue for now so that is what I added, although we may want to consider a way to start the workspace and follow the logs dynamically on that page and then show the app when finished (similar to the tasks page), or at least make the link automatically start the workspace instead of only taking you to the dashboard where you have to then start the workspace. |
||
|
|
54497f4f6b |
chore: add revocation endpoint to oauth well-known (#20561)
Was added to apps endpoints, but not the wider site ones. This is a site wide oauth route |
||
|
|
13ca9ead3a |
chore!: ensure consistent secret token generation and hashing (#20388)
This PR uses the same sha256 hashing technique as we use for APIKeys. So now all randomly generated secrets will be hashed with sha256 for consistency. This is a breaking change for the oauth tokens. Since oauth is only allowed for dev builds and experimental, this is ok. |
||
|
|
4bd7c7b7e0 |
feat: implement oauth2 RFC 7009 token revocation endpoint (#20362)
Adds RFC 7009 token revocation endpoint |
||
|
|
251f787743 | fix: normalize oauth2 scope parsing (#20359) | ||
|
|
05537c1894 |
feat: publish RBAC scopes in OAuth2 metadata endpoints (#19942)
<!-- If you have used AI to produce some or all of this PR, please ensure you have read our [AI Contribution guidelines](https://coder.com/docs/about/contributing/AI_CONTRIBUTING) before submitting. --> Publish supported OAuth2 scopes from RBAC external scope names This PR updates the OAuth2 metadata endpoints to publish the supported scopes from the RBAC external scope names. Previously, the `ScopesSupported` field was empty with a TODO to implement a scope system. Now, both the authorization server metadata and protected resource metadata endpoints return the list of scopes from `rbac.ExternalScopeNames()`. The tests have been updated to verify that the correct scopes are being returned in the metadata responses. |
||
|
|
6fb4cc6b82 |
fix: add retry logic to OAuth2 metadata tests to avoid race conditions (#19813)
This PR adds a readiness wait to OAuth2 metadata endpoint tests to avoid rare races with server startup. Instead of immediately making HTTP requests, the tests now use `testutil.Eventually` to retry the requests until they succeed, with a short interval between attempts. This helps prevent flaky tests that might fail due to timing issues during server initialization. Fixes: https://github.com/coder/internal/issues/996 |
||
|
|
088d14933c | feat: ensure OAuth2 refresh tokens outlive access tokens (#19769) | ||
|
|
7b06fc77ae |
refactor: simplify OAuth2 authorization flow and use 302 redirects (#18923)
# Refactor OAuth2 Provider Authorization Flow This PR refactors the OAuth2 provider authorization flow by: 1. Removing the `authorizeMW` middleware and directly implementing its functionality in the `ShowAuthorizePage` handler 2. Simplifying function signatures by removing unnecessary parameters: - Removed `db` parameter from `ShowAuthorizePage` - Removed `accessURL` parameter from `ProcessAuthorize` 3. Changing the redirect status code in `ProcessAuthorize` from 307 (Temporary Redirect) to 302 (Found) to improve compatibility with external OAuth2 apps and browsers. (Technical explanation: we replied with a 307 to a POST request, thus the browser performs a redirect to that URL as a POST request, but we need it to be a GET request to be compatible. Thus, we use the 302 redirect so that browsers turn it into a GET request when redirecting back to the redirect_uri.) The changes maintain the same functionality while simplifying the code and improving compatibility with external systems. |
||
|
|
071383bbe8 |
feat: add RFC 9728 OAuth2 resource metadata support (#18920)
# Enhanced OAuth2 and MCP Compliance for API Authentication This PR improves OAuth2 and MCP (Microsoft Cloud for Sovereignty) compliance by: 1. Adding RFC 9728 compliant `WWW-Authenticate` headers with resource metadata URLs 2. Passing the configured `AccessURL` to API key middleware for proper audience validation 3. Creating specialized CORS handling for OAuth2 and MCP endpoints with appropriate headers 4. Making the `state` parameter optional in OAuth2 authorization requests These changes ensure proper OAuth2 token audience validation against the configured access URL and improve interoperability with OAuth2 clients by providing better error responses and metadata discovery. Signed-off-by: Thomas Kosiewski <tk@coder.com> |
||
|
|
4607e5113b |
refactor: organize OAuth2 provider tests into dedicated packages (#18747)
# OAuth2 Provider Code Reorganization This PR reorganizes the OAuth2 provider code to improve separation of concerns and maintainability. The changes include: 1. Migrating OAuth2 provider app validation tests from `coderd/oauth2_test.go` to `oauth2provider/provider_test.go` 2. Moving OAuth2 client registration validation tests to `oauth2provider/validation_test.go` 3. Adding new comprehensive test files for metadata and validation edge cases 4. Renaming `OAuth2ProviderAppSecret` to `AppSecret` for better naming consistency 5. Simplifying the main integration test in `oauth2_test.go` to focus on core functionality The PR maintains all existing test coverage while organizing the code more logically, making it easier to understand and maintain the OAuth2 provider implementation. This reorganization will help with future enhancements to the OAuth2 provider functionality. |
||
|
|
c65013384a |
refactor: move OAuth2 provider code to dedicated package (#18746)
# Refactor OAuth2 Provider Code into Dedicated Package This PR refactors the OAuth2 provider functionality by moving it from the main `coderd` package into a dedicated `oauth2provider` package. The change improves code organization and maintainability without changing functionality. Key changes: - Created a new `oauth2provider` package to house all OAuth2 provider-related code - Moved existing OAuth2 provider functionality from `coderd/identityprovider` to the new package - Refactored handler functions to follow a consistent pattern of returning `http.HandlerFunc` instead of being handlers directly - Split large files into smaller, more focused files organized by functionality: - `app_secrets.go` - Manages OAuth2 application secrets - `apps.go` - Handles OAuth2 application CRUD operations - `authorize.go` - Implements the authorization flow - `metadata.go` - Provides OAuth2 metadata endpoints - `registration.go` - Handles dynamic client registration - `revoke.go` - Implements token revocation - `secrets.go` - Manages secret generation and validation - `tokens.go` - Handles token issuance and validation This refactoring improves code organization and makes the OAuth2 provider functionality more maintainable while preserving all existing behavior. |