Files
coder/coderd/oauth2provider/metadata_test.go
T
Bobby Ho 9be61a0c65 feat: accept PKCE-only token exchange for public clients (#28047)
**TL;DR**

Last of the stack, split out of #27873, that makes Coder usable by
public OAuth2 clients (CLIs, IDE plugins, MCP clients), which cannot
hold a secret and authenticate with PKCE alone.

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

Each of the earlier PRs is inert on its own: until this one, a
registered public client still could not complete a flow. Dynamic client
registration is off by default, so nothing here is user-visible until it
is enabled.

**Where in the flow**

- Token endpoint only — the `authorization_code` exchange. Authorize,
consent, and code issuance are untouched.
- Refresh and revocation come along for free: both already bind by
app_id, so a secretless token row works as-is.
- Discovery starts advertising `none`.

**What it satisfies**

- OAuth 2.1 §3.2.1 — only *confidential* clients must authenticate at
the token endpoint. A public client is no longer rejected for a missing
secret.
- OAuth 2.1 §4.1.3 — for a public client the server must instead ensure
the code was issued to the request's client_id. That check already
existed; here it becomes the sole binding.
- OAuth 2.1 §4.1.3 — client_id is required when the client does not
authenticate, and a code yields a token at most once: a failed PKCE
comparison consumes the code, so a leaked one cannot be brute-forced.
- OAuth 2.1 §2.1 + RFC 7591 §2 — `none` means public client with no
secret. The type is derived at registration (#28043) and read here.
- RFC 7636 §4.1 / §4.6 — a malformed verifier is `invalid_request`, a
wrong one `invalid_grant`. PKCE was already mandatory for every code
flow, so public clients inherit it.
- RFC 8414 §2 — advertised auth methods now match what the token
endpoint actually accepts.
- RFC 7009 — a cross-app revoke of a public client's token still returns
200 without revoking.

---

- The token endpoint stops requiring client_secret for a public client,
in both the presence check and secret validation. PKCE was already
mandatory for every authorization_code flow, so public clients inherit
it with no new validation code.
- The code ownership check (dbCode.AppID != app.ID) becomes the only
binding between the exchange and the app named by client_id for a public
client, where it was defense in depth for confidential ones. Retained,
now covered with a public client on both sides.
- Public client tokens carry a NULL app_secret_id rather than
referencing a secret row that does not exist. Refresh and revocation
already verify ownership via app_id, so they change only comments and
coverage.
- Discovery advertises `none` now that the token endpoint honors it.
- Valid() derives from the single canonical auth method list, so what
registration accepts and what discovery advertises cannot disagree.
- Swagger marks client_secret confidential-only.

Refs
https://linear.app/codercom/issue/ENG-3029/oauth2-support-public-client
2026-08-31 09:55:58 -07:00

148 lines
5.3 KiB
Go

package oauth2provider_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/oauth2provider"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
)
func TestOAuth2AuthorizationServerMetadata(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
serverURL := client.URL
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
// Use a plain HTTP client since this endpoint doesn't require authentication.
// Add a short readiness wait to avoid rare races with server startup.
endpoint := serverURL.ResolveReference(&url.URL{Path: "/.well-known/oauth-authorization-server"}).String()
var metadata codersdk.OAuth2AuthorizationServerMetadata
testutil.RequireEventuallyResponseOK(ctx, t, endpoint, &metadata)
// Verify the metadata
require.NotEmpty(t, metadata.Issuer)
require.NotEmpty(t, metadata.AuthorizationEndpoint)
require.NotEmpty(t, metadata.TokenEndpoint)
require.Contains(t, metadata.ResponseTypesSupported, codersdk.OAuth2ProviderResponseTypeCode)
require.Contains(t, metadata.GrantTypesSupported, codersdk.OAuth2ProviderGrantTypeAuthorizationCode)
require.Contains(t, metadata.GrantTypesSupported, codersdk.OAuth2ProviderGrantTypeRefreshToken)
require.Contains(t, metadata.CodeChallengeMethodsSupported, codersdk.OAuth2PKCECodeChallengeMethodS256)
// Pinned to a literal, not to the function the handler itself returns, which
// would hold for whatever that function said. "none" advertises secretless
// registration to public clients (RFC 8414 §2).
require.ElementsMatch(t, []codersdk.OAuth2TokenEndpointAuthMethod{
codersdk.OAuth2TokenEndpointAuthMethodClientSecretBasic,
codersdk.OAuth2TokenEndpointAuthMethodClientSecretPost,
codersdk.OAuth2TokenEndpointAuthMethodNone,
}, metadata.TokenEndpointAuthMethodsSupported)
// Supported scopes are published from the curated catalog
require.Equal(t, rbac.ExternalScopeNames(), metadata.ScopesSupported)
}
// TestGetAuthorizationServerMetadata_DCREnabled is a focused unit test on
// the discovery handler itself, bypassing the full coderdtest HTTP server.
// It verifies the dynamic-client-registration-enabled gate: registration_endpoint
// is advertised once an admin explicitly enables DCR, omitted when explicitly
// disabled, and omitted by default when the setting has never been
// configured.
func TestGetAuthorizationServerMetadata_DCREnabled(t *testing.T) {
t.Parallel()
accessURL, err := url.Parse("https://oauth2-metadata-dcr-test.example.com")
require.NoError(t, err)
tests := []struct {
name string
// configureDCR is nil for "never configured".
configureDCR *bool
wantRegistrationEndpoint bool
}{
{
name: "EnabledAdvertisesRegistrationEndpoint",
configureDCR: new(true),
wantRegistrationEndpoint: true,
},
{
name: "DisabledOmitsRegistrationEndpoint",
configureDCR: new(false),
wantRegistrationEndpoint: false,
},
{
name: "NeverConfiguredDefaultsToOmitted",
configureDCR: nil,
wantRegistrationEndpoint: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitLong)
db, _ := dbtestutil.NewDB(t)
if tt.configureDCR != nil {
err := db.UpsertOAuth2DCREnabled(ctx, *tt.configureDCR)
require.NoError(t, err)
}
handler := oauth2provider.GetAuthorizationServerMetadata(db, accessURL)
r := httptest.NewRequest(http.MethodGet, "/.well-known/oauth-authorization-server", nil).WithContext(ctx)
rw := httptest.NewRecorder()
handler.ServeHTTP(rw, r)
require.Equal(t, http.StatusOK, rw.Code)
var metadata codersdk.OAuth2AuthorizationServerMetadata
require.NoError(t, json.Unmarshal(rw.Body.Bytes(), &metadata))
if tt.wantRegistrationEndpoint {
require.NotEmpty(t, metadata.RegistrationEndpoint)
} else {
require.Empty(t, metadata.RegistrationEndpoint)
}
})
}
}
func TestOAuth2ProtectedResourceMetadata(t *testing.T) {
t.Parallel()
client := coderdtest.New(t, nil)
serverURL := client.URL
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
// Use a plain HTTP client since this endpoint doesn't require authentication.
// Add a short readiness wait to avoid rare races with server startup.
endpoint := serverURL.ResolveReference(&url.URL{Path: "/.well-known/oauth-protected-resource"}).String()
var metadata codersdk.OAuth2ProtectedResourceMetadata
testutil.RequireEventuallyResponseOK(ctx, t, endpoint, &metadata)
// Verify the metadata
require.NotEmpty(t, metadata.Resource)
require.NotEmpty(t, metadata.AuthorizationServers)
require.Len(t, metadata.AuthorizationServers, 1)
require.Equal(t, metadata.Resource, metadata.AuthorizationServers[0])
// RFC 6750 bearer tokens are now supported as fallback methods
require.Contains(t, metadata.BearerMethodsSupported, "header")
require.Contains(t, metadata.BearerMethodsSupported, "query")
// Supported scopes are published from the curated catalog
require.Equal(t, rbac.ExternalScopeNames(), metadata.ScopesSupported)
}