Cut the edge over from nginx and certbot to Caddy
Test and deploy / test (push) Successful in 3m30s
Test and deploy / deploy (push) Has been cancelled

Caddy takes nginx's place in compose: ports 80/443, the fixed address
172.28.255.251 that cloudflared pins the public names to, the network
aliases, the healthcheck and the autoheal label. nginx and certbot are
removed from compose; Caddy already holds its own certificates in
./caddy/data, obtained while it ran beside nginx. `traffic` now tails
logs/caddy/payloads.log, and the dev override switches Caddy to its dev
sites instead of putting nginx in DEV_MODE.

Docs and comments that described nginx's behaviour now describe Caddy's:
CLAUDE.md, DEPLOYMENT.md (topology, boot paths, TLS, rate limits, runbook
with a rollback, rough edges), the READMEs, .env.example and the comments
in the backend, Python service, Vue source and infra files. nginx/ and
certbot/ stay in the repo as the rollback until this has settled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-17 23:28:28 +00:00
co-authored by Claude Opus 5.5
parent e09b90afaa
commit daa2a465fb
54 changed files with 547 additions and 655 deletions
+1 -1
View File
@@ -22,7 +22,7 @@
# would fail certificate verification without a trust store.
#
# EXPOSE 8080 is documentation only; the port is never published to the host.
# nginx reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
# Caddy reaches it over app-network as BACKEND_HOST:BACKEND_PORT.
#
# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and
# amd64 (a dev laptop) with no platform pin.
+7 -7
View File
@@ -1,11 +1,11 @@
# Backend
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
The Go API for adam-french.co.uk. It is one process behind Caddy, serving a
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
that needs Claude is asked of the Python service, not called from here.
Nginx strips the `/api` prefix before proxying, so a browser request to
Caddy strips the `/api` prefix before proxying, so a browser request to
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
sees it.
@@ -33,7 +33,7 @@ graph/ GraphQL layer
## Request lifecycle
1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and
1. Caddy terminates TLS, applies its own rate limits, strips `/api`, and
proxies to this service.
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
that `ClientIP()` — which the login rate limiter keys on — cannot be
@@ -65,7 +65,7 @@ graph/ GraphQL layer
and will transparently refresh, so returning admins are recognised without a
visible re-login.
- `GET /auth/validate/:permission` is the same for one named permission
(200 / 403 / 401, and 404 for a key that does not exist). It backs nginx's
(200 / 403 / 401, and 404 for a key that does not exist). It backs Caddy's
*permission gate*, which lets a non-admin account into one service — the
receipt printer at `/receipt/` — without making it an admin. Grantable keys
are the registry `services.PermissionTypes` (`services/permissions.go`);
@@ -73,7 +73,7 @@ graph/ GraphQL layer
Users tab (`setUserPermissions`). Admins pass every permission check. The
check reads the user row, not the token, so a grant or revoke applies on
the next request. On 200 it returns the username in `X-Auth-User`, which
nginx forwards to the gated service as `X-Remote-User`.
Caddy forwards to the gated service as `X-Remote-User`.
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
is revoked server-side, and a token that has already been issued stays valid
until it expires. The same is true of demoting an admin: it takes effect on
@@ -195,7 +195,7 @@ no Anthropic client and does not read `CLAUDE_API_KEY`. (The job tracker at
`/jobs/` is a separate app with its own Claude calls.) It reaches the
internal routes directly over the Docker network
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
nginx, which answers 404 for `/py/internal/`:
Caddy, which answers 404 for `/py/internal/`:
| route | caller | sends | gets back |
| --- | --- | --- | --- |
@@ -244,7 +244,7 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
to show them. Public files go to the Garage bucket wrapped in
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
(nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket
(the edge cannot gate a bucket). Caddy serves `/uploads/` from the bucket
first and disk second, so either store's files work at the same URL. A new
handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind
admin-only `GET /uploads`, for the canvas's upload picker) returns the union
+2 -2
View File
@@ -22,8 +22,8 @@ var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-
const maxSlugLen = 100
// reservedFirstSegments are paths a page could never be reached at, because
// nginx or one of the SPA's own routes answers them first (see
// nginx/nginx_routes.conf.template and vue/src/router/index.js), plus the
// Caddy or one of the SPA's own routes answers them first (see
// caddy/routes.caddy and vue/src/router/index.js), plus the
// landing page's key "index", whose boxes a page of the same slug would
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
// pages under it and the home page /stp are all canvas pages.
+1 -1
View File
@@ -20,7 +20,7 @@ func TestValidateSlug(t *testing.T) {
{"shrines", true}, // the index is a canvas page too
{"shrines/demoman", true}, // no longer an SPA route
{"admin/pages", false}, // under an SPA route
{"jobs/x", false}, // under an nginx route
{"jobs/x", false}, // under a Caddy route
{"stp", true}, // the home page is a canvas page too
{"stp2", false}, // an SPA route
{"index", false}, // the landing canvas's key
+1 -1
View File
@@ -10,7 +10,7 @@ type User {
}
# One grantable service, from services.PermissionTypes: `key` is what is
# stored and what nginx gates on, `label` and `path` are for display.
# stored and what Caddy gates on, `label` and `path` are for display.
type PermissionType {
key: String!
label: String!
+9 -8
View File
@@ -93,7 +93,7 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
}
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
// decide whether to show admin UI, nginx's admin gate calls as an
// decide whether to show admin UI, Caddy's admin gate calls as an
// auth_request, and the jobs container calls with the visitor's cookies. It
// answers with a bare status code and no body: 200 admin, 403 authenticated
// but not admin, 401 not authenticated.
@@ -114,11 +114,11 @@ func (store *Store) ValidateAdmin(ctx *gin.Context) {
})
}
// ValidatePermission backs GET /auth/validate/:permission, nginx's permission
// ValidatePermission backs GET /auth/validate/:permission, Caddy's permission
// gate (see services/permissions.go). Same bare-status contract and refresh
// fallback as ValidateAdmin — 200 allowed, 403 signed in without the
// permission, 401 not signed in — plus 404 for a key that is not in
// services.PermissionTypes, so a typo in an nginx location fails closed and
// services.PermissionTypes, so a typo in a Caddy route fails closed and
// visibly rather than as a 403 that looks like a missing grant.
//
// The decision reads the user row, not the token, for admins as well: a
@@ -141,9 +141,10 @@ func (store *Store) ValidatePermission(ctx *gin.Context) {
// allow receives the access token's claims, or nil when the caller was
// identified from the refresh token (which carries no authorisation claims).
//
// On 200 the username goes back in X-Auth-User, which nginx can lift with
// auth_request_set and hand to the service behind the gate, so that service
// knows who is using it without having accounts of its own.
// On 200 the username goes back in X-Auth-User, which Caddy's forward_auth
// copies onto the proxied request (as X-Remote-User for /receipt/), so the
// service behind the gate knows who is using it without having accounts of
// its own.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
accessToken, err := ctx.Cookie("access_token")
if err == nil {
@@ -287,10 +288,10 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
// Login backs POST /auth/login. The user object it returns omits the password
// because models.User tags that field `json:"-"`.
func (store *Store) Login(ctx *gin.Context) {
// Per-IP limit (5/min) on top of nginx's own login rate limit.
// Per-IP limit (5/min) on top of Caddy's own login rate limit.
// ctx.ClientIP is only trustworthy because main.go pins the trusted
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
// client talking through nginx.
// client talking through Caddy.
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
return
+2 -2
View File
@@ -34,8 +34,8 @@ type ExtractedRowingData struct {
Distance uint64 `json:"distance"`
}
// rowingReadPath is the Python route. It is internal: nginx refuses
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
// rowingReadPath is the Python route. It is internal: Caddy refuses
// /py/internal/ and the route itself refuses anything Caddy forwarded, so the
// only way in is the direct container-to-container call services.CallPython
// makes.
const rowingReadPath = "/internal/rowing/read"
+1 -1
View File
@@ -32,7 +32,7 @@ func TestReadRowingDisplayRequestAndReply(t *testing.T) {
var forwarded bool
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
// The Python route treats either header as "came through nginx" and
// The Python route treats either header as "came through Caddy" and
// answers 404, so this call must never carry them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+1 -1
View File
@@ -255,7 +255,7 @@ func TestRequestIsAdmin(t *testing.T) {
// --- Permission gate ------------------------------------------------------
// An unknown key must be refused before any session lookup (Store has no DB
// or Auth here, so reaching one would panic): it is how a typo in an nginx
// or Auth here, so reaching one would panic): it is how a typo in a Caddy
// location shows up as a 404 rather than as a missing grant.
func TestValidatePermissionUnknownKey(t *testing.T) {
gin.SetMode(gin.TestMode)
+1 -1
View File
@@ -34,7 +34,7 @@ type Store struct {
LoginLimiter *services.RateLimiter
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass nginx, all through
// slash. Used for the calls that bypass Caddy, all through
// services.CallPython: reading a rowing display photo (handle_rowing.go).
PythonURL string
+4 -4
View File
@@ -50,7 +50,7 @@ func main() {
r.Use(gin.LoggerWithFormatter(services.TrafficLogFormatter))
r.Use(gin.Recovery())
// Only the Docker network nginx sits on may set X-Forwarded-For. Without
// Only the Docker network Caddy sits on may set X-Forwarded-For. Without
// this pin any client could spoof its IP and defeat the per-IP login rate
// limiter, which keys on ctx.ClientIP(). The CIDR must match the network
// defined in docker-compose.yml.
@@ -115,7 +115,7 @@ func main() {
steamID := os.Getenv("STEAM_ID")
// PYTHON SERVICE
// Called directly over the Docker network, not through nginx, for its
// Called directly over the Docker network, not through Caddy, for its
// /internal/ Claude route (services/python_call.go). The defaults
// mirror docker-compose.yml, where both variables are optional.
pythonHost := os.Getenv("PYTHON_HOST")
@@ -145,7 +145,7 @@ func main() {
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
// 5 login attempts per IP per minute, applied by both the REST handler
// and the GraphQL login mutation. Nginx rate-limits the login route too.
// and the GraphQL login mutation. Caddy rate-limits the login route too.
loginLimiter := services.NewRateLimiter(5, time.Minute)
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads}
@@ -153,7 +153,7 @@ func main() {
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters.
//
// Paths below have no /api prefix: nginx strips it before proxying.
// Paths below have no /api prefix: Caddy strips it before proxying.
protected := r.Group("/", store.AuthMiddlewear)
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
+5 -5
View File
@@ -10,17 +10,17 @@ import (
// service (the receipt printer, say) without being made an admin.
//
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// nginx gates a service on one key by asking GET /auth/validate/<key>
// Caddy gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping that location's
// nginx gate from /internal/auth/admin-validate to the permission gate (see
// "Permission gate" in nginx/nginx_routes.conf.template).
// Adding a grantable service is one entry below plus swapping its route in
// caddy/routes.caddy from `import admin_gate` to `import permission_gate
// <key>` (the snippet is in caddy/Caddyfile).
// PermissionType describes one grantable service. Key is what is stored and
// what nginx names; Label and Path are for the admin panel's checkboxes and
// what Caddy names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct {
Key string
+1 -1
View File
@@ -19,7 +19,7 @@ func TestValidPermission(t *testing.T) {
}
}
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
// Keys must be URL-path safe: Caddy splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{}
for _, p := range PermissionTypes {
+1 -1
View File
@@ -16,7 +16,7 @@ import (
// (handlers/handle_rowing.go); the job posting reader, email classifier and
// lead scorer went with the job tracker to its own repo.
//
// The routes are internal in a specific sense: nginx answers 404 for
// The routes are internal in a specific sense: Caddy answers 404 for
// /py/internal/, and each route itself refuses a request carrying a proxy
// header, so the only way in is this direct container-to-container call. That
// is why the request below sets nothing but Content-Type.
+1 -1
View File
@@ -36,7 +36,7 @@ func TestCallPythonRequestAndReply(t *testing.T) {
)
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type")
// The Python routes treat either header as "came through nginx" and
// The Python routes treat either header as "came through Caddy" and
// answer 404, so the helper must never send them.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
+1 -1
View File
@@ -12,7 +12,7 @@ import (
// RateLimiter is an in-memory sliding-window limiter keyed by an arbitrary
// string (in practice the client IP). It is process-local: restarting the
// backend clears every window, and a multi-replica deployment would limit
// per replica rather than globally. Nginx applies its own rate limits in
// per replica rather than globally. Caddy applies its own rate limits in
// front of this, so this layer is a second line of defence, not the only one.
type RateLimiter struct {
mu sync.Mutex
+5 -5
View File
@@ -11,7 +11,7 @@ import (
// site owner scanning the log for "who is using my site". Two goals:
//
// 1. Quietness. The log is flooded by traffic that is not a human visit:
// nginx auth_request subrequests (/auth/validate-admin, re-run for every
// Caddy forward_auth subrequests (/auth/validate-admin, re-run for every
// admin page hit), the front end's own polling (`/auth/refresh_token`,
// home-data refreshes), and Vite dev asset fetches. Each is collapsed to
// a single terse line, or dropped entirely when repeated in a short
@@ -24,7 +24,7 @@ import (
// logQuietDrop lists paths whose 2xx responses are dropped outright. These
// are all heartbeat-style endpoints: identical every few seconds, no signal.
var logQuietDrop = map[string]bool{
"/auth/validate-admin": true, // nginx auth_request subrequest
"/auth/validate-admin": true, // Caddy forward_auth subrequest
"/auth/refresh": true, // front-end token refresh
"/auth/check": true, // front-end session check
}
@@ -76,7 +76,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
fmt.Sprintf("%.0f%s", float64(latency), unit), marker)
// Visitor traffic gets the IP appended — the "who". Infrastructure
// traffic (nginx's own feet on the internal subnet) already has its IP
// traffic (the edge's own feet on the internal subnet) already has its IP
// implied and is left lean.
if params.StatusCode >= 400 || logIsInterestingClient(params.ClientIP) {
line += " " + params.ClientIP
@@ -86,10 +86,10 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
}
// logIsInterestingClient reports whether a client IP is likely an actual
// visitor rather than infrastructure. nginx proxies everything, so the IPs
// visitor rather than infrastructure. Caddy proxies everything, so the IPs
// that appear are either forwarded-from-humans or the ingress itself.
func logIsInterestingClient(ip string) bool {
// Docker's bridge network: nginx's own feet. Not a visitor.
// Docker's bridge network: the edge's own feet. Not a visitor.
return !startsWith(ip, "172.28.")
}
+10 -10
View File
@@ -34,26 +34,26 @@ import (
//
// WHERE FILES GO
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
// the `uploads` volume as a fallback for when Garage refuses a write. nginx
// the `uploads` volume as a fallback for when Garage refuses a write. Caddy
// mirrors that: /uploads/<name> is fetched from the bucket first and the
// volume second (nginx.conf.template), so the URL is the same wherever the
// volume second (caddy/routes.caddy), so the URL is the same wherever the
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
// the only store.
// Private files (admin-only chat attachments) always go to the volume, under
// /uploads/private/, which nginx gates behind an admin check. nginx can't
// /uploads/private/, which Caddy gates behind an admin check. Caddy can't
// sign S3 requests, so it has no way to gate a bucket.
//
// Everything public is reachable by anyone who has the URL, with no login.
// That is why the type checks below are strict, and why names are random.
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
// disk or the bucket; nginx rate-limits the route as well.
// disk or the bucket; Caddy rate-limits the route as well.
const MaxUploadSize = 10 << 20 // 10MB
// UploadType describes one allowed file extension.
type UploadType struct {
// ContentType is stored with the file and served back with it. Garage
// returns exactly this, and the browser renders by it: nginx adds
// returns exactly this, and the browser renders by it: Caddy adds
// `nosniff`, so a wrong type means the file doesn't display.
ContentType string
// SniffPrefix is what http.DetectContentType must report for the file's
@@ -100,7 +100,7 @@ type Uploads struct {
private FileStore
}
// URL prefixes the files are served under; nginx owns both paths.
// URL prefixes the files are served under; Caddy owns both paths.
const (
publicURLPrefix = "/uploads/"
privateURLPrefix = "/uploads/private/"
@@ -238,7 +238,7 @@ type FileStore interface {
type DiskFileStore struct{ Dir string }
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
// 0755 and 0644 so nginx, a different user, can reach and read the files.
// 0755 and 0644 so the edge, in another container, can reach and read the files.
if err := os.MkdirAll(d.Dir, 0755); err != nil {
return err
}
@@ -334,7 +334,7 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea
// List pages through the whole bucket. Keys containing "/" are skipped: they
// are not uploads (Save never makes one) but something put under a prefix by
// hand, and nginx's /uploads/<name> only ever serves a top-level name anyway.
// hand, and Caddy's /uploads/<name> only ever serves a top-level name anyway.
func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
@@ -358,7 +358,7 @@ func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
}
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
// Fallback instead. The upload still succeeds and its URL still works (nginx
// Fallback instead. The upload still succeeds and its URL still works (Caddy
// looks in both places), so a Garage outage costs a log line rather than
// broken uploads.
type FallbackFileStore struct {
@@ -378,7 +378,7 @@ func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r i
return f.Fallback.Put(ctx, key, contentType, r, size)
}
// List is the union of both stores, since nginx serves from both: the
// List is the union of both stores, since Caddy serves from both: the
// fallback holds whatever was written while the primary was down (and, on
// the live volume, the pre-Garage copies). A name in both is listed once,
// with the primary's details. A primary that can't list is logged and the