server

package
v0.1.21 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2025 License: Apache-2.0 Imports: 19 Imported by: 7 modules, 1 package

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.

Documentation

Overview

Package server implements the core OAuth 2.1 server logic.

This package provides the OAuth authorization server implementation with support for the authorization code flow, PKCE, token refresh, and client registration. It coordinates between OAuth providers, storage backends, and security features while remaining provider-agnostic.

The Server type delegates to specialized modules:

  • Provider integration (providers package)
  • Token and client storage (storage package)
  • Security features (security package)

Key Features:

  • OAuth 2.1 compliance with mandatory PKCE
  • Refresh token rotation with reuse detection
  • Dynamic client registration (RFC 7591)
  • Comprehensive security auditing
  • Rate limiting (IP and user-based)
  • Token encryption at rest

Example usage:

provider := google.NewProvider(clientID, clientSecret, redirectURL)
store := memory.NewStore()

config := &server.Config{
    Issuer: "https://auth.example.com",
    RequirePKCE: true,
}

srv, err := server.New(provider, store, store, store, config, logger)
if err != nil {
    log.Fatal(err)
}

Index

Constants

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

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

Client type constants

View Source
const (
	ErrorCodeInvalidClient      = "invalid_client"
	ErrorCodeInvalidRequest     = "invalid_request"
	ErrorCodeInvalidRedirectURI = "invalid_redirect_uri"
	ErrorCodeInvalidScope       = "invalid_scope"
	ErrorCodeInvalidGrant       = "invalid_grant"
)

