oauth

package module
v0.1.46 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2025 License: Apache-2.0 Imports: 17 Imported by: 11 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

mcp-oauth - OAuth 2.1 Authorization Server

A provider-agnostic library for implementing OAuth 2.1 Authorization Servers for Model Context Protocol (MCP) servers, with support for multiple identity providers.

✨ Key Features

πŸ”Œ Provider Abstraction
  • βœ… Google OAuth (built-in)
  • βœ… Easy to add custom providers
πŸ—„οΈ Storage Abstraction
  • βœ… In-memory (built-in, production-ready)
  • βœ… Simple interface to implement custom storage
πŸ”’ Security Features
  • Token encryption at rest (AES-256-GCM)
  • Security audit logging
  • Rate limiting (token bucket algorithm)
  • PKCE enforcement (S256 only)
  • Refresh token rotation (OAuth 2.1)
  • CORS support for browser-based clients

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Your MCP App  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
    β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”
    β”‚ Handler  β”‚  (HTTP layer)
    β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
         β”‚
    β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”
    β”‚  Server  β”‚  (Business logic)
    β””β”€β”€β”¬β”€β”€β”€β”¬β”€β”€β”€β”˜
       β”‚   β”‚
   β”Œβ”€β”€β”€β–Όβ” β”Œβ–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚Pro-β”‚ β”‚ Storage β”‚
   β”‚viderβ”‚ β”‚         β”‚
   β””β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Clean Separation:

  • Handler: HTTP request/response handling
  • Server: OAuth business logic (provider-agnostic)
  • Provider: Identity provider integration (Google, or custom)
  • Storage: Token/client/flow storage (in-memory, or custom)

πŸš€ Quick Start

Build an OAuth 2.1 Authorization Server for your MCP server:

package main

import (
    "log"
    "net/http"
    "os"

    oauth "github.com/giantswarm/mcp-oauth"
    "github.com/giantswarm/mcp-oauth/providers/google"
    "github.com/giantswarm/mcp-oauth/storage/memory"
)

func main() {
    // 1. Choose a provider (Google in this example)
    provider, _ := google.NewProvider(&google.Config{
        ClientID:     os.Getenv("GOOGLE_CLIENT_ID"),
        ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
        RedirectURL:  "http://localhost:8080/oauth/callback",
        Scopes:       []string{"openid", "email", "profile"},
    })

    // 2. Choose storage (in-memory is fine for most use cases)
    store := memory.New()
    defer store.Stop()

    // 3. Create OAuth server
    server, _ := oauth.NewServer(
        provider,
        store, // TokenStore
        store, // ClientStore
        store, // FlowStore
        &oauth.ServerConfig{
            Issuer: "http://localhost:8080",
        },
        nil, // logger (optional)
    )

    // 4. Create HTTP handler
    handler := oauth.NewHandler(server, nil)

    // 5. Setup routes
    mux := http.NewServeMux()
    
    // Register Protected Resource Metadata endpoints (root + sub-path)
    handler.RegisterProtectedResourceMetadataRoutes(mux, "/mcp")
    
    // Protected MCP endpoint
    mux.Handle("/mcp", handler.ValidateToken(yourMCPHandler))

    http.ListenAndServe(":8080", mux)
}

πŸ“¦ Installation

go get github.com/giantswarm/mcp-oauth

πŸ”Œ Providers

Google
import "github.com/giantswarm/mcp-oauth/providers/google"

provider, err := google.NewProvider(&google.Config{
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",
    RedirectURL:  "https://yourdomain.com/oauth/callback",
    Scopes: []string{
        "openid",
        "email",
        "https://www.googleapis.com/auth/gmail.readonly",
    },
})
Custom Provider

Implement the providers.Provider interface:

type Provider interface {
    Name() string
    AuthorizationURL(state string, opts *AuthOptions) string
    ExchangeCode(ctx context.Context, code string, opts *ExchangeOptions) (*TokenResponse, error)
    ValidateToken(ctx context.Context, accessToken string) (*UserInfo, error)
    RefreshToken(ctx context.Context, refreshToken string) (*TokenResponse, error)
    RevokeToken(ctx context.Context, token string) error
}

πŸ—„οΈ Storage

In-Memory (Built-in)

Perfect for most use cases:

import "github.com/giantswarm/mcp-oauth/storage/memory"

store := memory.New()
defer store.Stop() // Cleanup background goroutines

server, _ := oauth.NewServer(
    provider,
    store, // TokenStore
    store, // ClientStore
    store, // FlowStore
    config,
    logger,
)
Custom Storage

Implement the storage interfaces:

import "golang.org/x/oauth2"

type TokenStore interface {
    SaveToken(userID string, token *oauth2.Token) error
    GetToken(userID string) (*oauth2.Token, error)
    DeleteToken(userID string) error
    // ... more methods
}

πŸ”’ Security

πŸ“– For comprehensive security documentation, see SECURITY_ARCHITECTURE.md
This document explains the two-layer PKCE architecture, attack mitigation strategies, and production deployment best practices.

πŸ›‘οΈ Secure by Default

This library follows the secure-by-default principle. All security features are enabled out of the box:

βœ… PKCE Required - Mandatory PKCE (S256 only) for all authorization flows (OAuth 2.1)
βœ… Refresh Token Rotation - Automatic token rotation with reuse detection (OAuth 2.1)
βœ… S256 Only - Rejects insecure 'plain' PKCE method
βœ… No Proxy Trust - Doesn't trust X-Forwarded-For headers by default
βœ… Rate Limiting - Built-in protection against abuse

No configuration needed for secure defaults! Just create your server:

server, _ := oauth.NewServer(
    provider, tokenStore, clientStore, flowStore,
    &oauth.ServerConfig{
        Issuer: "https://your-domain.com",
        // All security features enabled by default!
    },
    logger,
)
πŸ”§ Supporting Legacy Clients

If you need to support older clients that don't support PKCE or S256:

server, _ := oauth.NewServer(
    provider, tokenStore, clientStore, flowStore,
    &oauth.ServerConfig{
        Issuer: "https://your-domain.com",
        
        // ⚠️  WARNING: Only enable for backward compatibility
        RequirePKCE: false,        // Allow clients without PKCE
        AllowPKCEPlain: true,      // Allow 'plain' method (not recommended)
    },
    logger,
)
// The server will log security warnings when you use less secure options

Important: The server logs clear warnings when security features are weakened.

WWW-Authenticate Header & Protected Resource Discovery

The library implements MCP 2025-11-25 specification for Protected Resource Metadata discovery via WWW-Authenticate headers. When enabled, all 401 Unauthorized responses include enhanced headers that help clients discover the authorization server and required scopes.

Configuration:

config := &server.Config{
    Issuer: "https://your-domain.com",
    
    // MCP 2025-11-25 compliant WWW-Authenticate headers are enabled by default
    // Only set to true if you need backward compatibility with legacy clients
    // DisableWWWAuthenticateMetadata: false,  // (default: false = enabled, secure)
    
    // Optional: Configure default scopes to advertise in 401 challenges
    DefaultChallengeScopes: []string{"mcp:access", "files:read"},
}

Example Response:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://auth.example.com/.well-known/oauth-protected-resource",
                         scope="mcp:access files:read",
                         error="invalid_token",
                         error_description="Token has expired"

