diff --git a/.env.example b/.env.example index 1cd4e8e..17710f7 100644 --- a/.env.example +++ b/.env.example @@ -187,7 +187,8 @@ LIQUIDSOAP_HARBOR_PORT=8001 # --- TLS / identity ---------------------------------------------------------- # 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. -# 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= EMAIL= @@ -198,10 +199,13 @@ EMAIL= # dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves # the container restarting with an error and the site reachable directly. CLOUDFLARE_TUNNEL_TOKEN= -# Cloudflare API token for certbot's DNS-01 challenge (My Profile -> API -# Tokens -> Create Token -> "Edit zone DNS", limited to this zone). Set, the -# certificate renews without any inbound port, so the router's 80/443 -# forwards can close. Blank falls back to HTTP-01 on port 80. +# Cloudflare API token for the DNS-01 challenge (My Profile -> API Tokens -> +# Create Token -> "Edit zone DNS", limited to this zone). Set, the certificate +# renews without any inbound port, so the router's 80/443 forwards can close. +# 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= # --- Third-party API keys (backend) ------------------------------------------ diff --git a/.gitignore b/.gitignore index 47b3433..6702e7c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ icecast2/fallback_music/* !icecast2/fallback_music/.gitkeep certbot/conf certbot/www +# Caddy's certificates, keys and ACME account (docker-compose.yml) +caddy/data/ backend/token/ jobs-data/ usaco-data/ diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 1eff180..91748a8 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -498,6 +498,36 @@ docker compose restart nginx 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:** ``` diff --git a/Makefile b/Makefile index 13fa4f0..71e2fed 100644 --- a/Makefile +++ b/Makefile @@ -13,6 +13,7 @@ # check-python python3 with the venv module # check-vue Node + `npm install` done in vue/ # check-compose / dev Docker with the compose plugin +# check-caddy Docker # 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 @@ -35,7 +36,7 @@ VENV := .venv # changes and skip the install otherwise. 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: @echo "Targets:" @@ -44,11 +45,12 @@ help: @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-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 dev build and run the dev stack (http://localhost)" # 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: 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"; \ 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 # graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved. generate: diff --git a/caddy/.dockerignore b/caddy/.dockerignore new file mode 100644 index 0000000..b88fc29 --- /dev/null +++ b/caddy/.dockerignore @@ -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 diff --git a/caddy/Caddyfile b/caddy/Caddyfile new file mode 100644 index 0000000..8aeffb6 --- /dev/null +++ b/caddy/Caddyfile @@ -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 ` 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 +# ", 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 +# +# A sliding window: at most per per client IP, then 429 +# (turned into 503 by `errors`). Unlike nginx's leaky bucket there is no +# separate burst, so each zone's is nginx's rate and 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 and ; 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 +# +# The same mechanism, but asking GET /auth/validate/ 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