OAuth 2.0 error codes from RFC 6749. Note: These are intentionally duplicated from errors.go to avoid circular imports (root package imports server for type aliases, server can't import root). Keep these in sync with errors.go.

View Source
const (
	MinCodeVerifierLength = 43
	MaxCodeVerifierLength = 128
	PKCEMethodS256        = "S256"
	PKCEMethodPlain       = "plain"
)

PKCE validation constants (RFC 7636)

View Source
const (
	SchemeHTTP  = "http"
	SchemeHTTPS = "https"
)

URI scheme constants

View Source
const (
	// MinTokenBytes is the minimum number of random bytes required for secure tokens.
	// 32 bytes = 256 bits of entropy, which exceeds NIST recommendations for
	// cryptographic keys and is sufficient to prevent brute-force attacks.
	// Base64url encoding without padding produces 43 characters from 32 bytes.
	MinTokenBytes = 32
)
View Source
const OAuthSpecVersion = "OAuth 2.1"

OAuthSpecVersion is the OAuth specification version this library implements. Note: This is intentionally duplicated from constants.go to avoid circular imports. Keep in sync with constants.go.

Variables

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

	// 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]"}
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// Issuer is the server's issuer identifier (base URL)
	Issuer string

	// AuthorizationCodeTTL is how long authorization codes are valid
	AuthorizationCodeTTL int64 // seconds, default: 600 (10 minutes)

	// AccessTokenTTL is how long access tokens are valid
	AccessTokenTTL int64 // seconds, default: 3600 (1 hour)

	// RefreshTokenTTL is how long refresh tokens are valid
	RefreshTokenTTL int64 // seconds, default: 7776000 (90 days)

	// AllowRefreshTokenRotation enables refresh token rotation (OAuth 2.1)
	// Default: true (secure by default)
	AllowRefreshTokenRotation bool // default: true

	// TrustProxy enables trusting X-Forwarded-For and X-Real-IP headers
	// WARNING: Only enable if behind a trusted reverse proxy (nginx, HAProxy, etc.)
	// When false, uses direct connection IP (secure by default)
	// Default: false
	TrustProxy bool // default: false

	// TrustedProxyCount is the number of trusted proxies in front of this server
	// Used with TrustProxy to correctly extract client IP from X-Forwarded-For
	// Example: If you have 2 proxies (CloudFlare + nginx), set this to 2
	// The client IP will be extracted as: ips[len(ips) - TrustedProxyCount - 1]
	// Default: 1
	TrustedProxyCount int // default: 1

	// MaxClientsPerIP limits client registrations per IP address
	// Prevents DoS via mass client registration
	// Default: 10
	MaxClientsPerIP int // default: 10

	// MaxRegistrationsPerHour limits client registrations per IP address per hour
	// This is a time-windowed rate limit that prevents resource exhaustion
	// through repeated registration/deletion cycles
	// Default: 10
	MaxRegistrationsPerHour int // default: 10

	// RegistrationRateLimitWindow is the time window for client registration rate limiting
	// Default: 1 hour
	RegistrationRateLimitWindow int64 // seconds, default: 3600 (1 hour)

	// ClockSkewGracePeriod is the grace period for token expiration checks (in seconds)
	// This prevents false expiration errors due to time synchronization issues
	// Default: 5 seconds
	ClockSkewGracePeriod int64 // seconds, default: 5

	// TokenRefreshThreshold is the time before token expiry (in seconds) when proactive
	// refresh should be attempted during token validation. If a token will expire within
	// this threshold and has a refresh token available, ValidateToken will attempt to
	// refresh it proactively to avoid validation failures.
	// This improves user experience by preventing expired token errors when refresh is possible.
	// Default: 300 seconds (5 minutes)
	TokenRefreshThreshold int64 // seconds, default: 300

	// ProviderRevocationTimeout is the timeout PER TOKEN for revoking tokens at the provider (Google/GitHub/etc)
	// during security events (code reuse, token reuse detection).
	// This prevents blocking indefinitely if the provider is slow or unreachable.
	// Default: 10 seconds per token (allows for network latency and rate limits)
	ProviderRevocationTimeout int64 // seconds, default: 10

	// ProviderRevocationMaxRetries is the maximum number of retry attempts for provider revocation
	// Retries use exponential backoff: 100ms, 200ms, 400ms, 800ms, 1600ms
	// Default: 3 retries (total max time per token: ~10s + ~3s retries = ~13s)
	ProviderRevocationMaxRetries int // default: 3

	// ProviderRevocationFailureThreshold is the maximum acceptable failure rate (0.0 to 1.0)
	// If more than this percentage of provider revocations fail, the entire operation fails
	// to ensure tokens aren't left valid at the provider during security events.
	// Default: 0.5 (50% - at least half must succeed)
	ProviderRevocationFailureThreshold float64 // default: 0.5

	// RevokedFamilyRetentionDays is the number of days to retain revoked token family metadata
	// for forensics and security auditing. After this period, revoked family metadata is deleted.
	// Longer retention enables better security incident investigation but uses more memory.
	// Default: 90 days (recommended for security compliance and forensics)
	RevokedFamilyRetentionDays int64 // days, default: 90

	// SupportedScopes lists the scopes that are allowed for clients
	// If empty, all scopes are allowed
	SupportedScopes []string

	// AllowPKCEPlain allows the 'plain' code_challenge_method (NOT RECOMMENDED)
	// WARNING: The 'plain' method is insecure and deprecated in OAuth 2.1
	// Only enable for backward compatibility with legacy clients
	// When false, only S256 method is accepted (secure by default)
	// Default: false
	AllowPKCEPlain bool // default: false

	// RequirePKCE enforces PKCE for all authorization requests
	// WARNING: Disabling this significantly weakens security
	// Only disable for backward compatibility with very old clients
	// When true, code_challenge parameter is mandatory (secure by default)
	// Default: true
	RequirePKCE bool // default: true

	// AllowPublicClientsWithoutPKCE allows public clients to authenticate without PKCE
	// WARNING: This creates a significant security vulnerability to authorization code theft attacks
	// Public clients (mobile apps, SPAs) cannot securely store credentials, making them vulnerable
	// to authorization code interception if PKCE is not used (OAuth 2.1 Section 7.6)
	// Only enable this for backward compatibility with legacy clients that cannot be updated
	// SECURITY: Even when RequirePKCE=false, public clients MUST use PKCE unless this is explicitly enabled
	// Default: false (PKCE is REQUIRED for public clients per OAuth 2.1)
	AllowPublicClientsWithoutPKCE bool // default: false

	// 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.
	// Default: 32 characters (192 bits of entropy)
	MinStateLength int // default: 32

	// AllowPublicClientRegistration allows unauthenticated dynamic client registration
	// WARNING: This can lead to DoS attacks via unlimited client registration
	// When false, client registration requires a registration access token
	// Default: false (authentication REQUIRED for security)
	AllowPublicClientRegistration bool // default: false

	// RegistrationAccessToken is the token required for client registration
	// Only checked if AllowPublicClientRegistration is false
	// Generate a secure random token and share it only with trusted client developers
	RegistrationAccessToken string

	// AllowedCustomSchemes is a list of allowed custom URI scheme patterns (regex)
	// Used for validating custom redirect URIs (e.g., myapp://, com.example.app://)
	// Empty list allows all RFC 3986 compliant schemes
	// Default: ["^[a-z][a-z0-9+.-]*$"] (RFC 3986 compliant schemes)
	AllowedCustomSchemes []string

	// AllowInsecureHTTP allows running OAuth server over HTTP (INSECURE - development only)
	// WARNING: OAuth over HTTP exposes all tokens and credentials to network interception
	// This should ONLY be enabled for local development (localhost, 127.0.0.1)
	// When false (default), the server enforces HTTPS for non-localhost deployments
	// Security: must be explicitly enabled to allow HTTP
	AllowInsecureHTTP bool
}