Security Considerations:

  • Information Disclosure: The resource_metadata URL and configured scopes are intentionally public information per OAuth 2.0/MCP specifications. This is similar to the existing metadata endpoint exposure and is required for proper OAuth discovery.
  • Scope Configuration: Review your DefaultChallengeScopes carefully. Don't include overly specific scopes that could aid attackers in reconnaissance. Use broad, general scopes like "mcp:access" rather than "internal:admin:full_access".
  • Backward Compatibility: Set DisableWWWAuthenticateMetadata: true only if you need compatibility with legacy OAuth clients that may not understand enhanced WWW-Authenticate parameters. Modern OAuth clients ignore parameters they don't understand, so the default (enabled) is safe for most deployments.
  • Header Size Limits: If configuring many scopes, be aware that some proxies/servers have HTTP header size limits (typically 8KB). The library will log warnings if you exceed 50 scopes.

Specification Compliance:

  • RFC 6750 Section 3: Bearer token challenge format
  • RFC 9728: Protected Resource Metadata discovery
  • MCP 2025-11-25: MUST include resource_metadata in WWW-Authenticate
Token Encryption
import "github.com/giantswarm/mcp-oauth/security"

// Generate encryption key (do once, store securely)
key, _ := security.GenerateKey()

encryptor, _ := security.NewEncryptor(key)
server.SetEncryptor(encryptor)
Audit Logging
auditor := security.NewAuditor(logger, true)
server.SetAuditor(auditor)

// Now all security events are logged:
// - Token issued/refreshed/revoked
// - Authentication failures
// - Rate limit violations
// - Security configuration warnings
Token Validation & Proactive Refresh

The server can proactively refresh provider tokens when they're near expiry, preventing validation failures and improving user experience:

&oauth.ServerConfig{
    // Proactive token refresh threshold (default: 300 seconds = 5 minutes)
    // When a token will expire within this window and has a refresh token,
    // ValidateToken will attempt to refresh it before validation
    TokenRefreshThreshold: 300,
    
    // Clock skew grace period (default: 5 seconds)
    // Prevents false expiration errors due to clock synchronization issues
    ClockSkewGracePeriod: 5,
}

How Proactive Refresh Works:

  1. During token validation, if the token will expire within TokenRefreshThreshold
  2. AND the token has a refresh token available
  3. The server attempts to refresh it with the provider (Google, GitHub, etc.)
  4. On success: Updated token is saved, validation continues seamlessly
  5. On failure: Gracefully falls back to normal validation (no error to user)

Benefits:

  • Better UX: Users don't see "token expired" errors when refresh is possible
  • Fewer API calls: Reduces failed validation attempts
  • Configurable: Adjust threshold based on your token lifetimes and usage patterns
  • Graceful fallback: Refresh failures don't break the validation flow

Example scenarios:

// Default 5 minute threshold - good for most use cases
TokenRefreshThreshold: 300

// Longer threshold for high-security apps (more frequent refresh)
TokenRefreshThreshold: 600  // 10 minutes

// Shorter threshold for low-latency requirements
TokenRefreshThreshold: 60   // 1 minute
CORS Support for Browser-Based Clients

Enable CORS (Cross-Origin Resource Sharing) to allow browser-based MCP clients to use your OAuth server:

server, _ := oauth.NewServer(
    provider, tokenStore, clientStore, flowStore,
    &oauth.ServerConfig{
        Issuer: "https://your-domain.com",
        
        // Configure CORS for browser clients
        CORS: server.CORSConfig{
            // List of allowed origins
            AllowedOrigins: []string{
                "https://app.example.com",
                "https://dashboard.example.com",
            },
            // Enable credentials (cookies, Bearer tokens)
            AllowCredentials: true,
            // Preflight cache duration (seconds)
            MaxAge: 3600,
        },
    },
    logger,
)

// Don't forget to handle OPTIONS preflight requests:
http.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) {
    if r.Method == http.MethodOptions {
        handler.ServePreflightRequest(w, r)
        return
    }
    handler.ServeToken(w, r)
})

CORS Configuration Options:

  • AllowedOrigins: List of allowed origin URLs. Empty list disables CORS (default, secure).
  • AllowCredentials: Set to true to allow cookies and authorization headers (needed for OAuth).
  • MaxAge: How long (in seconds) browsers can cache preflight responses (default: 3600).

⚠️ Security Warning: Wildcard Origins

CORS: server.CORSConfig{
    AllowedOrigins: []string{"*"},  // ⚠️  NOT RECOMMENDED for production!
}

Using wildcard * allows any website to make requests to your OAuth server, enabling potential CSRF attacks. Only use specific origins in production.

How It Works:

  1. Browser sends OPTIONS preflight request before actual request
  2. Server checks if origin is in AllowedOrigins
  3. If allowed, sets CORS headers (Access-Control-Allow-Origin, etc.)
  4. Browser proceeds with actual request
  5. Server sets CORS headers on actual response too

CORS is opt-in and disabled by default for security. Only enable it if you have browser-based clients.

Rate Limiting
IP-Based Rate Limiting

Protects against brute force attacks and DoS from specific IPs:

ipRateLimiter := security.NewRateLimiter(
    10,    // 10 requests/second per IP
    20,    // burst of 20
    logger,
)
defer ipRateLimiter.Stop() // Important: cleanup background goroutines
server.SetRateLimiter(ipRateLimiter)
User-Based Rate Limiting

Additional rate limiting for authenticated users (applies after authentication):

userRateLimiter := security.NewRateLimiter(
    100,   // 100 requests/second per user (higher than IP limit)
    200,   // burst of 200
    logger,
)
defer userRateLimiter.Stop() // Important: cleanup background goroutines
server.SetUserRateLimiter(userRateLimiter)
Client Registration Rate Limiting

Prevents resource exhaustion through repeated client registration/deletion cycles:

clientRegRateLimiter := security.NewClientRegistrationRateLimiter(logger)
defer clientRegRateLimiter.Stop() // Important: cleanup background goroutines
server.SetClientRegistrationRateLimiter(clientRegRateLimiter)

// Or with custom configuration:
clientRegRateLimiter := security.NewClientRegistrationRateLimiterWithConfig(
    10,              // max registrations per window
    time.Hour,       // time window
    10000,           // max IPs to track (memory bound)
    logger,
)
defer clientRegRateLimiter.Stop()
server.SetClientRegistrationRateLimiter(clientRegRateLimiter)

Rate Limiter Configuration via Server Config:

&oauth.ServerConfig{
    // Time-windowed client registration limits
    MaxRegistrationsPerHour: 10,        // default: 10 per IP per hour
    RegistrationRateLimitWindow: 3600,  // default: 3600 seconds (1 hour)
    
    // Static limit (complementary to rate limiting)
    MaxClientsPerIP: 10,                // max total active clients per IP
}

Security Benefits:

  • IP-based limiting prevents unauthenticated abuse
  • User-based limiting prevents authenticated abuse
  • Client registration limiting prevents registration/deletion cycle DoS
  • Layered defense: all limits are enforced independently
  • Time-windowed tracking prevents circumvention via deletion

Important Lifecycle Management: All rate limiters run background cleanup goroutines. Always call Stop() when shutting down:

// Proper cleanup prevents goroutine leaks
defer ipRateLimiter.Stop()
defer userRateLimiter.Stop()
defer clientRegRateLimiter.Stop()
Client Registration Protection

The AllowPublicClientRegistration configuration controls two security aspects:

  1. DCR Endpoint Authentication: Whether the /oauth/register endpoint requires a Bearer token
  2. Public Client Creation: Whether public clients (native apps with token_endpoint_auth_method: "none") can be registered

Secure Production Configuration (Recommended):

&oauth.ServerConfig{
    // SECURE: Require authentication AND deny public client creation
    AllowPublicClientRegistration: false,
    
    // Registration access token (share only with trusted developers)
    RegistrationAccessToken: "your-secure-token-here", // Use: openssl rand -base64 32
    
    // Limit registrations per IP
    MaxClientsPerIP: 10,
}

