Documentation
¶
Overview ¶
Package config provides configuration types and options for Aegis.
Index ¶
- type Config
- type Logger
- type Option
- func WithAPIOnlyMode(enabled bool) Option
- func WithArgon2KeyLength(length uint32) Option
- func WithArgon2Memory(memory uint32) Option
- func WithArgon2Threads(threads uint8) Option
- func WithArgon2Time(time uint32) Option
- func WithAuditLogger(logger core.AuditLogger) Option
- func WithAuthConfig(authConfig *core.AuthConfig) Option
- func WithCookieDomain(domain string) Option
- func WithCookieName(name string) Option
- func WithCookieSameSite(sameSite string) Option
- func WithCookieSecure(secure bool) Option
- func WithDB(db *sql.DB) Option
- func WithIDGenerator(generator func() string) Option
- func WithIDStrategy(strategy core.IDStrategy) Option
- func WithLogger(logger Logger) Option
- func WithPasswordPolicy(policy *core.PasswordPolicyConfig) Option
- func WithRateLimitConfig(cfg *core.RateLimitConfig) Option
- func WithRateLimiting() Option
- func WithRedis(host string, port int, password string, db int) Option
- func WithRefreshExpiry(duration time.Duration) Option
- func WithRouter(router router.Router) Option
- func WithSecret(secret []byte) Option
- func WithSessionExpiry(duration time.Duration) Option
- func WithUserFields(fields []string) Option
- type RedisConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// DB is the database provider for storing users, sessions, and auth data.
// Use a pointer so nil can represent "not provided" and to avoid copying
// a large sql.DB value accidentally.
DB *sql.DB
// Router is the HTTP router for mounting authentication endpoints.
// REQUIRED. Use WithRouter to set this.
Router router.Router
// Logger is an optional logger for Aegis lifecycle events.
// OPTIONAL. Use WithLogger to enable logging.
// Default: nil (no logging)
Logger Logger
// AuditLogger is an optional audit logger for security events.
// OPTIONAL. Use WithAuditLogger to enable audit logging.
// Default: nil (no audit logging)
AuditLogger core.AuditLogger
// Secret is the master secret for Aegis.
// REQUIRED for web applications (or use WithAPIOnlyMode for API-only apps).
// MUST be cryptographically random (32+ bytes recommended).
// All plugin-specific secrets (CSRF, OAuth, JWT, etc.) are derived from this.
// Use WithSecret to set this.
Secret []byte
// SessionExpiry is the duration before a session token expires.
// REQUIRED (has default).
// Default: 24 hours
// Production recommendation: 15 minutes to 24 hours, depending on sensitivity.
// Use WithSessionExpiry to override.
SessionExpiry time.Duration
// RefreshExpiry is the duration before a refresh token expires.
// REQUIRED (has default).
// Default: 7 days
// MUST be greater than SessionExpiry.
// Production recommendation: 7-30 days.
// Use WithRefreshExpiry to override.
RefreshExpiry time.Duration
// CookieDomain is the domain for session cookies.
// OPTIONAL.
// Default: "" (cookie applies to current domain only)
// Set to ".example.com" to share cookies across subdomains.
// Use WithCookieDomain to set this.
CookieDomain string
// CookieName is the name of the session cookie.
// OPTIONAL.
// Default: "aegis_session"
// Use WithCookieName to customize.
CookieName string
// CookieSecure determines if cookies are sent only over HTTPS.
// REQUIRED (has default).
// Default: true
// MUST be true in production for security.
// Use WithCookieSecure to override (only for local development).
CookieSecure bool
// CookieHTTPOnly prevents JavaScript from accessing cookies.
// REQUIRED (has default).
// Default: true
// MUST be true in production to prevent XSS attacks.
// DO NOT override in production.
CookieHTTPOnly bool
// CookieSameSite controls cross-site cookie behavior.
// REQUIRED (has default).
// Default: "Lax"
// Options: "Strict" (maximum protection), "Lax" (balanced), "None" (cross-site, requires Secure=true)
// Production recommendation: "Strict" or "Lax"
// Use WithCookieSameSite to override.
CookieSameSite string
// APIMode skips CSRF secret requirement for API-only applications.
// OPTIONAL.
// Default: false
// Set to true if building an API without browser-based sessions.
// Use WithAPIOnlyMode to enable.
APIMode bool
// Argon2Time is the number of iterations for Argon2id hashing.
// REQUIRED (has default).
// Default: 1
// Production recommendation: 1-3 iterations (higher = more secure but slower).
// See SECURITY.md for detailed guidance.
Argon2Time uint32
// Argon2Memory is the memory cost in KB for Argon2id hashing.
// REQUIRED (has default).
// Default: 64 MB (65536 KB)
// Production recommendation: 64-256 MB depending on server resources.
// See SECURITY.md for detailed guidance.
Argon2Memory uint32
// Argon2Threads is the degree of parallelism for Argon2id hashing.
// REQUIRED (has default).
// Default: 4
// Production recommendation: 4 threads is optimal for most servers.
Argon2Threads uint8
// Argon2KeyLength is the output key length in bytes for Argon2id.
// REQUIRED (has default).
// Default: 32 bytes (256-bit security)
// DO NOT change unless you have specific requirements.
Argon2KeyLength uint32
// IDGenerator is an optional custom function for generating IDs.
// OPTIONAL.
// Default: nil (uses built-in ULID generation - sortable, time-based, 26 characters)
// Override with: UUID, sequential IDs, or custom format (KSUID, nanoid, etc.)
// Example: WithIDGenerator(func() string { return uuid.New().String() })
// Use WithIDGenerator to set this.
IDGenerator func() string
// IDStrategy defines the algorithm used for generating unique identifiers.
// OPTIONAL.
// Default: core.IDStrategyULID
// Options: core.IDStrategyULID, core.IDStrategyUUID, core.IDStrategyCustom
// Use WithIDStrategy to set this.
IDStrategy core.IDStrategy
// Redis is optional configuration for Redis-based session storage.
// OPTIONAL.
// Default: nil (uses database for session storage)
// Use WithRedis to enable Redis sessions.
Redis *RedisConfig
// ========== AUTH CONFIGURATION ==========
// Auth holds authentication configuration.
// REQUIRED.
// Use WithCoreAuthConfig to set this.
Auth auth.Config
// CoreAuth holds core authentication configuration.
// OPTIONAL.
// Default: DefaultAuthConfig()
// Use WithCoreAuthConfig to set this.
CoreAuth *core.AuthConfig
// RateLimitEnabled enables rate limiting middleware.
// OPTIONAL.
// Default: false
// Use WithRateLimiting to enable.
RateLimitEnabled bool
// RateLimitConfig holds rate limiting configuration.
// OPTIONAL.
// Default: nil (uses DefaultRateLimitConfig() if enabled)
// Use WithRateLimiting or WithRateLimitConfig to configure.
RateLimitConfig *core.RateLimitConfig
// LoginAttemptConfig holds login attempt tracking configuration.
// OPTIONAL.
// Default: nil (uses DefaultLoginAttemptConfig() if rate limiting enabled)
// Use WithLoginAttemptConfig to configure.
LoginAttemptConfig *core.LoginAttemptConfig
}
Config holds the configuration for Aegis authentication framework.
Required fields:
- DB: sql.DB
- Router: HTTP router (use WithRouter)
- CSRFSecret: 32+ byte random secret (required for web apps, or use WithAPIOnlyMode)
All other fields have secure defaults and are optional. See SECURITY.md for production security recommendations.
func (*Config) DeriveSecret ¶
DeriveSecret derives a purpose-specific secret from the master secret. This uses HKDF-SHA256 to cryptographically separate secrets for different purposes. Returns nil if no master secret is configured.
Plugins should define their own purpose strings (e.g., "oauth-state", "jwt-signing"). This ensures cryptographic separation between different uses.
Example:
oauthSecret := cfg.DeriveSecret("oauth-state")
jwtSecret := cfg.DeriveSecret("jwt-signing")
type Logger ¶
type Logger interface {
Info(msg string, keysAndValues ...interface{})
Error(msg string, keysAndValues ...interface{})
Debug(msg string, keysAndValues ...interface{})
}
Logger is an optional interface for logging Aegis lifecycle events. Implementations can integrate with any logging framework (zap, logrus, slog, etc).
type Option ¶
type Option func(*Config)
Option is a functional option for configuring Aegis
func WithAPIOnlyMode ¶
WithAPIOnlyMode enables API-only mode (skips CSRF secret requirement) Use this when building APIs without web UI
func WithArgon2KeyLength ¶
WithArgon2KeyLength sets the output key length for Argon2id. Default: 32 bytes (256-bit security). Generally should not be changed.
Example:
aegis.New(ctx, config.WithArgon2KeyLength(32), ...)
func WithArgon2Memory ¶
WithArgon2Memory sets the memory cost in KB for Argon2id password hashing. Higher values increase security but also memory usage. Default: 65536 (64 MB). Recommended: 64-256 MB depending on resources.
Example:
aegis.New(ctx, config.WithArgon2Memory(128*1024), ...) // 128 MB
func WithArgon2Threads ¶
WithArgon2Threads sets the parallelism for Argon2id password hashing. Default: 4 threads.
Example:
aegis.New(ctx, config.WithArgon2Threads(4), ...)
func WithArgon2Time ¶
WithArgon2Time sets the number of iterations for Argon2id password hashing. Higher values increase security but also CPU time for password operations. Default: 1. Recommended: 1-3 depending on latency requirements.
Example:
aegis.New(ctx, config.WithArgon2Time(2), ...)
func WithAuditLogger ¶
func WithAuditLogger(logger core.AuditLogger) Option
WithAuditLogger sets an optional audit logger for security events. The audit logger will receive events for authentication attempts, user actions, etc. Example: WithAuditLogger(&MyAuditLogger{})
func WithAuthConfig ¶
func WithAuthConfig(authConfig *core.AuthConfig) Option
WithAuthConfig sets the core authentication configuration
func WithCookieDomain ¶
WithCookieDomain sets the cookie domain
func WithCookieName ¶
WithCookieName sets the session cookie name Default is "aegis_session"
func WithCookieSameSite ¶
WithCookieSameSite sets the SameSite cookie attribute
func WithCookieSecure ¶
WithCookieSecure sets whether cookies should be secure
func WithDB ¶
WithDB sets the database connection for Aegis. This is required for storing users, sessions, and authentication data.
Example:
db, _ := sql.Open("postgres", "postgres://user:pass@localhost:5432/db?sslmode=require")
aegis.New(ctx, config.WithDB(db), ...)
func WithIDGenerator ¶
WithIDGenerator sets a custom ID generation function, overriding the default ULID strategy.
By default, Aegis uses ULID (Universally Unique Lexicographically Sortable Identifier) which provides sortable, time-based IDs that work across restarts and distributed systems.
Use this option to override with:
- UUID: for standard UUID v4 format
- Custom libraries: KSUID, nanoid, etc.
- Database sequences: if handling at application level
Examples:
- UUID: WithIDGenerator(func() string { return uuid.New().String() })
- KSUID: WithIDGenerator(func() string { return ksuid.New().String() })
func WithIDStrategy ¶
func WithIDStrategy(strategy core.IDStrategy) Option
WithIDStrategy sets the global ID generation strategy for Aegis.
By default, Aegis uses ULID (Universally Unique Lexicographically Sortable Identifier) which provides sortable, time-based IDs.
Options:
- core.IDStrategyULID: Sortable, 26 chars (default)
- core.IDStrategyUUID: Random UUID v4, 36 chars
Example:
aegis.New(ctx, config.WithIDStrategy(core.IDStrategyUUID), ...)
func WithLogger ¶
WithLogger sets an optional logger for observability of Aegis lifecycle events. The logger will receive events for plugin registration, initialization, and errors. Example: WithLogger(slog.Default()) or a custom logger implementation
func WithPasswordPolicy ¶
func WithPasswordPolicy(policy *core.PasswordPolicyConfig) Option
WithPasswordPolicy sets custom password validation policies. This controls password strength requirements for user registration.
Example:
policy := &core.PasswordPolicyConfig{
MinLength: 12,
RequireUpper: true,
RequireLower: true,
RequireDigit: true,
RequireSpecial: true,
MaxLength: 256,
}
aegis.New(config.WithPasswordPolicy(policy), ...)
func WithRateLimitConfig ¶
func WithRateLimitConfig(cfg *core.RateLimitConfig) Option
WithRateLimitConfig sets custom rate limiting configuration. This also enables rate limiting.
Example:
cfg := &core.RateLimitConfig{
RequestsPerWindow: 50,
WindowDuration: time.Minute,
ByIP: true,
}
aegis.New(config.WithRateLimitConfig(cfg), ...)
func WithRateLimiting ¶
func WithRateLimiting() Option
WithRateLimiting enables rate limiting with default configuration. Rate limiting helps protect against brute-force attacks and DoS. By default, it allows 100 requests per minute per IP.
Example:
aegis.New(config.WithRateLimiting(), ...)
func WithRefreshExpiry ¶
WithRefreshExpiry sets the refresh token expiry duration
func WithRouter ¶
WithRouter sets the HTTP router for Aegis. router: an implementation of server.Router (ChiRouter, DefaultRouter, etc.)
Example:
mux := http.NewServeMux() router := server.NewDefaultRouter(mux) aegis.New(config.WithRouter(router), ...)
func WithSecret ¶
WithSecret sets the master secret for Aegis. All plugin-specific secrets (CSRF, OAuth state, JWT, etc.) are derived from this. The secret should be at least 32 bytes of cryptographically random data.
Example:
// Generate a secure secret (do this once and store securely) secret := make([]byte, 32) crypto/rand.Read(secret) aegis.New(config.WithSecret(secret), ...)
func WithSessionExpiry ¶
WithSessionExpiry sets the session expiry duration
func WithUserFields ¶
WithUserFields configures which extension fields are included in user API responses. Use this to control what plugin data (role, permissions, organizations, etc.) appears in user responses.
If not configured, all extension fields from plugins are included by default.
Example - Include only specific fields:
aegis.New(
config.WithUserFields([]string{"role", "permissions", "organizations"}),
...
)
This produces JSON responses like:
{
"id": "user_123",
"email": "user@example.com",
"role": "admin",
"permissions": ["read", "write"],
"organizations": ["org1", "org2"]
}
Note: Session endpoints (/session/validate) always return both session and enriched user data. This config only filters which extension fields appear in the user portion of responses.
type RedisConfig ¶
type RedisConfig struct {
// Host is the Redis server hostname or IP address.
// REQUIRED if using Redis.
Host string
// Port is the Redis server port.
// REQUIRED if using Redis.
// Default Redis port: 6379
Port int
// Password is the Redis authentication password.
// REQUIRED in production for security.
// See SECURITY.md for Redis security recommendations.
Password string
// DB is the Redis database number (0-15).
// OPTIONAL.
// Default: 0
DB int
}
RedisConfig holds configuration for Redis session storage.