config

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 13 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 DefaultJobsQueue = "default"

DefaultJobsQueue is the queue a job is dispatched to unless it names one.

View Source
const DefaultStorageLocalRoot = "storage"

DefaultStorageLocalRoot is the local driver's root directory, relative to the working directory, unless GOMBIT_STORAGE_LOCAL_ROOT says otherwise.

View Source
const DefaultStorageLocalURL = "/_storage"

DefaultStorageLocalURL is where the application serves the local and memory drivers' URLs unless GOMBIT_STORAGE_LOCAL_URL says otherwise.

View Source
const DefaultStoragePublicPrefix = "public/"

DefaultStoragePublicPrefix is the key prefix of public objects unless GOMBIT_STORAGE_PUBLIC_PREFIX says otherwise.

View Source
const DefaultStorageS3Region = "us-east-1"

DefaultStorageS3Region is the S3 region unless GOMBIT_STORAGE_S3_REGION says otherwise (many S3-compatible services accept any region).

View Source
const MinStorageURLSecretLength = 32

MinStorageURLSecretLength is the shortest GOMBIT_STORAGE_URL_SECRET.

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 ValidJobName added in v0.5.0

func ValidJobName(name string) bool

ValidJobName reports whether name can identify a job or a queue: 1-128 characters of a-z, 0-9, and _ . : -, starting with a letter or digit. jobs.ValidName is this rule; it lives here because config validates GOMBIT_JOBS_QUEUE and cannot import jobs.

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 ValidateJobs added in v0.5.0

func ValidateJobs(cfg JobsConfig) error

ValidateJobs returns explicit field errors for invalid job settings. It does not check the shared Redis connection; Config.Validate does.

func ValidateLogging

func ValidateLogging(cfg LoggingConfig) error

ValidateLogging returns explicit field errors for invalid logging settings.

func ValidateStorage added in v0.7.0

func ValidateStorage(cfg StorageConfig) error

ValidateStorage returns explicit field errors for invalid storage 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
	Jobs        JobsConfig
	Storage     StorageConfig
	Logging     LoggingConfig
	Auth        AuthConfig
	Security    SecurityConfig
}

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 LoadFromDir added in v0.1.13

func LoadFromDir(dir string) (Config, error)

LoadFromDir reads configuration for the project rooted at dir. It applies dir/.env with the process environment taking precedence (as Load does for cwd), then reads and validates. Unlike Load it never mutates the process environment or the working directory, so it is safe under concurrency and for tooling that inspects a directory other than cwd — e.g. gombit contract app --dir.

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
	// Required declares whether the application needs a database to function —
	// the signal a deployment host uses to decide whether to provision one
	// (surfaced in the HOST-1 application contract). Defaults to true because a
	// Gombit app is database-backed by default; set it false for an app that
	// runs without one. It does not itself force a database at startup.
	Required        bool
	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 is the per-handler deadline propagated into the request
	// context (and thus into DB/cache calls that honor it). It is opt-in: the
	// default is 0, which imposes no deadline (issue #270 / PERF-12). The
	// deadline is applied inside the request_context middleware, which always
	// runs; when this is 0 only the deadline setup is skipped, and that skip is
	// a true no-op (no timer, no extra context) so it costs nothing on the
	// request path. The http.Server read/write/idle timeouts remain the
	// connection-level safety net regardless. Scaffolded apps set
	// GOMBIT_HTTP_REQUEST_TIMEOUT explicitly so new projects keep a per-handler
	// deadline. A negative value is rejected by Validate.
	RequestTimeout time.Duration
}

HTTPConfig contains HTTP server configuration.

type JobsConfig added in v0.5.0

type JobsConfig struct {
	Driver JobsDriver
	// Queue is the default queue name.
	Queue string
	// Namespace prefixes every Redis key, so apps and environments sharing a
	// Redis server do not share queues.
	Namespace string
}

JobsConfig contains background-job configuration consumed by jobs.Open. The redis driver connects with Cache.Redis, the shared GOMBIT_REDIS_* settings.

type JobsDriver added in v0.5.0

type JobsDriver string

JobsDriver names a supported background-job queue driver.