With this configuration:

  • Only authenticated requests (with valid token) can access /oauth/register
  • Only confidential clients (with secrets) can be created
  • Public clients are denied even with valid authentication

Development/Native App Configuration:

&oauth.ServerConfig{
    // PERMISSIVE: Allow unauthenticated registration AND public clients
    AllowPublicClientRegistration: true,
    
    // Still recommended: limit per-IP to prevent abuse
    MaxClientsPerIP: 10,
}

With this configuration:

  • Anyone can register clients (⚠️ DoS risk - use only in trusted environments)
  • Both confidential AND public clients can be created

Registering Clients:

Confidential client (server-side app with secret):

curl -X POST https://your-server.com/oauth/register \
  -H "Authorization: Bearer your-registration-token" \
  -H "Content-Type: application/json" \
  -d '{
    "client_name": "My Web App",
    "redirect_uris": ["https://myapp.com/callback"],
    "token_endpoint_auth_method": "client_secret_basic"
  }'

Public client (native/CLI app, requires AllowPublicClientRegistration: true):

curl -X POST https://your-server.com/oauth/register \
  -H "Authorization: Bearer your-registration-token" \
  -H "Content-Type: application/json" \
  -d '{
    "client_name": "My Native App",
    "redirect_uris": ["myapp://callback"],
    "token_endpoint_auth_method": "none"
  }'

Metadata Discovery & Security:

The registration endpoint is advertised in RFC 8414 Authorization Server Metadata (/.well-known/oauth-authorization-server) when client registration is enabled:

  • Included: When RegistrationAccessToken is set OR AllowPublicClientRegistration=true
  • Excluded: When neither is configured (endpoint effectively disabled)

This conditional advertising provides defense-in-depth:

  • RFC 8414-compliant clients can automatically discover the registration endpoint
  • The endpoint remains hidden in metadata when registration is disabled
  • Even if advertised, the endpoint enforces authentication via Bearer token
  • Multiple layers of protection: authentication, rate limiting, per-IP limits, and audit logging

Security Note: Advertising the registration endpoint in metadata does NOT weaken security. The endpoint itself enforces strict authentication (when AllowPublicClientRegistration=false), rate limiting, and audit logging. This is analogous to advertising the token endpoint - it's public information about available functionality, but access is strictly controlled.

Custom Redirect URI Schemes

Support for native/mobile apps with custom URI schemes:

&oauth.ServerConfig{
    // Allow custom schemes for native apps
    AllowedCustomSchemes: []string{
        "^myapp$",                  // Exact: myapp://
        "^com\\.example\\.",        // Prefix: com.example.*://
        "^[a-z][a-z0-9+.-]*$",      // RFC 3986 (default)
    },
}

Security: Dangerous schemes (javascript, data, file) are always blocked.

Proxy Configuration

When running behind a reverse proxy (nginx, HAProxy, etc.):

&oauth.ServerConfig{
    TrustProxy: true,         // Enable proxy header trust
    TrustedProxyCount: 2,     // Number of proxies (e.g., CloudFlare + nginx)
    // Extracts client IP from: ips[len(ips) - TrustedProxyCount - 1]
}

Security Notes:

  • Only enable TrustProxy when behind a properly configured trusted reverse proxy
  • Critical for Rate Limiting: IP-based rate limiting (including client registration limits) depends on accurate client IP extraction
  • Without proper proxy configuration, attackers can spoof X-Forwarded-For headers to bypass rate limits
  • Ensure your reverse proxy (nginx, HAProxy, CloudFlare, etc.) is configured to set X-Forwarded-For correctly

Example nginx configuration:

location / {
    proxy_pass http://oauth-server:8080;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
}

Rate Limiting Effectiveness: Rate limiting is only as secure as your IP extraction. If TrustProxy=false (default), the library uses the direct connection IP, which is most secure but may not work behind proxies. If TrustProxy=true, ensure your proxy infrastructure is properly configured and trusted.

πŸ“Š Observability & Instrumentation

The library provides comprehensive OpenTelemetry (OTEL) instrumentation for metrics, distributed tracing, and structured logging.

Quick Start

Enable instrumentation in your server configuration:

import "github.com/giantswarm/mcp-oauth/instrumentation"

// Enable instrumentation with Prometheus metrics
server, _ := oauth.NewServer(
    provider, tokenStore, clientStore, flowStore,
    &oauth.ServerConfig{
        Issuer: "https://your-domain.com",
        Instrumentation: oauth.InstrumentationConfig{
            Enabled:         true,
            ServiceName:     "my-oauth-server",
            ServiceVersion:  "1.0.0",
            MetricsExporter: "prometheus", // Export metrics for Prometheus
            TracesExporter:  "otlp",       // Export traces via OTLP
            OTLPEndpoint:    "localhost:4318", // OTLP collector endpoint
        },
    },
    logger,
)

// Expose Prometheus metrics endpoint
import "github.com/prometheus/client_golang/prometheus/promhttp"
http.Handle("/metrics", promhttp.Handler())
Exporter Configuration

The library supports multiple exporters for metrics and traces:

Metrics Exporters:

  • "prometheus" - Export metrics in Prometheus format (production recommended)
  • "stdout" - Print metrics to stdout (development/debugging)
  • "none" or "" - No metrics export (default, zero overhead)

Trace Exporters:

  • "otlp" - Export traces via OTLP HTTP (production recommended, requires OTLPEndpoint)
  • "stdout" - Print traces to stdout (development/debugging)
  • "none" or "" - No trace export (default, zero overhead)

Examples:

// Production: Prometheus + OTLP traces
Instrumentation: oauth.InstrumentationConfig{
    Enabled:         true,
    MetricsExporter: "prometheus",
    TracesExporter:  "otlp",
    OTLPEndpoint:    "jaeger:4318", // Or your OTLP collector
}

// Development: stdout exporters for local debugging
Instrumentation: oauth.InstrumentationConfig{
    Enabled:         true,
    MetricsExporter: "stdout",
    TracesExporter:  "stdout",
}

// Minimal: Only metrics, no tracing
Instrumentation: oauth.InstrumentationConfig{
    Enabled:         true,
    MetricsExporter: "prometheus",
    TracesExporter:  "none",
}
Available Metrics

HTTP Layer:

  • oauth.http.requests.total{method, endpoint, status} - Total HTTP requests
  • oauth.http.request.duration{endpoint} - Request duration (ms)

OAuth Flows:

  • oauth.authorization.started{client_id} - Authorization flows started
  • oauth.code.exchanged{client_id, pkce_method} - Authorization codes exchanged
  • oauth.token.refreshed{client_id, rotated} - Tokens refreshed
  • oauth.token.revoked{client_id} - Tokens revoked
  • oauth.client.registered{client_type} - Clients registered

Security:

  • oauth.rate_limit.exceeded{limiter_type} - Rate limit violations
  • oauth.pkce.validation_failed{method} - PKCE validation failures
  • oauth.code.reuse_detected - Authorization code reuse attempts
  • oauth.token.reuse_detected - Token reuse attempts

Storage:

  • storage.operation.total{operation, result} - Storage operations
  • storage.operation.duration{operation} - Operation duration (ms)

Provider:

  • provider.api.calls.total{provider, operation, status} - Provider API calls
  • provider.api.duration{provider, operation} - API call duration (ms)
  • provider.api.errors.total{provider, operation, error_type} - Provider API errors
Distributed Tracing

Spans are automatically created for all major operations:

http.request (from otelhttp)
β”œβ”€β”€ oauth.http.authorization
β”‚   └── oauth.server.start_authorization_flow
β”‚       β”œβ”€β”€ storage.save_authorization_state
β”‚       └── provider.google.authorization_url
└── oauth.http.callback
    └── oauth.server.handle_provider_callback
        β”œβ”€β”€ storage.get_authorization_state
        β”œβ”€β”€ provider.google.exchange_code
        └── storage.save_token
