Read the config with Viper and environment variables, on Go 1.27.4
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m54s

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:
57_WolveandClaude Opus 5.5 committed 2026-11-30 08:12:57 -06:00
1 parent 92dcacb3b9
commit eacd0bfd27
18 files changed
+1244 -248

No files matched your search

+47 -1
View File
@@ -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",
+75
View File
@@ -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")
}
}