Config holds OAuth server configuration

type Server

type Server struct {
	Encryptor                     *security.Encryptor
	Auditor                       *security.Auditor
	RateLimiter                   *security.RateLimiter                   // IP-based rate limiter
	UserRateLimiter               *security.RateLimiter                   // User-based rate limiter (authenticated requests)
	SecurityEventRateLimiter      *security.RateLimiter                   // Rate limiter for security event logging (DoS prevention)
	ClientRegistrationRateLimiter *security.ClientRegistrationRateLimiter // Time-windowed rate limiter for client registrations
	Logger                        *slog.Logger
	Config                        *Config
	// contains filtered or unexported fields
}

Server implements the OAuth 2.1 server logic (provider-agnostic). It coordinates the OAuth flow using a Provider and storage backends.

func New

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

New creates a new OAuth server

func (*Server) ExchangeAuthorizationCode

func (s *Server) ExchangeAuthorizationCode(ctx context.Context, code, clientID, redirectURI, codeVerifier string) (*oauth2.Token, string, error)

ExchangeAuthorizationCode exchanges an authorization code for tokens Returns oauth2.Token directly

func (*Server) GetClient

func (s *Server) GetClient(clientID string) (*storage.Client, error)

GetClient retrieves a client by ID (for use by handler)

func (*Server) HandleProviderCallback

func (s *Server) HandleProviderCallback(ctx context.Context, providerState, code string) (*storage.AuthorizationCode, string, error)

HandleProviderCallback handles the callback from the OAuth provider Returns: (authorizationCode, clientState, error) clientState is the original state parameter from the client for CSRF validation

func (*Server) RefreshAccessToken

func (s *Server) RefreshAccessToken(ctx context.Context, refreshToken, clientID string) (*oauth2.Token, error)

RefreshAccessToken refreshes an access token using a refresh token with OAuth 2.1 rotation Returns oauth2.Token directly Implements OAuth 2.1 refresh token reuse detection for enhanced security

func (*Server) RegisterClient

func (s *Server) RegisterClient(clientName, clientType string, redirectURIs []string, scopes []string, clientIP string, maxClientsPerIP int) (*storage.Client, string, error)

RegisterClient registers a new OAuth client with IP-based DoS protection

func (*Server) RevokeAllTokensForUserClient added in v0.1.9

