Files
uberbringer/internal/app/uberbringer/server/server_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

378 lines
12 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
)
var testSecret = []byte("0123456789abcdef0123456789abcdef")
type fakeJobs struct {
mu sync.Mutex
submitted []receipt.Job
submitErr error
statuses map[printqueue.JobID]printqueue.Status
nextID printqueue.JobID
}
func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.submitErr != nil {
return printqueue.Status{}, f.submitErr
}
f.submitted = append(f.submitted, job)
st := printqueue.Status{ID: f.nextID, State: printqueue.StateQueued, CreatedAt: time.Now()}
f.statuses[f.nextID] = st
return st, nil
}
func (f *fakeJobs) Status(id printqueue.JobID) (printqueue.Status, error) {
f.mu.Lock()
defer f.mu.Unlock()
st, ok := f.statuses[id]
if !ok {
return printqueue.Status{}, printqueue.ErrNotFound
}
return st, nil
}
func (f *fakeJobs) Pending() int { return 0 }
type fakePrinter struct {
status escpos.Status
err error
}
func (f fakePrinter) Status(context.Context) (escpos.Status, error) { return f.status, f.err }
func newJobID(t *testing.T) printqueue.JobID {
t.Helper()
id, err := printqueue.ParseJobID("job_01h455vb4pex5vsknk084sn02q")
if err != nil {
t.Fatal(err)
}
return id
}
func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
t.Helper()
if jobs.statuses == nil {
jobs.statuses = map[printqueue.JobID]printqueue.Status{}
}
return New(Config{
Info: Info{Project: "Überbringer", Version: "test"},
Secret: testSecret,
RateLimit: 1000,
RateWindow: time.Minute,
TrustedProxies: []string{"127.0.0.1"},
ProxyHeader: "X-Real-IP",
BodyLimit: 1 << 20,
ReadTimeout: time.Second,
WriteTimeout: time.Second,
IdleTimeout: time.Second,
RequestID: func() string { return "req_test" },
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
}
func token(t *testing.T, secret []byte, method jwt.SigningMethod, claims jwt.Claims) string {
t.Helper()
signed, err := jwt.NewWithClaims(method, claims).SignedString(secret)
if err != nil {
t.Fatal(err)
}
return signed
}
func validToken(t *testing.T) string {
return token(t, testSecret, jwt.SigningMethodHS256, jwt.MapClaims{"user_id": "uberbringer"})
}
func do(t *testing.T, s *Server, req *http.Request) (*http.Response, map[string]any) {
t.Helper()
resp, err := s.app.Test(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var parsed map[string]any
_ = json.Unmarshal(body, &parsed) // some routes return plain text
return resp, parsed
}
func printRequest(t *testing.T, body, auth string) *http.Request {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/print", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if auth != "" {
req.Header.Set("Authorization", auth)
}
return req
}
const validJob = `{"elements":[{"type":"text","text":"Hello"}]}`
func TestPrintAuth(t *testing.T) {
expired := token(t, testSecret, jwt.SigningMethodHS256, jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Hour)),
})
wrongKey := token(t, []byte("another-secret-another-secret-xx"), jwt.SigningMethodHS256, jwt.MapClaims{})
hs512 := token(t, testSecret, jwt.SigningMethodHS512, jwt.MapClaims{})
tests := []struct {
name string
auth string
want int
}{
{"no header", "", http.StatusUnauthorized},
{"not bearer", "Basic abc", http.StatusUnauthorized},
{"garbage token", "Bearer nope", http.StatusUnauthorized},
{"wrong key", "Bearer " + wrongKey, http.StatusUnauthorized},
{"expired", "Bearer " + expired, http.StatusUnauthorized},
{"wrong algorithm", "Bearer " + hs512, http.StatusUnauthorized},
{"legacy install.sh token", "Bearer " + validToken(t), http.StatusAccepted},
{"lowercase scheme", "bearer " + validToken(t), http.StatusAccepted},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
resp, body := do(t, s, printRequest(t, validJob, tt.auth))
if resp.StatusCode != tt.want {
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
}
if tt.want == http.StatusUnauthorized && resp.Header.Get("WWW-Authenticate") == "" {
t.Error("401 without WWW-Authenticate")
}
})
}
}
func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
req := httptest.NewRequest(http.MethodPost, "/api/v1/print?token="+validToken(t), strings.NewReader(validJob))
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", resp.StatusCode)
}
}
func TestPrintAccepted(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, fakePrinter{})
resp, body := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
}
if body["id"] != "job_01h455vb4pex5vsknk084sn02q" || body["status"] != "queued" {
t.Errorf("body = %v", body)
}
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
t.Errorf("Location = %q", loc)
}
if len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "Hello" {
t.Errorf("submitted %+v", jobs.submitted)
}
}
func TestPrintBadRequests(t *testing.T) {
tests := []struct {
name, body, wantErr string
}{
{"not json", `nope`, "not a valid job"},
{"old format", `{"data":[{"type":1,"size":1,"text":"hi"}]}`, `replaced by {"elements": [...]}`},
{"unknown element field", `{"elements":[{"type":"text","colour":"red"}]}`, `unknown field "colour"`},
{"trailing data", validJob + `{}`, "trailing data"},
{"invalid element", `{"elements":[{"type":"text","size":12}]}`, "invalid job"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, fakePrinter{})
resp, body := do(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 (%v)", resp.StatusCode, body)
}
if msg, _ := body["error"].(string); !strings.Contains(msg, tt.wantErr) {
t.Errorf("error = %q, want it to contain %q", msg, tt.wantErr)
}
if len(jobs.submitted) != 0 {
t.Error("invalid job was submitted")
}
})
}
}
func TestPrintValidationDetails(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
_, body := do(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
details, _ := body["details"].([]any)
if len(details) != 2 {
t.Errorf("details = %v, want 2 problems", body["details"])
}
}
func TestPrintQueueFull(t *testing.T) {
s := newTestServer(t, &fakeJobs{submitErr: printqueue.ErrQueueFull}, fakePrinter{})
resp, _ := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") == "" {
t.Errorf("status = %d, Retry-After = %q", resp.StatusCode, resp.Header.Get("Retry-After"))
}
}
func TestJobStatus(t *testing.T) {
id := newJobID(t)
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
}}
s := newTestServer(t, jobs, fakePrinter{})
auth := "Bearer " + validToken(t)
tests := []struct {
path string
want int
}{
{"/api/v1/jobs/" + id.String(), http.StatusOK},
{"/api/v1/jobs/job_01h455vb4pex5vsknk084sn02r", http.StatusNotFound},
{"/api/v1/jobs/not-an-id", http.StatusNotFound},
}
for _, tt := range tests {
req := httptest.NewRequest(http.MethodGet, tt.path, nil)
req.Header.Set("Authorization", auth)
resp, body := do(t, s, req)
if resp.StatusCode != tt.want {
t.Errorf("GET %s = %d, want %d", tt.path, resp.StatusCode, tt.want)
}
if tt.want == http.StatusOK && body["status"] != "done" {
t.Errorf("body = %v", body)
}
}
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/"+id.String(), nil)
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
t.Errorf("unauthenticated status lookup = %d, want 401", resp.StatusCode)
}
}
func TestHealth(t *testing.T) {
tests := []struct {
name string
printer fakePrinter
want int
wantStatus string
wantPrinter string
wantPaper string
wantReachable bool
}{
{"ready", fakePrinter{status: escpos.Status{Online: true}}, 200, "ok", "ready", "ok", true},
{"paper low still ok", fakePrinter{status: escpos.Status{Online: true, PaperNearEnd: true}}, 200, "ok", "ready", "near_end", true},
{"paper out", fakePrinter{status: escpos.Status{PaperOut: true}}, 503, "degraded", "not_ready", "out", true},
{"no status support", fakePrinter{err: printer.ErrStatusUnsupported}, 200, "ok", "unknown", "", true},
{"unreachable", fakePrinter{err: errors.New("dial tcp: timeout")}, 503, "unavailable", "unreachable", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, tt.printer)
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
if resp.StatusCode != tt.want {
t.Fatalf("status = %d, want %d", resp.StatusCode, tt.want)
}
p, _ := body["printer"].(map[string]any)
if body["status"] != tt.wantStatus || p["status"] != tt.wantPrinter || p["reachable"] != tt.wantReachable {
t.Errorf("body = %v", body)
}
if paper, _ := p["paper"].(string); paper != tt.wantPaper {
t.Errorf("paper = %q, want %q", paper, tt.wantPaper)
}
if _, leaked := p["error"].(string); leaked && !tt.wantReachable {
t.Error("unreachable printer error text must not be exposed publicly")
}
})
}
}
func TestIndexAndRobotsAndNotFound(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, fakePrinter{})
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/", nil))
if resp.StatusCode != 200 || body["Project"] != "Überbringer" || body["Version"] != "test" {
t.Errorf("index = %d %v", resp.StatusCode, body)
}
if resp, _ := do(t, s, httptest.NewRequest(http.MethodGet, "/robots.txt", nil)); resp.StatusCode != 200 {
t.Errorf("robots = %d", resp.StatusCode)
}
resp, body = do(t, s, httptest.NewRequest(http.MethodGet, "/nope", nil))
if resp.StatusCode != 404 || body["error"] == nil {
t.Errorf("404 = %d %v, want JSON error", resp.StatusCode, body)
}
}
func TestRateLimitPerClientBehindProxy(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t), statuses: map[printqueue.JobID]printqueue.Status{}}
s := New(Config{
Info: Info{Project: "Überbringer"},
Secret: testSecret,
RateLimit: 2,
RateWindow: time.Minute,
TrustedProxies: []string{"0.0.0.0/0"},
ProxyHeader: "X-Real-IP",
BodyLimit: 1 << 20,
ReadTimeout: time.Second,
WriteTimeout: time.Second,
IdleTimeout: time.Second,
RequestID: func() string { return "req_test" },
}, jobs, fakePrinter{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
send := func(clientIP string) int {
req := printRequest(t, validJob, "Bearer "+validToken(t))
req.Header.Set("X-Real-IP", clientIP)
resp, _ := do(t, s, req)
return resp.StatusCode
}
for range 2 {
if code := send("203.0.113.1"); code != http.StatusAccepted {
t.Fatalf("status = %d, want 202", code)
}
}
if code := send("203.0.113.1"); code != http.StatusTooManyRequests {
t.Errorf("third request status = %d, want 429", code)
}
if code := send("203.0.113.2"); code != http.StatusAccepted {
t.Errorf("other client status = %d, want 202 (limits must be per client)", code)
}
}
func TestBearerToken(t *testing.T) {
tests := map[string]struct {
token string
ok bool
}{
"Bearer abc": {"abc", true},
"BEARER abc": {"abc", true},
"Bearer ": {"", false},
"Bearer": {"", false},
"Basic abc": {"", false},
"Bearer abc ": {"abc", true},
}
for header, want := range tests {
got, ok := bearerToken(header)
if got != want.token || ok != want.ok {
t.Errorf("bearerToken(%q) = %q, %v; want %q, %v", header, got, ok, want.token, want.ok)
}
}
}