Documentation
¶
Index ¶
Constants ¶
const ( AuthModeLocal = "local" AuthModeHTTPAPI = "http_api" )
Authentication mode constants
const ( RateLimitStoreMemory = "memory" RateLimitStoreRedis = "redis" )
Rate limit store constants
const ( CacheTypeMemory = "memory" CacheTypeRedis = "redis" CacheTypeRedisAside = "redis-aside" )
CacheType constants shared by metrics, user, and client count caches.
const ( AlgHS256 = "HS256" AlgRS256 = "RS256" AlgES256 = "ES256" )
JWT signing algorithm constants.
const DefaultJWTPrivateClaimPrefix = "extra"
DefaultJWTPrivateClaimPrefix is the namespace token AuthGate prepends to every AuthGate-emitted private JWT claim when JWT_PRIVATE_CLAIM_PREFIX is unset. Composed keys: extra_domain, extra_project, extra_service_account.
Variables ¶
This section is empty.
Functions ¶
func PrivateClaimLogicalNames ¶ added in v0.29.0
func PrivateClaimLogicalNames() []string
PrivateClaimLogicalNames returns a defensive copy of the local jwtPrivateClaimLogicalNames slice. Exported solely for the cross-package drift guard test that compares this list against token.PrivateClaimRegistry().
func StaticReservedClaimKeys ¶ added in v0.29.0
func StaticReservedClaimKeys() []string
StaticReservedClaimKeys returns a defensive copy of the canonical static reserved-claim list (see staticReservedClaimKeys). The underlying slice is intentionally unexported to prevent cross-package mutation; callers that need to iterate must use this accessor.
Types ¶
type Config ¶
type Config struct {
// Server settings
ServerAddr string
BaseURL string
TLSCertFile string // Both TLSCertFile and TLSKeyFile must be set to serve HTTPS.
TLSKeyFile string
// Environment detection
IsProduction bool
// JWT settings
JWTSecret string
JWTExpiration time.Duration
JWTSigningAlgorithm string // "HS256" (default), "RS256", or "ES256"
JWTPrivateKeyPath string // PEM file path (required for RS256/ES256 when PEM content is not set)
JWTPrivateKeyPEM string // PEM content (alternative to JWTPrivateKeyPath; takes precedence if both are set)
JWTKeyID string // "kid" header for JWKS key rotation (auto-generated if empty)
JWTExpirationJitter time.Duration // Max random jitter added to access token expiry (default: 30m)
JWTAudience []string // "aud" claim values for issued access/refresh tokens (comma-separated env). Single entry → string, multiple → array. Empty → claim omitted.
JWTDomain string // Server-attested domain value emitted as "<prefix>_domain" (default: "extra_domain") on every issued JWT. Empty → claim omitted (default). Validated at startup via util.IsValidProjectIdentifier.
// JWTPrivateClaimPrefix is the namespace token AuthGate prepends (with an
// underscore separator AuthGate adds itself) to every AuthGate-emitted
// private JWT claim. With the default "extra", JWTs carry "extra_domain",
// "extra_project", "extra_service_account". An empty value is treated as
// "use the default" — Validate() checks it against the default without
// mutating this field; runtime callers (NewLocalTokenProvider,
// NewExtraClaimsParser, TokenService) each normalize empty → default
// locally. Validated at startup: must match ^[a-zA-Z][a-zA-Z0-9_]*$,
// 1–15 chars, no trailing underscore, and none of the composed
// "<prefix>_<logical>" keys may collide with any RFC 7519 / OIDC /
// AuthGate-internal claim key.
JWTPrivateClaimPrefix string
// Session settings
SessionSecret string
SessionMaxAge int // Session max age in seconds (default: 3600 = 1 hour)
SessionIdleTimeout int // Session idle timeout in seconds (0 = disabled, default: 1800 = 30 minutes)
SessionFingerprint bool // Enable session fingerprinting (IP + User-Agent validation, default: true)
SessionFingerprintIP bool // Include IP address in fingerprint (default: false, due to dynamic IPs)
SessionRememberMeEnabled bool // Enable "Remember Me" checkbox on login (default: true)
SessionRememberMeMaxAge int // Remember Me session max age in seconds (default: 2592000 = 30 days)
// Device code settings
DeviceCodeExpiration time.Duration
PollingInterval int // seconds
// Database
DatabaseDriver string // "sqlite" or "postgres"
DatabaseDSN string // Database connection string (DSN or path)
// Database connection pool settings
DBMaxOpenConns int // Maximum number of open connections (default: 25)
DBMaxIdleConns int // Maximum number of idle connections (default: 10)
DBConnMaxLifetime time.Duration // Maximum connection lifetime (default: 5 minutes)
DBConnMaxIdleTime time.Duration // Maximum connection idle time (default: 10 minutes)
DBLogLevel string // GORM log level: "silent", "error", "warn", "info" (default: "warn")
// Default Admin User
DefaultAdminPassword string // Default admin password (if empty, random password is generated)
// Authentication
AuthMode string // "local" or "http_api"
// HTTP API Authentication
HTTPAPIURL string
HTTPAPITimeout time.Duration
HTTPAPIInsecureSkipVerify bool
HTTPAPIAuthMode string // Authentication mode: "none", "simple", or "hmac"
HTTPAPIAuthSecret string // Shared secret for authentication
HTTPAPIAuthHeader string // Custom header name for simple mode (default: "X-API-Secret")
HTTPAPIMaxRetries int // Maximum retry attempts (default: 3)
HTTPAPIRetryDelay time.Duration
HTTPAPIMaxRetryDelay time.Duration
// Refresh Token settings
RefreshTokenExpiration time.Duration // Refresh token lifetime (default: 720h = 30 days)
EnableRefreshTokens bool // Feature flag to enable/disable refresh tokens (default: true)
EnableTokenRotation bool // Enable token rotation mode (default: false, fixed mode)
// Token lifetime hard caps. Any TokenProfile value that exceeds these is rejected
// during Validate(). Prevents a misconfigured profile from silently extending token
// lifetime far beyond the security intent.
JWTExpirationMax time.Duration // env: JWT_EXPIRATION_MAX (default: 24h)
RefreshTokenExpirationMax time.Duration // env: REFRESH_TOKEN_EXPIRATION_MAX (default: 2160h / 90d)
// TokenProfiles maps a profile name ("short" / "standard" / "long") to its TTLs.
// Populated in Load() from the TOKEN_PROFILE_*_ACCESS_TTL / TOKEN_PROFILE_*_REFRESH_TTL env
// vars; the "standard" profile falls back to JWTExpiration / RefreshTokenExpiration.
TokenProfiles map[string]TokenProfile
// Client Credentials Flow settings (RFC 6749 §4.4)
ClientCredentialsTokenExpiration time.Duration // Access token lifetime for client_credentials grant (default: 1h, same as JWTExpiration)
// Caller-supplied JWT extra claims (extra_claims parameter on /oauth/token).
// Enabled by default. Reserved JWT/OIDC keys are always rejected regardless
// of these limits. Custom claims are NOT persisted, so callers must
// re-supply extra_claims on every refresh to retain them.
ExtraClaimsEnabled bool // EXTRA_CLAIMS_ENABLED (default: true)
ExtraClaimsMaxRawSize int // EXTRA_CLAIMS_MAX_RAW_SIZE in bytes (default: 4096; 0 disables the check)
ExtraClaimsMaxKeys int // EXTRA_CLAIMS_MAX_KEYS (default: 16; 0 disables the check)
ExtraClaimsMaxValSize int // EXTRA_CLAIMS_MAX_VAL_SIZE in bytes per value (default: 512; 0 disables the check)
// OAuth settings
// GitHub OAuth
GitHubOAuthEnabled bool
GitHubClientID string
GitHubClientSecret string
GitHubOAuthRedirectURL string
GitHubOAuthScopes []string
// Gitea OAuth
GiteaOAuthEnabled bool
GiteaURL string
GiteaClientID string
GiteaClientSecret string
GiteaOAuthRedirectURL string
GiteaOAuthScopes []string
// Microsoft Entra ID OAuth
MicrosoftOAuthEnabled bool
MicrosoftTenantID string // "common", "organizations", or tenant UUID
MicrosoftClientID string
MicrosoftClientSecret string
MicrosoftOAuthRedirectURL string
MicrosoftOAuthScopes []string
// GitLab OAuth
GitLabOAuthEnabled bool
GitLabURL string // Base URL; defaults to "https://gitlab.com" for cloud
GitLabClientID string
GitLabClientSecret string
GitLabOAuthRedirectURL string
GitLabOAuthScopes []string
// OAuth Auto Registration
OAuthAutoRegister bool // Allow OAuth to auto-create accounts (default: true)
// OAuth HTTP Client Settings
OAuthTimeout time.Duration // HTTP client timeout for OAuth requests (default: 15s)
OAuthInsecureSkipVerify bool // Skip TLS verification for OAuth (dev/testing only, default: false)
// Rate Limiting settings
EnableRateLimit bool // Enable rate limiting (default: true)
RateLimitStore string // Rate limit store: "memory" or "redis" (default: "memory")
RateLimitCleanupInterval time.Duration
LoginRateLimit int // Requests per minute for /login endpoint (default: 5)
DeviceCodeRateLimit int // Requests per minute for /oauth/device/code (default: 10)
TokenRateLimit int // Requests per minute for /oauth/token (default: 20)
DeviceVerifyRateLimit int // Requests per minute for /device/verify (default: 10)
IntrospectRateLimit int // Requests per minute for /oauth/introspect (default: 20)
// Redis settings (only used when RateLimitStore = "redis")
RedisAddr string // Redis address for rate limiting (e.g., "localhost:6379")
RedisPassword string // Redis password (empty for no auth)
RedisDB int // Redis database number (default: 0)
// Audit Logging settings
EnableAuditLogging bool // Enable audit logging (default: true)
AuditLogRetention time.Duration // Retention period for audit logs (default: 90 days)
AuditLogBufferSize int // Async buffer size (default: 1000)
AuditLogCleanupInterval time.Duration // Cleanup interval (default: 24 hours)
// Token/Device Code cleanup settings
EnableExpiredTokenCleanup bool // Enable periodic cleanup of expired tokens and device codes (default: false)
ExpiredTokenCleanupInterval time.Duration // How often to purge expired rows (default: 1h)
// Prometheus Metrics settings
MetricsEnabled bool // Enable Prometheus metrics endpoint (default: false)
MetricsToken string // Bearer token for /metrics (empty = no auth, recommended for production)
MetricsGaugeUpdateEnabled bool // Enable gauge metric updates (default: true, disable on all but one replica)
MetricsGaugeUpdateInterval time.Duration // Gauge update interval (default: 5m)
MetricsCacheType string // Cache backend: memory, redis, redis-aside (default: memory)
MetricsCacheClientTTL time.Duration // Client-side cache TTL for redis-aside (default: 30s)
MetricsCacheSizePerConn int // Client-side cache size per connection in MB for redis-aside (default: 32MB)
// User Cache settings
UserCacheType string // USER_CACHE_TYPE: memory|redis|redis-aside (default: memory)
UserCacheTTL time.Duration // USER_CACHE_TTL (default: 5m)
UserCacheClientTTL time.Duration // USER_CACHE_CLIENT_TTL for redis-aside client-side TTL (default: 30s)
UserCacheSizePerConn int // USER_CACHE_SIZE_PER_CONN: client-side cache size per connection in MB for redis-aside (default: 32MB)
// Client Count Cache settings (pending badge in admin navbar)
ClientCountCacheType string // CLIENT_COUNT_CACHE_TYPE: memory|redis|redis-aside (default: memory)
ClientCountCacheTTL time.Duration // CLIENT_COUNT_CACHE_TTL: server-side cache lifetime (default: 1h)
ClientCountCacheClientTTL time.Duration // CLIENT_COUNT_CACHE_CLIENT_TTL for redis-aside (default: 10m)
ClientCountCacheSizePerConn int // CLIENT_COUNT_CACHE_SIZE_PER_CONN for redis-aside in MB (default: 32MB)
// Client Cache settings (caches OAuth client lookups by client_id)
ClientCacheType string // CLIENT_CACHE_TYPE: memory|redis|redis-aside (default: memory)
ClientCacheTTL time.Duration // CLIENT_CACHE_TTL: cache lifetime (default: 5m)
ClientCacheClientTTL time.Duration // CLIENT_CACHE_CLIENT_TTL for redis-aside client-side TTL (default: 30s)
ClientCacheSizePerConn int // CLIENT_CACHE_SIZE_PER_CONN: client-side cache size per connection in MB for redis-aside (default: 32MB)
// Token Cache settings (reduces DB queries for token verification)
TokenCacheEnabled bool // TOKEN_CACHE_ENABLED: enable token verification cache (default: false)
TokenCacheType string // TOKEN_CACHE_TYPE: memory|redis|redis-aside (default: memory)
TokenCacheTTL time.Duration // TOKEN_CACHE_TTL: cache lifetime (default: 10h, matches JWT_EXPIRATION)
TokenCacheClientTTL time.Duration // TOKEN_CACHE_CLIENT_TTL: redis-aside client-side TTL (default: 1h)
TokenCacheSizePerConn int // TOKEN_CACHE_SIZE_PER_CONN: redis-aside size in MB (default: 32MB)
// Dynamic Client Registration (RFC 7591)
EnableDynamicClientRegistration bool // Enable POST /oauth/register endpoint (default: false)
DynamicClientRegistrationRateLimit int // Requests per minute for /oauth/register (default: 5)
DynamicClientRegistrationToken string // Initial access token for protected registration (empty = open registration)
// Authorization Code Flow settings (RFC 6749)
AuthCodeExpiration time.Duration // Authorization code lifetime (default: 10 minutes)
PKCERequired bool // Force PKCE for all public clients (default: false)
ConsentRemember bool // Skip consent page if user already authorized same scope (default: true)
// CORS settings
CORSEnabled bool // Enable CORS for API endpoints (default: false)
CORSAllowedOrigins []string // Allowed origins (comma-separated via env, e.g. "http://localhost:3000")
CORSAllowedMethods []string // Allowed HTTP methods (default: GET,POST,PUT,DELETE,OPTIONS)
CORSAllowedHeaders []string // Allowed request headers (default: Origin,Content-Type,Authorization)
CORSMaxAge time.Duration // Preflight cache duration (default: 12 hours)
// Static file caching
StaticCacheMaxAge time.Duration // Cache-Control max-age for non-hashed static files (default: 24h, 0 disables)
// Bootstrap and shutdown timeout settings
DBInitTimeout time.Duration // Database initialization timeout (default: 30s)
RedisConnTimeout time.Duration // Redis connection timeout (default: 5s)
CacheInitTimeout time.Duration // Cache initialization timeout (default: 5s)
ServerShutdownTimeout time.Duration // HTTP server graceful shutdown timeout (default: 5s)
AuditShutdownTimeout time.Duration // Audit service shutdown timeout (default: 10s)
RedisCloseTimeout time.Duration // Redis close timeout (default: 5s)
CacheCloseTimeout time.Duration // Cache close timeout (default: 5s)
DBCloseTimeout time.Duration // Database close timeout (default: 5s)
}
func (*Config) TLSEnabled ¶ added in v0.27.0
TLSEnabled reports whether TLS serving should be activated. Both TLSCertFile and TLSKeyFile must be set for TLS to be enabled.
type TokenProfile ¶ added in v0.28.0
TokenProfile defines the access and refresh token lifetimes for a named preset. Clients reference a profile by name via OAuthApplication.TokenProfile (see models.TokenProfile* constants) and the TTL is resolved at token issuance.