config

package
v0.1.10 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package config provides Gombit's typed configuration boundary.

Runtime packages should receive Config values instead of reading environment variables directly.

Index

Constants

View Source
const (
	// MinProductionJWTSecretLength is the Appendix C floor for production
	// HMAC secrets. Development and test may use a shorter or empty secret
	// (empty disables Bearer auth).
	MinProductionJWTSecretLength = 32

	// DevelopmentJWTPlaceholder is the short value written to generated
	// .env.example files. It enables local Bearer auth but is rejected in
	// production by length and by name. gombit new also writes a gitignored
	// .env with a per-project random secret.
	DevelopmentJWTPlaceholder = "dev-only-not-for-production"

	// DefaultAccessTokenTTL is the signed access-token lifetime.
	DefaultAccessTokenTTL = 15 * time.Minute

	// DefaultRefreshTokenTTL is the refresh-token lifetime. Refresh tokens
	// rotate on each successful refresh.
	DefaultRefreshTokenTTL = 7 * 24 * time.Hour
)
View Source
const RedactedSecret = "*****"

RedactedSecret is the placeholder used in place of passwords and DSN userinfo.

Variables

This section is empty.

Functions

func DefaultCacheNamespace

func DefaultCacheNamespace(appName string, env Environment) string

DefaultCacheNamespace returns the conventional cache namespace for app/env.

func DefaultDocsEnabled

func DefaultDocsEnabled(env Environment) bool

DefaultDocsEnabled reports whether /docs is on when GOMBIT_DOCS_ENABLED is unset. Production is off; development and test are on.

func IsInsecureJWTSecret

func IsInsecureJWTSecret(secret string) bool

IsInsecureJWTSecret reports whether secret is a well-known scaffold placeholder that must never be used in production.

func RedactDSN

func RedactDSN(dsn string) string

RedactDSN returns dsn with userinfo passwords, libpq keyword passwords (password=/pwd=/pass=), and password-like query parameters replaced. SQLite file paths without those keys are unchanged.

func SanitizeError

func SanitizeError(err error, cfg Config) string

SanitizeError returns err.Error() with known secrets from cfg removed.

func SanitizeSecretText

func SanitizeSecretText(text string, cfg Config) string

SanitizeSecretText replaces known secrets from cfg inside text.

func ValidateCache

func ValidateCache(cfg CacheConfig) error

ValidateCache returns explicit field errors for invalid cache settings.

func ValidateDatabase

func ValidateDatabase(cfg DatabaseConfig) error

ValidateDatabase returns explicit field errors for invalid database settings.

func ValidateLogging

func ValidateLogging(cfg LoggingConfig) error

ValidateLogging returns explicit field errors for invalid logging settings.

Types

type APIConfig

type APIConfig struct {
	Prefix string
	// DocsEnabled serves the FastAPI-style UI at /docs.
	// Default() (development) leaves this true. Changing Environment on a
	// Default() value does not flip it — use DefaultFor(env) or set this
	// field. LoadFromEnv uses DefaultDocsEnabled when GOMBIT_DOCS_ENABLED
	// is unset.
	DocsEnabled bool
}

APIConfig contains public API configuration.

type AuthConfig

type AuthConfig struct {
	// JWTSecret is the HMAC key for access tokens and, in cookie mode, the
	// CSRF double-submit token signature. It is never a VITE_* value.
	// Empty disables framework-owned auth routes outside production.
	JWTSecret string
	// AccessTokenTTL is the signed access-token lifetime.
	AccessTokenTTL time.Duration
	// RefreshTokenTTL is the refresh-token lifetime.
	RefreshTokenTTL time.Duration
	// BcryptCost is the bcrypt cost for password hashes. Zero means
	// bcrypt.DefaultCost. Tests may set a lower cost.
	BcryptCost int
	// Mode selects the mounted auth surface. Empty behaves as AuthModeJWT.
	Mode AuthMode
	// CookieSecure sets the Secure attribute on cookie-mode session and CSRF
	// cookies. Production requires true (Appendix C); development may set
	// false only for plain-HTTP localhost testing.
	CookieSecure bool
	// CookieSameSite sets the SameSite attribute on cookie-mode session and
	// CSRF cookies. Empty behaves as CookieSameSiteLax.
	CookieSameSite CookieSameSite
}