func (s *Server) RevokeAllTokensForUserClient(ctx context.Context, userID, clientID string) error

RevokeAllTokensForUserClient revokes all tokens (access + refresh) for a specific user+client combination. This is called when authorization code or refresh token reuse is detected (OAuth 2.1 security requirement). It provides defense against token theft by invalidating all tokens when an attack is detected.

SECURITY: This function revokes tokens at BOTH the provider (Google/GitHub) and locally. The storage backend MUST implement TokenRevocationStore for OAuth 2.1 compliance.

Provider Revocation Behavior: - Attempts to revoke all tokens at the OAuth provider (Google/GitHub/etc) FIRST before local revocation - Uses exponential backoff retry logic (configurable via ProviderRevocationMaxRetries) - Individual token failures are logged but don't stop the process - If provider revocation failures exceed ProviderRevocationFailureThreshold (default 50%), returns error - If ALL provider revocations fail (100% failure rate), returns error and logs critical alert - Tokens are ALWAYS revoked locally, even if provider revocation fails - This ensures defense-in-depth: tokens become invalid locally while operators investigate provider issues

Error Handling: - Returns error if storage doesn't support TokenRevocationStore (OAuth 2.1 compliance failure) - Returns error if provider revocation failure rate exceeds threshold - Returns error if local revocation fails - Logs detailed information about partial failures for operator investigation

func (*Server) RevokeToken

func (s *Server) RevokeToken(ctx context.Context, token, clientID, clientIP string) error

RevokeToken revokes a token (access or refresh)

func (*Server) SetAuditor

func (s *Server) SetAuditor(aud *security.Auditor)

SetAuditor sets the security auditor

func (*Server) SetClientRegistrationRateLimiter added in v0.1.20

func (s *Server) SetClientRegistrationRateLimiter(rl *security.ClientRegistrationRateLimiter)

SetClientRegistrationRateLimiter sets the time-windowed rate limiter for client registrations This prevents resource exhaustion through repeated registration/deletion cycles

func (*Server) SetEncryptor

func (s *Server) SetEncryptor(enc *security.Encryptor)

SetEncryptor sets the token encryptor for server and storage

func (*Server) SetRateLimiter

func (s *Server) SetRateLimiter(rl *security.RateLimiter)

SetRateLimiter sets the IP-based rate limiter

func (*Server) SetSecurityEventRateLimiter added in v0.1.11

func (s *Server) SetSecurityEventRateLimiter(rl *security.RateLimiter)

SetSecurityEventRateLimiter sets the rate limiter for security event logging This prevents DoS attacks via log flooding from repeated security events

func (*Server) SetUserRateLimiter

func (s *Server) SetUserRateLimiter(rl *security.RateLimiter)

SetUserRateLimiter sets the user-based rate limiter for authenticated requests

func (*Server) StartAuthorizationFlow

func (s *Server) StartAuthorizationFlow(clientID, redirectURI, scope, codeChallenge, codeChallengeMethod, clientState string) (string, error)

StartAuthorizationFlow starts a new OAuth authorization flow clientState is the state parameter from the client (REQUIRED for CSRF protection)

func (*Server) ValidateClientCredentials

func (s *Server) ValidateClientCredentials(clientID, clientSecret string) error

ValidateClientCredentials validates client credentials for token endpoint

func (*Server) ValidateToken

func (s *Server) ValidateToken(ctx context.Context, accessToken string) (*providers.UserInfo, error)

ValidateToken validates an access token with local expiry check and provider validation. This implements defense-in-depth by checking token expiry locally BEFORE delegating to the provider, preventing expired tokens from being accepted due to clock skew.

Validation flow: 1. Check if token exists in local storage 2. If found, validate expiry locally (with ClockSkewGracePeriod) 3. If expired locally, return error immediately (don't call provider) 4. Validate with provider (external check) 5. Store updated user info

Note: Rate limiting should be done at the HTTP layer with IP address, not here with token

Jump to

Keyboard shortcuts

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