config

package
v0.36.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 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.

Documentation

Index

Constants

View Source
const (
	AuthModeLocal   = "local"
	AuthModeHTTPAPI = "http_api"
)

Authentication mode constants

View Source
const (
	RateLimitStoreMemory = "memory"
	RateLimitStoreRedis  = "redis"
)

Rate limit store constants

View Source
const (
	CacheTypeMemory     = "memory"
	CacheTypeRedis      = "redis"
	CacheTypeRedisAside = "redis-aside"
)

CacheType constants shared by metrics, user, and client count caches.

View Source
const (
	AlgHS256 = "HS256"
	AlgRS256 = "RS256"
	AlgES256 = "ES256"
)

JWT signing algorithm constants.

View Source
const (
	DefaultJWTSecret     = "your-256-bit-secret-change-in-production"
	DefaultSessionSecret = "session-secret-change-in-production"
)

DefaultJWTSecret and DefaultSessionSecret are the canonical placeholder secret values used as the Load() defaults (and shown in .env.example). They exist so the example config still boots in development, but signing/encrypting with a public secret is unsafe in production. They are also members of publishedPlaceholderSecrets, which validateSecrets() rejects in production — reusing the constants for both the Load() default and that set keeps them from drifting.

View Source
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

	// Decoupled from IsProduction so prod deployments can opt in behind internal networking.
	SwaggerEnabled 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)

	// Login session tracking (Active Sessions page / remote sign-out)
	LoginSessionTrackingEnabled bool // Enable the server-side login-session registry (default: true). Gates the SID lookup added to the auth hot path so it can be disabled instantly.
	LoginSessionRetentionDays   int  // Retention/sweep window in days for revoked + expired login-session rows (default: 30)

	// 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)
	WellKnownRateLimit       int // Requests per minute for /.well-known/* endpoints (default: 30)

	// 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)
	StrictRedirectURIs bool          // Require redirect URIs to be loopback or HTTPS (OAuth 2.1 §1.5 / MCP); default: true
	ConsentRemember    bool          // Skip consent page if user already authorized same scope (default: true)

	// RedirectURIPatternMatchingEnabled is the global kill switch for origin-locked
	// path-prefix redirect_uri matching (default: false). When false, patterns
	// stored on a client are ignored and redirect_uri matching stays exact-only.
	// When true, a client with at least one RedirectURIPatterns entry additionally
	// accepts a redirect_uri whose scheme/host/port are byte-exact and whose path
	// is the pattern path or a sub-path of it. The token endpoint binding stays exact.
	RedirectURIPatternMatchingEnabled bool

	// 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 Load

func Load() *Config

func (*Config) TLSEnabled added in v0.27.0

func (c *Config) TLSEnabled() bool

TLSEnabled reports whether TLS serving should be activated. Both TLSCertFile and TLSKeyFile must be set for TLS to be enabled.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration for invalid values

type TokenProfile added in v0.28.0

type TokenProfile struct {
	AccessTokenTTL  time.Duration
	RefreshTokenTTL time.Duration
}

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.

Jump to

Keyboard shortcuts

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