Read the config with Viper and environment variables, on Go 1.27.4
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m54s

The config loader uses Viper instead of BurntSushi/toml. Every setting
can also come from UBERBRINGER_<SECTION>_<KEY>, which wins over the
file, and UBERBRINGER_CONFIG sets the default of --config; set empty, no
file is read, so a container can run from the environment alone. Each
setting is bound to its own variable, so a variable named after a
section changes nothing.

The file is parsed with go-toml and checked as written: unknown keys,
empty tables and keys that differ only in case are errors, a UTF-8 BOM
is skipped and a UTF-16 file is refused. Values are decoded strictly:
durations are strings, numbers decimal, flags true or false, and a
fraction for a whole number is refused. Errors name the file, the line
of a syntax error and the variables that were set, never their values.

`uberbringer config get <key>` prints one setting as the daemon would
use it. install.sh reads body_limit, bind_ip and port through it, so the
config is checked before the service restarts and Caddy proxies to the
configured address. The script then waits for the daemon to answer,
downloads Caddy's key and source list before replacing them, requires
Caddy's own repository, keeps the Caddyfile during dpkg upgrades,
detects an existing import loosely, logs Caddy's other errors, drops
query strings from the access log and validates the domain and printer
address more tightly.

go.mod names Go 1.27.4 with no toolchain line, and the workflows check
against the go line. The changelog folds the unreleased entries into
0.2.0, which is not tagged yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 08:12:57 -06:00
1 parent 92dcacb3b9
commit eacd0bfd27
18 files changed
+1244 -248

No files matched your search

