Documentation
¶
Index ¶
- func Redact(cfg any) any
- type AccountOptions
- type AuditOptions
- type AuthzOptions
- type CacheFileOptions
- type CacheMemoryOptions
- type CasbinOptions
- type DatabaseOptions
- type DebugOptions
- type HTTPOptions
- type HealthOptions
- type LogFileOptions
- type MetricsOptions
- type MySQLOptions
- type ProviderRawOptions
- type RedisOptions
- type SQLiteOptions
- type SelfValidating
- type SensitiveWarning
- type SlogOptions
- type SwaggerOptions
- type Validatable
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Redact ¶
Redact returns a shallow copy of the config struct with all fields tagged sensitive:"true" replaced by "***". Works on any struct (including nested ones). The original struct is never modified.
Use this before logging or serializing config to prevent credential leaks:
logger.Info("config loaded", "config", config.Redact(&cfg))
Types ¶
type AccountOptions ¶
type AccountOptions struct {
Enabled bool `mapstructure:"enabled" default:"false"`
SigningKey string `mapstructure:"signing_key" sensitive:"true"`
Expiration time.Duration `mapstructure:"expiration" default:"2h"`
ResetExpiration time.Duration `mapstructure:"reset_expiration" default:"15m"`
// LoginRateWindow + LoginRateLimit configure per-email login attempt
// throttling on /login. When both are positive the account module
// installs a sliding-window limiter; on threshold exceedance the
// endpoint returns 429 Too Many Requests. Both zero (the default)
// disables the limiter entirely. Recommended production values:
// window=15m, limit=10.
LoginRateWindow time.Duration `mapstructure:"login_rate_window"`
LoginRateLimit int `mapstructure:"login_rate_limit"`
// DisableRegister 关闭 POST /register 公开注册端点。true 时仍支持 login、
// change-password、reset-password 等已认证路径;公开注册路径不注册,
// 直接访问返回 404。适合"内部使用 / 仅 admin 创建账号"的场景。
DisableRegister bool `mapstructure:"disable_register" default:"false"`
// LinkByEmail enables the SPEC §8 LinkByEmail auto-merge path. The
// account module enforces additional double-checks (IdP-side
// EmailVerified=true, !IsAliasedEmail, local-side EmailVerified=true)
// even with this flag on, so default-off is safe; turn on only after
// the application has wired its own email-verification UI.
LinkByEmail bool `mapstructure:"link_by_email" default:"false"`
// AllowedRedirectBacks lists absolute URL prefixes that
// /auth/{name}/start will accept on its ?redirect_back parameter.
// Empty (the default) means relative paths only — the strictest
// posture. Each entry must be a fully-qualified https:// URL with
// no userinfo / query / fragment; account.Module rejects malformed
// entries at startup. See SPEC §6.1.
AllowedRedirectBacks []string `mapstructure:"allowed_redirect_backs"`
// OAuthCallbackFrontendURL is the fixed front-end landing URL the
// OAuth callback flow redirects to after issuing the one-shot auth
// code. The SPA there calls POST /auth/exchange to swap the code
// for a JWT (which never appears in the URL). REQUIRED whenever any
// provider in Providers has enabled=true.
OAuthCallbackFrontendURL string `mapstructure:"oauth_callback_frontend_url"`
// Providers maps provider name → raw config. Each entry is decoded
// by the provider package's factory (registered via
// account.RegisterProviderFactory in init()). Unknown provider
// names cause the builder to fail-fast at startup so a typo doesn't
// silently disable an IdP. SPEC §10.3.
Providers map[string]ProviderRawOptions `mapstructure:"providers"`
}
func (AccountOptions) GoString ¶
func (o AccountOptions) GoString() string
GoString implements fmt.GoStringer for AccountOptions.
Mask both SigningKey and any sensitive map keys inside Providers[name].Raw — without the latter, %#v on an AccountOptions with OAuth providers configured leaks every client_secret / private_key the operator put in yaml.
func (AccountOptions) String ¶
func (o AccountOptions) String() string
String implements fmt.Stringer for AccountOptions.
func (*AccountOptions) Validate ¶
func (o *AccountOptions) Validate() error
type AuditOptions ¶ added in v0.1.4
type AuditOptions struct {
Enabled bool `mapstructure:"enabled" default:"false"`
// AsyncBufferSize is the in-memory channel capacity feeding the
// background sink goroutine. When the channel saturates, behaviour
// is governed by DropOnFull. Restart-only (see Reload semantics).
AsyncBufferSize int `mapstructure:"async_buffer_size" default:"1024"`
// DropOnFull controls overflow behaviour: false = block the calling
// goroutine until space frees (use when audit is non-negotiable for
// compliance), true = drop the entry and increment a counter (use
// when audit must never delay business requests). Restart-only.
DropOnFull bool `mapstructure:"drop_on_full" default:"false"`
// RetentionDays caps how long records survive before the purge
// cron deletes them. Reload-safe.
RetentionDays int `mapstructure:"retention_days" default:"180"`
// PurgeInterval is how often the purge cron sweeps. Reload-safe.
PurgeInterval time.Duration `mapstructure:"purge_interval" default:"24h"`
// PurgeBatchSize bounds DELETE batch size to keep purge from
// holding row locks long enough to stall INSERT. Reload-safe.
PurgeBatchSize int `mapstructure:"purge_batch_size" default:"1000"`
// EnableAdminAPI registers GET /audit/logs (gated by
// middleware.RequireAuthz("audit", "read")) for admin UIs and
// compliance review. Defaults to true; turn off in headless
// deployments that scrape the table directly.
EnableAdminAPI bool `mapstructure:"enable_admin_api" default:"true"`
}
AuditOptions configures the audit log Component (parts/audit). Audit log is the compliance-grade record of "who did what to which resource"; distinct from access log (HTTP traffic) and metrics (aggregate counters). Disabled by default — enable when retention and queryability are explicit product requirements.
Reload semantics (parts/audit Reload):
- reload-safe : RetentionDays / PurgeInterval / PurgeBatchSize
- restart only: AsyncBufferSize (channel capacity, not resizable mid-flight) and DropOnFull (changes producer-side blocking semantics — switching live would surprise hot-path callers).
func (*AuditOptions) Validate ¶ added in v0.1.4
func (o *AuditOptions) Validate() error
Validate enforces the SPEC §8.5 invariants. Non-discriminator — AuditOptions does NOT implement SelfValidating; the framework's recursive walker handles its single level of nested fields fine.
type AuthzOptions ¶ added in v0.1.4
type AuthzOptions struct {
Enabled bool `mapstructure:"enabled" default:"false"`
Driver string `mapstructure:"driver" default:"casbin"`
Casbin CasbinOptions `mapstructure:"casbin"`
}
AuthzOptions controls the authorization layer.
When Enabled is true, autoregister attaches a parts.AuthzComponent using the blessed implementation named by Driver (currently always "casbin"). Driver is reserved for forward compatibility with future alternatives; Validate refuses anything else so a typo doesn't silently disable authorization.
Casbin sub-options live under .Casbin so a future second driver can land alongside without polluting the top-level shape.
func (*AuthzOptions) Validate ¶ added in v0.1.4
func (o *AuthzOptions) Validate() error
Validate enforces the SPEC §6.1 invariants. Disabled bypasses; enabled requires a recognised driver string.
type CacheFileOptions ¶
type CacheFileOptions struct {
Enabled bool `mapstructure:"enabled" default:"false"`
Path string `mapstructure:"path" default:".cache"`
TTL time.Duration `mapstructure:"ttl" default:"1h"`
}
func (*CacheFileOptions) Validate ¶
func (o *CacheFileOptions) Validate() error
type CacheMemoryOptions ¶
type CacheMemoryOptions struct {
Enabled bool `mapstructure:"enabled" default:"false"`
Capacity int `mapstructure:"capacity" default:"10000"`
TTL time.Duration `mapstructure:"ttl" default:"5m"`
}
func (*CacheMemoryOptions) Validate ¶
func (o *CacheMemoryOptions) Validate() error
type CasbinOptions ¶ added in v0.1.4
type CasbinOptions struct {
RedisWatcher bool `mapstructure:"redis_watcher"`
RedisWatcherChannel string `mapstructure:"redis_watcher_channel" default:"chok:authz:policy"`
AuditEnabled bool `mapstructure:"audit_enabled"`
BootstrapAdminUserID string `mapstructure:"bootstrap_admin_user_id" sensitive:"true"`
Model string `mapstructure:"model"`
}
CasbinOptions configures the authz/casbin Authorizer when AuthzOptions.Driver = "casbin".
BootstrapAdminUserID is sensitive: chok.config.Redact + the AccountOptions GoString-style heuristic both mask it on diagnostic dumps via the `*secret*` / `*password*` / `*signing_key*` / `*api_key*` / `*token*` substring rules. The "user_id" name doesn't match those, so we add the explicit `sensitive` tag — leaking the admin-bootstrap user id is low risk but principled to redact alongside other identity-shaped values.
type DatabaseOptions ¶
type DatabaseOptions struct {
Driver string `mapstructure:"driver"` // "sqlite" or "mysql"; empty = disabled
SQLite SQLiteOptions `mapstructure:"sqlite"`
MySQL MySQLOptions `mapstructure:"mysql"`
}
DatabaseOptions provides a discriminator-based database configuration. Instead of having separate MySQLOptions.Enabled and SQLiteOptions.Enabled fields (which can conflict), users set a single Driver field:
database:
driver: sqlite
sqlite:
path: "app.db"
mysql:
host: "127.0.0.1"
When Driver is empty, the component is disabled. The Driver field selects which nested config block is used; the other is ignored.
func (*DatabaseOptions) Validate ¶
func (o *DatabaseOptions) Validate() error
type DebugOptions ¶
type DebugOptions struct {
Enabled bool `mapstructure:"enabled" default:"false"`
}
DebugOptions configures the /componentz debug endpoint. Disabled by default — enable for development or staging environments to expose component topology and init timing via HTTP.
type HTTPOptions ¶
type HTTPOptions struct {
Enabled bool `mapstructure:"enabled" default:"true"`
Addr string `mapstructure:"addr" default:":8080"`
ReadTimeout time.Duration `mapstructure:"read_timeout" default:"30s"`
WriteTimeout time.Duration `mapstructure:"write_timeout" default:"30s"`
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" default:"10s"`
IdleTimeout time.Duration `mapstructure:"idle_timeout" default:"120s"`
// RequestTimeout is the maximum duration for processing a single HTTP
// request. When non-zero, a Timeout middleware is automatically added
// to the middleware stack, cancelling the request context and returning
// 504 if the handler does not complete in time. Zero disables the
// middleware (the default).
RequestTimeout time.Duration `mapstructure:"request_timeout"`
// DrainDelay is the pause between marking /readyz as 503 and actually
// stopping the HTTP server. In Kubernetes deployments this gives the
// load balancer time to deregister the pod before in-flight requests
// are drained. Default 5s; zero disables the delay.
DrainDelay time.Duration `mapstructure:"drain_delay" default:"5s"`
// TrustedProxies is the list of CIDRs / IPs whose X-Forwarded-For and
// X-Real-IP headers gin may honour when computing c.ClientIP(). Empty
// slice (the default) trusts NO proxy — c.ClientIP() returns the
// direct socket peer. Set to ["127.0.0.1"] when fronted by a local
// reverse proxy, ["10.0.0.0/8"] behind an in-cluster LB, etc.
//
// Not setting this means loginLimiter's IP-keyed bucket is bypassable
// by any client spoofing X-Forwarded-For; the fail-closed default
// avoids that trap.
TrustedProxies []string `mapstructure:"trusted_proxies"`
}
func (*HTTPOptions) Validate ¶
func (o *HTTPOptions) Validate() error
type HealthOptions ¶
type HealthOptions struct {
Enabled bool `mapstructure:"enabled" default:"true"`
Path string `mapstructure:"path" default:"/healthz"`
}
HealthOptions configures the /healthz endpoint. When Enabled is true and an HTTP server exists, the HealthComponent is auto-registered. Enabled defaults to true so health is available out of the box; set false to disable.
func (*HealthOptions) Validate ¶
func (o *HealthOptions) Validate() error
type LogFileOptions ¶
type LogFileOptions struct {
Path string `mapstructure:"path"`
MaxSizeMB int `mapstructure:"max_size_mb" default:"100"`
MaxBackups int `mapstructure:"max_backups" default:"7"`
MaxAgeDays int `mapstructure:"max_age_days" default:"30"`
Compress bool `mapstructure:"compress" default:"true"`
}
LogFileOptions configures a rotating log file output (lumberjack-backed). Empty path disables the entry; rotation thresholds are size-based with optional age/backup caps.
func (*LogFileOptions) Validate ¶
func (f *LogFileOptions) Validate() error
type MetricsOptions ¶
type MetricsOptions struct {
Enabled bool `mapstructure:"enabled" default:"true"`
Path string `mapstructure:"path" default:"/metrics"`
}
MetricsOptions configures the /metrics (Prometheus) endpoint. Same auto-registration semantics as HealthOptions.
func (*MetricsOptions) Validate ¶
func (o *MetricsOptions) Validate() error
type MySQLOptions ¶
type MySQLOptions struct {
Enabled bool `mapstructure:"enabled" default:"true"`
Host string `mapstructure:"host" default:"127.0.0.1"`
Port int `mapstructure:"port" default:"3306"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password" sensitive:"true"`
Database string `mapstructure:"database"`
MaxOpenConns int `mapstructure:"max_open_conns" default:"100"`
MaxIdleConns int `mapstructure:"max_idle_conns" default:"10"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime" default:"1h"`
ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time" default:"10m"`
}
func (MySQLOptions) GoString ¶
func (o MySQLOptions) GoString() string
GoString implements fmt.GoStringer for MySQLOptions. Prevents accidental credential leaks when using %#v.
func (MySQLOptions) String ¶
func (o MySQLOptions) String() string
String implements fmt.Stringer for MySQLOptions.
func (*MySQLOptions) Validate ¶
func (o *MySQLOptions) Validate() error
type ProviderRawOptions ¶ added in v0.1.4
type ProviderRawOptions struct {
// Enabled is the master switch. The builder skips entries with
// Enabled=false even if they appear in yaml.
Enabled bool `mapstructure:"enabled"`
// Raw collects every key under the provider entry that isn't
// `enabled`. mapstructure routes unknown keys here when the
// `,remain` tag is present.
Raw map[string]any `mapstructure:",remain"`
}
ProviderRawOptions is the yaml-side representation of a single provider's configuration. Concrete shape (client_id, client_secret, scopes, …) varies per provider, so the typed fields here are minimal (just Enabled) and provider-specific keys land in Raw via mapstructure's `,remain` mechanism. The provider package then calls Decode to convert Raw into its own typed Options struct.
This lets config.AccountOptions stay independent of the provider packages — no circular import: account/providers/google imports config, not the other way round.
func (*ProviderRawOptions) Decode ¶ added in v0.1.4
func (r *ProviderRawOptions) Decode(out any) error
Decode converts the provider-specific Raw map into a typed Options struct. Provider factories use it to extract their config:
var opts google.Options
if err := raw.Decode(&opts); err != nil { return nil, err }
The `mapstructure` tags on the target struct drive the field mapping. time.Duration and similar string-like types are honoured via the default decoder hooks chok already wires for viper.Unmarshal.
type RedisOptions ¶
type RedisOptions struct {
Enabled bool `mapstructure:"enabled" default:"true"`
Addr string `mapstructure:"addr" default:"127.0.0.1:6379"`
Password string `mapstructure:"password" sensitive:"true"`
DB int `mapstructure:"db" default:"0"`
// Network timeouts. Defaults are tighter than go-redis' library
// defaults (DialTimeout 5s, ReadTimeout 3s) because Redis on the hot
// path of a web request should fail fast and let the caller fall back
// (cache miss, circuit breaker) instead of stretching every request
// to the library timeout.
DialTimeout time.Duration `mapstructure:"dial_timeout" default:"1s"`
ReadTimeout time.Duration `mapstructure:"read_timeout" default:"500ms"`
WriteTimeout time.Duration `mapstructure:"write_timeout" default:"500ms"`
PoolTimeout time.Duration `mapstructure:"pool_timeout" default:"1s"`
PoolSize int `mapstructure:"pool_size" default:"10"`
}
func (RedisOptions) GoString ¶
func (o RedisOptions) GoString() string
GoString implements fmt.GoStringer for RedisOptions.
func (RedisOptions) String ¶
func (o RedisOptions) String() string
String implements fmt.Stringer for RedisOptions.
func (*RedisOptions) Validate ¶
func (o *RedisOptions) Validate() error
type SQLiteOptions ¶
type SQLiteOptions struct {
Enabled bool `mapstructure:"enabled" default:"true"`
Path string `mapstructure:"path" default:"app.db"`
}
func (*SQLiteOptions) Validate ¶
func (o *SQLiteOptions) Validate() error
type SelfValidating ¶
type SelfValidating interface {
Validatable
// contains filtered or unexported methods
}
SelfValidating signals that a Validatable type already validates its nested fields itself and the framework's recursive walker must NOT descend into them. Discriminator-shaped configs (e.g. DatabaseOptions where `driver: sqlite` selects between two mutually exclusive branches) implement this marker because blindly recursing would trip the validators on the *unselected* branch — those branches commonly have `enabled: true` defaults that demand fields the user deliberately left blank because they picked the other driver.
The interface intentionally has no methods; it is a pure type tag.
type SensitiveWarning ¶
type SensitiveWarning struct {
Path string // e.g. "Account.SigningKey"
EnvHint string // e.g. "MYAPP_ACCOUNT_SIGNING_KEY"
}
SensitiveWarning describes a sensitive config field that appears to hold a default / placeholder value rather than a real secret.
func AuditSensitiveDefaults ¶
func AuditSensitiveDefaults(cfg any, envPrefix string) []SensitiveWarning
AuditSensitiveDefaults walks a config struct recursively and returns warnings for any field tagged sensitive:"true" whose value looks like a placeholder (contains "CHANGE", "TODO", "FIXME", "example", or is empty while the parent struct is enabled).
envPrefix is the application's environment variable prefix (e.g. "BLOG") so the warning can suggest the correct env var override.
type SlogOptions ¶
type SlogOptions struct {
Level string `mapstructure:"level" default:"info"`
Format string `mapstructure:"format" default:"json"`
Output []string `mapstructure:"output" default:"stdout"`
Files []LogFileOptions `mapstructure:"files"`
// AccessFiles, if non-empty, routes access-log entries (the ones written via
// App.AccessLogger()) to a separate set of rotating files. Output is still
// applied (stdout shows both streams) but app-log Files do NOT receive access
// entries when this is set. Empty = access shares the main logger (legacy).
AccessFiles []LogFileOptions `mapstructure:"access_files"`
// AccessEnabled controls whether the application should record HTTP access
// logs at all. Set false when a fronting proxy (nginx, traefik, etc.) already
// captures access logs and you want to avoid double-logging. Application code
// should consult App.AccessLogEnabled() before mounting the AccessLog
// middleware. Default: true.
AccessEnabled bool `mapstructure:"access_enabled" default:"true"`
}
func (*SlogOptions) Validate ¶
func (o *SlogOptions) Validate() error
type SwaggerOptions ¶
type Validatable ¶
type Validatable interface {
Validate() error
}
Validatable is implemented by config structs that need validation. Run() calls Validate() on each sub-Options after unmarshal, then on the root config if it implements Validatable.