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 &#34;http://%zz\&#34;&gt;&lt;img src=x onerror=BAD&gt;&#34;...
literal `<img` in body: 0     entity encoded `&lt;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>
This commit is contained in:
authored and GitHub committed 2026-09-03 10:54:34 -07:00
1 parent 5320a79dfa
commit 68ca033d67
13 files changed
+1224 -240

No files matched your search

+116 -10
View File
@@ -16556,15 +16556,13 @@ const docTemplate = `{
},
{
"type": "string",
"description": "A random unguessable string",
"description": "A random unguessable string, echoed back on the callback",
"name": "state",
"in": "query",
"required": true
"in": "query"
},
{
"enum": [
"code",
"token"
"code"
],
"type": "string",
"description": "Response type",
@@ -16583,6 +16581,28 @@ const docTemplate = `{
"description": "Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist",
"name": "scope",
"in": "query"
},
{
"type": "string",
"description": "PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636)",
"name": "code_challenge",
"in": "query",
"required": true
},
{
"enum": [
"S256"
],
"type": "string",
"description": "PKCE challenge method. S256 only; omitting it means S256",
"name": "code_challenge_method",
"in": "query"
},
{
"type": "string",
"description": "RFC 8707 resource indicator: an absolute URI without a fragment",
"name": "resource",
"in": "query"
}
],
"responses": {
@@ -16591,6 +16611,12 @@ const docTemplate = `{
},
"302": {
"description": "Redirects to the app's registered callback carrying an OAuth2 error (RFC 6749 4.1.2.1)"
},
"400": {
"description": "HTML error page. The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback"
},
"500": {
"description": "HTML error page. The app's registered callback URL is not usable"
}
},
"security": [
@@ -16600,6 +16626,9 @@ const docTemplate = `{
]
},
"post": {
"produces": [
"application/json"
],
"tags": [
"Enterprise"
],
@@ -16615,15 +16644,13 @@ const docTemplate = `{
},
{
"type": "string",
"description": "A random unguessable string",
"description": "A random unguessable string, echoed back on the callback",
"name": "state",
"in": "query",
"required": true
"in": "query"
},
{
"enum": [
"code",
"token"
"code"
],
"type": "string",
"description": "Response type",
@@ -16642,11 +16669,45 @@ const docTemplate = `{
"description": "Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist",
"name": "scope",
"in": "query"
},
{
"type": "string",
"description": "PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636)",
"name": "code_challenge",
"in": "query",
"required": true
},
{
"enum": [
"S256"
],
"type": "string",
"description": "PKCE challenge method. S256 only; omitting it means S256",
"name": "code_challenge_method",
"in": "query"
},
{
"type": "string",
"description": "RFC 8707 resource indicator: an absolute URI without a fragment",
"name": "resource",
"in": "query"
}
],
"responses": {
"302": {
"description": "Redirects to the app's registered callback carrying either an authorization code or an OAuth2 error (RFC 6749 4.1.2.1)"
},
"400": {
"description": "The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback",
"schema": {
"$ref": "#/definitions/codersdk.OAuth2Error"
}
},
"500": {
"description": "The app's registered callback URL is not usable",
"schema": {
"$ref": "#/definitions/codersdk.OAuth2Error"
}
}
},
"security": [
@@ -25215,6 +25276,51 @@ const docTemplate = `{
}
}
},
"codersdk.OAuth2Error": {
"type": "object",
"properties": {
"error": {
"$ref": "#/definitions/codersdk.OAuth2ErrorCode"
},
"error_description": {
"type": "string"
},
"error_uri": {
"type": "string"
}
}
},
"codersdk.OAuth2ErrorCode": {
"type": "string",
"enum": [
"invalid_request",
"invalid_client",
"invalid_grant",
"unauthorized_client",
"unsupported_grant_type",
"invalid_scope",
"access_denied",
"unsupported_response_type",
"server_error",
"temporarily_unavailable",
"unsupported_token_type",
"invalid_target"
],
"x-enum-varnames": [
"OAuth2ErrorCodeInvalidRequest",
"OAuth2ErrorCodeInvalidClient",
"OAuth2ErrorCodeInvalidGrant",
"OAuth2ErrorCodeUnauthorizedClient",
"OAuth2ErrorCodeUnsupportedGrantType",
"OAuth2ErrorCodeInvalidScope",
"OAuth2ErrorCodeAccessDenied",
"OAuth2ErrorCodeUnsupportedResponseType",
"OAuth2ErrorCodeServerError",
"OAuth2ErrorCodeTemporarilyUnavailable",
"OAuth2ErrorCodeUnsupportedTokenType",
"OAuth2ErrorCodeInvalidTarget"
]
},
"codersdk.OAuth2GithubConfig": {
"type": "object",
"properties": {
+110 -8
View File
@@ -14718,13 +14718,12 @@
},
{
"type": "string",
"description": "A random unguessable string",
"description": "A random unguessable string, echoed back on the callback",
"name": "state",
"in": "query",
"required": true
"in": "query"
},
{
"enum": ["code", "token"],
"enum": ["code"],
"type": "string",
"description": "Response type",
"name": "response_type",
@@ -14742,6 +14741,26 @@
"description": "Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist",
"name": "scope",
"in": "query"
},
{
"type": "string",
"description": "PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636)",
"name": "code_challenge",
"in": "query",
"required": true
},
{
"enum": ["S256"],
"type": "string",
"description": "PKCE challenge method. S256 only; omitting it means S256",
"name": "code_challenge_method",
"in": "query"
},
{
"type": "string",
"description": "RFC 8707 resource indicator: an absolute URI without a fragment",
"name": "resource",
"in": "query"
}
],
"responses": {
@@ -14750,6 +14769,12 @@
},
"302": {
"description": "Redirects to the app's registered callback carrying an OAuth2 error (RFC 6749 4.1.2.1)"
},
"400": {
"description": "HTML error page. The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback"
},
"500": {
"description": "HTML error page. The app's registered callback URL is not usable"
}
},
"security": [
@@ -14759,6 +14784,7 @@
]
},
"post": {
"produces": ["application/json"],
"tags": ["Enterprise"],
"summary": "OAuth2 authorization request (POST - process authorization).",
"operationId": "oauth2-authorization-request-post",
@@ -14772,13 +14798,12 @@
},
{
"type": "string",
"description": "A random unguessable string",
"description": "A random unguessable string, echoed back on the callback",
"name": "state",
"in": "query",
"required": true
"in": "query"
},
{
"enum": ["code", "token"],
"enum": ["code"],
"type": "string",
"description": "Response type",
"name": "response_type",
@@ -14796,11 +14821,43 @@
"description": "Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist",
"name": "scope",
"in": "query"
},
{
"type": "string",
"description": "PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636)",
"name": "code_challenge",
"in": "query",
"required": true
},
{
"enum": ["S256"],
"type": "string",
"description": "PKCE challenge method. S256 only; omitting it means S256",
"name": "code_challenge_method",
"in": "query"
},
{
"type": "string",
"description": "RFC 8707 resource indicator: an absolute URI without a fragment",
"name": "resource",
"in": "query"
}
],
"responses": {
"302": {
"description": "Redirects to the app's registered callback carrying either an authorization code or an OAuth2 error (RFC 6749 4.1.2.1)"
},
"400": {
"description": "The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback",
"schema": {
"$ref": "#/definitions/codersdk.OAuth2Error"
}
},
"500": {
"description": "The app's registered callback URL is not usable",
"schema": {
"$ref": "#/definitions/codersdk.OAuth2Error"
}
}
},
"security": [
@@ -23051,6 +23108,51 @@
}
}
},
"codersdk.OAuth2Error": {
"type": "object",
"properties": {
"error": {
"$ref": "#/definitions/codersdk.OAuth2ErrorCode"
},
"error_description": {
"type": "string"
},
"error_uri": {
"type": "string"
}
}
},
"codersdk.OAuth2ErrorCode": {
"type": "string",
"enum": [
"invalid_request",
"invalid_client",
"invalid_grant",
"unauthorized_client",
"unsupported_grant_type",
"invalid_scope",
"access_denied",
"unsupported_response_type",
"server_error",
"temporarily_unavailable",
"unsupported_token_type",
"invalid_target"
],
"x-enum-varnames": [
"OAuth2ErrorCodeInvalidRequest",
"OAuth2ErrorCodeInvalidClient",
"OAuth2ErrorCodeInvalidGrant",
"OAuth2ErrorCodeUnauthorizedClient",
"OAuth2ErrorCodeUnsupportedGrantType",
"OAuth2ErrorCodeInvalidScope",
"OAuth2ErrorCodeAccessDenied",
"OAuth2ErrorCodeUnsupportedResponseType",
"OAuth2ErrorCodeServerError",
"OAuth2ErrorCodeTemporarilyUnavailable",
"OAuth2ErrorCodeUnsupportedTokenType",
"OAuth2ErrorCodeInvalidTarget"
]
},
"codersdk.OAuth2GithubConfig": {
"type": "object",
"properties": {
+15 -4
View File
@@ -118,12 +118,17 @@ func (api *API) deleteOAuth2ProviderAppSecret() http.HandlerFunc {
// @Security CoderSessionToken
// @Tags Enterprise
// @Param client_id query string true "Client ID"
// @Param state query string true "A random unguessable string"
// @Param response_type query codersdk.OAuth2ProviderResponseType true "Response type"
// @Param state query string false "A random unguessable string, echoed back on the callback"
// @Param response_type query string true "Response type" Enums(code)
// @Param redirect_uri query string false "Redirect here after authorization"
// @Param scope query string false "Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist"
// @Param code_challenge query string true "PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636)"
// @Param code_challenge_method query string false "PKCE challenge method. S256 only; omitting it means S256" Enums(S256)
// @Param resource query string false "RFC 8707 resource indicator: an absolute URI without a fragment"
// @Success 200 "Returns HTML authorization page"
// @Success 302 "Redirects to the app's registered callback carrying an OAuth2 error (RFC 6749 4.1.2.1)"
// @Failure 400 "HTML error page. The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback"
// @Failure 500 "HTML error page. The app's registered callback URL is not usable"
// @Router /oauth2/authorize [get]
func (api *API) getOAuth2ProviderAppAuthorize() http.HandlerFunc {
return oauth2provider.ShowAuthorizePage(api.AccessURL, api.Logger)
@@ -132,13 +137,19 @@ func (api *API) getOAuth2ProviderAppAuthorize() http.HandlerFunc {
// @Summary OAuth2 authorization request (POST - process authorization).
// @ID oauth2-authorization-request-post
// @Security CoderSessionToken
// @Produce json
// @Tags Enterprise
// @Param client_id query string true "Client ID"
// @Param state query string true "A random unguessable string"
// @Param response_type query codersdk.OAuth2ProviderResponseType true "Response type"
// @Param state query string false "A random unguessable string, echoed back on the callback"
// @Param response_type query string true "Response type" Enums(code)
// @Param redirect_uri query string false "Redirect here after authorization"
// @Param scope query string false "Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist"
// @Param code_challenge query string true "PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636)"
// @Param code_challenge_method query string false "PKCE challenge method. S256 only; omitting it means S256" Enums(S256)
// @Param resource query string false "RFC 8707 resource indicator: an absolute URI without a fragment"
// @Success 302 "Redirects to the app's registered callback carrying either an authorization code or an OAuth2 error (RFC 6749 4.1.2.1)"
// @Failure 400 {object} codersdk.OAuth2Error "The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback"
// @Failure 500 {object} codersdk.OAuth2Error "The app's registered callback URL is not usable"
// @Router /oauth2/authorize [post]
func (api *API) postOAuth2ProviderAppAuthorize() http.HandlerFunc {
return oauth2provider.ProcessAuthorize(api.Database, api.Logger)
+299 -117
View File
@@ -169,32 +169,102 @@ func consentScopes(granted string) (names []string, unrestricted bool) {
return names, false
}
// maxErrorDescription bounds error_description: long enough for a human reason,
// short enough for a Location header to survive the proxies in front of it.
const maxErrorDescription = 2048
// responseTypeCode is the only response type this server supports. response_type
// is read as text rather than through the SDK enum so every unsupported value
// takes one path, instead of splitting on whether a Go constant happens to
// exist for it.
const responseTypeCode = string(codersdk.OAuth2ProviderResponseTypeCode)
type authorizeParams struct {
clientID string
callback validatedCallbackURL
response authorizeResponse
redirectURIProvided bool
responseType codersdk.OAuth2ProviderResponseType
responseType string
scope []string
state string
resource string // RFC 8707 resource indicator
codeChallenge string // PKCE code challenge
codeChallengeMethod string // PKCE challenge method
}
func extractAuthorizeParams(r *http.Request, callbackURL *url.URL) (authorizeParams, []codersdk.ValidationError, error) {
// authorizeFailure is a request that will not produce an authorization code:
// either a parameter was rejected, or the app's registration is unusable. Which
// answer it gets is kind(), not the order a handler's checks happen to run in.
type authorizeFailure struct {
// validationErrors is every field the parser rejected, reported together.
validationErrors []codersdk.ValidationError
// description joins them into the error_description the client receives.
description string
// redirect is where RFC 6749 §4.1.2.1 puts the answer. Its zero value means
// the answer stays on this server, because the failure names the redirect
// URI or the client identifier.
redirect authorizeResponse
// corruptCallback is set when the app's registered callback does not parse
// or uses a scheme registration rejects. That is bad server state rather
// than a client mistake, so it answers 500, and it is decided before any
// parameter is read.
corruptCallback error
// code is the OAuth2 error to answer with. Read it through errorCode, which
// supplies the invalid_request default.
code codersdk.OAuth2ErrorCode
}
func (f authorizeFailure) errorCode() codersdk.OAuth2ErrorCode {
if f.code == "" {
return codersdk.OAuth2ErrorCodeInvalidRequest
}
return f.code
}
// failureKind is where a failure is answered. The three are mutually exclusive
// by construction here rather than by the shape of authorizeFailure, so both
// handlers dispatch on this instead of re-deriving the precedence from fields.
type failureKind int
const (
// failureCorruptRegistration outranks the rest: with the registration
// unusable there is nothing to redirect to, whatever else the client also
// got wrong.
failureCorruptRegistration failureKind = iota
// failureDeliverToClient is the RFC 6749 §4.1.2.1 default.
failureDeliverToClient
// failureAnswerHere is a §4.1.2.1 carve-out: no callback this server will
// send the answer to.
failureAnswerHere
)
func (f authorizeFailure) kind() failureKind {
switch {
case f.corruptCallback != nil:
return failureCorruptRegistration
case f.redirect.canRedirect():
return failureDeliverToClient
default:
return failureAnswerHere
}
}
func extractAuthorizeParams(r *http.Request, logger slog.Logger, app database.OAuth2ProviderApp) (authorizeParams, *authorizeFailure) {
p := httpapi.NewQueryParamParser()
vals := r.URL.Query()
// response_type and client_id are always required.
p.RequiredNotEmpty("response_type", "client_id")
response, err := newAuthorizeResponse(p, vals, app.CallbackURL)
if err != nil {
return authorizeParams{}, &authorizeFailure{corruptCallback: err}
}
params := authorizeParams{
clientID: p.String(vals, "", "client_id"),
callback: validatedCallbackURL{url: p.RedirectURL(vals, callbackURL, "redirect_uri")},
response: response,
redirectURIProvided: vals.Get("redirect_uri") != "",
responseType: httpapi.ParseCustom(p, vals, "", "response_type", httpapi.ParseEnum[codersdk.OAuth2ProviderResponseType]),
responseType: p.String(vals, "", "response_type"),
scope: strings.Fields(strings.TrimSpace(p.String(vals, "", "scope"))),
state: p.String(vals, "", "state"),
resource: p.String(vals, "", "resource"),
codeChallenge: p.String(vals, "", "code_challenge"),
codeChallengeMethod: p.String(vals, "", "code_challenge_method"),
@@ -203,7 +273,11 @@ func extractAuthorizeParams(r *http.Request, callbackURL *url.URL) (authorizePar
// PKCE is required for the authorization code flow. A malformed
// code_challenge is rejected here (RFC 7636 §4.4.1) rather than at token
// exchange, where the error would point at the code_verifier instead.
if params.responseType == codersdk.OAuth2ProviderResponseTypeCode {
//
// Only for the code flow: an unsupported response type must reach the
// handlers as unsupported_response_type rather than be recast here as a
// missing code_challenge.
if params.responseType == responseTypeCode {
switch {
case params.codeChallenge == "":
p.Errors = append(p.Errors, codersdk.ValidationError{
@@ -226,30 +300,143 @@ func extractAuthorizeParams(r *http.Request, callbackURL *url.URL) (authorizePar
})
}
p.ErrorExcessParams(vals)
if len(p.Errors) > 0 {
// Create a readable error message with validation details
var errorDetails []string
for _, err := range p.Errors {
errorDetails = append(errorDetails, err.Error())
}
errorMsg := "Invalid query params: " + strings.Join(errorDetails, ", ")
return authorizeParams{}, p.Errors, xerrors.Errorf(errorMsg)
// RFC 6749 §3.1 and OAuth 2.1 §3.1: unrecognized parameters MUST be ignored,
// so an OIDC nonce or a vendor extension is not this endpoint's business.
// Repeats of the parameters read above are still rejected, by parseSingle.
if ignored := ignoredParams(p, vals); len(ignored) > 0 {
logger.Debug(r.Context(), "ignoring unrecognized authorization parameters",
slog.F("params", ignored))
}
return params, nil, nil
if len(p.Errors) > 0 {
// Not err.Error(): its "field: x detail: y" shape is a Coder debug
// formatter, and details contain commas, so a comma join cannot be split
// back into per-field diagnostics by the client reading it.
details := make([]string, len(p.Errors))
for i, err := range p.Errors {
details[i] = err.Field + ": " + err.Detail
}
failure := &authorizeFailure{
validationErrors: p.Errors,
description: "Invalid query params: " + strings.Join(details, "; "),
}
// RFC 8707 §2 gives resource its own code, but only when nothing else
// failed. A client that retries on invalid_target would otherwise resend
// a request that is still broken in the field it did not hear about.
if !slices.ContainsFunc(p.Errors, func(e codersdk.ValidationError) bool {
return e.Field != "resource"
}) {
failure.code = codersdk.OAuth2ErrorCodeInvalidTarget
}
if !clientIDInDoubt(vals, params.clientID, app.ID) {
failure.redirect = response
}
return authorizeParams{}, failure
}
return params, nil
}
// validatedCallbackURL is a redirect URI extractAuthorizeParams has exact-matched
// against the app's registered callback. Requiring one keeps the error redirects
// below from becoming open redirects. The unexported field is a guard, not a
// proof: no other package can fabricate one; this package still can.
type validatedCallbackURL struct {
url *url.URL
// ignoredParams returns the query parameters this endpoint does not read,
// sorted so the log line is stable. A misspelled parameter (redirect_url for
// redirect_uri) surfaces here instead of in the client's error.
func ignoredParams(p *httpapi.QueryParamParser, vals url.Values) []string {
var ignored []string
for name := range vals {
if !p.Parsed[name] {
ignored = append(ignored, name)
}
}
slices.Sort(ignored)
return ignored
}
// String returns the registered callback, without the query a response adds.
func (c validatedCallbackURL) String() string {
return c.url.String()
// clientIDInDoubt reports whether the client's identity is unsettled, the
// RFC 6749 §4.1.2.1 carve-out that keeps the answer on this server rather than
// sending it to a registration that may not be the caller's. The other
// carve-out, a redirect URI at fault, needs no test here because the response
// it produced has nowhere to send.
//
// It reads the raw values because parseSingle collapses a repeated client_id to
// "", which is indistinguishable from a POST carrying client_id in the form
// body. httpmw accepts that body, so an absent query parameter still names a
// client and its failure is deliverable.
func clientIDInDoubt(vals url.Values, parsed string, appID uuid.UUID) bool {
// RFC 6749 §3.1: a parameter sent without a value is the omitted case, so
// ?client_id= names no candidate, and neither does a repeat of it.
named := slices.DeleteFunc(slices.Clone(vals["client_id"]), func(v string) bool {
return v == ""
})
switch {
case len(named) > 1:
// The callback was matched against one of several candidates.
return true
case len(named) == 0:
return false
default:
// Parsed rather than compared as text: httpmw resolves through
// uuid.Parse, which accepts spellings the canonical form does not match.
id, err := uuid.Parse(parsed)
return err != nil || id != appID
}
}
// authorizeResponse names where this request's response goes and what it carries
// back. Building one runs both preconditions a Location header needs, so a
// response holding a callback is what licenses a redirect. The unexported fields
// are a guard, not a proof: no other package can fabricate one; this package
// still can.
type authorizeResponse struct {
// callback is nil when the request named a redirect URI this server will not
// send anything to. RFC 6749 §4.1.2.1 keeps that answer on this server.
callback *url.URL
state string
}
// newAuthorizeResponse parses the app's registered callback, checks it,
// exact-matches any redirect_uri the client sent against it, and reads the
// state to echo back.
//
// The scheme is checked on the registered URL rather than on the match's result,
// because p.RedirectURL returns the client's URI when the match fails, and
// answering 500 for a scheme the client chose would blame the app for a request
// it did not make. It is checked before the match so no parse outcome can reach
// a Location header through a scheme nothing verified.
//
// A returned error means the registration itself is unusable, which is server
// state. A mismatch is the client's mistake and joins the other parameter
// failures in p.Errors.
func newAuthorizeResponse(p *httpapi.QueryParamParser, vals url.Values, registered string) (authorizeResponse, error) {
registeredURL, err := url.Parse(registered)
if err != nil {
return authorizeResponse{}, err
}
if err := codersdk.ValidateRedirectURIScheme(registeredURL); err != nil {
return authorizeResponse{}, err
}
callback := p.RedirectURL(vals, registeredURL, "redirect_uri")
response := authorizeResponse{state: p.String(vals, "", "state")}
// The field, not a count of errors across these two lines: reading state
// can fail too, and that failure belongs to the client's callback rather
// than to the carve-out that withholds one.
if !slices.ContainsFunc(p.Errors, func(e codersdk.ValidationError) bool {
return e.Field == "redirect_uri"
}) {
response.callback = callback
}
return response, nil
}
func (a authorizeResponse) canRedirect() bool {
return a.callback != nil
}
// callbackURL returns the destination, without the query a response adds. Named
// rather than String so the type is not an implicit fmt.Stringer: the zero value
// is routine on failure paths, and its String would panic through %v. Valid only
// on a response that holds a callback.
func (a authorizeResponse) callbackURL() string {
return a.callback.String()
}
// reservedResponseParams are the response parameters RFC 6749 §4.1.2.1 and
@@ -264,15 +451,15 @@ var reservedResponseParams = []string{"code", "error", "error_description", "sta
// The registered query is kept (§3.1.2) except for the reserved parameters: a
// registered error= would otherwise ride out on a success response, where a
// client reading error first discards a valid code.
func (c validatedCallbackURL) withQuery(state string, set func(url.Values)) *url.URL {
destination := *c.url
func (a authorizeResponse) withQuery(set func(url.Values)) *url.URL {
destination := *a.callback
query := destination.Query()
for _, param := range reservedResponseParams {
query.Del(param)
}
set(query)
if state != "" {
query.Set("state", state)
if a.state != "" {
query.Set("state", a.state)
}
destination.RawQuery = query.Encode()
return &destination
@@ -297,21 +484,27 @@ func sanitizeErrorDescription(description string) string {
}
// errorURL returns the callback carrying an RFC 6749 §4.1.2.1 error.
func (c validatedCallbackURL) errorURL(state string, code codersdk.OAuth2ErrorCode, description string) *url.URL {
return c.withQuery(state, func(query url.Values) {
func (a authorizeResponse) errorURL(code codersdk.OAuth2ErrorCode, description string) *url.URL {
return a.withQuery(func(query url.Values) {
query.Set("error", string(code))
query.Set("error_description", sanitizeErrorDescription(description))
})
}
// codeURL returns the callback carrying the authorization code.
func (c validatedCallbackURL) codeURL(state, code string) *url.URL {
return c.withQuery(state, func(query url.Values) {
func (a authorizeResponse) codeURL(code string) *url.URL {
return a.withQuery(func(query url.Values) {
query.Set("code", code)
})
}
func redirectAuthorizeError(rw http.ResponseWriter, r *http.Request, logger slog.Logger, callback validatedCallbackURL, state string, code codersdk.OAuth2ErrorCode, description string) {
func redirectAuthorizeError(rw http.ResponseWriter, r *http.Request, logger slog.Logger, response authorizeResponse, code codersdk.OAuth2ErrorCode, description string) {
// Descriptions echo values the client sent, so their length is the client's
// to choose. Cap here, ahead of both the log field and the Location header.
if len(description) > maxErrorDescription {
description = description[:maxErrorDescription] + " (truncated)"
}
app := httpmw.OAuth2ProviderApp(r)
logger.Info(r.Context(), "oauth2 authorization rejected",
slog.F("app_id", app.ID.String()),
@@ -320,7 +513,7 @@ func redirectAuthorizeError(rw http.ResponseWriter, r *http.Request, logger slog
// 302 rather than 307, matching the success redirect below: some external
// OAuth2 apps and browsers do not handle 307.
http.Redirect(rw, r, callback.errorURL(state, code, description).String(), http.StatusFound)
http.Redirect(rw, r, response.errorURL(code, description).String(), http.StatusFound)
}
// logCorruptCallback reports a registered callback URL this server should never
@@ -339,14 +532,13 @@ func ShowAuthorizePage(accessURL *url.URL, logger slog.Logger) http.HandlerFunc
app := httpmw.OAuth2ProviderApp(r)
ua := httpmw.UserAuthorization(r.Context())
callbackURL, err := url.Parse(app.CallbackURL)
if err != nil {
logCorruptCallback(r.Context(), logger, app, err)
errorPage := func(status int, title, description string, warnings []string) {
site.RenderStaticErrorPage(rw, r, site.ErrorPageData{
Status: http.StatusInternalServerError,
Status: status,
HideStatus: false,
Title: "Internal Server Error",
Description: err.Error(),
Title: title,
Description: description,
Warnings: warnings,
Actions: []site.Action{
{
URL: accessURL.String(),
@@ -354,49 +546,39 @@ func ShowAuthorizePage(accessURL *url.URL, logger slog.Logger) http.HandlerFunc
},
},
})
return
}
params, validationErrs, err := extractAuthorizeParams(r, callbackURL)
if err != nil {
errStr := make([]string, len(validationErrs))
for i, err := range validationErrs {
errStr[i] = err.Detail
params, failure := extractAuthorizeParams(r, logger, app)
if failure != nil {
switch failure.kind() {
case failureCorruptRegistration:
logCorruptCallback(r.Context(), logger, app, failure.corruptCallback)
errorPage(http.StatusInternalServerError, "Invalid Callback URL",
"The application's registered callback URL is not usable.", nil)
case failureDeliverToClient:
// §4.1.2.1: once the callback has been matched against the app's
// registration, a parameter failure is a response to the client
// rather than a page for the user. Without it the app never
// learns its request failed and waits on an authorization that
// will not arrive.
redirectAuthorizeError(rw, r, logger, failure.redirect,
failure.errorCode(), failure.description)
case failureAnswerHere:
warnings := make([]string, len(failure.validationErrors))
for i, err := range failure.validationErrors {
warnings[i] = err.Detail
}
errorPage(http.StatusBadRequest, "Invalid Query Parameters",
"One or more query parameters are missing or invalid.", warnings)
default:
logger.Error(r.Context(), "unhandled authorize failure kind",
slog.F("kind", int(failure.kind())))
errorPage(http.StatusInternalServerError, "Internal Server Error",
"The request could not be answered.", nil)
}
site.RenderStaticErrorPage(rw, r, site.ErrorPageData{
Status: http.StatusBadRequest,
HideStatus: false,
Title: "Invalid Query Parameters",
Description: "One or more query parameters are missing or invalid.",
Warnings: errStr,
Actions: []site.Action{
{
URL: accessURL.String(),
Text: "Back to site",
},
},
})
return
}
// Checked right after the exact match against the registered callback,
// because every redirect below writes this URL into a Location header,
// and the consent page into the cancel link's href. 500, not 400:
// registration rejects these schemes, so a stored one is bad server state.
if err := codersdk.ValidateRedirectURIScheme(params.callback.url); err != nil {
logCorruptCallback(r.Context(), logger, app, err)
site.RenderStaticErrorPage(rw, r, site.ErrorPageData{
Status: http.StatusInternalServerError,
HideStatus: false,
Title: "Invalid Callback URL",
Description: "The application's registered callback URL has an invalid scheme.",
Actions: []site.Action{
{
URL: accessURL.String(),
Text: "Back to site",
},
},
})
return
}
@@ -406,8 +588,8 @@ func ShowAuthorizePage(accessURL *url.URL, logger slog.Logger) http.HandlerFunc
// In the query, not the fragment §4.2.2.1 would use: Coder advertises
// code alone in response_types_supported, so a client asking for token
// is misconfigured rather than mid-implicit-flow.
if params.responseType != codersdk.OAuth2ProviderResponseTypeCode {
redirectAuthorizeError(rw, r, logger, params.callback, params.state,
if params.responseType != responseTypeCode {
redirectAuthorizeError(rw, r, logger, params.response,
codersdk.OAuth2ErrorCodeUnsupportedResponseType,
"Only response_type=code is supported")
return
@@ -417,7 +599,7 @@ func ShowAuthorizePage(accessURL *url.URL, logger slog.Logger) http.HandlerFunc
// negotiated below: the page must not render for a request POST will
// refuse. Only POST defaults an omitted method, since only POST stores it.
if err := codersdk.ValidatePKCECodeChallengeMethod(params.codeChallengeMethod); err != nil {
redirectAuthorizeError(rw, r, logger, params.callback, params.state,
redirectAuthorizeError(rw, r, logger, params.response,
codersdk.OAuth2ErrorCodeInvalidRequest, err.Error())
return
}
@@ -428,14 +610,13 @@ func ShowAuthorizePage(accessURL *url.URL, logger slog.Logger) http.HandlerFunc
grantedScope, err := negotiateScope(r.Context(), logger, app, params.scope)
if err != nil {
code, description := scopeFailureResponse(err)
redirectAuthorizeError(rw, r, logger, params.callback, params.state,
code, description)
redirectAuthorizeError(rw, r, logger, params.response, code, description)
return
}
// Declining is an authorization failure like any other, so the cancel
// link is the same §4.1.2.1 error URL the redirects above build.
cancel := params.callback.errorURL(params.state,
cancel := params.response.errorURL(
codersdk.OAuth2ErrorCodeAccessDenied,
"The resource owner or authorization server denied the request")
@@ -443,8 +624,8 @@ func ShowAuthorizePage(accessURL *url.URL, logger slog.Logger) http.HandlerFunc
site.RenderOAuthAllowPage(rw, r, site.RenderOAuthAllowData{
AppIcon: app.Icon,
AppName: app.Name,
// #nosec G203 -- The scheme is validated by
// codersdk.ValidateRedirectURIScheme after extractAuthorizeParams.
// #nosec G203 -- newAuthorizeResponse checked the scheme before this
// URL could exist.
CancelURI: htmltemplate.URL(cancel.String()),
DashboardURL: accessURL.String(),
CSRFToken: nosurf.Token(r),
@@ -463,32 +644,34 @@ func ProcessAuthorize(db database.Store, logger slog.Logger) http.HandlerFunc {
apiKey := httpmw.APIKey(r)
app := httpmw.OAuth2ProviderApp(r)
callbackURL, err := url.Parse(app.CallbackURL)
if err != nil {
logCorruptCallback(ctx, logger, app, err)
httpapi.WriteOAuth2Error(r.Context(), rw, http.StatusInternalServerError, codersdk.OAuth2ErrorCodeServerError, "Failed to validate query parameters")
return
}
params, failure := extractAuthorizeParams(r, logger, app)
if failure != nil {
switch failure.kind() {
case failureCorruptRegistration:
logCorruptCallback(ctx, logger, app, failure.corruptCallback)
httpapi.WriteOAuth2Error(ctx, rw, http.StatusInternalServerError,
codersdk.OAuth2ErrorCodeServerError,
"The application's registered callback URL is not usable")
params, _, err := extractAuthorizeParams(r, callbackURL)
if err != nil {
httpapi.WriteOAuth2Error(ctx, rw, http.StatusBadRequest, codersdk.OAuth2ErrorCodeInvalidRequest, err.Error())
return
}
case failureDeliverToClient:
redirectAuthorizeError(rw, r, logger, failure.redirect,
failure.errorCode(), failure.description)
// As on the GET side: every redirect below writes this URL into a
// Location header.
if err := codersdk.ValidateRedirectURIScheme(params.callback.url); err != nil {
logCorruptCallback(ctx, logger, app, err)
httpapi.WriteOAuth2Error(ctx, rw, http.StatusInternalServerError,
codersdk.OAuth2ErrorCodeServerError,
"The application's registered callback URL has an invalid scheme")
case failureAnswerHere:
httpapi.WriteOAuth2Error(ctx, rw, http.StatusBadRequest, failure.errorCode(), failure.description)
default:
logger.Error(ctx, "unhandled authorize failure kind",
slog.F("kind", int(failure.kind())))
httpapi.WriteOAuth2Error(ctx, rw, http.StatusInternalServerError,
codersdk.OAuth2ErrorCodeServerError, "The request could not be answered")
}
return
}
// As on the GET side: OAuth 2.1 removes the implicit grant.
if params.responseType != codersdk.OAuth2ProviderResponseTypeCode {
redirectAuthorizeError(rw, r, logger, params.callback, params.state,
if params.responseType != responseTypeCode {
redirectAuthorizeError(rw, r, logger, params.response,
codersdk.OAuth2ErrorCodeUnsupportedResponseType,
"Only response_type=code is supported")
return
@@ -500,7 +683,7 @@ func ProcessAuthorize(db database.Store, logger slog.Logger) http.HandlerFunc {
params.codeChallengeMethod = string(codersdk.OAuth2PKCECodeChallengeMethodS256)
}
if err := codersdk.ValidatePKCECodeChallengeMethod(params.codeChallengeMethod); err != nil {
redirectAuthorizeError(rw, r, logger, params.callback, params.state,
redirectAuthorizeError(rw, r, logger, params.response,
codersdk.OAuth2ErrorCodeInvalidRequest, err.Error())
return
}
@@ -508,8 +691,7 @@ func ProcessAuthorize(db database.Store, logger slog.Logger) http.HandlerFunc {
grantedScope, err := negotiateScope(ctx, logger, app, params.scope)
if err != nil {
code, description := scopeFailureResponse(err)
redirectAuthorizeError(rw, r, logger, params.callback, params.state,
code, description)
redirectAuthorizeError(rw, r, logger, params.response, code, description)
return
}
@@ -547,8 +729,8 @@ func ProcessAuthorize(db database.Store, logger slog.Logger) http.HandlerFunc {
ResourceUri: sql.NullString{String: params.resource, Valid: params.resource != ""},
CodeChallenge: sql.NullString{String: params.codeChallenge, Valid: params.codeChallenge != ""},
CodeChallengeMethod: sql.NullString{String: params.codeChallengeMethod, Valid: params.codeChallengeMethod != ""},
StateHash: hashOAuth2State(params.state),
RedirectUri: sql.NullString{String: params.callback.String(), Valid: params.redirectURIProvided},
StateHash: hashOAuth2State(params.response.state),
RedirectUri: sql.NullString{String: params.response.callbackURL(), Valid: params.redirectURIProvided},
// The negotiated scope, not the requested one. The exchange
// copies it onto the token row and the API key it mints, so
// this bounds the issued token.
@@ -567,7 +749,7 @@ func ProcessAuthorize(db database.Store, logger slog.Logger) http.HandlerFunc {
// (ThomasK33): Use a 302 redirect as some (external) OAuth 2 apps and browsers
// do not work with the 307.
http.Redirect(rw, r, params.callback.codeURL(params.state, code.Formatted).String(), http.StatusFound)
http.Redirect(rw, r, params.response.codeURL(code.Formatted).String(), http.StatusFound)
}
}
@@ -4,6 +4,10 @@ import (
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
@@ -14,6 +18,7 @@ import (
"cdr.dev/slog/v3/sloggers/slogtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
)
@@ -467,3 +472,222 @@ func TestConsentScopes(t *testing.T) {
})
}
}
// TestNewAuthorizeResponse covers the two preconditions the constructor exists
// to run together, and which of them is the server's fault.
func TestNewAuthorizeResponse(t *testing.T) {
t.Parallel()
const registered = "https://app.example.com/callback"
t.Run("MatchingRedirectURI", func(t *testing.T) {
t.Parallel()
p := httpapi.NewQueryParamParser()
response, err := newAuthorizeResponse(p, url.Values{
"redirect_uri": {registered},
"state": {"abc123"},
}, registered)
require.NoError(t, err)
require.Empty(t, p.Errors)
require.True(t, response.canRedirect())
require.Equal(t, registered, response.callbackURL())
require.Equal(t, "abc123", response.state)
})
t.Run("OmittedRedirectURIDefaultsToRegistered", func(t *testing.T) {
t.Parallel()
p := httpapi.NewQueryParamParser()
response, err := newAuthorizeResponse(p, url.Values{}, registered)
require.NoError(t, err)
require.Empty(t, p.Errors)
require.True(t, response.canRedirect())
require.Equal(t, registered, response.callbackURL())
})
t.Run("MismatchedRedirectURIHasNoDestination", func(t *testing.T) {
t.Parallel()
p := httpapi.NewQueryParamParser()
response, err := newAuthorizeResponse(p, url.Values{
"redirect_uri": {"https://elsewhere.example/cb"},
}, registered)
// The client's mistake, so it joins the parser's other errors rather
// than becoming a server fault.
require.NoError(t, err)
require.Len(t, p.Errors, 1)
require.Equal(t, "redirect_uri", p.Errors[0].Field)
require.False(t, response.canRedirect(),
"a URI that failed the match must not become a destination")
})
t.Run("DangerousClientSchemeIsNotTheServersFault", func(t *testing.T) {
t.Parallel()
p := httpapi.NewQueryParamParser()
response, err := newAuthorizeResponse(p, url.Values{
"redirect_uri": {"javascript:alert(1)"},
}, registered)
require.NoError(t, err, "the app registered a usable callback; the client did not send one")
require.NotEmpty(t, p.Errors)
require.False(t, response.canRedirect())
})
t.Run("DangerousRegisteredSchemeIsServerState", func(t *testing.T) {
t.Parallel()
p := httpapi.NewQueryParamParser()
response, err := newAuthorizeResponse(p, url.Values{}, "javascript:alert(1)")
require.Error(t, err)
require.Empty(t, p.Errors, "the registration is rejected before any parameter is read")
require.False(t, response.canRedirect())
})
t.Run("UnparsableRegisteredCallbackIsServerState", func(t *testing.T) {
t.Parallel()
p := httpapi.NewQueryParamParser()
response, err := newAuthorizeResponse(p, url.Values{}, "http://a b")
require.Error(t, err, "a registration that does not parse is the same class as one this server rejects")
require.Empty(t, p.Errors)
require.False(t, response.canRedirect())
})
}
// TestAuthorizeResponseZeroValue pins the zero value as inert, since it is what
// a failure with no deliverable destination carries.
func TestAuthorizeResponseZeroValue(t *testing.T) {
t.Parallel()
require.False(t, authorizeResponse{}.canRedirect())
require.False(t, (&authorizeFailure{}).redirect.canRedirect())
require.NotContains(t, fmt.Sprintf("%v", authorizeResponse{}), "PANIC",
"a String method on this type would panic through fmt on every failure path")
}
// TestFailureKind pins the precedence both handlers dispatch on, in the one
// place it is now written.
func TestFailureKind(t *testing.T) {
t.Parallel()
deliverable := authorizeResponse{callback: &url.URL{Scheme: "https", Host: "app.example.com"}}
unusable := xerrors.New("registered callback is not usable")
require.Equal(t, failureAnswerHere, authorizeFailure{}.kind())
require.Equal(t, failureDeliverToClient, authorizeFailure{redirect: deliverable}.kind())
require.Equal(t, failureCorruptRegistration, authorizeFailure{corruptCallback: unusable}.kind())
require.Equal(t, failureCorruptRegistration,
authorizeFailure{corruptCallback: unusable, redirect: deliverable}.kind(),
"the registration is what a Location header would be trusting, so its failure outranks a usable callback")
}
// TestCarveOutDelivery pins which failures reach the client's callback and which
// stay here, the two RFC 6749 §4.1.2.1 carve-outs: an unsettled client identity
// and a redirect URI at fault.
func TestCarveOutDelivery(t *testing.T) {
t.Parallel()
app := database.OAuth2ProviderApp{
ID: uuid.MustParse("6f1a9c30-0d6b-4f8e-9a71-2c4b83f0ab12"),
CallbackURL: "https://app.example.com/callback",
}
valid := func() url.Values {
return url.Values{
"client_id": {app.ID.String()},
"response_type": {"code"},
"redirect_uri": {"https://app.example.com/callback"},
"code_challenge": {"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"},
"code_challenge_method": {"S256"},
"state": {"xyz"},
}
}
cases := []struct {
name string
mutate func(url.Values)
deliver bool
}{
{
// Repeated: the callback was matched against one of two candidates.
name: "RepeatedClientID",
mutate: func(v url.Values) { v["client_id"] = []string{app.ID.String(), app.ID.String()} },
deliver: false,
},
{
name: "ClientIDIsNotTheResolvedApp",
mutate: func(v url.Values) {
v.Set("client_id", uuid.NewString())
v.Set("code_challenge", "short")
},
deliver: false,
},
{
// httpmw resolved the app from the POST form body, which this
// parser never reads. The identity is not in doubt.
name: "ClientIDAbsentFromTheQuery",
mutate: func(v url.Values) { v.Del("client_id") },
deliver: true,
},
{
// RFC 6749 §3.1: sent without a value is the absent case above, so
// httpmw resolved the same way and the failure is as deliverable.
name: "ClientIDValuelessInTheQuery",
mutate: func(v url.Values) { v.Set("client_id", "") },
deliver: true,
},
{
// Every value valueless, so httpmw had one candidate, not several.
name: "ClientIDRepeatedAndValueless",
mutate: func(v url.Values) { v["client_id"] = []string{"", ""} },
deliver: true,
},
{
// uuid.Parse accepts this and httpmw resolved through it.
name: "ClientIDInANonCanonicalSpelling",
mutate: func(v url.Values) {
v.Set("client_id", "{"+strings.ToUpper(app.ID.String())+"}")
v.Set("code_challenge", "short")
},
deliver: true,
},
{
name: "FailureOutsideTheIdentity",
mutate: func(v url.Values) { v.Set("code_challenge", "short") },
deliver: true,
},
{
// The state read shares a function with the redirect_uri match, so
// this used to be charged to the redirect_uri carve-out.
name: "RepeatedState",
mutate: func(v url.Values) { v["state"] = []string{"xyz", "xyz"} },
deliver: true,
},
{
name: "RedirectURIDoesNotMatchTheRegistration",
mutate: func(v url.Values) { v.Set("redirect_uri", "https://attacker.example.com/callback") },
deliver: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
vals := valid()
tc.mutate(vals)
r := httptest.NewRequest(http.MethodGet, "/oauth2/authorize?"+vals.Encode(), nil)
_, failure := extractAuthorizeParams(r, slogtest.Make(t, nil), app)
require.NotNil(t, failure)
require.Equal(t, tc.deliver, failure.redirect.canRedirect())
})
}
}
+264 -19
View File
@@ -404,9 +404,70 @@ func TestOAuth2AuthorizeScopeNegotiation(t *testing.T) {
"POST: a dangerous scheme must never reach a Location header")
postBody := readBody(t, postResp)
require.Contains(t, postBody, string(codersdk.OAuth2ErrorCodeServerError))
// The callback-parse branch also answers server_error.
require.Contains(t, postBody, "invalid scheme",
"POST: the failure must name the scheme, not just the error class")
require.Contains(t, postBody, "callback URL is not usable",
"POST: the failure must name the callback, not just the error class")
})
// The other half of the same class: a stored callback that does not even
// parse. Registration rejects it, so reaching this needs a row that bypassed
// registration, which is exactly what the scheme case above also assumes.
t.Run("UnparsableCallbackNotRedirected", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
const unparsable = "http://a b"
app := dbgen.OAuth2ProviderApp(t, db, database.OAuth2ProviderApp{
Name: testutil.GetRandomName(t),
CallbackURL: unparsable,
Scope: sql.NullString{String: scopeInCatalog, Valid: true},
})
getResp := authorizeRequest(ctx, t, client, http.MethodGet, app.ID.String(), scopeInCatalog)
defer getResp.Body.Close()
require.Equal(t, http.StatusInternalServerError, getResp.StatusCode)
getBody := readBody(t, getResp)
require.Contains(t, getBody, "Invalid Callback URL",
"GET: the failure must name the callback URL")
require.NotContains(t, getBody, unparsable,
"GET: the Go parse error carries the stored URL, which must not reach the page")
postResp := authorizeRequest(ctx, t, client, http.MethodPost, app.ID.String(), scopeInCatalog)
defer postResp.Body.Close()
require.Equal(t, http.StatusInternalServerError, postResp.StatusCode)
postBody := readBody(t, postResp)
require.Contains(t, postBody, string(codersdk.OAuth2ErrorCodeServerError))
require.Contains(t, postBody, "callback URL is not usable",
"POST: nothing was validated, so the description must not blame the query")
})
// The trap the constructor exists to close: a request that both fails the
// parser and belongs to an app whose registered scheme is rejected. Parser
// failures now redirect, so a scheme checked after parsing would be checked
// too late.
t.Run("DangerousCallbackSchemeOutranksParseFailure", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
app := dbgen.OAuth2ProviderApp(t, db, database.OAuth2ProviderApp{
Name: testutil.GetRandomName(t),
CallbackURL: "javascript:alert(1)",
Scope: sql.NullString{String: scopeInCatalog, Valid: true},
})
for _, method := range []string{http.MethodGet, http.MethodPost} {
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
query.Set("code_challenge", "tooshort")
resp := sendAuthorizeRequest(ctx, t, client, method, query)
defer resp.Body.Close()
require.Equal(t, http.StatusInternalServerError, resp.StatusCode,
"%s: the unusable registration outranks the client's own mistake", method)
require.Empty(t, resp.Header.Get("Location"),
"%s: a dangerous scheme must never reach a Location header", method)
require.NotContains(t, readBody(t, resp), "javascript:",
"%s: the scheme must not reach the response body either", method)
}
})
// A registered callback may carry its own state=, and the cancel link, the
@@ -558,28 +619,213 @@ func TestOAuth2AuthorizeErrorsReachTheClient(t *testing.T) {
})
}
// Every response type but code is unsupported, whether or not the SDK has a
// constant for it, so the client gets one answer for one mistake.
t.Run("UnsupportedResponseTypeRedirected", func(t *testing.T) {
t.Parallel()
app := seedAppInCatalog(t)
for _, method := range []string{http.MethodGet, http.MethodPost} {
t.Run(method, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
for _, responseType := range []string{"token", "id_token", "code id_token", "not_a_response_type"} {
for _, method := range []string{http.MethodGet, http.MethodPost} {
t.Run(responseType+"/"+method, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
query.Set("response_type", "token")
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
query.Set("response_type", responseType)
resp := sendAuthorizeRequest(ctx, t, client, method, query)
defer resp.Body.Close()
resp := sendAuthorizeRequest(ctx, t, client, method, query)
defer resp.Body.Close()
requireAuthorizeErrorRedirect(t, resp,
codersdk.OAuth2ErrorCodeUnsupportedResponseType, "Only response_type=code is supported")
})
requireAuthorizeErrorRedirect(t, resp,
codersdk.OAuth2ErrorCodeUnsupportedResponseType, "Only response_type=code is supported")
})
}
}
})
t.Run("UnparseableResponseTypeNotRedirected", func(t *testing.T) {
// RFC 8707 §2 names the authorization endpoint, so a bad resource gets the
// same invalid_target the token endpoint already gives it. Only when it is
// the sole failure: a client retrying on invalid_target must not be sent
// back with a second field still broken.
t.Run("MalformedResourceRedirected", func(t *testing.T) {
t.Parallel()
app := seedAppInCatalog(t)
for _, tc := range []struct {
name string
mutate func(url.Values)
code codersdk.OAuth2ErrorCode
}{
{
name: "ResourceAlone",
mutate: func(url.Values) {},
code: codersdk.OAuth2ErrorCodeInvalidTarget,
},
{
name: "ResourceAndCodeChallenge",
mutate: func(q url.Values) { q.Set("code_challenge", "tooshort") },
code: codersdk.OAuth2ErrorCodeInvalidRequest,
},
} {
for _, method := range []string{http.MethodGet, http.MethodPost} {
t.Run(tc.name+"/"+method, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
query.Set("resource", "not-an-absolute-uri")
tc.mutate(query)
resp := sendAuthorizeRequest(ctx, t, client, method, query)
defer resp.Body.Close()
requireAuthorizeErrorRedirect(t, resp, tc.code, "absolute URI")
})
}
}
})
// The parser reports every field at once, so these all arrive as
// invalid_request with the offending fields named in the description.
// Explicit as well as omitted redirect_uri, since the two take different
// paths through the parser.
t.Run("RejectedParametersRedirected", func(t *testing.T) {
t.Parallel()
app := seedAppInCatalog(t)
for _, tc := range []struct {
name string
mutate func(url.Values)
description string
}{
{
name: "MalformedCodeChallenge",
mutate: func(q url.Values) { q.Set("code_challenge", "tooshort") },
description: "43 to 128 characters",
},
} {
for _, method := range []string{http.MethodGet, http.MethodPost} {
for _, redirectURI := range []string{"", appCallbackURL} {
name := tc.name + "/" + method
if redirectURI != "" {
name += "ExplicitRedirectURI"
}
t.Run(name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
tc.mutate(query)
if redirectURI != "" {
query.Set("redirect_uri", redirectURI)
}
resp := sendAuthorizeRequest(ctx, t, client, method, query)
defer resp.Body.Close()
requireAuthorizeErrorRedirect(t, resp,
codersdk.OAuth2ErrorCodeInvalidRequest, tc.description)
})
}
}
}
})
// The client developer reads this string, so each failing field has to be
// separable from the next.
t.Run("DescriptionNamesEachFailingField", func(t *testing.T) {
t.Parallel()
app := seedAppInCatalog(t)
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
query.Add("scope", scopeInCatalog)
query.Set("resource", "https://api.example.com/#section")
resp := sendAuthorizeRequest(ctx, t, client, http.MethodGet, query)
defer resp.Body.Close()
requireAuthorizeErrorRedirect(t, resp, codersdk.OAuth2ErrorCodeInvalidRequest, "; ")
location, err := url.Parse(resp.Header.Get("Location"))
require.NoError(t, err)
description := location.Query().Get("error_description")
require.Contains(t, description, "scope: Query param")
require.Contains(t, description, "resource: must be an absolute URI without fragment")
require.NotContains(t, description, "field:",
"field and detail are Coder's own parser labels, meaningless to the client")
})
// The description echoes what the client sent, so its length is the
// client's to choose and a Location header would carry all of it.
t.Run("LongDescriptionTruncated", func(t *testing.T) {
t.Parallel()
app := seedAppInCatalog(t)
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), "coder:"+strings.Repeat("a", 20000))
resp := sendAuthorizeRequest(ctx, t, client, http.MethodGet, query)
defer resp.Body.Close()
requireAuthorizeErrorRedirect(t, resp, codersdk.OAuth2ErrorCodeInvalidScope, "(truncated)")
location, err := url.Parse(resp.Header.Get("Location"))
require.NoError(t, err)
require.Less(t, len(location.Query().Get("error_description")), 4096)
})
// OAuth 2.1 §3.1 requires unrecognized parameters to be ignored, so the
// nonce and prompt an OIDC client sends must not fail the request.
t.Run("UnrecognizedParametersIgnored", func(t *testing.T) {
t.Parallel()
app := seedAppInCatalog(t)
unrecognized := func(q url.Values) {
q.Set("nonce", "n-0S6_WzA2Mj")
q.Set("prompt", "consent")
q.Set(`we"ird`, "1")
}
t.Run(http.MethodGet, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
unrecognized(query)
resp := sendAuthorizeRequest(ctx, t, client, http.MethodGet, query)
defer resp.Body.Close()
require.Equal(t, http.StatusOK, resp.StatusCode,
"an ignored parameter must still reach the consent page")
})
t.Run(http.MethodPost, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
unrecognized(query)
resp := sendAuthorizeRequest(ctx, t, client, http.MethodPost, query)
defer resp.Body.Close()
require.Equal(t, http.StatusFound, resp.StatusCode)
location, err := url.Parse(resp.Header.Get("Location"))
require.NoError(t, err)
require.NotEmpty(t, location.Query().Get("code"),
"an ignored parameter must not withhold the authorization code")
require.Empty(t, location.Query().Get("error"))
})
})
// A redirect URI the parser could not use is the §4.1.2.1 carve-out: there
// is no callback worth trusting, so the answer stays on this server.
t.Run("UnparseableRedirectURINotRedirected", func(t *testing.T) {
t.Parallel()
app := seedAppInCatalog(t)
@@ -589,15 +835,14 @@ func TestOAuth2AuthorizeErrorsReachTheClient(t *testing.T) {
ctx := testutil.Context(t, testutil.WaitLong)
query := authorizeQuery(t, app.ID.String(), scopeInCatalog)
query.Set("response_type", "not_a_response_type")
query.Set("redirect_uri", "://not-a-url")
resp := sendAuthorizeRequest(ctx, t, client, method, query)
defer resp.Body.Close()
require.Equal(t, http.StatusBadRequest, resp.StatusCode,
"extractAuthorizeParams failures answer on Coder whether or not the callback was trustworthy, and this request omits redirect_uri, so it was")
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
require.Empty(t, resp.Header.Get("Location"),
"nothing may be redirected from inside extractAuthorizeParams")
"a redirect URI that did not parse must not become a destination")
})
}
})
+7 -3
View File
@@ -120,9 +120,13 @@ func TestOAuth2NoStoreHeaders(t *testing.T) {
app, _ := oauth2providertest.CreateTestOAuth2App(t, client)
_, challenge := oauth2providertest.GeneratePKCE(t)
// A response_type that does not parse renders a static error page
// rather than going through httpapi.
uri := strings.Replace(authorizeURL(baseURL, app.ID.String(), challenge), "response_type=code", "response_type=not_a_response_type", 1)
// A redirect_uri that does not match the registration is the one
// parameter failure RFC 6749 §4.1.2.1 keeps on this server, so it is
// what still renders a static error page rather than going through
// httpapi.
uri := strings.Replace(authorizeURL(baseURL, app.ID.String(), challenge),
url.QueryEscape(oauth2providertest.TestRedirectURI),
url.QueryEscape("http://localhost:9876/not-the-registered-callback"), 1)
resp := doRequest(ctx, t, http.MethodGet, uri, nil, sessionToken(client))
defer resp.Body.Close()
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
@@ -373,12 +373,31 @@ func CleanupOAuth2App(t *testing.T, client *codersdk.Client, appID uuid.UUID) {
}
}
// AuthorizeOAuth2AppExpectingError performs the OAuth2 authorization flow expecting an error
func AuthorizeOAuth2AppExpectingError(t *testing.T, client *codersdk.Client, baseURL string, params AuthorizeParams, expectedStatusCode int) {
// AuthorizeOAuth2AppExpectingRedirectError performs the OAuth2 authorization
// flow expecting a rejection, which RFC 6749 §4.1.2.1 delivers to the redirect
// URI the app registered rather than as a status code on this server.
//
// wantDescription is asserted as a substring of error_description. Without it
// every caller reduces to the same four assertions, and one blanket
// invalid_request would satisfy all of them.
func AuthorizeOAuth2AppExpectingRedirectError(t *testing.T, client *codersdk.Client, baseURL string, params AuthorizeParams, expectedError codersdk.OAuth2ErrorCode, wantDescription string) {
t.Helper()
resp := doAuthorizeRequest(t, client, baseURL, params)
defer resp.Body.Close()
require.Equal(t, expectedStatusCode, resp.StatusCode, "unexpected status code")
require.Equal(t, http.StatusFound, resp.StatusCode, "unexpected status code")
location, err := url.Parse(resp.Header.Get("Location"))
require.NoError(t, err, "failed to parse redirect location")
require.Equal(t, params.RedirectURI, location.Scheme+"://"+location.Host+location.Path,
"the error must go to the registered redirect URI")
query := location.Query()
require.Equal(t, string(expectedError), query.Get("error"))
require.Contains(t, query.Get("error_description"), wantDescription,
"the description must name the defect, not just its error class")
require.Equal(t, params.State, query.Get("state"),
"the client cannot correlate the failure with its request without its state")
require.Empty(t, query.Get("code"), "a rejected request must not issue a code")
}
@@ -13,6 +13,7 @@ import (
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/oauth2provider/oauth2providertest"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
@@ -290,8 +291,9 @@ func TestOAuth2WithoutPKCEIsRejected(t *testing.T) {
State: state,
}
oauth2providertest.AuthorizeOAuth2AppExpectingError(
t, client, client.URL.String(), authParams, http.StatusBadRequest,
oauth2providertest.AuthorizeOAuth2AppExpectingRedirectError(
t, client, client.URL.String(), authParams, codersdk.OAuth2ErrorCodeInvalidRequest,
"is required and cannot be empty",
)
}
@@ -323,8 +325,9 @@ func TestOAuth2MalformedCodeChallengeIsRejected(t *testing.T) {
CodeChallengeMethod: "S256",
}
oauth2providertest.AuthorizeOAuth2AppExpectingError(
t, client, client.URL.String(), authParams, http.StatusBadRequest,
oauth2providertest.AuthorizeOAuth2AppExpectingRedirectError(
t, client, client.URL.String(), authParams, codersdk.OAuth2ErrorCodeInvalidRequest,
"must be 43 to 128 characters",
)
}
+32 -35
View File
@@ -9,6 +9,7 @@ import (
"github.com/stretchr/testify/require"
"cdr.dev/slog/v3/sloggers/slogtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
@@ -381,9 +382,6 @@ func TestExtractAuthorizeParams_Scopes(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
callbackURL, err := url.Parse("http://localhost:3000/callback")
require.NoError(t, err)
// Build query parameters for GET request
query := url.Values{}
query.Set("response_type", "code")
@@ -407,10 +405,9 @@ func TestExtractAuthorizeParams_Scopes(t *testing.T) {
}
// Extract authorize params
params, validationErrs, err := extractAuthorizeParams(req, callbackURL)
params, failure := extractAuthorizeParams(req, slogtest.Make(t, nil), database.OAuth2ProviderApp{CallbackURL: "http://localhost:3000/callback"})
require.NoError(t, err)
require.Empty(t, validationErrs)
require.Nil(t, failure)
require.Equal(t, tc.expectedScopes, params.scope)
})
}
@@ -454,9 +451,6 @@ func TestExtractAuthorizeParams_CodeChallengeFormat(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
callbackURL, err := url.Parse("http://localhost:3000/callback")
require.NoError(t, err)
query := url.Values{}
query.Set("response_type", "code")
query.Set("client_id", "test-client")
@@ -471,45 +465,48 @@ func TestExtractAuthorizeParams_CodeChallengeFormat(t *testing.T) {
URL: reqURL,
}
_, validationErrs, err := extractAuthorizeParams(req, callbackURL)
_, failure := extractAuthorizeParams(req, slogtest.Make(t, nil), database.OAuth2ProviderApp{CallbackURL: "http://localhost:3000/callback"})
if tc.expectValid {
require.NoError(t, err)
require.Empty(t, validationErrs)
require.Nil(t, failure)
} else {
require.Error(t, err)
require.Len(t, validationErrs, 1)
require.Equal(t, "code_challenge", validationErrs[0].Field)
require.NotNil(t, failure)
require.Len(t, failure.validationErrors, 1)
require.Equal(t, "code_challenge", failure.validationErrors[0].Field)
}
})
}
}
// TestExtractAuthorizeParams_TokenResponseTypeDoesNotRequirePKCE ensures
// response_type=token is parsed without requiring PKCE fields so callers can
// return unsupported_response_type instead of invalid_request.
func TestExtractAuthorizeParams_TokenResponseTypeDoesNotRequirePKCE(t *testing.T) {
// TestExtractAuthorizeParams_NonCodeResponseTypeDoesNotRequirePKCE ensures a
// response type other than code is parsed without requiring PKCE fields so
// callers can answer unsupported_response_type instead of invalid_request.
func TestExtractAuthorizeParams_NonCodeResponseTypeDoesNotRequirePKCE(t *testing.T) {
t.Parallel()
callbackURL, err := url.Parse("http://localhost:3000/callback")
require.NoError(t, err)
// id_token has no SDK constant, so it also pins that the value is read as
// plain text.
for _, responseType := range []string{string(codersdk.OAuth2ProviderResponseTypeToken), "id_token"} {
t.Run(responseType, func(t *testing.T) {
t.Parallel()
query := url.Values{}
query.Set("response_type", string(codersdk.OAuth2ProviderResponseTypeToken))
query.Set("client_id", "test-client")
query.Set("redirect_uri", "http://localhost:3000/callback")
query := url.Values{}
query.Set("response_type", responseType)
query.Set("client_id", "test-client")
query.Set("redirect_uri", "http://localhost:3000/callback")
reqURL, err := url.Parse("http://localhost:8080/oauth2/authorize?" + query.Encode())
require.NoError(t, err)
reqURL, err := url.Parse("http://localhost:8080/oauth2/authorize?" + query.Encode())
require.NoError(t, err)
req := &http.Request{
Method: http.MethodGet,
URL: reqURL,
req := &http.Request{
Method: http.MethodGet,
URL: reqURL,
}
params, failure := extractAuthorizeParams(req, slogtest.Make(t, nil), database.OAuth2ProviderApp{CallbackURL: "http://localhost:3000/callback"})
require.Nil(t, failure)
require.Equal(t, responseType, params.responseType)
})
}
params, validationErrs, err := extractAuthorizeParams(req, callbackURL)
require.NoError(t, err)
require.Empty(t, validationErrs)
require.Equal(t, codersdk.OAuth2ProviderResponseTypeToken, params.responseType)
}
func TestExtractTokenRequest_ClientSecretRequirement(t *testing.T) {
+42 -8
View File
@@ -400,10 +400,14 @@ Ensure the redirect URI in your request exactly matches the one registered for y
### "Invalid Callback URL" on the consent page
If you see this error when authorizing, the registered callback URL uses a
blocked scheme (`javascript:`, `data:`, `file:`, or `ftp:`). Update the
application's callback URL to a valid scheme (see
[Callback URL schemes](#callback-url-schemes)).
If you see this error when authorizing, the application's registered callback
URL is not usable: either it does not parse as a URL, or it uses a blocked
scheme (`javascript:`, `data:`, `file:`, or `ftp:`). The same cause answers
`server_error` on `POST /oauth2/authorize`. Update the application's callback
URL (see [Callback URL schemes](#callback-url-schemes)).
The server log records the application ID and the stored value. The response
does not, so a bad URL is never echoed back to a browser.
### "invalid_scope" returned to your callback
@@ -445,12 +449,10 @@ scope is not something the client can change by requesting a different one.
Coder supports the authorization code flow only, so `response_type=code` is the single accepted value.
`GET /.well-known/oauth-authorization-server` reports it in `response_types_supported`.
`response_type=token`, the implicit grant, redirects to your registered callback with `error=unsupported_response_type`, an `error_description` of `Only response_type=code is supported`, and the `state` you sent.
Any other value, including the `token` of the implicit grant, redirects to your registered callback with `error=unsupported_response_type`, an `error_description` of `Only response_type=code is supported`, and the `state` you sent.
This holds for both `GET /oauth2/authorize` and `POST /oauth2/authorize`.
A value Coder does not recognize at all, or an omitted `response_type`, fails query parameter validation instead and is answered on Coder rather than redirected: `GET` renders an "Invalid Query Parameters" page and `POST` returns a 400 with a JSON `invalid_request` body.
Earlier releases answered `response_type=token` on Coder as well: `GET` rendered an "Unsupported Response Type" page and `POST` returned a 400 with a JSON body.
Earlier releases answered on Coder instead: `GET` rendered an "Unsupported Response Type" page and `POST` returned a 400 with a JSON body.
An integration that watched for either now has to read the error from its own callback.
### "invalid_request" for `code_challenge_method`
@@ -462,6 +464,38 @@ Omitting the parameter is allowed and means `S256`.
An unsupported method redirects to your registered callback with `error=invalid_request`, an `error_description` that names the method, and the `state` you sent.
This holds for both `GET /oauth2/authorize` and `POST /oauth2/authorize`.
### "invalid_request" for a rejected parameter
Coder validates every authorization parameter before issuing a code, and reports all the failing fields together in one `error_description`.
Each entry reads `field: reason`, and entries are separated by a semicolon and a space.
Common causes are a `code_challenge` outside the 43 to 128 character unreserved set, and any parameter sent more than once.
The rejection redirects to your registered callback with `error=invalid_request`, an `error_description` naming the fields, and the `state` you sent.
This holds for both `GET /oauth2/authorize` and `POST /oauth2/authorize`.
A description longer than 2048 characters is cut short and marked `(truncated)`.
Parameters the endpoint does not read are ignored, as RFC 6749 Section 3.1 requires, so an OIDC `nonce` or a vendor extension does not fail the request.
A misspelled parameter is ignored on the same rule, so what you see is the failure caused by the parameter you meant to send being absent.
Two failures stay on Coder rather than reaching your callback, because in both cases the callback is not yet trustworthy:
- A `redirect_uri` that does not parse, or that does not exactly match the one registered for the application.
Redirecting to it would defeat the check that just rejected it, so Coder answers 400 (see ["Invalid redirect_uri"](#invalid-redirect_uri)).
- A `client_id` sent more than once, or one that does not name the application the callback was matched against.
Coder cannot tell whose registration it is about to redirect to.
Earlier releases answered on Coder for all of these: `GET` rendered an "Invalid Query Parameters" page and `POST` returned a 400 with a JSON body.
An integration that watched for either now has to read the error from its own callback.
### "invalid_target" for a rejected `resource`
`resource` must be an absolute URI without a fragment (RFC 8707).
A value that is not redirects to your registered callback with `error=invalid_target`, an `error_description` naming the field, and the `state` you sent.
`POST /oauth2/token` already answered `invalid_target` for the same value.
If anything else in the request also failed, the answer is `invalid_request` instead, naming every failing field.
Correct them all before retrying: a retry that fixes only `resource` fails again.
### "PKCE verification failed"
Verify that the `code_verifier` used in the token request matches the one used to generate the `code_challenge`.
+54 -29
View File
@@ -4881,7 +4881,7 @@ To perform this operation, you must be authenticated. [Learn more](authenticatio
```sh
# Example request using curl
curl -X GET http://coder-server:8080/oauth2/authorize?client_id=string&state=string&response_type=code \
curl -X GET http://coder-server:8080/oauth2/authorize?client_id=string&response_type=code&code_challenge=string \
-H 'Coder-Session-Token: API_KEY'
```
@@ -4889,26 +4889,32 @@ curl -X GET http://coder-server:8080/oauth2/authorize?client_id=string&state=str
### Parameters
| Name | In | Type | Required | Description |
|-----------------|-------|--------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `client_id` | query | string | true | Client ID |
| `state` | query | string | true | A random unguessable string |
| `response_type` | query | string | true | Response type |
| `redirect_uri` | query | string | false | Redirect here after authorization |
| `scope` | query | string | false | Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist |
| Name | In | Type | Required | Description |
|-------------------------|-------|--------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `client_id` | query | string | true | Client ID |
| `state` | query | string | false | A random unguessable string, echoed back on the callback |
| `response_type` | query | string | true | Response type |
| `redirect_uri` | query | string | false | Redirect here after authorization |
| `scope` | query | string | false | Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist |
| `code_challenge` | query | string | true | PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636) |
| `code_challenge_method` | query | string | false | PKCE challenge method. S256 only; omitting it means S256 |
| `resource` | query | string | false | RFC 8707 resource indicator: an absolute URI without a fragment |
#### Enumerated Values
| Parameter | Value(s) |
|-----------------|-----------------|
| `response_type` | `code`, `token` |
| Parameter | Value(s) |
|-------------------------|----------|
| `response_type` | `code` |
| `code_challenge_method` | `S256` |
### Responses
| Status | Meaning | Description | Schema |
|--------|------------------------------------------------------------|----------------------------------------------------------------------------------------|--------|
| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | Returns HTML authorization page | |
| 302 | [Found](https://tools.ietf.org/html/rfc7231#section-6.4.3) | Redirects to the app's registered callback carrying an OAuth2 error (RFC 6749 4.1.2.1) | |
| Status | Meaning | Description | Schema |
|--------|----------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|--------|
| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | Returns HTML authorization page | |
| 302 | [Found](https://tools.ietf.org/html/rfc7231#section-6.4.3) | Redirects to the app's registered callback carrying an OAuth2 error (RFC 6749 4.1.2.1) | |
| 400 | [Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1) | HTML error page. The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback | |
| 500 | [Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1) | HTML error page. The app's registered callback URL is not usable | |
To perform this operation, you must be authenticated. [Learn more](authentication.md).
@@ -4918,7 +4924,8 @@ To perform this operation, you must be authenticated. [Learn more](authenticatio
```sh
# Example request using curl
curl -X POST http://coder-server:8080/oauth2/authorize?client_id=string&state=string&response_type=code \
curl -X POST http://coder-server:8080/oauth2/authorize?client_id=string&response_type=code&code_challenge=string \
-H 'Accept: application/json' \
-H 'Coder-Session-Token: API_KEY'
```
@@ -4926,25 +4933,43 @@ curl -X POST http://coder-server:8080/oauth2/authorize?client_id=string&state=st
### Parameters
| Name | In | Type | Required | Description |
|-----------------|-------|--------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `client_id` | query | string | true | Client ID |
| `state` | query | string | true | A random unguessable string |
| `response_type` | query | string | true | Response type |
| `redirect_uri` | query | string | false | Redirect here after authorization |
| `scope` | query | string | false | Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist |
| Name | In | Type | Required | Description |
|-------------------------|-------|--------|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `client_id` | query | string | true | Client ID |
| `state` | query | string | false | A random unguessable string, echoed back on the callback |
| `response_type` | query | string | true | Response type |
| `redirect_uri` | query | string | false | Redirect here after authorization |
| `scope` | query | string | false | Space-separated scopes to request. Each must be supported by this deployment, and the app's allowlist, when it has one, must cover the permissions requested rather than name each scope. Defaults to that allowlist, or to coder:all for an app with no allowlist |
| `code_challenge` | query | string | true | PKCE code challenge, 43 to 128 characters from [A-Za-z0-9-._~] (RFC 7636) |
| `code_challenge_method` | query | string | false | PKCE challenge method. S256 only; omitting it means S256 |
| `resource` | query | string | false | RFC 8707 resource indicator: an absolute URI without a fragment |
#### Enumerated Values
| Parameter | Value(s) |
|-----------------|-----------------|
| `response_type` | `code`, `token` |
| Parameter | Value(s) |
|-------------------------|----------|
| `response_type` | `code` |
| `code_challenge_method` | `S256` |
### Example responses
> 400 Response
```json
{
"error": "invalid_request",
"error_description": "string",
"error_uri": "string"
}
```
### Responses
| Status | Meaning | Description | Schema |
|--------|------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|--------|
| 302 | [Found](https://tools.ietf.org/html/rfc7231#section-6.4.3) | Redirects to the app's registered callback carrying either an authorization code or an OAuth2 error (RFC 6749 4.1.2.1) | |
| Status | Meaning | Description | Schema |
|--------|----------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------|
| 302 | [Found](https://tools.ietf.org/html/rfc7231#section-6.4.3) | Redirects to the app's registered callback carrying either an authorization code or an OAuth2 error (RFC 6749 4.1.2.1) | |
| 400 | [Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1) | The failure names the redirect URI or the client, so RFC 6749 4.1.2.1 withholds the callback | [codersdk.OAuth2Error](schemas.md#codersdkoauth2error) |
| 500 | [Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1) | The app's registered callback URL is not usable | [codersdk.OAuth2Error](schemas.md#codersdkoauth2error) |
To perform this operation, you must be authenticated. [Learn more](authentication.md).
+32
View File
@@ -10970,6 +10970,38 @@ Git clone makes use of this by parsing the URL from: 'Username for "https://gith
|----------|------------------------------------------------------------|----------|--------------|-------------|
| `github` | [codersdk.OAuth2GithubConfig](#codersdkoauth2githubconfig) | false | | |
## codersdk.OAuth2Error
```json
{
"error": "invalid_request",
"error_description": "string",
"error_uri": "string"
}
```
### Properties
| Name | Type | Required | Restrictions | Description |
|---------------------|------------------------------------------------------|----------|--------------|-------------|
| `error` | [codersdk.OAuth2ErrorCode](#codersdkoauth2errorcode) | false | | |
| `error_description` | string | false | | |
| `error_uri` | string | false | | |
## codersdk.OAuth2ErrorCode
```json
"invalid_request"
```
### Properties
#### Enumerated Values
| Value(s) |
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `access_denied`, `invalid_client`, `invalid_grant`, `invalid_request`, `invalid_scope`, `invalid_target`, `server_error`, `temporarily_unavailable`, `unauthorized_client`, `unsupported_grant_type`, `unsupported_response_type`, `unsupported_token_type` |
## codersdk.OAuth2GithubConfig
```json