AuthConfig contains Bearer JWT (default) and cookie/session (M5-3) auth configuration. Both modes share JWTSecret as the signing/HMAC key.

func (AuthConfig) EffectiveCookieSameSite

func (c AuthConfig) EffectiveCookieSameSite() CookieSameSite

EffectiveCookieSameSite returns c.CookieSameSite, defaulting empty to CookieSameSiteLax.

func (AuthConfig) EffectiveMode

func (c AuthConfig) EffectiveMode() AuthMode

EffectiveMode returns c.Mode, defaulting empty to AuthModeJWT.

func (AuthConfig) Enabled

func (c AuthConfig) Enabled() bool

Enabled reports whether auth routes should be mounted (JWT secret is set).

type AuthMode

type AuthMode string

AuthMode selects the runtime auth surface framework.New mounts (C3). AuthModeJWT (the v0.1 API default) mounts Bearer JWT + refresh rotation. AuthModeCookie (M5-3) mounts the HttpOnly/Secure/SameSite session + CSRF double-submit defense documented in docs/auth-cookie.md.

const (
	// AuthModeJWT is the v0.1 API default (C3). Empty Mode behaves as this.
	AuthModeJWT AuthMode = "jwt"
	// AuthModeCookie is the first-class session/CSRF mode (M5-3), a hard
	// prerequisite of the admin milestone.
	AuthModeCookie AuthMode = "cookie"
)

type CacheConfig

type CacheConfig struct {
	Driver    CacheDriver
	Namespace string
	Redis     RedisConfig
}

CacheConfig contains cache configuration consumed by cache.Open.

type CacheDriver

type CacheDriver string

CacheDriver names a supported cache driver.

const (
	// CacheDriverMemory stores cache values in process memory.
	CacheDriverMemory CacheDriver = "memory"
	// CacheDriverRedis stores cache values in Redis.
	CacheDriverRedis CacheDriver = "redis"
	// CacheDriverNoop disables persistence while preserving cache call sites.
	CacheDriverNoop CacheDriver = "noop"
)

type Config

type Config struct {
	AppName     string
	Environment Environment
	HTTP        HTTPConfig
	API         APIConfig
	Database    DatabaseConfig
	Cache       CacheConfig
	Logging     LoggingConfig
	Auth        AuthConfig
}

Config is the typed configuration consumed by Gombit runtime packages.

func ApplyEnvironmentDefaults

func ApplyEnvironmentDefaults(cfg Config) Config

ApplyEnvironmentDefaults sets fields that follow Environment when the caller did not set them explicitly. LoadFromEnv uses this when GOMBIT_DOCS_ENABLED is unset. WithConfig callers that only change Environment on Default() should use DefaultFor instead.

func Default

func Default() Config

Default returns the default development configuration, including /docs on. It does not follow Environment: mutating Environment on the result leaves DocsEnabled and the cache namespace at development values. Use DefaultFor when constructing a non-development config for framework.WithConfig.

func DefaultFor

func DefaultFor(env Environment) Config

DefaultFor returns Default-shaped configuration for env, including environment-derived DocsEnabled and cache namespace.

func Load

func Load() (Config, error)

Load reads configuration from the process environment and validates it. It first applies .env from the current working directory, if one exists, without overwriting variables the process environment already sets — see loadDotEnv.

func LoadFromEnv

func LoadFromEnv(lookup EnvLookup) (Config, error)

LoadFromEnv reads configuration through lookup and validates it.

func (Config) Redacted

func (c Config) Redacted() Config

Redacted returns a copy of c with secret-bearing fields replaced so it is safe to print (DSN userinfo/passwords and Redis password).

func (Config) Validate

