// Package config loads and validates the Überbringer daemon configuration // from a TOML file and UBERBRINGER_* environment variables. package config import ( "bytes" "errors" "fmt" "maps" "net/netip" "os" "reflect" "slices" "strconv" "strings" "time" "github.com/go-viper/mapstructure/v2" "github.com/pelletier/go-toml/v2" "github.com/spf13/viper" ) // EnvPrefix starts the environment variables that set config keys: a key // section.name is read from UBERBRINGER_SECTION_NAME, e.g. // UBERBRINGER_PRINTER_ADDRESS. An environment variable wins over the file. const EnvPrefix = "UBERBRINGER" // MinSecretLength is the minimum API secret length in bytes. HS256 keys // shorter than the 256-bit hash output weaken the signature (RFC 7518 §3.2). const MinSecretLength = 32 // MaxLineSpacing is the largest printer.box_line_spacing, the most ESC 3 // takes. const MaxLineSpacing = 255 // Log formats accepted by [LogConfig.Format]. const ( LogFormatText = "text" LogFormatJSON = "json" ) // Config is the root daemon configuration. type Config struct { WebServer WebServerConfig `mapstructure:"webserver"` API APIConfig `mapstructure:"api"` Printer PrinterConfig `mapstructure:"printer"` Format FormatConfig `mapstructure:"format"` Queue QueueConfig `mapstructure:"queue"` Images ImagesConfig `mapstructure:"images"` Sentry SentryConfig `mapstructure:"sentry"` Log LogConfig `mapstructure:"log"` } // WebServerConfig configures the HTTP listener. type WebServerConfig struct { BindIP string `mapstructure:"bind_ip"` Port int `mapstructure:"port"` // RateLimit is the number of API requests one client may make per // RateWindow. RateLimit int `mapstructure:"rate_limit"` RateWindow time.Duration `mapstructure:"rate_window"` // TrustedProxies lists proxy IPs or CIDR ranges whose ProxyHeader is // trusted to carry the real client IP. TrustedProxies []string `mapstructure:"trusted_proxies"` ProxyHeader string `mapstructure:"proxy_header"` // BodyLimit is the maximum request body size in bytes. BodyLimit int `mapstructure:"body_limit"` ReadTimeout time.Duration `mapstructure:"read_timeout"` WriteTimeout time.Duration `mapstructure:"write_timeout"` IdleTimeout time.Duration `mapstructure:"idle_timeout"` } // APIConfig configures API authentication. type APIConfig struct { // Secret is the HS256 key used to verify bearer tokens. Secret string `mapstructure:"secret"` } // PrinterConfig configures the network receipt printer. type PrinterConfig struct { Address string `mapstructure:"address"` Port int `mapstructure:"port"` // Model selects a printer profile, e.g. "tm-t88" or "generic-58mm". Model string `mapstructure:"model"` // CodePage is the character table text is transcoded to, e.g. "cp437". CodePage string `mapstructure:"codepage"` // PaperWidth overrides the profile's printable width in dots. Zero keeps // the profile default. PaperWidth int `mapstructure:"paper_width"` // Columns overrides the number of Font A characters per line used for // word wrapping. Zero derives it from the paper width. Columns int `mapstructure:"columns"` // BoxLineSpacing is the line spacing, in motion units (ESC 3), used // while a box prints, to close the gaps in its vertical borders. Zero // keeps the printer's default spacing. BoxLineSpacing int `mapstructure:"box_line_spacing"` DialTimeout time.Duration `mapstructure:"dial_timeout"` WriteTimeout time.Duration `mapstructure:"write_timeout"` // Retries is how many times a failed send is retried before the job is // marked failed. Retries int `mapstructure:"retries"` RetryDelay time.Duration `mapstructure:"retry_delay"` } // FormatConfig configures how receipts are laid out. type FormatConfig struct { // MaxLines fails a job that would print more lines, all copies // counted. It is a backstop against runaway text. MaxLines int `mapstructure:"max_lines"` // Timezone is the zone the times modules print are in: an IANA name // such as "Europe/London", "UTC", or "Local" for the host's zone. Timezone string `mapstructure:"timezone"` // TimeLayout is the Go time layout those times are printed in. TimeLayout string `mapstructure:"time_layout"` } // QueueConfig configures the print queue. type QueueConfig struct { // Size is the number of jobs that may wait to be printed. Size int `mapstructure:"size"` // History is the number of finished jobs whose status is kept. History int `mapstructure:"history"` } // ImagesConfig configures image elements. type ImagesConfig struct { Timeout time.Duration `mapstructure:"timeout"` MaxBytes int64 `mapstructure:"max_bytes"` // MaxPixels caps the decoded image size to guard against decompression // bombs. MaxPixels int `mapstructure:"max_pixels"` // MaxHeight caps the printed image height in dots after scaling. MaxHeight int `mapstructure:"max_height"` // AllowPrivateNetworks permits fetching from loopback, private and // link-local addresses. AllowPrivateNetworks bool `mapstructure:"allow_private_networks"` // AllowedHosts, when non-empty, restricts fetching to these hosts. Listed // hosts may resolve to private addresses. AllowedHosts []string `mapstructure:"allowed_hosts"` } // SentryConfig configures error reporting. type SentryConfig struct { DSN string `mapstructure:"dsn"` Environment string `mapstructure:"environment"` Debug bool `mapstructure:"debug"` } // LogConfig configures structured logging. type LogConfig struct { Level string `mapstructure:"level"` Format string `mapstructure:"format"` } // Default returns a configuration with every optional setting at its // default. API.Secret and Printer.Address have no defaults. func Default() Config { return Config{ WebServer: WebServerConfig{ BindIP: "127.0.0.1", Port: 8080, RateLimit: 60, RateWindow: time.Minute, TrustedProxies: []string{"127.0.0.1", "::1"}, ProxyHeader: "X-Real-IP", BodyLimit: 4 << 20, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, }, Printer: PrinterConfig{ Port: 9100, // The narrower 512-dot profile is the safe default: on a wider // printer lines are just shorter, while a profile wider than the // printer makes it break words at the right edge. Model: "tm-t88", CodePage: "cp437", DialTimeout: 5 * time.Second, WriteTimeout: 30 * time.Second, Retries: 3, RetryDelay: time.Second, }, Format: FormatConfig{ MaxLines: 2000, Timezone: "Local", TimeLayout: "02 Jan 15:04", }, Queue: QueueConfig{ Size: 100, History: 1000, }, Images: ImagesConfig{ Timeout: 10 * time.Second, MaxBytes: 10 << 20, MaxPixels: 25_000_000, MaxHeight: 4000, }, Sentry: SentryConfig{ Environment: "production", }, Log: LogConfig{ Level: "info", Format: LogFormatText, }, } } // Load builds the configuration from [Default], the TOML file at path and // UBERBRINGER_* environment variables, in rising order of precedence, and // validates the result. An empty path reads no file, for configuration by // environment alone. Keys in the file that Config does not have are errors, // so typos do not silently fall back to defaults. When sentry.dsn is unset, // the SENTRY_DSN environment variable is used. func Load(path string) (*Config, error) { v := viper.New() keys := make(map[string]keyKind) registerDefaults(v, "", reflect.ValueOf(Default()), keys) // Each setting is bound to its own variable. Viper's automatic lookup // would also read a variable named after a section, such as // UBERBRINGER_PRINTER, and let it hide every setting in that section. var envSet []string bound := map[string]bool{PathEnvVar: true} for _, key := range slices.Sorted(maps.Keys(keys)) { if keys[key] != setting { continue } name := envVar(key) bound[name] = true if err := v.BindEnv(key, name); err != nil { return nil, fmt.Errorf("binding %s: %w", name, err) } // Viper treats an empty variable as unset. One that holds only // spaces is refused: for a list it would clear the file's list. value := os.Getenv(name) if value != "" && strings.TrimSpace(value) == "" { return nil, fmt.Errorf("config: %s holds only spaces; unset it or give it a value", name) } if value != "" { envSet = append(envSet, name) } } if path != "" { table, err := readFile(path) if err != nil { return nil, err } unknown, clashes := checkKeys(table, "", "", keys) if len(clashes) > 0 { slices.Sort(clashes) return nil, fmt.Errorf("config %s: keys that differ only in case: %s", path, strings.Join(clashes, "; ")) } if len(unknown) > 0 { slices.Sort(unknown) return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(unknown, ", ")) } if err := v.MergeConfigMap(table); err != nil { return nil, fmt.Errorf("config %s: %w", path, err) } } // The names of the variables that were set, never their values, so a // bad value can be traced to the file or the environment. source := strings.Join(slices.Concat(slices.DeleteFunc([]string{path}, isEmpty), envSet), ", ") if source == "" { source = "(no file and no " + EnvPrefix + "_* settings)" } var cfg Config err := v.Unmarshal(&cfg, viper.DecodeHook(mapstructure.ComposeDecodeHookFunc( durations(), stringToList(), refuseFractions(), stringToNumberOrFlag(), )), // Values are taken as written, apart from the strings that hooks // above parse: environment variables are strings. func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false }, ) if err != nil { return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound)) } if cfg.Sentry.DSN == "" { cfg.Sentry.DSN = os.Getenv("SENTRY_DSN") } if err := cfg.Validate(); err != nil { return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound)) } return &cfg, nil } // PathEnvVar names the config file for the command line's --config. Load // does not read it, but does not count it as a misspelt setting either. const PathEnvVar = EnvPrefix + "_CONFIG" // envVar returns the environment variable that sets the dotted config key, // e.g. UBERBRINGER_PRINTER_ADDRESS for printer.address. func envVar(key string) string { return EnvPrefix + "_" + strings.ToUpper(strings.ReplaceAll(key, ".", "_")) } // unusedVariables returns a note naming the set UBERBRINGER_* variables // that match no setting, which are likely misspelt, or "" when there are // none. Only names are given, never values. func unusedVariables(bound map[string]bool) string { var unused []string for _, entry := range os.Environ() { name, value, _ := strings.Cut(entry, "=") if strings.HasPrefix(name, EnvPrefix+"_") && value != "" && !bound[name] { unused = append(unused, name) } } if len(unused) == 0 { return "" } slices.Sort(unused) return "\n" + EnvPrefix + "_* variables that set nothing: " + strings.Join(unused, ", ") } func isEmpty(s string) bool { return s == "" } // readFile parses the TOML file at path into a table. func readFile(path string) (map[string]any, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("reading config %s: %w", path, err) } if bytes.HasPrefix(data, []byte("\xff\xfe")) || bytes.HasPrefix(data, []byte("\xfe\xff")) { return nil, fmt.Errorf("config %s: the file is UTF-16; save it as UTF-8", path) } // A byte order mark, which some Windows editors write at the start of a // UTF-8 file, is not part of the TOML. data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")) var table map[string]any if err := toml.Unmarshal(data, &table); err != nil { var decodeErr *toml.DecodeError if errors.As(err, &decodeErr) { row, col := decodeErr.Position() return nil, fmt.Errorf("config %s: line %d, column %d: %w", path, row, col, err) } return nil, fmt.Errorf("config %s: %w", path, err) } return table, nil } // keyKind tells a setting from a section that holds settings. type keyKind int const ( setting keyKind = iota + 1 section ) // registerDefaults sets every field of the config struct rv as a Viper // default under its dotted mapstructure key, and records each key in keys. func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[string]keyKind) { rt := rv.Type() for i := range rt.NumField() { tag := rt.Field(i).Tag.Get("mapstructure") if tag == "" { continue } key := tag if prefix != "" { key = prefix + "." + tag } field := rv.Field(i) if field.Kind() == reflect.Struct { keys[key] = section registerDefaults(v, key, field, keys) continue } v.SetDefault(key, field.Interface()) keys[key] = setting } } // checkKeys walks the file's table under prefix. It returns the keys Config // does not have (unknown names, empty tables included, a setting written as // a table, a section written as a value, and a quoted name with a dot, which // is one key rather than a path) and the names in one table that differ only // in case. Names match case-insensitively, as Viper reads them, and Viper // would keep only one of two such names. lookup is the lowercase dotted path // of prefix, which names it as written. func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyKind) (unknown, clashes []string) { names := slices.Sorted(maps.Keys(table)) seen := make(map[string]string, len(names)) for _, name := range names { path := displayKey(name) key := strings.ToLower(name) if prefix != "" { path = prefix + "." + path key = lookup + "." + key } if other, ok := seen[key]; ok { clashes = append(clashes, other+" and "+path) continue } seen[key] = path sub, isTable := table[name].(map[string]any) kind := keys[key] if strings.Contains(name, ".") { kind = 0 } switch { case isTable && kind == section: u, c := checkKeys(sub, path, key, keys) unknown = append(unknown, u...) clashes = append(clashes, c...) case !isTable && kind == setting: default: unknown = append(unknown, path) } } return unknown, clashes } // displayKey quotes a key name that TOML would need quoted, so that spaces, // dots and empty names show in messages. func displayKey(name string) string { if name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == "" { return name } return strconv.Quote(name) } // durations decodes a duration from a string such as "1m30s". A bare number // is refused, since the decoder would read it as nanoseconds. func durations() mapstructure.DecodeHookFunc { durationType := reflect.TypeFor[time.Duration]() return func(from, to reflect.Type, data any) (any, error) { if to != durationType || from == durationType { return data, nil } s, ok := data.(string) if !ok { return nil, errors.New(`expected a duration as a string, such as "5s"`) } d, err := time.ParseDuration(strings.TrimSpace(s)) if err != nil { return nil, errors.New(`expected a duration such as "5s" or "1m30s"`) } return d, nil } } // refuseFractions refuses a number with a fraction for an integer setting, // which the decoder would otherwise truncate. func refuseFractions() mapstructure.DecodeHookFunc { return func(from, to reflect.Type, data any) (any, error) { if from.Kind() != reflect.Float32 && from.Kind() != reflect.Float64 { return data, nil } switch to.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return nil, errors.New("expected a whole number") } return data, nil } } // stringToNumberOrFlag parses a string, such as an environment variable, for // a number or flag setting: decimal digits for a number, true or false for a // flag. Spaces around the value are ignored. func stringToNumberOrFlag() mapstructure.DecodeHookFunc { return func(from, to reflect.Type, data any) (any, error) { if from.Kind() != reflect.String { return data, nil } s := strings.TrimSpace(data.(string)) switch to.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n, err := strconv.ParseInt(s, 10, to.Bits()) if err != nil { return nil, numberError(err) } return reflect.ValueOf(n).Convert(to).Interface(), nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: n, err := strconv.ParseUint(s, 10, to.Bits()) if err != nil { return nil, numberError(err) } return reflect.ValueOf(n).Convert(to).Interface(), nil case reflect.Bool: switch s { case "true": return true, nil case "false": return false, nil } return nil, errors.New("expected true or false") } return data, nil } } func numberError(err error) error { if errors.Is(err, strconv.ErrRange) { return errors.New("number out of range") } return errors.New("expected a whole number in decimal digits") } // stringToList splits a string, such as an environment variable, into a list // at commas and trims the spaces around each item, so "a, b" and "a,b" give // the same list. An empty item, from a doubled or trailing comma, is refused. func stringToList() mapstructure.DecodeHookFunc { return func(from, to reflect.Type, data any) (any, error) { if from.Kind() != reflect.String || to.Kind() != reflect.Slice { return data, nil } raw := strings.TrimSpace(data.(string)) if raw == "" { return []string{}, nil } items := strings.Split(raw, ",") for i := range items { items[i] = strings.TrimSpace(items[i]) if items[i] == "" { return nil, errors.New("a list item is empty; check for a doubled or trailing comma") } } return items, nil } } // Validate reports every problem with the configuration. func (c *Config) Validate() error { var errs []error check := func(ok bool, format string, args ...any) { if !ok { errs = append(errs, fmt.Errorf(format, args...)) } } ws := c.WebServer _, ipErr := netip.ParseAddr(ws.BindIP) check(ipErr == nil, "webserver.bind_ip: %q is not an IP address", ws.BindIP) check(validPort(ws.Port), "webserver.port: %d is out of range 1-65535", ws.Port) check(ws.RateLimit > 0, "webserver.rate_limit must be positive") check(ws.RateWindow > 0, "webserver.rate_window must be positive") check(ws.BodyLimit > 0, "webserver.body_limit must be positive") check(ws.ReadTimeout > 0 && ws.WriteTimeout > 0 && ws.IdleTimeout > 0, "webserver read/write/idle timeouts must be positive") for _, proxy := range ws.TrustedProxies { check(validIPOrPrefix(proxy), "webserver.trusted_proxies: %q is not an IP or CIDR", proxy) } check(len(c.API.Secret) >= MinSecretLength, "api.secret must be at least %d bytes (generate one with `uberbringer secret`)", MinSecretLength) p := c.Printer check(strings.TrimSpace(p.Address) != "", "printer.address is required") check(validPort(p.Port), "printer.port: %d is out of range 1-65535", p.Port) check(p.PaperWidth >= 0, "printer.paper_width must not be negative") check(p.Columns >= 0, "printer.columns must not be negative") check(p.BoxLineSpacing >= 0 && p.BoxLineSpacing <= MaxLineSpacing, "printer.box_line_spacing must be 0-%d", MaxLineSpacing) check(p.DialTimeout > 0 && p.WriteTimeout > 0, "printer dial/write timeouts must be positive") check(p.Retries >= 0, "printer.retries must not be negative") check(p.RetryDelay > 0, "printer.retry_delay must be positive") check(c.Format.MaxLines > 0, "format.max_lines must be positive") if c.Format.Timezone == "" { errs = append(errs, errors.New(`format.timezone is required: an IANA name such as "Europe/London", "UTC" or "Local"`)) } else if _, err := time.LoadLocation(c.Format.Timezone); err != nil { errs = append(errs, fmt.Errorf(`format.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, c.Format.Timezone)) } check(showsTime(c.Format.TimeLayout), `format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout) check(c.Queue.Size > 0, "queue.size must be positive") check(c.Queue.History >= 0, "queue.history must not be negative") img := c.Images check(img.Timeout > 0, "images.timeout must be positive") check(img.MaxBytes > 0, "images.max_bytes must be positive") check(img.MaxPixels > 0, "images.max_pixels must be positive") check(img.MaxHeight > 0, "images.max_height must be positive") check(slices.Contains([]string{"debug", "info", "warn", "error"}, c.Log.Level), "log.level: %q must be one of debug, info, warn, error", c.Log.Level) check(c.Log.Format == LogFormatText || c.Log.Format == LogFormatJSON, "log.format: %q must be %q or %q", c.Log.Format, LogFormatText, LogFormatJSON) return errors.Join(errs...) } // showsTime reports whether layout prints something of the time it // formats: two times that differ in every field format differently. A // layout with none of Go's reference values, such as "HH:MM", prints // itself. func showsTime(layout string) bool { a := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC) b := time.Date(2012, 11, 22, 16, 47, 58, 0, time.FixedZone("X", 3600)) return a.Format(layout) != b.Format(layout) } func validPort(port int) bool { return port >= 1 && port <= 65535 } func validIPOrPrefix(s string) bool { if _, err := netip.ParseAddr(s); err == nil { return true } _, err := netip.ParsePrefix(s) return err == nil }