Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s
CI / Lint, test and scan (push) Successful in 1m41s
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>
This commit is contained in:
1 parent
bb73348433
commit
6502d9551d
807 files changed
+6659
-500291
No files matched your search
@@ -0,0 +1,270 @@
|
||||
// Package config loads and validates the Überbringer daemon configuration
|
||||
// from a TOML file.
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
// 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
|
||||
|
||||
// Log formats accepted by [LogConfig.Format].
|
||||
const (
|
||||
LogFormatText = "text"
|
||||
LogFormatJSON = "json"
|
||||
)
|
||||
|
||||
// Config is the root daemon configuration.
|
||||
type Config struct {
|
||||
WebServer WebServerConfig `toml:"webserver"`
|
||||
API APIConfig `toml:"api"`
|
||||
Printer PrinterConfig `toml:"printer"`
|
||||
Queue QueueConfig `toml:"queue"`
|
||||
Images ImagesConfig `toml:"images"`
|
||||
Sentry SentryConfig `toml:"sentry"`
|
||||
Log LogConfig `toml:"log"`
|
||||
}
|
||||
|
||||
// WebServerConfig configures the HTTP listener.
|
||||
type WebServerConfig struct {
|
||||
BindIP string `toml:"bind_ip"`
|
||||
Port int `toml:"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"`
|
||||
|
||||
// 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"`
|
||||
|
||||
// BodyLimit is the maximum request body size in bytes.
|
||||
BodyLimit int `toml:"body_limit"`
|
||||
|
||||
ReadTimeout time.Duration `toml:"read_timeout"`
|
||||
WriteTimeout time.Duration `toml:"write_timeout"`
|
||||
IdleTimeout time.Duration `toml:"idle_timeout"`
|
||||
}
|
||||
|
||||
// APIConfig configures API authentication.
|
||||
type APIConfig struct {
|
||||
// Secret is the HS256 key used to verify bearer tokens.
|
||||
Secret string `toml:"secret"`
|
||||
}
|
||||
|
||||
// PrinterConfig configures the network receipt printer.
|
||||
type PrinterConfig struct {
|
||||
Address string `toml:"address"`
|
||||
Port int `toml:"port"`
|
||||
|
||||
// Model selects a printer profile, e.g. "tm-t20" or "generic-58mm".
|
||||
Model string `toml:"model"`
|
||||
|
||||
// CodePage is the character table text is transcoded to, e.g. "cp437".
|
||||
CodePage string `toml:"codepage"`
|
||||
|
||||
// PaperWidth overrides the profile's printable width in dots. Zero keeps
|
||||
// the profile default.
|
||||
PaperWidth int `toml:"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"`
|
||||
|
||||
DialTimeout time.Duration `toml:"dial_timeout"`
|
||||
WriteTimeout time.Duration `toml:"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"`
|
||||
}
|
||||
|
||||
// QueueConfig configures the print queue.
|
||||
type QueueConfig struct {
|
||||
// Size is the number of jobs that may wait to be printed.
|
||||
Size int `toml:"size"`
|
||||
|
||||
// History is the number of finished jobs whose status is kept.
|
||||
History int `toml:"history"`
|
||||
}
|
||||
|
||||
// ImagesConfig configures image elements.
|
||||
type ImagesConfig struct {
|
||||
Timeout time.Duration `toml:"timeout"`
|
||||
MaxBytes int64 `toml:"max_bytes"`
|
||||
|
||||
// MaxPixels caps the decoded image size to guard against decompression
|
||||
// bombs.
|
||||
MaxPixels int `toml:"max_pixels"`
|
||||
|
||||
// MaxHeight caps the printed image height in dots after scaling.
|
||||
MaxHeight int `toml:"max_height"`
|
||||
|
||||
// AllowPrivateNetworks permits fetching from loopback, private and
|
||||
// link-local addresses.
|
||||
AllowPrivateNetworks bool `toml:"allow_private_networks"`
|
||||
|
||||
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
|
||||
// hosts may resolve to private addresses.
|
||||
AllowedHosts []string `toml:"allowed_hosts"`
|
||||
}
|
||||
|
||||
// SentryConfig configures error reporting.
|
||||
type SentryConfig struct {
|
||||
DSN string `toml:"dsn"`
|
||||
Environment string `toml:"environment"`
|
||||
Debug bool `toml:"debug"`
|
||||
}
|
||||
|
||||
// LogConfig configures structured logging.
|
||||
type LogConfig struct {
|
||||
Level string `toml:"level"`
|
||||
Format string `toml:"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,
|
||||
Model: "tm-t20",
|
||||
CodePage: "cp437",
|
||||
DialTimeout: 5 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
Retries: 3,
|
||||
RetryDelay: time.Second,
|
||||
},
|
||||
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 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.
|
||||
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()
|
||||
}
|
||||
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
|
||||
}
|
||||
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 &cfg, 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(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.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.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...)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user