func (c Config) Validate() error

Validate returns explicit field errors for invalid configuration values.

type CookieSameSite

type CookieSameSite string

CookieSameSite is the SameSite attribute for cookie-mode session and CSRF cookies (M5-3). SameSite=None is intentionally not offered: cookie mode always pairs with the CSRF double-submit defense in docs/auth-cookie.md, and None requires cross-site use cases this framework does not target.

const (
	// CookieSameSiteLax is the default: cookies ride along top-level GET
	// navigations but not cross-site POSTs, pairing with CSRF double-submit.
	CookieSameSiteLax CookieSameSite = "lax"
	// CookieSameSiteStrict never sends cookies on cross-site requests.
	CookieSameSiteStrict CookieSameSite = "strict"
)

type DatabaseConfig

type DatabaseConfig struct {
	Driver          DatabaseDriver
	DSN             string
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
}

DatabaseConfig contains SQL database configuration consumed by database.Open.

type DatabaseDriver

type DatabaseDriver string

DatabaseDriver names a supported SQL database driver.

const (
	// DatabaseDriverSQLite selects the GORM SQLite dialector.
	DatabaseDriverSQLite DatabaseDriver = "sqlite"
	// DatabaseDriverPostgres selects the GORM PostgreSQL dialector.
	DatabaseDriverPostgres DatabaseDriver = "postgres"
	// DatabaseDriverMySQL selects the GORM MySQL dialector.
	DatabaseDriverMySQL DatabaseDriver = "mysql"
)

type EnvLookup

type EnvLookup func(key string) (value string, ok bool)

EnvLookup reads an environment variable by name.

type Environment

type Environment string

Environment is the runtime environment name.

const (
	// EnvironmentDevelopment is the default local development environment.
	EnvironmentDevelopment Environment = "development"
	// EnvironmentTest is used by tests and ephemeral verification.
	EnvironmentTest Environment = "test"
	// EnvironmentProduction is used by deployed production applications.
	EnvironmentProduction Environment = "production"
)

type FieldError

type FieldError struct {
	Field   string
	Env     string
	Value   string
	Message string
}

FieldError is one explicit configuration validation failure.

func (FieldError) Error

func (e FieldError) Error() string

Error returns a human-readable validation message.

type FieldErrors

type FieldErrors []FieldError

FieldErrors is a set of configuration validation failures.

func (FieldErrors) Error

func (e FieldErrors) Error() string

Error returns a human-readable validation summary.

type HTTPConfig

type HTTPConfig struct {
	Addr           string
	TrustedProxies []string
	RequestTimeout time.Duration
}

HTTPConfig contains HTTP server configuration.

type LogLevel

type LogLevel string

LogLevel names the configured logging level.

const (
	// LogLevelDebug enables debug, info, warn, and error logs.
	LogLevelDebug LogLevel = "debug"
	// LogLevelInfo enables info, warn, and error logs.
	LogLevelInfo LogLevel = "info"
	// LogLevelWarn enables warn and error logs.
	LogLevelWarn LogLevel = "warn"
	// LogLevelError enables error logs.
	LogLevelError LogLevel = "error"
)

type LogSink

type LogSink string

LogSink names the configured logging sink.

const (
	// LogSinkStderr writes JSON logs to stderr.
	LogSinkStderr LogSink = "stderr"
	// LogSinkStdout writes JSON logs to stdout.
	LogSinkStdout LogSink = "stdout"
	// LogSinkMongo selects an external Mongo logging module.
	LogSinkMongo LogSink = "mongo"
)

type LoggingConfig

type LoggingConfig struct {
	Level LogLevel
	Sink  LogSink
}

LoggingConfig contains structured logging configuration.

type RedisConfig

type RedisConfig struct {
	Addr         string
	Username     string
	Password     string
	DB           int
	DialTimeout  time.Duration
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	TLS          bool
	TLSInsecure  bool
}

RedisConfig contains go-redis client configuration.

Jump to

Keyboard shortcuts

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