Performance
  • When disabled: Zero overhead (uses no-op providers)
  • When enabled: < 1% latency increase, ~1-2 MB memory for metric registry
  • Thread-safe concurrent access
  • Lock-free atomic operations for metrics
Privacy & Compliance

Data Collection:

When instrumentation is enabled, the following data may be collected in distributed traces and metrics:

  • Client IPs - For security monitoring and rate limit enforcement
  • Client IDs and User IDs - Non-sensitive identifiers for tracking OAuth flows
  • OAuth Flow Metadata - Scopes, PKCE methods, grant types, token types
  • Timing Information - Request durations, operation latencies
  • Error Information - Error codes and non-sensitive error descriptions

Security Guarantees:

βœ… Actual credentials are NEVER logged:

  • Access tokens, refresh tokens, authorization codes are never included in traces
  • Client secrets are never logged
  • Only metadata about tokens (type, expiry, family ID) is recorded

⚠️ GDPR and Privacy Considerations:

  • Client IP addresses may be considered Personally Identifiable Information (PII) in some jurisdictions
  • User IDs may be subject to privacy regulations depending on your implementation
  • Configure trace sampling and retention policies appropriately for your compliance requirements
  • Consider data minimization: disable instrumentation in regions with strict privacy laws if not needed

Recommendations:

  1. Review your jurisdiction's privacy laws before enabling instrumentation in production
  2. Configure appropriate trace sampling rates (e.g., 1% for high-volume systems)
  3. Set reasonable retention periods for traces (7-30 days recommended)
  4. Implement access controls on your observability infrastructure
  5. Document data collection in your privacy policy
  6. Consider using trace scrubbing/redaction for sensitive attributes

Example - Minimal Data Collection:

// For privacy-sensitive environments, keep instrumentation disabled
server, _ := oauth.NewServer(
    provider, tokenStore, clientStore, flowStore,
    &oauth.ServerConfig{
        Issuer: "https://your-domain.com",
        Instrumentation: oauth.InstrumentationConfig{
            Enabled: false, // No data collection
        },
    },
    logger,
)
Integration with Observability Backends

Prometheus: The Prometheus exporter is pull-based and works with the standard prometheus/client_golang library. Simply expose the /metrics endpoint and configure Prometheus to scrape it.

Jaeger/OpenTelemetry Collector: Use the OTLP trace exporter to send traces to Jaeger, Grafana Tempo, or any OTLP-compatible backend:

# Example: Run Jaeger with OTLP support
docker run -d --name jaeger \
  -p 16686:16686 \
  -p 4318:4318 \
  jaegertracing/all-in-one:latest

# Configure your OAuth server
OTLPEndpoint: "localhost:4318"
TracesExporter: "otlp"

See the instrumentation package documentation for full details.

πŸ“š Examples

See the examples directory:

πŸ§ͺ Testing

The architecture makes testing easy:

// Create a mock provider
type MockProvider struct{}

func (m *MockProvider) ValidateToken(ctx context.Context, token string) (*providers.UserInfo, error) {
    return &providers.UserInfo{
        ID:    "test-user",
        Email: "test@example.com",
    }, nil
}

// Use in tests
server, _ := oauth.NewServer(&MockProvider{}, mockStore, ...)

πŸ“œ License

Apache License 2.0

πŸ›‘οΈ Security Best Practices

Production Deployment Checklist

Before deploying to production, ensure:

  • βœ… HTTPS Required: Set Issuer to HTTPS URL
  • βœ… Token Encryption: Set EncryptionKey (32 bytes from secure source)
  • βœ… Audit Logging: Enable security audit logging
  • βœ… Rate Limiting: Configure IP, user, and client registration rate limits
  • βœ… Rate Limiter Cleanup: Call Stop() on all rate limiters during shutdown
  • βœ… PKCE Enforced: Keep RequirePKCE=true (default)
  • βœ… S256 Only: Keep AllowPKCEPlain=false (default)
  • βœ… Token Rotation: Keep AllowRefreshTokenRotation=true (default)
  • βœ… Registration Protected: Set RegistrationAccessToken or disable registration
  • βœ… Proxy Configured: Set TrustProxy and TrustedProxyCount if behind proxy
  • βœ… Proxy Headers: Verify reverse proxy correctly sets X-Forwarded-For (critical for rate limiting)
Security Warnings

The library logs clear warnings when security is weakened:

⚠️  SECURITY WARNING: PKCE is DISABLED
⚠️  SECURITY WARNING: Plain PKCE method is ALLOWED
⚠️  SECURITY WARNING: Public client registration is ENABLED

Always investigate and address security warnings before production deployment.

OAuth 2.1 Compliance

This library implements OAuth 2.1 security best practices:

  • PKCE Required: Mandatory for all flows (prevents code interception)
  • Refresh Token Rotation: Automatic token rotation with reuse detection
  • S256 Only: Rejects insecure 'plain' PKCE method
  • State Required: CSRF protection via state parameter
  • HTTPS Required: Production deployments must use HTTPS
Vulnerability Reporting

Report security vulnerabilities privately via GitHub Security Advisories or email:

  • See SECURITY.md for details
  • Do not file public issues for security vulnerabilities

🀝 Contributing

Contributions welcome! Especially:

  • New provider implementations
  • Storage implementations
  • Bug fixes and improvements
  • Security enhancements

Documentation ΒΆ

Overview ΒΆ

Package oauth provides OAuth 2.1 authentication for the MCP server.

This package implements OAuth 2.1 authentication according to the Model Context Protocol (MCP) specification dated 2025-06-18. The MCP server acts as an OAuth 2.1 Resource Server, using Google as the Authorization Server for secure authentication.

Architecture:

  • MCP Server: OAuth 2.1 Resource Server (validates Google tokens)
  • Google: OAuth 2.1 Authorization Server (issues tokens, handles user auth)
  • MCP Client: OAuth 2.1 Client (handles OAuth flow, includes tokens in requests)

Key Features:

  • Protected Resource Metadata (RFC 9728) - advertises Google as authorization server
  • Bearer token validation via Google's userinfo endpoint
  • Automatic token refresh with rotation (OAuth 2.1 security best practice)
  • Rate limiting per IP address and per user with token bucket algorithm
  • Secure token storage with optional AES-256-GCM encryption at rest
  • Token expiration handling with automatic cleanup
  • Token revocation endpoint (RFC 7009)
  • Comprehensive audit logging for security events
  • Client type enforcement (public vs confidential)
  • PKCE S256 enforcement (plain method disabled for security)
  • Integration with Google APIs (Gmail, Drive, Calendar, etc.)

Security Features (Production-Ready):

1. Token Encryption at Rest (AES-256-GCM):

  • Tokens can be encrypted in memory using AES-256-GCM
  • Authenticated encryption prevents tampering
  • Configure via Security.EncryptionKey (32 bytes)
  • Use GenerateEncryptionKey() or load from secure storage (KMS, Vault)

2. Refresh Token Rotation (OAuth 2.1):

  • New refresh token issued on each use
  • Old refresh token invalidated immediately
  • Detects stolen tokens via reuse detection
  • Enabled by default (disable via Security.DisableRefreshTokenRotation)

3. Comprehensive Audit Logging:

  • All authentication events logged with structured logging
  • Security events: failed auth, rate limits, invalid tokens, token reuse
  • All sensitive data (tokens, emails) hashed before logging (SHA-256)
  • Enabled by default (disable via Security.EnableAuditLogging=false)

