config

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package config provides configuration types and options for Aegis.

Index

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 holds low-level authentication configuration for database operations.
	// REQUIRED. This is typically initialized automatically from the main DB connection.
	Auth auth.Config

	// CoreAuth holds high-level core authentication service configuration.
	// OPTIONAL.
	// Default: DefaultAuthConfig()
	// Use WithAuthConfig 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 Default

func Default() *Config

Default returns a Config with sensible defaults

func (*Config) DeriveSecret

func (c *Config) DeriveSecret(purpose string) []byte

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")

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid

func (*Config) WithAPIOnlyMode

func (c *Config) WithAPIOnlyMode(enabled bool) *Config

WithAPIOnlyMode enables API-only mode (skips CSRF secret requirement) Use this when building APIs without web UI

func (*Config) WithArgon2KeyLength

func (c *Config) WithArgon2KeyLength(length uint32) *Config

WithArgon2KeyLength sets the output key length for Argon2id. Default: 32 bytes (256-bit security). Generally should not be changed.

Example:

cfg := config.Default()
cfg.WithArgon2KeyLength(32)

aegis.New(ctx, cfg, ...)

func (*Config) WithArgon2Memory

func (c *Config) WithArgon2Memory(memory uint32) *Config

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:

cfg := config.Default()
cfg.WithArgon2Memory(128*1024) // 128 MB

aegis.New(ctx, cfg, ...)

func (*Config) WithArgon2Threads

func (c *Config) WithArgon2Threads(threads uint8) *Config

WithArgon2Threads sets the parallelism for Argon2id password hashing. Default: 4 threads.

Example:

cfg := config.Default()
cfg.WithArgon2Threads(4)

aegis.New(ctx, cfg, ...)

func (*Config) WithArgon2Time

func (c *Config) WithArgon2Time(time uint32) *Config

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:

cfg := config.Default()
cfg.WithArgon2Time(2)

aegis.New(ctx, cfg, ...)

func (*Config) WithAuditLogger

func (c *Config) WithAuditLogger(logger core.AuditLogger) *Config

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 (*Config) WithAuthConfig

func (c *Config) WithAuthConfig(authConfig *core.AuthConfig) *Config

WithAuthConfig sets the core authentication configuration

func (*Config) WithCookieDomain

func (c *Config) WithCookieDomain(domain string) *Config

WithCookieDomain sets the cookie domain

func (*Config) WithCookieName

func (c *Config) WithCookieName(name string) *Config

WithCookieName sets the session cookie name Default is "aegis_session"

func (*Config) WithCookieSameSite

func (c *Config) WithCookieSameSite(sameSite string) *Config

WithCookieSameSite sets the SameSite cookie attribute

func (*Config) WithCookieSecure

func (c *Config) WithCookieSecure(secure bool) *Config

WithCookieSecure sets whether cookies should be secure

func (*Config) WithDB

func (c *Config) WithDB(db *sql.DB) *Config

WithDB sets the database connection for Aegis. This is required for storing users, sessions, and authentication data.

Example:

cfg := config.Default()
cfg.WithDB(db)

aegis.New(ctx, cfg, ...)

func (*Config) WithIDGenerator

func (c *Config) WithIDGenerator(generator func() string) *Config

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 (*Config) WithIDStrategy

func (c *Config) WithIDStrategy(strategy core.IDStrategy) *Config

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:

cfg := config.Default()
cfg.WithIDStrategy(core.IDStrategyUUID)

aegis.New(ctx, cfg, ...)

func (*Config) WithLogger

func (c *Config) WithLogger(logger Logger) *Config

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 (*Config) WithPasswordPolicy

func (c *Config) WithPasswordPolicy(policy *core.PasswordPolicyConfig) *Config

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 (*Config) WithRateLimitConfig

func (c *Config) WithRateLimitConfig(cfg *core.RateLimitConfig) *Config

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 (*Config) WithRateLimiting

func (c *Config) WithRateLimiting() *Config

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:

cfg := config.Default()
cfg.WithRateLimiting()

aegis.New(ctx, cfg, ...)

func (*Config) WithRedis

func (c *Config) WithRedis(host string, port int, password string, db int) *Config

WithRedis sets the Redis configuration

func (*Config) WithRefreshExpiry

func (c *Config) WithRefreshExpiry(duration time.Duration) *Config

WithRefreshExpiry sets the refresh token expiry duration

func (*Config) WithRouter

func (c *Config) WithRouter(router router.Router) *Config

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 (*Config) WithSecret

func (c *Config) WithSecret(secret []byte) *Config

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 (*Config) WithSessionExpiry

func (c *Config) WithSessionExpiry(duration time.Duration) *Config

WithSessionExpiry sets the session expiry duration

func (*Config) WithUserFields

func (c *Config) WithUserFields(fields []string) *Config

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 Logger

type Logger interface {
	Info(msg string, keysAndValues ...any)
	Error(msg string, keysAndValues ...any)
	Debug(msg string, keysAndValues ...any)
}

Logger is an optional interface for logging Aegis lifecycle events. Implementations can integrate with any logging framework (zap, logrus, slog, etc).

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.

Jump to

Keyboard shortcuts

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