+4 -3
View File
@@ -35,13 +35,14 @@ jobs:
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.
# Releases are built with the Go release go.mod names: its toolchain line
# if it has one, else its go line. Fail if any other Go is running.
- name: Check the Go toolchain
run: |
want="$(sed -n 's/^toolchain //p' go.mod)"
[ -n "$want" ] || want="go$(sed -n 's/^go //p' go.mod)"
have="$(go env GOVERSION)"
echo "go.mod toolchain: ${want:-none}; running: $have"
echo "go.mod names: $want; running: $have"
[ "$have" = "$want" ]
# prerelease: auto in .goreleaser.yaml publishes vX.Y.Z-rc.N as a
+4 -4
View File
@@ -23,14 +23,14 @@ jobs:
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.
# which must be the release go.mod names, the one releases are built
# with: its toolchain line if it has one, else its go line.
- name: Check the Go toolchain
run: |
want="$(sed -n 's/^toolchain //p' go.mod)"
[ -n "$want" ] || want="go$(sed -n 's/^go //p' go.mod)"
have="$(go env GOVERSION)"
echo "go.mod toolchain: ${want:-none}; running: $have"
echo "go.mod names: $want; running: $have"
[ "$have" = "$want" ]
- name: govulncheck
+5 -3
View File
@@ -20,13 +20,15 @@ jobs:
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.
# setup-go@v5 installs the release named by go.mod's go line; with a
# toolchain line, the go command switches to that instead. Fail unless
# the running Go is the one go.mod names.
- name: Check the Go toolchain
run: |
want="$(sed -n 's/^toolchain //p' go.mod)"
[ -n "$want" ] || want="go$(sed -n 's/^go //p' go.mod)"
have="$(go env GOVERSION)"
echo "go.mod toolchain: ${want:-none}; running: $have"
echo "go.mod names: $want; running: $have"
[ "$have" = "$want" ]
# The gofmt on PATH is setup-go's; the one under GOROOT belongs to the
+87 -59
View File
@@ -7,52 +7,6 @@ version may break callers; such changes are listed under **Breaking**.
## [Unreleased]
### Added
- Blocks, laid out to the printer model's width when the job prints:
- `box`: `single`, `double`, `double-h`, `double-v` or `ascii` borders, a
title set into the top border (`inline` or `capped`), a footer in the
bottom border, `padding`, `fit` and `columns`. Its body is `text` or
`children`: text, feed, kv and rules, which print as dividers joined to
the borders.
- `rule`: nine line styles, from `single` and `double` to shades, dashes
and dots, with an optional label.
- `kv`: key-value rows joined by a leader; long values wrap.
`size` (1–3) and `font` scale a block's borders and text together. On
cp850, cp858 and cp1252, glyphs the code page lacks fall back to ones it
has. README § Blocks lists the fields.
- `POST /api/v1/preview` and `uberbringer preview [file.json|-]` show the
lines a job would print, read back from its rendered bytes, without
printing it or fetching images. The route answers plain text, or JSON with
the styled runs, the line count and warnings for characters printed as
`?`.
- `[format]` with `max_lines` (default 2000): a job that would print more
lines fails instead of printing. `/api/v1/preview` answers such a job with
`422` and the new code `too_many_lines`.
- `printer.box_line_spacing` (default 0): the line spacing used while a box
prints, to close the gaps in its vertical borders. The default, the
printer's own spacing, was checked on paper on the TM-T88IV.
- `examples/blocks.json`, a receipt with every block style, padding, size
and junction, for checking the borders on paper.
### Changed
- Text is composed to Unicode NFC before it is printed, so a decomposed `é`
prints as `é`. Characters the code page lacks fold to look-alikes instead
of printing as `?`: curly quotes print as `"` and `'`, `–` as `-`, `—` as
`--`, `…` as `...`, `•` as `·`, `→ ←` as `-> <-`, `✓ ✔` as `√` (or `x`),
`×` as `x`, `€` as `EUR` and `™` as `TM`. An emoji sequence, with its skin
tone, variation selector or joined emoji, prints as one `?` instead of
one per code point, and zero-width spaces and joiners are removed. A
character the code page has prints as before, so cp1252 keeps its curly
quotes and cp858 its `€`.
- `invalid_job` details name nested elements by their path, e.g.
`elements[0].children[3] (qr): not allowed inside a box; place it after the
box`. A block field on another element type, such as `title` on `text`, is
listed there (`field "title" does not apply to text`) instead of failing
the whole decode as an unknown field.
## [0.2.0] - 2026-11-30
The daemon is rewritten, and so are its install script and release process,
@@ -165,9 +119,69 @@ upgrade a 0.1 install.
`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.
- Blocks, laid out to the printer model's width when the job prints:
- `box`: `single`, `double`, `double-h`, `double-v` or `ascii` borders, a
title set into the top border (`inline` or `capped`), a footer in the
bottom border, `padding`, `fit` and `columns`. Its body is `text` or
`children`: text, feed, kv and rules, which print as dividers joined to
the borders.
- `rule`: nine line styles, from `single` and `double` to shades, dashes
and dots, with an optional label.
- `kv`: key-value rows joined by a leader; long values wrap.
`size` (1–3) and `font` scale a block's borders and text together. On
cp850, cp858 and cp1252, glyphs the code page lacks fall back to ones it
has. README § Blocks lists the fields.
- `POST /api/v1/preview` and `uberbringer preview [file.json|-]` show the
lines a job would print, read back from its rendered bytes, without
printing it or fetching images. The route answers plain text, or JSON with
the styled runs, the line count and warnings for characters printed as
`?`.
- `[format]` with `max_lines` (default 2000): a job that would print more
lines fails instead of printing. `/api/v1/preview` answers such a job with
`422` and the code `too_many_lines`.
- `printer.box_line_spacing` (default 0): the line spacing used while a box
prints, to close the gaps in its vertical borders. The default, the
printer's own spacing, was checked on paper on the TM-T88IV.
- `examples/blocks.json`, a receipt with every block style, padding, size
and junction, for checking the borders on paper.
- Every config key can be set by an environment variable,
`UBERBRINGER_<SECTION>_<KEY>` (e.g. `UBERBRINGER_PRINTER_ADDRESS`), which
wins over the config file. Numbers are decimal digits, flags `true` or
`false`, durations strings such as `5s`, and lists comma-separated. An
empty variable counts as unset; one of only spaces is an error. A failed
load names the set `UBERBRINGER_*` variables that match no setting.
- `UBERBRINGER_CONFIG` sets the default of `--config`. Set empty, or with
`--config ""`, no config file is read, so a container can run from
environment variables alone. The Docker image sets it to
`/etc/uberbringer/config.toml`.
- `uberbringer config get <key>` prints one setting as the daemon would use
it, and fails when the configuration does not load. It never prints
`api.secret`. `install.sh` reads the config through it.
### Changed
- The config is read with Viper. 0.1 config files load as before. Unknown
keys are errors, empty tables included, and so are two keys that differ
only in case. A duration must be a string such as `"5s"`, and a number
with a fraction for a whole-number setting is refused. A number, flag or
list may also be written as a string, as in an environment variable. A
file that starts with a UTF-8 byte order mark loads; a UTF-16 file is
refused with a message saying so. A TOML syntax error names its line and
column, and other errors name the file and the `UBERBRINGER_*` variables
that were set, never their values.
- Text is composed to Unicode NFC before it is printed, so a decomposed `é`
prints as `é`. Characters the code page lacks fold to look-alikes instead
of printing as `?`: curly quotes print as `"` and `'`, `–` as `-`, `—` as
`--`, `…` as `...`, `•` as `·`, `→ ←` as `-> <-`, `✓ ✔` as `√` (or `x`),
`×` as `x`, `€` as `EUR` and `™` as `TM`. An emoji sequence, with its skin
tone, variation selector or joined emoji, prints as one `?` instead of
one per code point, and zero-width spaces and joiners are removed.
- `invalid_job` details name nested elements by their path, e.g.
`elements[0].children[3] (qr): not allowed inside a box; place it after the
box`. A field that applies to another element type, such as `title` on
`text`, is listed there (`field "title" does not apply to text`).
- The licence is now the European Union Public Licence v. 1.2 (EUPL-1.2),
replacing the GNU Affero General Public License v3.0. Releases up to and
including 0.1.2 stay available under AGPL-3.0.
@@ -199,31 +213,45 @@ upgrade a 0.1 install.
instead of the terminal. Re-runs create no new tokens.
- `install.sh`, reverse proxy and certificate:
- Caddy replaces nginx and acme.sh. It is installed from Caddy's own apt
repository, obtains and renews the certificate itself, redirects HTTP to
HTTPS, sets `X-Real-IP` and adds HSTS and other security headers.
- Caddy limits bodies to `webserver.body_limit` and answers a larger one
with the daemon's `413` `body_too_large` JSON.
repository, and the script stops if that repository can't be read. Caddy
obtains and renews the certificate itself, redirects HTTP to HTTPS, sets
`X-Real-IP` and adds HSTS and other security headers. Its access log
leaves out query strings.
- Caddy proxies to `webserver.bind_ip` and `webserver.port`, limits bodies
to `webserver.body_limit` and answers a larger one with the daemon's
`413` `body_too_large` JSON. Its other errors are logged with their
cause.
- The site is `/etc/caddy/uberbringer.caddy`, imported by the Caddyfile.
The package's default Caddyfile is replaced; an edited Caddyfile only
gains the `import` line and keeps its owner and mode.
The package's default Caddyfile is replaced; an edited Caddyfile gains
the `import` line only if no line imports the site, and keeps its owner
and mode.
- The configuration is validated as the `caddy` user. If Caddy rejects
it, the previous Caddy files are restored and the script stops.
it, the previous Caddy files are restored and the script stops with
Caddy's error.
- `install.sh`, download:
- The download is checked against the release's `checksums.txt` (sha256).
Apart from installing curl and gnupg, nothing on the host changes until
the release is verified.
- `apt-get update` runs before packages are installed, and apt output goes
to `/var/log/uberbringer-install.log`.
to `/var/log/uberbringer-install.log`. dpkg keeps a changed Caddyfile
without asking.
- Caddy's signing key and source list are downloaded before the installed
ones are replaced, so a failed download leaves them as they were.
- `install.sh`, re-runs and validation:
- A re-run upgrades the binary, the unit and Caddy, keeps the config, an
edited Caddyfile and unit drop-ins, rewrites the Caddy site and restarts
the service.
- Domains, ACME email addresses and printer addresses that contain
anything other than the characters such values need are rejected.
- The config is read with the new binary before the service is restarted,
so a config that does not load stops the script and leaves the running
service alone. After the restart, the script waits for the daemon to
answer.
- The domain must be a DNS name with a dot, not an IP address. The printer
address must not carry a port. ACME email addresses and both of these are
limited to the characters such values need.
- 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.
- Go 1.27.4, the latest release, which fixes GO-2026-6859, is the
minimum Go and the one CI, the security scan and releases use. `go.mod`
has no separate toolchain line.
- 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
+9 -8
View File
@@ -64,14 +64,15 @@ 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.
- The `go` line in `go.mod` (1.27.4) names the latest Go release, and there
is no `toolchain` line. That release is the minimum and the build Go: CI
tests, scans and releases with it, and a local Go that is older switches to
it. README § Development says the same.
- Bump the go line to each new Go release, patch releases included, 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. From PowerShell, run `go mod edit -go=…` in Git Bash: PowerShell
splits the flag.
- goreleaser is pinned to the same version in `test.yml` and `release.yml`.
Move both together.
+7 -3
View File
@@ -1,6 +1,9 @@
# syntax=docker/dockerfile:1
FROM golang:1.27-alpine AS build
# go.mod's go line may name a newer patch release than this image has; the go
# command then downloads that release instead of failing.
ENV GOTOOLCHAIN=auto
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
@@ -20,8 +23,9 @@ COPY --from=build /out/uberbringer /usr/local/bin/uberbringer
USER uberbringer
WORKDIR /etc/uberbringer
# Plain HTTP for a reverse proxy in front, which terminates TLS. Mount
# config.toml at /etc/uberbringer/config.toml with bind_ip = "0.0.0.0" and the
# proxy's address in trusted_proxies.
# config.toml at /etc/uberbringer/config.toml, or set UBERBRINGER_CONFIG to ""
# and give the settings as UBERBRINGER_* variables. Either way, bind_ip must be
# 0.0.0.0 and trusted_proxies must hold the proxy's address.
ENV UBERBRINGER_CONFIG=/etc/uberbringer/config.toml
EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/uberbringer"]
CMD ["--config", "/etc/uberbringer/config.toml"]
+105 -38
View File
@@ -54,17 +54,22 @@ it set up. It does not upgrade a host set up by the 0.1 install script, which
used nginx and acme.sh. Ports 80 and 443 must be free for Caddy.
The arguments are the server's domain, the email address for the ACME
certificate account, 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 domain's DNS must point at the server, and ports 80 and
443 must be reachable, for the certificate to be issued.
certificate account, and the printer's address:
- The domain must be a DNS name with at least one dot, such as
`printer.example.com`, made of letters, digits, hyphens and dots; not an IP
address. Its DNS must point at the server, and ports 80 and 443 must be
reachable, for the certificate to be issued.
- The printer address is an IP address or host name without a port; IPv6
addresses may contain colons. A port other than 9100 goes in
`printer.port` in the config.
The script does the following:
- It installs curl and gnupg, then downloads the latest release for the
host's architecture and checks it against the release's `checksums.txt`
(sha256). If the check fails, nothing else is installed. To install a given
release, name its tag:
release, v0.2.0 or later, 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
from the release archive to
@@ -72,21 +77,30 @@ The script does the following:
dedicated `uberbringer` user.
- It writes `/etc/uberbringer/config.toml` (0640, root:uberbringer) with a
fresh secret.
- It reads the config with the new binary (`uberbringer config get`) before
it restarts the service, and stops if the config does not load. After the
restart it waits up to 15 seconds for the daemon to answer, and stops if it
does not.
- It installs [Caddy](https://caddyserver.com) from Caddy's own apt repository
as the HTTPS reverse proxy. Caddy obtains and renews the certificate itself
and redirects HTTP to HTTPS.
as the HTTPS reverse proxy, and stops if that repository can't be read.
Caddy obtains and renews the certificate itself and redirects HTTP to
HTTPS.
- The site is `/etc/caddy/uberbringer.caddy`; `/etc/caddy/Caddyfile`
imports it. The package's default Caddyfile is replaced and kept as
`Caddyfile.default`.
- Caddy passes the client address in `X-Real-IP`, adds HSTS and other
security headers, and logs requests to
`/var/log/caddy/uberbringer-access.log`.
- Caddy proxies to `webserver.bind_ip` and `webserver.port` from the
config, passes the client address in `X-Real-IP`, and adds HSTS and other
security headers.
- Caddy limits request bodies to `webserver.body_limit` from the config
(4 MiB by default). It answers a larger body itself, with the same `413`
`body_too_large` JSON the daemon sends.
`body_too_large` JSON the daemon sends. Its other errors, such as a `502`
while the daemon restarts or is down, have an empty body; Caddy logs
their cause to `journalctl -u caddy`.
- Requests are logged to `/var/log/caddy/uberbringer-access.log`, without
query strings.
- The configuration is validated as the `caddy` user before it is used. If
Caddy rejects it, the previous Caddyfile and site file are put back and
the script stops.
the script stops with Caddy's error.
- 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.
@@ -101,13 +115,15 @@ edits to that file are lost. It keeps:
edit `printer.address` in `/etc/uberbringer/config.toml` instead. The daemon
reads the config only when it starts: after an edit, run
`systemctl restart uberbringer`. After changing `webserver.body_limit`,
re-run the script instead, which copies the new limit into Caddy's site and
restarts the service.
- **Your Caddyfile edits.** Put global options and your other sites in the
Caddyfile. Once you have edited it, a re-run only adds the `import` line if
it is missing (keeping the previous copy as `Caddyfile.bak`), and the file
keeps its owner and mode. Überbringer's own site can't be changed there,
because `uberbringer.caddy` defines it.
`bind_ip` or `port`, re-run the script instead, which copies them into
Caddy's site and restarts the service.
- **Your Caddyfile edits.** Put your other sites in the Caddyfile, and
global options at its top, above every import and site. Once you have
edited it, a re-run adds the `import` line only if no line imports the
site file, by its path or by a glob such as `import /etc/caddy/*.caddy`
(keeping the previous copy as `Caddyfile.bak`). The file keeps its owner
and mode. Überbringer's own site can't be changed there, because
`uberbringer.caddy` defines it.
- **The certificate.** Caddy stores it and renews it before it expires.
- **Tokens.** A re-run creates none. Issue more with
`uberbringer token --config /etc/uberbringer/config.toml --subject <client>`.
@@ -125,21 +141,43 @@ The systemd unit ships as
```sh
docker build -t uberbringer .
docker run -d -p 8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" uberbringer
docker run -d -p 127.0.0.1:8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" uberbringer
```
The image is a microservice for running behind your own reverse proxy. It
contains no proxy and no TLS: it serves plain HTTP on port 8080, and the proxy
terminates HTTPS. In the mounted `config.toml`:
terminates HTTPS. The examples publish the port on the host's loopback
address only, for a proxy on the host; a proxy in another container reaches
it over a shared Docker network instead, with no `-p` at all. In the mounted
`config.toml`:
- Set `bind_ip = "0.0.0.0"` in `[webserver]`.
- Set `trusted_proxies` to your proxy's address or its container network
(e.g. `["172.18.0.0/16"]`), and have the proxy set `X-Real-IP` to the
client's address. Otherwise every request appears to come from the proxy,
and all clients share one rate limit.
- Set `trusted_proxies` to the address the proxy's requests come from: its
container network (e.g. `["172.18.0.0/16"]`), or for a proxy on the host,
the Docker bridge's gateway (usually `172.17.0.1`). Have the proxy set
`X-Real-IP` to the client's address. Otherwise every request appears to
come from the proxy, and all clients share one rate limit.
- Let the proxy pass request bodies up to `webserver.body_limit` (4 MiB by
default).
The settings can come from environment variables instead (see
[Configuration](#configuration)). To run without a config file, set
`UBERBRINGER_CONFIG` empty and put the variables in an env file that only you
can read (`chmod 600 uberbringer.env`), so the secret stays off the command
line:
```text
UBERBRINGER_CONFIG=
UBERBRINGER_WEBSERVER_BIND_IP=0.0.0.0
UBERBRINGER_WEBSERVER_TRUSTED_PROXIES=172.18.0.0/16
UBERBRINGER_API_SECRET=<the output of uberbringer secret>
UBERBRINGER_PRINTER_ADDRESS=192.168.1.245
```
```sh
docker run -d -p 127.0.0.1:8080:8080 --env-file uberbringer.env uberbringer
```
Publish port 8080 only to the proxy, never directly to the internet. For
container health checks, use `GET /` to see whether the daemon is up.
`/healthz` answers `503` while the printer is unreachable, so it suits
@@ -624,7 +662,25 @@ Copy [configs/config.example.toml](configs/config.example.toml) to
required; every other setting has a default, which the example shows. Configs
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.
silently fall back to a default, and so are two keys that differ only in
case. A duration is a string such as `"5s"`; a bare number is refused.
Every key can also be set by an environment variable named
`UBERBRINGER_<SECTION>_<KEY>`, such as `UBERBRINGER_PRINTER_ADDRESS` for
`printer.address`, and a variable wins over the file:
- Values are written without quotes: decimal digits for a number, `true` or
`false` for a flag, `5s` for a duration. Lists take comma-separated values,
e.g. `UBERBRINGER_WEBSERVER_TRUSTED_PROXIES=127.0.0.1,::1`; an empty item,
from a doubled or trailing comma, is an error. In the file, a number, flag
or list may also be written as such a string.
- An empty variable counts as unset, and one that holds only spaces is an
error. Variables that name no key are ignored, but when the configuration
fails to load, the error names them, since they are likely misspelt.
- `--config` names the file, and defaults to `config.toml` or to
`UBERBRINGER_CONFIG` when that is set. `--config ""`, or an empty
`UBERBRINGER_CONFIG`, reads no file, so the settings come from the
environment and the defaults alone.
Settings worth knowing:
@@ -657,9 +713,10 @@ Settings worth knowing:
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for
per-client rate limits comes from the `X-Real-IP` header set by the reverse
proxy (Caddy, as `install.sh` configures it) on `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 and the `Authorization` header are never sent
- `sentry.dsn`: error reporting. When neither the file nor
`UBERBRINGER_SENTRY_DSN` sets it, it falls back to the `SENTRY_DSN`
environment variable, then to a DSN built into release binaries (from the
`SENTRY_DSN` 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:
@@ -683,9 +740,19 @@ uberbringer [--config config.toml] run the daemon (default command)
uberbringer secret print a new random API secret
uberbringer token [--subject s] [--ttl 720h] print a signed bearer token
uberbringer preview [file.json|-] show the lines a job would print
uberbringer config get <key> print one setting, e.g. webserver.port
uberbringer version print the version
```
`config get` prints a setting as the daemon would use it, from the file,
`UBERBRINGER_*` variables and the defaults, and fails when the configuration
does not load. Durations print as `15s`, lists comma-separated. It never
prints `api.secret`.
Every command that reads the config takes `--config` (`-c`); see
[Configuration](#configuration) for its default and for running without a
file.
`preview` reads a job from the file, or from standard input with `-` or no
argument, and lays it out for the printer in the config, as
`/api/v1/preview` does. It prints nothing and fetches no images. On a
@@ -698,16 +765,16 @@ printing is finished, and jobs still waiting are marked failed.
## Development
The Go version is set in `go.mod`:
The Go version is the `go 1.27.4` line in `go.mod`, the latest Go release:
- 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
- It is the minimum for building, and builds with `GOTOOLCHAIN=local` need at
least that. 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`.
- CI tests, scans and releases with exactly that release; the workflows read
it from `go.mod`. There is no separate `toolchain` line.
- To move to a new Go release, change the go line
(`go mod edit -go=1.27.5`). In the same commit, bump the tool modules
golang.org/x/tools, golang.org/x/vuln and honnef.co/go/tools.
```sh
make check # the CI gate, below
@@ -742,7 +809,7 @@ module path is `uberbringer`, so packages import as
cmd/uberbringer/ main: build info, signals, exit code
internal/app/uberbringer/ CLI commands and wiring
server/ Fiber HTTP API, auth, health
internal/pkg/config/ TOML config: defaults and validation
internal/pkg/config/ Config from TOML and UBERBRINGER_* variables (Viper): defaults, validation
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter
internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview
internal/pkg/raster/ Image decoding, scaling and dithering
+8 -2
View File
@@ -1,10 +1,16 @@
# Überbringer configuration.
#
# Copy to config.toml and fill in api.secret and printer.address; everything
# else is optional and shows its default. Durations use Go syntax: "500ms",
# "10s", "1m".
# else is optional and shows its default. Durations are strings in Go
# syntax: "500ms", "10s", "1m".
#
# An environment variable UBERBRINGER_<SECTION>_<KEY> sets any key and wins
# over this file: UBERBRINGER_PRINTER_ADDRESS sets printer.address. Lists take
# comma-separated values.
[webserver]
# install.sh points Caddy at this address and port; re-run it after a
# change.
bind_ip = "127.0.0.1" # use "0.0.0.0" inside Docker
port = 8080
+11
View File
@@ -123,6 +123,14 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
- TypeID (UUIDv7) job and request IDs instead of snowflakes. They sort by
time and need no node configuration.
- An Alpine Docker image.
- **Stack choices (owner, 2026-11-30):**
- Viper instead of BurntSushi/toml for the config, as it goes with Cobra.
Every key can also come from an `UBERBRINGER_<SECTION>_<KEY>` environment
variable, which wins over the file, so a container can run without one.
Unknown keys in the file stay errors; unknown variables are ignored,
because the environment holds much besides Überbringer's settings.
- `go.mod`'s go line is the latest Go release, with no separate toolchain
line.
- **Packaging.** The daemon serves no TLS itself and binds 127.0.0.1 by
default; a reverse proxy in front terminates HTTPS and sets `X-Real-IP`.
- The release tarballs are built for linux amd64, armv6, armv7 and arm64.
@@ -133,6 +141,9 @@ client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (
certificate paths.
- `install.sh` sets up a fresh host, and re-runs upgrade what it set up.
It does not migrate hosts set up by the 0.1 script (owner, 2026-11-30).
It reads the settings Caddy needs through `uberbringer config get`, so
the daemon's own loader checks the config before the service restarts
and no TOML is parsed in shell.
- The Docker image is a microservice with no proxy inside: it runs behind
the operator's own reverse proxy, whose address goes in
`webserver.trusted_proxies`.
+1 -1
View File
@@ -769,7 +769,7 @@ Logs
- Second printer, for the TM-T88VII and TM-m50II:
- a printqueue Pool with one Queue and worker per printer
- [printers.<name>] config decoded through toml.Primitive onto the defaults, with the old [printer] table becoming "default" and strict unknown-key checks kept
- [printers.<name>] config, each table decoded through Viper onto the printer defaults, with the old [printer] table becoming "default" and strict unknown-key checks kept
- ?printer= on print, preview and modules; printer = "name" per subscription; optional priority routes
- /healthz per printer, with the status still following the default printer
- Jobs stay printer-neutral, so nothing in the block or module code changes.
+12 -7
View File
@@ -1,19 +1,16 @@
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
go 1.27.4
require (
github.com/BurntSushi/toml v1.6.0
github.com/getsentry/sentry-go v0.50.0
github.com/go-viper/mapstructure/v2 v2.5.0
github.com/gofiber/fiber/v3 v3.7.0
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/liamg/tml v0.7.1
github.com/pelletier/go-toml/v2 v2.4.3
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
go.jetify.com/typeid v1.3.0
golang.org/x/image v0.48.0
golang.org/x/sync v0.25.0
@@ -21,6 +18,8 @@ require (
)
require (
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/gofiber/schema v1.10.2 // indirect
github.com/gofiber/utils/v2 v2.6.5 // indirect
github.com/gofrs/uuid/v5 v5.5.1 // indirect
@@ -31,10 +30,16 @@ require (
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/molecule-man/go-brrr v1.3.1 // indirect
github.com/philhofer/fwd v1.2.1 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.1.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tinylib/msgp v1.6.5 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.80.0 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/crypto v0.59.0 // indirect
golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 // indirect
golang.org/x/mod v0.43.0 // indirect
+26
View File
@@ -1,12 +1,18 @@
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/fxamacker/cbor/v2 v2.10.0 h1:HVF3T5vYwLqO81ebPirWEPNv2SMrUMD3HLnKgEr6uWE=
github.com/fxamacker/cbor/v2 v2.10.0/go.mod h1:uSwlToFuT9BZAKRxxVm3qQC8DR4tlWl7D6pf20iRYH4=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
github.com/gofiber/schema v1.10.2 h1:mjqtglIvi/+NK3gJTra6wKOaBLZYx+tdNu7xtaCVPOg=
@@ -29,6 +35,10 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs=
github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/liamg/tml v0.7.1 h1:k6lvZhowxUN0S/uAbgSLZ67wZtaTU+stAkpSNy+CbN0=
github.com/liamg/tml v0.7.1/go.mod h1:Vuzs4Dn44Awoyd0MLl2EuJR++l1NlFqU6BJk0oxVYX4=
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
@@ -37,22 +47,38 @@ github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsRe
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu09hF1w=
github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/philhofer/fwd v1.2.1 h1:UtpS73q8bFgy/yH3gCq8LSNvj5gv/FowNOiWZa7uKwQ=
github.com/philhofer/fwd v1.2.1/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/shamaton/msgpack/v3 v3.2.7 h1:YuVYjZq5+NLIREdW52txCmEfVGIi4ithcdhOJhAmU5A=
github.com/shamaton/msgpack/v3 v3.2.7/go.mod h1:sgBYvEiyz8JR1NC3yGRoPVME9xXovpnh3l/plW1nfRo=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/tinylib/msgp v1.6.5 h1:iAH6XTP7BpzErjBZlujJQXxA+GmRi2YWs6M4KdLtNbE=
github.com/tinylib/msgp v1.6.5/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
+126 -57
View File
@@ -5,7 +5,8 @@
#
# Usage: sudo ./install.sh <domain> <acme-email> <printer-address>
#
# Installs the latest release. To install a given release instead, name its tag:
# Installs the latest release. To install a given release, v0.2.0 or later,
# name its tag:
# sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh <domain> <acme-email> <printer-address>
# Re-running the script upgrades the binary, the systemd unit and Caddy,
# rewrites Überbringer's Caddy site and restarts the service. It keeps the
@@ -26,8 +27,6 @@ SERVICE_USER=uberbringer
# /etc/systemd/system take precedence over it, so operator changes belong in
# drop-ins there.
UNIT_FILE=/usr/local/lib/systemd/system/uberbringer.service
# The daemon's default webserver.body_limit, used when the config sets none.
DEFAULT_BODY_LIMIT=4194304
CADDYFILE=/etc/caddy/Caddyfile
CADDY_SITE=/etc/caddy/uberbringer.caddy
CADDY_LOG=/var/log/caddy/uberbringer-access.log
@@ -41,6 +40,9 @@ RELEASE_URL="https://git.anomalous.dev/57_Wolve/uberbringer/releases/download/${
CONFIG_CREATED=0
WORK_DIR=""
# Set by read_settings from the config, as the daemon reads it.
BODY_LIMIT=""
UPSTREAM=""
if [[ "$EUID" -ne 0 ]]; then
echo -e "\e[31m[FATAL]\e[39m This script must be run as root." >&2
@@ -54,17 +56,20 @@ fi
# The domain and the email go unquoted into the Caddy site file, and the
# printer address into a TOML string, so each is limited to the characters
# its kind of value needs.
if [[ ! "$DOMAIN" =~ ^[A-Za-z0-9.-]+$ ]]; then
echo "Invalid domain: $DOMAIN" >&2
# its kind of value needs. The domain must be a DNS name with at least one
# dot that a certificate can be issued for, so not an IP address.
DOMAIN_RE='^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$'
if [[ ! "$DOMAIN" =~ $DOMAIN_RE || "$DOMAIN" =~ ^[0-9.]+$ ]]; then
echo "Invalid domain: $DOMAIN (expected a DNS name such as printer.example.com)" >&2
exit 1
fi
if [[ ! "$ACME_EMAIL" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+$ ]]; then
echo "Invalid email address: $ACME_EMAIL" >&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
# A single colon is a host:port pair; an IPv6 address has at least two.
if [[ ! "$PRINTER_ADDRESS" =~ ^[A-Za-z0-9.:-]+$ || "$PRINTER_ADDRESS" =~ ^[^:]*:[^:]*$ ]]; then
echo "Invalid printer address: $PRINTER_ADDRESS (expected an IP address or host name without a port; a port other than 9100 goes in printer.port in the config)" >&2
exit 1
fi
@@ -115,6 +120,15 @@ detect_arch() {
esac
}
# apt_install installs or upgrades packages without asking anything. Its
# output goes to the log, where a question would go unseen, so dpkg keeps a
# changed configuration file such as the Caddyfile instead of asking, and
# nothing is read from the terminal.
apt_install() {
apt-get install -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold \
"$@" < /dev/null >> "$LOG" 2>&1
}
install_base_packages() {
info "Installing curl and gnupg..."
export DEBIAN_FRONTEND=noninteractive
@@ -122,7 +136,7 @@ install_base_packages() {
# 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 curl gnupg >> "$LOG" 2>&1 || fatal "apt-get install failed; see $LOG."
apt_install curl gnupg || fatal "apt-get install failed; see $LOG."
require curl
require sha256sum
@@ -154,13 +168,15 @@ download_release() {
tar -xf "$WORK_DIR/$archive" -C "$WORK_DIR/release"
[[ -f "$WORK_DIR/release/uberbringer" ]] || fatal "$archive does not contain the uberbringer binary."
[[ -f "$WORK_DIR/release/packaging/uberbringer.service" ]] ||
fatal "$archive does not contain packaging/uberbringer.service."
fatal "$archive does not contain packaging/uberbringer.service; this script installs v0.2.0 or later."
}
install_binary() {
install -m 0755 "$WORK_DIR/release/uberbringer" "$BIN"
local version
# Run from its installed path: WORK_DIR may be on a noexec /tmp.
info "Installed $("$BIN" version)"
version="$("$BIN" version)" || fatal "$BIN does not run on this host."
info "Installed $version"
}
create_service_user() {
@@ -216,57 +232,86 @@ write_initial_token() {
debug "Wrote the first API token to $TOKEN_FILE."
}
# install_service installs the unit and restarts the service, which reads its
# config only at startup.
# config_get prints one setting as the installed binary reads it from the
# config. It fails, with the reason on stderr, when the config does not
# load.
config_get() {
"$BIN" config get --config "$CONFIG" "$1"
}
# read_settings checks the config before the service is restarted, and takes
# from it the body limit and the address Caddy proxies to.
read_settings() {
local bind_ip port
BODY_LIMIT="$(config_get webserver.body_limit)" ||
fatal "$CONFIG does not load (the reason is above). Fix it and rerun; the service was not restarted."
bind_ip="$(config_get webserver.bind_ip)"
port="$(config_get webserver.port)"
case "$bind_ip" in
0.0.0.0) UPSTREAM="127.0.0.1:$port" ;;
::) UPSTREAM="[::1]:$port" ;;
*:*) UPSTREAM="[$bind_ip]:$port" ;;
*) UPSTREAM="$bind_ip:$port" ;;
esac
}
# install_service installs the unit, restarts the service, which reads its
# config only at startup, and waits for it to answer.
install_service() {
install -D -m 0644 "$WORK_DIR/release/packaging/uberbringer.service" "$UNIT_FILE"
systemctl daemon-reload
systemctl enable uberbringer >> "$LOG" 2>&1
systemctl restart uberbringer
systemctl enable uberbringer >> "$LOG" 2>&1 || fatal "Enabling uberbringer.service failed; see $LOG."
systemctl restart uberbringer || fatal "Restarting uberbringer.service failed; see 'journalctl -u uberbringer'."
wait_for_daemon
}
# wait_for_daemon waits up to 15 seconds for the daemon to answer. systemd
# reports the service started as soon as the process runs, before it has
# opened its port or failed.
wait_for_daemon() {
local attempt
for attempt in {1..30}; do
if curl -fs -o /dev/null --max-time 2 "http://$UPSTREAM/"; then
debug "Überbringer answered on $UPSTREAM after $attempt attempts."
return
fi
sleep 0.5
done
fatal "Überbringer did not answer on $UPSTREAM; see 'journalctl -u uberbringer'."
}
# install_caddy installs or upgrades Caddy's Debian package from Caddy's
# signed apt repository, as Caddy's install guide describes.
# signed apt repository. The key and the source list are fetched into
# WORK_DIR first, so a failed download leaves the installed ones as they
# were.
install_caddy() {
info "Installing Caddy from its apt repository..."
# Optional helpers from Caddy's guide; gnupg and curl are what the steps
# below need.
apt-get install -y debian-keyring debian-archive-keyring apt-transport-https >> "$LOG" 2>&1 ||
# Optional keyring helpers; curl and gnupg are what the steps below need.
apt_install debian-keyring debian-archive-keyring apt-transport-https ||
debug "Optional keyring packages are unavailable; continuing."
curl -fsSL --proto '=https' --tlsv1.2 "$CADDY_REPO/gpg.key" |
gpg --dearmor --yes -o "$CADDY_KEYRING" ||
curl -fsSL --proto '=https' --tlsv1.2 -o "$WORK_DIR/caddy.key" "$CADDY_REPO/gpg.key" &&
gpg --dearmor --yes -o "$WORK_DIR/caddy.gpg" "$WORK_DIR/caddy.key" ||
fatal "Couldn't fetch Caddy's signing key."
curl -fsSL --proto '=https' --tlsv1.2 "$CADDY_REPO/debian.deb.txt" > "$CADDY_SOURCES" ||
curl -fsSL --proto '=https' --tlsv1.2 -o "$WORK_DIR/caddy.list" "$CADDY_REPO/debian.deb.txt" ||
fatal "Couldn't fetch Caddy's apt source list."
chmod o+r "$CADDY_KEYRING" "$CADDY_SOURCES"
apt-get update >> "$LOG" 2>&1 || warn "apt-get update failed; trying the install anyway (see $LOG)."
apt-get install -y caddy >> "$LOG" 2>&1 || fatal "Installing Caddy failed; see $LOG."
install -m 0644 "$WORK_DIR/caddy.gpg" "$CADDY_KEYRING"
install -m 0644 "$WORK_DIR/caddy.list" "$CADDY_SOURCES"
# Only Caddy's source is updated, and a failure is fatal: without its
# index, apt would install the distribution's older caddy package.
apt-get update -o Dir::Etc::sourcelist="$CADDY_SOURCES" -o Dir::Etc::sourceparts=- \
-o APT::Get::List-Cleanup=0 >> "$LOG" 2>&1 ||
fatal "Couldn't read Caddy's apt repository; see $LOG."
apt_install caddy || fatal "Installing Caddy failed; see $LOG."
require caddy
}
# body_limit prints webserver.body_limit from the config, so Caddy accepts
# exactly the request bodies the daemon does.
body_limit() {
local limit
limit="$(awk '
/^[ \t]*\[/ { section = $0; gsub(/[][ \t]/, "", section); next }
section == "webserver" && /^[ \t]*body_limit[ \t]*=/ {
sub(/^[^=]*=[ \t]*/, ""); sub(/[ \t#].*$/, ""); print; exit
}' "$CONFIG")"
limit="${limit//_/}"
if [[ "$limit" =~ ^[0-9]+$ ]] && ((limit > 0)); then
echo "$limit"
else
echo "$DEFAULT_BODY_LIMIT"
fi
}
# managed_caddyfile prints the Caddyfile this script writes. Once the
# operator edits it, it no longer matches and is kept.
managed_caddyfile() {
printf '%s\n%s\n%s\n' \
"# Written by Überbringer's install.sh. Your edits are kept: a re-run" \
"# only adds the import below if it is missing." \
printf '%s\n' \
"# Written by Überbringer's install.sh. Your edits are kept: a re-run only" \
"# adds the import below if nothing imports it. Global options go at the" \
"# top, above every import and site." \
"$CADDY_IMPORT"
}
@@ -281,14 +326,24 @@ caddyfile_is_package_default() {
[[ "$current" == "$packaged" ]]
}
# caddyfile_imports_site reports whether a line of the Caddyfile imports the
# site file, by its path or by a glob over /etc/caddy.
caddyfile_imports_site() {
tr -d '\r' < "$CADDYFILE" |
grep -qE '^[[:space:]]*import[[:space:]]+/etc/caddy/(uberbringer\.caddy|\*\.caddy|\*)([[:space:]]|#|$)'
}
# validate_caddy checks the configuration as the caddy user, with its home,
# so the files validation opens or creates are the caddy user's, as they are
# for caddy.service.
# for caddy.service. Caddy's output goes to WORK_DIR and the log.
validate_caddy() {
local home
local home status=0
home="$(getent passwd caddy | cut -d: -f6)"
runuser -u caddy -- env HOME="${home:-/var/lib/caddy}" \
caddy validate --config "$CADDYFILE" --adapter caddyfile >> "$LOG" 2>&1
caddy validate --config "$CADDYFILE" --adapter caddyfile > "$WORK_DIR/caddy-validate.log" 2>&1 ||
status=$?
cat "$WORK_DIR/caddy-validate.log" >> "$LOG"
return "$status"
}
# write_caddy_site writes Überbringer's site file and makes the Caddyfile
@@ -307,8 +362,6 @@ write_caddy_site() {
install -o caddy -g caddy -m 0640 /dev/null "$CADDY_LOG"
fi
local limit
limit="$(body_limit)"
cat <<EOT > "$CADDY_SITE"
# Written by Überbringer's install.sh, which rewrites it on every run.
(uberbringer_headers) {
@@ -326,11 +379,13 @@ $DOMAIN {
request_body {
# webserver.body_limit from $CONFIG, in bytes.
max_size $limit
max_size $BODY_LIMIT
}
reverse_proxy 127.0.0.1:8080 {
# Überbringer trusts X-Real-IP from 127.0.0.1 for per-client rate limits.
# webserver.bind_ip and webserver.port from $CONFIG.
reverse_proxy $UPSTREAM {
# Überbringer takes the client's address from X-Real-IP for
# per-client rate limits.
header_up X-Real-IP {remote_host}
}
@@ -345,8 +400,19 @@ $DOMAIN {
respond \`{"error":"request body is too large","code":"body_too_large"}\` 413
}
# Any other error, such as a 502 while Überbringer restarts, is passed
# on, so Caddy logs its cause.
handle_errors {
error "{err.message}" {err.status_code}
}
log {
output file $CADDY_LOG
# Query strings are dropped: a misdirected client may put a token
# in one.
format filter {
request>uri regexp "[?].*\$" ""
}
}
}
EOT
@@ -362,7 +428,7 @@ EOT
fi
managed_caddyfile > "$CADDYFILE"
chmod 0644 "$CADDYFILE"
elif ! grep -qxF "$CADDY_IMPORT" "$CADDYFILE"; then
elif ! caddyfile_imports_site; then
cp -p "$CADDYFILE" "$CADDYFILE.bak"
printf '\n%s\n' "$CADDY_IMPORT" >> "$CADDYFILE"
info "Added '$CADDY_IMPORT' to your $CADDYFILE (previous copy kept as $CADDYFILE.bak)."
@@ -371,18 +437,20 @@ EOT
if ! validate_caddy; then
if [[ -f "$backup/site" ]]; then cp -p "$backup/site" "$CADDY_SITE"; else rm -f "$CADDY_SITE"; fi
if [[ -f "$backup/Caddyfile" ]]; then cp -p "$backup/Caddyfile" "$CADDYFILE"; else rm -f "$CADDYFILE"; fi
fatal "Caddy rejected the configuration, so $CADDYFILE and $CADDY_SITE were put back as they were (details in $LOG). Überbringer's site must be defined only in $CADDY_SITE."
local reason
reason="$(grep -m1 '^Error:' "$WORK_DIR/caddy-validate.log" || true)"
fatal "Caddy rejected the configuration, so $CADDYFILE and $CADDY_SITE were put back as they were. ${reason:-See $LOG for the error from Caddy.}"
fi
}
start_caddy() {
systemctl enable caddy >> "$LOG" 2>&1
systemctl enable caddy >> "$LOG" 2>&1 || fatal "Enabling caddy.service failed; see $LOG."
if systemctl is-active --quiet caddy; then
systemctl reload caddy || fatal "Reloading Caddy failed; see 'journalctl -u caddy'."
else
systemctl restart caddy || fatal "Caddy did not start; see 'journalctl -u caddy' (ports 80 and 443 must be free)."
fi
info "Caddy is requesting a certificate for $DOMAIN. If https://$DOMAIN does not answer within a minute, see 'journalctl -u caddy': the domain's DNS must point here, and ports 80 and 443 must be reachable."
info "Caddy serves https://$DOMAIN and obtains or renews its certificate itself. If the site does not answer within a minute, see 'journalctl -u caddy': the domain's DNS must point here, and ports 80 and 443 must be reachable."
}
token_notice() {
@@ -412,6 +480,7 @@ main() {
create_service_user
write_config
write_initial_token
read_settings
install_service
install_caddy
+47 -1
View File
@@ -8,6 +8,8 @@ import (
"encoding/base64"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
@@ -47,8 +49,17 @@ func Execute(ctx context.Context, build BuildInfo, args []string) error {
return root.ExecuteContext(ctx)
}
// configPathEnv sets the default of --config. Set but empty, it means no
// config file: the configuration then comes from UBERBRINGER_* variables and
// defaults alone.
const configPathEnv = config.PathEnvVar
func newRootCommand(build BuildInfo) *cobra.Command {
var configPath string
defaultConfigPath := "config.toml"
if path, ok := os.LookupEnv(configPathEnv); ok {
defaultConfigPath = path
}
root := &cobra.Command{
Use: "uberbringer",
Short: "Runs the Überbringer receipt printer daemon.",
@@ -59,16 +70,51 @@ func newRootCommand(build BuildInfo) *cobra.Command {
return serve(cmd.Context(), configPath, build, cmd.OutOrStdout())
},
}
root.PersistentFlags().StringVarP(&configPath, "config", "c", "config.toml", "path to the daemon config file")
root.PersistentFlags().StringVarP(&configPath, "config", "c", defaultConfigPath,
`path to the config file, or "" to read none; `+configPathEnv+` sets the default`)
root.AddCommand(
newVersionCommand(build),
newSecretCommand(),
newTokenCommand(&configPath),
newPreviewCommand(&configPath),
newConfigCommand(&configPath),
)
return root
}
func newConfigCommand(configPath *string) *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Reads the configuration.",
Args: cobra.NoArgs,
}
cmd.AddCommand(&cobra.Command{
Use: "get <key>",
Short: "Prints one setting, e.g. webserver.port, as the daemon would use it.",
Long: "Prints one setting as the daemon would use it: from the config file, " +
"UBERBRINGER_* variables and the defaults, once the whole configuration " +
"is valid. api.secret is never printed.",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
key := args[0]
if strings.EqualFold(key, "api.secret") {
return fmt.Errorf("api.secret is not printed")
}
cfg, err := config.Load(*configPath)
if err != nil {
return err
}
value, err := cfg.Value(key)
if err != nil {
return err
}
_, err = fmt.Fprintln(cmd.OutOrStdout(), value)
return err
},
})
return cmd
}
func newVersionCommand(build BuildInfo) *cobra.Command {
return &cobra.Command{
Use: "version",
+75
View File
@@ -22,6 +22,51 @@ func runCommand(t *testing.T, args ...string) (string, error) {
return out.String(), err
}
func TestConfigPathFromEnvironment(t *testing.T) {
tests := []struct {
name string
value *string
want string
}{
{"unset", nil, "config.toml"},
{"set", ptr("/etc/uberbringer/config.toml"), "/etc/uberbringer/config.toml"},
{"empty means no file", ptr(""), ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.value == nil {
t.Setenv(configPathEnv, "")
os.Unsetenv(configPathEnv)
} else {
t.Setenv(configPathEnv, *tt.value)
}
got := newRootCommand(BuildInfo{}).PersistentFlags().Lookup("config").DefValue
if got != tt.want {
t.Errorf("--config default = %q, want %q", got, tt.want)
}
})
}
}
// The token command reads a config made of environment variables alone when
// --config is empty.
func TestTokenCommandFromEnvironment(t *testing.T) {
secret := "env-only-secret-env-only-secret-0123"
t.Setenv("UBERBRINGER_API_SECRET", secret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "192.168.1.245")
out, err := runCommand(t, "token", "--config", "")
if err != nil {
t.Fatal(err)
}
_, err = jwt.Parse(strings.TrimSpace(out), func(*jwt.Token) (any, error) { return []byte(secret), nil },
jwt.WithValidMethods([]string{"HS256"}))
if err != nil {
t.Errorf("token does not verify with the environment's secret: %v", err)
}
}
func ptr(s string) *string { return &s }
func TestVersionCommand(t *testing.T) {
out, err := runCommand(t, "version")
if err != nil {
@@ -102,3 +147,33 @@ func TestNewRequestID(t *testing.T) {
t.Errorf("request ID %q is not a req_ TypeID", id)
}
}
func TestConfigGetCommand(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
secret := "config-get-secret-config-get-secret-01"
body := "[webserver]\nport = 9090\n[api]\nsecret = \"" + secret + "\"\n[printer]\naddress = \"192.168.1.245\"\n"
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
out, err := runCommand(t, "config", "get", "--config", path, "webserver.port")
if err != nil || out != "9090\n" {
t.Errorf("config get webserver.port = %q, %v; want \"9090\n\"", out, err)
}
out, err = runCommand(t, "config", "get", "--config", path, "webserver.body_limit")
if err != nil || out != "4194304\n" {
t.Errorf("config get webserver.body_limit = %q, %v; want the default", out, err)
}
for _, key := range []string{"api.secret", "API.Secret"} {
out, err = runCommand(t, "config", "get", "--config", path, key)
if err == nil || strings.Contains(out, secret) || strings.Contains(err.Error(), secret) {
t.Errorf("config get %s = %q, %v; want a refusal without the secret", key, out, err)
}
}
if _, err = runCommand(t, "config", "get", "--config", path, "printer.adress"); err == nil {
t.Error("config get accepted an unknown key")
}
if _, err = runCommand(t, "config", "get", "--config", filepath.Join(t.TempDir(), "missing.toml"), "webserver.port"); err == nil {
t.Error("config get succeeded without a config file")
}
}
+370 -62
View File
@@ -1,19 +1,30 @@
// Package config loads and validates the Überbringer daemon configuration
// from a TOML file.
// from a TOML file and UBERBRINGER_* environment variables.
package config
import (
"bytes"
"errors"
"fmt"
"maps"
"net/netip"
"os"
"reflect"
"slices"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/go-viper/mapstructure/v2"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/viper"
)
// EnvPrefix starts the environment variables that set config keys: a key
// section.name is read from UBERBRINGER_SECTION_NAME, e.g.
// UBERBRINGER_PRINTER_ADDRESS. An environment variable wins over the file.
const EnvPrefix = "UBERBRINGER"
// MinSecretLength is the minimum API secret length in bytes. HS256 keys
// shorter than the 256-bit hash output weaken the signature (RFC 7518 §3.2).
const MinSecretLength = 32
@@ -30,126 +41,126 @@ const (
// Config is the root daemon configuration.
type Config struct {
WebServer WebServerConfig `toml:"webserver"`
API APIConfig `toml:"api"`
Printer PrinterConfig `toml:"printer"`
Format FormatConfig `toml:"format"`
Queue QueueConfig `toml:"queue"`
Images ImagesConfig `toml:"images"`
Sentry SentryConfig `toml:"sentry"`
Log LogConfig `toml:"log"`
WebServer WebServerConfig `mapstructure:"webserver"`
API APIConfig `mapstructure:"api"`
Printer PrinterConfig `mapstructure:"printer"`
Format FormatConfig `mapstructure:"format"`
Queue QueueConfig `mapstructure:"queue"`
Images ImagesConfig `mapstructure:"images"`
Sentry SentryConfig `mapstructure:"sentry"`
Log LogConfig `mapstructure:"log"`
}
// WebServerConfig configures the HTTP listener.
type WebServerConfig struct {
BindIP string `toml:"bind_ip"`
Port int `toml:"port"`
BindIP string `mapstructure:"bind_ip"`
Port int `mapstructure:"port"`
// RateLimit is the number of API requests one client may make per
// RateWindow.
RateLimit int `toml:"rate_limit"`
RateWindow time.Duration `toml:"rate_window"`
RateLimit int `mapstructure:"rate_limit"`
RateWindow time.Duration `mapstructure:"rate_window"`
// TrustedProxies lists proxy IPs or CIDR ranges whose ProxyHeader is
// trusted to carry the real client IP.
TrustedProxies []string `toml:"trusted_proxies"`
ProxyHeader string `toml:"proxy_header"`
TrustedProxies []string `mapstructure:"trusted_proxies"`
ProxyHeader string `mapstructure:"proxy_header"`
// BodyLimit is the maximum request body size in bytes.
BodyLimit int `toml:"body_limit"`
BodyLimit int `mapstructure:"body_limit"`
ReadTimeout time.Duration `toml:"read_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
IdleTimeout time.Duration `toml:"idle_timeout"`
ReadTimeout time.Duration `mapstructure:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
}
// APIConfig configures API authentication.
type APIConfig struct {
// Secret is the HS256 key used to verify bearer tokens.
Secret string `toml:"secret"`
Secret string `mapstructure:"secret"`
}
// PrinterConfig configures the network receipt printer.
type PrinterConfig struct {
Address string `toml:"address"`
Port int `toml:"port"`
Address string `mapstructure:"address"`
Port int `mapstructure:"port"`
// Model selects a printer profile, e.g. "tm-t88" or "generic-58mm".
Model string `toml:"model"`
Model string `mapstructure:"model"`
// CodePage is the character table text is transcoded to, e.g. "cp437".
CodePage string `toml:"codepage"`
CodePage string `mapstructure:"codepage"`
// PaperWidth overrides the profile's printable width in dots. Zero keeps
// the profile default.
PaperWidth int `toml:"paper_width"`
PaperWidth int `mapstructure:"paper_width"`
// Columns overrides the number of Font A characters per line used for
// word wrapping. Zero derives it from the paper width.
Columns int `toml:"columns"`
Columns int `mapstructure:"columns"`
// BoxLineSpacing is the line spacing, in motion units (ESC 3), used
// while a box prints, to close the gaps in its vertical borders. Zero
// keeps the printer's default spacing.
BoxLineSpacing int `toml:"box_line_spacing"`
BoxLineSpacing int `mapstructure:"box_line_spacing"`
DialTimeout time.Duration `toml:"dial_timeout"`
WriteTimeout time.Duration `toml:"write_timeout"`
DialTimeout time.Duration `mapstructure:"dial_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
// Retries is how many times a failed send is retried before the job is
// marked failed.
Retries int `toml:"retries"`
RetryDelay time.Duration `toml:"retry_delay"`
Retries int `mapstructure:"retries"`
RetryDelay time.Duration `mapstructure:"retry_delay"`
}
// FormatConfig configures how receipts are laid out.
type FormatConfig struct {
// MaxLines fails a job that would print more lines, all copies
// counted. It is a backstop against runaway text.
MaxLines int `toml:"max_lines"`
MaxLines int `mapstructure:"max_lines"`
}
// QueueConfig configures the print queue.
type QueueConfig struct {
// Size is the number of jobs that may wait to be printed.
Size int `toml:"size"`
Size int `mapstructure:"size"`
// History is the number of finished jobs whose status is kept.
History int `toml:"history"`
History int `mapstructure:"history"`
}
// ImagesConfig configures image elements.
type ImagesConfig struct {
Timeout time.Duration `toml:"timeout"`
MaxBytes int64 `toml:"max_bytes"`
Timeout time.Duration `mapstructure:"timeout"`
MaxBytes int64 `mapstructure:"max_bytes"`
// MaxPixels caps the decoded image size to guard against decompression
// bombs.
MaxPixels int `toml:"max_pixels"`
MaxPixels int `mapstructure:"max_pixels"`
// MaxHeight caps the printed image height in dots after scaling.
MaxHeight int `toml:"max_height"`
MaxHeight int `mapstructure:"max_height"`
// AllowPrivateNetworks permits fetching from loopback, private and
// link-local addresses.
AllowPrivateNetworks bool `toml:"allow_private_networks"`
AllowPrivateNetworks bool `mapstructure:"allow_private_networks"`
// AllowedHosts, when non-empty, restricts fetching to these hosts. Listed
// hosts may resolve to private addresses.
AllowedHosts []string `toml:"allowed_hosts"`
AllowedHosts []string `mapstructure:"allowed_hosts"`
}
// SentryConfig configures error reporting.
type SentryConfig struct {
DSN string `toml:"dsn"`
Environment string `toml:"environment"`
Debug bool `toml:"debug"`
DSN string `mapstructure:"dsn"`
Environment string `mapstructure:"environment"`
Debug bool `mapstructure:"debug"`
}
// LogConfig configures structured logging.
type LogConfig struct {
Level string `toml:"level"`
Format string `toml:"format"`
Level string `mapstructure:"level"`
Format string `mapstructure:"format"`
}
// Default returns a configuration with every optional setting at its
@@ -203,32 +214,329 @@ func Default() Config {
}
}
// Load reads the TOML file at path on top of [Default] and validates the
// result. Keys not recognised by Config are reported as errors so typos do not
// silently fall back to defaults. When sentry.dsn is unset, the SENTRY_DSN
// environment variable is used.
// Load builds the configuration from [Default], the TOML file at path and
// UBERBRINGER_* environment variables, in rising order of precedence, and
// validates the result. An empty path reads no file, for configuration by
// environment alone. Keys in the file that Config does not have are errors,
// so typos do not silently fall back to defaults. When sentry.dsn is unset,
// the SENTRY_DSN environment variable is used.
func Load(path string) (*Config, error) {
cfg := Default()
meta, err := toml.DecodeFile(path, &cfg)
if err != nil {
return nil, fmt.Errorf("reading config %s: %w", path, err)
}
if undecoded := meta.Undecoded(); len(undecoded) > 0 {
keys := make([]string, len(undecoded))
for i, key := range undecoded {
keys[i] = key.String()
v := viper.New()
keys := make(map[string]keyKind)
registerDefaults(v, "", reflect.ValueOf(Default()), keys)
// Each setting is bound to its own variable. Viper's automatic lookup
// would also read a variable named after a section, such as
// UBERBRINGER_PRINTER, and let it hide every setting in that section.
var envSet []string
bound := map[string]bool{PathEnvVar: true}
for _, key := range slices.Sorted(maps.Keys(keys)) {
if keys[key] != setting {
continue
}
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
name := envVar(key)
bound[name] = true
if err := v.BindEnv(key, name); err != nil {
return nil, fmt.Errorf("binding %s: %w", name, err)
}
// Viper treats an empty variable as unset. One that holds only
// spaces is refused: for a list it would clear the file's list.
value := os.Getenv(name)
if value != "" && strings.TrimSpace(value) == "" {
return nil, fmt.Errorf("config: %s holds only spaces; unset it or give it a value", name)
}
if value != "" {
envSet = append(envSet, name)
}
}
if path != "" {
table, err := readFile(path)
if err != nil {
return nil, err
}
unknown, clashes := checkKeys(table, "", "", keys)
if len(clashes) > 0 {
slices.Sort(clashes)
return nil, fmt.Errorf("config %s: keys that differ only in case: %s", path, strings.Join(clashes, "; "))
}
if len(unknown) > 0 {
slices.Sort(unknown)
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(unknown, ", "))
}
if err := v.MergeConfigMap(table); err != nil {
return nil, fmt.Errorf("config %s: %w", path, err)
}
}
// The names of the variables that were set, never their values, so a
// bad value can be traced to the file or the environment.
source := strings.Join(slices.Concat(slices.DeleteFunc([]string{path}, isEmpty), envSet), ", ")
if source == "" {
source = "(no file and no " + EnvPrefix + "_* settings)"
}
var cfg Config
err := v.Unmarshal(&cfg,
viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
durations(),
stringToList(),
refuseFractions(),
stringToNumberOrFlag(),
)),
// Values are taken as written, apart from the strings that hooks
// above parse: environment variables are strings.
func(dc *mapstructure.DecoderConfig) { dc.WeaklyTypedInput = false },
)
if err != nil {
return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound))
}
if cfg.Sentry.DSN == "" {
cfg.Sentry.DSN = os.Getenv("SENTRY_DSN")
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("config %s: %w", path, err)
return nil, fmt.Errorf("config %s: %w%s", source, err, unusedVariables(bound))
}
return &cfg, nil
}
// PathEnvVar names the config file for the command line's --config. Load
// does not read it, but does not count it as a misspelt setting either.
const PathEnvVar = EnvPrefix + "_CONFIG"
// envVar returns the environment variable that sets the dotted config key,
// e.g. UBERBRINGER_PRINTER_ADDRESS for printer.address.
func envVar(key string) string {
return EnvPrefix + "_" + strings.ToUpper(strings.ReplaceAll(key, ".", "_"))
}
// unusedVariables returns a note naming the set UBERBRINGER_* variables
// that match no setting, which are likely misspelt, or "" when there are
// none. Only names are given, never values.
func unusedVariables(bound map[string]bool) string {
var unused []string
for _, entry := range os.Environ() {
name, value, _ := strings.Cut(entry, "=")
if strings.HasPrefix(name, EnvPrefix+"_") && value != "" && !bound[name] {
unused = append(unused, name)
}
}
if len(unused) == 0 {
return ""
}
slices.Sort(unused)
return "\n" + EnvPrefix + "_* variables that set nothing: " + strings.Join(unused, ", ")
}
func isEmpty(s string) bool { return s == "" }
// readFile parses the TOML file at path into a table.
func readFile(path string) (map[string]any, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config %s: %w", path, err)
}
if bytes.HasPrefix(data, []byte("\xff\xfe")) || bytes.HasPrefix(data, []byte("\xfe\xff")) {
return nil, fmt.Errorf("config %s: the file is UTF-16; save it as UTF-8", path)
}
// A byte order mark, which some Windows editors write at the start of a
// UTF-8 file, is not part of the TOML.
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
var table map[string]any
if err := toml.Unmarshal(data, &table); err != nil {
var decodeErr *toml.DecodeError
if errors.As(err, &decodeErr) {
row, col := decodeErr.Position()
return nil, fmt.Errorf("config %s: line %d, column %d: %w", path, row, col, err)
}
return nil, fmt.Errorf("config %s: %w", path, err)
}
return table, nil
}
// keyKind tells a setting from a section that holds settings.
type keyKind int
const (
setting keyKind = iota + 1
section
)
// registerDefaults sets every field of the config struct rv as a Viper
// default under its dotted mapstructure key, and records each key in keys.
func registerDefaults(v *viper.Viper, prefix string, rv reflect.Value, keys map[string]keyKind) {
rt := rv.Type()
for i := range rt.NumField() {
tag := rt.Field(i).Tag.Get("mapstructure")
if tag == "" {
continue
}
key := tag
if prefix != "" {
key = prefix + "." + tag
}
field := rv.Field(i)
if field.Kind() == reflect.Struct {
keys[key] = section
registerDefaults(v, key, field, keys)
continue
}
v.SetDefault(key, field.Interface())
keys[key] = setting
}
}
// checkKeys walks the file's table under prefix. It returns the keys Config
// does not have (unknown names, empty tables included, a setting written as
// a table, a section written as a value, and a quoted name with a dot, which
// is one key rather than a path) and the names in one table that differ only
// in case. Names match case-insensitively, as Viper reads them, and Viper
// would keep only one of two such names. lookup is the lowercase dotted path
// of prefix, which names it as written.
func checkKeys(table map[string]any, prefix, lookup string, keys map[string]keyKind) (unknown, clashes []string) {
names := slices.Sorted(maps.Keys(table))
seen := make(map[string]string, len(names))
for _, name := range names {
path := displayKey(name)
key := strings.ToLower(name)
if prefix != "" {
path = prefix + "." + path
key = lookup + "." + key
}
if other, ok := seen[key]; ok {
clashes = append(clashes, other+" and "+path)
continue
}
seen[key] = path
sub, isTable := table[name].(map[string]any)
kind := keys[key]
if strings.Contains(name, ".") {
kind = 0
}
switch {
case isTable && kind == section:
u, c := checkKeys(sub, path, key, keys)
unknown = append(unknown, u...)
clashes = append(clashes, c...)
case !isTable && kind == setting:
default:
unknown = append(unknown, path)
}
}
return unknown, clashes
}
// displayKey quotes a key name that TOML would need quoted, so that spaces,
// dots and empty names show in messages.
func displayKey(name string) string {
if name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == "" {
return name
}
return strconv.Quote(name)
}
// durations decodes a duration from a string such as "1m30s". A bare number
// is refused, since the decoder would read it as nanoseconds.
func durations() mapstructure.DecodeHookFunc {
durationType := reflect.TypeFor[time.Duration]()
return func(from, to reflect.Type, data any) (any, error) {
if to != durationType || from == durationType {
return data, nil
}
s, ok := data.(string)
if !ok {
return nil, errors.New(`expected a duration as a string, such as "5s"`)
}
d, err := time.ParseDuration(strings.TrimSpace(s))
if err != nil {
return nil, errors.New(`expected a duration such as "5s" or "1m30s"`)
}
return d, nil
}
}
// refuseFractions refuses a number with a fraction for an integer setting,
// which the decoder would otherwise truncate.
func refuseFractions() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.Float32 && from.Kind() != reflect.Float64 {
return data, nil
}
switch to.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return nil, errors.New("expected a whole number")
}
return data, nil
}
}
// stringToNumberOrFlag parses a string, such as an environment variable, for
// a number or flag setting: decimal digits for a number, true or false for a
// flag. Spaces around the value are ignored.
func stringToNumberOrFlag() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.String {
return data, nil
}
s := strings.TrimSpace(data.(string))
switch to.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(s, 10, to.Bits())
if err != nil {
return nil, numberError(err)
}
return reflect.ValueOf(n).Convert(to).Interface(), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(s, 10, to.Bits())
if err != nil {
return nil, numberError(err)
}
return reflect.ValueOf(n).Convert(to).Interface(), nil
case reflect.Bool:
switch s {
case "true":
return true, nil
case "false":
return false, nil
}
return nil, errors.New("expected true or false")
}
return data, nil
}
}
func numberError(err error) error {
if errors.Is(err, strconv.ErrRange) {
return errors.New("number out of range")
}
return errors.New("expected a whole number in decimal digits")
}
// stringToList splits a string, such as an environment variable, into a list
// at commas and trims the spaces around each item, so "a, b" and "a,b" give
// the same list. An empty item, from a doubled or trailing comma, is refused.
func stringToList() mapstructure.DecodeHookFunc {
return func(from, to reflect.Type, data any) (any, error) {
if from.Kind() != reflect.String || to.Kind() != reflect.Slice {
return data, nil
}
raw := strings.TrimSpace(data.(string))
if raw == "" {
return []string{}, nil
}
items := strings.Split(raw, ",")
for i := range items {
items[i] = strings.TrimSpace(items[i])
if items[i] == "" {
return nil, errors.New("a list item is empty; check for a doubled or trailing comma")
}
}
return items, nil
}
}
// Validate reports every problem with the configuration.
func (c *Config) Validate() error {
var errs []error
@@ -255,7 +563,7 @@ func (c *Config) Validate() error {
"api.secret must be at least %d bytes (generate one with `uberbringer secret`)", MinSecretLength)
p := c.Printer
check(p.Address != "", "printer.address is required")
check(strings.TrimSpace(p.Address) != "", "printer.address is required")
check(validPort(p.Port), "printer.port: %d is out of range 1-65535", p.Port)
check(p.PaperWidth >= 0, "printer.paper_width must not be negative")
check(p.Columns >= 0, "printer.columns must not be negative")
+299
View File
@@ -164,6 +164,106 @@ func TestLoadErrors(t *testing.T) {
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[log]\nlevel = \"loud\"\n",
wantErr: "log.level",
},
{
name: "unknown empty table",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[printr]\n",
wantErr: "unknown keys: printr",
},
{
name: "unknown empty subtable",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[printer.extra]\n",
wantErr: "unknown keys: printer.extra",
},
{
name: "unknown empty inline table",
body: "extra = {}\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
wantErr: "unknown keys: extra",
},
{
name: "quoted dotted key",
body: "\"log.level\" = \"debug\"\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
wantErr: `unknown keys: "log.level"`,
},
{
name: "table for a setting",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[printer.port]\nnumber = 9100\n",
wantErr: "unknown keys: printer.port",
},
{
name: "value for a section",
body: "log = \"debug\"\n[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n",
wantErr: "unknown keys: log",
},
{
name: "fraction for an integer",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nretries = 2.9\n",
wantErr: "printer.retries",
},
{
name: "fraction for a duration",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ndial_timeout = 2.5\n",
wantErr: "printer.dial_timeout",
},
{
name: "number for a string",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nmodel = 88\n",
wantErr: "printer.model",
},
{
name: "empty string for an integer",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nretries = \"\"\n",
wantErr: "printer.retries",
},
{
name: "number for a flag",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[images]\nallow_private_networks = 1\n",
wantErr: "images.allow_private_networks",
},
{
name: "syntax error names its line",
body: "[printer]\naddress = \"p\n\"\n",
wantErr: "line 2",
},
{
name: "tables that differ only in case",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[Printer]\nport = 9101\n",
wantErr: "keys that differ only in case: Printer and printer",
},
{
name: "settings that differ only in case",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nport = 1000\nPORT = 2000\n",
wantErr: "keys that differ only in case: printer.PORT and printer.port",
},
{
name: "bare number for a duration",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\ndial_timeout = 5\n",
wantErr: `'printer.dial_timeout' expected a duration as a string`,
},
{
name: "number string in another base",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nretries = \"0x10\"\n",
wantErr: "'printer.retries' expected a whole number in decimal digits",
},
{
name: "flag string other than true or false",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[sentry]\ndebug = \"1\"\n",
wantErr: "'sentry.debug' expected true or false",
},
{
name: "key with a space is quoted",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n\"retry delay\" = \"1s\"\n",
wantErr: `unknown keys: printer."retry delay"`,
},
{
name: "blank printer address",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \" \"\n",
wantErr: "printer.address is required",
},
{
name: "UTF-16 file",
body: "\xff\xfe[\x00a\x00p\x00i\x00]\x00",
wantErr: "the file is UTF-16; save it as UTF-8",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -194,9 +294,208 @@ func TestExampleConfigLoads(t *testing.T) {
}
}
func TestLoadEnvironmentOverridesFile(t *testing.T) {
path := writeConfig(t, `
[api]
secret = "`+validSecret+`"
[printer]
address = "file.lan"
retries = 2
`)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "env.lan")
t.Setenv("UBERBRINGER_PRINTER_DIAL_TIMEOUT", "2s")
t.Setenv("UBERBRINGER_WEBSERVER_PORT", "9090")
t.Setenv("UBERBRINGER_IMAGES_ALLOW_PRIVATE_NETWORKS", "true")
t.Setenv("UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1, 172.18.0.0/16")
t.Setenv("UBERBRINGER_NOT_A_KEY", "ignored")
t.Setenv("UBERBRINGER_PRINTER_RETRIES", "")
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Address != "env.lan" {
t.Errorf("Address = %q, want the environment's value", cfg.Printer.Address)
}
if cfg.Printer.Retries != 2 {
t.Errorf("Retries = %d, want the file's value, since an empty variable counts as unset", cfg.Printer.Retries)
}
if cfg.Printer.DialTimeout != 2*time.Second || cfg.WebServer.Port != 9090 || !cfg.Images.AllowPrivateNetworks {
t.Errorf("typed environment values not applied: %+v %+v %+v", cfg.Printer, cfg.WebServer, cfg.Images)
}
if got := strings.Join(cfg.WebServer.TrustedProxies, "|"); got != "10.0.0.1|172.18.0.0/16" {
t.Errorf("TrustedProxies = %q, want two trimmed items", got)
}
}
// A variable named after a section rather than a setting changes nothing.
func TestLoadIgnoresSectionNamedVariables(t *testing.T) {
path := writeConfig(t, `
[api]
secret = "`+validSecret+`"
[printer]
address = "file.lan"
[sentry]
environment = "staging"
`)
t.Setenv("UBERBRINGER_PRINTER", "kitchen")
t.Setenv("UBERBRINGER_SENTRY", "x")
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Address != "file.lan" || cfg.Printer.Port != 9100 {
t.Errorf("printer = %+v, want the file's address and the default port", cfg.Printer)
}
if cfg.Sentry.Environment != "staging" {
t.Errorf("sentry.environment = %q, want the file's value", cfg.Sentry.Environment)
}
}
// Some Windows editors start a UTF-8 file with a byte order mark.
func TestLoadFileWithByteOrderMark(t *testing.T) {
path := writeConfig(t, "\xef\xbb\xbf[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"bom.lan\"\n")
cfg, err := config.Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Address != "bom.lan" {
t.Errorf("Address = %q", cfg.Printer.Address)
}
}
// An error from a value that may have come from the environment names the
// variables that were set, and never their values.
func TestLoadErrorNamesVariables(t *testing.T) {
path := writeConfig(t, "[api]\nsecret = \""+validSecret+"\"\n[printer]\naddress = \"p\"\n")
t.Setenv("UBERBRINGER_PRINTER_RETRY_DELAY", "soon")
_, err := config.Load(path)
if err == nil {
t.Fatal("Load accepted a bad retry_delay")
}
if msg := err.Error(); !strings.Contains(msg, path) || !strings.Contains(msg, "UBERBRINGER_PRINTER_RETRY_DELAY") {
t.Errorf("error = %q, want it to name the file and the variable", msg)
}
t.Setenv("UBERBRINGER_API_SECRET", "short-env-secret")
_, err = config.Load(path)
if err == nil || strings.Contains(err.Error(), "short-env-secret") {
t.Errorf("error = %v, want a failure that does not contain the secret", err)
}
}
func TestLoadEnvironmentOnly(t *testing.T) {
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "192.168.1.245")
t.Setenv("UBERBRINGER_WEBSERVER_BIND_IP", "0.0.0.0")
cfg, err := config.Load("")
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Address != "192.168.1.245" || cfg.WebServer.BindIP != "0.0.0.0" || cfg.API.Secret != validSecret {
t.Errorf("environment not applied: %+v %+v", cfg.Printer, cfg.WebServer)
}
if def := config.Default(); cfg.Queue.Size != def.Queue.Size || cfg.Printer.Model != def.Printer.Model {
t.Error("defaults not applied without a file")
}
}
// A failed load names the UBERBRINGER_* variables that set nothing, which
// are likely misspelt, but not their values or UBERBRINGER_CONFIG.
func TestLoadErrorNamesMisspeltVariables(t *testing.T) {
t.Setenv("UBERBRINGER_API_SECRETS", validSecret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
t.Setenv(config.PathEnvVar, "unused.toml")
_, err := config.Load("")
if err == nil {
t.Fatal("Load accepted a config without api.secret")
}
msg := err.Error()
if !strings.Contains(msg, "variables that set nothing: UBERBRINGER_API_SECRETS") {
t.Errorf("error = %q, want it to name UBERBRINGER_API_SECRETS", msg)
}
if strings.Contains(msg, validSecret) || strings.Contains(msg, config.PathEnvVar) {
t.Errorf("error = %q, want no values and no %s", msg, config.PathEnvVar)
}
}
// Strings for numbers are read as decimal, with spaces around them ignored.
func TestLoadEnvironmentNumbersAreDecimal(t *testing.T) {
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
t.Setenv("UBERBRINGER_QUEUE_SIZE", "010")
t.Setenv("UBERBRINGER_WEBSERVER_PORT", " 9090 ")
cfg, err := config.Load("")
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Queue.Size != 10 || cfg.WebServer.Port != 9090 {
t.Errorf("queue.size = %d, webserver.port = %d; want 10 and 9090", cfg.Queue.Size, cfg.WebServer.Port)
}
}
func TestLoadEnvironmentErrors(t *testing.T) {
tests := []struct {
name, key, value, wantErr string
}{
{"not a number", "UBERBRINGER_WEBSERVER_PORT", "eighty", "port"},
{"bad duration", "UBERBRINGER_PRINTER_RETRY_DELAY", "soon", "retry_delay"},
{"bare number for a duration", "UBERBRINGER_PRINTER_RETRY_DELAY", "5", "retry_delay"},
{"fails validation", "UBERBRINGER_LOG_LEVEL", "loud", "log.level"},
{"only spaces", "UBERBRINGER_IMAGES_ALLOWED_HOSTS", " ", "UBERBRINGER_IMAGES_ALLOWED_HOSTS holds only spaces"},
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("UBERBRINGER_API_SECRET", validSecret)
t.Setenv("UBERBRINGER_PRINTER_ADDRESS", "p")
t.Setenv(tt.key, tt.value)
_, err := config.Load("")
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Load error = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
func TestLoadMissingFile(t *testing.T) {
_, err := config.Load(filepath.Join(t.TempDir(), "nope.toml"))
if err == nil {
t.Fatal("expected error for missing file")
}
}
func TestValue(t *testing.T) {
cfg := config.Default()
cfg.Images.AllowedHosts = []string{"a.lan", "b.lan"}
tests := []struct {
key, want, wantErr string
}{
{key: "webserver.port", want: "8080"},
{key: "WebServer.Body_Limit", want: "4194304"},
{key: "printer.dial_timeout", want: "5s"},
{key: "webserver.trusted_proxies", want: "127.0.0.1,::1"},
{key: "images.allowed_hosts", want: "a.lan,b.lan"},
{key: "images.allow_private_networks", want: "false"},
{key: "printer", wantErr: `"printer" is a section`},
{key: "printer.adress", wantErr: `unknown key "printer.adress"`},
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
}
for _, tt := range tests {
t.Run(tt.key, func(t *testing.T) {
got, err := cfg.Value(tt.key)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("Value error = %v, want it to contain %q", err, tt.wantErr)
}
return
}
if err != nil || got != tt.want {
t.Errorf("Value = %q, %v; want %q", got, err, tt.want)
}
})
}
}
+48
View File
@@ -0,0 +1,48 @@
package config
import (
"fmt"
"reflect"
"strings"
"time"
)
// Value returns the setting at the dotted key, such as "webserver.port", in
// the form a config file or an environment variable gives it: durations such
// as "15s", lists comma-separated. Key names match case-insensitively.
func (c *Config) Value(key string) (string, error) {
v := reflect.ValueOf(*c)
for part := range strings.SplitSeq(key, ".") {
field, ok := fieldByKey(v, part)
if !ok {
return "", fmt.Errorf("unknown key %q", key)
}
v = field
}
if v.Kind() == reflect.Struct {
return "", fmt.Errorf("%q is a section; name one of its settings", key)
}
switch value := v.Interface().(type) {
case time.Duration:
return value.String(), nil
case []string:
return strings.Join(value, ","), nil
default:
return fmt.Sprint(value), nil
}
}
// fieldByKey returns the field of the struct v whose mapstructure tag is
// name.
func fieldByKey(v reflect.Value, name string) (reflect.Value, bool) {
if v.Kind() != reflect.Struct {
return reflect.Value{}, false
}
t := v.Type()
for i := range t.NumField() {
if tag := t.Field(i).Tag.Get("mapstructure"); tag != "" && tag == strings.ToLower(name) {
return v.Field(i), true
}
}
return reflect.Value{}, false
}