diff --git a/CHANGELOG.md b/CHANGELOG.md index 80d9685..37cbc6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,8 @@ upgrade a 0.1 install. - 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. +- `install.sh` sets up Caddy instead of nginx and acme.sh, on a fresh host. It + does not upgrade a host set up by the 0.1 script. See README § Quick start. - `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 @@ -178,7 +180,8 @@ upgrade a 0.1 install. - 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 + the reverse proxy, 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 @@ -194,21 +197,29 @@ upgrade a 0.1 install. 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. +- `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. + - 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 configuration is validated as the `caddy` user. If Caddy rejects + it, the previous Caddy files are restored and the script stops. +- `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`. - `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. + - 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. - Go: - The minimum is Go 1.26. - The toolchain is pinned in `go.mod` as `toolchain go1.27.4`, which fixes @@ -258,12 +269,10 @@ upgrade a 0.1 install. 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`. +- The 0.1 install script left `/etc/uberbringer/config.toml`, API secret + included, readable by every user (mode 0644 under the usual umask). Its unit + runs the daemon as root, so on such a host run + `chmod 0600 /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. diff --git a/CLAUDE.md b/CLAUDE.md index ccae7d2..a606ab6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ 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 +`install.sh` installs behind Caddy, and as the Alpine image built from the root `Dockerfile`. ## Read first diff --git a/Dockerfile b/Dockerfile index 4368b4a..1bea376 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,7 +19,9 @@ RUN apk add --no-cache ca-certificates tzdata \ COPY --from=build /out/uberbringer /usr/local/bin/uberbringer USER uberbringer WORKDIR /etc/uberbringer -# Mount config.toml at /etc/uberbringer/config.toml with bind_ip = "0.0.0.0". +# 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. EXPOSE 8080 ENTRYPOINT ["/usr/local/bin/uberbringer"] CMD ["--config", "/etc/uberbringer/config.toml"] diff --git a/README.md b/README.md index 9ddc565..ae523b6 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,13 @@ REST API and prints them on an EPSON ESC/POS network receipt printer. - **Health endpoint** with live printer status: paper low or out, cover open, errors. +> [!NOTE] +> **Pre-refactor code: no AI was used.** The original Überbringer (v0.1.x), +> up to commit +> [`bb73348`](https://git.anomalous.dev/57_Wolve/uberbringer/src/commit/bb73348433de1604c839de5fb8f8b2793e0e9518) +> from January 2025, was written without any AI. That commit shows the +> code as it was before the 0.2 refactor. + ## Contents - [Quick start](#quick-start) @@ -36,45 +43,72 @@ REST API and prints them on an EPSON ESC/POS network receipt printer. ## Quick start -### Debian/Ubuntu server with nginx and TLS +### Debian/Ubuntu server with Caddy and TLS ```sh sudo ./install.sh printer.example.com you@example.com 192.168.1.245 ``` -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 sets up a fresh Debian or Ubuntu host, and re-runs upgrade what +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. 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: +- 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: `sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh `. - 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. + from the release archive to + `/usr/local/lib/systemd/system/uberbringer.service`. 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 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. + - 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 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. + - 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. - 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: +Running the script again upgrades the binary, the unit and Caddy, and +restarts the service. It rewrites `/etc/caddy/uberbringer.caddy`, so local +edits to that file 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//` is missing or empty. + 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. +- **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 `. @@ -86,13 +120,6 @@ The systemd unit ships as - **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 @@ -101,7 +128,22 @@ docker build -t uberbringer . docker run -d -p 8080:8080 -v "$PWD/config.toml:/etc/uberbringer/config.toml:ro" uberbringer ``` -Inside a container, set `bind_ip = "0.0.0.0"` in the `[webserver]` section. +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`: + +- 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. +- Let the proxy pass request bodies up to `webserver.body_limit` (4 MiB by + default). + +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 +alerting better than restarting the container. ### From source @@ -560,7 +602,7 @@ 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. +These changes also affect 0.1 clients and configs. [CHANGELOG.md](CHANGELOG.md) lists every change. - Tokens are read only from the `Authorization` header. A `?token=` query @@ -569,26 +611,11 @@ These changes also affect 0.1 clients and installs. 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`. +- A 0.1 config needs a `[printer]` section with `address` before 0.2 + starts, because `printer.address` is now required. The 0.1 install script + did not write one. +- `install.sh` sets up a fresh host. It does not upgrade a server set up by + the 0.1 install script. ## Configuration @@ -628,8 +655,8 @@ Settings worth knowing: all copies counted, fails instead of printing. It is a backstop against runaway text; `/api/v1/preview` answers such a job with `422`. - `webserver.trusted_proxies` / `proxy_header`: the real client IP for - per-client rate limits comes from the `X-Real-IP` header set by nginx on - `127.0.0.1`. + 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 diff --git a/configs/config.example.toml b/configs/config.example.toml index 74a9374..3d282c3 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -13,11 +13,15 @@ rate_window = "1m" # Reverse proxies allowed to report the real client IP in proxy_header. - # install.sh configures nginx to set X-Real-IP. + # install.sh configures Caddy to set X-Real-IP. In Docker, list your + # proxy's address or its container network, e.g. ["172.18.0.0/16"]. trusted_proxies = ["127.0.0.1", "::1"] proxy_header = "X-Real-IP" - body_limit = 4194304 # bytes (4 MiB); raise it for large base64 images + # Bytes (4 MiB); raise it for large base64 images. After a change, re-run + # install.sh, which copies it into Caddy's limit and restarts the daemon; + # behind another proxy, raise that proxy's limit too. + body_limit = 4194304 read_timeout = "15s" write_timeout = "15s" idle_timeout = "60s" diff --git a/docs/design.md b/docs/design.md index a5aa01d..32f5770 100644 --- a/docs/design.md +++ b/docs/design.md @@ -8,12 +8,12 @@ daemon is shaped as it is. README.md describes how to use it. 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. +same endpoint, `POST /api/v1/print` behind a TLS reverse proxy, 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) +client ─HTTPS─▶ Caddy ─▶ server ── validate ──▶ printqueue (memory, 1 worker) │ │ receipt.Render: whole job │ │ to bytes, images via safehttp │ ▼ @@ -123,10 +123,19 @@ client ─HTTPS─▶ nginx ─▶ 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. -- **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. +- **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. + `install.sh` sets up Caddy as that proxy (TLS with automatic + certificates, `X-Real-IP`) and the sandboxed unit from `packaging/`. + Caddy replaced nginx and acme.sh because it issues and renews + certificates itself, so the installer needs no webroot, cron job or + 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). + - 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`. ## Planned: formatters @@ -149,8 +158,20 @@ and the preview, is built. Decided so far (owner, 2026-11-29): 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. +- **A persistent job store and print previews** (requested by the owner on + 2026-11-30; to be planned in full in `docs/plans/` before any of it is + built): + - Jobs stored with GORM on SQLite, so queued jobs, statuses and history + survive a restart. Release builds use `CGO_ENABLED=0`, so the SQLite + driver must be pure Go (for example `github.com/glebarez/sqlite`), and the + systemd unit needs a `StateDirectory` because its file system is + read-only. The plan must also say how to tell which receipts printed + before a crash, so a restart never prints a receipt twice. + - A print preview as an image: a digital test print of a job that shows + what the paper would look like, without printing. Formatters phase 1 adds + a text preview (`POST /api/v1/preview`); this goes further, rendering + text, boxes, barcodes, QR codes and images to a picture. + - Previews of submitted jobs, read back from the store by job ID. - **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. diff --git a/install.sh b/install.sh index 52353e0..bc25eba 100755 --- a/install.sh +++ b/install.sh @@ -1,12 +1,15 @@ #!/bin/bash -# Installs Überbringer behind nginx with a Let's Encrypt certificate. +# Installs Überbringer on a fresh Debian or Ubuntu host, behind Caddy, which +# obtains and renews the TLS certificate itself. Ports 80 and 443 must be +# free for Caddy. # # Usage: sudo ./install.sh # # Installs the latest release. To install a given release instead, name its tag: # sudo UBERBRINGER_VERSION=v0.2.0 ./install.sh -# Re-running the script upgrades the binary and the systemd unit, and keeps the -# config, the certificate and any `systemctl edit uberbringer` drop-ins. +# Re-running the script upgrades the binary, the systemd unit and Caddy, +# rewrites Überbringer's Caddy site and restarts the service. It keeps the +# config, an edited Caddyfile and any `systemctl edit uberbringer` drop-ins. set -euo pipefail DOMAIN="${1:-}" @@ -22,26 +25,22 @@ SERVICE_USER=uberbringer # 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" +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 +CADDY_IMPORT="import $CADDY_SITE" +CADDY_KEYRING=/usr/share/keyrings/caddy-stable-archive-keyring.gpg +CADDY_SOURCES=/etc/apt/sources.list.d/caddy-stable.list +CADDY_REPO=https://dl.cloudsmith.io/public/caddy/stable # 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." >&2 @@ -53,13 +52,17 @@ if [[ -z "$DOMAIN" || -z "$ACME_EMAIL" || -z "$PRINTER_ADDRESS" ]]; then 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. +# 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 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 exit 1 @@ -112,31 +115,19 @@ detect_arch() { esac } -# 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..." +install_base_packages() { + info "Installing curl and gnupg..." 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." + apt-get install -y curl gnupg >> "$LOG" 2>&1 || fatal "apt-get install failed; see $LOG." - require nginx require curl - require socat require sha256sum require systemctl + require runuser } # download_release fetches the release archive and checksums.txt into @@ -162,10 +153,12 @@ download_release() { 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." + [[ -f "$WORK_DIR/release/packaging/uberbringer.service" ]] || + fatal "$archive does not contain packaging/uberbringer.service." } install_binary() { - install_if_changed "$WORK_DIR/release/uberbringer" 0755 "$BIN" + install -m 0755 "$WORK_DIR/release/uberbringer" "$BIN" # Run from its installed path: WORK_DIR may be on a noexec /tmp. info "Installed $("$BIN" version)" } @@ -205,157 +198,6 @@ EOT 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() { - debug "Installing the systemd unit from $UNIT_SRC..." - - # 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 - - mkdir -p "$UNIT_DIR" - install_if_changed "$UNIT_SRC" 0644 "$UNIT_FILE" - - systemctl daemon-reload - 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() { - info "Configuring nginx..." - mkdir -p /etc/nginx/includes "/var/www/$DOMAIN" - - cat < /etc/nginx/includes/letsencrypt-webroot -location / { - alias /var/www/$DOMAIN/; -} -EOT - - rm -f /etc/nginx/sites-enabled/default /etc/nginx/sites-available/default - - cat < /etc/nginx/sites-available/default.conf -server { - listen 80; - listen [::]:80; - server_name $DOMAIN; - - include includes/letsencrypt-webroot; -} -EOT - - ln -sf /etc/nginx/sites-available/default.conf /etc/nginx/sites-enabled/default.conf - systemctl enable nginx >> "$LOG" 2>&1 - debug "Starting Nginx..." - systemctl restart nginx -} - -# 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 - - 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..." - 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 - - 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 < /etc/nginx/sites-available/reverse-proxy.conf -server { - listen 443 ssl; - listen [::]:443 ssl; - server_name $DOMAIN; - - 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; - - error_log /var/log/nginx/uberbringer_error.log; - access_log /var/log/nginx/uberbringer_access.log; - - client_max_body_size 4m; - - location / { - proxy_redirect off; - proxy_set_header Host \$http_host; - # Uberbringer trusts X-Real-IP from 127.0.0.1 for per-client rate limits. - proxy_set_header X-Real-IP \$remote_addr; - proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto \$scheme; - - proxy_pass http://127.0.0.1:8080; - proxy_read_timeout 90; - - add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; - add_header X-Frame-Options DENY always; - add_header X-Content-Type-Options nosniff always; - add_header Referrer-Policy "no-referrer" always; - } -} -EOT - - ln -sf /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf - nginx -t - debug "Reloading Nginx..." - systemctl reload nginx } # write_initial_token saves the first bearer token to a root-only file instead @@ -374,6 +216,175 @@ 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. +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 +} + +# install_caddy installs or upgrades Caddy's Debian package from Caddy's +# signed apt repository, as Caddy's install guide describes. +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 || + debug "Optional keyring packages are unavailable; continuing." + curl -fsSL --proto '=https' --tlsv1.2 "$CADDY_REPO/gpg.key" | + gpg --dearmor --yes -o "$CADDY_KEYRING" || + fatal "Couldn't fetch Caddy's signing key." + curl -fsSL --proto '=https' --tlsv1.2 "$CADDY_REPO/debian.deb.txt" > "$CADDY_SOURCES" || + 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." + 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." \ + "$CADDY_IMPORT" +} + +# caddyfile_is_package_default reports whether the Caddyfile is the caddy +# package's file, unchanged, by the checksum dpkg recorded for it. +caddyfile_is_package_default() { + local packaged current + packaged="$(dpkg-query -W -f='${Conffiles}\n' caddy 2> /dev/null | + awk -v f="$CADDYFILE" '$1 == f { print $2; exit }' || true)" + [[ -n "$packaged" ]] || return 1 + current="$(md5sum "$CADDYFILE" | awk '{ print $1 }')" + [[ "$current" == "$packaged" ]] +} + +# 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. +validate_caddy() { + local home + 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 +} + +# write_caddy_site writes Überbringer's site file and makes the Caddyfile +# import it, then validates the result. If Caddy rejects it, both files are +# put back as they were. +write_caddy_site() { + info "Configuring Caddy for $DOMAIN..." + local backup="$WORK_DIR/caddy-backup" + mkdir -p "$backup" + if [[ -f "$CADDY_SITE" ]]; then cp -p "$CADDY_SITE" "$backup/site"; fi + if [[ -f "$CADDYFILE" ]]; then cp -p "$CADDYFILE" "$backup/Caddyfile"; fi + + install -d -o caddy -g caddy /var/log/caddy + # Created as the caddy user's file before anything opens it. + if [[ ! -e "$CADDY_LOG" ]]; then + install -o caddy -g caddy -m 0640 /dev/null "$CADDY_LOG" + fi + + local limit + limit="$(body_limit)" + cat < "$CADDY_SITE" +# Written by Überbringer's install.sh, which rewrites it on every run. +(uberbringer_headers) { + header { + Strict-Transport-Security "max-age=31536000; includeSubDomains" + X-Frame-Options DENY + X-Content-Type-Options nosniff + Referrer-Policy no-referrer + -Server + } +} + +$DOMAIN { + tls $ACME_EMAIL + + request_body { + # webserver.body_limit from $CONFIG, in bytes. + max_size $limit + } + + reverse_proxy 127.0.0.1:8080 { + # Überbringer trusts X-Real-IP from 127.0.0.1 for per-client rate limits. + header_up X-Real-IP {remote_host} + } + + import uberbringer_headers + + # Caddy refuses a body over max_size before Überbringer sees it, so the + # refusal is the JSON error Überbringer would have sent. + handle_errors 413 { + import uberbringer_headers + header Content-Type application/json + header Cache-Control no-store + respond \`{"error":"request body is too large","code":"body_too_large"}\` 413 + } + + log { + output file $CADDY_LOG + } +} +EOT + chmod 0644 "$CADDY_SITE" + + # A missing Caddyfile, the package's untouched one and the one this + # script wrote are replaced. An edited Caddyfile only gains the import + # line, and keeps its owner and mode. + if [[ ! -f "$CADDYFILE" ]] || cmp -s "$CADDYFILE" <(managed_caddyfile) || caddyfile_is_package_default; then + if [[ -f "$CADDYFILE" ]] && ! cmp -s "$CADDYFILE" <(managed_caddyfile); then + cp -p "$CADDYFILE" "$CADDYFILE.default" + info "Replacing the package's default Caddyfile (kept as $CADDYFILE.default)..." + fi + managed_caddyfile > "$CADDYFILE" + chmod 0644 "$CADDYFILE" + elif ! grep -qxF "$CADDY_IMPORT" "$CADDYFILE"; 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)." + fi + + 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." + fi +} + +start_caddy() { + systemctl enable caddy >> "$LOG" 2>&1 + 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." +} + 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." @@ -388,23 +399,24 @@ token_notice() { main() { info "Script loaded, starting the install process..." - install_packages + install_base_packages WORK_DIR="$(mktemp -d)" trap cleanup EXIT + # Nothing else is installed unless the release downloads and matches its + # checksum. 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 - issue_certificate - install_reverse_proxy + + install_caddy + write_caddy_site + start_caddy info "Uberbringer service is now installed." info "Override unit settings with 'systemctl edit uberbringer'; drop-ins survive re-runs of this script."