Add Caddy beside nginx as the replacement edge
Test and deploy / test (push) Successful in 1m32s
Test and deploy / deploy (push) Successful in 29m5s

caddy/ reproduces nginx's routes, gates, /notes/ privacy denials, uploads
(bucket first, then disk), rate limits, real-IP and headers in one shared
route table, with certificates obtained over DNS-01 in-process instead of by
certbot. Until the cutover it serves nothing public: loopback-only ports
8880/8443, no network aliases, its own address. The image build validates
the prod and dev configs, so a broken Caddyfile stops the deploy before any
container is replaced (`make check-caddy` is the same build).

caddy/edge_test.sh checks the privacy boundary and the gates and prints
everything else for diffing nginx against Caddy before switching over.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-17 22:45:35 +00:00
co-authored by Claude Opus 5.5
parent 89aaf8d79e
commit e09b90afaa
14 changed files with 1464 additions and 8 deletions
+9 -5
View File
@@ -187,7 +187,8 @@ LIQUIDSOAP_HARBOR_PORT=8001
# --- TLS / identity ---------------------------------------------------------- # --- TLS / identity ----------------------------------------------------------
# DOMAIN is the APEX domain with no scheme and no www; certbot requests both # DOMAIN is the APEX domain with no scheme and no www; certbot requests both
# it and www.DOMAIN on one certificate, and nginx canonicalises to www. # it and www.DOMAIN on one certificate, and nginx canonicalises to www.
# EMAIL is the Let's Encrypt account address for expiry notices. # EMAIL is the Let's Encrypt account address for certbot. Caddy registers
# its ACME account without one (Let's Encrypt no longer sends expiry notices).
DOMAIN= DOMAIN=
EMAIL= EMAIL=
@@ -198,10 +199,13 @@ EMAIL=
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves # dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
# the container restarting with an error and the site reachable directly. # the container restarting with an error and the site reachable directly.
CLOUDFLARE_TUNNEL_TOKEN= CLOUDFLARE_TUNNEL_TOKEN=
# Cloudflare API token for certbot's DNS-01 challenge (My Profile -> API # Cloudflare API token for the DNS-01 challenge (My Profile -> API Tokens ->
# Tokens -> Create Token -> "Edit zone DNS", limited to this zone). Set, the # Create Token -> "Edit zone DNS", limited to this zone). Set, the certificate
# certificate renews without any inbound port, so the router's 80/443 # renews without any inbound port, so the router's 80/443 forwards can close.
# forwards can close. Blank falls back to HTTP-01 on port 80. # certbot: blank falls back to HTTP-01 on port 80.
# Caddy (caddy/sites/prod.caddy) has no fallback and also needs Zone -> Zone
# -> Read on the same zone, so add that permission to the token. Changing it
# needs `docker compose up -d caddy`.
CLOUDFLARE_DNS_API_TOKEN= CLOUDFLARE_DNS_API_TOKEN=
# --- Third-party API keys (backend) ------------------------------------------ # --- Third-party API keys (backend) ------------------------------------------
+2
View File
@@ -3,6 +3,8 @@ icecast2/fallback_music/*
!icecast2/fallback_music/.gitkeep !icecast2/fallback_music/.gitkeep
certbot/conf certbot/conf
certbot/www certbot/www
# Caddy's certificates, keys and ACME account (docker-compose.yml)
caddy/data/
backend/token/ backend/token/
jobs-data/ jobs-data/
usaco-data/ usaco-data/
+30
View File
@@ -498,6 +498,36 @@ docker compose restart nginx
Add `--dry-run` to test without burning rate limit. Add `--dry-run` to test without burning rate limit.
**Caddy beside nginx (the edge migration, in progress).** `caddy/` is the
replacement for `nginx/` and certbot. Until the cutover the `caddy` container
runs next to nginx and serves nothing public: it listens on the host's
loopback only (`127.0.0.1:8880` http, `127.0.0.1:8443` https), has no network
aliases, and gets its own certificates over DNS-01 into `./caddy/data`. That
needs `CLOUDFLARE_DNS_API_TOKEN` to carry **Zone → Zone → Read** as well as
DNS → Edit (certbot only needed the second); without it Caddy logs failed
orders and the public site is unaffected. Watch the first issuance with:
```
docker compose logs -f caddy | grep -i -E 'certificate|error'
```
Then compare the two edges request by request (the script's header explains
the output; pass an admin session's cookie as `EDGE_COOKIE` to cover the
signed-in cases too):
```
export "$(grep '^DOMAIN=' .env)"
caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >nginx.txt
caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >caddy.txt
diff nginx.txt caddy.txt
```
The expected differences: `Server: nginx` is gone, the gates match paths
case-insensitively (so `/SB/` is gated instead of falling to the SPA), and
`X-Frame-Options`/`Cache-Control` come out in a different order or combined.
A Caddyfile change is checked by `make check-caddy`, the same image build the
deploy runs, which validates the production and dev configs.
**Check logs:** **Check logs:**
``` ```
+14 -2
View File
@@ -13,6 +13,7 @@
# check-python python3 with the venv module # check-python python3 with the venv module
# check-vue Node + `npm install` done in vue/ # check-vue Node + `npm install` done in vue/
# check-compose / dev Docker with the compose plugin # check-compose / dev Docker with the compose plugin
# check-caddy Docker
# Nothing here installs a toolchain; a missing one fails that target only. # Nothing here installs a toolchain; a missing one fails that target only.
# #
# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in # Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in
@@ -35,7 +36,7 @@ VENV := .venv
# changes and skip the install otherwise. # changes and skip the install otherwise.
VENV_STAMP := $(VENV)/.installed VENV_STAMP := $(VENV)/.installed
.PHONY: help check check-backend check-python check-vue check-compose generate dev .PHONY: help check check-backend check-python check-vue check-compose check-caddy generate dev
help: help:
@echo "Targets:" @echo "Targets:"
@@ -44,11 +45,12 @@ help:
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)" @echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
@echo " make check-vue vite build of vue/ into a throwaway directory" @echo " make check-vue vite build of vue/ into a throwaway directory"
@echo " make check-compose validate docker-compose.yml, alone and with the dev override" @echo " make check-compose validate docker-compose.yml, alone and with the dev override"
@echo " make check-caddy build the Caddy image, which validates caddy/ for prod and dev"
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit" @echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
@echo " make dev build and run the dev stack (http://localhost)" @echo " make dev build and run the dev stack (http://localhost)"
# Run with `make -k check` to keep going past the first failing area. # Run with `make -k check` to keep going past the first failing area.
check: check-backend check-python check-vue check-compose check: check-backend check-python check-vue check-compose check-caddy
check-backend: check-backend:
cd backend && go vet ./... && go test ./... cd backend && go vet ./... && go test ./...
@@ -111,6 +113,16 @@ check-compose:
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \ echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
# The edge config is validated by the image build itself (the last RUN in
# caddy/Dockerfile runs `caddy validate` for the production and dev sites), so
# this is that build and nothing more. The deploy's `docker compose up
# --build` runs the same build, and a failure there stops before any
# container is replaced. The first build compiles Caddy with its plugins and
# takes a few minutes; later ones reuse that layer unless the Dockerfile
# changes.
check-caddy:
docker build -q -t web_server-caddy:check caddy/
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from # Rewrites backend/graph/generated.go and graph/model/models_gen.go from
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved. # graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
generate: generate:
+6
View File
@@ -0,0 +1,6 @@
**/.git
**/.DS_Store
# The certificate store (private keys) is bind-mounted at runtime, never sent
# to the build.
data
edge_test.sh
+398
View File
@@ -0,0 +1,398 @@
# =============================================================================
# Caddyfile — the public edge: TLS, the SPA, and the reverse proxy in front of
# every other service. Replaces nginx/ and the certbot container.
#
# FILES (all baked into the image by caddy/Dockerfile)
# Caddyfile this file: global options, the snippets every site
# uses, the healthcheck site, and the import that picks
# the dev or production sites.
# routes.caddy the proxy route table, shared by dev and production.
# ADD A NEW PROXIED ROUTE THERE.
# sites/prod.caddy production: http -> https://www, the apex (registry
# and redirect), the www site.
# sites/dev.caddy dev: localhost on http and https, `/` -> Vite.
#
# WHICH SITES ARE LOADED
# CADDY_SITE picks the file (`prod` unless set; docker-compose.dev.yml sets
# `dev`). It is a parse-time {$VAR}, substituted before the Caddyfile is
# read, so it can name the import itself.
#
# TWO KINDS OF VARIABLE
# {$NAME} / {$NAME:default} read from the environment ONCE, when the config
# is parsed. Used for upstream names and the
# domain. They end up in the JSON config Caddy
# autosaves to /config, so never a secret.
# {env.NAME} read per use at runtime, never written into the
# config. Used for the two secrets: the
# Cloudflare DNS token and the receipt token.
# Every variable must be in the caddy service's explicit `environment:`
# list in docker-compose.yml, or it reaches Caddy empty. Note an EMPTY
# variable is not "unset": {$X:default} keeps the empty value. So defaults
# live in that compose list (${X:-default}), which treats both alike, as
# nginx/entrypoint.sh's ${X:-default} did.
#
# WHAT NO LONGER NEEDS DOING (vs nginx)
# - Upstreams are resolved when Caddy dials them, not at startup, so it
# boots with any container missing and 502s until it appears. No
# `resolver` / `set $upstream_*` trick.
# - Certificates are obtained and renewed in-process (sites/prod.caddy), and
# Caddy serves while it does, so there is no bootstrap config, no certbot,
# no reload sentinel.
# - `header` is additive: a route that sets its own headers keeps the site's
# too. No security_headers.conf re-included everywhere.
# - Websocket upgrades, streaming responses and request-body streaming are
# the reverse proxy's defaults.
# =============================================================================
{
# No `email`: the ACME account works without one, Let's Encrypt stopped
# sending expiry notices in 2025, and an `email {$EMAIL}` line with EMAIL
# unset is a parse error that keeps the whole edge from starting.
# rate_limit is a plugin, so it has no place in Caddy's built-in directive
# order. Before basic_auth means before forward_auth too: a gated route
# counts the request before asking the backend about the session, as
# nginx's limit_req (preaccess phase) ran before auth_request (access).
order rate_limit before basic_auth
# Dev's `tls internal` would otherwise try to add Caddy's local CA to the
# container's trust store, which is pointless and logs an error.
skip_install_trust
servers {
# Real client IP behind the Cloudflare tunnel. For connections from
# the cloudflared container, and only those, the client IP is taken
# from Cloudflare's CF-Connecting-IP header. {client_ip} is then the
# visitor everywhere it is used: the rate-limit keys, the access log,
# and the X-Real-IP / X-Forwarded-For sent upstream (see `proxy`).
#
# Pinned to cloudflared's fixed address (ipv4_address in
# docker-compose.yml; change both together), NOT the subnet. Direct
# visitors on the published 80/443 can arrive from the bridge gateway,
# 172.28.0.1, so trusting the subnet would let anyone choose their own
# IP, and so their own rate-limit bucket, by sending the header.
trusted_proxies static 172.28.255.250
client_ip_headers CF-Connecting-IP
# No HTTP/3: 443/udp is not published and cloudflared does not use it,
# so advertising it (Alt-Svc) would only send browsers on a detour.
protocols h1 h2
}
# ---- Access logs ---------------------------------------------------------
# Every site imports `logging`, which names its access logger `payloads`.
# The two loggers below take that stream; the default logger is told to
# leave it alone, or each request would also be printed unfiltered,
# request body included.
log default {
exclude http.log.access.payloads
}
# The payload log: one JSON line per request, body included (log_append
# in `logging`), for seeing what actually arrives at the edge.
# logs/caddy/ on the host; from the cutover the `traffic` container tails
# it so Dozzle shows it as its own stream. Caddy rotates it itself, and
# `tail -F` follows the rotation. 0644 so `jq` on the host can read it
# unprivileged (Caddy's default is 0600).
#
# Redaction: any body mentioning a password, token or secret is replaced
# whole, not field by field, because there is no JSON parser here. That
# catches /auth/login, the GraphQL login and change-password mutations and
# the refresh-token call in one rule. Over-matching (a query that merely
# selects a field named *token*) costs a hidden body, never a leak.
# Cookie and Authorization headers are logged as REDACTED by Caddy itself
# (the `log_credentials` server option is off).
log payloads_file {
include http.log.access.payloads
output file /var/log/caddy/payloads.log {
roll_size 50MiB
roll_keep 5
mode 0644
}
format filter {
wrap json
fields {
req_body regexp "(?is)^.*(password|token|secret).*$" "[redacted]"
}
}
}
# The container's stdout, which `docker compose logs caddy` and Dozzle
# show: the same requests cut down to one short line each, without the
# body or headers, like nginx's `compact` format.
log payloads_stdout {
include http.log.access.payloads
output stdout
format filter {
wrap console
fields {
req_body delete
request>headers delete
request>tls delete
resp_headers delete
}
}
}
}
# ---- Snippets ----------------------------------------------------------------
# Defined here, before the site files are imported, so every file can use
# them. `import <snippet> <args...>` fills {args[N]}.
# Inside every reverse_proxy. Caddy already passes Host through and sets
# X-Forwarded-Proto/Host. X-Forwarded-For is overwritten rather than left to
# Caddy's default, which APPENDS the trusted peer: behind the tunnel that is
# "<visitor>, 172.28.255.250", and Gitea (REVERSE_PROXY_LIMIT = 1, so the
# rightmost entry) would log cloudflared for every visitor. With exactly one
# entry, the visitor, every upstream sees what nginx gave it: gin's ClientIP()
# (backend/main.go, trusts 172.28/16), Gitea, and python/app/main.py's
# _internal_only guard, which refuses any request carrying either header.
(proxy) {
header_up X-Real-IP {client_ip}
header_up X-Forwarded-For {client_ip}
}
# import limit <zone> <events> <window>
#
# A sliding window: at most <events> per <window> per client IP, then 429
# (turned into 503 by `errors`). Unlike nginx's leaky bucket there is no
# separate burst, so each zone's <events> is nginx's rate and <window> its
# unit, which keeps the sustained rates exact; the instant allowance comes out
# close to nginx's burst + 1. DEPLOYMENT.md §6 has the table and the reasoning
# behind each zone.
#
# State is shared per ZONE NAME across every route that names it (the plugin
# keeps one pool keyed by name), which is how /api, /py, /jobs, /usaco and
# /tracker share one `api` bucket, as in nginx. So a zone name must always be
# given the same <events> and <window>; a route that wants different numbers
# needs its own zone name (see `receipt`).
(limit) {
rate_limit {
zone {args[0]} {
key {client_ip}
events {args[1]}
window {args[2]}
}
}
}
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/,
# Gitea's history views, /uploads/private/) ----
# forward_auth sends a GET carrying the original request's headers, cookie
# included, to the backend's /auth/validate-admin before the request goes
# anywhere. 2xx lets it through; 401/403 become a redirect to the SPA login.
# This puts the Go backend's session in front of services that have no idea
# it exists. The body is never sent (the method is rewritten to GET), so a
# 2 GB garage-webui upload does not go to the backend twice.
#
# {http.request.orig_uri}, not {uri}: a route's `uri strip_prefix` runs
# BEFORE forward_auth in Caddy's directive order, so {uri} would have lost its
# prefix by the time this redirect is built. The `*` matters too: given only a
# target and a status, `redir` takes a target starting with / as a path
# MATCHER, and the redirect would never fire.
(admin_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate-admin
@denied status 401 403
handle_response @denied {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
}
}
# ---- Permission gate (/receipt/) ----
# import permission_gate <key>
#
# The same mechanism, but asking GET /auth/validate/<key> whether the session
# holds one named permission (backend/services/permissions.go; admins hold
# them all), so a non-admin account granted it in the admin panel gets in.
# 401 (not signed in) goes to the login page; 403 (signed in, not granted)
# goes to a page that says so, since sending a signed-in user to log in again
# only shows them "Already signed in".
#
# On success the backend returns the username in X-Auth-User, copied onto the
# proxied request as X-Remote-User. copy_headers deletes any X-Remote-User the
# client sent before it sets the real one, so the upstream can trust it.
(permission_gate) {
forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
uri /auth/validate/{args[0]}
copy_headers X-Auth-User>X-Remote-User
@unauthenticated status 401
handle_response @unauthenticated {
redir * /admin/login?redirect={http.request.orig_uri} 302
}
@forbidden status 403
handle_response @forbidden {
redir * /no-access?path={http.request.orig_uri} 302
}
}
}
# Production only (sites/prod.caddy); HSTS on localhost would poison the
# browser for every other localhost project on the machine.
#
# No site-wide CSP here. Gitea (proxied at /gitea/) relies on inline <script>
# blocks its own templates generate, so a shared script-src would need
# 'unsafe-inline', which voids almost all of CSP's value. If a real CSP
# matters again, give the SPA document its own, separate from Gitea.
(security_headers) {
header {
X-Frame-Options "SAMEORIGIN"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
Strict-Transport-Security "max-age=63072000; includeSubDomains"
}
}
# User-uploaded files are attacker-supplied bytes on our own origin. nosniff
# stops content-type guessing (so backend/services/uploads.go's stored type is
# what the browser goes by), Content-Disposition inline keeps them from being
# treated as downloads, and the locked-down CSP means even an uploaded .html
# can run no script and load no resource. `>` defers each one until the
# response is written, so it also wins over anything Garage sends. (-Server
# and -Via repeat `common`'s, for the error route, which does not run it.)
(upload_headers) {
header {
>X-Content-Type-Options "nosniff"
>Content-Disposition "inline"
>Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'"
-Server
-Via
}
}
# The disk half of /uploads/ (see routes.caddy): hand the request to the
# uploads disk site at the bottom of this file. Used both when Garage answers
# 404/5xx (handle_response) and when it cannot be reached at all (`errors`),
# so it works from the ORIGINAL path, whatever the route had stripped by then.
#
# Why proxy to a second site rather than call file_server here: in an error
# route file_server answers with the ERROR's status, so a file served while
# Garage is down would arrive as a 502 (with the file as its body), and
# forcing 200 instead would also turn its 206 and 304 answers into 200s. A
# proxied response keeps whatever status the disk site gave it.
#
# The headers are imported again because error routes do not inherit the
# deferred ones of the route that failed.
(uploads_disk) {
import upload_headers
rewrite * {http.request.orig_uri.path}
reverse_proxy 127.0.0.1:2080
}
# Error routes, for errors Caddy raises itself (never for an upstream's own
# error response, which is passed through untouched). Any error none of these
# handles is answered with its own status and an empty body.
(errors) {
# rate_limit's 429. Answered as 503, the status nginx's limit_req used,
# because vue/src/views/hotels/hotelsStream.js tells the two apart: 503 is
# "too many searches from your address", while a 429 is the Python
# service's own "someone else is searching right now".
handle_errors 429 {
respond "Too many requests from your address. Wait a moment and retry." 503
}
# An upstream that could not be reached or timed out. Two routes turn that
# into something better than a bare 502, each keyed on a variable its
# route sets (error routes keep the request's vars, and a variable cannot
# be spoofed the way a path can be dressed up):
# uploads_fallback Garage is down: serve the file from disk instead.
# receipt_upstream set only once the permission gate has passed, so a
# backend outage is not reported as the printer's.
handle_errors 502 504 {
@uploads_fallback vars uploads_fallback yes
handle @uploads_fallback {
import uploads_disk
}
@receipt_offline vars receipt_upstream yes
handle @receipt_offline {
respond "The receipt printer machine is offline." 503
}
}
}
# The access log, and the request body on it. {http.request.body} buffers the
# body in memory to log it, so it is only taken when the client declared a
# length under 100 KB and the route is not an upload path: big and chunked
# bodies are logged without one. nginx did the equivalent: bodies over its
# 64k buffer went to a temp file and logged empty.
(logging) {
log payloads
@small_body {
# Up to five digits, spelt out because a {1,5} would read as a
# placeholder.
header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$
not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/*
}
# `<` (early: taken before the request is proxied) must be explicit.
# Without it 2.11 takes the body early as documented, but then takes it a
# second time after the proxy has read it, logging an empty string.
log_append @small_body <req_body {http.request.body}
}
# Compression, for the types nginx's gzip_types listed. An explicit list so
# that streamed responses (application/x-ndjson from /py/hotels/*, Dozzle's
# text/event-stream, icecast's audio) are never held back to fill a
# compression buffer.
(encode) {
encode zstd gzip {
minimum_length 256
match {
header Content-Type text/html*
header Content-Type text/plain*
header Content-Type text/css*
header Content-Type text/javascript*
header Content-Type application/javascript*
header Content-Type application/json*
header Content-Type application/xml*
header Content-Type image/svg+xml*
}
}
}
(common) {
import logging
import errors
import encode
# Caddy's own `Server: Caddy` and an upstream's (icecast sends one), and
# the `Via: 1.1 Caddy` its reverse proxy adds: nginx sent neither.
header {
-Server
-Via
}
}
# ---- Container healthcheck ---------------------------------------------------
# The target of the healthcheck in docker-compose.yml, which the `autoheal`
# container acts on. Answered by Caddy itself, so it measures whether the
# server is serving and nothing upstream. Plain HTTP on :80, addressed by IP
# so it matches no real site; not logged, or it would put a line in the
# payload log every 30 s.
http://127.0.0.1 {
respond /caddy-health 204
respond 404
}
# ---- Uploads disk site -------------------------------------------------------
# The shared `uploads` volume (mounted at /srv/uploads), served to this
# container only (bound to the loopback; nothing publishes 2080). Reached by
# `uploads_disk` when Garage has no copy of a file; see that snippet for why
# it is a site of its own. Unlogged: the request was logged as it arrived.
#
# private/ is refused here as well as gated upstream. A request is routed by
# its cleaned, lower-cased path, so anything that could reach private/ goes to
# the gated /uploads/private/ route long before this; the refusal is the
# second lock, should that route ever be reordered.
http://:2080 {
bind 127.0.0.1
@private path /uploads/private /uploads/private/*
handle @private {
respond 404
}
handle /uploads/* {
root * /srv
file_server
}
respond 404
}
import sites/{$CADDY_SITE:prod}.caddy
+66
View File
@@ -0,0 +1,66 @@
# =============================================================================
# caddy image — the public edge. Caddy with two plugins, plus this
# directory's config, checked while the image is built.
#
# WHY A CUSTOM BUILD
# Stock Caddy has neither of these, and the config needs both:
# caddy-dns/cloudflare DNS-01 certificates through the Cloudflare API
# (sites/prod.caddy), since the router forwards
# nothing to obtain them over HTTP.
# mholt/caddy-ratelimit the `rate_limit` directive (the `limit` snippet
# in the Caddyfile).
# xcaddy compiles them in. The cloudflare plugin is pinned to a release;
# caddy-ratelimit has had one tagged release (v0.1.0, 2024) and is pinned
# to a commit, so Renovate leaves it alone and it is bumped by hand.
#
# BASE: caddy:2.11.9, the builder and the runtime from the same release
# (the builder's xcaddy builds the CADDY_VERSION its image sets). Both
# tags are bumped together. Official images are multi-arch.
#
# THE CONFIG IS VALIDATED AT BUILD TIME
# The last RUN parses and provisions the config with `caddy validate`, for
# the production sites and the dev ones, against placeholder values for
# every variable the config reads. A config that would not load therefore
# fails the image build, and a failed build aborts `docker compose up
# --build` BEFORE any container is replaced, so the running edge keeps
# serving. `make check-caddy` is the same build. The placeholders exist
# only for that RUN; the real values come from the container's
# environment (docker-compose.yml).
#
# NO ENTRYPOINT. The base image's CMD runs
# `caddy run --config /etc/caddy/Caddyfile --adapter caddyfile`, which is all
# that is needed: Caddy reads the environment itself, and obtains and renews
# its own certificates.
# =============================================================================
FROM caddy:2.11.9-builder AS builder
RUN xcaddy build \
--with github.com/caddy-dns/[email protected] \
--with github.com/mholt/caddy-ratelimit@5625512f24f6f59d6f64fb3aafe5eecff0b286db
FROM caddy:2.11.9
COPY --from=builder /usr/bin/caddy /usr/bin/caddy
COPY Caddyfile routes.caddy /etc/caddy/
COPY sites/ /etc/caddy/sites/
# Mount points (docker-compose.yml). Created so Caddy still starts without
# them: the log directory especially, since a log file that cannot be opened
# stops the config loading.
RUN mkdir -p /var/log/caddy /srv/www /srv/uploads
# Validation writes Caddy's data and the payload log, so it is pointed at a
# throwaway directory and the log is removed afterwards, leaving the image as
# it was.
RUN set -e; \
for site in prod dev; do \
echo "caddy validate (CADDY_SITE=$site)"; \
env XDG_DATA_HOME=/tmp/validate XDG_CONFIG_HOME=/tmp/validate \
CADDY_SITE=$site DOMAIN=example.com EMAIL=[email protected] \
BACKEND_HOST=backend BACKEND_PORT=8080 BACKEND_ENDPOINT=/api \
ICECAST_HOST=icecast2 ICECAST_PORT=8000 \
GITEA_HOST=gitea GITEA_PORT=3000 \
SILVERBULLET_HOST=silverbullet SILVERBULLET_PORT=3000 \
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_PORT=3000 \
PYTHON_HOST=python PYTHON_PORT=8000 \
RECEIPT_WEB_UPSTREAM=127.0.0.1:9 RECEIPT_WEB_TOKEN=validate \
CLOUDFLARE_DNS_API_TOKEN=validate-placeholder-token-0000000000000 \
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile; \
done; \
rm -rf /tmp/validate /var/log/caddy/*
+215
View File
@@ -0,0 +1,215 @@
#!/usr/bin/env bash
# =============================================================================
# edge_test.sh — what the public edge does with a fixed set of requests.
#
# WHAT IT DOES
# Sends each request below to the edge and prints one line per request
# (status and Location, or one response header). Two kinds of line:
# ok / FAIL the privacy boundary and the gates, which have a fixed right
# answer: the /notes/ denials, /py/internal/, every gated
# prefix. Any FAIL makes the exit status 1.
# show / hdr everything else (redirects, headers, carve-outs, uploads),
# whose answer depends on the upstream's data. Compare two runs
# instead (below).
#
# USAGE
# caddy/edge_test.sh <base-url> [curl options...]
# base-url the www origin, e.g. https://www.example.com
# curl options added to every request: --resolve to reach a given
# container, -k for dev's internal CA.
# Environment, all optional:
# EDGE_APEX the apex origin (production only): adds the apex cases.
# EDGE_HTTP the plain-http apex origin (production only), e.g.
# http://example.com: adds the http -> https case.
# EDGE_COOKIE an admin session's Cookie header value: adds the
# signed-in cases (each gated prefix must then NOT redirect
# to the login).
# EDGE_UPLOAD the name of a file under /uploads/ that exists.
#
# On stpvm, pin the hostname to this machine, or curl goes out over the
# internet and back (and hangs):
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1
# Dev stack:
# caddy/edge_test.sh https://localhost -k
#
# COMPARING TWO EDGES (the nginx -> Caddy cutover)
# Run it against each and diff the output:
# caddy/edge_test.sh https://www.$DOMAIN --resolve www.$DOMAIN:443:127.0.0.1 >nginx.txt
# caddy/edge_test.sh https://www.$DOMAIN:8443 --resolve www.$DOMAIN:8443:127.0.0.1 >caddy.txt
# diff nginx.txt caddy.txt
# Every remaining difference should be one that was intended.
#
# NOTHING HERE WRITES. Every request is a GET, apart from one POST to
# /py/internal/, which never gets past the edge.
# =============================================================================
set -u
if [ $# -lt 1 ]; then
echo "usage: $0 <base-url> [curl options...]" >&2
exit 2
fi
BASE=${1%/}
shift
CURL_OPTS=("$@")
FAILED=0
# The www host, without scheme or port.
BASE_HOST=$(printf '%s' "$BASE" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')
# "<status> <location>" for one request. Arguments after the URL are extra
# curl options (method, headers, --path-as-is). A redirect to the www host is
# shown as its path alone: nginx sends an absolute Location built from its
# own port, Caddy a relative one, and either way the browser lands on the
# same page.
probe() {
local url=$1 out
shift
out=$(curl -sS -o /dev/null --max-time 15 -w '%{http_code} %{redirect_url}' \
"${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null) || out=ERR
printf '%s' "$out" | sed -E "s#^([0-9]+) [a-z]+://$BASE_HOST(:[0-9]+)?/#\\1 /#"
}
# The first value of one response header, or "-".
header_of() {
local name=$1 url=$2 value
shift 2
value=$(curl -sS -o /dev/null -D - --max-time 15 "${CURL_OPTS[@]}" "$@" "$url" 2>/dev/null |
tr -d '\r' | grep -i "^$name:" | head -n 1 | cut -d: -f2- | sed 's/^ //')
printf '%s' "${value:--}"
}
# must <status> <location prefix, or -> <label> <path> [curl options]
must() {
local want_status=$1 want_loc=$2 label=$3 path=$4 got status loc ok=yes
shift 4
got=$(probe "$BASE$path" "$@")
status=${got%% *}
loc=${got#* }
[ "$status" = "$want_status" ] || ok=no
if [ "$want_loc" != "-" ] && [ "${loc#"$want_loc"}" = "$loc" ]; then
ok=no
fi
if [ $ok = yes ]; then
printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got"
else
printf 'FAIL %-12s %-58s %s (want %s %s)\n' "$label" "$path" "$got" "$want_status" "$want_loc"
FAILED=1
fi
}
# not_login <label> <path> [curl options]: anything but a redirect to the login.
not_login() {
local label=$1 path=$2 got
shift 2
got=$(probe "$BASE$path" "$@")
case $got in
ERR | "302 /admin/login"*)
printf 'FAIL %-12s %-58s %s (want: let through)\n' "$label" "$path" "$got"
FAILED=1 ;;
*) printf 'ok %-12s %-58s %s\n' "$label" "$path" "$got" ;;
esac
}
# show <label> <url> [curl options]
show() {
local label=$1 url=$2
shift 2
printf 'show %-12s %-58s %s\n' "$label" "${url#"$BASE"}" "$(probe "$url" "$@")"
}
# hdr <url> <header...>
hdr() {
local url=$1 h
shift
for h in "$@"; do
printf 'hdr %-12s %-58s %s\n' "$h" "${url#"$BASE"}" "$(header_of "$h" "$url")"
done
}
LOGIN="/admin/login?redirect="
echo "# privacy boundary: must be 404"
for p in \
/notes/private/x /notes/Private/x /notes/a/private/x /notes/private \
/notes/templates/t /notes/.fs/private/x.md /notes/.fs/a/private/x.md \
/notes/.fs/.git/HEAD /notes/a/.obsidian/workspace.json /notes/a/.git/config \
/notes/.revisions/x.md /notes/private%2Fx /notes/%70rivate/x; do
must 404 - notes "$p"
done
must 404 - notes /notes/a/../private/x --path-as-is
must 404 - notes /notes/a//private/x --path-as-is
must 404 - py-internal /py/internal/rowing/read -X POST
must 404 - py-internal /py/internal/rowing/read
must 404 - py-internal /py/x/../internal/rowing/read --path-as-is -X POST
must 404 - py-internal /py//internal/rowing/read --path-as-is -X POST
echo "# admin gate, signed out: must redirect to the login, with the original URI"
for p in \
/sb/ /sb/index.html /jobs/ /jobs/api/graphql /tracker/ /tracker/dashboard \
/dozzle/ /garage/ /radio/admin/stats.xsl /uploads/private/x.png \
/gitea/adamf/web_server/commit/0000000 /gitea/adamf/web_server/src/commit/0000000/README.md \
/gitea/adamf/web_server/archive/main.tar.gz /gitea/adamf/web_server/compare/main...x \
/gitea/adamf/web_server/blame/commit/0000000/README.md \
"/jobs/leads?x=1"; do
must 302 "$LOGIN$p" gate "$p"
done
must 302 "${LOGIN}/uploads/x/../private/x.png" gate /uploads/x/../private/x.png --path-as-is
show gate "$BASE/SB/"
must 302 "${LOGIN}/receipt/" permission /receipt/
if [ -n "${EDGE_COOKIE:-}" ]; then
echo "# admin gate, signed in: must be let through"
for p in /sb/ /jobs/ /tracker/ /dozzle/ /garage/ /radio/admin/stats.xsl \
/gitea/adamf/web_server/commit/0000000 /receipt/; do
not_login gate "$p" -H "Cookie: $EDGE_COOKIE"
done
fi
echo "# carve-outs and public routes (status depends on the upstream)"
for p in /jobs/api/capture /jobs/job-capture.user.js /tracker/api/v1/events \
/tracker/tracker.user.js /tracker/readyz /usaco/ /notes/ /gitea/ \
/gitea/adamf/web_server/src/branch/main/README.md /radio/status.xsl \
/py/ /py/docs /api/ /api/me /; do
show public "$BASE$p"
done
echo "# bare prefixes and moved URLs"
for p in /api /radio /dozzle /garage /gitea /notes /sb /py /jobs /usaco \
/tracker /receipt /cv/jobs /cv/leads /job-capture.user.js "/gitea?x=1"; do
show redirect "$BASE$p"
done
echo "# SPA"
for p in /admin /architecture /some-canvas-page /assets/does-not-exist.js; do
show spa "$BASE$p"
done
hdr "$BASE/" Content-Type Strict-Transport-Security X-Frame-Options \
X-Content-Type-Options Referrer-Policy Content-Security-Policy Server
hdr "$BASE/api/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/gitea/" Strict-Transport-Security X-Frame-Options Server
hdr "$BASE/assets/does-not-exist.js" Cache-Control
hdr "$BASE/img/stamps/mine.gif" Access-Control-Allow-Origin Cache-Control
echo "# uploads"
show uploads "$BASE/uploads/does-not-exist.png"
hdr "$BASE/uploads/does-not-exist.png" X-Content-Type-Options Content-Security-Policy
if [ -n "${EDGE_UPLOAD:-}" ]; then
show uploads "$BASE/uploads/$EDGE_UPLOAD"
show uploads "$BASE/uploads/$EDGE_UPLOAD" -H "Range: bytes=0-9"
hdr "$BASE/uploads/$EDGE_UPLOAD" Content-Type X-Content-Type-Options \
Content-Disposition Content-Security-Policy Strict-Transport-Security
fi
if [ -n "${EDGE_APEX:-}" ]; then
APEX=${EDGE_APEX%/}
echo "# apex (production)"
show apex "$APEX/x?y=1"
show apex "$APEX/v2/"
hdr "$APEX/x" Strict-Transport-Security
fi
if [ -n "${EDGE_HTTP:-}" ]; then
echo "# plain http (production)"
show http "${EDGE_HTTP%/}/x?y=1"
fi
echo "# result: $([ $FAILED = 0 ] && echo all MUST cases passed || echo SOME MUST CASES FAILED)"
exit $FAILED
+452
View File
@@ -0,0 +1,452 @@
# =============================================================================
# routes.caddy — the PROXY ROUTE TABLE shared by production and dev. Add a new
# proxied route HERE, once.
#
# WHO IMPORTS IT
# sites/prod.caddy (the www site) and sites/dev.caddy, each inside a
# `route { ... }` block, followed by that site's own `/` handler (the built
# SPA in production, the Vite dev server in dev). Everything else that
# differs between the two (TLS, security headers, static-asset caching, the
# apex) is in the site files.
#
# ORDER IS LITERAL: THE FIRST MATCHING handle WINS
# Inside `route`, Caddy keeps directives in the order written, and `handle`
# blocks are mutually exclusive. So this file is read top to bottom like a
# firewall list: denials first, then the specific routes, each carve-out
# ahead of the gated prefix it is carved out of, then the catch-alls.
# (nginx's longest-prefix / regex-in-file-order / ^~ rules are gone.)
#
# HOW PATHS ARE MATCHED
# `path` matchers are case-insensitive and see the decoded, cleaned path
# (`..` resolved, `//` merged), so /SB/, /notes/a/../private/x or
# /uploads/%70rivate/x cannot slip past a rule. `path_regexp` sees the
# decoded, cleaned path too but is case-sensitive, hence `(?i)` where case
# matters. caddy/edge_test.sh checks these against the live edge.
#
# PATTERNS THAT REPEAT BELOW
# - `uri strip_prefix /x`: the public URL carries a prefix (/api, /radio,
# /gitea, /py, /tracker, /receipt) but the upstream serves from /. Apps
# told their own base path (SilverBullet, the job tracker, usaco, Dozzle,
# garage-webui) keep it.
# - `import proxy` in every reverse_proxy: the forwarding headers (see the
# snippet in Caddyfile).
# - `import limit <zone> ...`: see the snippet; DEPLOYMENT.md §6 for the
# numbers.
# - `import admin_gate` / `import permission_gate <key>`: the session check
# against the backend. Some of these services have no auth of their own,
# so a gated route that loses its import is open to the internet.
# - Upstream read timeouts are not set anywhere: Caddy has none by default,
# so a long hotel search, an email sync or a log tail is never cut off by
# the proxy. (Cloudflare still gives up on an origin that sends nothing
# for 100 s; see DEPLOYMENT.md.)
#
# Upstream names come from the environment ({$BACKEND_HOST} etc.; see the
# caddy service in docker-compose.yml). The job tracker, activity tracker,
# usaco, Dozzle and Garage containers have fixed names there, so they are
# written literally.
# =============================================================================
# Request bodies: 50 MB everywhere except garage-webui, which takes video
# uploads and sets its own 2 GB below. (An outer limit cannot be raised by an
# inner one, so the exception has to be carved out here.) The backend caps
# uploads at 10 MB itself; this is the ceiling for everything else.
@body_default not path /garage/*
request_body @body_default {
max_size 50MB
}
# ---- Denials -----------------------------------------------------------------
# /py/internal/: routes the Go backend calls directly over app-network (the
# rowing photo reader, which spends a paid Claude call and has no auth of its
# own). Never proxied. The Python side also refuses anything carrying the
# X-Real-IP / X-Forwarded-For headers `proxy` sets, as a second layer.
handle /py/internal/* {
respond 404
}
# PUBLIC notes viewer privacy boundary. /notes/ is a second, read-only
# SilverBullet over the vault /sb/ edits, and SB_SPACE_IGNORE only hides
# paths from its file LIST. Everything else serves them (all verified against
# 2.11.0 with curl):
# /notes/.fs/private/x.md raw file, straight off disk
# /notes/private/x the page URL: the server pre-renders the
# note's content into the HTML shell
# /notes/.fs/.git/... the vault's whole git repo, i.e. every
# version of every private note ever
# and gitignore semantics mean `private/` in SB_SPACE_IGNORE hides a private/
# folder at ANY depth, so the block must too.
#
# 1. private/ or templates/ as any path segment, page URL or /.fs/. (?i) so
# Private/ is caught; (/|$) so the folder itself matches.
# 2. Any dot-segment below the first: .git, .obsidian, .env, ... The first
# segment is exempt because that is where SilverBullet's own endpoints
# live (/.fs, /.config, /.client, /.events ...). Nothing the client
# legitimately loads has a dot-segment deeper than that.
# 3. Revisions are read from the vault's own .git, i.e. the full history of
# every file INCLUDING private/ and anything ever deleted.
# SB_REVISIONS=disabled already turns this off upstream; this is the
# second lock in case that env var is ever dropped.
# Keep the folder list in step with SB_SPACE_IGNORE on silverbullet-public.
# 404 rather than 403 so the response does not confirm a private path exists.
@notes_private path_regexp (?i)^/notes/(.*/)?(private|templates)(/|$)
handle @notes_private {
respond 404
}
@notes_dot path_regexp ^/notes/.+/\.
handle @notes_dot {
respond 404
}
handle /notes/.revisions* {
respond 404
}
# ---- Bare prefixes and moved URLs ----------------------------------------------
# So a user typing /gitea without the slash lands correctly. Exact paths: unlike
# nginx's prefix locations, /gitea-something is not caught and is left to the
# SPA (where an admin-created canvas page with that slug now works).
redir {$BACKEND_ENDPOINT} {$BACKEND_ENDPOINT}/ 301
redir /radio /radio/ 301
redir /dozzle /dozzle/ 301
redir /garage /garage/ 301
redir /gitea /gitea/ 301
redir /notes /notes/ 301
redir /sb /sb/ 301
redir /py /py/ 301
redir /jobs /jobs/ 301
redir /usaco /usaco/ 301
redir /tracker /tracker/ 301
redir /receipt /receipt/ 301
# Where the job tracker used to be. The SPA routes were client-side, so these
# only catch bookmarks and typed URLs. The userscript's old @updateURL lands
# on the third, which is how installed copies find version 2.0.0 and its new
# API base.
redir /cv/jobs /jobs/ 301
redir /cv/leads /jobs/leads 301
redir /job-capture.user.js /jobs/job-capture.user.js 301
# ---- Backend API ---------------------------------------------------------------
# Live chat / activity feed websocket. Deliberately NOT rate limited: a
# websocket is one long-lived request, and a limit here would drop reconnect
# storms, not abuse.
handle {$BACKEND_ENDPOINT}/ws* {
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# Brute-force defence on password auth, on top of the backend's own 5/min.
handle {$BACKEND_ENDPOINT}/auth/login* {
import limit login 5 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/uploads* {
import limit upload 30 1m
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# Tighter than the REST catch-all, because one GraphQL query can be
# arbitrarily expensive to resolve.
handle {$BACKEND_ENDPOINT}/graphql* {
import limit graphql 10 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
handle {$BACKEND_ENDPOINT}/* {
import limit api 30 1s
uri strip_prefix {$BACKEND_ENDPOINT}
reverse_proxy {$BACKEND_HOST}:{$BACKEND_PORT} {
import proxy
}
}
# ---- Admin-gated services ------------------------------------------------------
# Dozzle: live view of every container's logs, including the `traffic`
# container's request-body log. It reads the Docker socket, so it is
# effectively root on the host: admin only. DOZZLE_BASE=/dozzle makes it serve
# under the prefix itself. Its log tails are server-sent events, which Caddy
# streams without buffering.
handle /dozzle/* {
import admin_gate
reverse_proxy dozzle:8080 {
import proxy
}
}
# garage-webui: buckets, keys and a file browser for the Garage object store.
# It holds Garage's admin token, so admin only, and its own login is left
# unset (one login, not two). BASE_PATH=/garage makes it serve under the
# prefix. 2 GB so videos can be uploaded through it; the body streams through
# rather than landing on disk first.
handle /garage/* {
import admin_gate
request_body {
max_size 2GB
}
reverse_proxy garage-webui:3909 {
import proxy
}
}
# The icecast ADMIN UI is a full station-control surface (kick sources, change
# metadata) protected only by the icecast admin password. Ahead of /radio/*,
# so listener traffic (the mount, status.xsl) is untouched.
handle /radio/admin/* {
import admin_gate
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
# Gitea's history views and archives. A crawler swarm (129k requests from
# 103k IPs over 2026-10-18/19, so per-IP rate limits are useless) walks every
# file at every commit, and those pages are the expensive ones: diffs, blame,
# tarballs. 89% of its requests were these shapes. People browsing the code
# use the branch views (src/branch/..., commits/branch/...), which stay
# public, so the CV's repo links still work. Gitea's own
# REQUIRE_SIGNIN_VIEW=expensive would also block src/branch, hence doing it
# here. Ahead of /gitea/*.
@gitea_history path_regexp ^/gitea/[^/]+/[^/]+/((src|raw|blame|commits|media)/commit/|commit/|archive/|compare/)
handle @gitea_history {
import admin_gate
uri strip_prefix /gitea
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes. NO
# prefix strip: it is a PWA told its own base path via SB_URL_PREFIX=/sb, and
# builds its service-worker scope and asset URLs from it. Strip the prefix and
# the app loads a blank page with no error in the log.
handle /sb/* {
import admin_gate
reverse_proxy {$SILVERBULLET_HOST}:{$SILVERBULLET_PORT} {
import proxy
}
}
# ---- Public services -----------------------------------------------------------
handle /radio/* {
uri strip_prefix /radio
reverse_proxy {$ICECAST_HOST}:{$ICECAST_PORT} {
import proxy
}
}
handle /gitea/* {
uri strip_prefix /gitea
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
# The public notes viewer, behind the denials at the top of this file. No
# prefix strip, for the same reason as /sb/ (SB_URL_PREFIX=/notes).
handle /notes/* {
reverse_proxy {$SILVERBULLET_PUBLIC_HOST}:{$SILVERBULLET_PUBLIC_PORT} {
import proxy
}
}
# /py/hotels/search[/stream] and /py/hotels/scan/stream: public, minutes-long
# upstream calls to Travelodge/TfL with a single search slot on the Python
# side, so this zone is really concurrency protection. flush_interval -1
# passes each NDJSON progress line on as it arrives (chunked responses are
# flushed anyway; this makes it explicit). `encode` never touches
# application/x-ndjson.
@hotels path_regexp ^/py/hotels/(search|scan)
handle @hotels {
import limit hotel_search 3 1m
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
flush_interval -1
}
}
handle /py/* {
import limit api 30 1s
uri strip_prefix /py
reverse_proxy {$PYTHON_HOST}:{$PYTHON_PORT} {
import proxy
}
}
# ---- Job tracker (/jobs/) ----
# Its own container (the adamf/job-tracker repo), which serves its SPA and its
# API from the same prefix, NOT stripped: the app is built to live at /jobs/.
# Gated like /sb/ (the app checks the session itself too), with two
# exceptions ahead of it that a session cookie can never reach:
# - the capture API, called by the userscript from job sites' origins with
# the capture bearer token rather than cookies; the app's
# CaptureTokenMiddleware guards it;
# - the userscript itself: userscript managers fetch its @updateURL without
# the session, and it holds no secrets (the token is entered after
# install).
handle /jobs/api/capture* {
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/job-capture.user.js {
reverse_proxy jobs:8080 {
import proxy
}
}
handle /jobs/* {
import admin_gate
import limit api 30 1s
reverse_proxy jobs:8080 {
import proxy
}
}
# ---- USACO practice log (/usaco/) ----
# Its own container (the usaco repo's site/), shaped like /jobs/: SPA and API
# under one prefix that is NOT stripped, and no gate, because most of it is
# public and the app checks the session itself for the admin's edits. Gitea's
# push webhook does not come through here: it calls the container directly
# on the Docker network.
handle /usaco/* {
import limit api 30 1s
reverse_proxy usaco:8080 {
import proxy
}
}
# ---- Activity tracker (/tracker/) ----
# Its own container (the adamf/ccp repo): an ingest API for device collectors,
# which send batches of events with a per-device bearer key, plus a dashboard
# and setup page. Gated like /sb/ (the app also checks the session itself),
# with two exceptions ahead of it: the API, which collectors call with bearer
# keys and no cookies (the app guards each route, by device key, admin
# session or either), and the public userscript. Unlike /jobs/ the prefix IS
# stripped: the server serves /api/v1/... and /readyz from /. Collectors must
# use the www host: the apex 301 would turn their POSTs into GETs. Health Auto
# Export bodies can be several MB; the 50 MB default above covers them.
handle /tracker/api/v1/* {
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/tracker.user.js {
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
handle /tracker/* {
import admin_gate
import limit api 30 1s
uri strip_prefix /tracker
reverse_proxy activity-tracker:8080 {
import proxy
}
}
# ---- Receipt printer (/receipt/) ----
# The adamf/receipt_maker repo's `receipt serve`, running on stppi (not in
# this stack: that machine reaches the printer on the home LAN), reached over
# Tailscale by IP. A page for printing a note or an uploaded image, plus its
# API. Behind the permission gate on `receipt`, so an account granted it in
# the admin panel can print without being an admin; the prefix IS stripped.
# The server trusts nothing without X-Receipt-Token, which only this proxy
# adds (header_up replaces any copy the client sent), and is told who is
# printing in X-Remote-User, which the gate sets.
#
# A `route`, so the steps run in the order written: receipt_upstream is set
# only after the gate has passed, so `errors` reports "printer offline" for a
# failed dial to stppi and not for a backend outage during the auth check.
# Its own zone, not `api`: a zone name must always carry the same numbers.
# 17 MB: the server caps uploads at 16 MB, plus room for the multipart
# framing around one.
handle /receipt/* {
route {
import limit receipt 10 1s
request_body {
max_size 17MB
}
import permission_gate receipt
vars receipt_upstream yes
uri strip_prefix /receipt
reverse_proxy {$RECEIPT_WEB_UPSTREAM} {
import proxy
header_up X-Receipt-Token {env.RECEIPT_WEB_TOKEN}
# Caddy's default, spelt out: when stppi is off, fail fast and
# let `errors` answer.
transport http {
dial_timeout 3s
}
}
}
}
# ---- Uploads (/uploads/) ----
# PRIVATE attachments (admin-only): files on *private* chat messages, which
# the backend always writes to disk, at uploads/private/. Ahead of the public
# route below, and matched on the cleaned, lower-cased path, so no spelling of
# a path into private/ reaches the ungated one.
handle /uploads/private/* {
import admin_gate
import upload_headers
root * /srv
file_server
}
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the Garage
# bucket's website endpoint, which serves the bucket anonymously and picks it
# by the Host header (garage/garage.toml: s3_web). The bucket is reachable
# only over app-network, so this is the only public way in. If Garage has no
# such file (404), errors (5xx), or cannot be reached at all (a dial error,
# caught by `errors` through the uploads_fallback variable), the file is
# served from the shared `uploads` volume instead (`uploads_disk`). That
# volume holds uploads from before Garage and anything the backend wrote
# there because Garage refused it (backend/services/uploads.go). So the bucket
# is the source of truth (deleting a file in garage-webui unpublishes it
# unless a disk copy exists), while a Garage outage only costs files that are
# nowhere else. dial_timeout 2s: Garage is on the same bridge, so a slow
# connect means it is down; fall back quickly. Range requests pass through
# either way, so video seeks.
handle /uploads/* {
import upload_headers
vars uploads_fallback yes
uri strip_prefix /uploads
reverse_proxy garage:3902 {
import proxy
header_up Host uploads.web.garage
transport http {
dial_timeout 2s
}
@not_in_bucket status 404 5xx
handle_response @not_in_bucket {
import uploads_disk
}
}
}
+32
View File
@@ -0,0 +1,32 @@
# =============================================================================
# sites/dev.caddy — LOCAL DEVELOPMENT sites. Imported by the Caddyfile when
# CADDY_SITE=dev, which only docker-compose.dev.yml sets.
#
# HOW IT DIFFERS FROM sites/prod.caddy
# - `/` is proxied to the Vite dev server at vue:5173 instead of serving the
# built SPA. Its HMR websocket needs nothing extra.
# - http AND https both serve the full site, with no redirects, so
# http://localhost just works. Listing the http:// addresses is what
# stops Caddy adding its automatic http -> https redirect.
# - TLS is `tls internal`: a certificate from Caddy's own local CA, kept in
# ./caddy/data. Browsers warn until that CA is trusted, which is expected.
# - No security headers: HSTS on localhost would poison the browser for
# every other localhost project on the machine.
# - No static-asset caching: Vite serves those, and long cache lifetimes
# would defeat hot reload.
# Everything else, every proxied route, gate, denial and rate limit, is the
# same routes.caddy as production.
# =============================================================================
http://{$DOMAIN}, https://{$DOMAIN}, http://www.{$DOMAIN}, https://www.{$DOMAIN} {
tls internal
import common
route {
import ../routes.caddy
handle {
reverse_proxy vue:5173
}
}
}
+133
View File
@@ -0,0 +1,133 @@
# =============================================================================
# sites/prod.caddy — PRODUCTION sites. Imported by the Caddyfile unless
# CADDY_SITE says otherwise.
#
# FOUR SITES
# 1. http:// apex + www -> 301 to https://www.DOMAIN.
# 2. https:// apex -> Gitea's registry at /v2/, else 301 to www, so
# there is exactly one canonical origin (cookies,
# CORS and the SPA all assume www).
# 3. https:// www -> the real site.
# (4. the healthcheck site, http://127.0.0.1, is in the Caddyfile.)
#
# CERTIFICATES
# Caddy obtains one for each name over DNS-01 through the Cloudflare API
# (`prod_tls`), keeps them in /data (./caddy/data on the host), and renews
# each when a third of its lifetime is left, in-process, with no reload.
# DNS-01 because the router forwards nothing: behind the tunnel no ACME
# server can reach :80 or :443. The token needs Zone -> Zone -> Read and
# Zone -> DNS -> Edit on this zone; see .env.example. Until the first
# certificate arrives (about a minute on a fresh ./caddy/data) the TLS
# handshake fails, so the tunnel, which verifies it, serves 502s.
#
# resolvers: on app-network, DOMAIN is a network alias for this very
# container, so Docker's DNS would answer the plugin's zone lookup itself
# and the order fails with "expected 1 zone, got 0". Asking Cloudflare's
# public resolvers sees the real zone.
# =============================================================================
(prod_tls) {
tls {
dns cloudflare {env.CLOUDFLARE_DNS_API_TOKEN}
resolvers 1.1.1.1 1.0.0.1
}
}
# Spelt out rather than left to Caddy's automatic redirect, which goes to the
# same host: http://apex would then take two hops (https://apex, then www).
http://{$DOMAIN}, http://www.{$DOMAIN} {
import logging
header -Server
redir https://www.{$DOMAIN}{uri} 301
}
{$DOMAIN} {
import prod_tls
import common
header Strict-Transport-Security "max-age=63072000; includeSubDomains"
route {
# Gitea's container registry, which publishes images such as
# DOMAIN/adamf/job-tracker. Docker always talks to /v2/ at the root of
# the host, whatever Gitea's ROOT_URL says, and Gitea advertises its
# token endpoint at https://DOMAIN/v2/token: on the apex, not under
# /gitea/ and not on www. So the apex serves /v2/ itself rather than
# redirecting it; a redirect on a blob upload is not something every
# Docker client follows. No request_body limit (routes.caddy's 50 MB
# is not imported here): image layers are far larger, and Caddy
# streams them to Gitea as they arrive.
handle /v2/* {
reverse_proxy {$GITEA_HOST}:{$GITEA_PORT} {
import proxy
}
}
redir https://www.{$DOMAIN}{uri} 301
}
}
www.{$DOMAIN} {
import prod_tls
import common
import security_headers
# ---- Static asset caching ----
# Each matcher also requires the file to exist (`file`), so only a real
# file is marked cacheable: a 404 for a hash the browser asks for before
# the new build lands must never be cached for a year as `immutable`.
# (nginx's add_header without `always` skipped error responses the same
# way.)
# Vite hashed assets: a new build has new names, so these never change.
@hashed {
path /assets/*
file {
root /srv/www
}
}
header @hashed Cache-Control "public, max-age=31536000, immutable"
@fonts {
path /fonts/*
file {
root /srv/www
}
}
header @fonts Cache-Control "public, max-age=2592000"
@week {
path /img/* /sound/*
file {
root /srv/www
}
}
header @week Cache-Control "public, max-age=604800"
# This GIF is a "web stamp" other people's sites hot-link, so it needs a
# CORS header. It is a public, deliberately hot-linkable image and nothing
# here is credentialed, so `*` is safe.
header /img/stamps/mine.gif Access-Control-Allow-Origin "*"
route {
import ../routes.caddy
# Static directories: a missing file is a 404, never the SPA's
# index.html. A stale page asking for an old asset hash then gets an
# honest error rather than HTML served as JavaScript.
@static path /assets/* /fonts/* /img/* /sound/*
handle @static {
root * /srv/www
file_server
}
# The built SPA (the vue_dist volume). Serve the file if it exists,
# otherwise hand index.html to the browser so Vue Router can resolve
# the path client-side: that is what makes deep links like /admin or
# a canvas page's /<slug> work on refresh.
handle {
root * /srv/www
try_files {path} {path}/ /index.html
file_server
}
}
}
+7
View File
@@ -14,6 +14,8 @@
# - backend : dev flags on, including database seeding. # - backend : dev flags on, including database seeding.
# - nginx : DEV_MODE=true, which makes its entrypoint render # - nginx : DEV_MODE=true, which makes its entrypoint render
# nginx_dev.conf.template and self-sign a localhost certificate. # nginx_dev.conf.template and self-sign a localhost certificate.
# - caddy : CADDY_SITE=dev, which loads caddy/sites/dev.caddy. Until the
# cutover it runs beside nginx, on 127.0.0.1:8880 / :8443.
# - python : uvicorn --reload with the app source bind-mounted. # - python : uvicorn --reload with the app source bind-mounted.
# - certbot : disabled entirely. # - certbot : disabled entirely.
# - cloudflared : disabled entirely. # - cloudflared : disabled entirely.
@@ -66,6 +68,11 @@ services:
ports: ports:
- 80:80 - 80:80
- 443:443 - 443:443
caddy:
environment:
# Loads caddy/sites/dev.caddy instead of the production sites:
# localhost on http and https, `tls internal`, `/` -> Vite.
- CADDY_SITE=dev
python: python:
# Same command as the Dockerfile's CMD plus --reload, paired with the # Same command as the Dockerfile's CMD plus --reload, paired with the
# source bind mount below so editing python/app/ restarts uvicorn. # source bind mount below so editing python/app/ restarts uvicorn.
+82
View File
@@ -87,6 +87,11 @@ volumes:
# one-shot `vue` container writes the built SPA here and exits; nginx mounts # one-shot `vue` container writes the built SPA here and exits; nginx mounts
# it at /etc/nginx/html and serves it. Repopulated on every rebuild. # it at /etc/nginx/html and serves it. Repopulated on every rebuild.
vue_dist: vue_dist:
# Caddy's /config: the JSON it autosaves on each config load. Nothing in it
# is needed across restarts (the Caddyfile is the source); named only so
# the image's VOLUME does not leave an anonymous volume behind on every
# recreate. The certificates are in ./caddy/data, not here.
caddy_config:
services: services:
# One-shot build container, NOT a long-running service. `vite build` writes # One-shot build container, NOT a long-running service. `vite build` writes
@@ -184,6 +189,83 @@ services:
labels: labels:
- autoheal=true - autoheal=true
# The replacement edge (caddy/Caddyfile), RUNNING BESIDE nginx until the
# cutover. While it does:
# - it is reachable only from this host, on 127.0.0.1:8880 (http) and
# 127.0.0.1:8443 (https), so the public site is still nginx;
# - it holds no network aliases and a fixed address of its own, so nothing
# on app-network (cloudflared included) is sent to it;
# - it obtains its certificates over DNS-01 into ./caddy/data, which needs
# no inbound port, so they are ready before it takes over;
# - autoheal ignores it.
# Compare the two with caddy/edge_test.sh (its header has the commands).
# The cutover gives it nginx's ports, aliases, address and autoheal label,
# and removes nginx and certbot.
#
# ENVIRONMENT: an explicit list, not the whole .env, so the edge never sees
# the database password or the JWT secret. A variable the Caddyfile reads
# must be added here, or it reaches Caddy empty. The ${X:-default} forms
# are the defaults nginx/entrypoint.sh gave the optional services; they live
# here because Caddy's own {$X:default} keeps a variable that is set but
# empty, which is how a blank line in .env arrives.
#
# NO depends_on: Caddy resolves an upstream when it dials it, so it starts
# with any of them missing (502 until it appears), and there is no Vue
# build to wait for: the SPA is files in vue_dist, served as they appear.
caddy:
build:
context: ./caddy
dockerfile: Dockerfile
container_name: caddy
restart: always
environment:
- DOMAIN=${DOMAIN}
- BACKEND_HOST=${BACKEND_HOST}
- BACKEND_PORT=${BACKEND_PORT}
- BACKEND_ENDPOINT=${BACKEND_ENDPOINT}
- ICECAST_HOST=${ICECAST_HOST}
- ICECAST_PORT=${ICECAST_PORT}
- GITEA_HOST=${GITEA_HOST}
- GITEA_PORT=${GITEA_PORT}
- SILVERBULLET_HOST=${SILVERBULLET_HOST:-silverbullet}
- SILVERBULLET_PORT=${SILVERBULLET_PORT:-3000}
- SILVERBULLET_PUBLIC_HOST=${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}
- SILVERBULLET_PUBLIC_PORT=${SILVERBULLET_PUBLIC_PORT:-3000}
- PYTHON_HOST=${PYTHON_HOST:-python}
- PYTHON_PORT=${PYTHON_PORT:-8000}
# A dead port by default, so /receipt/ reads "offline".
- RECEIPT_WEB_UPSTREAM=${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}
- RECEIPT_WEB_TOKEN=${RECEIPT_WEB_TOKEN:-}
# Zone -> Zone -> Read and Zone -> DNS -> Edit; see .env.example.
- CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-}
networks:
app-network:
# Beside nginx's .251 and cloudflared's .250. Becomes .251 at the
# cutover.
ipv4_address: 172.28.255.252
ports:
- 127.0.0.1:8880:80
- 127.0.0.1:8443:443
volumes:
# The certificates, their keys and the ACME account. PERSISTENT and
# private key material: gitignored, never commit. Losing it only costs
# a re-issue on the next start (about a minute over DNS-01).
- ./caddy/data:/data
- caddy_config:/config
- uploads:/srv/uploads:ro
# The SPA written by the one-shot `vue` container.
- vue_dist:/srv/www:ro
# The JSON request-body log, tailed by `traffic` after the cutover.
- ./logs/caddy:/var/log/caddy
# Answered by Caddy itself (http://127.0.0.1 in the Caddyfile). The image
# has busybox wget, not curl.
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/caddy-health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 30s
# Obtains the cert once, then renews every 12h forever. Disabled in dev via # Obtains the cert once, then renews every 12h forever. Disabled in dev via
# the `disabled` profile in docker-compose.dev.yml. Note this is the stock # the `disabled` profile in docker-compose.dev.yml. Note this is the stock
# certbot image with our script bind-mounted over the entrypoint, so editing # certbot image with our script bind-mounted over the entrypoint, so editing
+18 -1
View File
@@ -14,7 +14,8 @@
// pip_requirements python/requirements.txt, requirements-dev.txt // pip_requirements python/requirements.txt, requirements-dev.txt
// dockerfile every */Dockerfile FROM line // dockerfile every */Dockerfile FROM line
// docker-compose every image: in docker-compose*.yml // docker-compose every image: in docker-compose*.yml
// custom (below) the images deploy.yaml and renovate.yaml `docker run` // custom (below) the images deploy.yaml and renovate.yaml `docker run`,
// and the Caddy plugins caddy/Dockerfile compiles in
// //
// NOTHING IS AUTOMERGED, on purpose: a merge to main IS a deploy. Each // NOTHING IS AUTOMERGED, on purpose: a merge to main IS a deploy. Each
// Renovate branch is pushed to Gitea, so deploy.yaml's `test` job runs on it // Renovate branch is pushed to Gitea, so deploy.yaml's `test` job runs on it
@@ -50,6 +51,15 @@
matchStrings: ["(?<depName>golang|python|renovate/renovate):(?<currentValue>[0-9][\\w.-]*)"], matchStrings: ["(?<depName>golang|python|renovate/renovate):(?<currentValue>[0-9][\\w.-]*)"],
datasourceTemplate: "docker", datasourceTemplate: "docker",
}, },
{
// The Caddy plugins compiled in by caddy/Dockerfile's `xcaddy build
// --with <module>@<version>`. Only versions starting with v match, so
// caddy-ratelimit, pinned to a commit, is left for a hand bump.
customType: "regex",
managerFilePatterns: ["/^caddy/Dockerfile$/"],
matchStrings: ["--with (?<depName>[\\w./-]+)@(?<currentValue>v[0-9][\\w.-]*)"],
datasourceTemplate: "go",
},
], ],
packageRules: [ packageRules: [
@@ -103,6 +113,13 @@
matchPackageNames: ["python"], matchPackageNames: ["python"],
groupName: "Python image", groupName: "Python image",
}, },
// caddy/Dockerfile's builder and runtime images must be the same release
// (the builder compiles the version its image sets), so one PR moves
// both, along with the plugins.
{
matchFileNames: ["caddy/Dockerfile"],
groupName: "Caddy",
},
// gqlgen's runtime and gqlparser are versioned together. If a bump breaks // gqlgen's runtime and gqlparser are versioned together. If a bump breaks
// the build, regenerate (`go run github.com/99designs/gqlgen generate`) // the build, regenerate (`go run github.com/99designs/gqlgen generate`)