4. Client Type Validation:

  • Public clients (mobile, SPA) must use "none" auth method
  • Confidential clients must use client_secret_basic or client_secret_post
  • Prevents security violations (confidential client without secret)

5. PKCE Security:

  • Only S256 method supported (plain method disabled per OAuth 2.1)
  • 43-128 character code_verifier enforced
  • Prevents authorization code interception attacks

6. Token Revocation (RFC 7009):

  • Clients can revoke access and refresh tokens
  • Client authentication required
  • All revocations logged for audit trail

7. Cryptographically Secure Token Generation:

  • All tokens generated using crypto/rand (not math/rand)
  • 48-byte access and refresh tokens (384 bits of entropy)
  • 32-byte client IDs and secrets

Security Considerations:

  • Token Storage: Tokens can be encrypted at rest with AES-256-GCM. Enable via Security.EncryptionKey for production deployments.
  • Logging: All sensitive data (tokens, emails, PII) is hashed before logging using SHA256 to prevent exposure in log files. Only use structured logging.
  • Clock Skew: A 5-second grace period is applied to token expiration checks to handle time synchronization issues between systems.
  • Refresh Token Protection: Tokens with valid refresh tokens are preserved even if the access token expires, allowing automatic renewal.
  • Rate Limiting: Per-IP and per-user rate limiting prevents brute force attacks and DoS attempts. Configure based on your threat model.

Compliance:

  • OAuth 2.1 Draft: Implements key security improvements
  • RFC 6749: OAuth 2.0 Authorization Framework
  • RFC 6750: Bearer Token Usage
  • RFC 7009: Token Revocation
  • RFC 7591: Dynamic Client Registration
  • RFC 7636: PKCE (S256 only)
  • RFC 8414: Authorization Server Metadata
  • RFC 9728: Protected Resource Metadata

The package is designed to be used by the MCP server's HTTP and SSE transports to add OAuth protection to their endpoints.

Example usage:

// Generate encryption key for production (do this once, store securely)
encKey, _ := oauth.GenerateEncryptionKey()
// Or load from environment: oauth.EncryptionKeyFromBase64(os.Getenv("OAUTH_ENCRYPTION_KEY"))

// Create OAuth handler with full security features
handler, err := oauth.NewHandler(&oauth.Config{
	Resource: "https://mcp.example.com",
	SupportedScopes: []string{
		"https://www.googleapis.com/auth/gmail.readonly",
		// ... other Google scopes
	},
	GoogleAuth: oauth.GoogleAuthConfig{
		ClientID:     os.Getenv("GOOGLE_CLIENT_ID"),
		ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
	},
	RateLimit: oauth.RateLimitConfig{
		Rate:     10,
		Burst:    20,
		UserRate: 100,
		UserBurst: 200,
	},
	Security: oauth.SecurityConfig{
		EncryptionKey: encKey,                      // Enable encryption
		EnableAuditLogging: true,                   // Enable audit logs
		DisableRefreshTokenRotation: false,         // Enable rotation
		AllowPublicClientRegistration: false,       // Require auth
		RegistrationAccessToken: "secure-token",    // Registration token
		RefreshTokenTTL: 90 * 24 * time.Hour,      // 90 days
	},
})
if err != nil {
	log.Fatal(err)
}

// Protect MCP endpoints
http.Handle("/mcp", handler.ValidateGoogleToken(mcpHandler))

// Serve metadata endpoints
http.HandleFunc("/.well-known/oauth-protected-resource",
	handler.ServeProtectedResourceMetadata)
http.HandleFunc("/.well-known/oauth-authorization-server",
	handler.ServeAuthorizationServerMetadata)

// Token revocation endpoint (RFC 7009)
http.HandleFunc("/oauth/revoke", handler.ServeTokenRevocation)

Index ΒΆ

Constants ΒΆ

View Source
const (
	// DefaultRefreshTokenTTL is the default time-to-live for refresh tokens (90 days)
	DefaultRefreshTokenTTL = 90 * 24 * time.Hour

	// DefaultAuthorizationCodeTTL is how long authorization codes are valid (10 minutes)
	DefaultAuthorizationCodeTTL = 10 * time.Minute

	// DefaultAccessTokenTTL is the default access token expiry (1 hour)
	DefaultAccessTokenTTL = 1 * time.Hour

	// DefaultCleanupInterval is how often to cleanup expired tokens (1 minute)
	DefaultCleanupInterval = 1 * time.Minute

	// DefaultRateLimitCleanupInterval is how often to cleanup inactive rate limiters
	DefaultRateLimitCleanupInterval = 5 * time.Minute

	// InactiveLimiterCleanupWindow is the time after which inactive limiters are removed
	InactiveLimiterCleanupWindow = 10 * time.Minute

	// TokenRefreshThreshold is how soon before expiry to attempt token refresh
	TokenRefreshThreshold = 5 * time.Minute

	// TokenExpiringThreshold is the minimum time before a token is considered expiring
	TokenExpiringThreshold = 60 // seconds

	// ClockSkewGrace is the grace period (in seconds) for clock skew when validating token expiration
	//
	// Security Rationale:
	//   - Prevents false expiration errors due to minor time differences between systems
	//   - Balances security (minimize token lifetime extension) with usability
	//   - 5 seconds is a conservative value that handles typical NTP drift
	//
	// Trade-offs:
	//   - Allows tokens to be used up to 5 seconds beyond their true expiration
	//   - This is acceptable for most use cases and improves reliability
	//   - For high-security scenarios, consider reducing or removing this grace period
	ClockSkewGrace = 5 // seconds
)

OAuth token and code timeouts

View Source
const (
	// DefaultMaxClientsPerIP is the default limit for client registrations per IP
	DefaultMaxClientsPerIP = 10

	// DefaultRateLimitRate is the default requests per second per IP
	DefaultRateLimitRate = 10

	// DefaultRateLimitBurst is the default burst size for rate limiting
	DefaultRateLimitBurst = 20

	// DefaultTokenEndpointAuthMethod is the default client authentication method
	DefaultTokenEndpointAuthMethod = "client_secret_basic"
)

OAuth client and security defaults

View Source
const (
	// MinCodeVerifierLength is the minimum length for PKCE code_verifier (RFC 7636)
	MinCodeVerifierLength = 43

	// MaxCodeVerifierLength is the maximum length for PKCE code_verifier (RFC 7636)
	MaxCodeVerifierLength = 128

	// ClientIDTokenLength is the length of generated client IDs
	ClientIDTokenLength = 32

	// ClientSecretTokenLength is the length of generated client secrets
	ClientSecretTokenLength = 48

	// AccessTokenLength is the length of generated access tokens
	AccessTokenLength = 48

	// RefreshTokenLength is the length of generated refresh tokens
	RefreshTokenLength = 48

	// StateTokenLength is the length of generated state parameters
	StateTokenLength = 32

	// MinStateLength is the minimum length for state parameters to prevent
	// timing attacks and ensure sufficient entropy for CSRF protection.
	// OAuth 2.1 recommends at least 128 bits (16 bytes) of entropy.
	// This value is used as the default for server.Config.MinStateLength.
	MinStateLength = 32
)

PKCE and token generation constants

View Source
const (
	// ClientTypeConfidential represents a confidential OAuth client
	ClientTypeConfidential = "confidential"

	// ClientTypePublic represents a public OAuth client
	ClientTypePublic = "public"
)

OAuth client types

View Source
const (
	// TokenEndpointAuthMethodNone represents no authentication (public clients)
	TokenEndpointAuthMethodNone = "none"

	// TokenEndpointAuthMethodBasic represents HTTP Basic authentication
	TokenEndpointAuthMethodBasic = "client_secret_basic"

	// TokenEndpointAuthMethodPost represents POST form parameters
	TokenEndpointAuthMethodPost = "client_secret_post"
)

