Files
uberbringer/internal/pkg/config/config.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

271 lines
8.3 KiB
Go

// 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
}