Adopt norn's CI, release, API and docs practices; bare module path
Test / Lint, test and build (push) Successful in 3m17s
Test / Lint, test and build (push) Successful in 3m17s
Module
- The module path is now the bare "uberbringer"; imports read
uberbringer/internal/... The banner keeps the Gitea URL.
CI and releases
- Workflows move to .gitea/workflows: test.yml (every branch push:
gofmt, goimports, tidy, vet, staticcheck, race tests, goreleaser
snapshot), security.yml (govulncheck weekly and on main) and a hardened
release.yml (v* tags on main only, tags fetched, goreleaser pinned to
2.20.3). The broken labeler workflow is removed.
- go.mod pins toolchain go1.27.4, which fixes GO-2026-6859; workflows
check that the running Go matches it.
- .goreleaser.yaml: tidy check that never writes, reproducible file times,
prerelease: auto, a release header linking CHANGELOG.md, and archives
that ship CHANGELOG.md, the example config and the systemd unit.
- Makefile mirrors the CI gate; .dockerignore is an allowlist.
API and tests
- Every error answers {"error", "code", "details"} with a stable code from
server/errors.go; the framework's own error text is never sent.
- Panics and unexpected errors are logged and reported to Sentry once;
refusals are not logged as failures. /healthz sends no-store.
- TestRoutesConform requires auth, rate limiting and the body limit on
every /api/v1 route.
- Race-prone tests no longer rely on freed ports or sleeps; serve takes
an injected listener.
- The test config uses a placeholder secret instead of a real one.
Install and packaging
- install.sh resolves the latest release through the Gitea API, verifies
checksums, requests a certificate only when none exists, installs the
hardened packaging/uberbringer.service and writes the first token to a
0600 file instead of printing it. It is now executable in git.
Docs
- CLAUDE.md, CHANGELOG.md (0.2.0 with breaking changes and upgrade
steps), docs/design.md, and docs/plans/formatters.md for the planned
CP437 blocks, modules and ntfy printing. README updated throughout.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
afcf96431f
commit
9b91109550
39 files changed
+3197
-433
No files matched your search
+7
-14
@@ -1,14 +1,7 @@
|
||||
# Only the Go sources are needed to build the image.
|
||||
.git
|
||||
.github
|
||||
.idea
|
||||
.vscode
|
||||
bin
|
||||
dist
|
||||
*.exe
|
||||
*.test
|
||||
*.out
|
||||
config.toml
|
||||
Dockerfile
|
||||
README.md
|
||||
install.sh
|
||||
# The image is built from the Go sources alone; everything else, the local
|
||||
# config.toml with its API secret included, stays out of the build context.
|
||||
*
|
||||
!go.mod
|
||||
!go.sum
|
||||
!cmd
|
||||
!internal
|
||||
@@ -0,0 +1,65 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
name: Publish the release with GoReleaser
|
||||
runs-on: ubuntu-latest
|
||||
if: github.ref_type == 'tag' && startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# The runner's checkout does not reliably fetch tags, and goreleaser
|
||||
# needs the previous tag to list the commits since it.
|
||||
- name: Fetch tags
|
||||
run: git fetch --force --tags
|
||||
|
||||
# Releases come from main only.
|
||||
- name: Verify the tag is on main
|
||||
run: |
|
||||
git fetch origin +refs/heads/main:refs/remotes/origin/main
|
||||
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then
|
||||
echo "Tag $GITHUB_REF_NAME is not on main; refusing to release."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
# Releases are built with go.mod's toolchain line. setup-go@v5 installs
|
||||
# the go line's release and the go command switches; fail if it did not.
|
||||
- name: Check the Go toolchain
|
||||
run: |
|
||||
want="$(sed -n 's/^toolchain //p' go.mod)"
|
||||
have="$(go env GOVERSION)"
|
||||
echo "go.mod toolchain: ${want:-none}; running: $have"
|
||||
[ "$have" = "$want" ]
|
||||
|
||||
# prerelease: auto in .goreleaser.yaml publishes vX.Y.Z-rc.N as a
|
||||
# prerelease, so it never becomes the latest release.
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
distribution: goreleaser
|
||||
# Pinned so that re-running a tag uses the same goreleaser. Same
|
||||
# pin as the snapshot step in test.yml.
|
||||
version: '2.20.3'
|
||||
args: release --clean
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.TOKEN_GITEA }}
|
||||
GORELEASER_FORCE_TOKEN: gitea
|
||||
# The tag that triggered this run. Left to itself, goreleaser takes
|
||||
# the highest-sorting tag on the commit, and vX.Y.Z-rc.N sorts
|
||||
# above vX.Y.Z.
|
||||
GORELEASER_CURRENT_TAG: ${{ github.ref_name }}
|
||||
# Optional default Sentry DSN baked into release binaries.
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Security
|
||||
|
||||
# govulncheck reads the live vulnerability database, so the weekly run
|
||||
# reports a new advisory against code that has not changed. Scheduled runs
|
||||
# use the default branch's copy of this file.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: '0 6 * * 1'
|
||||
|
||||
jobs:
|
||||
govulncheck:
|
||||
name: Vulnerability check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
# The scan covers the standard library of the Go release that runs it,
|
||||
# which must be go.mod's toolchain line, the one releases are built
|
||||
# with. setup-go@v5 installs the go line's release and the go command
|
||||
# switches; fail if it did not.
|
||||
- name: Check the Go toolchain
|
||||
run: |
|
||||
want="$(sed -n 's/^toolchain //p' go.mod)"
|
||||
have="$(go env GOVERSION)"
|
||||
echo "go.mod toolchain: ${want:-none}; running: $have"
|
||||
[ "$have" = "$want" ]
|
||||
|
||||
- name: govulncheck
|
||||
run: go tool govulncheck ./...
|
||||
@@ -0,0 +1,72 @@
|
||||
name: Test
|
||||
|
||||
# Every branch push, and no pull_request trigger: branches are pushed
|
||||
# directly, so each commit runs once. Tag pushes are left to release.yml.
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Lint, test and build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
|
||||
# setup-go@v5 installs the release named by go.mod's go line; the go
|
||||
# command then switches to its toolchain line. Fail if it did not.
|
||||
- name: Check the Go toolchain
|
||||
run: |
|
||||
want="$(sed -n 's/^toolchain //p' go.mod)"
|
||||
have="$(go env GOVERSION)"
|
||||
echo "go.mod toolchain: ${want:-none}; running: $have"
|
||||
[ "$have" = "$want" ]
|
||||
|
||||
# The gofmt on PATH is setup-go's; the one under GOROOT belongs to the
|
||||
# toolchain the go command switched to.
|
||||
- name: gofmt
|
||||
run: |
|
||||
unformatted="$("$(go env GOROOT)/bin/gofmt" -l .)"
|
||||
if [ -n "$unformatted" ]; then
|
||||
echo "These files need gofmt:"; echo "$unformatted"; exit 1
|
||||
fi
|
||||
|
||||
- name: goimports
|
||||
run: |
|
||||
unformatted="$(go tool goimports -l .)"
|
||||
if [ -n "$unformatted" ]; then
|
||||
echo "These files need goimports:"; echo "$unformatted"; exit 1
|
||||
fi
|
||||
|
||||
# Prints the change and fails, without writing, if go.mod or go.sum
|
||||
# is not tidy.
|
||||
- name: go mod tidy
|
||||
run: go mod tidy -diff
|
||||
|
||||
- name: go vet
|
||||
run: go vet ./...
|
||||
|
||||
- name: staticcheck
|
||||
run: go tool staticcheck ./...
|
||||
|
||||
# The limit is per package: a hung test fails with every goroutine's
|
||||
# stack instead of being killed by the runner.
|
||||
- name: Test (race detector)
|
||||
run: go test -race -timeout 5m ./...
|
||||
|
||||
# The release build without publishing: runs the before hooks,
|
||||
# cross-compiles every shipped target and packs the archives, so a
|
||||
# config error or a missing archive file fails here, not on a tag.
|
||||
# Same pin as release.yml.
|
||||
- name: Release snapshot
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: '2.20.3'
|
||||
args: release --snapshot --clean
|
||||
@@ -1,40 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
name: Lint, test and scan
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
# Latest patch of the current release, so standard-library security
|
||||
# fixes are picked up without editing this file.
|
||||
go-version: "1.27.x"
|
||||
check-latest: true
|
||||
|
||||
- name: gofmt
|
||||
run: |
|
||||
unformatted="$(gofmt -l .)"
|
||||
if [ -n "$unformatted" ]; then
|
||||
echo "These files need gofmt:"; echo "$unformatted"; exit 1
|
||||
fi
|
||||
|
||||
- name: go vet
|
||||
run: go vet ./...
|
||||
|
||||
- name: staticcheck
|
||||
run: go tool staticcheck ./...
|
||||
|
||||
- name: Test (race detector)
|
||||
run: go test -race ./...
|
||||
|
||||
- name: govulncheck
|
||||
run: go tool govulncheck ./...
|
||||
@@ -1,11 +0,0 @@
|
||||
name: Pull Request Labeler
|
||||
on:
|
||||
pull_request_target
|
||||
|
||||
jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v3.0.2
|
||||
with:
|
||||
repo-token: "${{ secrets.TOKEN_GITHUB }}"
|
||||
@@ -1,34 +0,0 @@
|
||||
name: Create Release & Upload Assets
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*" # e.g. v1.0, v20.15.10
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
name: Upload Assets To Gitea w/ goreleaser
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.27.x"
|
||||
check-latest: true
|
||||
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: "~> v2"
|
||||
args: release --clean
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.TOKEN_GITEA }}
|
||||
GORELEASER_FORCE_TOKEN: gitea
|
||||
# Optional default Sentry DSN baked into release binaries.
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
@@ -1,6 +1,7 @@
|
||||
# Build output
|
||||
/bin/
|
||||
/dist/
|
||||
/uberbringer
|
||||
*.exe
|
||||
*.test
|
||||
*.out
|
||||
@@ -18,3 +19,6 @@ go.work.sum
|
||||
.vscode/
|
||||
*.swp
|
||||
.DS_Store
|
||||
|
||||
# Claude Code
|
||||
.claude/
|
||||
+30
-1
@@ -1,3 +1,4 @@
|
||||
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
|
||||
version: 2
|
||||
|
||||
project_name: uberbringer
|
||||
@@ -9,7 +10,9 @@ gitea_urls:
|
||||
|
||||
before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
# A release builds from the committed go.mod and go.sum: print the
|
||||
# change and fail, without writing, if tidy would alter them.
|
||||
- go mod tidy -diff
|
||||
|
||||
builds:
|
||||
- id: uberbringer
|
||||
@@ -32,10 +35,29 @@ builds:
|
||||
# SENTRY_DSN comes from a CI secret; when unset, binaries report
|
||||
# nothing unless sentry.dsn or the SENTRY_DSN env var is configured.
|
||||
- -s -w -X main.version={{ .Version }} -X main.commit={{ .ShortCommit }} -X main.sentryDSN={{ index .Env "SENTRY_DSN" }}
|
||||
# File times from the commit, not the build, so rebuilding a tag gives
|
||||
# the same binaries.
|
||||
mod_timestamp: "{{ .CommitTimestamp }}"
|
||||
|
||||
archives:
|
||||
- formats: [tar]
|
||||
name_template: "{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}"
|
||||
# Listing files replaces goreleaser's defaults, so the license, README and
|
||||
# changelog are listed too. Each must exist; paths are kept, and install.sh
|
||||
# takes packaging/uberbringer.service from the unpacked archive.
|
||||
files:
|
||||
- src: LICENSE.txt
|
||||
info: &commit-mtime
|
||||
mtime: "{{ .CommitDate }}"
|
||||
- src: README.md
|
||||
info: *commit-mtime
|
||||
- src: CHANGELOG.md
|
||||
info: *commit-mtime
|
||||
- src: configs/config.example.toml
|
||||
info: *commit-mtime
|
||||
- src: packaging/uberbringer.service
|
||||
info: *commit-mtime
|
||||
builds_info: *commit-mtime
|
||||
|
||||
source:
|
||||
enabled: true
|
||||
@@ -49,3 +71,10 @@ release:
|
||||
owner: 57_Wolve
|
||||
name: uberbringer
|
||||
draft: false
|
||||
# vX.Y.Z-rc.N is published as a prerelease, so it never becomes the
|
||||
# latest release.
|
||||
prerelease: auto
|
||||
header: |
|
||||
**uberbringer {{ .Tag }}**, built {{ .Date }} from `{{ .ShortCommit }}`.
|
||||
|
||||
Breaking changes and upgrade steps are in [CHANGELOG.md](https://git.anomalous.dev/57_Wolve/uberbringer/src/tag/{{ .Tag }}/CHANGELOG.md).
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to Überbringer are recorded here. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
||||
[Semantic Versioning](https://semver.org/spec/v2.0.0.html). Until 1.0, a minor
|
||||
version may break callers; such changes are listed under **Breaking**.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
Planned as 0.2.0. The daemon is rewritten, and so are its install script and
|
||||
release process. Read **Breaking** before you upgrade a 0.1 install.
|
||||
|
||||
### Breaking
|
||||
|
||||
- `POST /api/v1/print` takes `{"elements": [...]}` instead of
|
||||
`{"data": [...]}`. A body in the old format is refused with `400`
|
||||
`invalid_job`, and its message points to the README. README § Migrating
|
||||
from the old format maps each 0.1 item type to an element.
|
||||
- `POST /api/v1/print` answers `202 Accepted` with a `Location` header and a
|
||||
JSON job (`id`, `status`, `created_at`). 0.1 answered `200` with the text
|
||||
`OK - <id>`. Job IDs are `job_` TypeIDs instead of numbers.
|
||||
- Every error is JSON: `{"error": "...", "code": "...", "details": [...]}`.
|
||||
Clients should match on `code`. 0.1 answered with `{"message": "..."}` or
|
||||
plain text.
|
||||
- Bearer tokens are read only from the `Authorization` header. A token in a
|
||||
`?token=` query string gets `401`. 0.1 tokens keep working in the header
|
||||
while `api.secret` is unchanged.
|
||||
- `printer.address` is required. The 0.1 install script did not write it, so
|
||||
add a `[printer]` section with `address` to such a config before starting
|
||||
0.2. Unknown config keys are now errors, so a typo no longer falls back to a
|
||||
default silently. `api.secret` must be at least 32 bytes; secrets generated
|
||||
by the 0.1 install script are long enough.
|
||||
- `config.toml` is no longer tracked in the repository. If a clone uses it,
|
||||
copy it aside before pulling and put it back afterwards; git then leaves it
|
||||
untracked. New setups start from `configs/config.example.toml`.
|
||||
|
||||
### Added
|
||||
|
||||
- Print queue. A job is accepted at once and printed in order by a single
|
||||
background worker. A failed send is retried with a doubling delay
|
||||
(`printer.retries`, `printer.retry_delay`). A full queue answers `503`
|
||||
`queue_full` with `Retry-After: 10`.
|
||||
- `GET /api/v1/jobs/:id` reports `queued`, `printing`, `done` or `failed`. A
|
||||
failed job includes an `error`. The last `queue.history` finished jobs are
|
||||
kept.
|
||||
- Elements:
|
||||
- `text`: sizes 1–8 (or separate width and height), bold, underline,
|
||||
invert, Font B and alignment;
|
||||
- `feed` and `qr`;
|
||||
- `barcode`: EAN-13, EAN-8, UPC-A, UPC-E, CODE39 and CODE128;
|
||||
- `image`, `raw` and `cut`.
|
||||
- `copies` (1–5) prints the job several times, cutting after each copy.
|
||||
- UTF-8 text is transcoded to `printer.codepage`: `cp437` by default, or
|
||||
`cp850`, `cp858` or `cp1252`. A character the code page lacks prints as
|
||||
`?`. Control characters are removed.
|
||||
- Word wrap at word boundaries for the paper width and character size. The
|
||||
position is tracked across `"newline": false` elements.
|
||||
- Images come from a URL or base64, as PNG, JPEG, GIF or WebP. Each is scaled
|
||||
to the paper and dithered, with limits on download size, pixel count and
|
||||
printed height.
|
||||
- Printer profiles, chosen with `printer.model`:
|
||||
- `tm-t88` (TM-T88IV to VII), the default;
|
||||
- `tm-m50` (TM-m50, TM-m50II);
|
||||
- `tm-t20` (TM-T20, II, III);
|
||||
- `generic-80mm` and `generic-58mm`.
|
||||
|
||||
`printer.paper_width` and `printer.columns` override the profile.
|
||||
- `GET /healthz` reports live printer status: paper near end or out, cover
|
||||
open, errors.
|
||||
- It answers `200` when the printer is ready or does not answer status
|
||||
requests, and `503` when it is unreachable, not ready or too slow to
|
||||
answer.
|
||||
- A printer that looks not ready is read again 750 ms later, so a printer
|
||||
that is busy cutting or feeding raises no false alarm.
|
||||
- A stable `code` in every error response, listed in README § Errors.
|
||||
Examples are `job_not_found` and `not_found` for `404`, and `queue_full` and
|
||||
`shutting_down` for `503`. A `405` carries `Allow`, and a `429` carries
|
||||
`Retry-After`.
|
||||
- `Cache-Control: no-store` on `/healthz` and on every `/api/v1` response,
|
||||
error responses included.
|
||||
- Commands `uberbringer secret`, which prints a new API secret, and
|
||||
`uberbringer token [--subject] [--ttl]`, which prints a signed bearer token.
|
||||
- Config sections:
|
||||
- `[webserver]`: rate limit, trusted proxies, body limit and timeouts;
|
||||
- `[queue]`, `[images]` and `[sentry]`;
|
||||
- `[log]`: level, and text or JSON format.
|
||||
|
||||
Every optional key has a default, shown in `configs/config.example.toml`.
|
||||
- Graceful shutdown on SIGINT and SIGTERM. A receipt that is printing is
|
||||
finished, and waiting jobs are marked failed.
|
||||
- Logging:
|
||||
- one `request` line per request, at INFO, or at WARN for a 5xx answer;
|
||||
- for an unexpected failure, one ERROR `request failed` line and one Sentry
|
||||
event;
|
||||
- for a recovered panic, one ERROR `panic` line with its stack trace and one
|
||||
Sentry event.
|
||||
- An Alpine `Dockerfile` that runs as a non-root user.
|
||||
- A hardened systemd unit, `packaging/uberbringer.service`, shipped in the
|
||||
release archives and installed to `/usr/local/lib/systemd/system/`.
|
||||
- It has no capabilities and a read-only file system, and its address
|
||||
families and system calls are restricted.
|
||||
- It sets start-rate limits.
|
||||
- Customise it with `systemctl edit uberbringer` drop-ins.
|
||||
- `install.sh`:
|
||||
- takes the printer address as its third argument;
|
||||
- installs a given release with `UBERBRINGER_VERSION=vX.Y.Z`;
|
||||
- installs on arm64, armv7 and armv6 as well as amd64.
|
||||
- Release archives contain `LICENSE.txt`, `README.md`,
|
||||
`configs/config.example.toml` and `packaging/uberbringer.service` next to
|
||||
the binary.
|
||||
- A weekly govulncheck run (Mondays 06:00 UTC, and on every push to main), so
|
||||
a new advisory against unchanged dependencies is reported.
|
||||
- A Makefile for development. `make check` runs the CI gate in the same order,
|
||||
`make vuln` runs govulncheck and `make snapshot` builds the release archives
|
||||
without publishing them. `make` builds report the version without a leading
|
||||
`v`, as release binaries do.
|
||||
|
||||
### Changed
|
||||
|
||||
- The HTTP server is Fiber v3 instead of Echo. ESC/POS commands come from an
|
||||
in-house package instead of justinmichaelvieira/escpos.
|
||||
- `printer.model` defaults to `tm-t88`: 512 dots, 42 Font A columns. On a
|
||||
576-dot printer such as a TM-T20, set `model = "tm-t20"` to use the full
|
||||
width. A profile wider than the printer makes it break words at the right
|
||||
edge; a narrower one only shortens lines.
|
||||
- Request IDs are `req_` TypeIDs (UUIDv7).
|
||||
- Rate limiting is per client and covers `/api` only: `webserver.rate_limit`
|
||||
requests per `webserver.rate_window`, 60 per minute by default. Behind
|
||||
nginx, the client is the `X-Real-IP` set by the proxy on 127.0.0.1. 0.1
|
||||
allowed about one request per second on every route.
|
||||
- Error messages are fixed texts set by the server. The HTTP framework's own
|
||||
text, which can quote bytes of the request, is never sent; an unknown route
|
||||
answers `not found`.
|
||||
- Expected refusals are not logged as errors or sent to Sentry: 4xx answers,
|
||||
a full queue, shutdown, and an unhealthy `/healthz`.
|
||||
- Release binaries take their default Sentry DSN from the `SENTRY_DSN` CI
|
||||
secret instead of from the repository. `sentry.dsn` and the `SENTRY_DSN`
|
||||
environment variable override it.
|
||||
- `install.sh`, user and secrets:
|
||||
- The service runs as a dedicated `uberbringer` user instead of root.
|
||||
- The config is written under umask 027 and set to 0640
|
||||
root:uberbringer.
|
||||
- The first API token goes to `/etc/uberbringer/initial-token` (0600, root)
|
||||
instead of the terminal. Re-runs create no new tokens.
|
||||
- `install.sh`, download and certificate:
|
||||
- The download is checked against the release's `checksums.txt` (sha256)
|
||||
before anything is installed.
|
||||
- A certificate is requested only when none is installed, and acme.sh's cron
|
||||
job renews it. The CA is now explicitly Let's Encrypt; acme.sh's default
|
||||
is ZeroSSL.
|
||||
- `apt-get update` runs before packages are installed, and apt output goes
|
||||
to `/var/log/uberbringer-install.log`.
|
||||
- `install.sh`, re-runs and validation:
|
||||
- A re-run keeps the config, the certificate and unit drop-ins. It restarts
|
||||
the service only when the binary, the unit or the config changed.
|
||||
- A unit at `/etc/systemd/system/uberbringer.service` written by the 0.1
|
||||
script is disabled and renamed to `.bak`.
|
||||
- Domains and printer addresses that contain anything other than host-name
|
||||
or IP-address characters are rejected.
|
||||
- Go:
|
||||
- The minimum is Go 1.26.
|
||||
- The toolchain is pinned in `go.mod` as `toolchain go1.27.4`, which fixes
|
||||
GO-2026-6859. CI, the security scan and releases all use it.
|
||||
- Every dependency is upgraded, and `vendor/` is gone.
|
||||
- The module path is still the bare `uberbringer`, so build from a clone.
|
||||
- CI moved from `.github/workflows` to `.gitea/workflows`. `test.yml` runs
|
||||
once per branch push, and its gate is gofmt, goimports,
|
||||
`go mod tidy -diff`, go vet, staticcheck, `go test -race -timeout 5m` and a
|
||||
goreleaser snapshot of every shipped target.
|
||||
- Releases:
|
||||
- Releases are cut only from `v*` tags whose commit is on main, with
|
||||
goreleaser pinned to 2.20.3.
|
||||
- `-rc.N` tags are published as prereleases, and an rc tag on the same
|
||||
commit as the final tag cannot be picked by mistake.
|
||||
- A release fails, instead of silently rewriting `go.mod` and `go.sum`, when
|
||||
they are not tidy.
|
||||
- File times come from the tag's commit, so rebuilding a tag gives
|
||||
byte-identical archives.
|
||||
- Release notes start with a link to this file.
|
||||
|
||||
### Removed
|
||||
|
||||
- The `{"data": [...]}` job format with numeric item types, and token lookup
|
||||
from query strings (see **Breaking**).
|
||||
- The pull-request labeler workflow, which had no configuration.
|
||||
- The `vendor/` directory and the `.idea/` project files.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A job is validated in full before it is queued; the `400` lists every
|
||||
problem. Nothing reaches the printer unless the whole receipt rendered.
|
||||
- A failed connection to the printer is retried, and the job is then marked
|
||||
failed. In 0.1 it panicked the request handler, which answered `500`.
|
||||
- Request logs never contain tokens.
|
||||
- Sentry no longer receives the `Authorization` header or print contents.
|
||||
- `install.sh` writes the `[printer]` section. Without it, 0.1 dialled port
|
||||
9100 on the local host.
|
||||
|
||||
### Security
|
||||
|
||||
- The `config.toml` tracked in 0.1.x held an API secret, and that secret is
|
||||
still readable in the repository history.
|
||||
- An install that uses it must replace `api.secret` with the output of
|
||||
`uberbringer secret`, then issue new tokens. Every token signed with the
|
||||
old secret stops working.
|
||||
- Installs set up by `install.sh` generated their own secret and are not
|
||||
affected.
|
||||
- The 0.1 install script left `/etc/uberbringer/config.toml` readable by every
|
||||
user (mode 0644 under the usual umask). Re-running the new script keeps the
|
||||
file as it is. On an upgraded host, after the re-run has created the
|
||||
`uberbringer` group, run
|
||||
`chown root:uberbringer /etc/uberbringer/config.toml` and
|
||||
`chmod 0640 /etc/uberbringer/config.toml`.
|
||||
- Image URLs are fetched through an SSRF guard.
|
||||
- A URL is refused when it resolves to a loopback, private or link-local
|
||||
address, cloud metadata endpoints included.
|
||||
- The check runs at connect time, after DNS resolution, and again on every
|
||||
redirect.
|
||||
- `images.allow_private_networks` turns the address check off.
|
||||
`images.allowed_hosts` limits fetches to the listed hosts, which may then
|
||||
be on the LAN.
|
||||
- 0.1 fetched any URL.
|
||||
- `api.secret` must be at least 32 bytes (see **Breaking**).
|
||||
|
||||
## [0.1.2] - 2025-01-12
|
||||
|
||||
### Added
|
||||
|
||||
- Item type 7 prints the image at the URL given in `text`.
|
||||
|
||||
## [0.1.1] - 2025-01-12
|
||||
|
||||
### Added
|
||||
|
||||
- First release:
|
||||
- `POST /api/v1/print` with `{"data": [...]}` items of types 1–6: text,
|
||||
bold text, QR code, line feed, n line feeds and raw hex;
|
||||
- HS256 bearer tokens;
|
||||
- `install.sh` for Debian and Ubuntu with nginx and an acme.sh
|
||||
certificate.
|
||||
|
||||
[Unreleased]: https://git.anomalous.dev/57_Wolve/uberbringer/compare/v0.1.2...main
|
||||
[0.1.2]: https://git.anomalous.dev/57_Wolve/uberbringer/compare/v0.1.1...v0.1.2
|
||||
[0.1.1]: https://git.anomalous.dev/57_Wolve/uberbringer/src/tag/v0.1.1
|
||||
@@ -0,0 +1,140 @@
|
||||
# Überbringer
|
||||
|
||||
Notes for agents working in this repository. Überbringer is a single Go
|
||||
binary. It takes JSON print jobs over a REST API (Fiber v3) and queues them in
|
||||
memory. It renders each job to ESC/POS and sends it over TCP port 9100 to one
|
||||
Epson receipt printer. It ships in two forms: as release tarballs, which
|
||||
`install.sh` installs behind nginx, and as the Alpine image built from the
|
||||
root `Dockerfile`.
|
||||
|
||||
## Read first
|
||||
|
||||
- Coding rules: `R:\Current Storage\Projects\AI-Memory\Golang-Programming-Standards.md`.
|
||||
Every change follows it. `.gitea/workflows/`, `packaging/`, the root
|
||||
`Dockerfile` and `install.sh` take the place of the standards' `build/` and
|
||||
`scripts/`.
|
||||
- `README.md` is the reference for the API, elements, error codes,
|
||||
configuration, command line and package layout. There is no api.md or
|
||||
OpenAPI document.
|
||||
- `docs/design.md` explains why the daemon is shaped as it is and lists what
|
||||
is deferred. Change it in the same commit as any code that departs from it.
|
||||
- `docs/plans/<feature>.md` holds a feature until it ships. A decision made
|
||||
while planning goes into design.md at once. Once the feature is done, delete
|
||||
the plan.
|
||||
|
||||
## Layout
|
||||
|
||||
`cmd/uberbringer` is a thin main. `internal/app/uberbringer` holds the CLI and
|
||||
the wiring, and `server/` holds the HTTP API. `internal/pkg/*` holds the
|
||||
libraries. README § Development lists them. The module path is the bare
|
||||
`uberbringer`, so imports read `uberbringer/internal/...`. Imports point down:
|
||||
|
||||
- server → printqueue, receipt, printer, escpos
|
||||
- printqueue → receipt
|
||||
- receipt → escpos, raster
|
||||
- printer → escpos
|
||||
|
||||
Only `internal/app` reads config or wires in safehttp. Packages under
|
||||
`internal/pkg` take plain values, and escpos knows nothing of JSON or HTTP.
|
||||
|
||||
## Gate
|
||||
|
||||
There is no `make` and no `docker` on this workstation. Run the steps of
|
||||
`make check` directly, in PowerShell. The race detector needs cgo, which
|
||||
works from PowerShell and fails from Git Bash.
|
||||
|
||||
gofmt -l . # must print nothing (fix: gofmt -w .)
|
||||
go tool goimports -l . # must print nothing (fix: go tool goimports -w .)
|
||||
go mod tidy -diff
|
||||
go vet ./...
|
||||
go tool staticcheck ./...
|
||||
go test -race -timeout 5m ./... *> "$env:TEMP\uberbringer-test.txt"; "exit $LASTEXITCODE"
|
||||
go tool govulncheck ./... # after any dependency or toolchain change, and before a tag
|
||||
goreleaser release --snapshot --clean # into dist/; after a change to .goreleaser.yaml or packaging/
|
||||
|
||||
Read the test output back from the file. The per-package `-timeout 5m` makes a
|
||||
hung test fail with every goroutine's stack. Without it, the tool's own time
|
||||
limit would kill the run first. staticcheck, goimports and govulncheck are
|
||||
pinned as tools in `go.mod`, so never install them separately.
|
||||
`.gitea/workflows/test.yml` runs the same gate on every branch push, and
|
||||
`security.yml` runs govulncheck weekly and on pushes to main. A change is done
|
||||
when the gate passes and README and CHANGELOG.md say what changed.
|
||||
|
||||
## Go version
|
||||
|
||||
- The `go` line in `go.mod` (1.26.0) is the minimum Go. Raise it only when the
|
||||
code needs a newer language or library feature. README § Development states
|
||||
the same minimum.
|
||||
- The `toolchain` line is the pinned build toolchain. CI tests, scans and
|
||||
releases with it, and a local Go that is older switches to it. Bump it to
|
||||
each new patch release, since govulncheck flags standard-library fixes. Bump
|
||||
the tool modules (golang.org/x/tools, golang.org/x/vuln, honnef.co/go/tools)
|
||||
in the same commit.
|
||||
- goreleaser is pinned to the same version in `test.yml` and `release.yml`.
|
||||
Move both together.
|
||||
|
||||
## Rules
|
||||
|
||||
- Nothing reaches the printer unless the whole receipt rendered. The order is
|
||||
validate, render in full, then send.
|
||||
- Text is transcoded to the configured code page and stripped of control
|
||||
characters, so data can never become printer commands. Only the `raw`
|
||||
element sends bytes as given.
|
||||
- Layout comes from the printer profile's dots and glyph widths. Never
|
||||
hard-code 42 or 512.
|
||||
- The printer takes one TCP connection at a time, and it can report a passing
|
||||
problem while it cuts or feeds. A status read cut short by our own deadline
|
||||
is a timeout, never a printer fault. Anything that acts on status re-checks
|
||||
first, as `/healthz` does.
|
||||
- Every refusal is an `apiError` with a code from `server/errors.go`. A code is
|
||||
part of the API: never rename one, and add a new code to the README table.
|
||||
Refusals are not logged as failures. An unexpected error is logged and sent
|
||||
to Sentry once.
|
||||
- Print contents, tokens and the API secret never reach logs or Sentry. The
|
||||
root `config.toml` is untracked and holds the secret. Never commit it, and
|
||||
never echo its secret.
|
||||
- These changes land in one commit with their docs:
|
||||
- A config key: `internal/pkg/config` (the default and the validation),
|
||||
`configs/config.example.toml` and README § Configuration.
|
||||
- A route, element field, status or error code: its code, its tests and
|
||||
README. A new route also needs its case in `TestRoutesConform`, which
|
||||
fails for a route without one.
|
||||
- Dependencies are at their latest stable release when added or bumped.
|
||||
- Commit, push, tag or release only when the owner asks. Releases are
|
||||
`vX.Y.Z` tags on `main`; `release.yml` refuses a tag whose commit is not on
|
||||
`main`.
|
||||
|
||||
## Comments and docs
|
||||
|
||||
- Code comments describe the code only: what it does and why. They never
|
||||
mention docs, plans, other repositories or history ("pre-refactor", "the old
|
||||
format"). This holds for Go, shell, YAML, TOML, the systemd unit, the
|
||||
Dockerfile and the Makefile.
|
||||
- `docs/` stays tidy. When something there is finished or superseded, delete
|
||||
it or fold it in. Keep no "was considered" history and no answered question
|
||||
lists.
|
||||
- `CHANGELOG.md`: every user-visible change gets an entry under
|
||||
`## [Unreleased]`, which becomes the version's section when the tag is cut.
|
||||
A change that breaks an existing caller, config or install goes under
|
||||
**Breaking**.
|
||||
|
||||
## Testing on the printer
|
||||
|
||||
Unit tests run against fakes and pin command bytes. Passing tests do not
|
||||
prove a change to what prints, such as layout, wrapping, code pages, images,
|
||||
barcodes, QR codes or cuts, or a change to how status is read. Only the paper
|
||||
proves it.
|
||||
|
||||
- The printer is an Epson TM-T88IV at 192.168.1.245:9100. Its model is
|
||||
`tm-t88`: 512 dots, 42 Font A and 56 Font B columns, CP437. A TM-T88VII and
|
||||
a TM-m50II are planned, with the same geometry.
|
||||
- It is live and uses real paper. Ask the owner before printing anything. Say
|
||||
what to look for (line breaks, characters, image edges, the cut), print one
|
||||
short receipt at a time, and wait for his report or photo.
|
||||
- Judge by what printed and by `/healthz`, never by a log line or a `202`.
|
||||
- To print: `go run ./cmd/uberbringer` reads the root `config.toml`, and
|
||||
`go run ./cmd/uberbringer token` prints a token. Write the job to a file
|
||||
outside the repository, then send it:
|
||||
`curl.exe -H "Authorization: Bearer <token>" -H "Content-Type: application/json" --data-binary "@job.json" http://127.0.0.1:8080/api/v1/print`
|
||||
- Once the owner passes a receipt, pin its rendered bytes in a receipt test,
|
||||
so that a later change to them shows up in `go test`.
|
||||
@@ -1,14 +1,16 @@
|
||||
.PHONY: build test lint fmt vet tidy vuln check run
|
||||
.PHONY: build test lint fmt fmt-check vet tidy tidy-check vuln snapshot check run
|
||||
|
||||
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev)
|
||||
# Without the leading v, as goreleaser's {{ .Version }} reports it.
|
||||
VERSION ?= $(patsubst v%,%,$(shell git describe --tags --always --dirty 2>/dev/null || echo dev))
|
||||
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo none)
|
||||
LDFLAGS := -s -w -X main.version=$(VERSION) -X main.commit=$(COMMIT)
|
||||
|
||||
build:
|
||||
go build -trimpath -ldflags "$(LDFLAGS)" -o bin/ ./cmd/...
|
||||
|
||||
# The limit is per package: a hung test fails with every goroutine's stack.
|
||||
test:
|
||||
go test -race ./...
|
||||
go test -race -timeout 5m ./...
|
||||
|
||||
lint:
|
||||
go tool staticcheck ./...
|
||||
@@ -18,18 +20,31 @@ fmt:
|
||||
gofmt -w .
|
||||
go tool goimports -w .
|
||||
|
||||
fmt-check:
|
||||
@test -z "$$(gofmt -l .)" || (echo "gofmt needed:"; gofmt -l .; exit 1)
|
||||
@test -z "$$(go tool goimports -l .)" || (echo "goimports needed:"; go tool goimports -l .; exit 1)
|
||||
|
||||
vet:
|
||||
go vet ./...
|
||||
|
||||
tidy:
|
||||
go mod tidy
|
||||
|
||||
# Prints the change and fails, without writing, if go.mod or go.sum is not tidy.
|
||||
tidy-check:
|
||||
go mod tidy -diff
|
||||
|
||||
vuln:
|
||||
go tool govulncheck ./...
|
||||
|
||||
# Everything CI runs.
|
||||
check: vet lint test vuln
|
||||
@test -z "$$(gofmt -l .)" || (echo "gofmt needed:"; gofmt -l .; exit 1)
|
||||
# Cross-compiles every shipped target and packs the release archives into
|
||||
# dist/, publishing nothing.
|
||||
snapshot:
|
||||
goreleaser release --snapshot --clean
|
||||
|
||||
# The gate .gitea/workflows/test.yml runs, in the same order.
|
||||
# .gitea/workflows/security.yml runs vuln.
|
||||
check: fmt-check tidy-check vet lint test snapshot
|
||||
|
||||
run:
|
||||
go run ./cmd/uberbringer --config config.toml
|
||||
@@ -36,10 +36,57 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
|
||||
sudo ./install.sh printer.example.com you@example.com 192.168.1.245
|
||||
```
|
||||
|
||||
The script installs the latest release as a systemd service running as a
|
||||
dedicated `uberbringer` user. It also sets up nginx with a Let's Encrypt
|
||||
certificate, writes `/etc/uberbringer/config.toml` with a fresh secret, and
|
||||
prints an API token.
|
||||
The arguments are the server's domain, the email address for Let's Encrypt,
|
||||
and the printer's address. The domain may contain only letters, digits, dots
|
||||
and hyphens. The printer address may also contain colons, for IPv6.
|
||||
|
||||
The script does the following:
|
||||
|
||||
- It downloads the latest release for the host's architecture and checks it
|
||||
against the release's `checksums.txt` (sha256). If the check fails, nothing
|
||||
is installed. To install a given release, name its tag:
|
||||
`sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh <domain> <acme-email> <printer-address>`.
|
||||
- It installs the binary to `/usr/local/bin/uberbringer` and the systemd unit
|
||||
to `/usr/local/lib/systemd/system/uberbringer.service`. The unit comes from
|
||||
the release archive, or from this checkout's `packaging/` directory if the
|
||||
archive lacks it. The service runs as a dedicated `uberbringer` user.
|
||||
- It writes `/etc/uberbringer/config.toml` (0640, root:uberbringer) with a
|
||||
fresh secret.
|
||||
- It sets up nginx as the HTTPS reverse proxy. The certificate comes from
|
||||
Let's Encrypt through acme.sh, whose cron job renews it.
|
||||
- It writes the first API token to `/etc/uberbringer/initial-token` (0600,
|
||||
readable by root only) instead of printing it. Copy the token to your
|
||||
client, then delete the file.
|
||||
|
||||
The install log, apt output included, is `/var/log/uberbringer-install.log`.
|
||||
|
||||
Running the script again upgrades the binary and the unit, and restarts the
|
||||
service only if the binary, the unit or the config changed. It also rewrites
|
||||
the nginx site files `/etc/nginx/sites-available/default.conf` and
|
||||
`reverse-proxy.conf`, so local edits to them are lost. It keeps:
|
||||
|
||||
- **The config.** The printer-address argument is ignored on a re-run, so
|
||||
edit `printer.address` in `/etc/uberbringer/config.toml` instead.
|
||||
- **The certificate.** One is requested only when `fullchain.pem` or
|
||||
`privkey.pem` in `/etc/letsencrypt/live/<domain>/` is missing or empty.
|
||||
- **Tokens.** A re-run creates none. Issue more with
|
||||
`uberbringer token --config /etc/uberbringer/config.toml --subject <client>`.
|
||||
|
||||
The systemd unit ships as
|
||||
[packaging/uberbringer.service](packaging/uberbringer.service):
|
||||
|
||||
- **Changing it.** Use `systemctl edit uberbringer`, never the installed unit
|
||||
file. Those drop-ins survive re-runs.
|
||||
- **Sandboxing.** The unit has no capabilities and a read-only file system,
|
||||
and it can reach the network over IPv4 and IPv6 only. Check it on the host
|
||||
with `systemd-analyze security uberbringer`.
|
||||
- **The 0.1 unit.** The 0.1 install script wrote
|
||||
`/etc/systemd/system/uberbringer.service`, and a re-run renames that file to
|
||||
`uberbringer.service.bak`. Any other file at that path overrides the
|
||||
packaged unit; the script leaves it in place and warns.
|
||||
|
||||
Upgrading a 0.1 install needs a few manual steps; see
|
||||
[Migrating from the old format](#migrating-from-the-old-format).
|
||||
|
||||
### Docker
|
||||
|
||||
@@ -67,6 +114,9 @@ tokens with `uberbringer token`. Tokens created by the old install script keep
|
||||
working as long as the secret is unchanged. Tokens in query strings are not
|
||||
accepted, because they leak into proxy logs.
|
||||
|
||||
Responses from `/healthz` and every `/api/v1` route, error responses
|
||||
included, carry `Cache-Control: no-store`.
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|--------|--------------------|------------------------------------------|
|
||||
| POST | `/api/v1/print` | Queue a print job |
|
||||
@@ -153,16 +203,37 @@ Details:
|
||||
|
||||
### Errors
|
||||
|
||||
Errors are JSON: `{"error": "message", "details": ["..."]}`.
|
||||
Errors are JSON:
|
||||
|
||||
| Status | Meaning |
|
||||
|--------|---------|
|
||||
| 400 | Malformed JSON, an unknown field, or invalid elements. `details` lists every problem, e.g. `elements[2] (text): size, width and height must be 1-8` |
|
||||
| 401 | Missing, invalid or expired token |
|
||||
| 404 | Unknown route or job |
|
||||
| 413 | Body larger than `webserver.body_limit` |
|
||||
| 429 | Rate limit exceeded |
|
||||
| 503 | Queue full (with `Retry-After`) or the server is shutting down |
|
||||
```json
|
||||
{"error": "invalid job", "code": "invalid_job", "details": ["elements[2] (text): size, width and height must be 1-8"]}
|
||||
```
|
||||
|
||||
- `code` is stable and meant for clients to match on.
|
||||
- `error` is for people and may change. It never repeats the HTTP
|
||||
framework's own text; for example, an unknown route answers `not found`.
|
||||
- `details` appears only when an `invalid_job` fails validation.
|
||||
|
||||
| Status | `code` | Meaning |
|
||||
|--------|--------|---------|
|
||||
| 400 | `invalid_job` | Malformed JSON, an unknown field, trailing data after the job, or invalid elements. When elements are invalid, `details` lists every problem. A `{"data": [...]}` body gets a message pointing to [the new format](#migrating-from-the-old-format) |
|
||||
| 400 | `bad_request` | A malformed HTTP request, refused by the server itself |
|
||||
| 401 | `unauthorized` | `missing bearer token`, or `invalid or expired token`. Sent with `WWW-Authenticate` |
|
||||
| 404 | `not_found` | Unknown route |
|
||||
| 404 | `job_not_found` | Unknown, expired or malformed job ID |
|
||||
| 405 | `method_not_allowed` | Known route, wrong method, e.g. `DELETE /api/v1/print` with a valid token (without one, `/api/v1` answers `401` first). Sent with `Allow` |
|
||||
| 408 | `request_timeout` | The request was not received in time |
|
||||
| 413 | `body_too_large` | Body larger than `webserver.body_limit` |
|
||||
| 429 | `rate_limited` | Rate limit exceeded. `Retry-After` gives the seconds to wait |
|
||||
| 431 | `headers_too_large` | Request headers too large |
|
||||
| 500 | `internal_error` | Unexpected failure. The cause is logged and reported to Sentry, never sent to the client |
|
||||
| 501 | `not_implemented` | A request body with an unsupported transfer coding. An unknown HTTP method (e.g. `FOO /healthz`) is refused by the HTTP server itself with a plain-text `501` |
|
||||
| 503 | `queue_full` | The print queue is full. Sent with `Retry-After: 10` |
|
||||
| 503 | `shutting_down` | The server is shutting down |
|
||||
|
||||
Any other status that the HTTP layer produces itself gets the code
|
||||
`http_<status>`, e.g. `http_502`. `/healthz` answers `503` with its own body,
|
||||
shown under [Health](#health), not with this shape.
|
||||
|
||||
Validation happens before a job is queued. Images are fetched by the worker,
|
||||
so a blocked or broken image URL shows up as a `failed` job. Nothing is sent
|
||||
@@ -274,13 +345,44 @@ Old text items did not end the line, hence `"newline": false`. You can usually
|
||||
drop it now and let each `text` element be a line. Hex-encoded CP437 box
|
||||
drawing can become plain text: `B3 20 21 21 21` is `"│ !!!"`.
|
||||
|
||||
These changes also affect 0.1 clients and installs.
|
||||
[CHANGELOG.md](CHANGELOG.md) lists every change.
|
||||
|
||||
- Tokens are read only from the `Authorization` header. A `?token=` query
|
||||
string gets `401`.
|
||||
- Errors have the [JSON shape above](#errors) instead of `{"message": "..."}`
|
||||
or plain text.
|
||||
- `printer.model` defaults to `tm-t88` (512 dots). On a TM-T20, set
|
||||
`model = "tm-t20"` to use the full 576-dot width.
|
||||
|
||||
To upgrade a server set up by the 0.1 install script:
|
||||
|
||||
1. Add a `[printer]` section to `/etc/uberbringer/config.toml`. The 0.1
|
||||
script did not write one, `printer.address` is now required, and
|
||||
`install.sh` keeps an existing config as it is, so without this step the
|
||||
service does not start:
|
||||
|
||||
```toml
|
||||
[printer]
|
||||
address = "192.168.1.245"
|
||||
```
|
||||
|
||||
2. Run the new `install.sh` with the domain, the email address and the
|
||||
printer address; it needs all three, although the printer address in the
|
||||
kept config is the one used. It creates the `uberbringer` user, installs
|
||||
the new unit and moves the 0.1 unit aside.
|
||||
3. The 0.1 script left the config readable by every user. Once the
|
||||
`uberbringer` group exists, fix that with
|
||||
`sudo chown root:uberbringer /etc/uberbringer/config.toml && sudo chmod 0640 /etc/uberbringer/config.toml`.
|
||||
|
||||
## Configuration
|
||||
|
||||
Copy [configs/config.example.toml](configs/config.example.toml) to
|
||||
`config.toml`. Only `api.secret` (at least 32 bytes) and `printer.address` are
|
||||
required; every other setting has a default, which the example shows. Configs
|
||||
written by the old install script still load. Unknown keys are reported as
|
||||
errors, so a typo can't silently fall back to a default.
|
||||
from 0.1 still load, because their keys are unchanged, but `printer.address`
|
||||
is now required. Unknown keys are reported as errors, so a typo can't
|
||||
silently fall back to a default.
|
||||
|
||||
Settings worth knowing:
|
||||
|
||||
@@ -307,7 +409,22 @@ Settings worth knowing:
|
||||
`127.0.0.1`.
|
||||
- `sentry.dsn`: error reporting. Falls back to the `SENTRY_DSN` environment
|
||||
variable, then to a DSN built into release binaries (from the `SENTRY_DSN`
|
||||
CI secret). Request bodies are never sent to Sentry.
|
||||
CI secret). Request bodies and the `Authorization` header are never sent
|
||||
to Sentry.
|
||||
- `log.level` (`debug`, `info`, `warn`, `error`) and `log.format` (`text` or
|
||||
`json`) control what is logged:
|
||||
- Each request is logged once, as `request`: at INFO, or at WARN when the
|
||||
status is 5xx. Only the path is logged, never the query string, the body
|
||||
or the token.
|
||||
- An unexpected failure adds one ERROR `request failed` line, with `err` and
|
||||
`request_id`, and one Sentry event.
|
||||
- A recovered panic adds one ERROR `panic` line, with `panic` and `stack`,
|
||||
and one Sentry event.
|
||||
- A print job that fails after its retries is logged as ERROR `job failed`
|
||||
with its `job_id`, and is reported to Sentry.
|
||||
- Refusals are never logged at ERROR and never go to Sentry. Refusals are
|
||||
4xx answers, the `queue_full` and `shutting_down` 503s, and 503s from
|
||||
`/healthz`.
|
||||
|
||||
## Command line
|
||||
|
||||
@@ -323,17 +440,43 @@ printing is finished, and jobs still waiting are marked failed.
|
||||
|
||||
## Development
|
||||
|
||||
Go 1.26 or newer is required. Use the latest patch release, since govulncheck
|
||||
flags standard-library fixes.
|
||||
The Go version is set in `go.mod`:
|
||||
|
||||
- The `go 1.26.0` line is the minimum, and builds with `GOTOOLCHAIN=local`
|
||||
need at least that.
|
||||
- The `toolchain go1.27.4` line picks the Go release that CI tests, scans and
|
||||
releases with. With the default `GOTOOLCHAIN=auto`, an older local Go
|
||||
downloads go1.27.4 by itself.
|
||||
- To move to a new Go release, change the toolchain line. In the same commit,
|
||||
bump the tool modules golang.org/x/tools, golang.org/x/vuln and
|
||||
honnef.co/go/tools. The workflows read the version from `go.mod`.
|
||||
|
||||
```sh
|
||||
make check # gofmt, go vet, staticcheck, go test -race, govulncheck
|
||||
make build # bin/uberbringer
|
||||
make fmt # gofmt + goimports
|
||||
make check # the CI gate, below
|
||||
make build # bin/uberbringer
|
||||
make fmt # gofmt + goimports
|
||||
make vuln # govulncheck
|
||||
make snapshot # release archives in dist/; publishes nothing
|
||||
```
|
||||
|
||||
`make check` runs the same steps as `.gitea/workflows/test.yml`, in the same
|
||||
order:
|
||||
|
||||
1. `fmt-check`: gofmt and goimports.
|
||||
2. `tidy-check`: `go mod tidy -diff`.
|
||||
3. `go vet`.
|
||||
4. staticcheck.
|
||||
5. `go test -race -timeout 5m`.
|
||||
6. `snapshot`: `goreleaser release --snapshot --clean`.
|
||||
|
||||
It needs goreleaser installed. govulncheck is not part of it; run
|
||||
`make vuln`. `make` builds report the version without the leading `v`, e.g.
|
||||
`0.1.2-3-gabc1234`, as release binaries do.
|
||||
|
||||
The linters are pinned as Go tools in `go.mod`, so `go tool staticcheck`,
|
||||
`go tool govulncheck` and `go tool goimports` need no separate install.
|
||||
`go tool govulncheck` and `go tool goimports` need no separate install. The
|
||||
module path is `uberbringer`, so packages import as
|
||||
`uberbringer/internal/...`. Build from a clone of the repository.
|
||||
|
||||
```text
|
||||
cmd/uberbringer/ main: build info, signals, exit code
|
||||
@@ -347,6 +490,27 @@ internal/pkg/safehttp/ SSRF-guarded image fetching
|
||||
internal/pkg/printer/ TCP printer client (port 9100) and status queries
|
||||
internal/pkg/printqueue/ Job queue, worker and status history
|
||||
configs/ Example configuration
|
||||
packaging/ systemd unit
|
||||
docs/ Design notes and feature plans
|
||||
```
|
||||
|
||||
Releases are built by GoReleaser when a `v*` tag is pushed.
|
||||
[docs/design.md](docs/design.md) explains why the daemon is shaped as it is.
|
||||
[CHANGELOG.md](CHANGELOG.md) lists the changes in each release.
|
||||
|
||||
### CI and releases
|
||||
|
||||
CI runs on the Gitea runner from `.gitea/workflows/`. The repository has no
|
||||
`.github/` directory.
|
||||
|
||||
- `test.yml` runs the `make check` gate on every branch push. It does not run
|
||||
on pull requests or tags.
|
||||
- `security.yml` runs govulncheck on pushes to main and every Monday at
|
||||
06:00 UTC. Scheduled runs use main's copy of the workflow.
|
||||
- `release.yml` builds and publishes a release with goreleaser 2.20.3 when a
|
||||
`v*` tag is pushed.
|
||||
- It runs only for tags whose commit is on main, and refuses any other tag.
|
||||
- `vX.Y.Z-rc.N` tags are published as prereleases, so they never become the
|
||||
latest release that `install.sh` installs.
|
||||
- Each archive holds the binary, `LICENSE.txt`, `README.md`,
|
||||
`configs/config.example.toml` and `packaging/uberbringer.service`.
|
||||
- The release notes link to `CHANGELOG.md` at the tag.
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/app/uberbringer"
|
||||
"uberbringer/internal/app/uberbringer"
|
||||
)
|
||||
|
||||
// Set at build time with -ldflags "-X main.version=... -X main.commit=...".
|
||||
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
# Überbringer: design
|
||||
|
||||
Status: the daemon is built and has been checked on paper on the TM-T88IV.
|
||||
Next is the release of CHANGELOG.md § Unreleased as 0.2.0, and the formatters
|
||||
work in `docs/plans/formatters.md`. This page records why the daemon is
|
||||
shaped as it is. README.md describes how to use it.
|
||||
|
||||
## Why
|
||||
|
||||
Scripts and services on the owner's network send short JSON jobs, and one
|
||||
Epson receipt printer prints them. The daemon replaces the 0.1 one on the
|
||||
same endpoint, `POST /api/v1/print` behind nginx, and 0.1 installs are
|
||||
deployed. It is one static binary with no database, sized for receipt rates
|
||||
on one printer.
|
||||
|
||||
```text
|
||||
client ─HTTPS─▶ nginx ─▶ server ── validate ──▶ printqueue (memory, 1 worker)
|
||||
│ │ receipt.Render: whole job
|
||||
│ │ to bytes, images via safehttp
|
||||
│ ▼
|
||||
└─ /healthz ──────▶ printer.Client ─TCP 9100─▶ printer
|
||||
(one connection at a time)
|
||||
```
|
||||
|
||||
## Decisions
|
||||
|
||||
- **One printer per instance.** The config names one printer, and its client
|
||||
holds one connection to it at a time, shared by sends and status reads. A
|
||||
second printer means a second instance with its own config and port.
|
||||
The planned TM-T88VII and TM-m50II (owner, 2026-11-29) have the same
|
||||
geometry as the TM-T88IV, so a single profile default covers all three.
|
||||
- **The queue lives in memory, on purpose.** ESC/POS gives no
|
||||
acknowledgement of what has printed. A queue replayed after a crash could
|
||||
therefore print a receipt twice. A lost job, by contrast, shows as failed
|
||||
or unknown, and the client can send it again. Waiting jobs are marked
|
||||
failed at shutdown. After a crash their IDs answer `job_not_found`. One
|
||||
worker keeps jobs in submission order, and the history is capped by
|
||||
`queue.history`.
|
||||
- **Render, then send.** The handler validates the whole job, and a `400`
|
||||
lists every problem. The worker then renders the complete receipt, images
|
||||
included, to one byte stream that starts with a printer reset (ESC @). It
|
||||
sends that stream over one connection. A failure before the send, such as a
|
||||
broken image, costs no paper and leaves no half-printed receipt. A retry
|
||||
resends the same bytes and does not render again. A send that fails
|
||||
part-way can print part of a receipt twice. That is accepted, because
|
||||
retries are what let a job survive a printer that is briefly offline.
|
||||
- **Text in, code page out.** Clients send UTF-8, which is transcoded to
|
||||
`printer.codepage`. The default is CP437, for the box drawing and shading
|
||||
the owner prints (owner, 2026-11-29). Control characters are stripped, so
|
||||
data can never become a printer command. Only the `raw` element sends bytes
|
||||
as given.
|
||||
- **Profiles set the layout, and the default is the narrower one.** Columns
|
||||
are the profile's dots per line divided by the glyph width; nothing
|
||||
hard-codes 42 or 512. The first paper test ran the 576-dot `tm-t20`
|
||||
profile on the TM-T88IV, which has 512 dots, and the printer broke words at
|
||||
its own edge (`seve` / `ral`). A profile wider than the printer breaks
|
||||
words, while a narrower one only shortens lines. So `tm-t88` (512 dots, 42
|
||||
columns) is the default.
|
||||
- **Status is read in a way that tolerates a busy printer.** `/healthz` sends
|
||||
DLE EOT 1 to 4 over the same connection slot that sends use.
|
||||
- The DLE EOT 2 bits (cover open, paper-end stop) are cleared while DLE
|
||||
EOT 1 says online. Epson printers go offline for both causes, and a
|
||||
TM-T88IV reported a stale cover-open bit while cutting.
|
||||
- A not-ready reading is re-read 750 ms later.
|
||||
- A read cut short by our own deadline is `timeout` with `503`. It never
|
||||
counts as "status unsupported", because an unknown state must not look
|
||||
healthy.
|
||||
- A printer that never answers status gets `200` `unknown`.
|
||||
- The TM-T88VII does not report paper near-end through DLE EOT 4.
|
||||
- **Health is for monitors.** `/healthz` answers `200` when the printer is
|
||||
ready, or when it cannot report status. It answers `503` when a job could
|
||||
not print now: the printer is unreachable, not ready or timed out. A `503`
|
||||
from it is a refusal: it is logged at WARN by the request line and never
|
||||
sent to Sentry.
|
||||
- **Images are fetched by the worker, through an SSRF guard.** A slow or
|
||||
broken image URL holds no HTTP request and shows up as a `failed` job.
|
||||
`safehttp` checks the resolved address at connect time, so DNS rebinding
|
||||
and redirects cannot reach loopback, private, link-local or cloud metadata
|
||||
addresses. Exceptions are configured explicitly (`images.*`). Time, size,
|
||||
pixel and height limits bound each image.
|
||||
- **Errors are flat JSON with a stable code.** The shape is
|
||||
`{"error", "code", "details"}`. `code` is the contract with clients, and
|
||||
`error` is for people. A refusal is answered and never logged as a failure.
|
||||
An unexpected error or panic is logged once and reported to Sentry once,
|
||||
without the body or the `Authorization` header.
|
||||
- **What stays compatible with 0.1.** The endpoint, the HS256 tokens and the
|
||||
config keys stay as they were. The 0.1 body and its plain-text answer do
|
||||
not. A 0.1 body gets a `400` that points to the migration table, instead of
|
||||
being translated. Tokens are read only from the header, because tokens in
|
||||
query strings end up in proxy logs.
|
||||
- **Stack choices (owner, 2026-11-29):**
|
||||
- Fiber v3 instead of Echo.
|
||||
- TypeID (UUIDv7) job and request IDs instead of snowflakes. They sort by
|
||||
time and need no node configuration.
|
||||
- An Alpine Docker image.
|
||||
- **Packaging.** The release tarballs are built for linux amd64, armv6, armv7
|
||||
and arm64. `install.sh` sets up nginx (TLS, `X-Real-IP`), acme.sh and the
|
||||
sandboxed unit from `packaging/`. The daemon binds 127.0.0.1 by default and
|
||||
serves no TLS itself.
|
||||
|
||||
## Planned: formatters
|
||||
|
||||
Layout blocks and modules, ntfy among them, that turn plain input into
|
||||
receipts. The plan is `docs/plans/formatters.md`. Decided so far (owner,
|
||||
2026-11-29):
|
||||
|
||||
- ntfy is an input: its notifications are printed. The server is
|
||||
self-hosted at a public URL, the subscriber authenticates with a token, and
|
||||
attachments come from a public host, so image fetches need no
|
||||
private-network exception.
|
||||
- Which priorities print is configurable per subscription. By default every
|
||||
priority prints, and priorities 1 and 2 print in a compact form.
|
||||
- On `/print`, characters the code page lacks fold to ASCII look-alikes
|
||||
(smart quotes, dashes, the ellipsis), and an emoji sequence prints as one
|
||||
`?`. Today each such character prints as `?`.
|
||||
- Labels are in English. The footer's time zone and date format come from
|
||||
the config.
|
||||
|
||||
## Deferred
|
||||
|
||||
- **Paper near-end on the TM-T88VII**, which `GS r 1` reports. Add it when
|
||||
that printer arrives.
|
||||
- **Several printers from one instance**, through routing or a pool. Until
|
||||
then, run one instance per printer.
|
||||
- **A durable queue.** It needs a way to tell which receipts printed before a
|
||||
crash.
|
||||
- **Printer alerts sent out to ntfy** (paper out, cover open). They have not
|
||||
been requested. Printing incoming ntfy messages is part of the formatters
|
||||
plan.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,12 @@
|
||||
module git.anomalous.dev/57_Wolve/uberbringer
|
||||
module uberbringer
|
||||
|
||||
go 1.26.0
|
||||
|
||||
// The Go release CI tests, scans and builds releases with; the workflows
|
||||
// read it from here. A local Go older than this switches to it, so local
|
||||
// runs use the same standard library.
|
||||
toolchain go1.27.4
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.6.0
|
||||
github.com/getsentry/sentry-go v0.50.0
|
||||
|
||||
Regular → Executable
+234
-62
@@ -2,6 +2,11 @@
|
||||
# Installs Überbringer behind nginx with a Let's Encrypt certificate.
|
||||
#
|
||||
# Usage: sudo ./install.sh <domain> <acme-email> <printer-address>
|
||||
#
|
||||
# Installs the latest release. To install a given release instead, name its tag:
|
||||
# sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh <domain> <acme-email> <printer-address>
|
||||
# Re-running the script upgrades the binary and the systemd unit, and keeps the
|
||||
# config, the certificate and any `systemctl edit uberbringer` drop-ins.
|
||||
set -euo pipefail
|
||||
|
||||
DOMAIN="${1:-}"
|
||||
@@ -10,17 +15,53 @@ PRINTER_ADDRESS="${3:-}"
|
||||
|
||||
LOG=/var/log/uberbringer-install.log
|
||||
CONFIG_DIR=/etc/uberbringer
|
||||
CONFIG="$CONFIG_DIR/config.toml"
|
||||
TOKEN_FILE="$CONFIG_DIR/initial-token"
|
||||
BIN=/usr/local/bin/uberbringer
|
||||
SERVICE_USER=uberbringer
|
||||
RELEASE_URL=https://git.anomalous.dev/57_Wolve/uberbringer/releases/download/latest
|
||||
# The vendor unit path for locally installed software. Units in
|
||||
# /etc/systemd/system take precedence over it, so operator changes belong in
|
||||
# drop-ins there.
|
||||
UNIT_DIR=/usr/local/lib/systemd/system
|
||||
UNIT_FILE="$UNIT_DIR/uberbringer.service"
|
||||
ETC_UNIT_FILE=/etc/systemd/system/uberbringer.service
|
||||
ACME=/root/.acme.sh/acme.sh
|
||||
CERT_DIR="/etc/letsencrypt/live/$DOMAIN"
|
||||
# Gitea resolves the tag "latest" to the newest release that is neither a
|
||||
# draft nor a prerelease.
|
||||
RELEASE_URL="https://git.anomalous.dev/57_Wolve/uberbringer/releases/download/${UBERBRINGER_VERSION:-latest}"
|
||||
# The checkout this script runs from, or empty when it is piped into bash.
|
||||
SCRIPT_DIR=""
|
||||
if [[ -n "${BASH_SOURCE[0]:-}" && -f "${BASH_SOURCE[0]}" ]]; then
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
fi
|
||||
|
||||
# Set when the binary, the unit or the config changed, so the service is
|
||||
# restarted only then.
|
||||
RESTART_NEEDED=0
|
||||
CONFIG_CREATED=0
|
||||
WORK_DIR=""
|
||||
UNIT_SRC=""
|
||||
|
||||
if [[ "$EUID" -ne 0 ]]; then
|
||||
echo -e "\e[31m[FATAL]\e[39m This script must be run as root."
|
||||
echo -e "\e[31m[FATAL]\e[39m This script must be run as root." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -z "$DOMAIN" || -z "$ACME_EMAIL" || -z "$PRINTER_ADDRESS" ]]; then
|
||||
echo "Usage: $0 <domain> <acme-email> <printer-address>"
|
||||
echo "Usage: $0 <domain> <acme-email> <printer-address>" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The domain goes unquoted into nginx config and file paths, and the printer
|
||||
# address into a TOML string, so both are limited to host name and IP address
|
||||
# characters.
|
||||
if [[ ! "$DOMAIN" =~ ^[A-Za-z0-9.-]+$ ]]; then
|
||||
echo "Invalid domain: $DOMAIN" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! "$PRINTER_ADDRESS" =~ ^[A-Za-z0-9.:-]+$ ]]; then
|
||||
echo "Invalid printer address: $PRINTER_ADDRESS (expected an IP address or host name)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -31,6 +72,11 @@ info() {
|
||||
echo "[INFO] $1" >> "$LOG"
|
||||
}
|
||||
|
||||
warn() {
|
||||
echo -e "\e[33m[WARN]\e[39m $1"
|
||||
echo "[WARN] $1" >> "$LOG"
|
||||
}
|
||||
|
||||
debug() {
|
||||
if [[ -n "${DEBUG:-}" ]]; then
|
||||
echo -e "\e[96m[DEBUG]\e[39m $1"
|
||||
@@ -38,8 +84,10 @@ debug() {
|
||||
echo "[DEBUG] $1" >> "$LOG"
|
||||
}
|
||||
|
||||
# fatal writes to stderr so its message is not swallowed when it runs inside a
|
||||
# command substitution.
|
||||
fatal() {
|
||||
echo -e "\e[31m[FATAL]\e[39m $1"
|
||||
echo -e "\e[31m[FATAL]\e[39m $1" >&2
|
||||
echo "[FATAL] $1" >> "$LOG"
|
||||
exit 1
|
||||
}
|
||||
@@ -48,6 +96,12 @@ require() {
|
||||
command -v "$1" > /dev/null 2>&1 || fatal "Couldn't find $1 - please install it and rerun the script."
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
if [[ -n "$WORK_DIR" ]]; then
|
||||
rm -rf "$WORK_DIR"
|
||||
fi
|
||||
}
|
||||
|
||||
detect_arch() {
|
||||
case "$(uname -m)" in
|
||||
x86_64) echo "amd64" ;;
|
||||
@@ -58,17 +112,62 @@ detect_arch() {
|
||||
esac
|
||||
}
|
||||
|
||||
install_uberbringer_binary() {
|
||||
local arch archive tmp
|
||||
# install_if_changed installs $1 as $3 with mode $2 unless $3 already has the
|
||||
# same content, and records that the service needs a restart.
|
||||
install_if_changed() {
|
||||
if cmp -s "$1" "$3"; then
|
||||
debug "$3 is unchanged."
|
||||
return
|
||||
fi
|
||||
install -m "$2" "$1" "$3"
|
||||
RESTART_NEEDED=1
|
||||
}
|
||||
|
||||
install_packages() {
|
||||
info "Installing curl, socat and nginx..."
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
# A broken third-party source makes the update fail even when the
|
||||
# packages below are installed or still installable, so only the install
|
||||
# is fatal.
|
||||
apt-get update >> "$LOG" 2>&1 || warn "apt-get update failed; trying the install anyway (see $LOG)."
|
||||
apt-get install -y nginx curl socat >> "$LOG" 2>&1 || fatal "apt-get install failed; see $LOG."
|
||||
|
||||
require nginx
|
||||
require curl
|
||||
require socat
|
||||
require sha256sum
|
||||
require systemctl
|
||||
}
|
||||
|
||||
# download_release fetches the release archive and checksums.txt into
|
||||
# WORK_DIR, verifies the archive and unpacks it there.
|
||||
download_release() {
|
||||
local arch archive
|
||||
arch="$(detect_arch)"
|
||||
archive="uberbringer_linux_${arch}.tar"
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' RETURN
|
||||
|
||||
info "Downloading ${archive}..."
|
||||
curl -fsSL -o "$tmp/$archive" "$RELEASE_URL/$archive"
|
||||
tar -xf "$tmp/$archive" -C "$tmp"
|
||||
install -m 0755 "$tmp/uberbringer" "$BIN"
|
||||
info "Downloading ${archive} from ${RELEASE_URL}..."
|
||||
curl -fsSL -o "$WORK_DIR/checksums.txt" "$RELEASE_URL/checksums.txt" ||
|
||||
fatal "Couldn't download checksums.txt from $RELEASE_URL."
|
||||
curl -fsSL -o "$WORK_DIR/$archive" "$RELEASE_URL/$archive" ||
|
||||
fatal "Couldn't download $archive from $RELEASE_URL."
|
||||
|
||||
info "Verifying ${archive}..."
|
||||
# A leading * on the file name marks a binary-mode checksum line.
|
||||
awk -v f="$archive" '$2 == f || $2 == "*" f' "$WORK_DIR/checksums.txt" > "$WORK_DIR/archive.sha256"
|
||||
[[ -s "$WORK_DIR/archive.sha256" ]] || fatal "checksums.txt has no entry for $archive."
|
||||
(cd "$WORK_DIR" && sha256sum --check --strict --quiet archive.sha256) >> "$LOG" 2>&1 ||
|
||||
fatal "$archive does not match checksums.txt; nothing was installed."
|
||||
|
||||
mkdir "$WORK_DIR/release"
|
||||
tar -xf "$WORK_DIR/$archive" -C "$WORK_DIR/release"
|
||||
[[ -f "$WORK_DIR/release/uberbringer" ]] || fatal "$archive does not contain the uberbringer binary."
|
||||
}
|
||||
|
||||
install_binary() {
|
||||
install_if_changed "$WORK_DIR/release/uberbringer" 0755 "$BIN"
|
||||
# Run from its installed path: WORK_DIR may be on a noexec /tmp.
|
||||
info "Installed $("$BIN" version)"
|
||||
}
|
||||
|
||||
create_service_user() {
|
||||
@@ -80,14 +179,18 @@ create_service_user() {
|
||||
|
||||
write_config() {
|
||||
mkdir -p "$CONFIG_DIR"
|
||||
if [[ -f "$CONFIG_DIR/config.toml" ]]; then
|
||||
info "Keeping existing $CONFIG_DIR/config.toml"
|
||||
if [[ -f "$CONFIG" ]]; then
|
||||
info "Keeping existing $CONFIG; edit printer.address there to change the printer."
|
||||
return
|
||||
fi
|
||||
info "Creating Uberbringer config..."
|
||||
local secret
|
||||
secret="$("$BIN" secret)"
|
||||
cat <<EOT > "$CONFIG_DIR/config.toml"
|
||||
# The config holds the API secret, so it is never readable by others, not
|
||||
# even between being written and being chmodded.
|
||||
(
|
||||
umask 027
|
||||
cat <<EOT > "$CONFIG"
|
||||
[webserver]
|
||||
bind_ip = "127.0.0.1"
|
||||
port = 8080
|
||||
@@ -98,39 +201,55 @@ write_config() {
|
||||
[printer]
|
||||
address = "$PRINTER_ADDRESS"
|
||||
EOT
|
||||
chown root:"$SERVICE_USER" "$CONFIG_DIR/config.toml"
|
||||
chmod 0640 "$CONFIG_DIR/config.toml"
|
||||
)
|
||||
chown root:"$SERVICE_USER" "$CONFIG"
|
||||
chmod 0640 "$CONFIG"
|
||||
CONFIG_CREATED=1
|
||||
RESTART_NEEDED=1
|
||||
}
|
||||
|
||||
# unit_source prints the path of the unit to install: the release archive's
|
||||
# copy, or for releases that do not ship one, the copy in this checkout.
|
||||
unit_source() {
|
||||
local candidate
|
||||
for candidate in "$WORK_DIR/release/packaging/uberbringer.service" \
|
||||
${SCRIPT_DIR:+"$SCRIPT_DIR/packaging/uberbringer.service"}; do
|
||||
if [[ -f "$candidate" ]]; then
|
||||
echo "$candidate"
|
||||
return
|
||||
fi
|
||||
done
|
||||
fatal "Neither the release archive nor this checkout has packaging/uberbringer.service."
|
||||
}
|
||||
|
||||
install_service() {
|
||||
info "Creating uberbringer.service..."
|
||||
cat <<EOT > /etc/systemd/system/uberbringer.service
|
||||
[Unit]
|
||||
Description=Uberbringer Daemon
|
||||
Wants=network-online.target
|
||||
After=network.target network-online.target
|
||||
debug "Installing the systemd unit from $UNIT_SRC..."
|
||||
|
||||
[Service]
|
||||
User=$SERVICE_USER
|
||||
Group=$SERVICE_USER
|
||||
WorkingDirectory=$CONFIG_DIR
|
||||
ExecStart=$BIN --config $CONFIG_DIR/config.toml
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
LimitNOFILE=4096
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
# A full unit in /etc shadows the packaged one. One with this Description
|
||||
# is an installer-generated copy rather than an operator's override, so it
|
||||
# is moved aside; any other file there is left alone with a warning.
|
||||
if [[ -f "$ETC_UNIT_FILE" ]] && grep -qx 'Description=Uberbringer Daemon' "$ETC_UNIT_FILE"; then
|
||||
info "Replacing the unit in $ETC_UNIT_FILE with $UNIT_FILE (old copy kept as $ETC_UNIT_FILE.bak)..."
|
||||
# Disabling first removes the wants symlink that points at the old path.
|
||||
systemctl disable uberbringer >> "$LOG" 2>&1
|
||||
mv "$ETC_UNIT_FILE" "$ETC_UNIT_FILE.bak"
|
||||
RESTART_NEEDED=1
|
||||
elif [[ -e "$ETC_UNIT_FILE" ]]; then
|
||||
warn "$ETC_UNIT_FILE overrides $UNIT_FILE; remove it to use the packaged unit."
|
||||
fi
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOT
|
||||
mkdir -p "$UNIT_DIR"
|
||||
install_if_changed "$UNIT_SRC" 0644 "$UNIT_FILE"
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable uberbringer
|
||||
debug "Starting Uberbringer Web Service..."
|
||||
systemctl restart uberbringer
|
||||
systemctl enable uberbringer >> "$LOG" 2>&1
|
||||
if [[ "$RESTART_NEEDED" -eq 1 ]]; then
|
||||
debug "Restarting Uberbringer Web Service..."
|
||||
systemctl restart uberbringer
|
||||
else
|
||||
debug "Binary, unit and config are unchanged; starting Uberbringer only if it is stopped..."
|
||||
systemctl start uberbringer
|
||||
fi
|
||||
}
|
||||
|
||||
install_nginx() {
|
||||
@@ -156,34 +275,55 @@ server {
|
||||
EOT
|
||||
|
||||
ln -sf /etc/nginx/sites-available/default.conf /etc/nginx/sites-enabled/default.conf
|
||||
systemctl enable nginx
|
||||
systemctl enable nginx >> "$LOG" 2>&1
|
||||
debug "Starting Nginx..."
|
||||
systemctl restart nginx
|
||||
}
|
||||
|
||||
install_acmesh() {
|
||||
mkdir -p "/etc/letsencrypt/live/$DOMAIN"
|
||||
# issue_certificate gets a certificate only when none is installed yet;
|
||||
# renewals are left to the cron job acme.sh installs.
|
||||
issue_certificate() {
|
||||
if [[ -s "$CERT_DIR/fullchain.pem" && -s "$CERT_DIR/privkey.pem" ]]; then
|
||||
info "Keeping the existing certificate in $CERT_DIR; acme.sh's cron job renews it."
|
||||
return
|
||||
fi
|
||||
|
||||
info "Installing acme.sh..."
|
||||
curl -fsSL https://get.acme.sh | sh -s email="$ACME_EMAIL"
|
||||
if [[ ! -x "$ACME" ]]; then
|
||||
info "Installing acme.sh..."
|
||||
curl -fsSL https://get.acme.sh | sh -s email="$ACME_EMAIL"
|
||||
|
||||
info "Enabling acme.sh automatic upgrade..."
|
||||
"$ACME" --upgrade --auto-upgrade || true
|
||||
fi
|
||||
|
||||
info "Issuing SSL certificate..."
|
||||
/root/.acme.sh/acme.sh --issue -w "/var/www/$DOMAIN" \
|
||||
--keypath "/etc/letsencrypt/live/$DOMAIN/privkey.pem" \
|
||||
--fullchainpath "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" \
|
||||
-d "$DOMAIN" --reloadcmd "systemctl reload nginx" --force
|
||||
local rc=0
|
||||
"$ACME" --issue --server letsencrypt -w "/var/www/$DOMAIN" -d "$DOMAIN" || rc=$?
|
||||
# 2 means acme.sh already holds a certificate for the domain that is not
|
||||
# due for renewal; --install-cert below copies it into place.
|
||||
if [[ "$rc" -ne 0 && "$rc" -ne 2 ]]; then
|
||||
fatal "acme.sh could not issue a certificate for $DOMAIN (exit code $rc)."
|
||||
fi
|
||||
|
||||
info "Enabling acme.sh automatic upgrade..."
|
||||
/root/.acme.sh/acme.sh --upgrade --auto-upgrade || true
|
||||
mkdir -p "$CERT_DIR"
|
||||
# acme.sh records these paths and the reload command, and reuses them when
|
||||
# its cron job renews the certificate.
|
||||
"$ACME" --install-cert -d "$DOMAIN" \
|
||||
--key-file "$CERT_DIR/privkey.pem" \
|
||||
--fullchain-file "$CERT_DIR/fullchain.pem" \
|
||||
--reloadcmd "systemctl reload nginx"
|
||||
}
|
||||
|
||||
install_reverse_proxy() {
|
||||
info "Configuring the HTTPS reverse proxy..."
|
||||
cat <<EOT > /etc/nginx/sites-available/reverse-proxy.conf
|
||||
server {
|
||||
listen 443 ssl;
|
||||
listen [::]:443 ssl;
|
||||
server_name $DOMAIN;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
|
||||
ssl_certificate $CERT_DIR/fullchain.pem;
|
||||
ssl_certificate_key $CERT_DIR/privkey.pem;
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_prefer_server_ciphers off;
|
||||
@@ -218,25 +358,57 @@ EOT
|
||||
systemctl reload nginx
|
||||
}
|
||||
|
||||
# write_initial_token saves the first bearer token to a root-only file instead
|
||||
# of printing it, so it does not end up in terminal scrollback or the log. It
|
||||
# runs right after the config is created, because a re-run after a later step
|
||||
# failed keeps that config and writes no token.
|
||||
write_initial_token() {
|
||||
if [[ "$CONFIG_CREATED" -ne 1 ]]; then
|
||||
return
|
||||
fi
|
||||
rm -f "$TOKEN_FILE"
|
||||
(
|
||||
umask 077
|
||||
"$BIN" token --config "$CONFIG" > "$TOKEN_FILE"
|
||||
)
|
||||
debug "Wrote the first API token to $TOKEN_FILE."
|
||||
}
|
||||
|
||||
token_notice() {
|
||||
if [[ "$CONFIG_CREATED" -eq 1 ]]; then
|
||||
info "The first API token is in $TOKEN_FILE (readable by root only). Copy it to your client, then delete the file."
|
||||
return
|
||||
fi
|
||||
if [[ -s "$TOKEN_FILE" ]]; then
|
||||
warn "$TOKEN_FILE still holds the first API token; delete it once your client has it."
|
||||
fi
|
||||
info "Issue API tokens with: $BIN token --config $CONFIG --subject <client>"
|
||||
}
|
||||
|
||||
main() {
|
||||
info "Script loaded, starting the install process..."
|
||||
|
||||
info "Installing curl, socat and nginx..."
|
||||
apt-get install -y nginx curl socat > /dev/null 2>&1
|
||||
install_packages
|
||||
|
||||
require nginx
|
||||
require curl
|
||||
require socat
|
||||
WORK_DIR="$(mktemp -d)"
|
||||
trap cleanup EXIT
|
||||
|
||||
install_uberbringer_binary
|
||||
download_release
|
||||
# Resolved first, so a missing unit stops the script before any of
|
||||
# Uberbringer's files are installed.
|
||||
UNIT_SRC="$(unit_source)"
|
||||
install_binary
|
||||
create_service_user
|
||||
write_config
|
||||
write_initial_token
|
||||
install_service
|
||||
install_nginx
|
||||
install_acmesh
|
||||
issue_certificate
|
||||
install_reverse_proxy
|
||||
|
||||
info "Uberbringer service is now installed."
|
||||
echo -e "\e[34m[INFO]\e[39m API token: $("$BIN" token --config "$CONFIG_DIR/config.toml")"
|
||||
info "Override unit settings with 'systemctl edit uberbringer'; drop-ins survive re-runs of this script."
|
||||
token_notice
|
||||
}
|
||||
|
||||
main
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"github.com/liamg/tml"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
// Project information shown by the banner, the version command and the API
|
||||
|
||||
@@ -14,25 +14,39 @@ import (
|
||||
"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"
|
||||
"uberbringer/internal/app/uberbringer/server"
|
||||
"uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
"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.
|
||||
// serve loads the config at configPath and runs the daemon on the address it
|
||||
// names 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
|
||||
}
|
||||
return run(ctx, cfg, build, out, listenTCP)
|
||||
}
|
||||
|
||||
// listenFunc opens the HTTP listener on addr.
|
||||
type listenFunc func(ctx context.Context, addr string) (net.Listener, error)
|
||||
|
||||
func listenTCP(ctx context.Context, addr string) (net.Listener, error) {
|
||||
var lc net.ListenConfig
|
||||
return lc.Listen(ctx, "tcp", addr)
|
||||
}
|
||||
|
||||
// run wires every component from cfg, opens the HTTP listener with listen
|
||||
// once the wiring has succeeded, and serves until ctx is cancelled.
|
||||
func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer, listen listenFunc) error {
|
||||
logger := newLogger(cfg.Log, os.Stderr)
|
||||
printBanner(out, build)
|
||||
|
||||
@@ -98,8 +112,7 @@ func serve(ctx context.Context, configPath string, build BuildInfo, out io.Write
|
||||
}, 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)
|
||||
ln, err := listen(ctx, addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("listening on %s: %w", addr, err)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
// fakePrinter records everything sent to it.
|
||||
@@ -55,26 +57,15 @@ func (p *fakePrinter) received() []byte {
|
||||
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.
|
||||
// client and HTTP server, then checks a graceful shutdown. The HTTP listener
|
||||
// is bound before the daemon starts and handed to it, so no other process can
|
||||
// take its port in between.
|
||||
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
|
||||
body := fmt.Sprintf(`
|
||||
[api]
|
||||
secret = %q
|
||||
[printer]
|
||||
@@ -82,17 +73,27 @@ 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 {
|
||||
`, secret, printer.addr.Port)
|
||||
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
listen := func(context.Context, string) (net.Listener, error) { return ln, nil }
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
served := make(chan error, 1)
|
||||
go func() { served <- serve(ctx, path, BuildInfo{Version: "test"}, io.Discard) }()
|
||||
go func() { served <- run(ctx, cfg, BuildInfo{Version: "test"}, io.Discard, listen) }()
|
||||
|
||||
base := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
base := "http://" + ln.Addr().String()
|
||||
waitFor(t, func() bool {
|
||||
resp, err := http.Get(base + "/")
|
||||
if err != nil {
|
||||
|
||||
@@ -18,11 +18,11 @@ func requireBearerToken(secret []byte) fiber.Handler {
|
||||
token, ok := bearerToken(c.Get(fiber.HeaderAuthorization))
|
||||
if !ok {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, `Bearer realm="uberbringer"`)
|
||||
return fiber.NewError(fiber.StatusUnauthorized, "missing bearer token")
|
||||
return newAPIError(codeUnauthorized.withMessage("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 newAPIError(codeUnauthorized.withMessage("invalid or expired token"))
|
||||
}
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
)
|
||||
|
||||
// errorCode is a stable, machine-readable error identifier together with its
|
||||
// HTTP status and the message sent when no more specific one is given.
|
||||
// Clients match on code; the message is for people and may change.
|
||||
type errorCode struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
}
|
||||
|
||||
// The codes the API answers with.
|
||||
var (
|
||||
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
|
||||
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
|
||||
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
|
||||
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
|
||||
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
|
||||
codeMethodNotAllowed = errorCode{fiber.StatusMethodNotAllowed, "method_not_allowed", "method not allowed"}
|
||||
codeRequestTimeout = errorCode{fiber.StatusRequestTimeout, "request_timeout", "request was not received in time"}
|
||||
codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"}
|
||||
codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"}
|
||||
codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"}
|
||||
codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"}
|
||||
codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"}
|
||||
codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"}
|
||||
codeShuttingDown = errorCode{fiber.StatusServiceUnavailable, "shutting_down", "server is shutting down"}
|
||||
)
|
||||
|
||||
// fiberCodes are the codes for the statuses Fiber and fasthttp answer with on
|
||||
// their own, e.g. for an unknown route or a body over the limit.
|
||||
var fiberCodes = []errorCode{
|
||||
codeBadRequest, codeNotFound, codeMethodNotAllowed, codeRequestTimeout, codeBodyTooLarge,
|
||||
codeRateLimited, codeHeadersTooLarge, codeInternal, codeNotImplemented,
|
||||
}
|
||||
|
||||
// fiberCode returns the code for a status Fiber raised itself, or http_<status>
|
||||
// for one without its own code.
|
||||
func fiberCode(status int) errorCode {
|
||||
for _, c := range fiberCodes {
|
||||
if c.status == status {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return errorCode{status, "http_" + strconv.Itoa(status), http.StatusText(status)}
|
||||
}
|
||||
|
||||
// withMessage returns c with message in place of its default message.
|
||||
func (c errorCode) withMessage(message string) errorCode {
|
||||
c.message = message
|
||||
return c
|
||||
}
|
||||
|
||||
// apiError is a refusal: an answer the client caused or has to wait out. It
|
||||
// is sent with its code and is not logged as a failure.
|
||||
type apiError struct {
|
||||
errorCode
|
||||
details []string
|
||||
}
|
||||
|
||||
func newAPIError(code errorCode, details ...string) *apiError {
|
||||
return &apiError{errorCode: code, details: details}
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.message }
|
||||
|
||||
// errorResponse is the JSON body of every error.
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
Code string `json:"code"`
|
||||
Details []string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// panicError carries a value recovered from a panic in a handler.
|
||||
type panicError struct{ value any }
|
||||
|
||||
func (e *panicError) Error() string { return fmt.Sprintf("panic: %v", e.value) }
|
||||
|
||||
// handleError is the Fiber error handler: it answers every error with an
|
||||
// errorResponse. Refusals, the server's own and Fiber's, are expected, so the
|
||||
// request line is their only log. Any other error is a failure the server
|
||||
// did not expect; it is logged and reported to Sentry here, once. Fiber's own
|
||||
// message is never sent, since it can quote bytes of the request.
|
||||
func (s *Server) handleError(c fiber.Ctx, err error) error {
|
||||
var (
|
||||
panicErr *panicError
|
||||
apiErr *apiError
|
||||
fiberErr *fiber.Error
|
||||
)
|
||||
switch {
|
||||
case errors.As(err, &panicErr):
|
||||
// reportPanic has already logged and reported it.
|
||||
apiErr = newAPIError(codeInternal)
|
||||
case errors.As(err, &apiErr):
|
||||
case errors.As(err, &fiberErr):
|
||||
apiErr = newAPIError(fiberCode(fiberErr.Code))
|
||||
default:
|
||||
s.logger.LogAttrs(c.Context(), slog.LevelError, "request failed",
|
||||
slog.String("method", c.Method()),
|
||||
slog.String("path", c.Path()),
|
||||
slog.String("request_id", requestid.FromContext(c)),
|
||||
slog.Any("err", err),
|
||||
)
|
||||
hubFrom(c).CaptureException(err)
|
||||
apiErr = newAPIError(codeInternal)
|
||||
}
|
||||
return c.Status(apiErr.status).JSON(errorResponse{
|
||||
Error: apiErr.message,
|
||||
Code: apiErr.code,
|
||||
Details: apiErr.details,
|
||||
})
|
||||
}
|
||||
|
||||
// reportPanic logs a recovered panic with its stack and reports it to Sentry.
|
||||
// The recover middleware calls it from its deferred function, before the
|
||||
// stack unwinds, so both show where the panic happened.
|
||||
func (s *Server) reportPanic(c fiber.Ctx, r any) {
|
||||
s.logger.LogAttrs(c.Context(), slog.LevelError, "panic",
|
||||
slog.String("method", c.Method()),
|
||||
slog.String("path", c.Path()),
|
||||
slog.String("request_id", requestid.FromContext(c)),
|
||||
slog.String("panic", fmt.Sprint(r)),
|
||||
slog.String("stack", string(debug.Stack())),
|
||||
)
|
||||
hubFrom(c).Recover(r)
|
||||
}
|
||||
|
||||
// recoveredPanic turns a recovered panic into the error handleError answers.
|
||||
func recoveredPanic(_ fiber.Ctx, r any) error {
|
||||
return &panicError{value: r}
|
||||
}
|
||||
@@ -12,53 +12,15 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
|
||||
"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"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"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{
|
||||
@@ -83,7 +45,7 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
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 newAPIError(codeInvalidJob, ve.Problems...)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -92,9 +54,9 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
switch {
|
||||
case errors.Is(err, printqueue.ErrQueueFull):
|
||||
c.Set(fiber.HeaderRetryAfter, "10")
|
||||
return fiber.NewError(fiber.StatusServiceUnavailable, "print queue is full, try again shortly")
|
||||
return newAPIError(codeQueueFull)
|
||||
case errors.Is(err, printqueue.ErrClosed):
|
||||
return fiber.NewError(fiber.StatusServiceUnavailable, "server is shutting down")
|
||||
return newAPIError(codeShuttingDown)
|
||||
case err != nil:
|
||||
return fmt.Errorf("submitting job: %w", err)
|
||||
}
|
||||
@@ -102,8 +64,9 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
|
||||
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.
|
||||
// decodeJob strictly decodes a job body. Unknown fields are rejected so that
|
||||
// typos fail loudly. An unknown "data" field gets a message that points to
|
||||
// "elements" and the README instead of the decoder's text.
|
||||
func decodeJob(body []byte) (receipt.Job, error) {
|
||||
var job receipt.Job
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
@@ -113,10 +76,10 @@ func decodeJob(body []byte) (receipt.Job, 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}
|
||||
return job, newAPIError(codeInvalidJob.withMessage(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, newAPIError(codeInvalidJob.withMessage("request body has trailing data after the job"))
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
@@ -126,11 +89,11 @@ 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")
|
||||
return newAPIError(codeJobNotFound)
|
||||
}
|
||||
status, err := s.jobs.Status(id)
|
||||
if errors.Is(err, printqueue.ErrNotFound) {
|
||||
return fiber.NewError(fiber.StatusNotFound, "job not found")
|
||||
return newAPIError(codeJobNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
@@ -15,9 +16,9 @@ import (
|
||||
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"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// shutdownTimeout bounds how long in-flight requests may take to finish.
|
||||
@@ -113,22 +114,30 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
|
||||
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}))
|
||||
// logRequests is outermost so that it logs the status the client got for
|
||||
// every request, a recovered panic included: the recover middleware
|
||||
// inside it has turned the panic into an error by then.
|
||||
s.app.Use(s.logRequests)
|
||||
s.app.Use(recoverer.New(recoverer.Config{
|
||||
EnableStackTrace: true,
|
||||
StackTraceHandler: s.reportPanic,
|
||||
PanicHandler: recoveredPanic,
|
||||
}))
|
||||
s.app.Use(attachSentryHub)
|
||||
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
|
||||
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)
|
||||
s.app.Get("/healthz", noStore, s.handleHealth)
|
||||
|
||||
api := s.app.Group("/api/v1",
|
||||
noStore,
|
||||
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 },
|
||||
LimitReached: func(fiber.Ctx) error { return newAPIError(codeRateLimited) },
|
||||
}),
|
||||
requireBearerToken(config.Secret),
|
||||
)
|
||||
@@ -152,19 +161,22 @@ func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
|
||||
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.
|
||||
// logRequests logs one line per request with the status the client got. It
|
||||
// hands errors to handleError itself so that the line carries the final
|
||||
// status. A 5xx line is a warning so that outages stand out; the cause of an
|
||||
// unexpected failure is logged once, by handleError or reportPanic. 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
|
||||
if err := s.handleError(c, err); err != nil {
|
||||
c.Status(fiber.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
status := c.Response().StatusCode()
|
||||
level := slog.LevelInfo
|
||||
if status >= fiber.StatusInternalServerError {
|
||||
level = slog.LevelError
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
s.logger.LogAttrs(c.Context(), level, "request",
|
||||
slog.String("method", c.Method()),
|
||||
@@ -180,20 +192,23 @@ func (s *Server) logRequests(c fiber.Ctx) error {
|
||||
// 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
|
||||
// attachSentryHub gives each request its own Sentry hub, tagged with the
|
||||
// method and path, for handleError and reportPanic to report with. Request
|
||||
// bodies are deliberately not attached: they hold the text being printed.
|
||||
func sentryMiddleware(c fiber.Ctx) error {
|
||||
func attachSentryHub(c fiber.Ctx) error {
|
||||
hub := sentry.CurrentHub().Clone()
|
||||
hub.Scope().SetTag("method", c.Method())
|
||||
hub.Scope().SetTag("path", c.Path())
|
||||
// Clone: the path points into a buffer fasthttp reuses for the next
|
||||
// request, and the SDK may send the event after this one has ended.
|
||||
hub.Scope().SetTag("path", strings.Clone(c.Path()))
|
||||
c.Locals(sentryHubKey{}, hub)
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
hub.Recover(r)
|
||||
panic(r)
|
||||
}
|
||||
}()
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
// noStore keeps caches from storing a response: health and job status
|
||||
// change from one request to the next.
|
||||
func noStore(c fiber.Ctx) error {
|
||||
c.Set(fiber.HeaderCacheControl, "no-store")
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,30 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"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"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
var testSecret = []byte("0123456789abcdef0123456789abcdef")
|
||||
@@ -28,6 +33,7 @@ type fakeJobs struct {
|
||||
mu sync.Mutex
|
||||
submitted []receipt.Job
|
||||
submitErr error
|
||||
statusErr error
|
||||
statuses map[printqueue.JobID]printqueue.Status
|
||||
nextID printqueue.JobID
|
||||
}
|
||||
@@ -47,6 +53,9 @@ func (f *fakeJobs) Submit(job receipt.Job) (printqueue.Status, error) {
|
||||
func (f *fakeJobs) Status(id printqueue.JobID) (printqueue.Status, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.statusErr != nil {
|
||||
return printqueue.Status{}, f.statusErr
|
||||
}
|
||||
st, ok := f.statuses[id]
|
||||
if !ok {
|
||||
return printqueue.Status{}, printqueue.ErrNotFound
|
||||
@@ -89,12 +98,26 @@ func newJobID(t *testing.T) printqueue.JobID {
|
||||
return id
|
||||
}
|
||||
|
||||
func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
|
||||
// newTestServer returns a server that discards its logs. opts adjust the
|
||||
// config before the server is built.
|
||||
func newTestServer(t *testing.T, jobs *fakeJobs, p Printer, opts ...func(*Config)) *Server {
|
||||
t.Helper()
|
||||
return newServer(t, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)), opts)
|
||||
}
|
||||
|
||||
// newLoggedServer is newTestServer with its JSON log lines kept for the test.
|
||||
func newLoggedServer(t *testing.T, jobs *fakeJobs, p Printer, opts ...func(*Config)) (*Server, *logBuffer) {
|
||||
t.Helper()
|
||||
logs := &logBuffer{}
|
||||
return newServer(t, jobs, p, slog.New(slog.NewJSONHandler(logs, nil)), opts), logs
|
||||
}
|
||||
|
||||
func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opts []func(*Config)) *Server {
|
||||
t.Helper()
|
||||
if jobs.statuses == nil {
|
||||
jobs.statuses = map[printqueue.JobID]printqueue.Status{}
|
||||
}
|
||||
return New(Config{
|
||||
cfg := Config{
|
||||
Info: Info{Project: "Überbringer", Version: "test"},
|
||||
Secret: testSecret,
|
||||
RateLimit: 1000,
|
||||
@@ -108,7 +131,101 @@ func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
|
||||
RequestID: func() string { return "req_test" },
|
||||
|
||||
HealthRecheckDelay: time.Millisecond,
|
||||
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
return New(cfg, jobs, p, logger)
|
||||
}
|
||||
|
||||
// logBuffer collects the server's JSON log lines.
|
||||
type logBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *logBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
// lines returns every log line written so far, decoded.
|
||||
func (b *logBuffer) lines(t *testing.T) []map[string]any {
|
||||
t.Helper()
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
var lines []map[string]any
|
||||
for line := range bytes.Lines(b.buf.Bytes()) {
|
||||
var parsed map[string]any
|
||||
if err := json.Unmarshal(line, &parsed); err != nil {
|
||||
t.Fatalf("log line %q: %v", line, err)
|
||||
}
|
||||
lines = append(lines, parsed)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// linesAt returns the lines with message msg at level, or at any level when
|
||||
// level is empty.
|
||||
func linesAt(lines []map[string]any, level, msg string) []map[string]any {
|
||||
var found []map[string]any
|
||||
for _, line := range lines {
|
||||
if line["msg"] == msg && (level == "" || line["level"] == level) {
|
||||
found = append(found, line)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func errorLines(lines []map[string]any) []map[string]any {
|
||||
var found []map[string]any
|
||||
for _, line := range lines {
|
||||
if line["level"] == slog.LevelError.String() {
|
||||
found = append(found, line)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// fakeTransport records the events sent to Sentry.
|
||||
type fakeTransport struct {
|
||||
mu sync.Mutex
|
||||
events []*sentry.Event
|
||||
}
|
||||
|
||||
func (f *fakeTransport) Flush(time.Duration) bool { return true }
|
||||
func (f *fakeTransport) FlushWithContext(context.Context) bool { return true }
|
||||
func (f *fakeTransport) Configure(sentry.ClientOptions) {}
|
||||
func (f *fakeTransport) Close() {}
|
||||
|
||||
func (f *fakeTransport) SendEvent(event *sentry.Event) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.events = append(f.events, event)
|
||||
}
|
||||
|
||||
func (f *fakeTransport) count() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.events)
|
||||
}
|
||||
|
||||
// captureSentryEvents binds a Sentry client that records its events to the
|
||||
// current hub until the test ends.
|
||||
func captureSentryEvents(t *testing.T) *fakeTransport {
|
||||
t.Helper()
|
||||
t.Setenv("SENTRY_DSN", "")
|
||||
transport := &fakeTransport{}
|
||||
client, err := sentry.NewClient(sentry.ClientOptions{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hub := sentry.CurrentHub()
|
||||
previous := hub.Client()
|
||||
hub.BindClient(client)
|
||||
t.Cleanup(func() { hub.BindClient(previous) })
|
||||
return transport
|
||||
}
|
||||
|
||||
func token(t *testing.T, secret []byte, method jwt.SigningMethod, claims jwt.Claims) string {
|
||||
@@ -120,23 +237,62 @@ func token(t *testing.T, secret []byte, method jwt.SigningMethod, claims jwt.Cla
|
||||
return signed
|
||||
}
|
||||
|
||||
// validToken returns a token whose only claim is user_id.
|
||||
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) {
|
||||
// send runs req through the server and returns the response and its body.
|
||||
func send(t *testing.T, s *Server, req *http.Request) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
resp, err := s.app.Test(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resp, body
|
||||
}
|
||||
|
||||
// do is send with a JSON body decoded; it is nil for routes that answer
|
||||
// plain text.
|
||||
func do(t *testing.T, s *Server, req *http.Request) (*http.Response, map[string]any) {
|
||||
t.Helper()
|
||||
resp, body := send(t, s, req)
|
||||
var parsed map[string]any
|
||||
_ = json.Unmarshal(body, &parsed) // some routes return plain text
|
||||
if strings.HasPrefix(resp.Header.Get(fiber.HeaderContentType), fiber.MIMEApplicationJSON) {
|
||||
if err := json.Unmarshal(body, &parsed); err != nil {
|
||||
t.Fatalf("response body %q: %v", body, err)
|
||||
}
|
||||
}
|
||||
return resp, parsed
|
||||
}
|
||||
|
||||
// expectError checks that the response is an error with the given status
|
||||
// and code, in the shape every error has, and returns the decoded body.
|
||||
func expectError(t *testing.T, resp *http.Response, body []byte, status int, code string) errorResponse {
|
||||
t.Helper()
|
||||
if resp.StatusCode != status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, status, body)
|
||||
}
|
||||
if ct := resp.Header.Get(fiber.HeaderContentType); !strings.HasPrefix(ct, fiber.MIMEApplicationJSON) {
|
||||
t.Fatalf("Content-Type = %q, want JSON", ct)
|
||||
}
|
||||
var e errorResponse
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&e); err != nil {
|
||||
t.Fatalf("error body %s: %v", body, err)
|
||||
}
|
||||
if e.Code != code || e.Error == "" {
|
||||
t.Fatalf("error body %s, want code %q and a message", body, code)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func printRequest(t *testing.T, body, auth string) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/print", strings.NewReader(body))
|
||||
@@ -155,6 +311,7 @@ func TestPrintAuth(t *testing.T) {
|
||||
})
|
||||
wrongKey := token(t, []byte("another-secret-another-secret-xx"), jwt.SigningMethodHS256, jwt.MapClaims{})
|
||||
hs512 := token(t, testSecret, jwt.SigningMethodHS512, jwt.MapClaims{})
|
||||
withSubject := token(t, testSecret, jwt.SigningMethodHS256, jwt.RegisteredClaims{Subject: "till-1"})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -167,17 +324,22 @@ func TestPrintAuth(t *testing.T) {
|
||||
{"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},
|
||||
{"token with a subject", "Bearer " + withSubject, http.StatusAccepted},
|
||||
{"token with only user_id", "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)
|
||||
resp, body := send(t, s, printRequest(t, validJob, tt.auth))
|
||||
if tt.want != http.StatusUnauthorized {
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.want, body)
|
||||
}
|
||||
return
|
||||
}
|
||||
if tt.want == http.StatusUnauthorized && resp.Header.Get("WWW-Authenticate") == "" {
|
||||
expectError(t, resp, body, http.StatusUnauthorized, "unauthorized")
|
||||
if resp.Header.Get("WWW-Authenticate") == "" {
|
||||
t.Error("401 without WWW-Authenticate")
|
||||
}
|
||||
})
|
||||
@@ -187,9 +349,8 @@ func TestPrintAuth(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
resp, body := send(t, s, req)
|
||||
expectError(t, resp, body, http.StatusUnauthorized, "unauthorized")
|
||||
}
|
||||
|
||||
func TestPrintAccepted(t *testing.T) {
|
||||
@@ -205,6 +366,9 @@ func TestPrintAccepted(t *testing.T) {
|
||||
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
|
||||
t.Errorf("Location = %q", loc)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
if len(jobs.submitted) != 1 || jobs.submitted[0].Elements[0].Text != "Hello" {
|
||||
t.Errorf("submitted %+v", jobs.submitted)
|
||||
}
|
||||
@@ -215,7 +379,7 @@ func TestPrintBadRequests(t *testing.T) {
|
||||
name, body, wantErr string
|
||||
}{
|
||||
{"not json", `nope`, "not a valid job"},
|
||||
{"old format", `{"data":[{"type":1,"size":1,"text":"hi"}]}`, `replaced by {"elements": [...]}`},
|
||||
{"data instead of elements", `{"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"},
|
||||
@@ -224,12 +388,10 @@ func TestPrintBadRequests(t *testing.T) {
|
||||
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)
|
||||
resp, body := send(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
|
||||
e := expectError(t, resp, body, http.StatusBadRequest, "invalid_job")
|
||||
if !strings.Contains(e.Error, tt.wantErr) {
|
||||
t.Errorf("error = %q, want it to contain %q", e.Error, tt.wantErr)
|
||||
}
|
||||
if len(jobs.submitted) != 0 {
|
||||
t.Error("invalid job was submitted")
|
||||
@@ -240,18 +402,31 @@ func TestPrintBadRequests(t *testing.T) {
|
||||
|
||||
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"])
|
||||
resp, body := send(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
|
||||
if e := expectError(t, resp, body, http.StatusBadRequest, "invalid_job"); len(e.Details) != 2 {
|
||||
t.Errorf("details = %v, want 2 problems", e.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 TestPrintQueueRefusals(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
wantRetryAfter bool
|
||||
}{
|
||||
{"queue full", printqueue.ErrQueueFull, "queue_full", true},
|
||||
{"shutting down", printqueue.ErrClosed, "shutting_down", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
|
||||
resp, body := send(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
|
||||
if got := resp.Header.Get("Retry-After") != ""; got != tt.wantRetryAfter {
|
||||
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,32 +436,28 @@ func TestJobStatus(t *testing.T) {
|
||||
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
|
||||
}}
|
||||
s := newTestServer(t, jobs, &fakePrinter{})
|
||||
get := func(path, auth string) *http.Request {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
if auth != "" {
|
||||
req.Header.Set("Authorization", auth)
|
||||
}
|
||||
return req
|
||||
}
|
||||
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},
|
||||
resp, body := do(t, s, get("/api/v1/jobs/"+id.String(), auth))
|
||||
if resp.StatusCode != http.StatusOK || body["status"] != "done" {
|
||||
t.Errorf("GET known job = %d %v", resp.StatusCode, body)
|
||||
}
|
||||
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)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
|
||||
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)
|
||||
for _, path := range []string{"/api/v1/jobs/job_01h455vb4pex5vsknk084sn02r", "/api/v1/jobs/not-an-id"} {
|
||||
resp, raw := send(t, s, get(path, auth))
|
||||
expectError(t, resp, raw, http.StatusNotFound, "job_not_found")
|
||||
}
|
||||
resp, raw := send(t, s, get("/api/v1/jobs/"+id.String(), ""))
|
||||
expectError(t, resp, raw, http.StatusUnauthorized, "unauthorized")
|
||||
}
|
||||
|
||||
func TestHealth(t *testing.T) {
|
||||
@@ -319,6 +490,9 @@ func TestHealth(t *testing.T) {
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
if got := tt.printer.Calls(); got != tt.wantCalls {
|
||||
t.Errorf("printer queried %d times, want %d", got, tt.wantCalls)
|
||||
}
|
||||
@@ -342,47 +516,334 @@ func TestIndexAndRobotsAndNotFound(t *testing.T) {
|
||||
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 {
|
||||
if resp, _ := send(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)
|
||||
resp, raw := send(t, s, httptest.NewRequest(http.MethodGet, "/nope", nil))
|
||||
if e := expectError(t, resp, raw, http.StatusNotFound, "not_found"); strings.Contains(e.Error, "/nope") {
|
||||
t.Errorf("error = %q; Fiber's own text must not reach the client", e.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMethodNotAllowed(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/print", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
resp, body := send(t, s, req)
|
||||
expectError(t, resp, body, http.StatusMethodNotAllowed, "method_not_allowed")
|
||||
if allow := resp.Header.Get(fiber.HeaderAllow); !strings.Contains(allow, http.MethodPost) {
|
||||
t.Errorf("Allow = %q, want it to list POST", allow)
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}, func(c *Config) {
|
||||
c.RateLimit = 2
|
||||
c.TrustedProxies = []string{"0.0.0.0/0"}
|
||||
})
|
||||
sendFrom := func(clientIP string) (*http.Response, []byte) {
|
||||
req := printRequest(t, validJob, "Bearer "+validToken(t))
|
||||
req.Header.Set("X-Real-IP", clientIP)
|
||||
resp, _ := do(t, s, req)
|
||||
return resp.StatusCode
|
||||
return send(t, s, req)
|
||||
}
|
||||
for range 2 {
|
||||
if code := send("203.0.113.1"); code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", code)
|
||||
if resp, body := sendFrom("203.0.113.1"); resp.StatusCode != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202 (%s)", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
if code := send("203.0.113.1"); code != http.StatusTooManyRequests {
|
||||
t.Errorf("third request status = %d, want 429", code)
|
||||
resp, body := sendFrom("203.0.113.1")
|
||||
expectError(t, resp, body, http.StatusTooManyRequests, "rate_limited")
|
||||
if resp.Header.Get("Retry-After") == "" {
|
||||
t.Error("429 without Retry-After")
|
||||
}
|
||||
if code := send("203.0.113.2"); code != http.StatusAccepted {
|
||||
t.Errorf("other client status = %d, want 202 (limits must be per client)", code)
|
||||
if resp, body := sendFrom("203.0.113.2"); resp.StatusCode != http.StatusAccepted {
|
||||
t.Errorf("other client status = %d, want 202 (limits must be per client): %s", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutesConform walks every registered route. Each /api/v1 route must
|
||||
// refuse a request without a token, be rate limited and keep to the body
|
||||
// limit; the other routes are public. A route without a case here fails the
|
||||
// test, so none is added without being checked and documented.
|
||||
func TestRoutesConform(t *testing.T) {
|
||||
id := newJobID(t)
|
||||
public := map[string]bool{
|
||||
"GET /": true,
|
||||
"GET /robots.txt": true,
|
||||
"GET /healthz": true,
|
||||
}
|
||||
// Each authenticated route maps to a path that reaches it.
|
||||
authenticated := map[string]string{
|
||||
"POST /api/v1/print": "/api/v1/print",
|
||||
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
|
||||
}
|
||||
|
||||
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
seen := map[string]bool{}
|
||||
for _, route := range s.app.GetRoutes(true) {
|
||||
key := route.Method + " " + route.Path
|
||||
if route.Method == http.MethodHead || seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
switch path, ok := authenticated[key]; {
|
||||
case ok:
|
||||
t.Run(key, func(t *testing.T) { checkAuthenticatedRoute(t, route.Method, path) })
|
||||
case public[key]:
|
||||
t.Run(key, func(t *testing.T) {
|
||||
resp, body := send(t, s, httptest.NewRequest(route.Method, route.Path, nil))
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
t.Errorf("public route answered 401: %s", body)
|
||||
}
|
||||
})
|
||||
default:
|
||||
t.Errorf("%s has no conformance case: add one here and a row to the README's API table", key)
|
||||
}
|
||||
}
|
||||
for key := range authenticated {
|
||||
if !seen[key] {
|
||||
t.Errorf("conformance case %s has no route", key)
|
||||
}
|
||||
}
|
||||
for key := range public {
|
||||
if !seen[key] {
|
||||
t.Errorf("conformance case %s has no route", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkAuthenticatedRoute checks the refusals every /api/v1 route shares.
|
||||
func checkAuthenticatedRoute(t *testing.T, method, path string) {
|
||||
request := func(body string, withToken bool) *http.Request {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if withToken {
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
}
|
||||
return req
|
||||
}
|
||||
// fasthttp does not read the body of a GET, so only other methods send one.
|
||||
body := validJob
|
||||
if method == http.MethodGet {
|
||||
body = ""
|
||||
}
|
||||
|
||||
t.Run("requires a token", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
|
||||
resp, raw := send(t, s, request(body, false))
|
||||
expectError(t, resp, raw, http.StatusUnauthorized, "unauthorized")
|
||||
if resp.Header.Get("WWW-Authenticate") == "" {
|
||||
t.Error("401 without WWW-Authenticate")
|
||||
}
|
||||
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
|
||||
t.Errorf("Cache-Control = %q, want no-store", cc)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("is rate limited", func(t *testing.T) {
|
||||
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}, func(c *Config) { c.RateLimit = 1 })
|
||||
if resp, raw := send(t, s, request(body, true)); resp.StatusCode == http.StatusTooManyRequests {
|
||||
t.Fatalf("first request was rate limited: %s", raw)
|
||||
}
|
||||
resp, raw := send(t, s, request(body, true))
|
||||
expectError(t, resp, raw, http.StatusTooManyRequests, "rate_limited")
|
||||
if n, err := strconv.Atoi(resp.Header.Get("Retry-After")); err != nil || n < 1 {
|
||||
t.Errorf("Retry-After = %q, want a positive number of seconds", resp.Header.Get("Retry-After"))
|
||||
}
|
||||
})
|
||||
|
||||
if method == http.MethodGet {
|
||||
return
|
||||
}
|
||||
t.Run("keeps to the body limit", func(t *testing.T) {
|
||||
// The token is valid so that the request is refused for its size
|
||||
// alone, and is logged with that status.
|
||||
s, logs := newLoggedServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{}, func(c *Config) { c.BodyLimit = 512 })
|
||||
req := request(strings.Repeat(" ", 1024)+body, true)
|
||||
req.URL.Scheme, req.URL.Host, req.RequestURI = "http", "uberbringer.test", ""
|
||||
resp, err := serveInMemory(t, s).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expectError(t, resp, raw, http.StatusRequestEntityTooLarge, "body_too_large")
|
||||
requests := linesAt(logs.lines(t), "", "request")
|
||||
if len(requests) != 1 || requests[0]["status"] != float64(http.StatusRequestEntityTooLarge) {
|
||||
t.Errorf("request lines = %v, want one with status 413", requests)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// serveInMemory serves s on an in-memory listener until the test ends and
|
||||
// returns a client connected to it. Requests then pass through the whole
|
||||
// fasthttp server, which refuses some itself, such as a body over the
|
||||
// limit; app.Test returns those refusals as errors instead of responses.
|
||||
func serveInMemory(t *testing.T, s *Server) *http.Client {
|
||||
t.Helper()
|
||||
ln := &pipeListener{conns: make(chan net.Conn), closed: make(chan struct{})}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
served := make(chan error, 1)
|
||||
go func() { served <- s.Serve(ctx, ln) }()
|
||||
transport := &http.Transport{DialContext: ln.dial}
|
||||
t.Cleanup(func() {
|
||||
transport.CloseIdleConnections()
|
||||
cancel()
|
||||
if err := <-served; err != nil {
|
||||
t.Errorf("Serve: %v", err)
|
||||
}
|
||||
})
|
||||
return &http.Client{Transport: transport}
|
||||
}
|
||||
|
||||
// pipeListener is a net.Listener whose connections are net.Pipe pairs.
|
||||
type pipeListener struct {
|
||||
conns chan net.Conn
|
||||
closed chan struct{}
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
func (l *pipeListener) Accept() (net.Conn, error) {
|
||||
select {
|
||||
case conn := <-l.conns:
|
||||
return conn, nil
|
||||
case <-l.closed:
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
}
|
||||
|
||||
func (l *pipeListener) Close() error {
|
||||
l.closeOnce.Do(func() { close(l.closed) })
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *pipeListener) Addr() net.Addr { return pipeAddr{} }
|
||||
|
||||
func (l *pipeListener) dial(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
server, client := net.Pipe()
|
||||
select {
|
||||
case l.conns <- server:
|
||||
return client, nil
|
||||
case <-l.closed:
|
||||
return nil, net.ErrClosed
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
type pipeAddr struct{}
|
||||
|
||||
func (pipeAddr) Network() string { return "pipe" }
|
||||
func (pipeAddr) String() string { return "pipe" }
|
||||
|
||||
func TestRefusalsAreNotLoggedAsFailures(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
jobs *fakeJobs
|
||||
printer *fakePrinter
|
||||
request func(t *testing.T) *http.Request
|
||||
status int
|
||||
level slog.Level
|
||||
}{
|
||||
{
|
||||
name: "queue full",
|
||||
jobs: &fakeJobs{submitErr: printqueue.ErrQueueFull},
|
||||
printer: &fakePrinter{},
|
||||
request: func(t *testing.T) *http.Request { return printRequest(t, validJob, "Bearer "+validToken(t)) },
|
||||
status: http.StatusServiceUnavailable,
|
||||
level: slog.LevelWarn,
|
||||
},
|
||||
{
|
||||
name: "printer unreachable",
|
||||
jobs: &fakeJobs{},
|
||||
printer: &fakePrinter{err: errors.New("connection refused")},
|
||||
request: func(*testing.T) *http.Request { return httptest.NewRequest(http.MethodGet, "/healthz", nil) },
|
||||
status: http.StatusServiceUnavailable,
|
||||
level: slog.LevelWarn,
|
||||
},
|
||||
{
|
||||
name: "no token",
|
||||
jobs: &fakeJobs{},
|
||||
printer: &fakePrinter{},
|
||||
request: func(t *testing.T) *http.Request { return printRequest(t, validJob, "") },
|
||||
status: http.StatusUnauthorized,
|
||||
level: slog.LevelInfo,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, logs := newLoggedServer(t, tt.jobs, tt.printer)
|
||||
if resp, body := send(t, s, tt.request(t)); resp.StatusCode != tt.status {
|
||||
t.Fatalf("status = %d, want %d (%s)", resp.StatusCode, tt.status, body)
|
||||
}
|
||||
lines := logs.lines(t)
|
||||
requests := linesAt(lines, "", "request")
|
||||
if len(requests) != 1 || requests[0]["level"] != tt.level.String() || requests[0]["status"] != float64(tt.status) {
|
||||
t.Errorf("request lines = %v, want one at %s with status %d", requests, tt.level, tt.status)
|
||||
}
|
||||
if failures := errorLines(lines); len(failures) != 0 {
|
||||
t.Errorf("a refusal was logged as a failure: %v", failures)
|
||||
}
|
||||
})
|
||||
}
|
||||
if n := events.count(); n != 0 {
|
||||
t.Errorf("%d Sentry events for refusals, want none", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnexpectedErrorIsLoggedAndReportedOnce(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
id := newJobID(t)
|
||||
s, logs := newLoggedServer(t, &fakeJobs{statusErr: errors.New("status store broke")}, &fakePrinter{})
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/jobs/"+id.String(), nil)
|
||||
req.Header.Set("Authorization", "Bearer "+validToken(t))
|
||||
|
||||
resp, body := send(t, s, req)
|
||||
expectError(t, resp, body, http.StatusInternalServerError, "internal_error")
|
||||
if bytes.Contains(body, []byte("status store broke")) {
|
||||
t.Errorf("body %s repeats the internal error", body)
|
||||
}
|
||||
lines := logs.lines(t)
|
||||
failures := errorLines(lines)
|
||||
if len(failures) != 1 || failures[0]["msg"] != "request failed" || failures[0]["err"] != "status store broke" {
|
||||
t.Errorf("error lines = %v, want one request failed line with the error", failures)
|
||||
}
|
||||
if requests := linesAt(lines, slog.LevelWarn.String(), "request"); len(requests) != 1 {
|
||||
t.Errorf("request lines = %v, want one warning", linesAt(lines, "", "request"))
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanicIsLoggedAndReportedOnce(t *testing.T) {
|
||||
events := captureSentryEvents(t)
|
||||
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
|
||||
s.app.Get("/panic", func(fiber.Ctx) error { panic("handler exploded") })
|
||||
|
||||
resp, body := send(t, s, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
||||
expectError(t, resp, body, http.StatusInternalServerError, "internal_error")
|
||||
if bytes.Contains(body, []byte("exploded")) {
|
||||
t.Errorf("body %s repeats the panic", body)
|
||||
}
|
||||
lines := logs.lines(t)
|
||||
failures := errorLines(lines)
|
||||
if len(failures) != 1 || failures[0]["msg"] != "panic" || failures[0]["panic"] != "handler exploded" {
|
||||
t.Fatalf("error lines = %v, want one panic line", failures)
|
||||
}
|
||||
if stack, _ := failures[0]["stack"].(string); !strings.Contains(stack, "TestPanicIsLoggedAndReportedOnce") {
|
||||
t.Errorf("stack does not show where the panic happened:\n%s", stack)
|
||||
}
|
||||
requests := linesAt(lines, "", "request")
|
||||
if len(requests) != 1 || requests[0]["status"] != float64(http.StatusInternalServerError) {
|
||||
t.Errorf("request lines = %v, want one with status 500", requests)
|
||||
}
|
||||
if n := events.count(); n != 1 {
|
||||
t.Errorf("%d Sentry events, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,10 +7,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/config"
|
||||
"uberbringer/internal/pkg/config"
|
||||
)
|
||||
|
||||
const validSecret = "xTw8qdxTy7Ng4DiptTqmeVy506xWLht3OhFn4kdawmM="
|
||||
// validSecret is a placeholder that satisfies the 32-byte minimum.
|
||||
const validSecret = "test-only-secret-test-only-secret-0123"
|
||||
|
||||
func writeConfig(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
@@ -21,9 +22,10 @@ func writeConfig(t *testing.T, body string) string {
|
||||
return path
|
||||
}
|
||||
|
||||
func TestLoadLegacyConfigGetsDefaults(t *testing.T) {
|
||||
func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
|
||||
t.Setenv("SENTRY_DSN", "")
|
||||
// The exact shape written by the original install.sh, plus a printer.
|
||||
// The shape install.sh writes; every other setting comes from the
|
||||
// defaults.
|
||||
path := writeConfig(t, `
|
||||
[webserver]
|
||||
bind_ip = "127.0.0.1"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// Byte-exact checks against the Epson ESC/POS command reference.
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// statusTimeout bounds how long the printer may take to answer one real-time
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/printer"
|
||||
)
|
||||
|
||||
// fakePrinter accepts one connection per handle call.
|
||||
@@ -71,8 +71,10 @@ func TestSendUnreachable(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
|
||||
accepted := make(chan struct{}, 1)
|
||||
release := make(chan struct{})
|
||||
addr := fakePrinter(t, func(conn net.Conn) {
|
||||
accepted <- struct{}{}
|
||||
<-release
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
@@ -80,9 +82,15 @@ func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
|
||||
client := printer.NewClient(addr, time.Second, 5*time.Second)
|
||||
|
||||
// Hold the single connection slot with a status query that never gets
|
||||
// an answer, then try to send with a short deadline.
|
||||
// an answer, then try to send with a short deadline. The client takes
|
||||
// the slot before it dials, so once the printer has accepted the status
|
||||
// query's connection the slot is held.
|
||||
go func() { _, _ = client.Status(context.Background()) }()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
select {
|
||||
case <-accepted:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the status query never connected")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
@@ -168,14 +176,17 @@ func TestStatusUnsupported(t *testing.T) {
|
||||
|
||||
func TestStatusContextDeadlineIsNotUnsupported(t *testing.T) {
|
||||
// A printer that answers, just later than the caller is willing to wait,
|
||||
// e.g. while it works through a large buffered image.
|
||||
// e.g. while it works through a large buffered image. It answers only
|
||||
// once the test is over, after the caller's deadline has passed.
|
||||
late := make(chan struct{})
|
||||
t.Cleanup(func() { close(late) })
|
||||
addr := fakePrinter(t, func(conn net.Conn) {
|
||||
req := make([]byte, 3)
|
||||
for {
|
||||
if _, err := io.ReadFull(conn, req); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
<-late
|
||||
_, _ = conn.Write([]byte{0x1A}) // offline
|
||||
}
|
||||
})
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
"go.jetify.com/typeid"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
// jobTimeout bounds rendering and sending one job, including retries.
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/printqueue"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
type fakeRenderer struct{ err error }
|
||||
@@ -72,11 +72,11 @@ func newQueue(r printqueue.Renderer, s printqueue.Sender, opts printqueue.Option
|
||||
return printqueue.New(r, s, discardLogger(), opts)
|
||||
}
|
||||
|
||||
// startQueue runs q until the test ends and returns a func that stops it and
|
||||
// waits for Run to return.
|
||||
func startQueue(t *testing.T, q *printqueue.Queue) (stop func()) {
|
||||
// startQueue runs q until the test ends. cancel cancels Run's context and
|
||||
// wait blocks until Run has returned.
|
||||
func startQueue(t *testing.T, q *printqueue.Queue) (cancel, wait func()) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ctx, cancelRun := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
@@ -84,10 +84,9 @@ func startQueue(t *testing.T, q *printqueue.Queue) (stop func()) {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
var once sync.Once
|
||||
stop = func() { once.Do(func() { cancel(); <-done }) }
|
||||
t.Cleanup(stop)
|
||||
return stop
|
||||
wait = func() { <-done }
|
||||
t.Cleanup(func() { cancelRun(); wait() })
|
||||
return cancelRun, wait
|
||||
}
|
||||
|
||||
func waitForState(t *testing.T, q *printqueue.Queue, id printqueue.JobID, want printqueue.State) printqueue.Status {
|
||||
@@ -145,27 +144,31 @@ func TestRetriesThenSucceeds(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFailsAfterRetries(t *testing.T) {
|
||||
var reported []printqueue.JobID
|
||||
var mu sync.Mutex
|
||||
reported := make(chan printqueue.JobID, 2)
|
||||
sender := &fakeSender{failures: 10}
|
||||
q := newQueue(fakeRenderer{}, sender, printqueue.Options{
|
||||
Retries: 2,
|
||||
OnFailure: func(id printqueue.JobID, _ error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
reported = append(reported, id)
|
||||
},
|
||||
Retries: 2,
|
||||
OnFailure: func(id printqueue.JobID, _ error) { reported <- id },
|
||||
})
|
||||
startQueue(t, q)
|
||||
cancel, wait := startQueue(t, q)
|
||||
st, _ := q.Submit(job("x"))
|
||||
failed := waitForState(t, q, st.ID, printqueue.StateFailed)
|
||||
if failed.Attempts != 3 || !strings.Contains(failed.Error, "printer offline") {
|
||||
t.Errorf("failed status = %+v", failed)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(reported) != 1 || reported[0] != st.ID {
|
||||
t.Errorf("OnFailure got %v", reported)
|
||||
// OnFailure runs after the job is marked failed, so wait for it.
|
||||
select {
|
||||
case id := <-reported:
|
||||
if id != st.ID {
|
||||
t.Errorf("OnFailure got %s, want %s", id, st.ID)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("OnFailure was not called")
|
||||
}
|
||||
cancel()
|
||||
wait()
|
||||
if n := len(reported); n != 0 {
|
||||
t.Errorf("OnFailure called %d more times, want once", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,17 +202,17 @@ func TestQueueFull(t *testing.T) {
|
||||
func TestShutdownFinishesCurrentJobAndFailsWaiting(t *testing.T) {
|
||||
sender := &fakeSender{block: make(chan struct{})}
|
||||
q := newQueue(fakeRenderer{}, sender, printqueue.Options{})
|
||||
stop := startQueue(t, q)
|
||||
cancel, wait := startQueue(t, q)
|
||||
|
||||
first, _ := q.Submit(job("first"))
|
||||
waitForState(t, q, first.ID, printqueue.StatePrinting)
|
||||
second, _ := q.Submit(job("second"))
|
||||
|
||||
stopped := make(chan struct{})
|
||||
go func() { stop(); close(stopped) }()
|
||||
time.Sleep(20 * time.Millisecond) // let Run observe the cancellation
|
||||
close(sender.block) // the in-flight send completes
|
||||
<-stopped
|
||||
// Cancel while the first send is still blocked, so Run is shutting down
|
||||
// by the time that send completes.
|
||||
cancel()
|
||||
close(sender.block)
|
||||
wait()
|
||||
|
||||
if st, _ := q.Status(first.ID); st.State != printqueue.StateDone {
|
||||
t.Errorf("in-flight job state = %s, want done", st.State)
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"image/png"
|
||||
"testing"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
|
||||
"uberbringer/internal/pkg/raster"
|
||||
)
|
||||
|
||||
func encodePNG(t *testing.T, img image.Image) []byte {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// Element types.
|
||||
|
||||
@@ -3,7 +3,7 @@ package receipt
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
)
|
||||
|
||||
// tabWidth matches the printer's default horizontal tab stops.
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/receipt"
|
||||
)
|
||||
|
||||
type fakeFetcher struct {
|
||||
|
||||
@@ -8,8 +8,8 @@ import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/raster"
|
||||
"uberbringer/internal/pkg/escpos"
|
||||
"uberbringer/internal/pkg/raster"
|
||||
)
|
||||
|
||||
// Fetcher downloads remote image data.
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/safehttp"
|
||||
"uberbringer/internal/pkg/safehttp"
|
||||
)
|
||||
|
||||
func newServer(t *testing.T, body string) *httptest.Server {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
[Unit]
|
||||
Description=Uberbringer receipt printer server
|
||||
Documentation=https://git.anomalous.dev/57_Wolve/uberbringer
|
||||
Wants=network-online.target
|
||||
After=network.target network-online.target
|
||||
# Start-rate limits are [Unit] settings (systemd v230+); systemd ignores
|
||||
# StartLimitIntervalSec= in [Service].
|
||||
StartLimitIntervalSec=60
|
||||
StartLimitBurst=3
|
||||
|
||||
# Change settings with `systemctl edit uberbringer` rather than editing this
|
||||
# file: drop-ins in /etc/systemd/system/uberbringer.service.d/ survive upgrades.
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=uberbringer
|
||||
Group=uberbringer
|
||||
WorkingDirectory=/etc/uberbringer
|
||||
ExecStart=/usr/local/bin/uberbringer --config /etc/uberbringer/config.toml
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
LimitNOFILE=4096
|
||||
|
||||
# ── Privileges ────────────────────────────────────────────────────────────────
|
||||
# The daemon binds an unprivileged port, dials the printer over TCP and fetches
|
||||
# images and reports errors to Sentry over HTTPS. It needs no capabilities.
|
||||
CapabilityBoundingSet=
|
||||
AmbientCapabilities=
|
||||
NoNewPrivileges=true
|
||||
|
||||
# ── Sandboxing ────────────────────────────────────────────────────────────────
|
||||
# The daemon only reads its config and the system CA bundle; it writes no
|
||||
# files and opens no devices, so the whole file system is read-only to it.
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
PrivateDevices=true
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectKernelLogs=true
|
||||
ProtectControlGroups=true
|
||||
ProtectClock=true
|
||||
ProtectHostname=true
|
||||
LockPersonality=true
|
||||
MemoryDenyWriteExecute=true
|
||||
RestrictSUIDSGID=true
|
||||
RestrictRealtime=true
|
||||
RestrictNamespaces=true
|
||||
SystemCallArchitectures=native
|
||||
SystemCallFilter=@system-service
|
||||
SystemCallErrorNumber=EPERM
|
||||
# IPv4 and IPv6 for the listener, the printer, DNS, image fetches and Sentry;
|
||||
# AF_UNIX for local sockets such as the journal.
|
||||
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Reference in new issue
Block a user