Token endpoint authentication methods (RFC 7591)

View Source
const (
	// PKCEMethodS256 is the SHA256 code challenge method (recommended, OAuth 2.1)
	PKCEMethodS256 = "S256"

	// PKCEMethodPlain is the plain code challenge method (deprecated, insecure)
	PKCEMethodPlain = "plain"
)

PKCE code challenge methods

View Source
const (
	// SchemeHTTP is the HTTP URI scheme
	SchemeHTTP = "http"

	// SchemeHTTPS is the HTTPS URI scheme
	SchemeHTTPS = "https"
)

URI schemes

View Source
const (
	// MetadataPathProtectedResource is the RFC 9728 Protected Resource Metadata discovery path
	MetadataPathProtectedResource = "/.well-known/oauth-protected-resource"

	// MetadataPathAuthorizationServer is the RFC 8414 Authorization Server Metadata discovery path
	MetadataPathAuthorizationServer = "/.well-known/oauth-authorization-server"

	// MaxMetadataPathLength is the maximum allowed length for custom metadata paths
	// This prevents DoS attacks through excessively long path registration
	MaxMetadataPathLength = 256
)

OAuth discovery paths (RFC 8414, RFC 9728)

View Source
const (
	ErrorCodeInvalidRequest       = "invalid_request"
	ErrorCodeInvalidGrant         = "invalid_grant"
	ErrorCodeInvalidClient        = "invalid_client"
	ErrorCodeInvalidScope         = "invalid_scope"
	ErrorCodeInvalidToken         = "invalid_token"
	ErrorCodeInsufficientScope    = "insufficient_scope"
	ErrorCodeUnauthorizedClient   = "unauthorized_client"
	ErrorCodeUnsupportedGrantType = "unsupported_grant_type"
	ErrorCodeServerError          = "server_error"
	ErrorCodeAccessDenied         = "access_denied"
	ErrorCodeInvalidRedirectURI   = "invalid_redirect_uri"
	ErrorCodeRateLimitExceeded    = "rate_limit_exceeded"
)

OAuth error codes as constants

View Source
const (
	// OAuthSpecVersion is the OAuth specification version this library implements
	OAuthSpecVersion = "OAuth 2.1"
)

OAuth specification version

Variables ΒΆ

View Source
var (
	// AllowedHTTPSchemes lists allowed HTTP-based redirect URI schemes
	AllowedHTTPSchemes = []string{"http", "https"}

	// DangerousSchemes lists URI schemes that must never be allowed for security
	DangerousSchemes = []string{"javascript", "data", "file", "vbscript", "about"}

	// DefaultRFC3986SchemePattern is the default regex pattern for custom URI schemes (RFC 3986)
	DefaultRFC3986SchemePattern = []string{"^[a-z][a-z0-9+.-]*$"}

	// LoopbackAddresses lists recognized loopback addresses for development
	LoopbackAddresses = []string{"localhost", "127.0.0.1", "::1", "[::1]"}
)

Redirect URI validation constants

View Source
var (
	// DefaultGrantTypes are the grant types supported by default
	DefaultGrantTypes = []string{"authorization_code", "refresh_token"}

	// DefaultResponseTypes are the response types supported by default
	DefaultResponseTypes = []string{"code"}

	// SupportedCodeChallengeMethods are the PKCE methods we support
	// Security: Only S256 is allowed. "plain" method is insecure and violates OAuth 2.1
	SupportedCodeChallengeMethods = []string{"S256"}

	// SupportedTokenAuthMethods are the supported token endpoint auth methods
	SupportedTokenAuthMethods = []string{"client_secret_basic", "client_secret_post", "none"}
)

OAuth grant types and response types

View Source
var (
	// ErrInvalidRequest indicates the request is malformed or missing required parameters
	ErrInvalidRequest = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeInvalidRequest, desc, http.StatusBadRequest)
	}

	// ErrInvalidGrant indicates the authorization code or refresh token is invalid or expired
	ErrInvalidGrant = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeInvalidGrant, desc, http.StatusBadRequest)
	}

	// ErrInvalidClient indicates client authentication failed
	ErrInvalidClient = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeInvalidClient, desc, http.StatusUnauthorized)
	}

	// ErrInvalidScope indicates the requested scope is invalid or unsupported
	ErrInvalidScope = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeInvalidScope, desc, http.StatusBadRequest)
	}

	// ErrInvalidToken indicates the access token is invalid or expired
	ErrInvalidToken = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeInvalidToken, desc, http.StatusUnauthorized)
	}

	// ErrInsufficientScope indicates the access token lacks required scopes
	ErrInsufficientScope = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeInsufficientScope, desc, http.StatusForbidden)
	}

	// ErrUnauthorizedClient indicates the client is not authorized for the requested grant type
	ErrUnauthorizedClient = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeUnauthorizedClient, desc, http.StatusBadRequest)
	}

	// ErrUnsupportedGrantType indicates the grant type is not supported
	ErrUnsupportedGrantType = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeUnsupportedGrantType, desc, http.StatusBadRequest)
	}

	// ErrServerError indicates an internal server error occurred
	ErrServerError = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeServerError, desc, http.StatusInternalServerError)
	}

	// ErrAccessDenied indicates the user or authorization server denied the request
	ErrAccessDenied = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeAccessDenied, desc, http.StatusForbidden)
	}

	// ErrInvalidRedirectURI indicates the redirect URI is invalid or not registered
	ErrInvalidRedirectURI = func(desc string) *OAuthError {
		return NewOAuthError(ErrorCodeInvalidRedirectURI, desc, http.StatusBadRequest)
	}
)

Common OAuth errors as reusable instances

Functions ΒΆ

func UserInfoFromContext ΒΆ

func UserInfoFromContext(ctx context.Context) (*providers.UserInfo, bool)

UserInfoFromContext retrieves user info from the request context

Types ΒΆ

type AuthorizationServerMetadata ΒΆ

type AuthorizationServerMetadata struct {
	// Issuer is the authorization server's issuer identifier URL
	Issuer string `json:"issuer"`

	// AuthorizationEndpoint is the URL of the authorization endpoint
	AuthorizationEndpoint string `json:"authorization_endpoint"`

	// TokenEndpoint is the URL of the token endpoint
	TokenEndpoint string `json:"token_endpoint"`

	// RegistrationEndpoint is the URL of the dynamic client registration endpoint (RFC 7591)
	RegistrationEndpoint string `json:"registration_endpoint,omitempty"`

	// ScopesSupported lists the OAuth scopes supported
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// ResponseTypesSupported lists the OAuth response types supported
	ResponseTypesSupported []string `json:"response_types_supported"`

	// GrantTypesSupported lists the OAuth grant types supported
	GrantTypesSupported []string `json:"grant_types_supported,omitempty"`

	// TokenEndpointAuthMethodsSupported lists the client authentication methods supported at the token endpoint
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`

	// CodeChallengeMethodsSupported lists the PKCE code challenge methods supported
	CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`

	// RevocationEndpoint is the URL of the OAuth 2.0 token revocation endpoint (RFC 7009)
	RevocationEndpoint string `json:"revocation_endpoint,omitempty"`

	// IntrospectionEndpoint is the URL of the OAuth 2.0 token introspection endpoint (RFC 7662)
	IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`

	// ClientIDMetadataDocumentSupported indicates support for Client ID Metadata Documents (MCP 2025-11-25)
	ClientIDMetadataDocumentSupported bool `json:"client_id_metadata_document_supported,omitempty"`
}

AuthorizationServerMetadata represents OAuth 2.0 Authorization Server Metadata (RFC 8414)

type ClientRegistrationRequest ΒΆ

type ClientRegistrationRequest struct {
	// RedirectURIs is the array of redirection URIs for use in redirect-based flows
	RedirectURIs []string `json:"redirect_uris,omitempty"`

	// TokenEndpointAuthMethod is the requested authentication method for the token endpoint
	TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`

	// GrantTypes is the array of OAuth 2.0 grant types the client will use
	GrantTypes []string `json:"grant_types,omitempty"`

	// ResponseTypes is the array of OAuth 2.0 response types the client will use
	ResponseTypes []string `json:"response_types,omitempty"`

	// ClientName is the human-readable name of the client
	ClientName string `json:"client_name,omitempty"`

	// ClientURI is the URL of the client's home page
	ClientURI string `json:"client_uri,omitempty"`

	// Scope is the space-separated list of scope values
	Scope string `json:"scope,omitempty"`

	// ClientType indicates if this is a "public" or "confidential" client
	// Public clients (mobile, SPA) can use "none" auth method
	// Confidential clients (server-side) must use client_secret_basic or client_secret_post
	ClientType string `json:"client_type,omitempty"`
}

