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,165 @@
|
||||
// Package uberbringer wires the Überbringer daemon together and provides its
|
||||
// command-line interface.
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/liamg/tml"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
// Project information shown by the banner, the version command and the API
|
||||
// index route.
|
||||
const (
|
||||
Project = "Überbringer"
|
||||
Description = "EPSON Receipt Printer Server"
|
||||
Authors = "https://git.anomalous.dev/57_Wolve/uberbringer"
|
||||
copyright = "William Gill"
|
||||
)
|
||||
|
||||
// secretBytes is the size of generated API secrets: 256 bits, the HS256 hash
|
||||
// size.
|
||||
const secretBytes = 32
|
||||
|
||||
// BuildInfo is injected at build time through -ldflags.
|
||||
type BuildInfo struct {
|
||||
Version string
|
||||
Commit string
|
||||
|
||||
// SentryDSN is the default DSN for release builds; sentry.dsn in the
|
||||
// config and the SENTRY_DSN environment variable take precedence.
|
||||
SentryDSN string
|
||||
}
|
||||
|
||||
// Execute runs the command line given by args.
|
||||
func Execute(ctx context.Context, build BuildInfo, args []string) error {
|
||||
root := newRootCommand(build)
|
||||
root.SetArgs(args)
|
||||
return root.ExecuteContext(ctx)
|
||||
}
|
||||
|
||||
func newRootCommand(build BuildInfo) *cobra.Command {
|
||||
var configPath string
|
||||
root := &cobra.Command{
|
||||
Use: "uberbringer",
|
||||
Short: "Runs the Überbringer receipt printer daemon.",
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
return serve(cmd.Context(), configPath, build, cmd.OutOrStdout())
|
||||
},
|
||||
}
|
||||
root.PersistentFlags().StringVarP(&configPath, "config", "c", "config.toml", "path to the daemon config file")
|
||||
root.AddCommand(
|
||||
newVersionCommand(build),
|
||||
newSecretCommand(),
|
||||
newTokenCommand(&configPath),
|
||||
)
|
||||
return root
|
||||
}
|
||||
|
||||
func newVersionCommand(build BuildInfo) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Prints the version and exits.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
_, err := fmt.Fprintln(cmd.OutOrStdout(), versionLine(build))
|
||||
return err
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newSecretCommand() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "secret",
|
||||
Short: "Prints a new random API secret for api.secret in the config.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
_, err := fmt.Fprintln(cmd.OutOrStdout(), newSecret())
|
||||
return err
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newTokenCommand(configPath *string) *cobra.Command {
|
||||
var (
|
||||
subject string
|
||||
ttl time.Duration
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "token",
|
||||
Short: "Prints a bearer token signed with the config's api.secret.",
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
cfg, err := config.Load(*configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
token, err := signToken([]byte(cfg.API.Secret), subject, ttl, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(cmd.OutOrStdout(), token)
|
||||
return err
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&subject, "subject", "uberbringer", "token subject, e.g. the client's name")
|
||||
cmd.Flags().DurationVar(&ttl, "ttl", 0, "token lifetime, e.g. 720h (0 means it never expires)")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// newSecret returns a random base64 API secret. crypto/rand.Read never fails
|
||||
// on supported platforms; it crashes the program rather than return weak bytes.
|
||||
func newSecret() string {
|
||||
b := make([]byte, secretBytes)
|
||||
_, _ = rand.Read(b) // documented to never return an error
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
// signToken returns an HS256 JWT for subject. A zero ttl means no expiry.
|
||||
func signToken(secret []byte, subject string, ttl time.Duration, now time.Time) (string, error) {
|
||||
if ttl < 0 {
|
||||
return "", fmt.Errorf("ttl must not be negative")
|
||||
}
|
||||
claims := jwt.RegisteredClaims{
|
||||
Subject: subject,
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
}
|
||||
if ttl > 0 {
|
||||
claims.ExpiresAt = jwt.NewNumericDate(now.Add(ttl))
|
||||
}
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("signing token: %w", err)
|
||||
}
|
||||
return signed, nil
|
||||
}
|
||||
|
||||
func versionLine(build BuildInfo) string {
|
||||
return fmt.Sprintf("%s | Version: %s Build: %s | Copyright © %d %s",
|
||||
Project, build.Version, build.Commit, time.Now().Year(), copyright)
|
||||
}
|
||||
|
||||
// printBanner writes the startup banner.
|
||||
func printBanner(w io.Writer, build BuildInfo) {
|
||||
const rule = "-----------------------------------------------------------------------------------------------"
|
||||
// The banner is cosmetic; a failed write to the terminal is not worth
|
||||
// stopping the daemon for.
|
||||
_ = tml.Fprintf(w, "%s\n\n", rule)
|
||||
_ = tml.Fprintf(w, "<bold> <lightblue>%s</lightblue></bold>\n\n", versionLine(build))
|
||||
_ = tml.Fprintf(w, "<bold> <lightblue>Project:</lightblue> %s</bold>\n", Project)
|
||||
_ = tml.Fprintf(w, "<bold> <lightblue>Description:</lightblue> %s</bold>\n", Description)
|
||||
_ = tml.Fprintf(w, "<bold> <lightblue>Authors:</lightblue> %s</bold>\n\n", Authors)
|
||||
_ = tml.Fprintf(w, "%s\n", rule)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func runCommand(t *testing.T, args ...string) (string, error) {
|
||||
t.Helper()
|
||||
cmd := newRootCommand(BuildInfo{Version: "1.2.3", Commit: "abc123"})
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetArgs(args)
|
||||
err := cmd.Execute()
|
||||
return out.String(), err
|
||||
}
|
||||
|
||||
func TestVersionCommand(t *testing.T) {
|
||||
out, err := runCommand(t, "version")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, "Überbringer | Version: 1.2.3 Build: abc123") {
|
||||
t.Errorf("version output = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretCommand(t *testing.T) {
|
||||
out, err := runCommand(t, "secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(out))
|
||||
if err != nil || len(raw) != secretBytes {
|
||||
t.Errorf("secret %q decodes to %d bytes, %v", out, len(raw), err)
|
||||
}
|
||||
again, _ := runCommand(t, "secret")
|
||||
if again == out {
|
||||
t.Error("two secrets were identical")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCommand(t *testing.T) {
|
||||
secret, _ := runCommand(t, "secret")
|
||||
secret = strings.TrimSpace(secret)
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
body := "[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, "token", "-c", path, "--subject", "kitchen", "--ttl", "1h")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claims := &jwt.RegisteredClaims{}
|
||||
_, err = jwt.ParseWithClaims(strings.TrimSpace(out), claims, func(*jwt.Token) (any, error) {
|
||||
return []byte(secret), nil
|
||||
}, jwt.WithValidMethods([]string{"HS256"}))
|
||||
if err != nil {
|
||||
t.Fatalf("token does not verify: %v", err)
|
||||
}
|
||||
if claims.Subject != "kitchen" || claims.ExpiresAt == nil {
|
||||
t.Errorf("claims = %+v", claims)
|
||||
}
|
||||
if left := time.Until(claims.ExpiresAt.Time); left < 59*time.Minute || left > time.Hour {
|
||||
t.Errorf("expires in %v, want about 1h", left)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCommandNoExpiryByDefault(t *testing.T) {
|
||||
token, err := signToken([]byte("0123456789abcdef0123456789abcdef"), "x", 0, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claims := &jwt.RegisteredClaims{}
|
||||
if _, _, err := jwt.NewParser().ParseUnverified(token, claims); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if claims.ExpiresAt != nil {
|
||||
t.Errorf("ExpiresAt = %v, want none", claims.ExpiresAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeRejectsBadConfig(t *testing.T) {
|
||||
_, err := runCommand(t, "-c", filepath.Join(t.TempDir(), "missing.toml"))
|
||||
if err == nil {
|
||||
t.Fatal("serve with a missing config must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewRequestID(t *testing.T) {
|
||||
id := newRequestID()
|
||||
if !strings.HasPrefix(id, "req_") || len(id) != len("req_")+26 {
|
||||
t.Errorf("request ID %q is not a req_ TypeID", id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"go.jetify.com/typeid"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/app/uberbringer/server"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||
"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"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
|
||||
)
|
||||
|
||||
// sentryFlushTimeout bounds how long shutdown waits for queued error reports.
|
||||
const sentryFlushTimeout = 2 * time.Second
|
||||
|
||||
// serve loads the config, wires every component and runs until ctx is
|
||||
// cancelled.
|
||||
func serve(ctx context.Context, configPath string, build BuildInfo, out io.Writer) error {
|
||||
cfg, err := config.Load(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logger := newLogger(cfg.Log, os.Stderr)
|
||||
printBanner(out, build)
|
||||
|
||||
profile, err := escpos.LookupProfile(cfg.Printer.Model)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config printer.model: %w", err)
|
||||
}
|
||||
if cfg.Printer.PaperWidth > 0 {
|
||||
profile.DotsPerLine = cfg.Printer.PaperWidth
|
||||
}
|
||||
codePage, err := escpos.ParseCodePage(cfg.Printer.CodePage)
|
||||
if err != nil {
|
||||
return fmt.Errorf("config printer.codepage: %w", err)
|
||||
}
|
||||
|
||||
flushSentry, err := initSentry(cfg.Sentry, build, logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer flushSentry()
|
||||
|
||||
fetcher := safehttp.New(safehttp.Options{
|
||||
Timeout: cfg.Images.Timeout,
|
||||
MaxBytes: cfg.Images.MaxBytes,
|
||||
AllowPrivate: cfg.Images.AllowPrivateNetworks,
|
||||
AllowedHosts: cfg.Images.AllowedHosts,
|
||||
})
|
||||
renderer := receipt.NewRenderer(receipt.Options{
|
||||
Profile: profile,
|
||||
CodePage: codePage,
|
||||
Columns: cfg.Printer.Columns,
|
||||
MaxPixels: cfg.Images.MaxPixels,
|
||||
MaxHeight: cfg.Images.MaxHeight,
|
||||
}, fetcher)
|
||||
printerClient := printer.NewClient(
|
||||
net.JoinHostPort(cfg.Printer.Address, strconv.Itoa(cfg.Printer.Port)),
|
||||
cfg.Printer.DialTimeout, cfg.Printer.WriteTimeout)
|
||||
queue := printqueue.New(renderer, printerClient, logger, printqueue.Options{
|
||||
Size: cfg.Queue.Size,
|
||||
History: cfg.Queue.History,
|
||||
Retries: cfg.Printer.Retries,
|
||||
RetryDelay: cfg.Printer.RetryDelay,
|
||||
OnFailure: reportJobFailure,
|
||||
})
|
||||
srv := server.New(server.Config{
|
||||
Info: server.Info{
|
||||
Project: Project,
|
||||
Description: Description,
|
||||
Authors: Authors,
|
||||
Version: build.Version,
|
||||
Build: build.Commit,
|
||||
},
|
||||
Secret: []byte(cfg.API.Secret),
|
||||
RateLimit: cfg.WebServer.RateLimit,
|
||||
RateWindow: cfg.WebServer.RateWindow,
|
||||
TrustedProxies: cfg.WebServer.TrustedProxies,
|
||||
ProxyHeader: cfg.WebServer.ProxyHeader,
|
||||
BodyLimit: cfg.WebServer.BodyLimit,
|
||||
ReadTimeout: cfg.WebServer.ReadTimeout,
|
||||
WriteTimeout: cfg.WebServer.WriteTimeout,
|
||||
IdleTimeout: cfg.WebServer.IdleTimeout,
|
||||
RequestID: newRequestID,
|
||||
}, queue, printerClient, logger)
|
||||
|
||||
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
|
||||
var lc net.ListenConfig
|
||||
ln, err := lc.Listen(ctx, "tcp", addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listening on %s: %w", addr, err)
|
||||
}
|
||||
logger.Info("listening",
|
||||
"addr", ln.Addr().String(),
|
||||
"printer", printerClient.Addr(),
|
||||
"model", profile.Name,
|
||||
"codepage", codePage.String(),
|
||||
"paper_dots", profile.DotsPerLine)
|
||||
|
||||
group, groupCtx := errgroup.WithContext(ctx)
|
||||
group.Go(func() error { return queue.Run(groupCtx) })
|
||||
group.Go(func() error { return srv.Serve(groupCtx, ln) })
|
||||
err = group.Wait()
|
||||
logger.Info("shutdown complete")
|
||||
return err
|
||||
}
|
||||
|
||||
// newLogger builds the structured logger described by cfg.
|
||||
func newLogger(cfg config.LogConfig, w io.Writer) *slog.Logger {
|
||||
var level slog.Level
|
||||
// config.Validate has already checked the level name.
|
||||
_ = level.UnmarshalText([]byte(cfg.Level))
|
||||
options := &slog.HandlerOptions{Level: level}
|
||||
if cfg.Format == config.LogFormatJSON {
|
||||
return slog.New(slog.NewJSONHandler(w, options))
|
||||
}
|
||||
return slog.New(slog.NewTextHandler(w, options))
|
||||
}
|
||||
|
||||
// initSentry enables error reporting when a DSN is configured and returns a
|
||||
// func that flushes pending events.
|
||||
func initSentry(cfg config.SentryConfig, build BuildInfo, logger *slog.Logger) (func(), error) {
|
||||
dsn := cfg.DSN
|
||||
if dsn == "" {
|
||||
dsn = build.SentryDSN
|
||||
}
|
||||
if dsn == "" {
|
||||
logger.Info("error reporting disabled: no Sentry DSN configured")
|
||||
return func() {}, nil
|
||||
}
|
||||
// Leaving DataCollection unset keeps the SDK's no-PII defaults: no user
|
||||
// data, cookies or sensitive headers. The HTTP middleware also never
|
||||
// attaches request bodies, which hold the text being printed.
|
||||
err := sentry.Init(sentry.ClientOptions{
|
||||
Dsn: dsn,
|
||||
Environment: cfg.Environment,
|
||||
Release: "uberbringer@" + build.Version,
|
||||
Debug: cfg.Debug,
|
||||
AttachStacktrace: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initializing Sentry: %w", err)
|
||||
}
|
||||
logger.Info("error reporting enabled", "environment", cfg.Environment)
|
||||
return func() { sentry.Flush(sentryFlushTimeout) }, nil
|
||||
}
|
||||
|
||||
// reportJobFailure sends a failed print job to Sentry.
|
||||
func reportJobFailure(id printqueue.JobID, err error) {
|
||||
hub := sentry.CurrentHub().Clone()
|
||||
hub.Scope().SetTag("job_id", id.String())
|
||||
hub.CaptureException(err)
|
||||
}
|
||||
|
||||
// newRequestID returns a "req_" TypeID.
|
||||
func newRequestID() string {
|
||||
id, err := typeid.WithPrefix("req")
|
||||
if err != nil {
|
||||
// Only possible if the system random source fails; a timestamp still
|
||||
// lets log lines for one request be correlated.
|
||||
return "req_" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return id.String()
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package uberbringer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakePrinter records everything sent to it.
|
||||
type fakePrinter struct {
|
||||
mu sync.Mutex
|
||||
data bytes.Buffer
|
||||
addr *net.TCPAddr
|
||||
}
|
||||
|
||||
func startFakePrinter(t *testing.T) *fakePrinter {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
p := &fakePrinter{addr: ln.Addr().(*net.TCPAddr)}
|
||||
go func() {
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer conn.Close()
|
||||
data, _ := io.ReadAll(conn)
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.data.Write(data)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *fakePrinter) received() []byte {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return bytes.Clone(p.data.Bytes())
|
||||
}
|
||||
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ln.Close()
|
||||
return ln.Addr().(*net.TCPAddr).Port
|
||||
}
|
||||
|
||||
// TestServeEndToEnd runs the real wiring: config, queue, renderer, printer
|
||||
// client and HTTP server, then checks a graceful shutdown.
|
||||
func TestServeEndToEnd(t *testing.T) {
|
||||
printer := startFakePrinter(t)
|
||||
port := freePort(t)
|
||||
const secret = "end-to-end-secret-end-to-end-secret!"
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
cfg := fmt.Sprintf(`
|
||||
[webserver]
|
||||
port = %d
|
||||
[api]
|
||||
secret = %q
|
||||
[printer]
|
||||
address = "127.0.0.1"
|
||||
port = %d
|
||||
[log]
|
||||
level = "error"
|
||||
`, port, secret, printer.addr.Port)
|
||||
if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
served := make(chan error, 1)
|
||||
go func() { served <- serve(ctx, path, BuildInfo{Version: "test"}, io.Discard) }()
|
||||
|
||||
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
waitFor(t, func() bool {
|
||||
resp, err := http.Get(base + "/")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
resp.Body.Close()
|
||||
return resp.StatusCode == http.StatusOK
|
||||
})
|
||||
|
||||
token, err := signToken([]byte(secret), "test", 0, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req, _ := http.NewRequest(http.MethodPost, base+"/api/v1/print",
|
||||
strings.NewReader(`{"elements":[{"type":"text","text":"Grüße aus dem Test"}]}`))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var queued struct{ ID, Status string }
|
||||
if err := json.NewDecoder(resp.Body).Decode(&queued); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusAccepted || !strings.HasPrefix(queued.ID, "job_") {
|
||||
t.Fatalf("POST = %d %+v", resp.StatusCode, queued)
|
||||
}
|
||||
|
||||
waitFor(t, func() bool {
|
||||
req, _ := http.NewRequest(http.MethodGet, base+"/api/v1/jobs/"+queued.ID, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var st struct{ Status string }
|
||||
_ = json.NewDecoder(resp.Body).Decode(&st)
|
||||
return st.Status == "done"
|
||||
})
|
||||
waitFor(t, func() bool {
|
||||
// "Grüße" in CP437: ü is 0x81, ß is 0xE1.
|
||||
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e aus dem Test"))
|
||||
})
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-served:
|
||||
if err != nil {
|
||||
t.Fatalf("serve returned %v after shutdown", err)
|
||||
}
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("serve did not shut down")
|
||||
}
|
||||
if _, err := http.Get(base + "/"); err == nil {
|
||||
t.Error("server still accepting connections after shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, cond func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if cond() {
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("condition not met within 10s")
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// requireBearerToken rejects requests without a valid HS256 bearer token.
|
||||
// Tokens are only read from the Authorization header: query-string tokens
|
||||
// end up in proxy and access logs.
|
||||
func requireBearerToken(secret []byte) fiber.Handler {
|
||||
parser := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
|
||||
keyFunc := func(*jwt.Token) (any, error) { return secret, nil }
|
||||
|
||||
return func(c fiber.Ctx) error {
|
||||
token, ok := bearerToken(c.Get(fiber.HeaderAuthorization))
|
||||
if !ok {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "missing bearer token")
|
||||
}
|
||||
if _, err := parser.Parse(token, keyFunc); err != nil {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer", error="invalid_token"`)
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "invalid or expired token")
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// bearerToken extracts the token from an Authorization header value. The
|
||||
// scheme is case-insensitive (RFC 7235).
|
||||
func bearerToken(header string) (string, bool) {
|
||||
const scheme = "bearer "
|
||||
if len(header) <= len(scheme) || !strings.EqualFold(header[:len(scheme)], scheme) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimSpace(header[len(scheme):])
|
||||
return token, token != ""
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// healthTimeout bounds the printer status check behind /healthz.
|
||||
const healthTimeout = 3 * time.Second
|
||||
|
||||
// apiError is an error with an HTTP status and optional details.
|
||||
type apiError struct {
|
||||
status int
|
||||
message string
|
||||
details []string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.message }
|
||||
|
||||
// errorResponse is the JSON body of every error.
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Details []string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// handleError turns errors into JSON responses. Server errors are logged and
|
||||
// reported to Sentry here, once, at the HTTP boundary.
|
||||
func (s *Server) handleError(c fiber.Ctx, err error) error {
|
||||
resp := errorResponse{Error: "internal server error"}
|
||||
status := fiber.StatusInternalServerError
|
||||
|
||||
var (
|
||||
apiErr *apiError
|
||||
fiberErr *fiber.Error
|
||||
)
|
||||
switch {
|
||||
case errors.As(err, &apiErr):
|
||||
status, resp.Error, resp.Details = apiErr.status, apiErr.message, apiErr.details
|
||||
case errors.As(err, &fiberErr):
|
||||
status, resp.Error = fiberErr.Code, fiberErr.Message
|
||||
}
|
||||
if status >= fiber.StatusInternalServerError {
|
||||
s.logger.Error("request failed", "path", c.Path(), "err", err)
|
||||
hubFrom(c).CaptureException(err)
|
||||
}
|
||||
return c.Status(status).JSON(resp)
|
||||
}
|
||||
|
||||
func (s *Server) handleIndex(c fiber.Ctx) error {
|
||||
info := s.config.Info
|
||||
return c.JSON(fiber.Map{
|
||||
"Project": info.Project,
|
||||
"Description": info.Description,
|
||||
"Authors": info.Authors,
|
||||
"Version": info.Version,
|
||||
"Build": info.Build,
|
||||
})
|
||||
}
|
||||
|
||||
func handleRobots(c fiber.Ctx) error {
|
||||
return c.SendString("User-agent: *\nDisallow:\n")
|
||||
}
|
||||
|
||||
// handlePrint validates and queues a job.
|
||||
func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
job, err := decodeJob(c.Body())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := job.Validate(); err != nil {
|
||||
var ve *receipt.ValidationError
|
||||
if errors.As(err, &ve) {
|
||||
return &apiError{status: fiber.StatusBadRequest, message: "invalid job", details: ve.Problems}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
status, err := s.jobs.Submit(job)
|
||||
switch {
|
||||
case errors.Is(err, printqueue.ErrQueueFull):
|
||||
c.Set(fiber.HeaderRetryAfter, "10")
|
||||
return fiber.NewError(fiber.StatusServiceUnavailable, "print queue is full, try again shortly")
|
||||
case errors.Is(err, printqueue.ErrClosed):
|
||||
return fiber.NewError(fiber.StatusServiceUnavailable, "server is shutting down")
|
||||
case err != nil:
|
||||
return fmt.Errorf("submitting job: %w", err)
|
||||
}
|
||||
c.Location("/api/v1/jobs/" + status.ID.String())
|
||||
return c.Status(fiber.StatusAccepted).JSON(status)
|
||||
}
|
||||
|
||||
// decodeJob strictly decodes a job body. Unknown fields are rejected so typos
|
||||
// and the pre-refactor {"data": [...]} format fail loudly.
|
||||
func decodeJob(body []byte) (receipt.Job, error) {
|
||||
var job receipt.Job
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&job); err != nil {
|
||||
msg := "request body is not a valid job: " + err.Error()
|
||||
if strings.Contains(err.Error(), `unknown field "data"`) {
|
||||
msg = `the {"data": [...]} format was replaced by {"elements": [...]}; see the README for the element format`
|
||||
}
|
||||
return job, &apiError{status: fiber.StatusBadRequest, message: msg}
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return job, &apiError{status: fiber.StatusBadRequest, message: "request body has trailing data after the job"}
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
// handleJob returns the status of one job.
|
||||
func (s *Server) handleJob(c fiber.Ctx) error {
|
||||
// Clone: fasthttp reuses the buffer behind route params.
|
||||
id, err := printqueue.ParseJobID(strings.Clone(c.Params("id")))
|
||||
if err != nil {
|
||||
return fiber.NewError(fiber.StatusNotFound, "job not found")
|
||||
}
|
||||
status, err := s.jobs.Status(id)
|
||||
if errors.Is(err, printqueue.ErrNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "job not found")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.JSON(status)
|
||||
}
|
||||
|
||||
// printerHealth is the printer part of the /healthz response.
|
||||
type printerHealth struct {
|
||||
Reachable bool `json:"reachable"`
|
||||
Status string `json:"status"`
|
||||
Online *bool `json:"online,omitempty"`
|
||||
CoverOpen *bool `json:"cover_open,omitempty"`
|
||||
Paper string `json:"paper,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
Printer printerHealth `json:"printer"`
|
||||
Queue struct {
|
||||
Pending int `json:"pending"`
|
||||
} `json:"queue"`
|
||||
}
|
||||
|
||||
// handleHealth reports whether the printer is reachable and ready. It
|
||||
// answers 503 when it is not, so load balancers and monitors can alert.
|
||||
func (s *Server) handleHealth(c fiber.Ctx) error {
|
||||
ctx, cancel := context.WithTimeout(c.Context(), healthTimeout)
|
||||
defer cancel()
|
||||
|
||||
var resp healthResponse
|
||||
resp.Queue.Pending = s.jobs.Pending()
|
||||
httpStatus := fiber.StatusOK
|
||||
|
||||
st, err := s.printer.Status(ctx)
|
||||
switch {
|
||||
case errors.Is(err, printer.ErrStatusUnsupported):
|
||||
resp.Status = "ok"
|
||||
resp.Printer = printerHealth{Reachable: true, Status: "unknown"}
|
||||
case err != nil:
|
||||
s.logger.Warn("printer health check failed", "err", err)
|
||||
resp.Status = "unavailable"
|
||||
resp.Printer = printerHealth{Reachable: false, Status: "unreachable"}
|
||||
httpStatus = fiber.StatusServiceUnavailable
|
||||
default:
|
||||
paper := "ok"
|
||||
switch {
|
||||
case st.PaperOut:
|
||||
paper = "out"
|
||||
case st.PaperNearEnd:
|
||||
paper = "near_end"
|
||||
}
|
||||
resp.Printer = printerHealth{
|
||||
Reachable: true,
|
||||
Status: "ready",
|
||||
Online: &st.Online,
|
||||
CoverOpen: &st.CoverOpen,
|
||||
Paper: paper,
|
||||
}
|
||||
resp.Status = "ok"
|
||||
if !st.Ready() {
|
||||
resp.Status = "degraded"
|
||||
resp.Printer.Status = "not_ready"
|
||||
if st.CutterError || st.Unrecoverable || st.AutoRecoverable {
|
||||
resp.Printer.Error = "printer reports an error"
|
||||
}
|
||||
httpStatus = fiber.StatusServiceUnavailable
|
||||
}
|
||||
}
|
||||
return c.Status(httpStatus).JSON(resp)
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// Package server exposes the Überbringer HTTP API on Fiber.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/compress"
|
||||
"github.com/gofiber/fiber/v3/middleware/limiter"
|
||||
recoverer "github.com/gofiber/fiber/v3/middleware/recover" // avoids shadowing the recover builtin
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// shutdownTimeout bounds how long in-flight requests may take to finish.
|
||||
const shutdownTimeout = 10 * time.Second
|
||||
|
||||
// Jobs is the print queue as seen by the HTTP handlers.
|
||||
type Jobs interface {
|
||||
Submit(job receipt.Job) (printqueue.Status, error)
|
||||
Status(id printqueue.JobID) (printqueue.Status, error)
|
||||
Pending() int
|
||||
}
|
||||
|
||||
// Printer reports the printer's real-time status.
|
||||
type Printer interface {
|
||||
Status(ctx context.Context) (escpos.Status, error)
|
||||
}
|
||||
|
||||
// Info describes the running build for the index route.
|
||||
type Info struct {
|
||||
Project string
|
||||
Description string
|
||||
Authors string
|
||||
Version string
|
||||
Build string
|
||||
}
|
||||
|
||||
// Config configures the HTTP server.
|
||||
type Config struct {
|
||||
Info Info
|
||||
|
||||
// Secret is the HS256 key bearer tokens must be signed with.
|
||||
Secret []byte
|
||||
|
||||
// RateLimit requests per RateWindow are allowed per client IP on /api.
|
||||
RateLimit int
|
||||
RateWindow time.Duration
|
||||
|
||||
// TrustedProxies may set ProxyHeader to the real client IP.
|
||||
TrustedProxies []string
|
||||
ProxyHeader string
|
||||
|
||||
BodyLimit int
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
IdleTimeout time.Duration
|
||||
|
||||
// RequestID generates request IDs.
|
||||
RequestID func() string
|
||||
}
|
||||
|
||||
// Server is the HTTP API.
|
||||
type Server struct {
|
||||
app *fiber.App
|
||||
config Config
|
||||
jobs Jobs
|
||||
printer Printer
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// New builds the server and its routes.
|
||||
func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server {
|
||||
switch {
|
||||
case jobs == nil || printer == nil || logger == nil:
|
||||
panic("server.New: jobs, printer and logger must not be nil")
|
||||
case len(config.Secret) == 0:
|
||||
panic("server.New: secret must not be empty")
|
||||
case config.RequestID == nil:
|
||||
panic("server.New: RequestID must not be nil")
|
||||
}
|
||||
s := &Server{config: config, jobs: jobs, printer: printer, logger: logger}
|
||||
|
||||
s.app = fiber.New(fiber.Config{
|
||||
AppName: config.Info.Project,
|
||||
BodyLimit: config.BodyLimit,
|
||||
ReadTimeout: config.ReadTimeout,
|
||||
WriteTimeout: config.WriteTimeout,
|
||||
IdleTimeout: config.IdleTimeout,
|
||||
ErrorHandler: s.handleError,
|
||||
TrustProxy: len(config.TrustedProxies) > 0,
|
||||
ProxyHeader: config.ProxyHeader,
|
||||
EnableIPValidation: true,
|
||||
TrustProxyConfig: fiber.TrustProxyConfig{Proxies: config.TrustedProxies},
|
||||
})
|
||||
|
||||
s.app.Use(recoverer.New())
|
||||
s.app.Use(sentryMiddleware)
|
||||
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
|
||||
s.app.Use(s.logRequests)
|
||||
s.app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))
|
||||
|
||||
s.app.Get("/", s.handleIndex)
|
||||
s.app.Get("/robots.txt", handleRobots)
|
||||
s.app.Get("/healthz", s.handleHealth)
|
||||
|
||||
api := s.app.Group("/api/v1",
|
||||
limiter.New(limiter.Config{
|
||||
Max: config.RateLimit,
|
||||
Expiration: config.RateWindow,
|
||||
KeyGenerator: func(c fiber.Ctx) string { return c.IP() },
|
||||
LimitReached: func(fiber.Ctx) error { return fiber.ErrTooManyRequests },
|
||||
}),
|
||||
requireBearerToken(config.Secret),
|
||||
)
|
||||
api.Post("/print", s.handlePrint)
|
||||
api.Get("/jobs/:id", s.handleJob)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// Serve accepts connections on ln until ctx is cancelled, then shuts down
|
||||
// gracefully.
|
||||
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
|
||||
err := s.app.Listener(ln, fiber.ListenConfig{
|
||||
GracefulContext: ctx,
|
||||
ShutdownTimeout: shutdownTimeout,
|
||||
DisableStartupMessage: true,
|
||||
})
|
||||
if err != nil && !errors.Is(err, net.ErrClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// logRequests logs every request once, after the error handler has set the
|
||||
// final status. Only the path is logged, never the query string.
|
||||
func (s *Server) logRequests(c fiber.Ctx) error {
|
||||
start := time.Now()
|
||||
if err := c.Next(); err != nil {
|
||||
if handlerErr := s.handleError(c, err); handlerErr != nil {
|
||||
return handlerErr
|
||||
}
|
||||
}
|
||||
status := c.Response().StatusCode()
|
||||
level := slog.LevelInfo
|
||||
if status >= fiber.StatusInternalServerError {
|
||||
level = slog.LevelError
|
||||
}
|
||||
s.logger.LogAttrs(c.Context(), level, "request",
|
||||
slog.String("method", c.Method()),
|
||||
slog.String("path", c.Path()),
|
||||
slog.Int("status", status),
|
||||
slog.Duration("latency", time.Since(start)),
|
||||
slog.String("ip", c.IP()),
|
||||
slog.String("request_id", requestid.FromContext(c)),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
// sentryHubKey stores the per-request Sentry hub in fiber Locals.
|
||||
type sentryHubKey struct{}
|
||||
|
||||
// sentryMiddleware reports panics to Sentry with a per-request hub, then
|
||||
// re-panics so the recover middleware can turn them into a 500. Request
|
||||
// bodies are deliberately not attached: they hold the text being printed.
|
||||
func sentryMiddleware(c fiber.Ctx) error {
|
||||
hub := sentry.CurrentHub().Clone()
|
||||
hub.Scope().SetTag("method", c.Method())
|
||||
hub.Scope().SetTag("path", c.Path())
|
||||
c.Locals(sentryHubKey{}, hub)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
hub.Recover(r)
|
||||
panic(r)
|
||||
}
|
||||
}()
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
func hubFrom(c fiber.Ctx) *sentry.Hub {
|
||||
if hub, ok := c.Locals(sentryHubKey{}).(*sentry.Hub); ok {
|
||||
return hub
|
||||
}
|
||||
return sentry.CurrentHub()
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user