Documentation
¶
Overview ¶
Package config loads, validates, and hot-reloads the subflux YAML configuration.
Index ¶
- Constants
- Variables
- func ParseDuration(s string) (time.Duration, error)
- func ValidLogFormat(f LogFormat) bool
- func ValidLogLevel(l LogLevel) bool
- type AudioRule
- type Config
- func (c *Config) Adaptive() subflux.AdaptiveConfig
- func (c *Config) AuthDisabled() bool
- func (c *Config) BackupEnabled() bool
- func (c *Config) BackupFrequency() time.Duration
- func (c *Config) BackupPath() string
- func (c *Config) BackupRetention() int
- func (c *Config) BasicAuthEnabled() bool
- func (c *Config) CheckBreachedPasswords() bool
- func (c *Config) Close() error
- func (c *Config) EmbeddedPolicy() subflux.EmbeddedPolicy
- func (c *Config) HostAllowlist() *webhttp.HostPolicy
- func (c *Config) LanguageCodes() []string
- func (c *Config) LanguageRulesForUI() subflux.LanguageRulesJSON
- func (c *Config) LoggingFormat() subflux.LogFormat
- func (c *Config) LoggingLevel() subflux.LogLevel
- func (c *Config) MinScoreForTarget(t *subflux.SubtitleTarget, _ subflux.MediaType) int
- func (c *Config) OIDC() auth.OIDCConfig
- func (c *Config) OIDCEnabled() bool
- func (c *Config) PollInterval() time.Duration
- func (c *Config) PostProcess() subflux.PostProcessConfig
- func (c *Config) ProviderPriority(name subflux.ProviderID) int
- func (c *Config) Providers() map[subflux.ProviderID]subflux.ProviderCfg
- func (c *Config) ProvidersForTarget(t *subflux.SubtitleTarget, allProviders []subflux.ProviderID) []subflux.ProviderID
- func (c *Config) Radarr() subflux.ArrConfig
- func (c *Config) RemoveUnderRoot(ctx context.Context, path string) error
- func (c *Config) ResolveTargetsWithFallback(originalLang string, audioLangs []string) []subflux.SubtitleTarget
- func (c *Config) Scores() subflux.Scores
- func (c *Config) Search() subflux.SearchConfig
- func (c *Config) SessionAbsoluteTimeout() time.Duration
- func (c *Config) SessionIdleTimeout() time.Duration
- func (c *Config) Sonarr() subflux.ArrConfig
- func (c *Config) Sync() subflux.SyncConfig
- func (c *Config) TrustedProxyNets() []*net.IPNet
- func (c *Config) Validate() error
- func (c *Config) ValidatePath(ctx context.Context, path string) error
- func (c *Config) WebAuthnRPID() string
- type Duration
- type FieldDependencyError
- type LanguageRules
- type LogFormat
- type LogLevel
- type LoggingConfig
- type ScoringConfig
- type ValidationError
- type ValidationErrors
- type Validator
Constants ¶
const ( // DefaultConfigPath is the container-internal config file path. DefaultConfigPath = "/config/config.yaml" // DefaultDBPath is the container-internal bbolt database file path. // Core and auth buckets live in the same file; no separate auth path. DefaultDBPath = "/config/subflux.bolt" // AdminSocketDir is the private runtime directory holding the admin // bootstrap Unix socket. The directory (0700, owned by the effective // UID) is the custody boundary: only in-container processes running as // the server's user can traverse into it, so the zero-credential // bootstrap channel is unreachable over every TCP path. Deliberately // under /tmp (in-container overlayfs in the shipped composes — never a // volume mount), NOT under /config: /config is a user-controlled volume // where a socket path would outlive the container and cross the mount // trust boundary. A future read_only deployment profile must add // tmpfs: /tmp or both this socket and the health marker fail. AdminSocketDir = "/tmp/subflux-admin" // AdminSocketPath is the Unix domain socket the admin bootstrap server // listens on, inside AdminSocketDir. AdminSocketPath = AdminSocketDir + "/admin.sock" // AdminBootstrapURLPath is the one route served on the admin socket. // Hand-written here (not generated apipaths): the endpoint is // deliberately off the wirespec table, so config owns the path string // for both main.go and the CLI socket client. AdminBootstrapURLPath = "/api/admin/bootstrap" )
Container-internal path constants (single source of truth).
const DefaultSessionAbsoluteTimeout = defaults.DefaultSessionAbsoluteTimeout
DefaultSessionAbsoluteTimeout is the session absolute timeout when not configured.
const DefaultSessionIdleTimeout = defaults.DefaultSessionIdleTimeout
DefaultSessionIdleTimeout is the session idle timeout when not configured.
const ServerPort = 8374
ServerPort is the fixed HTTP server port.
Variables ¶
var ( // ErrEmbeddedProviderRemoved indicates a legacy embedded-provider config // shape (alpha hard cutover, no migration path): the fail-fast message is // guidance to the new section, not a compatibility path. ErrEmbeddedProviderRemoved = errors.New("providers.embedded has been replaced by the top-level embedded_subtitles section") // ErrNoArr indicates neither Sonarr nor Radarr is configured. ErrNoArr = errors.New("at least one of sonarr or radarr must be configured") // ErrNoDefaultLang indicates the languages.default section is empty. ErrNoDefaultLang = errors.New("languages.default must contain at least one subtitle target; every item must have a fallback set of subtitles to look for") // ErrDuplicateAudioRule indicates a duplicate audio language rule was found. ErrDuplicateAudioRule = errors.New("duplicate audio language rule") // ErrSearchConfig indicates an invalid search configuration. ErrSearchConfig = errors.New("invalid search configuration") // ErrAdaptiveConfig indicates an invalid adaptive configuration. ErrAdaptiveConfig = errors.New("invalid adaptive configuration") // ErrLoggingConfig indicates an invalid logging configuration. ErrLoggingConfig = errors.New("invalid logging configuration") // ErrPostProcessConfig indicates an invalid post-processing configuration. ErrPostProcessConfig = errors.New("invalid post-processing configuration") // ErrScoringConfig indicates an invalid scoring configuration. ErrScoringConfig = errors.New("invalid scoring configuration") // ErrMissingAPIKey indicates a required API key is not configured. ErrMissingAPIKey = errors.New("API key required") )
Sentinel errors for the most common config validation failures. These enable errors.Is dispatch instead of string matching.
var ErrConfigTooLarge = errors.New("config too large")
ErrConfigTooLarge indicates the config file or data exceeds the maximum allowed size.
var ErrPathNotAllowed = errors.New("path not under any configured media_roots")
ErrPathNotAllowed is returned when a path is not under any configured media_roots.
var ErrVariantConflict = errors.New("cannot set both variant and variants")
ErrVariantConflict indicates both "variant" and "variants" are set on the same target.
Functions ¶
func ParseDuration ¶
ParseDuration extends time.ParseDuration with D, M, and Y suffixes.
func ValidLogFormat ¶
ValidLogFormat returns true if the format is a recognized value, judged by slogx.ParseFormat — the same case-insensitive, trimming normalization setupLogging applies when it consumes the value — so validation and consumption cannot drift. The empty string is "unset" (the caller falls back to the default), not a valid value.
func ValidLogLevel ¶
ValidLogLevel returns true if the level is a recognized value.
Types ¶
type AudioRule ¶
type AudioRule struct {
Audio string `yaml:"audio"` // ISO 639-1 audio to match
Subtitles []yamlSubtitleTarget `yaml:"subtitles"` // What to download
}
AudioRule maps a detected audio language to subtitle targets.
type Config ¶
type Config struct {
ProvidersCfg map[subflux.ProviderID]yamlProviderCfg `yaml:"providers"`
Scoring ScoringConfig `yaml:"scoring"`
SonarrCfg yamlArrConfig `yaml:"sonarr"`
RadarrCfg yamlArrConfig `yaml:"radarr"`
Logging LoggingConfig `yaml:"logging"`
Languages LanguageRules `yaml:"languages"`
MediaRootDirs []string `yaml:"media_roots"`
// TrustedProxies lists reverse-proxy CIDR ranges (or single IPs as /32)
// whose X-Forwarded-For may be trusted for client-IP resolution. Empty
// (the default) trusts nothing: the socket peer is used and XFF ignored.
TrustedProxies []string `yaml:"trusted_proxies"`
// AllowedHosts lists the exact hostnames/IPs subflux answers for; a
// request whose Host header is not listed is rejected with 403, breaking
// DNS rebinding (loopback requests are exempt so the container
// healthcheck keeps working). Empty (the default) accepts any Host.
AllowedHosts []string `yaml:"allowed_hosts"`
Auth yamlAuthConfig `yaml:"auth"`
Backup yamlBackupConfig `yaml:"backup"`
Cfg yamlSearchConfig `yaml:"search"`
AdaptiveCfg yamlAdaptiveConfig `yaml:"adaptive"`
PostProcessing yamlPostProcessConfig `yaml:"post_processing"`
EmbeddedSubtitles yamlEmbeddedConfig `yaml:"embedded_subtitles"`
PollIntervalCfg Duration `yaml:"poll_interval"`
// contains filtered or unexported fields
}
Config is the top-level configuration.
func Load ¶
Load reads and validates a config file. The context enables cancellation during file I/O and validation (e.g. media_roots stat loop).
func LoadFromBytes ¶
LoadFromBytes parses config from raw YAML bytes.
func (*Config) Adaptive ¶
func (c *Config) Adaptive() subflux.AdaptiveConfig
Adaptive returns the adaptive search config.
func (*Config) AuthDisabled ¶
AuthDisabled returns whether authentication is completely bypassed. This is an undocumented escape hatch. Read live per request by the authenticator's bypass predicate, so toggling it hot-applies.
func (*Config) BackupEnabled ¶
BackupEnabled reports whether scheduled database backups are enabled.
func (*Config) BackupFrequency ¶
BackupFrequency returns how often a backup is taken.
func (*Config) BackupPath ¶
BackupPath returns the backup directory override. Empty means backups are written next to the database file.
func (*Config) BackupRetention ¶
BackupRetention returns how many backup files to keep on disk.
func (*Config) BasicAuthEnabled ¶
BasicAuthEnabled returns whether password login is enabled. Defaults to true if not explicitly set.
func (*Config) CheckBreachedPasswords ¶
CheckBreachedPasswords returns whether to check passwords against HIBP. Defaults to true if not explicitly set.
func (*Config) EmbeddedPolicy ¶ added in v0.1.148
func (c *Config) EmbeddedPolicy() subflux.EmbeddedPolicy
EmbeddedPolicy returns the typed embedded subtitle codec policy from the top-level embedded_subtitles section. This is the single config source for the search engine's ignored-codec decision (the detector takes no settings and always returns every track).
func (*Config) HostAllowlist ¶ added in v0.1.166
func (c *Config) HostAllowlist() *webhttp.HostPolicy
HostAllowlist returns the parsed exact-match Host allowlist built from allowed_hosts. It is inactive (a safe pass-through) when allowed_hosts is unset — the backward-compatible default — and active as soon as any non-blank entry is configured. Read by the server's host gate on every activation, which re-wraps the middleware chain with the returned policy.
func (*Config) LanguageCodes ¶
LanguageCodes returns a deduplicated list of all subtitle language codes across all rules and the default. Used for full library scans where audio language isn't known upfront.
func (*Config) LanguageRulesForUI ¶
func (c *Config) LanguageRulesForUI() subflux.LanguageRulesJSON
LanguageRulesForUI returns the raw (unexpanded) language rules for the UI.
func (*Config) LoggingFormat ¶
LoggingFormat returns the configured log format.
func (*Config) LoggingLevel ¶
LoggingLevel returns the configured log level.
func (*Config) MinScoreForTarget ¶
MinScoreForTarget returns the minimum score for a target, falling back to the global min_score. The mediaType parameter is part of search.Cfg's signature for future per-media-type score overrides; currently unused.
func (*Config) OIDC ¶ added in v0.4.0
func (c *Config) OIDC() auth.OIDCConfig
OIDC returns the OIDC provider settings.
func (*Config) OIDCEnabled ¶
OIDCEnabled returns whether OIDC login is enabled.
func (*Config) PollInterval ¶
PollInterval returns the configured arr history poll interval.
func (*Config) PostProcess ¶ added in v0.4.0
func (c *Config) PostProcess() subflux.PostProcessConfig
PostProcess returns the post-processing configuration.
func (*Config) ProviderPriority ¶
func (c *Config) ProviderPriority(name subflux.ProviderID) int
ProviderPriority returns the priority for a provider (lower = higher trust). Returns subflux.DefaultProviderPriority for unconfigured or zero-priority providers.
func (*Config) Providers ¶
func (c *Config) Providers() map[subflux.ProviderID]subflux.ProviderCfg
Providers returns the resolved provider configuration map. The map, and every Settings map inside it, is a copy: a caller that adds a provider or edits a setting is editing its own copy, not the live configuration every subsequent scan reads. The copy is deep because a shallow one would change nothing — the aliasing that matters is the inner Settings map, which both the cached and the recomputed path used to hand out directly.
Named Providers, not ProviderConfigs: the raw YAML field beside it is ProvidersCfg, which is the same split SonarrCfg/Sonarr() and RadarrCfg/ Radarr() already use in this package — the Cfg suffix marks the unparsed decode target, and the bare name is the resolved answer callers want. The two also differ in TYPE (yamlProviderCfg vs subflux.ProviderCfg), so the field was the one claiming a name it could not honour.
func (*Config) ProvidersForTarget ¶
func (c *Config) ProvidersForTarget(t *subflux.SubtitleTarget, allProviders []subflux.ProviderID) []subflux.ProviderID
ProvidersForTarget returns which providers to use for a subtitle target.
func (*Config) Radarr ¶
Radarr returns the Radarr connection config. Returns empty config when disabled.
func (*Config) RemoveUnderRoot ¶
RemoveUnderRoot deletes a file atomically through an os.Root handle, eliminating the TOCTOU window between path validation and removal. Returns nil if the file was removed or did not exist.
If no media_roots are configured the operation is refused — earlier versions fell back to a bare os.Remove(path), but that gave callers implicit superuser-style FS access that bypassed the os.Root containment guarantee. The fallback also tripped CodeQL's go/path-injection rule for code paths where row.Path originates from the database (and ultimately from a filesystem scan that itself ran outside any safety envelope). Refusing is the safe default; admins who want subtitle deletion to work must configure media_roots.
func (*Config) ResolveTargetsWithFallback ¶
func (c *Config) ResolveTargetsWithFallback(originalLang string, audioLangs []string) []subflux.SubtitleTarget
ResolveTargetsWithFallback implements the full language resolution chain: 1. Match originalLanguage against rules 2. If no match, try each audio track language against rules 3. If still no match, return default targets
func (*Config) Search ¶
func (c *Config) Search() subflux.SearchConfig
Search returns the search config.
ExcludeArrTags is cloned: it is the only reference-typed field in the struct, and the scan loop reads it every pass, so a caller sorting or rewriting the returned slice in place would be editing the live config. []string needs exactly one level of copy — a string is an immutable value, so the clone shares nothing a caller can reach.
func (*Config) SessionAbsoluteTimeout ¶
SessionAbsoluteTimeout returns the session absolute timeout. Defaults to 7 days if not configured.
func (*Config) SessionIdleTimeout ¶
SessionIdleTimeout returns the session idle timeout. Defaults to 24 hours if not configured.
func (*Config) Sonarr ¶
Sonarr returns the Sonarr connection config. Returns empty config when disabled.
func (*Config) Sync ¶ added in v0.4.0
func (c *Config) Sync() subflux.SyncConfig
Sync returns the sync configuration.
func (*Config) TrustedProxyNets ¶ added in v0.1.92
TrustedProxyNets returns the parsed trusted reverse-proxy CIDR set used for spoof-safe client-IP resolution. It is empty when trusted_proxies is unset (the default), in which case the client IP resolves to the unspoofable socket peer and X-Forwarded-For is ignored. Read by internal/server's activation on every reload, which holds this concrete type, so a trusted_proxies edit re-parses without a restart.
The returned set is a deep copy. This one is worth the allocation: it is the set that decides whether X-Forwarded-For is honoured, so a caller holding a live *net.IPNet could widen the trusted range — and net.IPNet's own fields are byte slices, so copying only the pointers or only the slice would still share the address and mask a caller can overwrite in place.
func (*Config) ValidatePath ¶
ValidatePath checks that a file path is under one of the configured media roots using pre-opened os.Root handles for symlink-safe containment. Returns an error if the path escapes all roots.
If no media roots are configured the check FAILS CLOSED, matching RemoveUnderRoot: earlier versions allowed every path in that case, which turned an unset media_roots into an allow-all for request-supplied preview/sync/manual-download paths. Admins who want path-based operations must configure media_roots.
func (*Config) WebAuthnRPID ¶
WebAuthnRPID returns the configured WebAuthn Relying Party ID. Returns empty string if not set (auto-detected from hostname at runtime).
type Duration ¶
Duration wraps time.Duration with extended YAML parsing that supports day (D), month (M), and year (Y) suffixes in addition to Go's standard duration units (ns, us, ms, s, m, h). Only single-unit values are supported for extended units (e.g. "7D", "3M", "1Y").
Conversions: 1D = 24h, 1M = 730h (30.4 days), 1Y = 8760h (365 days).
func (*Duration) UnmarshalYAML ¶
UnmarshalYAML parses a duration string, extending time.ParseDuration with D (days), M (months), and Y (years) suffixes.
The error deliberately withholds the offending value (and does not wrap the parse error, whose message embeds it): the scalar may be an expanded ${VAR} secret after yamlenv.Expand, and this error reaches the startup log and the PUT /api/config response via the app-owned error passthrough (appOwnedDecodeErr, handed to yamlenv.Load). The line number is the locator; the value stays out of operator-facing text (field-name-only posture, as in seadex-scout).
type FieldDependencyError ¶
type FieldDependencyError struct {
Field string // the field that has the constraint
DependsOn string // the field it depends on
Reason string // human-readable explanation
}
FieldDependencyError is a typed error for config field-requires-field constraint violations. Callers can use errors.As to programmatically identify which field combinations are invalid.
func (*FieldDependencyError) Error ¶
func (e *FieldDependencyError) Error() string
type LanguageRules ¶
type LanguageRules struct {
// Rules maps an audio language (ISO 639-1) to subtitle targets.
// Example: audio "en" -> download "fr" normal + "fr" forced
Rules []AudioRule `yaml:"rules"`
// Default applies when the audio language doesn't match any rule.
// If empty, no subtitles are downloaded for unmatched audio.
Default []yamlSubtitleTarget `yaml:"default,omitempty"`
}
LanguageRules maps detected audio languages to desired subtitle downloads.
type LogFormat ¶
LogFormat is a typed string for log output formats. The recognized values are owned by slogx.ParseFormat (see ValidLogFormat), not by a local vocabulary.
type LoggingConfig ¶
LoggingConfig controls log output.
type ScoringConfig ¶
ScoringConfig allows users to customize scoring weights.
type ValidationError ¶
type ValidationError struct {
Field string // e.g. "search.min_score", "sonarr.api_key"
Message string
}
ValidationError is a structured validation error that identifies the offending config field. Callers can use errors.As to extract the field name for targeted UI display or programmatic handling.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type ValidationErrors ¶
type ValidationErrors struct {
// contains filtered or unexported fields
}
ValidationErrors accumulates multiple validation errors from config checking. Sub-validators append directly via Add, eliminating the repeated if-err-append boilerplate.
func (*ValidationErrors) Add ¶
func (ve *ValidationErrors) Add(err error)
Add appends a non-nil error to the accumulator.
func (*ValidationErrors) Err ¶
func (ve *ValidationErrors) Err() error
Err returns the accumulated errors joined, or nil if none.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package defaults provides the shared configuration default values and validation thresholds used by both config/ and config/schema/.
|
Package defaults provides the shared configuration default values and validation thresholds used by both config/ and config/schema/. |
|
Package schema generates the UI configuration schema for the web frontend.
|
Package schema generates the UI configuration schema for the web frontend. |