ClientRegistrationRequest represents a dynamic client registration request

type ClientRegistrationResponse ΒΆ

type ClientRegistrationResponse struct {
	// ClientID is the unique client identifier
	ClientID string `json:"client_id"`

	// ClientSecret is the client secret (for confidential clients)
	ClientSecret string `json:"client_secret,omitempty"`

	// ClientIDIssuedAt is the time the client_id was issued
	ClientIDIssuedAt int64 `json:"client_id_issued_at,omitempty"`

	// ClientSecretExpiresAt is when the client_secret expires (0 = never)
	ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`

	// RedirectURIs is the array of redirection URIs
	RedirectURIs []string `json:"redirect_uris,omitempty"`

	// TokenEndpointAuthMethod is the authentication method for the token endpoint
	TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`

	// GrantTypes is the array of OAuth 2.0 grant types
	GrantTypes []string `json:"grant_types,omitempty"`

	// ResponseTypes is the array of OAuth 2.0 response types
	ResponseTypes []string `json:"response_types,omitempty"`

	// ClientName is the human-readable name of the client
	ClientName string `json:"client_name,omitempty"`

	// Scope is the space-separated list of scope values
	Scope string `json:"scope,omitempty"`

	// ClientType indicates if this is a "public" or "confidential" client
	ClientType string `json:"client_type,omitempty"`
}

ClientRegistrationResponse represents a dynamic client registration response

type Config ΒΆ

type Config struct {
	// Resource is the MCP server resource identifier for RFC 8707
	// This should be the base URL of the MCP server
	Resource string

	// SupportedScopes are all available Google API scopes
	SupportedScopes []string

	// Google OAuth credentials and settings
	GoogleAuth GoogleAuthConfig

	// Rate limiting configuration
	RateLimit RateLimitConfig

	// Security settings (secure by default)
	Security SecurityConfig

	// CleanupInterval is how often to cleanup expired tokens
	// Default: 1 minute
	CleanupInterval time.Duration

	// Logger for structured logging (optional, uses default if not provided)
	Logger *slog.Logger

	// HTTPClient is a custom HTTP client for OAuth requests
	// If not provided, uses the default HTTP client
	// Can be used to add timeouts, logging, metrics, etc.
	HTTPClient *http.Client
}

Config holds the OAuth handler configuration Structured using composition for better organization and maintainability

type ErrorResponse ΒΆ

type ErrorResponse struct {
	// Error is the error code
	Error string `json:"error"`

	// ErrorDescription provides additional information
	ErrorDescription string `json:"error_description,omitempty"`

	// ErrorURI points to error documentation
	ErrorURI string `json:"error_uri,omitempty"`
}

ErrorResponse represents an OAuth error response

type GoogleAuthConfig ΒΆ

type GoogleAuthConfig struct {
	// ClientID is the Google OAuth Client ID (required).
	ClientID string

	// ClientSecret is the Google OAuth Client Secret (required).
	ClientSecret string

	// RedirectURL is where Google redirects after authentication.
	RedirectURL string
}

GoogleAuthConfig holds Google OAuth proxy configuration

type Handler ΒΆ

type Handler struct {
	// contains filtered or unexported fields
}

Handler is a thin HTTP adapter for the OAuth Server. It handles HTTP requests and delegates to the Server for business logic.

func NewHandler ΒΆ

func NewHandler(server *Server, logger *slog.Logger) *Handler

NewHandler creates a new HTTP handler

func (*Handler) RegisterProtectedResourceMetadataRoutes ΒΆ added in v0.1.35

func (h *Handler) RegisterProtectedResourceMetadataRoutes(mux *http.ServeMux, mcpPath string)

RegisterProtectedResourceMetadataRoutes registers all Protected Resource Metadata discovery routes. It registers both the root endpoint and optional sub-path endpoint if mcpPath is provided.

Security: This function validates the mcpPath to prevent path traversal attacks and DoS through excessively long paths. Invalid paths are logged and skipped.

Example usage:

mux := http.NewServeMux()
handler.RegisterProtectedResourceMetadataRoutes(mux, "/mcp")
// This registers both:
//   /.well-known/oauth-protected-resource
//   /.well-known/oauth-protected-resource/mcp

func (*Handler) ServeAuthorization ΒΆ

func (h *Handler) ServeAuthorization(w http.ResponseWriter, r *http.Request)

ServeAuthorization handles OAuth authorization requests

func (*Handler) ServeAuthorizationServerMetadata ΒΆ

func (h *Handler) ServeAuthorizationServerMetadata(w http.ResponseWriter, r *http.Request)

ServeAuthorizationServerMetadata serves RFC 8414 Authorization Server Metadata

func (*Handler) ServeCallback ΒΆ

func (h *Handler) ServeCallback(w http.ResponseWriter, r *http.Request)

ServeCallback handles the OAuth provider callback

func (*Handler) ServeClientRegistration ΒΆ

func (h *Handler) ServeClientRegistration(w http.ResponseWriter, r *http.Request)

ServeClientRegistration handles dynamic client registration (RFC 7591)

func (*Handler) ServeOpenIDConfiguration ΒΆ added in v0.1.43

func (h *Handler) ServeOpenIDConfiguration(w http.ResponseWriter, r *http.Request)

ServeOpenIDConfiguration handles OpenID Connect Discovery 1.0 requests Per RFC 8414 Section 5, this endpoint returns the same metadata as the Authorization Server Metadata endpoint for compatibility with OpenID Connect clients

func (*Handler) ServePreflightRequest ΒΆ added in v0.1.22

func (h *Handler) ServePreflightRequest(w http.ResponseWriter, r *http.Request)

ServePreflightRequest handles CORS preflight (OPTIONS) requests. Required for non-simple requests (POST with JSON, custom headers, etc.).

func (*Handler) ServeProtectedResourceMetadata ΒΆ

func (h *Handler) ServeProtectedResourceMetadata(w http.ResponseWriter, r *http.Request)

ServeProtectedResourceMetadata serves RFC 9728 Protected Resource Metadata

func (*Handler) ServeToken ΒΆ

func (h *Handler) ServeToken(w http.ResponseWriter, r *http.Request)

ServeToken handles the OAuth token endpoint

func (*Handler) ServeTokenIntrospection ΒΆ added in v0.1.1

func (h *Handler) ServeTokenIntrospection(w http.ResponseWriter, r *http.Request)

ServeTokenIntrospection handles the RFC 7662 token introspection endpoint This allows resource servers to validate access tokens Security: Requires client authentication to prevent token scanning attacks

