Files
uberbringer/internal/pkg/config/config_test.go
T
57_WolveandClaude Opus 5.5 6502d9551d
CI / Lint, test and scan (push) Successful in 1m41s
Refactor to Go standards; add print queue and own ESC/POS library
Restructure the daemon to follow the project's Go coding standards and
expand its features.

Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
  dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
  Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.

Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
  retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
  replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
  1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
  internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
  with live printer status, `secret` and `token` subcommands.

Fixes
- Jobs are validated before anything is sent; a failed printer dial no
  longer panics.
- Request logs never contain tokens; Sentry no longer receives the
  Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
  dedicated user and uses a current nginx TLS config.

config.toml is no longer tracked; start from configs/config.example.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:17:16 -06:00

174 lines
4.9 KiB
Go

package config_test
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
)
const validSecret = "xTw8qdxTy7Ng4DiptTqmeVy506xWLht3OhFn4kdawmM="
func writeConfig(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
return path
}
func TestLoadLegacyConfigGetsDefaults(t *testing.T) {
t.Setenv("SENTRY_DSN", "")
// The exact shape written by the original install.sh, plus a printer.
path := writeConfig(t, `
[webserver]
bind_ip = "127.0.0.1"
port = 8080
[api]
secret = "`+validSecret+`"
[printer]
address = "192.168.1.245"
`)
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Port != 9100 || cfg.Printer.Model != "tm-t20" || cfg.Printer.CodePage != "cp437" {
t.Errorf("printer defaults not applied: %+v", cfg.Printer)
}
if cfg.WebServer.RateWindow != time.Minute || cfg.Queue.Size != 100 {
t.Errorf("defaults not applied: %+v %+v", cfg.WebServer, cfg.Queue)
}
if cfg.Images.AllowPrivateNetworks {
t.Error("private networks must be blocked by default")
}
}
func TestLoadOverridesAndDurations(t *testing.T) {
path := writeConfig(t, `
[api]
secret = "`+validSecret+`"
[printer]
address = "printer.lan"
dial_timeout = "750ms"
paper_width = 384
[images]
allowed_hosts = ["images.lan"]
[sentry]
dsn = "https://key@sentry.example/1"
[log]
format = "json"
`)
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.DialTimeout != 750*time.Millisecond {
t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout)
}
if cfg.Printer.PaperWidth != 384 || cfg.Log.Format != "json" {
t.Errorf("overrides not applied: %+v %+v", cfg.Printer, cfg.Log)
}
if len(cfg.Images.AllowedHosts) != 1 || cfg.Images.AllowedHosts[0] != "images.lan" {
t.Errorf("AllowedHosts = %v", cfg.Images.AllowedHosts)
}
if cfg.Sentry.DSN != "https://key@sentry.example/1" {
t.Errorf("DSN = %q", cfg.Sentry.DSN)
}
}
func TestLoadSentryDSNFromEnvironment(t *testing.T) {
t.Setenv("SENTRY_DSN", "https://env@sentry.example/2")
path := writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n")
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Sentry.DSN != "https://env@sentry.example/2" {
t.Errorf("DSN = %q, want value from SENTRY_DSN", cfg.Sentry.DSN)
}
}
func TestLoadErrors(t *testing.T) {
tests := []struct {
name string
body string
wantErr string
}{
{
name: "missing secret",
body: "[printer]\naddress = \"p\"\n",
wantErr: "api.secret must be at least 32 bytes",
},
{
name: "short secret",
body: "[api]\nsecret = \"short\"\n[printer]\naddress = \"p\"\n",
wantErr: "api.secret must be at least 32 bytes",
},
{
name: "missing printer address",
body: "[api]\nsecret = \"" + validSecret + "\"\n",
wantErr: "printer.address is required",
},
{
name: "unknown key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nadress = \"typo\"\n",
wantErr: "unknown keys: printer.adress",
},
{
name: "bad duration",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ndial_timeout = \"soon\"\n",
wantErr: "dial_timeout",
},
{
name: "bad trusted proxy",
body: "[webserver]\ntrusted_proxies = [\"nginx\"]\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
wantErr: `"nginx" is not an IP or CIDR`,
},
{
name: "bad log level",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
wantErr: "log.level",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := config.Load(writeConfig(t, tt.body))
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Load error = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
// The documented example must stay loadable: every key in it must exist.
func TestExampleConfigLoads(t *testing.T) {
example, err := os.ReadFile(filepath.Join("..", "..", "..", "configs", "config.example.toml"))
if err != nil {
t.Fatal(err)
}
body := strings.Replace(string(example), `secret = ""`, `secret = "`+validSecret+`"`, 1)
body = strings.Replace(body, `address = ""`, `address = "192.168.1.245"`, 1)
cfg, err := config.Load(writeConfig(t, body))
if err != nil {
t.Fatalf("example config: %v", err)
}
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model {
t.Error("example config values drifted from the defaults it documents")
}
}
func TestLoadMissingFile(t *testing.T) {
_, err := config.Load(filepath.Join(t.TempDir(), "nope.toml"))
if err == nil {
t.Fatal("expected error for missing file")
}
}