const (
	// JobsDriverSync runs a dispatched job immediately, inside the
	// dispatching call. It needs no infrastructure and no worker.
	JobsDriverSync JobsDriver = "sync"
	// JobsDriverMemory queues jobs in process memory. Queued jobs are lost
	// when the process exits.
	JobsDriverMemory JobsDriver = "memory"
	// JobsDriverRedis queues jobs durably in Redis, using the shared Redis
	// connection settings (GOMBIT_REDIS_*).
	JobsDriverRedis JobsDriver = "redis"
)

type LocalStorageConfig added in v0.7.0

type LocalStorageConfig struct {
	// Root is the directory objects are stored under; a relative path is
	// resolved against the working directory when the app starts. It is
	// created on the first write.
	Root string
	// URL is where the application serves stored objects' URLs, for the
	// local and memory drivers: a path ("/_storage", the default) or an
	// absolute URL ending in one. Empty: those drivers have no URLs.
	URL string
}

LocalStorageConfig configures the local filesystem driver.

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.

type S3StorageConfig added in v0.7.0

type S3StorageConfig struct {
	// Endpoint is the service's base URL ("https://<account>.r2.cloudflarestorage.com",
	// "http://127.0.0.1:9000" for a local MinIO). Empty means AWS S3.
	Endpoint string
	// Region signs requests. Default us-east-1.
	Region string
	// Bucket holds the objects. Required.
	Bucket string
	// Prefix, when set, is put before every key ("myapp/"), so several apps
	// or environments can share a bucket.
	Prefix string
	// AccessKeyID and SecretAccessKey are static credentials. Leave both
	// empty to use the AWS default credential chain (environment, shared
	// config, an IAM role on EC2/ECS/Fargate).
	AccessKeyID     string
	SecretAccessKey string
	// ForcePathStyle addresses the bucket in the path
	// (endpoint/bucket/key) rather than the host (bucket.endpoint/key), as
	// MinIO and many S3-compatible services need.
	ForcePathStyle bool
	// PublicURL is the base URL public objects are read from, standing for
	// the bucket's root (a CDN, a custom domain, or the bucket's address).
	// Empty: public objects have no URL (signed URLs still work).
	PublicURL string
}

S3StorageConfig configures the S3-compatible driver.

type SecurityConfig added in v0.2.0

type SecurityConfig struct {
	// SanitizeInput installs the request-input HTML sanitizer (issue #271 /
	// PERF-13). It is off by default: the framework does not rewrite request
	// input. XSS is an output-encoding concern — the generated React frontend
	// escapes text (JSX), the framework admin SPA renders values as React text
	// (not HTML), a JSON API response is not an HTML sink, and the response CSP
	// is a backstop — and stripping markup on ingress corrupts faithful values
	// (a comment of `x < y`, a stored `<b>bold</b>`) as well as costing
	// allocations on every write request.
	// Enable it (GOMBIT_SECURITY_SANITIZE_INPUT=true) to restore the legacy
	// behavior: JSON string values and query values are stripped to plain text
	// before handlers run, with WithRawBodyPaths still exempting webhook paths.
	// For field-level stripping without turning the whole pipeline back on,
	// call framework.SanitizeHTML from a handler instead.
	SanitizeInput bool
}

SecurityConfig contains opt-in application security toggles.

type StorageConfig added in v0.7.0

type StorageConfig struct {
	Driver StorageDriver
	// PublicPrefix makes the objects whose keys start with it public: they
	// have permanent URLs (storage.PublicURL). Empty makes none public.
	// Default "public/".
	PublicPrefix string
	// URLSecret signs the local and memory drivers' URLs (HMAC-SHA256), at
	// least 32 bytes. Empty derives one from Auth.JWTSecret; with neither,
	// those drivers have no URLs.
	URLSecret string
	Local     LocalStorageConfig
	S3        S3StorageConfig
}

StorageConfig contains object storage configuration, opened by framework.New into App.Storage().

type StorageDriver added in v0.7.0

type StorageDriver string

StorageDriver names a supported object storage driver.

const (
	// StorageDriverLocal stores objects as files under
	// Storage.Local.Root, for development and single-host deployments.
	StorageDriverLocal StorageDriver = "local"
	// StorageDriverMemory keeps objects in process memory, for tests.
	// Stored objects are lost when the process exits.
	StorageDriverMemory StorageDriver = "memory"
	// StorageDriverS3 stores objects in an S3-compatible bucket (AWS S3,
	// Cloudflare R2, MinIO, ...), configured by Storage.S3.
	StorageDriverS3 StorageDriver = "s3"
)

Jump to

Keyboard shortcuts

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