Read the config with Viper and environment variables, on Go 1.27.4
The config loader uses Viper instead of BurntSushi/toml. Every setting can also come from UBERBRINGER_<SECTION>_<KEY>, which wins over the file, and UBERBRINGER_CONFIG sets the default of --config; set empty, no file is read, so a container can run from the environment alone. Each setting is bound to its own variable, so a variable named after a section changes nothing. The file is parsed with go-toml and checked as written: unknown keys, empty tables and keys that differ only in case are errors, a UTF-8 BOM is skipped and a UTF-16 file is refused. Values are decoded strictly: durations are strings, numbers decimal, flags true or false, and a fraction for a whole number is refused. Errors name the file, the line of a syntax error and the variables that were set, never their values. `uberbringer config get <key>` prints one setting as the daemon would use it. install.sh reads body_limit, bind_ip and port through it, so the config is checked before the service restarts and Caddy proxies to the configured address. The script then waits for the daemon to answer, downloads Caddy's key and source list before replacing them, requires Caddy's own repository, keeps the Caddyfile during dpkg upgrades, detects an existing import loosely, logs Caddy's other errors, drops query strings from the access log and validates the domain and printer address more tightly. go.mod names Go 1.27.4 with no toolchain line, and the workflows check against the go line. The changelog folds the unreleased entries into 0.2.0, which is not tagged yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
92dcacb3b9
commit
eacd0bfd27
18 files changed
+1244
-248
No files matched your search
@@ -8,6 +8,8 @@ import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
@@ -47,8 +49,17 @@ func Execute(ctx context.Context, build BuildInfo, args []string) error {
|
||||
return root.ExecuteContext(ctx)
|
||||
}
|
||||
|
||||
// configPathEnv sets the default of --config. Set but empty, it means no
|
||||
// config file: the configuration then comes from UBERBRINGER_* variables and
|
||||
// defaults alone.
|
||||
const configPathEnv = config.PathEnvVar
|
||||
|
||||
func newRootCommand(build BuildInfo) *cobra.Command {
|
||||
var configPath string
|
||||
defaultConfigPath := "config.toml"
|
||||
if path, ok := os.LookupEnv(configPathEnv); ok {
|
||||
defaultConfigPath = path
|
||||
}
|
||||
root := &cobra.Command{
|
||||
Use: "uberbringer",
|
||||
Short: "Runs the Überbringer receipt printer daemon.",
|
||||
@@ -59,16 +70,51 @@ func newRootCommand(build BuildInfo) *cobra.Command {
|
||||
return serve(cmd.Context(), configPath, build, cmd.OutOrStdout())
|
||||
},
|
||||
}
|
||||
root.PersistentFlags().StringVarP(&configPath, "config", "c", "config.toml", "path to the daemon config file")
|
||||
root.PersistentFlags().StringVarP(&configPath, "config", "c", defaultConfigPath,
|
||||
`path to the config file, or "" to read none; `+configPathEnv+` sets the default`)
|
||||
root.AddCommand(
|
||||
newVersionCommand(build),
|
||||
newSecretCommand(),
|
||||
newTokenCommand(&configPath),
|
||||
newPreviewCommand(&configPath),
|
||||
newConfigCommand(&configPath),
|
||||
)
|
||||
return root
|
||||
}
|
||||
|
||||
func newConfigCommand(configPath *string) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "config",
|
||||
Short: "Reads the configuration.",
|
||||
Args: cobra.NoArgs,
|
||||
}
|
||||
cmd.AddCommand(&cobra.Command{
|
||||
Use: "get <key>",
|
||||
Short: "Prints one setting, e.g. webserver.port, as the daemon would use it.",
|
||||
Long: "Prints one setting as the daemon would use it: from the config file, " +
|
||||
"UBERBRINGER_* variables and the defaults, once the whole configuration " +
|
||||
"is valid. api.secret is never printed.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
key := args[0]
|
||||
if strings.EqualFold(key, "api.secret") {
|
||||
return fmt.Errorf("api.secret is not printed")
|
||||
}
|
||||
cfg, err := config.Load(*configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
value, err := cfg.Value(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(cmd.OutOrStdout(), value)
|
||||
return err
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newVersionCommand(build BuildInfo) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "version",
|
||||
|
||||
@@ -22,6 +22,51 @@ func runCommand(t *testing.T, args ...string) (string, error) {
|
||||
return out.String(), err
|
||||
}
|
||||
|
||||
func TestConfigPathFromEnvironment(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value *string
|
||||
want string
|
||||
}{
|
||||
{"unset", nil, "config.toml"},
|
||||
{"set", ptr("/etc/uberbringer/config.toml"), "/etc/uberbringer/config.toml"},
|
||||
{"empty means no file", ptr(""), ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if tt.value == nil {
|
||||
t.Setenv(configPathEnv, "")
|
||||
os.Unsetenv(configPathEnv)
|
||||
} else {
|
||||
t.Setenv(configPathEnv, *tt.value)
|
||||
}
|
||||
got := newRootCommand(BuildInfo{}).PersistentFlags().Lookup("config").DefValue
|
||||
if got != tt.want {
|
||||
t.Errorf("--config default = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The token command reads a config made of environment variables alone when
|
||||
// --config is empty.
|
||||
func TestTokenCommandFromEnvironment(t *testing.T) {
|
||||
secret := "env-only-secret-env-only-secret-0123"
|
||||
t.Setenv("UBERBRINGER_API_SECRET", secret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "192.168.1.245")
|
||||
out, err := runCommand(t, "token", "--config", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = jwt.Parse(strings.TrimSpace(out), func(*jwt.Token) (any, error) { return []byte(secret), nil },
|
||||
jwt.WithValidMethods([]string{"HS256"}))
|
||||
if err != nil {
|
||||
t.Errorf("token does not verify with the environment's secret: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func ptr(s string) *string { return &s }
|
||||
|
||||
func TestVersionCommand(t *testing.T) {
|
||||
out, err := runCommand(t, "version")
|
||||
if err != nil {
|
||||
@@ -102,3 +147,33 @@ func TestNewRequestID(t *testing.T) {
|
||||
t.Errorf("request ID %q is not a req_ TypeID", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigGetCommand(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
secret := "config-get-secret-config-get-secret-01"
|
||||
body := "[webserver]\nport = 9090\n[api]\nsecret = \"" + secret + "\"\n[printer]\naddress = \"192.168.1.245\"\n"
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
out, err := runCommand(t, "config", "get", "--config", path, "webserver.port")
|
||||
if err != nil || out != "9090\n" {
|
||||
t.Errorf("config get webserver.port = %q, %v; want \"9090\n\"", out, err)
|
||||
}
|
||||
out, err = runCommand(t, "config", "get", "--config", path, "webserver.body_limit")
|
||||
if err != nil || out != "4194304\n" {
|
||||
t.Errorf("config get webserver.body_limit = %q, %v; want the default", out, err)
|
||||
}
|
||||
for _, key := range []string{"api.secret", "API.Secret"} {
|
||||
out, err = runCommand(t, "config", "get", "--config", path, key)
|
||||
if err == nil || strings.Contains(out, secret) || strings.Contains(err.Error(), secret) {
|
||||
t.Errorf("config get %s = %q, %v; want a refusal without the secret", key, out, err)
|
||||
}
|
||||
}
|
||||
if _, err = runCommand(t, "config", "get", "--config", path, "printer.adress"); err == nil {
|
||||
t.Error("config get accepted an unknown key")
|
||||
}
|
||||
if _, err = runCommand(t, "config", "get", "--config", filepath.Join(t.TempDir(), "missing.toml"), "webserver.port"); err == nil {
|
||||
t.Error("config get succeeded without a config file")
|
||||
}
|
||||
}
|
||||
+370
-62
@@ -1,19 +1,30 @@
|
||||
// Package config loads and validates the Überbringer daemon configuration
|
||||
// from a TOML file.
|
||||
// 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/BurntSushi/toml"
|
||||
"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
|
||||
@@ -30,126 +41,126 @@ const (
|
||||
|
||||
// Config is the root daemon configuration.
|
||||
type Config struct {
|
||||
WebServer WebServerConfig `toml:"webserver"`
|
||||
API APIConfig `toml:"api"`
|
||||
Printer PrinterConfig `toml:"printer"`
|
||||
Format FormatConfig `toml:"format"`
|
||||
Queue QueueConfig `toml:"queue"`
|
||||
Images ImagesConfig `toml:"images"`
|
||||
Sentry SentryConfig `toml:"sentry"`
|
||||
Log LogConfig `toml:"log"`
|
||||
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 `toml:"bind_ip"`
|
||||
Port int `toml:"port"`
|
||||
BindIP string `mapstructure:"bind_ip"`
|
||||
Port int `mapstructure:"port"`
|
||||
|
||||
// RateLimit is the number of API requests one client may make per
|
||||
// RateWindow.
|
||||
RateLimit int `toml:"rate_limit"`
|
||||
RateWindow time.Duration `toml:"rate_window"`
|
||||
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 `toml:"trusted_proxies"`
|
||||
ProxyHeader string `toml:"proxy_header"`
|
||||
TrustedProxies []string `mapstructure:"trusted_proxies"`
|
||||
ProxyHeader string `mapstructure:"proxy_header"`
|
||||
|
||||
// BodyLimit is the maximum request body size in bytes.
|
||||
BodyLimit int `toml:"body_limit"`
|
||||
BodyLimit int `mapstructure:"body_limit"`
|
||||
|
||||
ReadTimeout time.Duration `toml:"read_timeout"`
|
||||
WriteTimeout time.Duration `toml:"write_timeout"`
|
||||
IdleTimeout time.Duration `toml:"idle_timeout"`
|
||||
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 `toml:"secret"`
|
||||
Secret string `mapstructure:"secret"`
|
||||
}
|
||||
|
||||
// PrinterConfig configures the network receipt printer.
|
||||
type PrinterConfig struct {
|
||||
Address string `toml:"address"`
|
||||
Port int `toml:"port"`
|
||||
Address string `mapstructure:"address"`
|
||||
Port int `mapstructure:"port"`
|
||||
|
||||
// Model selects a printer profile, e.g. "tm-t88" or "generic-58mm".
|
||||
Model string `toml:"model"`
|
||||
Model string `mapstructure:"model"`
|
||||
|
||||
// CodePage is the character table text is transcoded to, e.g. "cp437".
|
||||
CodePage string `toml:"codepage"`
|
||||
CodePage string `mapstructure:"codepage"`
|
||||
|
||||
// PaperWidth overrides the profile's printable width in dots. Zero keeps
|
||||
// the profile default.
|
||||
PaperWidth int `toml:"paper_width"`
|
||||
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 `toml:"columns"`
|
||||
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 `toml:"box_line_spacing"`
|
||||
BoxLineSpacing int `mapstructure:"box_line_spacing"`
|
||||
|
||||
DialTimeout time.Duration `toml:"dial_timeout"`
|
||||
WriteTimeout time.Duration `toml:"write_timeout"`
|
||||
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 `toml:"retries"`
|
||||
RetryDelay time.Duration `toml:"retry_delay"`
|
||||
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 `toml:"max_lines"`
|
||||
MaxLines int `mapstructure:"max_lines"`
|
||||
}
|
||||
|
||||
// QueueConfig configures the print queue.
|
||||
type QueueConfig struct {
|
||||
// Size is the number of jobs that may wait to be printed.
|
||||
Size int `toml:"size"`
|
||||
Size int `mapstructure:"size"`
|
||||
|
||||
// History is the number of finished jobs whose status is kept.
|
||||
History int `toml:"history"`
|
||||
History int `mapstructure:"history"`
|
||||
}
|
||||
|
||||
// ImagesConfig configures image elements.
|
||||
type ImagesConfig struct {
|
||||
Timeout time.Duration `toml:"timeout"`
|
||||
MaxBytes int64 `toml:"max_bytes"`
|
||||
Timeout time.Duration `mapstructure:"timeout"`
|
||||
MaxBytes int64 `mapstructure:"max_bytes"`
|
||||
|
||||
// MaxPixels caps the decoded image size to guard against decompression
|
||||
// bombs.
|
||||
MaxPixels int `toml:"max_pixels"`
|
||||
MaxPixels int `mapstructure:"max_pixels"`
|
||||
|
||||
// MaxHeight caps the printed image height in dots after scaling.
|
||||
MaxHeight int `toml:"max_height"`
|
||||
MaxHeight int `mapstructure:"max_height"`
|
||||
|
||||
// AllowPrivateNetworks permits fetching from loopback, private and
|
||||
// link-local addresses.
|
||||
AllowPrivateNetworks bool `toml:"allow_private_networks"`
|
||||
AllowPrivateNetworks bool `mapstructure:"allow_private_networks"`
|
||||
|
||||
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
|
||||
// hosts may resolve to private addresses.
|
||||
AllowedHosts []string `toml:"allowed_hosts"`
|
||||
AllowedHosts []string `mapstructure:"allowed_hosts"`
|
||||
}
|
||||
|
||||
// SentryConfig configures error reporting.
|
||||
type SentryConfig struct {
|
||||
DSN string `toml:"dsn"`
|
||||
Environment string `toml:"environment"`
|
||||
Debug bool `toml:"debug"`
|
||||
DSN string `mapstructure:"dsn"`
|
||||
Environment string `mapstructure:"environment"`
|
||||
Debug bool `mapstructure:"debug"`
|
||||
}
|
||||
|
||||
// LogConfig configures structured logging.
|
||||
type LogConfig struct {
|
||||
Level string `toml:"level"`
|
||||
Format string `toml:"format"`
|
||||
Level string `mapstructure:"level"`
|
||||
Format string `mapstructure:"format"`
|
||||
}
|
||||
|
||||
// Default returns a configuration with every optional setting at its
|
||||
@@ -203,32 +214,329 @@ func Default() Config {
|
||||
}
|
||||
}
|
||||
|
||||
// Load reads the TOML file at path on top of [Default] and validates the
|
||||
// result. Keys not recognised by Config are reported as errors so typos do not
|
||||
// silently fall back to defaults. When sentry.dsn is unset, the SENTRY_DSN
|
||||
// environment variable is used.
|
||||
// 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) {
|
||||
cfg := Default()
|
||||
meta, err := toml.DecodeFile(path, &cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading config %s: %w", path, err)
|
||||
}
|
||||
if undecoded := meta.Undecoded(); len(undecoded) > 0 {
|
||||
keys := make([]string, len(undecoded))
|
||||
for i, key := range undecoded {
|
||||
keys[i] = key.String()
|
||||
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
|
||||
}
|
||||
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
|
||||
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", path, err)
|
||||
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
|
||||
@@ -255,7 +563,7 @@ func (c *Config) Validate() error {
|
||||
"api.secret must be at least %d bytes (generate one with `uberbringer secret`)", MinSecretLength)
|
||||
|
||||
p := c.Printer
|
||||
check(p.Address != "", "printer.address is required")
|
||||
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")
|
||||
|
||||
@@ -164,6 +164,106 @@ func TestLoadErrors(t *testing.T) {
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
|
||||
wantErr: "log.level",
|
||||
},
|
||||
{
|
||||
name: "unknown empty table",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[printr]\n",
|
||||
wantErr: "unknown keys: printr",
|
||||
},
|
||||
{
|
||||
name: "unknown empty subtable",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[printer.extra]\n",
|
||||
wantErr: "unknown keys: printer.extra",
|
||||
},
|
||||
{
|
||||
name: "unknown empty inline table",
|
||||
body: "extra = {}\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
|
||||
wantErr: "unknown keys: extra",
|
||||
},
|
||||
{
|
||||
name: "quoted dotted key",
|
||||
body: "\"log.level\" = \"debug\"\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
|
||||
wantErr: `unknown keys: "log.level"`,
|
||||
},
|
||||
{
|
||||
name: "table for a setting",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[printer.port]\nnumber = 9100\n",
|
||||
wantErr: "unknown keys: printer.port",
|
||||
},
|
||||
{
|
||||
name: "value for a section",
|
||||
body: "log = \"debug\"\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
|
||||
wantErr: "unknown keys: log",
|
||||
},
|
||||
{
|
||||
name: "fraction for an integer",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nretries = 2.9\n",
|
||||
wantErr: "printer.retries",
|
||||
},
|
||||
{
|
||||
name: "fraction for a duration",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ndial_timeout = 2.5\n",
|
||||
wantErr: "printer.dial_timeout",
|
||||
},
|
||||
{
|
||||
name: "number for a string",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nmodel = 88\n",
|
||||
wantErr: "printer.model",
|
||||
},
|
||||
{
|
||||
name: "empty string for an integer",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nretries = \"\"\n",
|
||||
wantErr: "printer.retries",
|
||||
},
|
||||
{
|
||||
name: "number for a flag",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[images]\nallow_private_networks = 1\n",
|
||||
wantErr: "images.allow_private_networks",
|
||||
},
|
||||
{
|
||||
name: "syntax error names its line",
|
||||
body: "[printer]\naddress = \"p\n\"\n",
|
||||
wantErr: "line 2",
|
||||
},
|
||||
{
|
||||
name: "tables that differ only in case",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[Printer]\nport = 9101\n",
|
||||
wantErr: "keys that differ only in case: Printer and printer",
|
||||
},
|
||||
{
|
||||
name: "settings that differ only in case",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nport = 1000\nPORT = 2000\n",
|
||||
wantErr: "keys that differ only in case: printer.PORT and printer.port",
|
||||
},
|
||||
{
|
||||
name: "bare number for a duration",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ndial_timeout = 5\n",
|
||||
wantErr: `'printer.dial_timeout' expected a duration as a string`,
|
||||
},
|
||||
{
|
||||
name: "number string in another base",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nretries = \"0x10\"\n",
|
||||
wantErr: "'printer.retries' expected a whole number in decimal digits",
|
||||
},
|
||||
{
|
||||
name: "flag string other than true or false",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[sentry]\ndebug = \"1\"\n",
|
||||
wantErr: "'sentry.debug' expected true or false",
|
||||
},
|
||||
{
|
||||
name: "key with a space is quoted",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n\"retry delay\" = \"1s\"\n",
|
||||
wantErr: `unknown keys: printer."retry delay"`,
|
||||
},
|
||||
{
|
||||
name: "blank printer address",
|
||||
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \" \"\n",
|
||||
wantErr: "printer.address is required",
|
||||
},
|
||||
{
|
||||
name: "UTF-16 file",
|
||||
body: "\xff\xfe[\x00a\x00p\x00i\x00]\x00",
|
||||
wantErr: "the file is UTF-16; save it as UTF-8",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -194,9 +294,208 @@ func TestExampleConfigLoads(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadEnvironmentOverridesFile(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
[api]
|
||||
secret = "`+validSecret+`"
|
||||
[printer]
|
||||
address = "file.lan"
|
||||
retries = 2
|
||||
`)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "env.lan")
|
||||
t.Setenv("UBERBRINGER_PRINTER_DIAL_TIMEOUT", "2s")
|
||||
t.Setenv("UBERBRINGER_WEBSERVER_PORT", "9090")
|
||||
t.Setenv("UBERBRINGER_IMAGES_ALLOW_PRIVATE_NETWORKS", "true")
|
||||
t.Setenv("UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1, 172.18.0.0/16")
|
||||
t.Setenv("UBERBRINGER_NOT_A_KEY", "ignored")
|
||||
t.Setenv("UBERBRINGER_PRINTER_RETRIES", "")
|
||||
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Printer.Address != "env.lan" {
|
||||
t.Errorf("Address = %q, want the environment's value", cfg.Printer.Address)
|
||||
}
|
||||
if cfg.Printer.Retries != 2 {
|
||||
t.Errorf("Retries = %d, want the file's value, since an empty variable counts as unset", cfg.Printer.Retries)
|
||||
}
|
||||
if cfg.Printer.DialTimeout != 2*time.Second || cfg.WebServer.Port != 9090 || !cfg.Images.AllowPrivateNetworks {
|
||||
t.Errorf("typed environment values not applied: %+v %+v %+v", cfg.Printer, cfg.WebServer, cfg.Images)
|
||||
}
|
||||
if got := strings.Join(cfg.WebServer.TrustedProxies, "|"); got != "10.0.0.1|172.18.0.0/16" {
|
||||
t.Errorf("TrustedProxies = %q, want two trimmed items", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A variable named after a section rather than a setting changes nothing.
|
||||
func TestLoadIgnoresSectionNamedVariables(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
[api]
|
||||
secret = "`+validSecret+`"
|
||||
[printer]
|
||||
address = "file.lan"
|
||||
[sentry]
|
||||
environment = "staging"
|
||||
`)
|
||||
t.Setenv("UBERBRINGER_PRINTER", "kitchen")
|
||||
t.Setenv("UBERBRINGER_SENTRY", "x")
|
||||
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Printer.Address != "file.lan" || cfg.Printer.Port != 9100 {
|
||||
t.Errorf("printer = %+v, want the file's address and the default port", cfg.Printer)
|
||||
}
|
||||
if cfg.Sentry.Environment != "staging" {
|
||||
t.Errorf("sentry.environment = %q, want the file's value", cfg.Sentry.Environment)
|
||||
}
|
||||
}
|
||||
|
||||
// Some Windows editors start a UTF-8 file with a byte order mark.
|
||||
func TestLoadFileWithByteOrderMark(t *testing.T) {
|
||||
path := writeConfig(t, "\xef\xbb\xbf[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"bom.lan\"\n")
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Printer.Address != "bom.lan" {
|
||||
t.Errorf("Address = %q", cfg.Printer.Address)
|
||||
}
|
||||
}
|
||||
|
||||
// An error from a value that may have come from the environment names the
|
||||
// variables that were set, and never their values.
|
||||
func TestLoadErrorNamesVariables(t *testing.T) {
|
||||
path := writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n")
|
||||
t.Setenv("UBERBRINGER_PRINTER_RETRY_DELAY", "soon")
|
||||
_, err := config.Load(path)
|
||||
if err == nil {
|
||||
t.Fatal("Load accepted a bad retry_delay")
|
||||
}
|
||||
if msg := err.Error(); !strings.Contains(msg, path) || !strings.Contains(msg, "UBERBRINGER_PRINTER_RETRY_DELAY") {
|
||||
t.Errorf("error = %q, want it to name the file and the variable", msg)
|
||||
}
|
||||
|
||||
t.Setenv("UBERBRINGER_API_SECRET", "short-env-secret")
|
||||
_, err = config.Load(path)
|
||||
if err == nil || strings.Contains(err.Error(), "short-env-secret") {
|
||||
t.Errorf("error = %v, want a failure that does not contain the secret", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadEnvironmentOnly(t *testing.T) {
|
||||
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "192.168.1.245")
|
||||
t.Setenv("UBERBRINGER_WEBSERVER_BIND_IP", "0.0.0.0")
|
||||
|
||||
cfg, err := config.Load("")
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Printer.Address != "192.168.1.245" || cfg.WebServer.BindIP != "0.0.0.0" || cfg.API.Secret != validSecret {
|
||||
t.Errorf("environment not applied: %+v %+v", cfg.Printer, cfg.WebServer)
|
||||
}
|
||||
if def := config.Default(); cfg.Queue.Size != def.Queue.Size || cfg.Printer.Model != def.Printer.Model {
|
||||
t.Error("defaults not applied without a file")
|
||||
}
|
||||
}
|
||||
|
||||
// A failed load names the UBERBRINGER_* variables that set nothing, which
|
||||
// are likely misspelt, but not their values or UBERBRINGER_CONFIG.
|
||||
func TestLoadErrorNamesMisspeltVariables(t *testing.T) {
|
||||
t.Setenv("UBERBRINGER_API_SECRETS", validSecret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
|
||||
t.Setenv(config.PathEnvVar, "unused.toml")
|
||||
_, err := config.Load("")
|
||||
if err == nil {
|
||||
t.Fatal("Load accepted a config without api.secret")
|
||||
}
|
||||
msg := err.Error()
|
||||
if !strings.Contains(msg, "variables that set nothing: UBERBRINGER_API_SECRETS") {
|
||||
t.Errorf("error = %q, want it to name UBERBRINGER_API_SECRETS", msg)
|
||||
}
|
||||
if strings.Contains(msg, validSecret) || strings.Contains(msg, config.PathEnvVar) {
|
||||
t.Errorf("error = %q, want no values and no %s", msg, config.PathEnvVar)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings for numbers are read as decimal, with spaces around them ignored.
|
||||
func TestLoadEnvironmentNumbersAreDecimal(t *testing.T) {
|
||||
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
|
||||
t.Setenv("UBERBRINGER_QUEUE_SIZE", "010")
|
||||
t.Setenv("UBERBRINGER_WEBSERVER_PORT", " 9090 ")
|
||||
cfg, err := config.Load("")
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Queue.Size != 10 || cfg.WebServer.Port != 9090 {
|
||||
t.Errorf("queue.size = %d, webserver.port = %d; want 10 and 9090", cfg.Queue.Size, cfg.WebServer.Port)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadEnvironmentErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, key, value, wantErr string
|
||||
}{
|
||||
{"not a number", "UBERBRINGER_WEBSERVER_PORT", "eighty", "port"},
|
||||
{"bad duration", "UBERBRINGER_PRINTER_RETRY_DELAY", "soon", "retry_delay"},
|
||||
{"bare number for a duration", "UBERBRINGER_PRINTER_RETRY_DELAY", "5", "retry_delay"},
|
||||
{"fails validation", "UBERBRINGER_LOG_LEVEL", "loud", "log.level"},
|
||||
{"only spaces", "UBERBRINGER_IMAGES_ALLOWED_HOSTS", " ", "UBERBRINGER_IMAGES_ALLOWED_HOSTS holds only spaces"},
|
||||
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
|
||||
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
|
||||
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
|
||||
t.Setenv(tt.key, tt.value)
|
||||
_, err := config.Load("")
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("Load error = %v, want it to contain %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadMissingFile(t *testing.T) {
|
||||
_, err := config.Load(filepath.Join(t.TempDir(), "nope.toml"))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValue(t *testing.T) {
|
||||
cfg := config.Default()
|
||||
cfg.Images.AllowedHosts = []string{"a.lan", "b.lan"}
|
||||
tests := []struct {
|
||||
key, want, wantErr string
|
||||
}{
|
||||
{key: "webserver.port", want: "8080"},
|
||||
{key: "WebServer.Body_Limit", want: "4194304"},
|
||||
{key: "printer.dial_timeout", want: "5s"},
|
||||
{key: "webserver.trusted_proxies", want: "127.0.0.1,::1"},
|
||||
{key: "images.allowed_hosts", want: "a.lan,b.lan"},
|
||||
{key: "images.allow_private_networks", want: "false"},
|
||||
{key: "printer", wantErr: `"printer" is a section`},
|
||||
{key: "printer.adress", wantErr: `unknown key "printer.adress"`},
|
||||
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.key, func(t *testing.T) {
|
||||
got, err := cfg.Value(tt.key)
|
||||
if tt.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("Value error = %v, want it to contain %q", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || got != tt.want {
|
||||
t.Errorf("Value = %q, %v; want %q", got, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Value returns the setting at the dotted key, such as "webserver.port", in
|
||||
// the form a config file or an environment variable gives it: durations such
|
||||
// as "15s", lists comma-separated. Key names match case-insensitively.
|
||||
func (c *Config) Value(key string) (string, error) {
|
||||
v := reflect.ValueOf(*c)
|
||||
for part := range strings.SplitSeq(key, ".") {
|
||||
field, ok := fieldByKey(v, part)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("unknown key %q", key)
|
||||
}
|
||||
v = field
|
||||
}
|
||||
if v.Kind() == reflect.Struct {
|
||||
return "", fmt.Errorf("%q is a section; name one of its settings", key)
|
||||
}
|
||||
switch value := v.Interface().(type) {
|
||||
case time.Duration:
|
||||
return value.String(), nil
|
||||
case []string:
|
||||
return strings.Join(value, ","), nil
|
||||
default:
|
||||
return fmt.Sprint(value), nil
|
||||
}
|
||||
}
|
||||
|
||||
// fieldByKey returns the field of the struct v whose mapstructure tag is
|
||||
// name.
|
||||
func fieldByKey(v reflect.Value, name string) (reflect.Value, bool) {
|
||||
if v.Kind() != reflect.Struct {
|
||||
return reflect.Value{}, false
|
||||
}
|
||||
t := v.Type()
|
||||
for i := range t.NumField() {
|
||||
if tag := t.Field(i).Tag.Get("mapstructure"); tag != "" && tag == strings.ToLower(name) {
|
||||
return v.Field(i), true
|
||||
}
|
||||
}
|
||||
return reflect.Value{}, false
|
||||
}
|
||||
Reference in new issue
Block a user