Files
coder/coderd/oauth2provider/registration_test.go
T
Bobby Ho 20a41c067e feat: reject secret creation and fix reporting for public clients (#28097)
**TL;DR**

On top of #28047, closing the last two gaps in the stack split out of
#27873. A public client can now register (#28046) and exchange a code
(#28047), but the admin secrets API will still issue it a secret that
authenticates nothing, and the registration responses still report an
auth method the token endpoint will not accept.

| PR | What it does |
|---|---|
| #27712 | Schema: `app_secret_id` becomes nullable and tokens gain an
always-populated `app_id`, so ownership checks work without a secret
row. |
| #28041 | Accepts bare custom-scheme redirect URIs (`vscode://`,
`cursor://`) that native apps actually register. |
| #28043 | Derives and stores `client_type` (public vs confidential)
from the requested `token_endpoint_auth_method`, and pins it across
updates. |
| #28046 | Registration issues no secret for a public client and returns
no `client_secret`. |
| #28047 | The token endpoint accepts the exchange without a
`client_secret`. Discovery advertises `none`. |
| **#28097 (this)** | The admin secrets API refuses to create a secret
for a public client, and registration, read, and update report the auth
method the token endpoint actually enforces. |

A public client can only come into existence through dynamic client
registration, which is off by default, so neither guard is reachable
until DCR is enabled.

**Where in the flow**

- `POST /oauth2-provider/apps/{app}/secrets`, the admin secrets API. The
rest of the secret lifecycle is untouched: `GET` and `DELETE` are
unchanged, and a confidential app behaves exactly as before.
- The three RFC 7591 and 7592 responses that carry
`token_endpoint_auth_method`: registration (`POST`), read (`GET`), and
update (`PUT`). Only what is reported changes; the stored column is left
as the client sent it.
- Authorize, token exchange, refresh, and revocation are untouched.

**What it satisfies**

- RFC 7591 §2: `none` means the client is public and "does not have a
client secret", so the secrets API should not create one for it.
- RFC 7591 §3.2.1: the server MUST return all registered metadata and
MAY replace a requested value with a suitable one. Reporting the
enforced method in place of a stored one that contradicts `client_type`
is that substitution.
- RFC 7592 §2.2: an update MUST include all metadata as returned by a
previous registration, read, or update. Because clients echo back what
Coder reports, reporting the enforced method is what lets a legacy row
heal on the client's next `PUT`.
- RFC 7591 §2 default: an app with no stored method reports
`client_secret_basic`, which is both the RFC default and what
`ApplyDefaults` substitutes on update.
- OAuth 2.1 §3.2.1: the token endpoint enforces on `client_type`, so a
reported method that disagrees with it tells a client to authenticate in
a way the server will reject.

---

- `CreateAppSecret` returns 400 for a public client before generating
anything. The secret would authenticate nothing, since the token
endpoint no longer checks one for a public client. Deleting it would be
worse: `oauth2_provider_app_tokens.app_secret_id` is `ON DELETE
CASCADE`, so removing a confidential app's secret takes its tokens with
it, but a public client's tokens carry a NULL `app_secret_id` (#27712)
and survive. An admin who deleted the secret would think they had cut
off the client when they had not.
- `reportedAuthMethod()` replaces the raw stored value in all three
registration responses. It returns the stored method when it agrees with
`client_type`, `none` for a public app, and `client_secret_basic`
otherwise.
- The rows that can disagree are clients registered before #28043
derived the type from the method: the method was stored as sent while
the type was always `confidential`. Such a client holds a secret its
exchange still requires, while `GET` reported `none` and told it to drop
that secret.
- The stored column is deliberately not rewritten, so the response can
still differ from the row. That divergence is what a read-modify-write
client resolves on its next update, and the test asserts the row keeps
what the client sent.
- Coverage: the secrets guard asserts the 400 and that no partial secret
row was left behind. A table test walks `GET` then `PUT` over six
stored-method and client-type pairs: the legacy mismatch in both resend
shapes, the reverse mismatch that registration cannot produce but the
function still handles, an empty stored method, and the single pair that
already agrees and must be reported as stored.
- Docs: the client type is fixed at registration and a type-changing
update is rejected with `invalid_client_metadata` (behavior from #28043
that was never written down), plus what a legacy `none` client now sees.

Refs
https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client



## Manual Tests

Verified by hand against a local dev deployment
(`v2.36.3-devel+c85e4621ef`, dev Postgres), in addition to the automated
suite.

Both guards are reachable only through dynamic client registration,
which was confirmed off by default on this deployment and enabled for
the run. Two of the scenarios need a row where `client_type` and
`token_endpoint_auth_method` disagree, which registration cannot produce
since #28043 derives one from the other, so those rows were seeded by
updating the method column directly on a purpose-built client.

| # | Scenario | Result |
|---|----------|--------|
| 1 | Secrets API refuses a public client, with the guard's own message
| Pass |
| 2 | No partial secret row is left behind by the rejection | Pass |
| 3 | A confidential app's secret create, list, and delete are unchanged
| Pass |
| 4 | Admin-created apps are always confidential, so the guard is
unreachable there | Pass |
| 5 | When stored method and client type agree, the stored value is
reported unchanged | Pass |
| 6 | A legacy confidential row storing `none` reports
`client_secret_basic` | Pass |
| 7 | The reported method is the one the token endpoint enforces, in
both directions | Pass |
| 8 | An update resending the stored value is accepted and leaves the
row alone | Pass |
| 9 | An update resending the reported value heals the row | Pass |
| 10 | The reverse mismatch, a public row storing a secret method,
reports `none` | Pass |
| 11 | An empty or unrecognized stored method falls back to
`client_secret_basic` | Pass |
| 12 | Type-changing updates are rejected both ways,
`client_secret_basic` to `client_secret_post` is allowed | Pass |
| 13 | Regression sweep of the merged stack, discovery through
revocation | Pass |
| 14 | Every claim in the new docs paragraphs matches observed behavior
| Pass |

No correctness defects found. Commands and captured output for each
scenario below.

**Two notes for anyone re-running this.**

The previous runbook for this stack asserts the opposite of scenario 12:
it flips a confidential client to public with a `PUT` and records `200`.
That was correct before #28043 pinned the client type. The `400` here is
the fix, not a regression.

Generate the PKCE verifier with enough entropy that stripping `=+/`
still leaves 43 characters. The `openssl rand -base64 32 | tr -d "=+/" |
cut -c -43` recipe yields 38 to 43, so most runs are rejected by the
token endpoint under RFC 7636 section 4.1 with an error that looks
unrelated. Same trap noted in #28045.

<details>
<summary>Shell helpers used throughout</summary>

```bash
export BASE_URL=http://localhost:3000
export AUTH_HEADER="Coder-Session-Token: $(cat ./.coderv2/session)"
export PGURL="postgres://coder@localhost:$(cat ./.coderv2/postgres/port)/coder?sslmode=disable&password=$(cat ./.coderv2/postgres/password)"

# Enable DCR; both guards are unreachable without it.
curl -s -X PUT "$BASE_URL/api/v2/oauth2-provider/settings" -H "$AUTH_HEADER" \
  -H "Content-Type: application/json" \
  -d '{"dynamic_client_registration_enabled": true}'

# Print "HTTP <code>" then the body.
show() {
  local out; out=$(curl -s -w '\n%{http_code}' "$@")
  echo "HTTP $(printf '%s\n' "$out" | tail -n1)"
  printf '%s\n' "$out" | sed '$d' | jq . 2>/dev/null || printf '%s\n' "$out" | sed '$d'
}

# $1=name, $2=auth method ("" to omit the field).
register() {
  local body
  if [ -z "$2" ]; then
    body=$(jq -nc --arg n "$1" '{client_name:$n,redirect_uris:["http://localhost:9876/callback"]}')
  else
    body=$(jq -nc --arg n "$1" --arg m "$2" '{client_name:$n,redirect_uris:["http://localhost:9876/callback"],token_endpoint_auth_method:$m}')
  fi
  curl -s -X POST "$BASE_URL/oauth2/register" -H "Content-Type: application/json" -d "$body"
}

# The stored row, as opposed to what the API reports.
stored() {
  psql "$PGURL" -At -c "select client_type || ' | ' || coalesce(token_endpoint_auth_method,'<NULL>')
    from oauth2_provider_apps where id = '$1';"
}

# 43 characters from the unreserved set, always. See the note above.
gen_verifier() { openssl rand -base64 96 | tr -d "=+/\n" | cut -c -43; }
challenge_for() { printf '%s' "$1" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_'; }

# Full PKCE authorize plus exchange. $1=client_id, $2=client_secret ("" for none).
exchange() {
  local verifier challenge redirect code args
  verifier=$(gen_verifier); challenge=$(challenge_for "$verifier")
  redirect=$(curl -s -X POST \
    "$BASE_URL/oauth2/authorize?client_id=$1&response_type=code&redirect_uri=http://localhost:9876/callback&state=$(openssl rand -hex 16)&code_challenge=$challenge&code_challenge_method=S256" \
    -H "$AUTH_HEADER" -w '\n%{redirect_url}' -o /dev/null)
  code=$(printf '%s' "$redirect" | grep -oE 'code=[^&]+' | sed 's/code=//')
  args=(-d "grant_type=authorization_code" -d "code=$code" -d "client_id=$1"
        -d "redirect_uri=http://localhost:9876/callback" -d "code_verifier=$verifier")
  [ -n "$2" ] && args+=(-d "client_secret=$2")
  curl -s -X POST "$BASE_URL/oauth2/tokens" -H "Content-Type: application/x-www-form-urlencoded" "${args[@]}"
}
```

</details>

<details>
<summary>1. Secrets API refuses a public client</summary>

A bare non-`201` would also be produced by a request that failed on
authentication, routing, or a malformed UUID before reaching the guard,
so the status and the message are both asserted.

```bash
PUB=$(register manual-28097-public none)
PUB_ID=$(echo "$PUB" | jq -r '.client_id')
stored "$PUB_ID"
show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$PUB_ID/secrets" -H "$AUTH_HEADER"
```

```text
public | none
HTTP 400
{
  "message": "Cannot create a client secret for a public OAuth2 app.",
  "detail": "Public clients authenticate with PKCE and have no client secret. The client type is fixed at registration, so register a new confidential client instead."
}
```

The message is the guard's own, so execution reached `CreateAppSecret`
and returned at the `IsPublic()` check. The detail points at registering
a new confidential client, which scenario 12 confirms is the only
remedy.

</details>

<details>
<summary>2. No partial secret row is left behind</summary>

The guard returns before `GenerateSecret()`, so nothing should exist at
either layer. The count was already `0` at registration, and a
confidential app is queried the same way as a control, so `0` is not
merely what this query always returns.

```bash
curl -s "$BASE_URL/api/v2/oauth2-provider/apps/$PUB_ID/secrets" -H "$AUTH_HEADER" | jq -c .
psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$PUB_ID';"
psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$CONF_ID';"
```

```text
[]
0
1
```

</details>

<details>
<summary>3. A confidential app's secret lifecycle is unchanged</summary>

```bash
CONF=$(register manual-28097-confidential "")
CONF_ID=$(echo "$CONF" | jq -r '.client_id')
show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets" -H "$AUTH_HEADER"
curl -s "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets" -H "$AUTH_HEADER" | jq -c '[.[].id]'
curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$CONF_ID/secrets/$SECRET_ID" \
  -H "$AUTH_HEADER" -o /dev/null -w "delete: HTTP %{http_code}\n"
```

```text
HTTP 201
{
  "id": "da7a1029-47c4-435e-988a-557ffa4aeacf",
  "client_secret_full": "coder_POUtoElODM_<redacted>"
}
["b2fc55b6-...","da7a1029-...","24f8f8c2-..."]
delete: HTTP 204
["b2fc55b6-...","da7a1029-..."]
```

Create, list, and delete all behave as before. The guard keys on
`client_type` and nothing else on this path changed.

Unrelated observation, not a finding against this PR: the listing
returns two different `client_secret_truncated` formats. Secrets issued
at registration are asterisk-padded (`***...TzqEOt`, from
`createDisplaySecret`), while secrets issued through the admin API show
the bare last six characters (`Rixs60`). Both write the same column and
surface through the same field. Cosmetic and pre-existing, but a UI
listing both kinds together would render them inconsistently.

</details>

<details>
<summary>4. Admin-created apps are always confidential</summary>

`postOAuth2ProviderApp` hardcodes the client type, so the guard is
unreachable through the admin create path.

```bash
ADMIN_APP=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps" -H "$AUTH_HEADER" \
  -H "Content-Type: application/json" \
  -d '{"name":"manual-28097-admin","callback_url":"http://localhost:9876/callback"}')
ADMIN_ID=$(echo "$ADMIN_APP" | jq -r '.id')
stored "$ADMIN_ID"
show -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$ADMIN_ID/secrets" -H "$AUTH_HEADER"
```

```text
confidential | client_secret_post
HTTP 201
{
  "id": "a77ab276-ea74-4711-ba8b-955a8cb97951",
  "client_secret_full": "coder_eGlt04LhYg_<redacted>"
}
```

Together with scenario 1 this brackets the guard: it fires for a
dynamically registered public client and for nothing else. Note the
admin API stores `client_secret_post`, not the RFC 7591 section 2
default, so every admin-created app is an agreement case for scenario 5.
Such apps carry no registration access token, so they cannot reach the
RFC 7592 endpoints where the reporting change applies at all.

</details>

<details>
<summary>5. Agreement cases report the stored value unchanged</summary>

The `client_secret_post` case is the one that matters. An implementation
that substituted the type default on every call would still pass the
public case, since `none` is the public default, but would rewrite this
client to `client_secret_basic` and tell it to send its secret in the
wrong place.

```bash
curl -s "$BASE_URL/oauth2/clients/$PUB_ID" -H "Authorization: Bearer $PUB_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'

POST_REG=$(register manual-28097-post client_secret_post)
POST_ID=$(echo "$POST_REG" | jq -r '.client_id')
echo "$POST_REG" | jq -c '{reported_on_register: .token_endpoint_auth_method}'
curl -s "$BASE_URL/oauth2/clients/$POST_ID" -H "Authorization: Bearer $POST_RAT" \
  | jq -c '.token_endpoint_auth_method'
stored "$POST_ID"
```

```text
{"reported":"none"}
{"reported_on_register":"client_secret_post"}
"client_secret_post"
confidential | client_secret_post
```

Registration and read both report the stored value. The update site is
covered by scenarios 8 and 9.

</details>

<details>
<summary>6. A legacy confidential row storing `none` reports
`client_secret_basic`</summary>

Seeded from a real confidential client so it genuinely holds the secret
its exchange requires, with only the method column rewritten. This is
the pre-#28043 shape and cannot be produced through the API any more.

```bash
LEGACY=$(register manual-28097-legacy "")
LEGACY_ID=$(echo "$LEGACY" | jq -r '.client_id')
LEGACY_SECRET=$(echo "$LEGACY" | jq -r '.client_secret')
stored "$LEGACY_ID"

psql "$PGURL" -c "update oauth2_provider_apps set token_endpoint_auth_method = 'none'
  where id = '$LEGACY_ID';"
stored "$LEGACY_ID"
psql "$PGURL" -At -c "select count(*) from oauth2_provider_app_secrets where app_id = '$LEGACY_ID';"

curl -s "$BASE_URL/oauth2/clients/$LEGACY_ID" -H "Authorization: Bearer $LEGACY_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'
stored "$LEGACY_ID"
```

```text
confidential | client_secret_basic
UPDATE 1
confidential | none
1
{"reported":"client_secret_basic"}
confidential | none
```

The response substitutes and the row is deliberately not rewritten. A
read has no side effects.

</details>

<details>
<summary>7. The reported method is the one actually enforced</summary>

The token endpoint enforces on `client_type`, which is still
confidential, so the secret is required regardless of what the method
column says.

```bash
exchange "$LEGACY_ID" "$LEGACY_SECRET" | jq -c '{has_access: has("access_token"), error, error_description}'
exchange "$LEGACY_ID" ""               | jq -c '{has_access: has("access_token"), error, error_description}'
```

```text
{"has_access":true,"error":null,"error_description":null}
{"has_access":false,"error":"invalid_request","error_description":"Missing required parameter: client_secret"}
```

The second line is the pre-fix breakage reproduced. A client that read
`"token_endpoint_auth_method": "none"` from `GET` and dropped its secret
accordingly, which is what RFC 7592 tells it to do, would have hit
exactly this on its next exchange. The old response was not internally
inconsistent, it was actionable and wrong.

Scenario 10 shows the same property in the opposite direction.

</details>

<details>
<summary>8. An update resending the stored value is accepted and changes
nothing</summary>

```bash
show -X PUT "$BASE_URL/oauth2/clients/$LEGACY_ID" \
  -H "Authorization: Bearer $LEGACY_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-legacy","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}'
stored "$LEGACY_ID"
```

```text
HTTP 200
  "token_endpoint_auth_method": "client_secret_basic",
confidential | none
```

Three things at once. The update is accepted, which is why the
type-change guard requires the auth method to actually change: the
requested `none` implies a public client while the row is confidential,
so a guard keyed on the type mismatch alone would reject this and lock a
legacy client out of managing its own registration. The `PUT` reports
the same substituted value as the `GET`, covering the third call site.
The row keeps what the client sent, so the divergence persists until
scenario 9.

</details>

<details>
<summary>9. An update resending the reported value heals the
row</summary>

```bash
show -X PUT "$BASE_URL/oauth2/clients/$LEGACY_ID" \
  -H "Authorization: Bearer $LEGACY_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-legacy","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_basic"}'
stored "$LEGACY_ID"
curl -s "$BASE_URL/oauth2/clients/$LEGACY_ID" -H "Authorization: Bearer $LEGACY_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'
exchange "$LEGACY_ID" "$LEGACY_SECRET" | jq -c '{has_access: has("access_token")}'
```

```text
HTTP 200
  "token_endpoint_auth_method": "client_secret_basic",
confidential | client_secret_basic
{"reported":"client_secret_basic"}
{"has_access":true}
```

The row healed through an ordinary read-modify-write cycle, with no
migration, backfill, or admin action. That works only because scenario 8
keeps the door open and this response gives the client a correct value
to echo back; remove either and the row stays inconsistent indefinitely.

</details>

<details>
<summary>10. The reverse mismatch reports `none`</summary>

Registration cannot produce this direction either, but
`reportedAuthMethod` branches on the general disagreement rather than
the one shape known to exist, so it is covered.

```bash
REVERSE=$(register manual-28097-reverse none)
REVERSE_ID=$(echo "$REVERSE" | jq -r '.client_id')
psql "$PGURL" -c "update oauth2_provider_apps set token_endpoint_auth_method = 'client_secret_basic'
  where id = '$REVERSE_ID';"
stored "$REVERSE_ID"
curl -s "$BASE_URL/oauth2/clients/$REVERSE_ID" -H "Authorization: Bearer $REVERSE_RAT" \
  | jq -c '{reported: .token_endpoint_auth_method}'
exchange "$REVERSE_ID" "" | jq -c '{has_access: has("access_token"), error}'
```

```text
public | client_secret_basic
{"reported":"none"}
{"has_access":true,"error":null}
```

This client has no secret row at all and the token endpoint does not ask
for one, so `none` is what the response should say. Reporting the stored
`client_secret_basic` would have instructed it to send a secret that
does not exist.

Both resend shapes behave symmetrically with scenarios 8 and 9:

```text
resend stored (client_secret_basic) -> reported "none", row unchanged
resend reported (none)              -> reported "none", row now public | none
```

</details>

<details>
<summary>11. Empty or unrecognized stored methods fall back to the
default</summary>

`NULL` and `''` are indistinguishable once read into `sql.NullString`. A
third case was added because the function gates on validity rather than
emptiness.

```bash
for v in "null" "''" "'private_key_jwt'"; do
  psql "$PGURL" -At -c "update oauth2_provider_apps set token_endpoint_auth_method = $v where id = '$CONF_ID';"
  stored "$CONF_ID"
  curl -s "$BASE_URL/oauth2/clients/$CONF_ID" -H "Authorization: Bearer $CONF_RAT" \
    | jq -c '.token_endpoint_auth_method'
done
```

```text
confidential | <NULL>
"client_secret_basic"
confidential |
"client_secret_basic"
confidential | private_key_jwt
"client_secret_basic"
```

`private_key_jwt` is a real RFC 7591 method that Coder does not
implement. Reporting it back would advertise an authentication scheme
the token endpoint cannot honor, which is the same class of problem as
the legacy `none` report in scenario 7.

</details>

<details>
<summary>12. Type-changing updates are rejected both ways</summary>

```bash
show -X PUT "$BASE_URL/oauth2/clients/$CONF_ID" \
  -H "Authorization: Bearer $CONF_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-confidential","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}'
stored "$CONF_ID"

show -X PUT "$BASE_URL/oauth2/clients/$PUB_ID" \
  -H "Authorization: Bearer $PUB_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-public","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_basic"}'
stored "$PUB_ID"

show -X PUT "$BASE_URL/oauth2/clients/$CONF_ID" \
  -H "Authorization: Bearer $CONF_RAT" -H "Content-Type: application/json" \
  -d '{"client_name":"manual-28097-confidential","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"client_secret_post"}'
stored "$CONF_ID"
```

```text
HTTP 400
{
  "error": "invalid_client_metadata",
  "error_description": "token_endpoint_auth_method cannot move an existing client between public and confidential (stored \"client_secret_basic\", requested \"none\"); the client type is fixed at registration, so register a new client instead"
}
confidential | client_secret_basic

HTTP 400
{
  "error": "invalid_client_metadata",
  "error_description": "token_endpoint_auth_method cannot move an existing client between public and confidential (stored \"none\", requested \"client_secret_basic\"); the client type is fixed at registration, so register a new client instead"
}
public | none

HTTP 200
  "token_endpoint_auth_method": "client_secret_post",
confidential | client_secret_post
```

Both rejections leave the row and its secrets untouched. A partial
application would be the dangerous outcome here, a client left
confidential while its caller believes it went public.

The third case is the control. Two `400`s alone would be equally
consistent with a guard that rejects every `token_endpoint_auth_method`
change, a considerably more disruptive rule than the documented one. The
`200` pins the guard to the derived client type rather than the method
string.

The second case is also what backs scenario 1. If public to confidential
were permitted, the workaround to a refused secret request would be to
flip the type and ask again. The two guards close that loop, which is
why the same remedy appears in both error messages.

</details>

<details>
<summary>13. Regression sweep of the merged stack</summary>

Nothing here is new in this PR, but the guards sit on top of it.

```text
discovery token_endpoint_auth_methods_supported : ["client_secret_basic","client_secret_post","none"]
public registration, client_secret key present  : false
confidential registration, secret issued        : true, method defaulted to client_secret_basic
PKCE-only exchange, no client_secret sent       : access + refresh issued
access token against /api/v2/users/me           : 200
token row app_id / app_secret_id                : populated / NULL
RFC 7009 revoke of own refresh token            : 200, access token then 401
authorized-apps listing while a token is live   : [{"name":"manual-28097-public"}]
bulk DELETE /oauth2/tokens                      : 204, listing then []
```

The NULL `app_secret_id` is what makes the secrets guard necessary. That
column is `ON DELETE CASCADE`, so deleting a confidential app's secret
takes its tokens with it, while a public client's tokens would survive.
An admin who deleted such a secret would believe access was cut off when
it was not.

PKCE failure modes were checked separately, since the token endpoint
distinguishes two the previous runbook treated as one:

```text
verifier omitted                     : invalid_request, RFC 7636 section 4.1 bounds
well-formed 43 chars but wrong       : invalid_grant, "The PKCE code verifier is invalid"
correct verifier, replaying that code: invalid_grant, "invalid or expired"
```

The third confirms the failed check destroys the code, so a leaked code
cannot absorb repeated verifier guesses.

</details>

<details>
<summary>14. The new docs paragraphs match observed behavior</summary>

`pnpm run lint-docs` reports 0 errors across 501 files, `pnpm run
format-docs` rewrites nothing, and Vale reports 0 errors with 2
warnings, both on pre-existing gerund headings that the same file on
`main` also produces. The new prose is one sentence per line.

| Documented claim | Verified by |
|---|---|
| A client's type is fixed when it registers | 12 |
| A type-changing update is rejected with `invalid_client_metadata` |
12, both directions |
| The client either holds a secret that would stop being required or has
none and no way to be issued one | 12 (2 secrets), 1 and 12 (0 secrets,
issuance refused) |
| Switching between `client_secret_basic` and `client_secret_post` is
allowed | 12 |
| To change type, register a new client | matches the remedy in both
errors and in scenario 1's detail |
| Legacy `none` clients are stored as confidential and still require
their `client_secret` | 6, 7 |
| Coder reports `client_secret_basic` for those clients | 6 |
| So that what it reports matches what it enforces | 7, both directions
|
| The mismatch clears itself the next time the client updates its
registration | 9 |

One wording note. Scenario 8 shows the mismatch does not clear on an
update that resends the stored value, so strictly it clears on the next
update carrying the reported value. A read-modify-write client, which is
what RFC 7592 section 2.2 prescribes, always carries the reported value,
so the sentence holds for the client it describes. A client that
hardcodes its own metadata would not self-heal, but it would also not be
following RFC 7592.

</details>

<details>
<summary>Cleanup</summary>

```bash
for id in "$PUB_ID" "$CONF_ID" "$POST_ID" "$LEGACY_ID" "$REVERSE_ID" "$ADMIN_ID"; do
  curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$id" -H "$AUTH_HEADER" \
    -o /dev/null -w "%{http_code}\n"
done
curl -s -X PUT "$BASE_URL/api/v2/oauth2-provider/settings" -H "$AUTH_HEADER" \
  -H "Content-Type: application/json" -d '{"dynamic_client_registration_enabled": false}'
show -X POST "$BASE_URL/oauth2/register" -H "Content-Type: application/json" \
  -d '{"client_name":"should-fail","redirect_uris":["http://localhost:9876/callback"],"token_endpoint_auth_method":"none"}'
```

```text
204 (x6)
{"dynamic_client_registration_enabled":false}
HTTP 403
{"error":"invalid_request","error_description":"Dynamic client registration is disabled on this deployment"}
```

All six test apps deleted with no orphaned secret or token rows. Both
seeded rows had already healed to a consistent state before deletion.
DCR is back off, confirmed by a registration attempt rather than by
reading the flag back.

</details>
2026-09-01 08:58:01 -07:00

794 lines
31 KiB
Go

package oauth2provider_test
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
"golang.org/x/xerrors"
"cdr.dev/slog/v3/sloggers/slogtest"
"github.com/coder/coder/v2/coderd/audit"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/coderd/database/dbmock"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/oauth2provider"
"github.com/coder/coder/v2/coderd/tracing"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
// TestCreateDynamicClientRegistration_DCREnabled is a focused unit test on
// the RFC 7591 handler itself, bypassing the full coderdtest HTTP server. It
// verifies the dynamic-client-registration-enabled gate: registration
// succeeds once an admin explicitly enables DCR, is rejected with 403 when
// explicitly disabled, and defaults to disabled when the setting has never
// been configured.
func TestCreateDynamicClientRegistration_DCREnabled(t *testing.T) {
t.Parallel()
accessURL, err := url.Parse("https://oauth2-registration-dcr-test.example.com")
require.NoError(t, err)
tests := []struct {
name string
// configureDCR is nil for "never configured".
configureDCR *bool
wantStatus int
}{
{
name: "EnabledAllowsRegistration",
configureDCR: new(true),
wantStatus: http.StatusCreated,
},
{
name: "DisabledRejectsRegistration",
configureDCR: new(false),
wantStatus: http.StatusForbidden,
},
{
name: "NeverConfiguredDefaultsToDisabled",
configureDCR: nil,
wantStatus: http.StatusForbidden,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
if tt.configureDCR != nil {
err := db.UpsertOAuth2DCREnabled(ctx, *tt.configureDCR)
require.NoError(t, err)
}
logger := slogtest.Make(t, nil)
auditor := audit.NewNop()
// audit.InitRequest requires the ResponseWriter to be a
// *tracing.StatusWriter, which normally comes from the
// middleware chain in coderd.go; wrap it here to match.
handler := tracing.StatusWriterMiddleware(oauth2provider.CreateDynamicClientRegistration(db, accessURL, &auditor, logger))
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
}
body, err := json.Marshal(req)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodPost, "/oauth2/register", bytes.NewReader(body)).WithContext(ctx)
r.Header.Set("Content-Type", "application/json")
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, tt.wantStatus, rw.Code)
if tt.wantStatus != http.StatusForbidden {
return
}
var errResp map[string]string
require.NoError(t, json.Unmarshal(rw.Body.Bytes(), &errResp))
require.Equal(t, "invalid_request", errResp["error"])
require.Contains(t, errResp["error_description"], "disabled")
})
}
}
func TestCreateDynamicClientRegistration_ClientType(t *testing.T) {
t.Parallel()
accessURL, err := url.Parse("https://oauth2-registration-client-type-test.example.com")
require.NoError(t, err)
tests := []struct {
name string
req codersdk.OAuth2ClientRegistrationRequest
wantClientType string
wantSecret bool
}{
{
name: "DefaultAuthMethodIsConfidential",
req: codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
},
wantClientType: "confidential",
wantSecret: true,
},
{
name: "ClientSecretPostIsConfidential",
req: codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
TokenEndpointAuthMethod: codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost,
},
wantClientType: "confidential",
wantSecret: true,
},
{
name: "NoneIsPublicWithNoSecret",
req: codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
TokenEndpointAuthMethod: codersdk.OAuth2TokenEndpointAuthMethodNone,
},
wantClientType: "public",
wantSecret: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
require.NoError(t, db.UpsertOAuth2DCREnabled(ctx, true))
logger := slogtest.Make(t, nil)
auditor := audit.NewNop()
handler := tracing.StatusWriterMiddleware(oauth2provider.CreateDynamicClientRegistration(db, accessURL, &auditor, logger))
body, err := json.Marshal(tt.req)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodPost, "/oauth2/register", bytes.NewReader(body)).WithContext(ctx)
r.Header.Set("Content-Type", "application/json")
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, http.StatusCreated, rw.Code)
var resp codersdk.OAuth2ClientRegistrationResponse
require.NoError(t, json.Unmarshal(rw.Body.Bytes(), &resp))
// RFC 7591 §3.2.1: client_secret is omitted entirely for a client
// that was not issued one. Assert against the raw body, because a
// decoded struct cannot tell an absent key from a present empty
// one, and key presence is exactly what a client branches on.
var rawBody map[string]json.RawMessage
require.NoError(t, json.Unmarshal(rw.Body.Bytes(), &rawBody))
if tt.wantSecret {
require.Contains(t, rawBody, "client_secret")
require.NotEmpty(t, resp.ClientSecret)
} else {
require.NotContains(t, rawBody, "client_secret")
}
clientID, err := uuid.Parse(resp.ClientID)
require.NoError(t, err)
app, err := db.GetOAuth2ProviderAppByClientID(ctx, clientID)
require.NoError(t, err)
require.Equal(t, tt.wantClientType, app.ClientType)
secrets, err := db.GetOAuth2ProviderAppSecretsByAppID(ctx, clientID)
require.NoError(t, err)
if tt.wantSecret {
require.Len(t, secrets, 1)
} else {
require.Empty(t, secrets)
}
})
}
}
// TestCreateDynamicClientRegistration_RegistrationClientURI pins the
// accessURL.JoinPath fix: a trailing slash on the configured access URL
// used to mint "//oauth2/clients/{id}" via fmt.Sprintf. Without this test,
// reverting to fmt.Sprintf would pass every other test in this file, since
// none of them configures a trailing-slash accessURL.
func TestCreateDynamicClientRegistration_RegistrationClientURI(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
accessURL, err := url.Parse("https://oauth2-registration-client-uri-test.example.com/")
require.NoError(t, err)
db, _ := dbtestutil.NewDB(t)
require.NoError(t, db.UpsertOAuth2DCREnabled(ctx, true))
logger := slogtest.Make(t, nil)
auditor := audit.NewNop()
handler := tracing.StatusWriterMiddleware(oauth2provider.CreateDynamicClientRegistration(db, accessURL, &auditor, logger))
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
}
body, err := json.Marshal(req)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodPost, "/oauth2/register", bytes.NewReader(body)).WithContext(ctx)
r.Header.Set("Content-Type", "application/json")
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, http.StatusCreated, rw.Code)
var resp codersdk.OAuth2ClientRegistrationResponse
require.NoError(t, json.Unmarshal(rw.Body.Bytes(), &resp))
wantURI := "https://oauth2-registration-client-uri-test.example.com/oauth2/clients/" + resp.ClientID
require.Equal(t, wantURI, resp.RegistrationClientURI)
}
// TestCreateDynamicClientRegistration_Transaction verifies that the app insert
// and the secret insert share a single database transaction, so a failure
// partway through can't leave a permanently committed, orphaned app row with
// no matching secret.
//
// A mock store is used because the failure needs to be injected between the
// two inserts, which isn't reachable through the public registration API
// against a real database (the failing insert's unique secret_prefix is
// generated internally and can't be forced to collide from the outside).
// mDB.EXPECT().InTx(...).Times(1) is the key assertion: it fails the test if
// the two inserts are ever changed back to being independent, unwrapped
// db.InsertX calls, since that path never calls InTx at all.
func TestCreateDynamicClientRegistration_Transaction(t *testing.T) {
t.Parallel()
accessURL, err := url.Parse("https://oauth2-registration-tx-test.example.com")
require.NoError(t, err)
tests := []struct {
name string
secretInsertErr error
wantStatus int
}{
{
name: "BothInsertsShareOneTransaction",
wantStatus: http.StatusCreated,
},
{
name: "SecretInsertFailureFailsTheWholeRegistration",
secretInsertErr: xerrors.New("simulated secret insert failure"),
wantStatus: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
// A separate handle for the transaction, so a call made on the
// outer store is distinguishable from one made on tx.
mTx := dbmock.NewMockStore(ctrl)
mDB.EXPECT().GetOAuth2DCREnabled(gomock.Any()).Return(true, nil).Times(1)
mDB.EXPECT().InTx(gomock.Any(), gomock.Any()).DoAndReturn(
func(f func(database.Store) error, _ *database.TxOptions) error {
return f(mTx)
},
).Times(1)
// Both expectations live on mTx, not mDB, and that is the
// assertion. An insert issued on the outer store, whether after
// InTx returns or from inside the closure against the wrong
// handle, lands on mDB, which has no expectation for it, so
// gomock fails the unexpected call. Registering both on a single
// mock makes inside and outside the transaction indistinguishable
// and the test then passes either way, which is the trap the
// project's own InTx rule exists to catch
// (.claude/docs/DATABASE.md).
// Echoes params.ClientType rather than hardcoding it, so the mock
// stays honest about what the handler asked for; a hardcoded
// value would keep passing if a later change reused this
// scaffolding for a public request without updating it.
appCall := mTx.EXPECT().InsertOAuth2ProviderApp(gomock.Any(), gomock.Any()).
DoAndReturn(func(_ context.Context, params database.InsertOAuth2ProviderAppParams) (database.OAuth2ProviderApp, error) {
return database.OAuth2ProviderApp{
ID: uuid.New(),
ClientType: params.ClientType,
}, nil
}).
Times(1)
secretCall := mTx.EXPECT().InsertOAuth2ProviderAppSecret(gomock.Any(), gomock.Any()).
Return(database.OAuth2ProviderAppSecret{}, tt.secretInsertErr).
Times(1)
// The secret insert can only run after the app insert, matching
// registration.go's literal ordering inside the InTx closure.
gomock.InOrder(appCall, secretCall)
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: tt.secretInsertErr != nil})
auditor := audit.NewNop()
handler := tracing.StatusWriterMiddleware(oauth2provider.CreateDynamicClientRegistration(mDB, accessURL, &auditor, logger))
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
}
body, err := json.Marshal(req)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodPost, "/oauth2/register", bytes.NewReader(body)).WithContext(ctx)
r.Header.Set("Content-Type", "application/json")
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, tt.wantStatus, rw.Code)
})
}
}
// TestCreateDynamicClientRegistration_PublicClientSkipsSecretInsert verifies
// that a public client's registration issues no InsertOAuth2ProviderAppSecret
// call at all, rather than inserting a row with an empty secret. This pins
// the mechanism (no call made); TestCreateDynamicClientRegistration_ClientType
// /NoneIsPublicWithNoSecret pins the outcome (no row exists) against a real
// database. Both are kept: a handler that inserts an empty-secret row would
// pass the outcome test's require.Empty only if the read side also filters
// it out, so the mechanism test is the one that fails at the actual call
// site if that regresses.
func TestCreateDynamicClientRegistration_PublicClientSkipsSecretInsert(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
accessURL, err := url.Parse("https://oauth2-registration-public-tx-test.example.com")
require.NoError(t, err)
ctrl := gomock.NewController(t)
mDB := dbmock.NewMockStore(ctrl)
mTx := dbmock.NewMockStore(ctrl)
mDB.EXPECT().GetOAuth2DCREnabled(gomock.Any()).Return(true, nil).Times(1)
mDB.EXPECT().InTx(gomock.Any(), gomock.Any()).DoAndReturn(
func(f func(database.Store) error, _ *database.TxOptions) error {
return f(mTx)
},
).Times(1)
mTx.EXPECT().InsertOAuth2ProviderApp(gomock.Any(), gomock.Any()).
Return(database.OAuth2ProviderApp{
ID: uuid.New(),
ClientType: database.OAuth2ProviderAppClientTypePublic,
}, nil).
Times(1)
// The absence of an InsertOAuth2ProviderAppSecret expectation on either
// handle is the assertion: gomock fails on an unexpected call. This only
// holds because the two handles are distinct, so a secret insert issued
// anywhere is unexpected rather than absorbed by a shared expectation.
logger := slogtest.Make(t, nil)
auditor := audit.NewNop()
handler := tracing.StatusWriterMiddleware(oauth2provider.CreateDynamicClientRegistration(mDB, accessURL, &auditor, logger))
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
TokenEndpointAuthMethod: codersdk.OAuth2TokenEndpointAuthMethodNone,
}
body, err := json.Marshal(req)
require.NoError(t, err)
r := httptest.NewRequest(http.MethodPost, "/oauth2/register", bytes.NewReader(body)).WithContext(ctx)
r.Header.Set("Content-Type", "application/json")
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, http.StatusCreated, rw.Code)
}
// TestUpdateClientConfiguration_ClientTypeIsImmutable verifies that an
// RFC 7592 update cannot move a registered client between public and
// confidential. Allowing it would either drop the secret requirement for a
// client that has a secret, or mark a client confidential when it has no
// secret and no way to be issued one, permanently breaking its token
// exchange. Switching between the two confidential auth methods stays
// allowed, since it changes nothing about how the client authenticates.
func TestUpdateClientConfiguration_ClientTypeIsImmutable(t *testing.T) {
t.Parallel()
accessURL, err := url.Parse("https://oauth2-registration-immutable-type-test.example.com")
require.NoError(t, err)
tests := []struct {
name string
registerAs codersdk.OAuth2TokenEndpointAuthMethod
updateTo codersdk.OAuth2TokenEndpointAuthMethod
// omitAuthMethod sends the update with no token_endpoint_auth_method at
// all, which ApplyDefaults rewrites to client_secret_basic before the
// guard sees it. updateTo is ignored when set.
omitAuthMethod bool
wantStatus int
wantFinalCallback string
// wantClientType is deliberately a bare literal rather than the
// database constant: it pins the value actually stored in the column,
// so it must fail if that spelling ever changes. Fixtures that set
// state use the constant instead.
wantClientType string
}{
{
name: "ConfidentialToPublicIsRejected",
registerAs: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
updateTo: codersdk.OAuth2TokenEndpointAuthMethodNone,
wantStatus: http.StatusBadRequest,
wantClientType: "confidential",
},
{
name: "PublicToConfidentialIsRejected",
registerAs: codersdk.OAuth2TokenEndpointAuthMethodNone,
updateTo: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
wantStatus: http.StatusBadRequest,
wantClientType: "public",
},
{
// RFC 7592 makes PUT a full replacement, so an omitted auth method
// defaults to client_secret_basic and moves a public client to
// confidential, which is rejected. The rejection is correct; what
// matters is that it is reported in terms the caller can act on,
// since they never sent the field named in the error.
name: "PublicWithOmittedAuthMethodIsRejected",
registerAs: codersdk.OAuth2TokenEndpointAuthMethodNone,
omitAuthMethod: true,
wantStatus: http.StatusBadRequest,
wantClientType: "public",
},
{
// Both are confidential, so the guard must not fire.
name: "BasicToPostIsAllowed",
registerAs: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
updateTo: codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost,
wantStatus: http.StatusOK,
wantFinalCallback: "https://example.com/updated-callback",
wantClientType: "confidential",
},
{
// A confidential client omitting the field is unaffected, because
// the default it lands on is also confidential. Pinned so the
// asymmetry with the public case above stays visible.
name: "ConfidentialWithOmittedAuthMethodIsAllowed",
registerAs: codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost,
omitAuthMethod: true,
wantStatus: http.StatusOK,
wantFinalCallback: "https://example.com/updated-callback",
wantClientType: "confidential",
},
{
name: "PublicToPublicIsAllowed",
registerAs: codersdk.OAuth2TokenEndpointAuthMethodNone,
updateTo: codersdk.OAuth2TokenEndpointAuthMethodNone,
wantStatus: http.StatusOK,
wantFinalCallback: "https://example.com/updated-callback",
wantClientType: "public",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
require.NoError(t, db.UpsertOAuth2DCREnabled(ctx, true))
logger := slogtest.Make(t, nil)
auditor := audit.NewNop()
// Register the client first, so the update runs against a real
// persisted client_type rather than a hand-built fixture.
createHandler := tracing.StatusWriterMiddleware(oauth2provider.CreateDynamicClientRegistration(db, accessURL, &auditor, logger))
createBody, err := json.Marshal(codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
TokenEndpointAuthMethod: tt.registerAs,
})
require.NoError(t, err)
createReq := httptest.NewRequest(http.MethodPost, "/oauth2/register", bytes.NewReader(createBody)).WithContext(ctx)
createReq.Header.Set("Content-Type", "application/json")
createRW := httptest.NewRecorder()
createHandler.ServeHTTP(createRW, createReq)
require.Equal(t, http.StatusCreated, createRW.Code)
var created codersdk.OAuth2ClientRegistrationResponse
require.NoError(t, json.Unmarshal(createRW.Body.Bytes(), &created))
clientID, err := uuid.Parse(created.ClientID)
require.NoError(t, err)
updateHandler := tracing.StatusWriterMiddleware(oauth2provider.UpdateClientConfiguration(db, &auditor, logger))
updateReqBody := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/updated-callback"},
}
if !tt.omitAuthMethod {
updateReqBody.TokenEndpointAuthMethod = tt.updateTo
}
updateBody, err := json.Marshal(updateReqBody)
require.NoError(t, err)
// The handler reads client_id via chi.URLParam, which normally
// comes from the router in coderd.go.
rctx := chi.NewRouteContext()
rctx.URLParams.Add("client_id", clientID.String())
updateCtx := context.WithValue(ctx, chi.RouteCtxKey, rctx)
updateReq := httptest.NewRequest(http.MethodPut, "/oauth2/clients/"+clientID.String(), bytes.NewReader(updateBody)).WithContext(updateCtx)
updateReq.Header.Set("Content-Type", "application/json")
updateRW := httptest.NewRecorder()
updateHandler.ServeHTTP(updateRW, updateReq)
require.Equal(t, tt.wantStatus, updateRW.Code)
app, err := db.GetOAuth2ProviderAppByClientID(ctx, clientID)
require.NoError(t, err)
// client_type is what IsPublic() reads to decide whether the token
// endpoint validates a secret, so it must be unchanged whether the
// update was accepted or rejected.
require.Equal(t, tt.wantClientType, app.ClientType)
if tt.wantStatus != http.StatusOK {
var errResp map[string]string
require.NoError(t, json.Unmarshal(updateRW.Body.Bytes(), &errResp))
require.Equal(t, "invalid_client_metadata", errResp["error"])
// The error code alone cannot distinguish this guard from
// req.Validate() failing, which returns the same one, and
// neither can the untouched row below. The description is the
// only field that tells them apart, so assert on it: a change
// that made "none" fail validation outright would otherwise
// leave these cases green while testing something else.
require.Contains(t, errResp["error_description"], "cannot move an existing client between public and confidential")
// It must also name what the server actually compared, since
// the caller may never have sent the field.
require.Contains(t, errResp["error_description"], "client_secret_basic")
// The rejection must leave the whole update unapplied, not
// just the client_type field.
require.Equal(t, "https://example.com/callback", app.CallbackURL)
return
}
require.Equal(t, tt.wantFinalCallback, app.CallbackURL)
wantMethod := tt.updateTo
if tt.omitAuthMethod {
// ApplyDefaults substitutes the RFC 7591 default.
wantMethod = codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic
}
require.Equal(t, string(wantMethod), app.TokenEndpointAuthMethod.String)
})
}
}
// TestUpdateClientConfiguration_LegacyAuthMethodMismatch covers clients that
// registered before client_type was derived from token_endpoint_auth_method.
// Registration persisted whatever auth method was requested while hardcoding
// client_type to "confidential", and "none" has always passed validation, so
// apps stored as confidential with an auth method of "none" exist in any
// deployment where a native or MCP client self-registered. That is the exact
// population public clients are for.
//
// Such a client must still be able to manage its registration. Comparing only
// the derived client type would reject it forever, including when it resends
// the metadata GET reports, leaving re-registration as the only recovery. It
// must also not be silently converted to public, since it holds a secret that
// would stop being required.
func TestUpdateClientConfiguration_LegacyAuthMethodMismatch(t *testing.T) {
t.Parallel()
tests := []struct {
name string
updateTo codersdk.OAuth2TokenEndpointAuthMethod
}{
{
// The read-modify-write shape: echo back what GET reports.
name: "ResendingStoredAuthMethodIsAccepted",
updateTo: codersdk.OAuth2TokenEndpointAuthMethodNone,
},
{
// Moving to a secret-based method matches the stored confidential
// type, so it is allowed and repairs the divergence.
name: "MovingToSecretBasedMethodIsAccepted",
updateTo: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
require.NoError(t, db.UpsertOAuth2DCREnabled(ctx, true))
legacy := dbgen.OAuth2ProviderApp(t, db, database.OAuth2ProviderApp{
CallbackURL: "https://example.com/callback",
RedirectUris: []string{"https://example.com/callback"},
ClientType: database.OAuth2ProviderAppClientTypeConfidential,
TokenEndpointAuthMethod: sql.NullString{String: "none", Valid: true},
DynamicallyRegistered: sql.NullBool{Bool: true, Valid: true},
})
// Registration issued a secret unconditionally back then.
_ = dbgen.OAuth2ProviderAppSecret(t, db, database.OAuth2ProviderAppSecret{AppID: legacy.ID})
logger := slogtest.Make(t, nil)
auditor := audit.NewNop()
handler := tracing.StatusWriterMiddleware(oauth2provider.UpdateClientConfiguration(db, &auditor, logger))
body, err := json.Marshal(codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/updated-callback"},
TokenEndpointAuthMethod: tt.updateTo,
})
require.NoError(t, err)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("client_id", legacy.ID.String())
r := httptest.NewRequest(http.MethodPut, "/oauth2/clients/"+legacy.ID.String(),
bytes.NewReader(body)).WithContext(context.WithValue(ctx, chi.RouteCtxKey, rctx))
r.Header.Set("Content-Type", "application/json")
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, http.StatusOK, rw.Code, "body: %s", rw.Body.String())
app, err := db.GetOAuth2ProviderAppByClientID(ctx, legacy.ID)
require.NoError(t, err)
require.Equal(t, "https://example.com/updated-callback", app.CallbackURL)
require.Equal(t, string(tt.updateTo), app.TokenEndpointAuthMethod.String)
// The update must not convert the client to public. It still holds
// a secret, and IsPublic() reading "public" here would stop the
// token endpoint from requiring it.
require.Equal(t, "confidential", app.ClientType)
require.False(t, app.IsPublic())
secrets, err := db.GetOAuth2ProviderAppSecretsByAppID(ctx, legacy.ID)
require.NoError(t, err)
require.Len(t, secrets, 1)
})
}
}
func TestClientConfiguration_ReportedAuthMethod(t *testing.T) {
t.Parallel()
tests := []struct {
name string
clientType string
// An old row reads back empty whether it is NULL or an empty string.
stored sql.NullString
// Sent on the PUT. Must either match the stored method or agree with
// the client type, or the type-change guard rejects the update first.
resend codersdk.OAuth2TokenEndpointAuthMethod
want codersdk.OAuth2TokenEndpointAuthMethod
}{
{
// A client that sends back the stored method, not the reported one.
name: "ConfidentialStoringNoneResendingStored",
clientType: database.OAuth2ProviderAppClientTypeConfidential,
stored: sql.NullString{String: string(codersdk.OAuth2TokenEndpointAuthMethodNone), Valid: true},
resend: codersdk.OAuth2TokenEndpointAuthMethodNone,
want: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
},
{
// A client that sends back what GET reported, which fixes the row.
name: "ConfidentialStoringNoneResendingReported",
clientType: database.OAuth2ProviderAppClientTypeConfidential,
stored: sql.NullString{String: string(codersdk.OAuth2TokenEndpointAuthMethodNone), Valid: true},
resend: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
want: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
},
{
name: "PublicStoringSecretMethodResendingStored",
clientType: database.OAuth2ProviderAppClientTypePublic,
stored: sql.NullString{String: string(codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic), Valid: true},
resend: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
want: codersdk.OAuth2TokenEndpointAuthMethodNone,
},
{
name: "PublicStoringSecretMethodResendingReported",
clientType: database.OAuth2ProviderAppClientTypePublic,
stored: sql.NullString{String: string(codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic), Valid: true},
resend: codersdk.OAuth2TokenEndpointAuthMethodNone,
want: codersdk.OAuth2TokenEndpointAuthMethodNone,
},
{
// RFC 7591 §2 defaults an unset method to client_secret_basic.
name: "ConfidentialStoringNothing",
clientType: database.OAuth2ProviderAppClientTypeConfidential,
stored: sql.NullString{String: "", Valid: true},
resend: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
want: codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
},
{
// The stored method agrees with the type but is not the type
// default, so this case fails if the default is returned instead.
name: "ConfidentialStoringClientSecretPost",
clientType: database.OAuth2ProviderAppClientTypeConfidential,
stored: sql.NullString{String: string(codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost), Valid: true},
resend: codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost,
want: codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
// Seeded directly, since registration derives the type from the
// method and can no longer create a disagreeing row.
app := dbgen.OAuth2ProviderApp(t, db, database.OAuth2ProviderApp{
CallbackURL: "https://example.com/callback",
RedirectUris: []string{"https://example.com/callback"},
ClientType: tt.clientType,
TokenEndpointAuthMethod: tt.stored,
DynamicallyRegistered: sql.NullBool{Bool: true, Valid: true},
})
rctx := chi.NewRouteContext()
rctx.URLParams.Add("client_id", app.ID.String())
getReq := httptest.NewRequest(http.MethodGet, "/oauth2/clients/"+app.ID.String(), nil).
WithContext(context.WithValue(ctx, chi.RouteCtxKey, rctx))
getRW := httptest.NewRecorder()
oauth2provider.GetClientConfiguration(db).ServeHTTP(getRW, getReq)
require.Equal(t, http.StatusOK, getRW.Code, "body: %s", getRW.Body.String())
var got codersdk.OAuth2ClientConfiguration
require.NoError(t, json.NewDecoder(getRW.Body).Decode(&got))
require.Equal(t, tt.want, got.TokenEndpointAuthMethod)
logger := slogtest.Make(t, nil)
auditor := audit.NewNop()
handler := tracing.StatusWriterMiddleware(oauth2provider.UpdateClientConfiguration(db, &auditor, logger))
body, err := json.Marshal(codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
TokenEndpointAuthMethod: tt.resend,
})
require.NoError(t, err)
putRCtx := chi.NewRouteContext()
putRCtx.URLParams.Add("client_id", app.ID.String())
putReq := httptest.NewRequest(http.MethodPut, "/oauth2/clients/"+app.ID.String(),
bytes.NewReader(body)).WithContext(context.WithValue(ctx, chi.RouteCtxKey, putRCtx))
putReq.Header.Set("Content-Type", "application/json")
putRW := httptest.NewRecorder()
handler.ServeHTTP(putRW, putReq)
require.Equal(t, http.StatusOK, putRW.Code, "body: %s", putRW.Body.String())
var updated codersdk.OAuth2ClientConfiguration
require.NoError(t, json.NewDecoder(putRW.Body).Decode(&updated))
require.Equal(t, tt.want, updated.TokenEndpointAuthMethod)
// The row keeps what the client sent, so the response can still
// disagree with it.
stored, err := db.GetOAuth2ProviderAppByClientID(ctx, app.ID)
require.NoError(t, err)
require.Equal(t, string(tt.resend), stored.TokenEndpointAuthMethod.String)
require.Equal(t, tt.clientType, stored.ClientType)
})
}
}