Files
coder/coderd/oauth2_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

2240 lines
75 KiB
Go

package coderd_test
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/apikey"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/coderdtest/oidctest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/coderd/oauth2provider"
"github.com/coder/coder/v2/coderd/oauth2provider/oauth2providertest"
"github.com/coder/coder/v2/coderd/userpassword"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
"github.com/coder/serpent"
)
func TestOAuth2ProviderApps(t *testing.T) {
t.Parallel()
// NOTE: Unit tests for OAuth2 provider app validation have been migrated to
// oauth2provider/provider_test.go for better separation of concerns.
// This test function now focuses on integration testing with the full server stack.
t.Run("IntegrationFlow", func(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
ctx := testutil.Context(t, testutil.WaitLong)
// Test basic app creation and management in integration context
//nolint:gocritic // OAuth2 app management requires owner permission.
app, err := client.PostOAuth2ProviderApp(ctx, codersdk.PostOAuth2ProviderAppRequest{
Name: fmt.Sprintf("integration-test-%d", time.Now().UnixNano()%1000000),
CallbackURL: "http://localhost:3000",
})
require.NoError(t, err)
require.NotEmpty(t, app.ID)
require.NotEmpty(t, app.Name)
require.Equal(t, "http://localhost:3000", app.CallbackURL)
})
}
func TestOAuth2ProviderAppSecrets(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
ctx := testutil.Context(t, testutil.WaitLong)
// Make some apps.
apps := generateApps(ctx, t, client, "app-secrets")
t.Run("DeleteNonExisting", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
// Should not be able to create secrets for a non-existent app.
//nolint:gocritic // OAauth2 app management requires owner permission.
_, err := client.OAuth2ProviderAppSecrets(ctx, uuid.New())
require.Error(t, err)
// Should not be able to delete non-existing secrets when there is no app.
//nolint:gocritic // OAauth2 app management requires owner permission.
err = client.DeleteOAuth2ProviderAppSecret(ctx, uuid.New(), uuid.New())
require.Error(t, err)
// Should not be able to delete non-existing secrets when the app exists.
//nolint:gocritic // OAauth2 app management requires owner permission.
err = client.DeleteOAuth2ProviderAppSecret(ctx, apps.Default.ID, uuid.New())
require.Error(t, err)
// Should not be able to delete an existing secret with the wrong app ID.
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := client.PostOAuth2ProviderAppSecret(ctx, apps.NoPort.ID)
require.NoError(t, err)
//nolint:gocritic // OAauth2 app management requires owner permission.
err = client.DeleteOAuth2ProviderAppSecret(ctx, apps.Default.ID, secret.ID)
require.Error(t, err)
})
t.Run("OK", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
// No secrets yet.
//nolint:gocritic // OAauth2 app management requires owner permission.
secrets, err := client.OAuth2ProviderAppSecrets(ctx, apps.Default.ID)
require.NoError(t, err)
require.Len(t, secrets, 0)
// Should be able to create secrets.
for i := 0; i < 5; i++ {
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := client.PostOAuth2ProviderAppSecret(ctx, apps.Default.ID)
require.NoError(t, err)
require.NotEmpty(t, secret.ClientSecretFull)
require.True(t, len(secret.ClientSecretFull) > 6)
//nolint:gocritic // OAauth2 app management requires owner permission.
_, err = client.PostOAuth2ProviderAppSecret(ctx, apps.NoPort.ID)
require.NoError(t, err)
}
// Should get secrets now, but only for the one app.
//nolint:gocritic // OAauth2 app management requires owner permission.
secrets, err = client.OAuth2ProviderAppSecrets(ctx, apps.Default.ID)
require.NoError(t, err)
require.Len(t, secrets, 5)
for _, secret := range secrets {
require.Len(t, secret.ClientSecretTruncated, 6)
}
// Should be able to delete a secret.
//nolint:gocritic // OAauth2 app management requires owner permission.
err = client.DeleteOAuth2ProviderAppSecret(ctx, apps.Default.ID, secrets[0].ID)
require.NoError(t, err)
secrets, err = client.OAuth2ProviderAppSecrets(ctx, apps.Default.ID)
require.NoError(t, err)
require.Len(t, secrets, 4)
// No secrets once the app is deleted.
//nolint:gocritic // OAauth2 app management requires owner permission.
err = client.DeleteOAuth2ProviderApp(ctx, apps.Default.ID)
require.NoError(t, err)
//nolint:gocritic // OAauth2 app management requires owner permission.
_, err = client.OAuth2ProviderAppSecrets(ctx, apps.Default.ID)
require.Error(t, err)
})
t.Run("RejectsPublicClient", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
oauth2providertest.EnableDCR(t, client)
app := oauth2providertest.RegisterPublicClient(t, client, "app-secrets-public", "http://localhost:8080/callback")
appID, err := uuid.Parse(app.ClientID)
require.NoError(t, err)
//nolint:gocritic // OAuth2 app management requires owner permission.
_, err = client.PostOAuth2ProviderAppSecret(ctx, appID)
// Check the status and message, since a bare require.Error would also
// pass for a request that never reached the guard.
var sdkError *codersdk.Error
require.ErrorAsf(t, err, &sdkError, "error should be of type *codersdk.Error")
require.Equal(t, http.StatusBadRequest, sdkError.StatusCode())
require.Contains(t, sdkError.Message, "public OAuth2 app")
// No partial secret was created.
//nolint:gocritic // OAuth2 app management requires owner permission.
secrets, err := client.OAuth2ProviderAppSecrets(ctx, appID)
require.NoError(t, err)
require.Empty(t, secrets)
})
}
func TestOAuth2ProviderTokenExchange(t *testing.T) {
t.Parallel()
db, pubsub := dbtestutil.NewDB(t)
ownerClient := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
owner := coderdtest.CreateFirstUser(t, ownerClient)
ctx := testutil.Context(t, testutil.WaitLong)
apps := generateApps(ctx, t, ownerClient, "token-exchange")
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := ownerClient.PostOAuth2ProviderAppSecret(ctx, apps.Default.ID)
require.NoError(t, err)
// The typical oauth2 flow from this point is:
// Create an oauth2.Config using the id, secret, endpoints, and redirect:
// cfg := oauth2.Config{ ... }
// Display url for the user to click:
// userClickURL := cfg.AuthCodeURL("random_state")
// userClickURL looks like: https://idp url/authorize?
// client_id=...
// response_type=code
// redirect_uri=.. (back to backstage url) ..
// scope=...
// state=...
// *1* User clicks "Allow" on provided page above
// The redirect_uri is followed which sends back to backstage with the code and state
// Now backstage has the info to do a cfg.Exchange() in the back to get an access token.
//
// ---NOTE---: If the user has already approved this oauth app, then *1* is optional.
// Coder can just immediately redirect back to backstage without user intervention.
tests := []struct {
name string
app codersdk.OAuth2ProviderApp
// The flow is setup(ctx, client, user) -> preAuth(cfg) -> cfg.AuthCodeURL() -> preToken(cfg) -> cfg.Exchange()
setup func(context.Context, *codersdk.Client, codersdk.User) error
preAuth func(valid *oauth2.Config)
authError string
preToken func(valid *oauth2.Config)
tokenError string
// If null, assume the code should be valid.
defaultCode *string
// custom allows some more advanced manipulation of the oauth2 exchange.
exchangeMutate []oauth2.AuthCodeOption
}{
{
name: "AuthInParams",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
valid.Endpoint.AuthStyle = oauth2.AuthStyleInParams
},
},
{
name: "AuthInvalidAppID",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
valid.ClientID = uuid.NewString()
},
authError: "invalid_client",
},
{
name: "TokenInvalidAppID",
app: apps.Default,
preToken: func(valid *oauth2.Config) {
valid.ClientID = uuid.NewString()
},
tokenError: "invalid_client",
},
{
name: "InvalidPort",
app: apps.NoPort,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Host = newURL.Hostname() + ":8081"
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "WrongAppHost",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
valid.RedirectURL = apps.NoPort.CallbackURL
},
authError: "Invalid query params:",
},
{
name: "InvalidHostPrefix",
app: apps.NoPort,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Host = "prefix" + newURL.Hostname()
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "InvalidHost",
app: apps.NoPort,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Host = "invalid"
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "InvalidHostAndPort",
app: apps.NoPort,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Host = "invalid:8080"
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "InvalidPath",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Path = path.Join("/prepend", newURL.Path)
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "MissingPath",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Path = "/"
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "DifferentProtocol",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Scheme = "https"
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "NestedPath",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Path = path.Join(newURL.Path, "nested")
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
// Some oauth implementations allow this, but our users can host
// at subdomains. So we should not.
name: "Subdomain",
app: apps.Default,
preAuth: func(valid *oauth2.Config) {
newURL := must(url.Parse(valid.RedirectURL))
newURL.Host = "sub." + newURL.Host
valid.RedirectURL = newURL.String()
},
authError: "Invalid query params:",
},
{
name: "NoSecretScheme",
app: apps.Default,
preToken: func(valid *oauth2.Config) {
valid.ClientSecret = "1234_4321"
},
tokenError: "The client credentials are invalid",
},
{
name: "InvalidSecretScheme",
app: apps.Default,
preToken: func(valid *oauth2.Config) {
valid.ClientSecret = "notcoder_1234_4321"
},
tokenError: "The client credentials are invalid",
},
{
name: "MissingSecretSecret",
app: apps.Default,
preToken: func(valid *oauth2.Config) {
valid.ClientSecret = "coder_1234"
},
tokenError: "The client credentials are invalid",
},
{
name: "MissingSecretPrefix",
app: apps.Default,
preToken: func(valid *oauth2.Config) {
valid.ClientSecret = "coder__1234"
},
tokenError: "The client credentials are invalid",
},
{
name: "InvalidSecretPrefix",
app: apps.Default,
preToken: func(valid *oauth2.Config) {
valid.ClientSecret = "coder_1234_4321"
},
tokenError: "The client credentials are invalid",
},
{
name: "MissingSecret",
app: apps.Default,
preToken: func(valid *oauth2.Config) {
valid.ClientSecret = ""
},
tokenError: "invalid_request",
},
{
name: "NoCodeScheme",
app: apps.Default,
defaultCode: new("1234_4321"),
tokenError: "The authorization code is invalid or expired",
},
{
name: "InvalidCodeScheme",
app: apps.Default,
defaultCode: new("notcoder_1234_4321"),
tokenError: "The authorization code is invalid or expired",
},
{
name: "MissingCodeSecret",
app: apps.Default,
defaultCode: new("coder_1234"),
tokenError: "The authorization code is invalid or expired",
},
{
name: "MissingCodePrefix",
app: apps.Default,
defaultCode: new("coder__1234"),
tokenError: "The authorization code is invalid or expired",
},
{
name: "InvalidCodePrefix",
app: apps.Default,
defaultCode: new("coder_1234_4321"),
tokenError: "The authorization code is invalid or expired",
},
{
name: "MissingCode",
app: apps.Default,
defaultCode: new(""),
tokenError: "invalid_request",
},
{
name: "InvalidGrantType",
app: apps.Default,
tokenError: "unsupported_grant_type",
exchangeMutate: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("grant_type", "foobar"),
},
},
{
name: "EmptyGrantType",
app: apps.Default,
tokenError: "unsupported_grant_type",
exchangeMutate: []oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("grant_type", ""),
},
},
{
name: "ExpiredCode",
app: apps.Default,
defaultCode: new("coder_prefix_code"),
tokenError: "The authorization code is invalid or expired",
setup: func(ctx context.Context, client *codersdk.Client, user codersdk.User) error {
// Insert an expired code.
hashedCode, err := userpassword.Hash("prefix_code")
if err != nil {
return err
}
_, err = db.InsertOAuth2ProviderAppCode(ctx, database.InsertOAuth2ProviderAppCodeParams{
ID: uuid.New(),
CreatedAt: dbtime.Now().Add(-time.Minute * 11),
ExpiresAt: dbtime.Now().Add(-time.Minute),
SecretPrefix: []byte("prefix"),
HashedSecret: []byte(hashedCode),
AppID: apps.Default.ID,
UserID: user.ID,
Scope: string(database.ApiKeyScopeCoderAll),
})
return err
},
},
{
// secret belongs to apps.Default (see the shared "secret" above),
// but this app's client_id is apps.NoPort. The token endpoint
// must reject a secret that belongs to a different app than the
// one identified by client_id, rather than trusting client_id
// alone to attribute the resulting token.
name: "SecretBelongsToDifferentApp",
app: apps.NoPort,
tokenError: "The client credentials are invalid",
},
{
name: "OK",
app: apps.Default,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
// Each test gets its own user, since we allow only one code per user and
// app at a time and running tests in parallel could clobber each other.
userClient, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
if test.setup != nil {
err := test.setup(ctx, userClient, user)
require.NoError(t, err)
}
// Each test gets its own oauth2.Config so they can run in parallel.
// In practice, you would only use 1 as a singleton.
valid := &oauth2.Config{
ClientID: test.app.ID.String(),
ClientSecret: secret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: test.app.Endpoints.Authorization,
DeviceAuthURL: test.app.Endpoints.DeviceAuth,
TokenURL: test.app.Endpoints.Token,
// TODO: @emyrk we should support both types.
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: test.app.CallbackURL,
Scopes: []string{},
}
if test.preAuth != nil {
test.preAuth(valid)
}
var code string
var verifier string
if test.defaultCode != nil {
code = *test.defaultCode
// These subtests exercise malformed/expired code_
// handling; the code lookup fails before code_verifier is
// ever compared, but it still has to satisfy RFC 7636
// §4.1's format floor to reach that point.
verifier = strings.Repeat("a", 43)
} else {
var err error
code, verifier, err = authorizationFlow(ctx, userClient, valid)
if test.authError != "" {
require.Error(t, err)
require.ErrorContains(t, err, test.authError)
// If this errors the token exchange will fail. So end here.
return
}
require.NoError(t, err)
}
// Mutate the valid config for the exchange.
if test.preToken != nil {
test.preToken(valid)
}
// Do the actual exchange. Include PKCE code_verifier when
// we obtained a code through the authorization flow.
exchangeOpts := append([]oauth2.AuthCodeOption{
oauth2.SetAuthURLParam("code_verifier", verifier),
}, test.exchangeMutate...)
token, err := valid.Exchange(ctx, code, exchangeOpts...)
if test.tokenError != "" {
require.Error(t, err)
require.ErrorContains(t, err, test.tokenError)
} else {
require.NoError(t, err)
require.NotEmpty(t, token.AccessToken)
require.True(t, dbtime.Now().Before(token.Expiry))
// Check that the token works.
newClient := codersdk.New(userClient.URL)
newClient.SetSessionToken(token.AccessToken)
gotUser, err := newClient.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, user.ID, gotUser.ID)
}
})
}
}
// TestOAuth2ProviderTokenExchangeCodeBelongsToDifferentApp covers
// authorizationCodeGrant's code-ownership check in isolation. The token
// endpoint validates redirect_uri against the app resolved from client_id
// (before the grant runs at all) and separately against the redirect_uri
// recorded on the code itself (inside the grant). Both must pass for the
// request to reach the code-ownership check, which only happens when the
// app identified by client_id and the app that originally issued the code
// happen to share the exact same callback URL, which is plausible for
// native clients that commonly register a conventional localhost
// redirect. Two apps with distinct callbacks (as in the table above) can
// never reach this check via a redirect_uri mismatch; this test
// constructs the one scenario that does.
func TestOAuth2ProviderTokenExchangeCodeBelongsToDifferentApp(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, nil)
owner := coderdtest.CreateFirstUser(t, ownerClient)
ctx := testutil.Context(t, testutil.WaitLong)
const sharedCallback = "http://localhost1:8080/foo/bar"
createApp := func(name string) (codersdk.OAuth2ProviderApp, codersdk.OAuth2ProviderAppSecretFull) {
//nolint:gocritic // OAauth2 app management requires owner permission.
app, err := ownerClient.PostOAuth2ProviderApp(ctx, codersdk.PostOAuth2ProviderAppRequest{
Name: fmt.Sprintf("%s-%d", name, time.Now().UnixNano()),
CallbackURL: sharedCallback,
})
require.NoError(t, err)
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := ownerClient.PostOAuth2ProviderAppSecret(ctx, app.ID)
require.NoError(t, err)
return app, secret
}
appA, _ := createApp("code-owner")
appB, secretB := createApp("code-thief")
userClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
cfgA := &oauth2.Config{
ClientID: appA.ID.String(),
Endpoint: oauth2.Endpoint{
AuthURL: appA.Endpoints.Authorization,
TokenURL: appA.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: sharedCallback,
Scopes: []string{},
}
code, verifier, err := authorizationFlow(ctx, userClient, cfgA)
require.NoError(t, err)
// Exchange the code issued for appA, but presenting appB's client_id
// and appB's own valid secret. redirect_uri is identical for both
// apps, so both the request-level check (against the app resolved
// from client_id) and the grant's own check (against the code's
// recorded redirect_uri) pass, isolating the code-ownership check.
cfgB := &oauth2.Config{
ClientID: appB.ID.String(),
ClientSecret: secretB.ClientSecretFull,
Endpoint: oauth2.Endpoint{
TokenURL: appB.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: sharedCallback,
Scopes: []string{},
}
_, err = cfgB.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", verifier))
require.Error(t, err)
require.ErrorContains(t, err, "The authorization code is invalid or expired")
}
func TestOAuth2ProviderPublicClientTokenExchange(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, nil)
owner := coderdtest.CreateFirstUser(t, ownerClient)
oauth2providertest.EnableDCR(t, ownerClient)
ctx := testutil.Context(t, testutil.WaitLong)
// Neither app has a secret, so code ownership and PKCE are all that bind an
// exchange. A shared redirect URI is the common case for native apps.
const sharedCallback = "http://localhost:8080/callback"
appA := oauth2providertest.RegisterPublicClient(t, ownerClient, "public-code-owner", sharedCallback)
appB := oauth2providertest.RegisterPublicClient(t, ownerClient, "public-code-thief", sharedCallback)
userClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
authURL := ownerClient.URL.JoinPath("/oauth2/authorize").String()
tokenURL := ownerClient.URL.JoinPath("/oauth2/tokens").String()
cfgA := &oauth2.Config{
ClientID: appA.ClientID,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: sharedCallback,
Scopes: []string{},
}
code, verifier, err := authorizationFlow(ctx, userClient, cfgA)
require.NoError(t, err)
// Redeem appA's code under appB's client_id: everything except the code's
// own app_id lines up.
cfgB := &oauth2.Config{
ClientID: appB.ClientID,
Endpoint: oauth2.Endpoint{
TokenURL: tokenURL,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: sharedCallback,
Scopes: []string{},
}
_, err = cfgB.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", verifier))
require.Error(t, err)
require.ErrorContains(t, err, "The authorization code is invalid or expired")
// An under-length verifier fails the format check before the grant runs, so
// it does not consume the code (RFC 6749 §10.5).
_, err = cfgA.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", "a"))
require.Error(t, err)
require.ErrorContains(t, err, "code_verifier")
// A well-formed verifier reaches the PKCE comparison, which does consume the
// code: otherwise a leaked code could be replayed with unlimited guesses.
wrongVerifier, _ := oauth2providertest.GeneratePKCE(t)
_, err = cfgA.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", wrongVerifier))
require.Error(t, err)
require.ErrorContains(t, err, "The PKCE code verifier is invalid")
// Consumed above, so even the matching verifier can no longer redeem it.
_, err = cfgA.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", verifier))
require.Error(t, err)
require.ErrorContains(t, err, "The authorization code is invalid or expired")
}
func TestOAuth2ProviderTokenRefresh(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, pubsub := dbtestutil.NewDB(t)
ownerClient := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
owner := coderdtest.CreateFirstUser(t, ownerClient)
apps := generateApps(ctx, t, ownerClient, "token-refresh")
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := ownerClient.PostOAuth2ProviderAppSecret(ctx, apps.Default.ID)
require.NoError(t, err)
// One path not tested here is when the token is empty, because Go's OAuth2
// client library will not even try to make the request.
tests := []struct {
name string
app codersdk.OAuth2ProviderApp
// refreshAsApp, if set, performs the refresh request under this
// app's client_id/endpoints instead of app, while the token itself
// still belongs to app. Used to test that refreshing a token under
// a different app's client_id is rejected outright, rather than
// silently re-parenting the token to the presented client_id.
refreshAsApp *codersdk.OAuth2ProviderApp
// If null, assume the token should be valid.
defaultToken *string
error string
expires time.Time
}{
{
name: "NoTokenScheme",
app: apps.Default,
defaultToken: new("1234_4321"),
error: "The refresh token is invalid or expired",
},
{
name: "InvalidTokenScheme",
app: apps.Default,
defaultToken: new("notcoder_1234_4321"),
error: "The refresh token is invalid or expired",
},
{
name: "MissingTokenSecret",
app: apps.Default,
defaultToken: new("coder_1234"),
error: "The refresh token is invalid or expired",
},
{
name: "MissingTokenPrefix",
app: apps.Default,
defaultToken: new("coder__1234"),
error: "The refresh token is invalid or expired",
},
{
name: "InvalidTokenPrefix",
app: apps.Default,
defaultToken: new("coder_1234_4321"),
error: "The refresh token is invalid or expired",
},
{
name: "Expired",
app: apps.Default,
expires: time.Now().Add(time.Minute * -1),
error: "The refresh token is invalid or expired",
},
{
// The token belongs to apps.Default, but the refresh request
// presents apps.NoPort's client_id. This must be rejected
// outright: silently accepting it (and re-parenting the
// token's app_id to whatever client_id is presented) would let
// a stolen refresh token be laundered to a different app,
// after which the issuing app could no longer revoke it.
name: "WrongApp",
app: apps.Default,
refreshAsApp: &apps.NoPort,
error: "The refresh token is invalid or expired",
},
{
name: "OK",
app: apps.Default,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
userClient, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
// Insert the token and its key.
key, sessionToken, err := apikey.Generate(apikey.CreateParams{
UserID: user.ID,
LoginType: database.LoginTypeOAuth2ProviderApp,
ExpiresAt: time.Now().Add(time.Hour * 10),
})
require.NoError(t, err)
newKey, err := db.InsertAPIKey(ctx, key)
require.NoError(t, err)
token, err := oauth2provider.GenerateSecret()
require.NoError(t, err)
expires := test.expires
if expires.IsZero() {
expires = time.Now().Add(time.Hour * 10)
}
_, err = db.InsertOAuth2ProviderAppToken(ctx, database.InsertOAuth2ProviderAppTokenParams{
ID: uuid.New(),
CreatedAt: dbtime.Now(),
ExpiresAt: expires,
HashPrefix: []byte(token.Prefix),
RefreshHash: token.Hashed,
AppID: test.app.ID,
AppSecretID: uuid.NullUUID{UUID: secret.ID, Valid: true},
APIKeyID: newKey.ID,
UserID: user.ID,
Scope: string(database.ApiKeyScopeCoderAll),
})
require.NoError(t, err)
// Check that the key works.
newClient := codersdk.New(userClient.URL)
newClient.SetSessionToken(sessionToken)
gotUser, err := newClient.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, user.ID, gotUser.ID)
refreshAsApp := test.app
if test.refreshAsApp != nil {
refreshAsApp = *test.refreshAsApp
}
cfg := &oauth2.Config{
ClientID: refreshAsApp.ID.String(),
ClientSecret: secret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: refreshAsApp.Endpoints.Authorization,
DeviceAuthURL: refreshAsApp.Endpoints.DeviceAuth,
TokenURL: refreshAsApp.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: refreshAsApp.CallbackURL,
Scopes: []string{},
}
// Test whether it can be refreshed.
refreshToken := token.Formatted
if test.defaultToken != nil {
refreshToken = *test.defaultToken
}
refreshed, err := cfg.TokenSource(ctx, &oauth2.Token{
AccessToken: sessionToken,
RefreshToken: refreshToken,
Expiry: time.Now().Add(time.Minute * -1),
}).Token()
if test.error != "" {
require.Error(t, err)
require.ErrorContains(t, err, test.error)
} else {
require.NoError(t, err)
require.NotEmpty(t, refreshed.AccessToken)
// Old token is now invalid.
_, err = newClient.User(ctx, codersdk.Me)
require.Error(t, err)
require.ErrorContains(t, err, "401")
// Refresh token is valid.
newClient := codersdk.New(userClient.URL)
newClient.SetSessionToken(refreshed.AccessToken)
gotUser, err := newClient.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, user.ID, gotUser.ID)
}
})
}
}
type exchangeSetup struct {
cfg *oauth2.Config
app codersdk.OAuth2ProviderApp
secret codersdk.OAuth2ProviderAppSecretFull
code string
verifier string
}
func TestOAuth2ProviderRevoke(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
owner := coderdtest.CreateFirstUser(t, client)
tests := []struct {
name string
// fn performs some action that removes the user's code and token.
fn func(context.Context, *codersdk.Client, exchangeSetup)
// replacesToken specifies whether the action replaces the token or only
// deletes it.
replacesToken bool
}{
{
name: "DeleteApp",
fn: func(ctx context.Context, _ *codersdk.Client, s exchangeSetup) {
//nolint:gocritic // OAauth2 app management requires owner permission.
err := client.DeleteOAuth2ProviderApp(ctx, s.app.ID)
require.NoError(t, err)
},
},
{
name: "DeleteSecret",
fn: func(ctx context.Context, _ *codersdk.Client, s exchangeSetup) {
//nolint:gocritic // OAauth2 app management requires owner permission.
err := client.DeleteOAuth2ProviderAppSecret(ctx, s.app.ID, s.secret.ID)
require.NoError(t, err)
},
},
{
name: "DeleteApp",
fn: func(ctx context.Context, client *codersdk.Client, s exchangeSetup) {
err := client.RevokeOAuth2ProviderApp(ctx, s.app.ID)
require.NoError(t, err)
},
},
{
name: "OverrideCodeAndToken",
fn: func(ctx context.Context, client *codersdk.Client, s exchangeSetup) {
// Generating a new code should wipe out the old code.
code, verifier, err := authorizationFlow(ctx, client, s.cfg)
require.NoError(t, err)
// Generating a new token should wipe out the old token.
_, err = s.cfg.Exchange(ctx, code,
oauth2.SetAuthURLParam("code_verifier", verifier),
)
require.NoError(t, err)
},
replacesToken: true,
},
}
setup := func(ctx context.Context, testClient *codersdk.Client, name string) exchangeSetup {
// We need a new app each time because we only allow one code and token per
// app and user at the moment and because the test might delete the app.
//nolint:gocritic // OAauth2 app management requires owner permission.
app, err := client.PostOAuth2ProviderApp(ctx, codersdk.PostOAuth2ProviderAppRequest{
Name: name,
CallbackURL: "http://localhost",
})
require.NoError(t, err)
// We need a new secret every time because the test might delete the secret.
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := client.PostOAuth2ProviderAppSecret(ctx, app.ID)
require.NoError(t, err)
cfg := &oauth2.Config{
ClientID: app.ID.String(),
ClientSecret: secret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: app.Endpoints.Authorization,
DeviceAuthURL: app.Endpoints.DeviceAuth,
TokenURL: app.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: app.CallbackURL,
Scopes: []string{},
}
// Go through the auth flow to get a code.
code, verifier, err := authorizationFlow(ctx, testClient, cfg)
require.NoError(t, err)
return exchangeSetup{
cfg: cfg,
app: app,
secret: secret,
code: code,
verifier: verifier,
}
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
testClient, testUser := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
testEntities := setup(ctx, testClient, test.name+"-1")
// Delete before the exchange completes (code should delete and attempting
// to finish the exchange should fail).
test.fn(ctx, testClient, testEntities)
// Exchange should fail because the code should be gone.
_, err := testEntities.cfg.Exchange(ctx, testEntities.code,
oauth2.SetAuthURLParam("code_verifier", testEntities.verifier),
)
require.Error(t, err)
// Try again, this time letting the exchange complete first.
testEntities = setup(ctx, testClient, test.name+"-2")
token, err := testEntities.cfg.Exchange(ctx, testEntities.code,
oauth2.SetAuthURLParam("code_verifier", testEntities.verifier),
)
require.NoError(t, err)
// Validate the returned access token and that the app is listed.
newClient := codersdk.New(client.URL)
newClient.SetSessionToken(token.AccessToken)
gotUser, err := newClient.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, testUser.ID, gotUser.ID)
filter := codersdk.OAuth2ProviderAppFilter{UserID: testUser.ID}
apps, err := testClient.OAuth2ProviderApps(ctx, filter)
require.NoError(t, err)
require.Contains(t, apps, testEntities.app)
// Should not show up for another user.
apps, err = client.OAuth2ProviderApps(ctx, codersdk.OAuth2ProviderAppFilter{UserID: owner.UserID})
require.NoError(t, err)
require.Len(t, apps, 0)
// Perform the deletion.
test.fn(ctx, testClient, testEntities)
// App should no longer show up for the user unless it was replaced.
if !test.replacesToken {
apps, err = testClient.OAuth2ProviderApps(ctx, filter)
require.NoError(t, err)
require.NotContains(t, apps, testEntities.app, fmt.Sprintf("contains %q", testEntities.app.Name))
}
// The token should no longer be valid.
_, err = newClient.User(ctx, codersdk.Me)
require.Error(t, err)
require.ErrorContains(t, err, "401")
})
}
}
// TestOAuth2ProviderRevokeCrossApp covers RFC 7009 revocation's ownership
// check, which compares a token's app_id directly rather than joining
// through app_secret_id. That rewrite had zero test coverage on its
// unequal branch: revoking a token while presenting a different app's
// client_id than the one that issued it must be rejected (masked as a
// success per RFC 7009, since revocation must not reveal whether a token
// exists), and must leave the token's session intact. Revoking under the
// correct, issuing app must still work.
func TestOAuth2ProviderRevokeCrossApp(t *testing.T) {
t.Parallel()
ownerClient := coderdtest.New(t, nil)
owner := coderdtest.CreateFirstUser(t, ownerClient)
ctx := testutil.Context(t, testutil.WaitLong)
apps := generateApps(ctx, t, ownerClient, "revoke-cross-app")
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := ownerClient.PostOAuth2ProviderAppSecret(ctx, apps.Default.ID)
require.NoError(t, err)
tests := []struct {
name string
// tokenFor extracts the token under test from a successful exchange,
// covering both the refresh-token (revokeRefreshTokenInTx) and
// access-token (revokeAPIKeyInTx) revocation branches.
tokenFor func(*oauth2.Token) string
}{
{
name: "AccessToken",
tokenFor: func(tok *oauth2.Token) string { return tok.AccessToken },
},
{
name: "RefreshToken",
tokenFor: func(tok *oauth2.Token) string { return tok.RefreshToken },
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
userClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
cfg := &oauth2.Config{
ClientID: apps.Default.ID.String(),
ClientSecret: secret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: apps.Default.Endpoints.Authorization,
DeviceAuthURL: apps.Default.Endpoints.DeviceAuth,
TokenURL: apps.Default.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: apps.Default.CallbackURL,
Scopes: []string{},
}
code, verifier, err := authorizationFlow(ctx, userClient, cfg)
require.NoError(t, err)
token, err := cfg.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", verifier))
require.NoError(t, err)
sessionWorks := func() bool {
checkClient := codersdk.New(userClient.URL)
checkClient.SetSessionToken(token.AccessToken)
_, err := checkClient.User(ctx, codersdk.Me)
return err == nil
}
require.True(t, sessionWorks(), "session should be valid before any revoke attempt")
tokenUnderTest := test.tokenFor(token)
// RFC 7009: revoking under a different app than the one that
// issued the token must not reveal whether it exists (no
// error), and must not actually end the session.
err = userClient.RevokeOAuth2Token(ctx, apps.NoPort.ID, tokenUnderTest)
require.NoError(t, err, "cross-app revoke must appear to succeed per RFC 7009")
require.True(t, sessionWorks(), "cross-app revoke must not actually end the session")
// Revoking under the correct, issuing app must actually work.
err = userClient.RevokeOAuth2Token(ctx, apps.Default.ID, tokenUnderTest)
require.NoError(t, err)
require.False(t, sessionWorks(), "same-app revoke must end the session")
})
}
}
func TestOAuth2ProviderPublicClientTokenLifecycle(t *testing.T) {
t.Parallel()
tests := []struct {
name string
// tokenFor covers both revokeRefreshTokenInTx and revokeAPIKeyInTx.
tokenFor func(*oauth2.Token) string
}{
{
name: "AccessToken",
tokenFor: func(tok *oauth2.Token) string { return tok.AccessToken },
},
{
name: "RefreshToken",
tokenFor: func(tok *oauth2.Token) string { return tok.RefreshToken },
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
session := refreshedPublicClientSession(ctx, t)
tokenUnderTest := test.tokenFor(session.token)
err := session.userClient.RevokeOAuth2Token(ctx, session.otherAppID, tokenUnderTest)
require.NoError(t, err, "cross-app revoke must appear to succeed per RFC 7009")
require.True(t, session.works(), "cross-app revoke must not end the session")
err = session.userClient.RevokeOAuth2Token(ctx, session.appID, tokenUnderTest)
require.NoError(t, err)
require.False(t, session.works(), "public client must be able to revoke its own token")
})
}
}
// publicClientSession is a refreshed public-client token with the app that
// issued it and an unrelated public app.
type publicClientSession struct {
token *oauth2.Token
appID uuid.UUID
otherAppID uuid.UUID
userClient *codersdk.Client
// works reports whether token.AccessToken still authenticates a request.
works func() bool
}
// refreshedPublicClientSession registers two public clients and runs one through
// the code exchange and a refresh, asserting each minted row is secretless.
func refreshedPublicClientSession(ctx context.Context, t *testing.T) publicClientSession {
t.Helper()
db, pubsub := dbtestutil.NewDB(t)
ownerClient := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
owner := coderdtest.CreateFirstUser(t, ownerClient)
oauth2providertest.EnableDCR(t, ownerClient)
const callback = "http://localhost:8080/callback"
app := oauth2providertest.RegisterPublicClient(t, ownerClient, "public-lifecycle", callback)
otherApp := oauth2providertest.RegisterPublicClient(t, ownerClient, "public-lifecycle-other", callback)
appID, err := uuid.Parse(app.ClientID)
require.NoError(t, err)
otherAppID, err := uuid.Parse(otherApp.ClientID)
require.NoError(t, err)
userClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
cfg := &oauth2.Config{
ClientID: app.ClientID,
Endpoint: oauth2.Endpoint{
AuthURL: ownerClient.URL.JoinPath("/oauth2/authorize").String(),
TokenURL: ownerClient.URL.JoinPath("/oauth2/tokens").String(),
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: callback,
Scopes: []string{},
}
code, verifier, err := authorizationFlow(ctx, userClient, cfg)
require.NoError(t, err)
token, err := cfg.Exchange(ctx, code, oauth2.SetAuthURLParam("code_verifier", verifier))
require.NoError(t, err)
require.NotEmpty(t, token.RefreshToken)
// Locates the row by key ID alone, so it says nothing about whether the
// token authenticates; the works closure is what proves that.
assertSecretlessToken := func(accessToken string) {
t.Helper()
keyID, _, err := httpmw.SplitAPIToken(accessToken)
require.NoError(t, err)
// Raw store handle, not the dbauthz-wrapped one, so no system actor.
dbToken, err := db.GetOAuth2ProviderAppTokenByAPIKeyID(ctx, keyID)
require.NoError(t, err)
require.False(t, dbToken.AppSecretID.Valid, "public client token must have a NULL app_secret_id")
require.Equal(t, appID, dbToken.AppID)
}
assertSecretlessToken(token.AccessToken)
// Refresh carries AppSecretID forward, so the refreshed row must still be
// secretless.
refreshCfg := *cfg
refreshed, err := refreshCfg.TokenSource(ctx, &oauth2.Token{
RefreshToken: token.RefreshToken,
Expiry: time.Now().Add(-time.Hour),
}).Token()
require.NoError(t, err)
require.NotEmpty(t, refreshed.AccessToken)
assertSecretlessToken(refreshed.AccessToken)
works := func() bool {
checkClient := codersdk.New(userClient.URL)
checkClient.SetSessionToken(refreshed.AccessToken)
_, err := checkClient.User(ctx, codersdk.Me)
return err == nil
}
require.True(t, works(), "refreshed public-client session should be valid")
return publicClientSession{
token: refreshed,
appID: appID,
otherAppID: otherAppID,
userClient: userClient,
works: works,
}
}
type provisionedApps struct {
Default codersdk.OAuth2ProviderApp
NoPort codersdk.OAuth2ProviderApp
Subdomain codersdk.OAuth2ProviderApp
// For sorting purposes these are included. You will likely never touch them.
Extra []codersdk.OAuth2ProviderApp
}
func generateApps(ctx context.Context, t *testing.T, client *codersdk.Client, suffix string) provisionedApps {
create := func(name, callback string) codersdk.OAuth2ProviderApp {
name = fmt.Sprintf("%s-%s", name, suffix)
//nolint:gocritic // OAauth2 app management requires owner permission.
app, err := client.PostOAuth2ProviderApp(ctx, codersdk.PostOAuth2ProviderAppRequest{
Name: name,
CallbackURL: callback,
Icon: "",
})
require.NoError(t, err)
require.Equal(t, name, app.Name)
require.Equal(t, callback, app.CallbackURL)
return app
}
return provisionedApps{
Default: create("app-a", "http://localhost1:8080/foo/bar"),
NoPort: create("app-b", "http://localhost2"),
Subdomain: create("app-z", "http://30.localhost:3000"),
Extra: []codersdk.OAuth2ProviderApp{
create("app-x", "http://20.localhost:3000"),
create("app-y", "http://10.localhost:3000"),
},
}
}
// generatePKCE creates a PKCE verifier and S256 challenge for testing.
func generatePKCE() (verifier, challenge string) {
verifier = uuid.NewString() + uuid.NewString()
h := sha256.Sum256([]byte(verifier))
challenge = base64.RawURLEncoding.EncodeToString(h[:])
return verifier, challenge
}
func authorizationFlow(ctx context.Context, client *codersdk.Client, cfg *oauth2.Config) (code, codeVerifier string, err error) {
state := uuid.NewString()
codeVerifier, challenge := generatePKCE()
authURL := cfg.AuthCodeURL(state,
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
// Make a POST request to simulate clicking "Allow" on the authorization page.
// This bypasses the HTML consent page and directly processes the authorization.
code, err = oidctest.OAuth2GetCode(
authURL,
func(req *http.Request) (*http.Response, error) {
// Change to POST to simulate the form submission.
req.Method = http.MethodPost
// Prevent automatic redirect following.
client.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return client.Request(ctx, req.Method, req.URL.String(), nil)
},
)
return code, codeVerifier, err
}
func must[T any](value T, err error) T {
if err != nil {
panic(err)
}
return value
}
// TestOAuth2ProviderResourceIndicators tests RFC 8707 Resource Indicators support
// including resource parameter validation in authorization and token exchange flows.
func TestOAuth2ProviderResourceIndicators(t *testing.T) {
t.Parallel()
db, pubsub := dbtestutil.NewDB(t)
ownerClient := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
owner := coderdtest.CreateFirstUser(t, ownerClient)
ctx := testutil.Context(t, testutil.WaitLong)
apps := generateApps(ctx, t, ownerClient, "resource-indicators")
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := ownerClient.PostOAuth2ProviderAppSecret(ctx, apps.Default.ID)
require.NoError(t, err)
resource := ownerClient.URL.String()
tests := []struct {
name string
authResource string // Resource parameter during authorization
tokenResource string // Resource parameter during token exchange
refreshResource string // Resource parameter during refresh
expectAuthError bool
expectTokenError bool
expectRefreshError bool
}{
{
name: "NoResourceParameter",
// Standard flow without resource parameter
},
{
name: "ValidResourceParameter",
authResource: resource,
tokenResource: resource,
refreshResource: resource,
},
{
name: "ResourceInAuthOnly",
authResource: resource,
tokenResource: "", // Missing in token exchange
expectTokenError: true,
},
{
name: "ResourceInTokenOnly",
authResource: "", // Missing in auth
tokenResource: resource,
expectTokenError: true,
},
{
name: "ResourceMismatch",
authResource: "https://resource1.example.com",
tokenResource: "https://resource2.example.com", // Different resource
expectTokenError: true,
},
{
name: "RefreshWithDifferentResource",
authResource: resource,
tokenResource: resource,
refreshResource: "https://different.example.com", // Different in refresh
expectRefreshError: true,
},
{
name: "RefreshWithoutResource",
authResource: resource,
tokenResource: resource,
refreshResource: "", // No resource in refresh (allowed)
},
{
name: "RefreshWithSameResource",
authResource: resource,
tokenResource: resource,
refreshResource: resource, // Same resource in refresh
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
userClient, user := coderdtest.CreateAnotherUser(t, ownerClient, owner.OrganizationID)
cfg := &oauth2.Config{
ClientID: apps.Default.ID.String(),
ClientSecret: secret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: apps.Default.Endpoints.Authorization,
TokenURL: apps.Default.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: apps.Default.CallbackURL,
Scopes: []string{},
}
// Step 1: Authorization with resource parameter and PKCE.
state := uuid.NewString()
verifier, challenge := generatePKCE()
authURL := cfg.AuthCodeURL(state,
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
if test.authResource != "" {
// Add resource parameter to auth URL.
parsedURL, err := url.Parse(authURL)
require.NoError(t, err)
query := parsedURL.Query()
query.Set("resource", test.authResource)
parsedURL.RawQuery = query.Encode()
authURL = parsedURL.String()
}
// Simulate authorization flow
code, err := oidctest.OAuth2GetCode(
authURL,
func(req *http.Request) (*http.Response, error) {
req.Method = http.MethodPost
userClient.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return userClient.Request(ctx, req.Method, req.URL.String(), nil)
},
)
if test.expectAuthError {
require.Error(t, err)
return
}
require.NoError(t, err)
// Step 2: Token exchange with resource parameter
// Use custom token exchange since golang.org/x/oauth2 doesn't support resource parameter in token requests
token, err := customTokenExchange(ctx, ownerClient.URL.String(), apps.Default.ID.String(), secret.ClientSecretFull, code, apps.Default.CallbackURL, test.tokenResource, verifier)
if test.expectTokenError {
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_target")
return
}
require.NoError(t, err)
require.NotEmpty(t, token.AccessToken)
// Per RFC 8707, audience is stored in database but not returned in token response
// The audience validation happens server-side during API requests
// Step 3: Test API access with token audience validation
newClient := codersdk.New(userClient.URL)
newClient.SetSessionToken(token.AccessToken)
// Token should work for API access
gotUser, err := newClient.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, user.ID, gotUser.ID)
// Step 4: Test refresh token flow with resource parameter
if token.RefreshToken != "" {
// Note: OAuth2 library doesn't easily support custom parameters in refresh flows
// For now, we test basic refresh functionality without resource parameter
// TODO: Implement custom refresh flow testing with resource parameter
// Create a token source with refresh capability
tokenSource := cfg.TokenSource(ctx, &oauth2.Token{
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
Expiry: time.Now().Add(-time.Minute), // Force refresh
})
// Test token refresh
refreshedToken, err := tokenSource.Token()
require.NoError(t, err)
require.NotEmpty(t, refreshedToken.AccessToken)
// Old token should be invalid
_, err = newClient.User(ctx, codersdk.Me)
require.Error(t, err)
// New token should work
newClient.SetSessionToken(refreshedToken.AccessToken)
gotUser, err = newClient.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, user.ID, gotUser.ID)
}
})
}
}
// TestOAuth2ProviderCrossResourceAudienceValidation tests that tokens are properly
// validated against the audience/resource server they were issued for.
func TestOAuth2ProviderCrossResourceAudienceValidation(t *testing.T) {
t.Parallel()
db, pubsub := dbtestutil.NewDB(t)
// Set up first Coder instance (resource server 1)
server1 := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
owner := coderdtest.CreateFirstUser(t, server1)
// Set up second Coder instance (resource server 2) - simulate different host
server2 := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
})
ctx := testutil.Context(t, testutil.WaitLong)
// Create OAuth2 app
apps := generateApps(ctx, t, server1, "cross-resource")
//nolint:gocritic // OAauth2 app management requires owner permission.
secret, err := server1.PostOAuth2ProviderAppSecret(ctx, apps.Default.ID)
require.NoError(t, err)
userClient, user := coderdtest.CreateAnotherUser(t, server1, owner.OrganizationID)
// Get token with specific audience for server1
resource1 := server1.URL.String()
cfg := &oauth2.Config{
ClientID: apps.Default.ID.String(),
ClientSecret: secret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: apps.Default.Endpoints.Authorization,
TokenURL: apps.Default.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: apps.Default.CallbackURL,
Scopes: []string{},
}
// Authorization with resource parameter for server1 and PKCE.
state := uuid.NewString()
verifier, challenge := generatePKCE()
authURL := cfg.AuthCodeURL(state,
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
parsedURL, err := url.Parse(authURL)
require.NoError(t, err)
query := parsedURL.Query()
query.Set("resource", resource1)
parsedURL.RawQuery = query.Encode()
authURL = parsedURL.String()
code, err := oidctest.OAuth2GetCode(
authURL,
func(req *http.Request) (*http.Response, error) {
req.Method = http.MethodPost
userClient.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return userClient.Request(ctx, req.Method, req.URL.String(), nil)
},
)
require.NoError(t, err)
// Exchange code for token with resource parameter and PKCE verifier.
token, err := cfg.Exchange(ctx, code,
oauth2.SetAuthURLParam("resource", resource1),
oauth2.SetAuthURLParam("code_verifier", verifier),
)
require.NoError(t, err)
require.NotEmpty(t, token.AccessToken)
// Token should work on server1 (correct audience)
client1 := codersdk.New(server1.URL)
client1.SetSessionToken(token.AccessToken)
gotUser, err := client1.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, user.ID, gotUser.ID)
// Token should NOT work on server2 (different audience/host) if audience validation is implemented
// Note: This test verifies that the audience validation middleware properly rejects
// tokens issued for different resource servers
client2 := codersdk.New(server2.URL)
client2.SetSessionToken(token.AccessToken)
// This should fail due to audience mismatch if validation is properly implemented
// The expected behavior depends on whether the middleware detects Host differences
if _, err := client2.User(ctx, codersdk.Me); err != nil {
// This is expected if audience validation is working properly
t.Logf("Cross-resource token properly rejected: %v", err)
// Assert that the error is related to audience validation
require.Contains(t, err.Error(), "audience")
} else {
// The token might still work if both servers use the same database but different URLs
// since the actual audience validation depends on Host header comparison
t.Logf("Cross-resource token was accepted (both servers use same database)")
// For now, we accept this behavior since both servers share the same database
// In a real cross-deployment scenario, this should fail
}
// TODO: Enhance this test when we have better cross-deployment testing setup
// For now, this verifies the basic token flow works correctly
}
// TestOAuth2RefreshExpiryOutlivesAccess verifies that refresh token expiry is
// greater than the provisioned access token (API key) expiry per configuration.
func TestOAuth2RefreshExpiryOutlivesAccess(t *testing.T) {
t.Parallel()
// Set explicit lifetimes to make comparison deterministic.
db, pubsub := dbtestutil.NewDB(t)
dv := coderdtest.DeploymentValues(t, func(d *codersdk.DeploymentValues) {
d.Sessions.DefaultDuration = serpent.Duration(1 * time.Hour)
d.Sessions.RefreshDefaultDuration = serpent.Duration(48 * time.Hour)
})
ownerClient := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: pubsub,
DeploymentValues: dv,
})
_ = coderdtest.CreateFirstUser(t, ownerClient)
ctx := testutil.Context(t, testutil.WaitLong)
// Create app and secret
// Keep suffix short to satisfy name validation (<=32 chars, alnum + hyphens).
apps := generateApps(ctx, t, ownerClient, "ref-exp")
//nolint:gocritic // Owner permission required for app secret creation
secret, err := ownerClient.PostOAuth2ProviderAppSecret(ctx, apps.Default.ID)
require.NoError(t, err)
cfg := &oauth2.Config{
ClientID: apps.Default.ID.String(),
ClientSecret: secret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: apps.Default.Endpoints.Authorization,
DeviceAuthURL: apps.Default.Endpoints.DeviceAuth,
TokenURL: apps.Default.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: apps.Default.CallbackURL,
Scopes: []string{},
}
// Authorization and token exchange
code, verifier, err := authorizationFlow(ctx, ownerClient, cfg)
require.NoError(t, err)
tok, err := cfg.Exchange(ctx, code,
oauth2.SetAuthURLParam("code_verifier", verifier),
)
require.NoError(t, err)
require.NotEmpty(t, tok.AccessToken)
require.NotEmpty(t, tok.RefreshToken)
// Parse refresh token prefix (coder_<prefix>_<secret>)
parts := strings.Split(tok.RefreshToken, "_")
require.Len(t, parts, 3)
prefix := parts[1]
// Look up refresh token row and associated API key
dbToken, err := db.GetOAuth2ProviderAppTokenByPrefix(dbauthz.AsSystemRestricted(ctx), []byte(prefix))
require.NoError(t, err)
apiKey, err := db.GetAPIKeyByID(dbauthz.AsSystemRestricted(ctx), dbToken.APIKeyID)
require.NoError(t, err)
// Assert refresh token expiry is strictly after access token expiry
require.Truef(t, dbToken.ExpiresAt.After(apiKey.ExpiresAt),
"expected refresh expiry %s to be after access expiry %s",
dbToken.ExpiresAt, apiKey.ExpiresAt,
)
}
// customTokenExchange performs a custom OAuth2 token exchange with support for resource parameter
// This is needed because golang.org/x/oauth2 doesn't support custom parameters in token requests
func customTokenExchange(ctx context.Context, baseURL, clientID, clientSecret, code, redirectURI, resource, codeVerifier string) (*oauth2.Token, error) {
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("code", code)
data.Set("client_id", clientID)
data.Set("client_secret", clientSecret)
data.Set("redirect_uri", redirectURI)
if resource != "" {
data.Set("resource", resource)
}
if codeVerifier != "" {
data.Set("code_verifier", codeVerifier)
}
req, err := http.NewRequestWithContext(ctx, "POST", baseURL+"/oauth2/tokens", strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var errorResp struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
_ = json.NewDecoder(resp.Body).Decode(&errorResp)
return nil, xerrors.Errorf("oauth2: %q %q", errorResp.Error, errorResp.ErrorDescription)
}
var token oauth2.Token
if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
return nil, err
}
return &token, nil
}
// TestOAuth2DynamicClientRegistration tests RFC 7591 dynamic client registration
func TestOAuth2DynamicClientRegistration(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
t.Run("BasicRegistration", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
clientName := fmt.Sprintf("test-client-basic-%d", time.Now().UnixNano())
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
ClientURI: "https://example.com",
LogoURI: "https://example.com/logo.png",
TOSURI: "https://example.com/tos",
PolicyURI: "https://example.com/privacy",
Contacts: []string{"admin@example.com"},
}
// Register client
resp, err := client.PostOAuth2ClientRegistration(ctx, req)
require.NoError(t, err)
// Verify response fields
require.NotEmpty(t, resp.ClientID)
require.NotEmpty(t, resp.ClientSecret)
require.NotEmpty(t, resp.RegistrationAccessToken)
require.NotEmpty(t, resp.RegistrationClientURI)
require.Greater(t, resp.ClientIDIssuedAt, int64(0))
require.Equal(t, int64(0), resp.ClientSecretExpiresAt) // Non-expiring
// Verify default values
require.Contains(t, resp.GrantTypes, codersdk.OAuth2ProviderGrantTypeAuthorizationCode)
require.Contains(t, resp.GrantTypes, codersdk.OAuth2ProviderGrantTypeRefreshToken)
require.Contains(t, resp.ResponseTypes, codersdk.OAuth2ProviderResponseTypeCode)
require.Equal(t, codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic, resp.TokenEndpointAuthMethod)
// Verify request values are preserved
require.Equal(t, req.RedirectURIs, resp.RedirectURIs)
require.Equal(t, req.ClientName, resp.ClientName)
require.Equal(t, req.ClientURI, resp.ClientURI)
require.Equal(t, req.LogoURI, resp.LogoURI)
require.Equal(t, req.TOSURI, resp.TOSURI)
require.Equal(t, req.PolicyURI, resp.PolicyURI)
require.Equal(t, req.Contacts, resp.Contacts)
})
t.Run("MinimalRegistration", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://minimal.com/callback"},
}
// Register client with minimal fields
resp, err := client.PostOAuth2ClientRegistration(ctx, req)
require.NoError(t, err)
// Should still get all required fields
require.NotEmpty(t, resp.ClientID)
require.NotEmpty(t, resp.ClientSecret)
require.NotEmpty(t, resp.RegistrationAccessToken)
require.NotEmpty(t, resp.RegistrationClientURI)
// Should have defaults applied
require.Contains(t, resp.GrantTypes, codersdk.OAuth2ProviderGrantTypeAuthorizationCode)
require.Contains(t, resp.ResponseTypes, codersdk.OAuth2ProviderResponseTypeCode)
require.Equal(t, codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic, resp.TokenEndpointAuthMethod)
})
t.Run("InvalidRedirectURI", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"not-a-url"},
}
_, err := client.PostOAuth2ClientRegistration(ctx, req)
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_client_metadata")
})
t.Run("NoRedirectURIs", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
req := codersdk.OAuth2ClientRegistrationRequest{
ClientName: fmt.Sprintf("no-uris-client-%d", time.Now().UnixNano()),
}
_, err := client.PostOAuth2ClientRegistration(ctx, req)
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_client_metadata")
})
}
// TestOAuth2DynamicClientRegistrationDisabled verifies the admin DCR
// enabled/disabled toggle: new registrations are rejected while a client
// that registered before DCR was disabled keeps working (RFC 7592
// self-management, authorization, and token exchange are unaffected).
func TestOAuth2DynamicClientRegistrationDisabled(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
ctx := testutil.Context(t, testutil.WaitLong)
oauth2providertest.EnableDCR(t, client)
// Register a client while DCR is still enabled.
regResp, err := client.PostOAuth2ClientRegistration(ctx, codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{oauth2providertest.TestRedirectURI},
})
require.NoError(t, err)
_, err = client.PutOAuth2ProviderSettings(ctx, codersdk.OAuth2ProviderSettings{
DynamicClientRegistrationEnabled: new(false),
})
require.NoError(t, err)
t.Run("NewRegistrationRejected", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
_, err := client.PostOAuth2ClientRegistration(ctx, codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{oauth2providertest.TestRedirectURI},
})
require.Error(t, err)
var sdkError *codersdk.Error
require.ErrorAsf(t, err, &sdkError, "error should be of type *codersdk.Error")
require.Equal(t, http.StatusForbidden, sdkError.StatusCode())
})
t.Run("DiscoveryOmitsRegistrationEndpoint", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
res, err := client.Request(ctx, http.MethodGet, "/.well-known/oauth-authorization-server", nil)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
var metadata codersdk.OAuth2AuthorizationServerMetadata
require.NoError(t, json.NewDecoder(res.Body).Decode(&metadata))
require.Empty(t, metadata.RegistrationEndpoint)
})
t.Run("ExistingClientSelfManagementUnaffected", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
config, err := client.GetOAuth2ClientConfiguration(ctx, regResp.ClientID, regResp.RegistrationAccessToken)
require.NoError(t, err)
require.Equal(t, regResp.ClientID, config.ClientID)
})
t.Run("ExistingClientAuthorizeAndTokenUnaffected", func(t *testing.T) {
t.Parallel()
codeVerifier, codeChallenge := oauth2providertest.GeneratePKCE(t)
state := oauth2providertest.GenerateState(t)
code := oauth2providertest.AuthorizeOAuth2App(t, client, client.URL.String(), oauth2providertest.AuthorizeParams{
ClientID: regResp.ClientID,
ResponseType: "code",
RedirectURI: oauth2providertest.TestRedirectURI,
State: state,
CodeChallenge: codeChallenge,
CodeChallengeMethod: "S256",
})
require.NotEmpty(t, code)
token := oauth2providertest.ExchangeCodeForToken(t, client.URL.String(), oauth2providertest.TokenExchangeParams{
GrantType: "authorization_code",
Code: code,
ClientID: regResp.ClientID,
ClientSecret: regResp.ClientSecret,
CodeVerifier: codeVerifier,
RedirectURI: oauth2providertest.TestRedirectURI,
})
require.NotEmpty(t, token.AccessToken)
})
}
// TestOAuth2ClientConfiguration tests RFC 7592 client configuration management
func TestOAuth2ClientConfiguration(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
// Helper to register a client
registerClient := func(t *testing.T) (string, string, string) {
ctx := testutil.Context(t, testutil.WaitLong)
// Use shorter client name to avoid database varchar(64) constraint
clientName := fmt.Sprintf("client-%d", time.Now().UnixNano())
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: clientName,
ClientURI: "https://example.com",
}
resp, err := client.PostOAuth2ClientRegistration(ctx, req)
require.NoError(t, err)
return resp.ClientID, resp.RegistrationAccessToken, clientName
}
t.Run("GetConfiguration", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
clientID, token, clientName := registerClient(t)
// Get client configuration
config, err := client.GetOAuth2ClientConfiguration(ctx, clientID, token)
require.NoError(t, err)
// Verify fields
require.Equal(t, clientID, config.ClientID)
require.Greater(t, config.ClientIDIssuedAt, int64(0))
require.Equal(t, []string{"https://example.com/callback"}, config.RedirectURIs)
require.Equal(t, clientName, config.ClientName)
require.Equal(t, "https://example.com", config.ClientURI)
// Should not contain client_secret in GET response
require.Empty(t, config.RegistrationAccessToken) // Not included in GET
})
t.Run("UpdateConfiguration", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
clientID, token, _ := registerClient(t)
// Update client configuration
updatedName := fmt.Sprintf("updated-test-client-%d", time.Now().UnixNano())
updateReq := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://newdomain.com/callback", "https://example.com/callback"},
ClientName: updatedName,
ClientURI: "https://newdomain.com",
LogoURI: "https://newdomain.com/logo.png",
}
config, err := client.PutOAuth2ClientConfiguration(ctx, clientID, token, updateReq)
require.NoError(t, err)
// Verify updates
require.Equal(t, clientID, config.ClientID)
require.Equal(t, updateReq.RedirectURIs, config.RedirectURIs)
require.Equal(t, updateReq.ClientName, config.ClientName)
require.Equal(t, updateReq.ClientURI, config.ClientURI)
require.Equal(t, updateReq.LogoURI, config.LogoURI)
})
t.Run("DeleteConfiguration", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
clientID, token, _ := registerClient(t)
// Delete client
err := client.DeleteOAuth2ClientConfiguration(ctx, clientID, token)
require.NoError(t, err)
// Should no longer be able to get configuration
_, err = client.GetOAuth2ClientConfiguration(ctx, clientID, token)
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_token")
})
t.Run("InvalidToken", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
clientID, _, _ := registerClient(t)
invalidToken := "invalid-token"
// Should fail with invalid token
_, err := client.GetOAuth2ClientConfiguration(ctx, clientID, invalidToken)
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_token")
})
t.Run("NonexistentClient", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
fakeClientID := uuid.NewString()
fakeToken := "fake-token"
_, err := client.GetOAuth2ClientConfiguration(ctx, fakeClientID, fakeToken)
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_token")
})
t.Run("MissingAuthHeader", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
clientID, _, _ := registerClient(t)
// Try to access without token (empty string)
_, err := client.GetOAuth2ClientConfiguration(ctx, clientID, "")
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_token")
})
}
// TestOAuth2RegistrationAccessToken tests the registration access token middleware
func TestOAuth2RegistrationAccessToken(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
oauth2providertest.EnableDCR(t, client)
t.Run("ValidToken", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
// Register a client
req := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://example.com/callback"},
ClientName: fmt.Sprintf("token-test-client-%d", time.Now().UnixNano()),
}
resp, err := client.PostOAuth2ClientRegistration(ctx, req)
require.NoError(t, err)
// Valid token should work
config, err := client.GetOAuth2ClientConfiguration(ctx, resp.ClientID, resp.RegistrationAccessToken)
require.NoError(t, err)
require.Equal(t, resp.ClientID, config.ClientID)
})
t.Run("ManuallyCreatedClient", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
// Create a client through the normal API (not dynamic registration)
appReq := codersdk.PostOAuth2ProviderAppRequest{
Name: fmt.Sprintf("manual-%d", time.Now().UnixNano()%1000000),
CallbackURL: "https://manual.com/callback",
}
app, err := client.PostOAuth2ProviderApp(ctx, appReq)
require.NoError(t, err)
// Should not be able to manage via RFC 7592 endpoints
_, err = client.GetOAuth2ClientConfiguration(ctx, app.ID.String(), "any-token")
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_token") // Client was not dynamically registered
})
t.Run("TokenPasswordComparison", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
// Register two clients to ensure tokens are unique
timestamp := time.Now().UnixNano()
req1 := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://client1.com/callback"},
ClientName: fmt.Sprintf("client-1-%d", timestamp),
}
req2 := codersdk.OAuth2ClientRegistrationRequest{
RedirectURIs: []string{"https://client2.com/callback"},
ClientName: fmt.Sprintf("client-2-%d", timestamp+1),
}
resp1, err := client.PostOAuth2ClientRegistration(ctx, req1)
require.NoError(t, err)
resp2, err := client.PostOAuth2ClientRegistration(ctx, req2)
require.NoError(t, err)
// Each client should only work with its own token
_, err = client.GetOAuth2ClientConfiguration(ctx, resp1.ClientID, resp1.RegistrationAccessToken)
require.NoError(t, err)
_, err = client.GetOAuth2ClientConfiguration(ctx, resp2.ClientID, resp2.RegistrationAccessToken)
require.NoError(t, err)
// Cross-client tokens should fail
_, err = client.GetOAuth2ClientConfiguration(ctx, resp1.ClientID, resp2.RegistrationAccessToken)
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_token")
_, err = client.GetOAuth2ClientConfiguration(ctx, resp2.ClientID, resp1.RegistrationAccessToken)
require.Error(t, err)
require.Contains(t, err.Error(), "invalid_token")
})
}
// TestOAuth2CoderClient verfies a codersdk client can be used with an oauth client.
func TestOAuth2CoderClient(t *testing.T) {
t.Parallel()
owner := coderdtest.New(t, nil)
first := coderdtest.CreateFirstUser(t, owner)
// Setup an oauth app
ctx := testutil.Context(t, testutil.WaitLong)
app, err := owner.PostOAuth2ProviderApp(ctx, codersdk.PostOAuth2ProviderAppRequest{
Name: "new-app",
CallbackURL: "http://localhost",
})
require.NoError(t, err)
appsecret, err := owner.PostOAuth2ProviderAppSecret(ctx, app.ID)
require.NoError(t, err)
cfg := &oauth2.Config{
ClientID: app.ID.String(),
ClientSecret: appsecret.ClientSecretFull,
Endpoint: oauth2.Endpoint{
AuthURL: app.Endpoints.Authorization,
DeviceAuthURL: app.Endpoints.DeviceAuth,
TokenURL: app.Endpoints.Token,
AuthStyle: oauth2.AuthStyleInParams,
},
RedirectURL: app.CallbackURL,
Scopes: []string{},
}
// Make a new user
client, user := coderdtest.CreateAnotherUser(t, owner, first.OrganizationID)
// Do an OAuth2 token exchange and get a new client with an oauth token.
state := uuid.NewString()
verifier, challenge := generatePKCE()
// Get an OAuth2 code for a token exchange.
code, err := oidctest.OAuth2GetCode(
cfg.AuthCodeURL(state,
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
),
func(req *http.Request) (*http.Response, error) {
// Change to POST to simulate the form submission.
req.Method = http.MethodPost
// Prevent automatic redirect following.
client.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return client.Request(ctx, req.Method, req.URL.String(), nil)
},
)
require.NoError(t, err)
token, err := cfg.Exchange(ctx, code,
oauth2.SetAuthURLParam("code_verifier", verifier),
)
require.NoError(t, err)
// Use the oauth client's authentication
// TODO: The SDK could probably support this with a better syntax/api.
oauthClient := oauth2.NewClient(ctx, oauth2.StaticTokenSource(token))
usingOauth := codersdk.New(owner.URL)
usingOauth.HTTPClient = oauthClient
me, err := usingOauth.User(ctx, codersdk.Me)
require.NoError(t, err)
require.Equal(t, user.ID, me.ID)
// Revoking the refresh token should prevent further access
// Revoking the refresh also invalidates the associated access token.
err = usingOauth.RevokeOAuth2Token(ctx, app.ID, token.RefreshToken)
require.NoError(t, err)
_, err = usingOauth.User(ctx, codersdk.Me)
require.Error(t, err)
}
// NOTE: OAuth2 client registration validation tests have been migrated to
// oauth2provider/validation_test.go for better separation of concerns