func (*Handler) ServeTokenRevocation ΒΆ

func (h *Handler) ServeTokenRevocation(w http.ResponseWriter, r *http.Request)

ServeTokenRevocation handles the RFC 7009 token revocation endpoint

func (*Handler) ValidateToken ΒΆ

func (h *Handler) ValidateToken(next http.Handler) http.Handler

ValidateToken is middleware that validates OAuth tokens

type InstrumentationConfig ΒΆ added in v0.1.26

type InstrumentationConfig = server.InstrumentationConfig

InstrumentationConfig is a type alias for backward compatibility. Use server.InstrumentationConfig for new code.

type OAuthError ΒΆ

type OAuthError struct {
	Code        string // OAuth error code (e.g., "invalid_request", "invalid_grant")
	Description string // Human-readable error description
	Status      int    // HTTP status code
}

OAuthError represents an OAuth 2.0 error response

func NewOAuthError ΒΆ

func NewOAuthError(code, description string, status int) *OAuthError

NewOAuthError creates a new OAuth error

func (*OAuthError) Error ΒΆ

func (e *OAuthError) Error() string

Error implements the error interface

type ProtectedResourceMetadata ΒΆ

type ProtectedResourceMetadata struct {
	// Resource is the identifier for the protected resource
	Resource string `json:"resource"`

	// AuthorizationServers lists the authorization servers that can issue tokens for this resource
	AuthorizationServers []string `json:"authorization_servers"`

	// BearerMethodsSupported lists the ways Bearer tokens can be sent (RFC 6750)
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`

	// ResourceSigningAlgValuesSupported lists supported signing algorithms
	ResourceSigningAlgValuesSupported []string `json:"resource_signing_alg_values_supported,omitempty"`

	// ScopesSupported lists the scopes understood by this resource
	ScopesSupported []string `json:"scopes_supported,omitempty"`
}

ProtectedResourceMetadata represents OAuth 2.0 Protected Resource Metadata (RFC 9728)

type RateLimitConfig ΒΆ

type RateLimitConfig struct {
	// Rate is requests per second allowed per IP. Zero disables limiting.
	Rate int

	// Burst is the maximum burst size allowed per IP.
	Burst int

	// CleanupInterval is how often to cleanup inactive rate limiters.
	CleanupInterval time.Duration

	// UserRate is requests per second allowed per authenticated user.
	// Applied in addition to IP-based limiting. Zero disables.
	UserRate int

	// UserBurst is the maximum burst size per authenticated user.
	UserBurst int

	// TrustProxy enables trusting X-Forwarded-For and X-Real-IP headers.
	// Only enable behind a trusted reverse proxy.
	TrustProxy bool
}

RateLimitConfig holds rate limiting configuration

type SecurityConfig ΒΆ

type SecurityConfig struct {
	// AllowInsecureAuthWithoutState permits auth requests without state parameter.
	// WARNING: Weakens CSRF protection. Only for legacy clients.
	AllowInsecureAuthWithoutState bool

	// DisableRefreshTokenRotation disables automatic refresh token rotation.
	// WARNING: Violates OAuth 2.1. Stolen tokens remain valid indefinitely.
	DisableRefreshTokenRotation bool

	// AllowPublicClientRegistration permits unauthenticated client registration.
	// WARNING: Can enable DoS via mass registration.
	AllowPublicClientRegistration bool

	// RegistrationAccessToken is required for client registration when
	// AllowPublicClientRegistration is false.
	RegistrationAccessToken string

	// RefreshTokenTTL is how long refresh tokens remain valid.
	// Recommended: 30-90 days. Zero means never expire.
	RefreshTokenTTL time.Duration

	// MaxClientsPerIP limits registrations per IP to prevent DoS.
	// Zero means no limit (not recommended).
	MaxClientsPerIP int

	// AllowCustomRedirectSchemes permits non-http/https URIs (e.g., myapp://).
	// Custom schemes are validated against AllowedCustomSchemes patterns.
	AllowCustomRedirectSchemes bool

	// AllowedCustomSchemes lists allowed custom URI scheme regex patterns.
	// Default: RFC 3986 compliant schemes.
	AllowedCustomSchemes []string

	// EncryptionKey is the AES-256 key (32 bytes) for token encryption at rest.
	// Nil disables encryption. Generate with oauth.GenerateEncryptionKey().
	EncryptionKey []byte

	// EnableAuditLogging enables security audit logging.
	// Logs auth events, token operations, and violations (sensitive data hashed).
	EnableAuditLogging bool
}

SecurityConfig holds OAuth security settings (secure by default)

type Server ΒΆ

type Server = server.Server

Server is a type alias for backward compatibility. All server logic is now in the server package.

func NewServer ΒΆ

func NewServer(
	provider providers.Provider,
	tokenStore storage.TokenStore,
	clientStore storage.ClientStore,
	flowStore storage.FlowStore,
	config *ServerConfig,
	logger *slog.Logger,
) (*Server, error)

NewServer creates a new OAuth server. This is a convenience wrapper for server.New() to maintain backward compatibility.

type ServerConfig ΒΆ

type ServerConfig = server.Config

ServerConfig is a type alias for backward compatibility. Use server.Config for new code.

type TokenResponse ΒΆ

type TokenResponse struct {
	// AccessToken is the access token
	AccessToken string `json:"access_token"`

	// TokenType is the type of token (always "Bearer")
	TokenType string `json:"token_type"`

	// ExpiresIn is the lifetime in seconds of the access token
	ExpiresIn int64 `json:"expires_in,omitempty"`

	// RefreshToken is the refresh token (optional)
	RefreshToken string `json:"refresh_token,omitempty"`

	// Scope is the scope of the access token
	Scope string `json:"scope,omitempty"`
}

TokenResponse represents an OAuth 2.0 token response

Directories ΒΆ

Path Synopsis
Package instrumentation provides OpenTelemetry (OTEL) instrumentation for the mcp-oauth library.
Package instrumentation provides OpenTelemetry (OTEL) instrumentation for the mcp-oauth library.
internal
testutil
Package testutil provides testing utilities, mock implementations, and test fixtures for the mcp-oauth library.
Package testutil provides testing utilities, mock implementations, and test fixtures for the mcp-oauth library.
util
Package util provides common utility functions used across the mcp-oauth library.
Package util provides common utility functions used across the mcp-oauth library.
Package providers defines the interface for OAuth identity providers and implements provider-specific logic for Google, GitHub, Microsoft, and other OAuth/OIDC providers.
Package providers defines the interface for OAuth identity providers and implements provider-specific logic for Google, GitHub, Microsoft, and other OAuth/OIDC providers.
google
Package google implements the OAuth provider interface for Google OAuth 2.0.
Package google implements the OAuth provider interface for Google OAuth 2.0.
mock
Package mock provides mock implementations of the Provider interface for testing purposes.
Package mock provides mock implementations of the Provider interface for testing purposes.
Package security provides security features for OAuth including encryption, rate limiting, audit logging, and secure header management.
Package security provides security features for OAuth including encryption, rate limiting, audit logging, and secure header management.
Package server provides OAuth 2.1 authorization server implementation with MCP support
Package server provides OAuth 2.1 authorization server implementation with MCP support
Package storage defines interfaces for persisting OAuth tokens, clients, and authorization flows.
Package storage defines interfaces for persisting OAuth tokens, clients, and authorization flows.
memory
Package memory provides an in-memory implementation of all storage interfaces.
Package memory provides an in-memory implementation of all storage interfaces.
mock
Package mock provides mock implementations of storage interfaces for testing purposes.
Package mock provides mock implementations of storage interfaces for testing purposes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL