mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08: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:
@@ -0,0 +1,150 @@
|
||||
# OAuth2 Test Scripts
|
||||
|
||||
This directory contains test scripts for the MCP OAuth2 implementation in Coder.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. Start Coder in development mode:
|
||||
|
||||
```bash
|
||||
./scripts/develop.sh
|
||||
```
|
||||
|
||||
2. Login to get a session token:
|
||||
|
||||
```bash
|
||||
./scripts/coder-dev.sh login
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
### `test-mcp-oauth2.sh`
|
||||
|
||||
Complete automated test suite that verifies all OAuth2 functionality:
|
||||
|
||||
- Metadata endpoint
|
||||
- PKCE flow
|
||||
- Resource parameter support
|
||||
- Token refresh
|
||||
- Error handling
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
chmod +x ./scripts/oauth2/test-mcp-oauth2.sh
|
||||
./scripts/oauth2/test-mcp-oauth2.sh
|
||||
```
|
||||
|
||||
### `setup-test-app.sh`
|
||||
|
||||
Creates a test OAuth2 application and outputs environment variables.
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
eval $(./scripts/oauth2/setup-test-app.sh)
|
||||
echo "Client ID: $CLIENT_ID"
|
||||
```
|
||||
|
||||
### `cleanup-test-app.sh`
|
||||
|
||||
Deletes a test OAuth2 application.
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
./scripts/oauth2/cleanup-test-app.sh $CLIENT_ID
|
||||
# Or if CLIENT_ID is set as environment variable:
|
||||
./scripts/oauth2/cleanup-test-app.sh
|
||||
```
|
||||
|
||||
### `generate-pkce.sh`
|
||||
|
||||
Generates PKCE code verifier and challenge for manual testing.
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
./scripts/oauth2/generate-pkce.sh
|
||||
```
|
||||
|
||||
### `test-manual-flow.sh`
|
||||
|
||||
Launches a local Go web server to test the OAuth2 flow interactively. The server automatically handles the OAuth2 callback and token exchange, providing a user-friendly web interface with results.
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
# First set up an app
|
||||
eval $(./scripts/oauth2/setup-test-app.sh)
|
||||
|
||||
# Then run the test server
|
||||
./scripts/oauth2/test-manual-flow.sh
|
||||
```
|
||||
|
||||
Features:
|
||||
|
||||
- Starts a local web server on port 9876
|
||||
- Automatically captures the authorization code
|
||||
- Performs token exchange without manual intervention
|
||||
- Displays results in a clean web interface
|
||||
- Shows example API calls you can make with the token
|
||||
|
||||
### `oauth2-test-server.go`
|
||||
|
||||
A Go web server that handles OAuth2 callbacks and token exchange. Used internally by `test-manual-flow.sh` but can also be run standalone:
|
||||
|
||||
```bash
|
||||
export CLIENT_ID="your-client-id"
|
||||
export CLIENT_SECRET="your-client-secret"
|
||||
export CODE_VERIFIER="your-code-verifier"
|
||||
export STATE="your-state"
|
||||
go run ./scripts/oauth2/oauth2-test-server.go
|
||||
```
|
||||
|
||||
## Example Workflow
|
||||
|
||||
1. **Run automated tests:**
|
||||
|
||||
```bash
|
||||
./scripts/oauth2/test-mcp-oauth2.sh
|
||||
```
|
||||
|
||||
2. **Interactive browser testing:**
|
||||
|
||||
```bash
|
||||
# Create app
|
||||
eval $(./scripts/oauth2/setup-test-app.sh)
|
||||
|
||||
# Run the test server (opens in browser automatically)
|
||||
./scripts/oauth2/test-manual-flow.sh
|
||||
# - Opens authorization URL in terminal
|
||||
# - Handles callback automatically
|
||||
# - Shows token exchange results
|
||||
|
||||
# Clean up when done
|
||||
./scripts/oauth2/cleanup-test-app.sh
|
||||
```
|
||||
|
||||
3. **Generate PKCE for custom testing:**
|
||||
|
||||
```bash
|
||||
./scripts/oauth2/generate-pkce.sh
|
||||
# Use the generated values in your own curl commands
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
All scripts respect these environment variables:
|
||||
|
||||
- `SESSION_TOKEN`: Coder session token (auto-read from `.coderv2/session`)
|
||||
- `BASE_URL`: Coder server URL (default: `http://localhost:3000`)
|
||||
- `CLIENT_ID`: OAuth2 client ID
|
||||
- `CLIENT_SECRET`: OAuth2 client secret
|
||||
|
||||
## OAuth2 Endpoints
|
||||
|
||||
- Metadata: `GET /.well-known/oauth-authorization-server`
|
||||
- Authorization: `GET/POST /oauth2/authorize`
|
||||
- Token: `POST /oauth2/tokens`
|
||||
- Apps API: `/api/v2/oauth2-provider/apps`
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Cleanup OAuth2 test app
|
||||
# Usage: ./cleanup-test-app.sh [CLIENT_ID]
|
||||
|
||||
CLIENT_ID="${1:-$CLIENT_ID}"
|
||||
SESSION_TOKEN="${SESSION_TOKEN:-$(cat ./.coderv2/session 2>/dev/null || echo '')}"
|
||||
BASE_URL="${BASE_URL:-http://localhost:3000}"
|
||||
|
||||
if [ -z "$CLIENT_ID" ]; then
|
||||
echo "ERROR: CLIENT_ID must be provided as argument or environment variable"
|
||||
echo "Usage: ./cleanup-test-app.sh <CLIENT_ID>"
|
||||
echo "Or set CLIENT_ID environment variable"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$SESSION_TOKEN" ]; then
|
||||
echo "ERROR: SESSION_TOKEN must be set or ./.coderv2/session must exist"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
AUTH_HEADER="Coder-Session-Token: $SESSION_TOKEN"
|
||||
|
||||
echo "Deleting OAuth2 app: $CLIENT_ID"
|
||||
|
||||
RESPONSE=$(curl -s -w "\n%{http_code}" -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$CLIENT_ID" \
|
||||
-H "$AUTH_HEADER")
|
||||
|
||||
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
|
||||
BODY=$(echo "$RESPONSE" | head -n -1)
|
||||
|
||||
if [ "$HTTP_CODE" = "204" ]; then
|
||||
echo "✓ Successfully deleted OAuth2 app: $CLIENT_ID"
|
||||
else
|
||||
echo "✗ Failed to delete OAuth2 app: $CLIENT_ID"
|
||||
echo "HTTP $HTTP_CODE"
|
||||
if [ -n "$BODY" ]; then
|
||||
echo "$BODY" | jq . 2>/dev/null || echo "$BODY"
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Generate PKCE code verifier and challenge for OAuth2 flow
|
||||
# Usage: ./generate-pkce.sh
|
||||
|
||||
# Generate code verifier (43-128 characters, URL-safe)
|
||||
CODE_VERIFIER=$(openssl rand -base64 32 | tr -d "=+/" | cut -c -43)
|
||||
|
||||
# Generate code challenge (S256 method)
|
||||
CODE_CHALLENGE=$(echo -n "$CODE_VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_')
|
||||
|
||||
echo "Code Verifier: $CODE_VERIFIER"
|
||||
echo "Code Challenge: $CODE_CHALLENGE"
|
||||
|
||||
# Export as environment variables for use in other scripts
|
||||
export CODE_VERIFIER
|
||||
export CODE_CHALLENGE
|
||||
|
||||
echo ""
|
||||
echo "Environment variables set:"
|
||||
echo " CODE_VERIFIER=\"$CODE_VERIFIER\""
|
||||
echo " CODE_CHALLENGE=\"$CODE_CHALLENGE\""
|
||||
echo ""
|
||||
echo "Usage in curl:"
|
||||
echo " curl \"...&code_challenge=$CODE_CHALLENGE&code_challenge_method=S256\""
|
||||
echo " curl -d \"code_verifier=$CODE_VERIFIER\" ..."
|
||||
@@ -0,0 +1,292 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
type TokenResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
RefreshToken string `json:"refresh_token,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
ErrorDesc string `json:"error_description,omitempty"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
CodeVerifier string
|
||||
State string
|
||||
BaseURL string
|
||||
RedirectURI string
|
||||
}
|
||||
|
||||
type ServerOptions struct {
|
||||
KeepRunning bool
|
||||
}
|
||||
|
||||
func main() {
|
||||
var serverOpts ServerOptions
|
||||
flag.BoolVar(&serverOpts.KeepRunning, "keep-running", false, "Keep server running after successful authorization")
|
||||
flag.Parse()
|
||||
|
||||
config := &Config{
|
||||
ClientID: os.Getenv("CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("CLIENT_SECRET"),
|
||||
CodeVerifier: os.Getenv("CODE_VERIFIER"),
|
||||
State: os.Getenv("STATE"),
|
||||
BaseURL: cmp.Or(os.Getenv("BASE_URL"), "http://localhost:3000"),
|
||||
RedirectURI: "http://localhost:9876/callback",
|
||||
}
|
||||
|
||||
if config.ClientID == "" || config.ClientSecret == "" {
|
||||
log.Fatal("CLIENT_ID and CLIENT_SECRET must be set. Run: eval $(./setup-test-app.sh) first")
|
||||
}
|
||||
|
||||
if config.CodeVerifier == "" || config.State == "" {
|
||||
log.Fatal("CODE_VERIFIER and STATE must be set. Run test-manual-flow.sh to get these values")
|
||||
}
|
||||
|
||||
var server *http.Server
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
|
||||
html := fmt.Sprintf(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>OAuth2 Test Server</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
|
||||
.status { padding: 20px; margin: 20px 0; border-radius: 5px; }
|
||||
.waiting { background: #fff3cd; color: #856404; }
|
||||
.success { background: #d4edda; color: #155724; }
|
||||
.error { background: #f8d7da; color: #721c24; }
|
||||
pre { background: #f5f5f5; padding: 15px; overflow-x: auto; }
|
||||
a { color: #0066cc; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>OAuth2 Test Server</h1>
|
||||
<div class="status waiting">
|
||||
<h2>Waiting for OAuth2 callback...</h2>
|
||||
<p>Please authorize the application in your browser.</p>
|
||||
<p>Listening on: <code>%s</code></p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`, config.RedirectURI)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = fmt.Fprint(w, html)
|
||||
})
|
||||
|
||||
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.URL.Query().Get("code")
|
||||
state := r.URL.Query().Get("state")
|
||||
errorParam := r.URL.Query().Get("error")
|
||||
errorDesc := r.URL.Query().Get("error_description")
|
||||
|
||||
if errorParam != "" {
|
||||
showError(w, fmt.Sprintf("Authorization failed: %s - %s", errorParam, errorDesc))
|
||||
return
|
||||
}
|
||||
|
||||
if code == "" {
|
||||
showError(w, "No authorization code received")
|
||||
return
|
||||
}
|
||||
|
||||
if state != config.State {
|
||||
showError(w, fmt.Sprintf("State mismatch. Expected: %s, Got: %s", config.State, state))
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Received authorization code: %s", code)
|
||||
log.Printf("Exchanging code for token...")
|
||||
|
||||
tokenResp, err := exchangeToken(config, code)
|
||||
if err != nil {
|
||||
showError(w, fmt.Sprintf("Token exchange failed: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
showSuccess(w, code, tokenResp, serverOpts)
|
||||
|
||||
if !serverOpts.KeepRunning {
|
||||
// Schedule graceful shutdown after giving time for the response to be sent
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
cancel()
|
||||
}()
|
||||
}
|
||||
})
|
||||
|
||||
server = &http.Server{
|
||||
Addr: ":9876",
|
||||
Handler: mux,
|
||||
ReadTimeout: 5 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
log.Printf("Starting OAuth2 test server on http://localhost:9876")
|
||||
log.Printf("Waiting for callback at %s", config.RedirectURI)
|
||||
if !serverOpts.KeepRunning {
|
||||
log.Printf("Server will shut down automatically after successful authorization")
|
||||
}
|
||||
|
||||
// Start server in a goroutine
|
||||
go func() {
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("Server failed: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for context cancellation
|
||||
<-ctx.Done()
|
||||
|
||||
// Graceful shutdown
|
||||
log.Printf("Shutting down server...")
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer shutdownCancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("Server shutdown error: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("Server stopped successfully")
|
||||
}
|
||||
|
||||
func exchangeToken(config *Config, code string) (*TokenResponse, error) {
|
||||
data := url.Values{}
|
||||
data.Set("grant_type", "authorization_code")
|
||||
data.Set("code", code)
|
||||
data.Set("client_id", config.ClientID)
|
||||
data.Set("client_secret", config.ClientSecret)
|
||||
data.Set("code_verifier", config.CodeVerifier)
|
||||
data.Set("redirect_uri", config.RedirectURI)
|
||||
|
||||
ctx := context.Background()
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", config.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{Timeout: 10 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var tokenResp TokenResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
|
||||
return nil, xerrors.Errorf("failed to decode response: %w", err)
|
||||
}
|
||||
|
||||
if tokenResp.Error != "" {
|
||||
return nil, xerrors.Errorf("token error: %s - %s", tokenResp.Error, tokenResp.ErrorDesc)
|
||||
}
|
||||
|
||||
return &tokenResp, nil
|
||||
}
|
||||
|
||||
func showError(w http.ResponseWriter, message string) {
|
||||
log.Printf("ERROR: %s", message)
|
||||
html := fmt.Sprintf(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>OAuth2 Test - Error</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
|
||||
.status { padding: 20px; margin: 20px 0; border-radius: 5px; }
|
||||
.error { background: #f8d7da; color: #721c24; }
|
||||
pre { background: #f5f5f5; padding: 15px; overflow-x: auto; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>OAuth2 Test Server - Error</h1>
|
||||
<div class="status error">
|
||||
<h2>❌ Error</h2>
|
||||
<p>%s</p>
|
||||
</div>
|
||||
<p>Check the server logs for more details.</p>
|
||||
</body>
|
||||
</html>`, message)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = fmt.Fprint(w, html)
|
||||
}
|
||||
|
||||
func showSuccess(w http.ResponseWriter, code string, tokenResp *TokenResponse, opts ServerOptions) {
|
||||
log.Printf("SUCCESS: Token exchange completed")
|
||||
tokenJSON, _ := json.MarshalIndent(tokenResp, "", " ")
|
||||
|
||||
serverNote := "The server will shut down automatically in a few seconds."
|
||||
if opts.KeepRunning {
|
||||
serverNote = "The server will continue running. Press Ctrl+C in the terminal to stop it."
|
||||
}
|
||||
|
||||
html := fmt.Sprintf(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>OAuth2 Test - Success</title>
|
||||
<style>
|
||||
body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; }
|
||||
.status { padding: 20px; margin: 20px 0; border-radius: 5px; }
|
||||
.success { background: #d4edda; color: #155724; }
|
||||
pre { background: #f5f5f5; padding: 15px; overflow-x: auto; }
|
||||
.section { margin: 20px 0; }
|
||||
code { background: #e9ecef; padding: 2px 4px; border-radius: 3px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>OAuth2 Test Server - Success</h1>
|
||||
<div class="status success">
|
||||
<h2>Authorization Successful!</h2>
|
||||
<p>Successfully exchanged authorization code for tokens.</p>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>Authorization Code</h3>
|
||||
<pre>%s</pre>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>Token Response</h3>
|
||||
<pre>%s</pre>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h3>Next Steps</h3>
|
||||
<p>You can now use the access token to make API requests:</p>
|
||||
<pre>curl -H "Coder-Session-Token: %s" %s/api/v2/users/me | jq .</pre>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<p><strong>Note:</strong> %s</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`, code, string(tokenJSON), tokenResp.AccessToken, cmp.Or(os.Getenv("BASE_URL"), "http://localhost:3000"), serverNote)
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = fmt.Fprint(w, html)
|
||||
}
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Setup OAuth2 test app and return credentials
|
||||
# Usage: eval $(./setup-test-app.sh)
|
||||
|
||||
SESSION_TOKEN="${SESSION_TOKEN:-$(tr -d '\n' <./.coderv2/session || echo '')}"
|
||||
BASE_URL="${BASE_URL:-http://localhost:3000}"
|
||||
|
||||
if [ -z "$SESSION_TOKEN" ]; then
|
||||
echo "ERROR: SESSION_TOKEN must be set or ./.coderv2/session must exist" >&2
|
||||
echo "Run: ./scripts/coder-dev.sh login" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
AUTH_HEADER="Coder-Session-Token: $SESSION_TOKEN"
|
||||
|
||||
# Create OAuth2 App
|
||||
APP_NAME="test-mcp-$(date +%s)"
|
||||
APP_RESPONSE=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps" \
|
||||
-H "$AUTH_HEADER" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"name\": \"$APP_NAME\",
|
||||
\"callback_url\": \"http://localhost:9876/callback\"
|
||||
}")
|
||||
|
||||
CLIENT_ID=$(echo "$APP_RESPONSE" | jq -r '.id')
|
||||
if [ "$CLIENT_ID" = "null" ] || [ -z "$CLIENT_ID" ]; then
|
||||
echo "ERROR: Failed to create OAuth2 app" >&2
|
||||
echo "$APP_RESPONSE" | jq . >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create Client Secret
|
||||
SECRET_RESPONSE=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$CLIENT_ID/secrets" \
|
||||
-H "$AUTH_HEADER")
|
||||
|
||||
CLIENT_SECRET=$(echo "$SECRET_RESPONSE" | jq -r '.client_secret_full')
|
||||
if [ "$CLIENT_SECRET" = "null" ] || [ -z "$CLIENT_SECRET" ]; then
|
||||
echo "ERROR: Failed to create client secret" >&2
|
||||
echo "$SECRET_RESPONSE" | jq . >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Output environment variable exports
|
||||
echo "export CLIENT_ID=\"$CLIENT_ID\""
|
||||
echo "export CLIENT_SECRET=\"$CLIENT_SECRET\""
|
||||
echo "export APP_NAME=\"$APP_NAME\""
|
||||
echo "export BASE_URL=\"$BASE_URL\""
|
||||
echo "export SESSION_TOKEN=\"$SESSION_TOKEN\""
|
||||
|
||||
echo "# OAuth2 app created successfully:" >&2
|
||||
echo "# App Name: $APP_NAME" >&2
|
||||
echo "# Client ID: $CLIENT_ID" >&2
|
||||
echo "# Run: eval \$(./setup-test-app.sh) to set environment variables" >&2
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Manual OAuth2 flow test with automatic callback handling
|
||||
# Usage: ./test-manual-flow.sh
|
||||
|
||||
SESSION_TOKEN="${SESSION_TOKEN:-$(cat ./.coderv2/session 2>/dev/null || echo '')}"
|
||||
BASE_URL="${BASE_URL:-http://localhost:3000}"
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
# Colors for output
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Cleanup function
|
||||
cleanup() {
|
||||
if [ -n "$SERVER_PID" ]; then
|
||||
echo -e "\n${YELLOW}Stopping OAuth2 test server...${NC}"
|
||||
kill "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
|
||||
# Check if app credentials are set
|
||||
if [ -z "$CLIENT_ID" ] || [ -z "$CLIENT_SECRET" ]; then
|
||||
echo -e "${RED}ERROR: CLIENT_ID and CLIENT_SECRET must be set${NC}"
|
||||
echo "Run: eval \$(./setup-test-app.sh) first"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if Go is installed
|
||||
if ! command -v go &>/dev/null; then
|
||||
echo -e "${RED}ERROR: Go is not installed${NC}"
|
||||
echo "Please install Go to use the OAuth2 test server"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Generate PKCE parameters
|
||||
CODE_VERIFIER=$(openssl rand -base64 32 | tr -d "=+/" | cut -c -43)
|
||||
export CODE_VERIFIER
|
||||
CODE_CHALLENGE=$(echo -n "$CODE_VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_')
|
||||
export CODE_CHALLENGE
|
||||
|
||||
# Generate state parameter
|
||||
STATE=$(openssl rand -hex 16)
|
||||
export STATE
|
||||
|
||||
# Export required environment variables
|
||||
export CLIENT_ID
|
||||
export CLIENT_SECRET
|
||||
export BASE_URL
|
||||
|
||||
# Start the OAuth2 test server
|
||||
echo -e "${YELLOW}Starting OAuth2 test server on http://localhost:9876${NC}"
|
||||
go run "$SCRIPT_DIR/oauth2-test-server.go" &
|
||||
SERVER_PID=$!
|
||||
|
||||
# Wait for server to start
|
||||
sleep 1
|
||||
|
||||
# Build authorization URL
|
||||
AUTH_URL="$BASE_URL/oauth2/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http://localhost:9876/callback&state=$STATE&code_challenge=$CODE_CHALLENGE&code_challenge_method=S256"
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}=== Manual OAuth2 Flow Test ===${NC}"
|
||||
echo ""
|
||||
echo "1. Open this URL in your browser:"
|
||||
echo -e "${YELLOW}$AUTH_URL${NC}"
|
||||
echo ""
|
||||
echo "2. Log in if required, then click 'Allow' to authorize the application"
|
||||
echo ""
|
||||
echo "3. You'll be automatically redirected to the test server"
|
||||
echo " The server will handle the token exchange and display the results"
|
||||
echo ""
|
||||
echo -e "${YELLOW}Waiting for OAuth2 callback...${NC}"
|
||||
echo "Press Ctrl+C to cancel"
|
||||
echo ""
|
||||
|
||||
# Wait for the server process
|
||||
wait $SERVER_PID
|
||||
Executable
+180
@@ -0,0 +1,180 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
# Configuration
|
||||
SESSION_TOKEN="${SESSION_TOKEN:-$(cat ./.coderv2/session 2>/dev/null || echo '')}"
|
||||
BASE_URL="${BASE_URL:-http://localhost:3000}"
|
||||
|
||||
# Colors for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[0;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Check prerequisites
|
||||
if [ -z "$SESSION_TOKEN" ]; then
|
||||
echo -e "${RED}ERROR: SESSION_TOKEN must be set or ./.coderv2/session must exist${NC}"
|
||||
echo "Usage: SESSION_TOKEN=xxx ./test-mcp-oauth2.sh"
|
||||
echo "Or run: ./scripts/coder-dev.sh login"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Use session token for authentication
|
||||
AUTH_HEADER="Coder-Session-Token: $SESSION_TOKEN"
|
||||
|
||||
echo -e "${BLUE}=== MCP OAuth2 Phase 1 Complete Test Suite ===${NC}\n"
|
||||
|
||||
# Test 1: Metadata endpoint
|
||||
echo -e "${YELLOW}Test 1: OAuth2 Authorization Server Metadata${NC}"
|
||||
METADATA=$(curl -s "$BASE_URL/.well-known/oauth-authorization-server")
|
||||
echo "$METADATA" | jq .
|
||||
|
||||
if echo "$METADATA" | jq -e '.authorization_endpoint' >/dev/null; then
|
||||
echo -e "${GREEN}✓ Metadata endpoint working${NC}\n"
|
||||
else
|
||||
echo -e "${RED}✗ Metadata endpoint failed${NC}\n"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create OAuth2 App
|
||||
echo -e "${YELLOW}Creating OAuth2 app...${NC}"
|
||||
APP_NAME="test-mcp-$(date +%s)"
|
||||
APP_RESPONSE=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps" \
|
||||
-H "$AUTH_HEADER" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"name\": \"$APP_NAME\",
|
||||
\"callback_url\": \"http://localhost:9876/callback\"
|
||||
}")
|
||||
|
||||
if ! CLIENT_ID=$(echo "$APP_RESPONSE" | jq -r '.id'); then
|
||||
echo -e "${RED}Failed to create app:${NC}"
|
||||
echo "$APP_RESPONSE" | jq .
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${GREEN}✓ Created app: $APP_NAME (ID: $CLIENT_ID)${NC}"
|
||||
|
||||
# Create Client Secret
|
||||
echo -e "${YELLOW}Creating client secret...${NC}"
|
||||
SECRET_RESPONSE=$(curl -s -X POST "$BASE_URL/api/v2/oauth2-provider/apps/$CLIENT_ID/secrets" \
|
||||
-H "$AUTH_HEADER")
|
||||
|
||||
CLIENT_SECRET=$(echo "$SECRET_RESPONSE" | jq -r '.client_secret_full')
|
||||
echo -e "${GREEN}✓ Created client secret${NC}\n"
|
||||
|
||||
# Test 2: PKCE Flow
|
||||
echo -e "${YELLOW}Test 2: PKCE Flow${NC}"
|
||||
CODE_VERIFIER=$(openssl rand -base64 32 | tr -d "=+/" | cut -c -43)
|
||||
CODE_CHALLENGE=$(echo -n "$CODE_VERIFIER" | openssl dgst -sha256 -binary | base64 | tr -d "=" | tr '+/' '-_')
|
||||
STATE=$(openssl rand -hex 16)
|
||||
|
||||
AUTH_URL="$BASE_URL/oauth2/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http://localhost:9876/callback&state=$STATE&code_challenge=$CODE_CHALLENGE&code_challenge_method=S256"
|
||||
|
||||
REDIRECT_URL=$(curl -s -X POST "$AUTH_URL" \
|
||||
-H "Coder-Session-Token: $SESSION_TOKEN" \
|
||||
-w '\n%{redirect_url}' \
|
||||
-o /dev/null)
|
||||
|
||||
CODE=$(echo "$REDIRECT_URL" | grep -oP 'code=\K[^&]+')
|
||||
|
||||
if [ -n "$CODE" ]; then
|
||||
echo -e "${GREEN}✓ Got authorization code with PKCE${NC}"
|
||||
else
|
||||
echo -e "${RED}✗ Failed to get authorization code${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Exchange with PKCE
|
||||
TOKEN_RESPONSE=$(curl -s -X POST "$BASE_URL/oauth2/tokens" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "grant_type=authorization_code" \
|
||||
-d "code=$CODE" \
|
||||
-d "client_id=$CLIENT_ID" \
|
||||
-d "client_secret=$CLIENT_SECRET" \
|
||||
-d "code_verifier=$CODE_VERIFIER")
|
||||
|
||||
if echo "$TOKEN_RESPONSE" | jq -e '.access_token' >/dev/null; then
|
||||
echo -e "${GREEN}✓ PKCE token exchange successful${NC}\n"
|
||||
else
|
||||
echo -e "${RED}✗ PKCE token exchange failed:${NC}"
|
||||
echo "$TOKEN_RESPONSE" | jq .
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Test 3: Invalid PKCE
|
||||
echo -e "${YELLOW}Test 3: Invalid PKCE (negative test)${NC}"
|
||||
# Get new code
|
||||
REDIRECT_URL=$(curl -s -X POST "$AUTH_URL" \
|
||||
-H "Coder-Session-Token: $SESSION_TOKEN" \
|
||||
-w '\n%{redirect_url}' \
|
||||
-o /dev/null)
|
||||
CODE=$(echo "$REDIRECT_URL" | grep -oP 'code=\K[^&]+')
|
||||
|
||||
ERROR_RESPONSE=$(curl -s -X POST "$BASE_URL/oauth2/tokens" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "grant_type=authorization_code" \
|
||||
-d "code=$CODE" \
|
||||
-d "client_id=$CLIENT_ID" \
|
||||
-d "client_secret=$CLIENT_SECRET" \
|
||||
-d "code_verifier=wrong-verifier")
|
||||
|
||||
if echo "$ERROR_RESPONSE" | jq -e '.error' >/dev/null; then
|
||||
echo -e "${GREEN}✓ Invalid PKCE correctly rejected${NC}\n"
|
||||
else
|
||||
echo -e "${RED}✗ Invalid PKCE was not rejected${NC}\n"
|
||||
fi
|
||||
|
||||
# Test 4: Resource Parameter
|
||||
echo -e "${YELLOW}Test 4: Resource Parameter Support${NC}"
|
||||
RESOURCE="https://api.example.com"
|
||||
STATE=$(openssl rand -hex 16)
|
||||
RESOURCE_AUTH_URL="$BASE_URL/oauth2/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http://localhost:9876/callback&state=$STATE&resource=$RESOURCE"
|
||||
|
||||
REDIRECT_URL=$(curl -s -X POST "$RESOURCE_AUTH_URL" \
|
||||
-H "Coder-Session-Token: $SESSION_TOKEN" \
|
||||
-w '\n%{redirect_url}' \
|
||||
-o /dev/null)
|
||||
|
||||
CODE=$(echo "$REDIRECT_URL" | grep -oP 'code=\K[^&]+')
|
||||
|
||||
TOKEN_RESPONSE=$(curl -s -X POST "$BASE_URL/oauth2/tokens" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "grant_type=authorization_code" \
|
||||
-d "code=$CODE" \
|
||||
-d "client_id=$CLIENT_ID" \
|
||||
-d "client_secret=$CLIENT_SECRET" \
|
||||
-d "resource=$RESOURCE")
|
||||
|
||||
if echo "$TOKEN_RESPONSE" | jq -e '.access_token' >/dev/null; then
|
||||
echo -e "${GREEN}✓ Resource parameter flow successful${NC}\n"
|
||||
else
|
||||
echo -e "${RED}✗ Resource parameter flow failed${NC}\n"
|
||||
fi
|
||||
|
||||
# Test 5: Token Refresh
|
||||
echo -e "${YELLOW}Test 5: Token Refresh${NC}"
|
||||
REFRESH_TOKEN=$(echo "$TOKEN_RESPONSE" | jq -r '.refresh_token')
|
||||
|
||||
REFRESH_RESPONSE=$(curl -s -X POST "$BASE_URL/oauth2/tokens" \
|
||||
-H "Content-Type: application/x-www-form-urlencoded" \
|
||||
-d "grant_type=refresh_token" \
|
||||
-d "refresh_token=$REFRESH_TOKEN" \
|
||||
-d "client_id=$CLIENT_ID" \
|
||||
-d "client_secret=$CLIENT_SECRET")
|
||||
|
||||
if echo "$REFRESH_RESPONSE" | jq -e '.access_token' >/dev/null; then
|
||||
echo -e "${GREEN}✓ Token refresh successful${NC}\n"
|
||||
else
|
||||
echo -e "${RED}✗ Token refresh failed${NC}\n"
|
||||
fi
|
||||
|
||||
# Cleanup
|
||||
echo -e "${YELLOW}Cleaning up...${NC}"
|
||||
curl -s -X DELETE "$BASE_URL/api/v2/oauth2-provider/apps/$CLIENT_ID" \
|
||||
-H "$AUTH_HEADER" >/dev/null
|
||||
|
||||
echo -e "${GREEN}✓ Deleted test app${NC}"
|
||||
|
||||
echo -e "\n${BLUE}=== All tests completed successfully! ===${NC}"
|
||||
Reference in New Issue
Block a user