mirror of
https://github.com/coder/coder.git
synced 2025-07-06 15:41:45 +00:00
feat: oauth2 - add authorization server metadata endpoint and PKCE support (#18548)
## Summary This PR implements critical MCP OAuth2 compliance features for Coder's authorization server, adding PKCE support, resource parameter handling, and OAuth2 server metadata discovery. This brings Coder's OAuth2 implementation significantly closer to production readiness for MCP (Model Context Protocol) integrations. ## What's Added ### OAuth2 Authorization Server Metadata (RFC 8414) - Add `/.well-known/oauth-authorization-server` endpoint for automatic client discovery - Returns standardized metadata including supported grant types, response types, and PKCE methods - Essential for MCP client compatibility and OAuth2 standards compliance ### PKCE Support (RFC 7636) - Implement Proof Key for Code Exchange with S256 challenge method - Add `code_challenge` and `code_challenge_method` parameters to authorization flow - Add `code_verifier` validation in token exchange - Provides enhanced security for public clients (mobile apps, CLIs) ### Resource Parameter Support (RFC 8707) - Add `resource` parameter to authorization and token endpoints - Store resource URI and bind tokens to specific audiences - Critical for MCP's resource-bound token model ### Enhanced OAuth2 Error Handling - Add OAuth2-compliant error responses with proper error codes - Use standard error format: `{"error": "code", "error_description": "details"}` - Improve error consistency across OAuth2 endpoints ### Authorization UI Improvements - Fix authorization flow to use POST-based consent instead of GET redirects - Remove dependency on referer headers for security decisions - Improve CSRF protection with proper state parameter validation ## Why This Matters **For MCP Integration:** MCP requires OAuth2 authorization servers to support PKCE, resource parameters, and metadata discovery. Without these features, MCP clients cannot securely authenticate with Coder. **For Security:** PKCE prevents authorization code interception attacks, especially critical for public clients. Resource binding ensures tokens are only valid for intended services. **For Standards Compliance:** These are widely adopted OAuth2 extensions that improve interoperability with modern OAuth2 clients. ## Database Changes - **Migration 000343:** Adds `code_challenge`, `code_challenge_method`, `resource_uri` to `oauth2_provider_app_codes` - **Migration 000343:** Adds `audience` field to `oauth2_provider_app_tokens` for resource binding - **Audit Updates:** New OAuth2 fields properly tracked in audit system - **Backward Compatibility:** All changes maintain compatibility with existing OAuth2 flows ## Test Coverage - Comprehensive PKCE test suite in `coderd/identityprovider/pkce_test.go` - OAuth2 metadata endpoint tests in `coderd/oauth2_metadata_test.go` - Integration tests covering PKCE + resource parameter combinations - Negative tests for invalid PKCE verifiers and malformed requests ## Testing Instructions ```bash # Run the comprehensive OAuth2 test suite ./scripts/oauth2/test-mcp-oauth2.sh Manual Testing with Interactive Server # Start Coder in development mode ./scripts/develop.sh # In another terminal, set up test app and run interactive flow eval $(./scripts/oauth2/setup-test-app.sh) ./scripts/oauth2/test-manual-flow.sh # Opens browser with OAuth2 flow, handles callback automatically # Clean up when done ./scripts/oauth2/cleanup-test-app.sh Individual Component Testing # Test metadata endpoint curl -s http://localhost:3000/.well-known/oauth-authorization-server | jq . # Test PKCE generation ./scripts/oauth2/generate-pkce.sh # Run specific test suites go test -v ./coderd/identityprovider -run TestVerifyPKCE go test -v ./coderd -run TestOAuth2AuthorizationServerMetadata ``` ### Breaking Changes None. All changes maintain backward compatibility with existing OAuth2 flows. --- Change-Id: Ifbd0d9a543d545f9f56ecaa77ff2238542ff954a Signed-off-by: Thomas Kosiewski <tk@coder.com>
This commit is contained in:
@ -422,7 +422,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preAuth: func(valid *oauth2.Config) {
|
||||
valid.ClientID = uuid.NewString()
|
||||
},
|
||||
authError: "Resource not found",
|
||||
authError: "invalid_client",
|
||||
},
|
||||
{
|
||||
name: "TokenInvalidAppID",
|
||||
@ -430,7 +430,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preToken: func(valid *oauth2.Config) {
|
||||
valid.ClientID = uuid.NewString()
|
||||
},
|
||||
tokenError: "Resource not found",
|
||||
tokenError: "invalid_client",
|
||||
},
|
||||
{
|
||||
name: "InvalidPort",
|
||||
@ -440,7 +440,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
newURL.Host = newURL.Hostname() + ":8081"
|
||||
valid.RedirectURL = newURL.String()
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
name: "WrongAppHost",
|
||||
@ -448,7 +448,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preAuth: func(valid *oauth2.Config) {
|
||||
valid.RedirectURL = apps.NoPort.CallbackURL
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
name: "InvalidHostPrefix",
|
||||
@ -458,7 +458,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
newURL.Host = "prefix" + newURL.Hostname()
|
||||
valid.RedirectURL = newURL.String()
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
name: "InvalidHost",
|
||||
@ -468,7 +468,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
newURL.Host = "invalid"
|
||||
valid.RedirectURL = newURL.String()
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
name: "InvalidHostAndPort",
|
||||
@ -478,7 +478,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
newURL.Host = "invalid:8080"
|
||||
valid.RedirectURL = newURL.String()
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
name: "InvalidPath",
|
||||
@ -488,7 +488,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
newURL.Path = path.Join("/prepend", newURL.Path)
|
||||
valid.RedirectURL = newURL.String()
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
name: "MissingPath",
|
||||
@ -498,7 +498,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
newURL.Path = "/"
|
||||
valid.RedirectURL = newURL.String()
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
// TODO: This is valid for now, but should it be?
|
||||
@ -529,7 +529,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
newURL.Host = "sub." + newURL.Host
|
||||
valid.RedirectURL = newURL.String()
|
||||
},
|
||||
authError: "Invalid query params",
|
||||
authError: "Invalid query params:",
|
||||
},
|
||||
{
|
||||
name: "NoSecretScheme",
|
||||
@ -537,7 +537,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preToken: func(valid *oauth2.Config) {
|
||||
valid.ClientSecret = "1234_4321"
|
||||
},
|
||||
tokenError: "Invalid client secret",
|
||||
tokenError: "The client credentials are invalid",
|
||||
},
|
||||
{
|
||||
name: "InvalidSecretScheme",
|
||||
@ -545,7 +545,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preToken: func(valid *oauth2.Config) {
|
||||
valid.ClientSecret = "notcoder_1234_4321"
|
||||
},
|
||||
tokenError: "Invalid client secret",
|
||||
tokenError: "The client credentials are invalid",
|
||||
},
|
||||
{
|
||||
name: "MissingSecretSecret",
|
||||
@ -553,7 +553,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preToken: func(valid *oauth2.Config) {
|
||||
valid.ClientSecret = "coder_1234"
|
||||
},
|
||||
tokenError: "Invalid client secret",
|
||||
tokenError: "The client credentials are invalid",
|
||||
},
|
||||
{
|
||||
name: "MissingSecretPrefix",
|
||||
@ -561,7 +561,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preToken: func(valid *oauth2.Config) {
|
||||
valid.ClientSecret = "coder__1234"
|
||||
},
|
||||
tokenError: "Invalid client secret",
|
||||
tokenError: "The client credentials are invalid",
|
||||
},
|
||||
{
|
||||
name: "InvalidSecretPrefix",
|
||||
@ -569,7 +569,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preToken: func(valid *oauth2.Config) {
|
||||
valid.ClientSecret = "coder_1234_4321"
|
||||
},
|
||||
tokenError: "Invalid client secret",
|
||||
tokenError: "The client credentials are invalid",
|
||||
},
|
||||
{
|
||||
name: "MissingSecret",
|
||||
@ -577,48 +577,48 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
preToken: func(valid *oauth2.Config) {
|
||||
valid.ClientSecret = ""
|
||||
},
|
||||
tokenError: "Invalid query params",
|
||||
tokenError: "invalid_request",
|
||||
},
|
||||
{
|
||||
name: "NoCodeScheme",
|
||||
app: apps.Default,
|
||||
defaultCode: ptr.Ref("1234_4321"),
|
||||
tokenError: "Invalid code",
|
||||
tokenError: "The authorization code is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "InvalidCodeScheme",
|
||||
app: apps.Default,
|
||||
defaultCode: ptr.Ref("notcoder_1234_4321"),
|
||||
tokenError: "Invalid code",
|
||||
tokenError: "The authorization code is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "MissingCodeSecret",
|
||||
app: apps.Default,
|
||||
defaultCode: ptr.Ref("coder_1234"),
|
||||
tokenError: "Invalid code",
|
||||
tokenError: "The authorization code is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "MissingCodePrefix",
|
||||
app: apps.Default,
|
||||
defaultCode: ptr.Ref("coder__1234"),
|
||||
tokenError: "Invalid code",
|
||||
tokenError: "The authorization code is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "InvalidCodePrefix",
|
||||
app: apps.Default,
|
||||
defaultCode: ptr.Ref("coder_1234_4321"),
|
||||
tokenError: "Invalid code",
|
||||
tokenError: "The authorization code is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "MissingCode",
|
||||
app: apps.Default,
|
||||
defaultCode: ptr.Ref(""),
|
||||
tokenError: "Invalid query params",
|
||||
tokenError: "invalid_request",
|
||||
},
|
||||
{
|
||||
name: "InvalidGrantType",
|
||||
app: apps.Default,
|
||||
tokenError: "Invalid query params",
|
||||
tokenError: "unsupported_grant_type",
|
||||
exchangeMutate: []oauth2.AuthCodeOption{
|
||||
oauth2.SetAuthURLParam("grant_type", "foobar"),
|
||||
},
|
||||
@ -626,7 +626,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
{
|
||||
name: "EmptyGrantType",
|
||||
app: apps.Default,
|
||||
tokenError: "Invalid query params",
|
||||
tokenError: "unsupported_grant_type",
|
||||
exchangeMutate: []oauth2.AuthCodeOption{
|
||||
oauth2.SetAuthURLParam("grant_type", ""),
|
||||
},
|
||||
@ -635,7 +635,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
name: "ExpiredCode",
|
||||
app: apps.Default,
|
||||
defaultCode: ptr.Ref("coder_prefix_code"),
|
||||
tokenError: "Invalid 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")
|
||||
@ -720,7 +720,7 @@ func TestOAuth2ProviderTokenExchange(t *testing.T) {
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, token.AccessToken)
|
||||
require.True(t, time.Now().After(token.Expiry))
|
||||
require.True(t, time.Now().Before(token.Expiry))
|
||||
|
||||
// Check that the token works.
|
||||
newClient := codersdk.New(userClient.URL)
|
||||
@ -764,37 +764,37 @@ func TestOAuth2ProviderTokenRefresh(t *testing.T) {
|
||||
name: "NoTokenScheme",
|
||||
app: apps.Default,
|
||||
defaultToken: ptr.Ref("1234_4321"),
|
||||
error: "Invalid token",
|
||||
error: "The refresh token is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "InvalidTokenScheme",
|
||||
app: apps.Default,
|
||||
defaultToken: ptr.Ref("notcoder_1234_4321"),
|
||||
error: "Invalid token",
|
||||
error: "The refresh token is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "MissingTokenSecret",
|
||||
app: apps.Default,
|
||||
defaultToken: ptr.Ref("coder_1234"),
|
||||
error: "Invalid token",
|
||||
error: "The refresh token is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "MissingTokenPrefix",
|
||||
app: apps.Default,
|
||||
defaultToken: ptr.Ref("coder__1234"),
|
||||
error: "Invalid token",
|
||||
error: "The refresh token is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "InvalidTokenPrefix",
|
||||
app: apps.Default,
|
||||
defaultToken: ptr.Ref("coder_1234_4321"),
|
||||
error: "Invalid token",
|
||||
error: "The refresh token is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "Expired",
|
||||
app: apps.Default,
|
||||
expires: time.Now().Add(time.Minute * -1),
|
||||
error: "Invalid token",
|
||||
error: "The refresh token is invalid or expired",
|
||||
},
|
||||
{
|
||||
name: "OK",
|
||||
@ -1085,20 +1085,21 @@ func generateApps(ctx context.Context, t *testing.T, client *codersdk.Client, su
|
||||
|
||||
func authorizationFlow(ctx context.Context, client *codersdk.Client, cfg *oauth2.Config) (string, error) {
|
||||
state := uuid.NewString()
|
||||
authURL := cfg.AuthCodeURL(state)
|
||||
|
||||
// Make a POST request to simulate clicking "Allow" on the authorization page
|
||||
// This bypasses the HTML consent page and directly processes the authorization
|
||||
return oidctest.OAuth2GetCode(
|
||||
cfg.AuthCodeURL(state),
|
||||
authURL,
|
||||
func(req *http.Request) (*http.Response, error) {
|
||||
// TODO: Would be better if client had a .Do() method.
|
||||
// TODO: Is this the best way to handle redirects?
|
||||
// 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, func(req *http.Request) {
|
||||
// Set the referer so the request bypasses the HTML page (normally you
|
||||
// have to click "allow" first, and the way we detect that is using the
|
||||
// referer header).
|
||||
req.Header.Set("Referer", req.URL.String())
|
||||
})
|
||||
return client.Request(ctx, req.Method, req.URL.String(), nil)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
Reference in New Issue
Block a user