diff --git a/CLAUDE.md b/CLAUDE.md index ddccde3..d4ef9be 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,7 +62,7 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi. **Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`. -**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. +**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/nginx/payloads.log` via `nginx/payload_log.conf`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. ## Backend Structure diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 1b7e81a..bc8c2df 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -65,6 +65,8 @@ backend icecast2 gitea sb sb-pub python | | | vue | `vue` | 5173 (dev only) | `/` (dev only) | no | | certbot | `certbot` | — | — | no | | cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) | +| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no | +| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no | Container names come from `.env`, and nginx builds its upstreams from the same variables. **Renaming a `*_HOST` value renames the container and repoints nginx @@ -333,7 +335,7 @@ of deleting the directory: | `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. | | `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data | | `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea | -| `./logs` | Backend logs | | +| `./logs` | Backend logs (`go.log`); nginx's JSON request-body log in `logs/nginx/payloads.log` | The payload log grows without bound; rotate it on the host (§7, "Incoming request bodies") | | `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git | | `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public | @@ -467,6 +469,40 @@ docker compose ps # note: `vue` Exited(0) is correct docker compose logs certbot # issuance / renewal outcomes ``` +Or browse every container's logs at `https://www./dozzle/` (admin +login required). + +**Incoming request bodies.** nginx writes one JSON line per request, body +included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The +`traffic` container tails it, so in Dozzle pick **traffic** and each request +renders as fields you can search. From a shell: + +``` +tail -f logs/nginx/payloads.log | jq 'select(.method=="POST")' +jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log +``` + +Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]` +(that covers every login and the refresh call). Bodies over 64 KB, i.e. +uploads, are logged with an empty `body`, and responses are never logged. + +The file is never rotated by the stack. On the Pi, add +`/etc/logrotate.d/web_server`: + +``` +/home//web_server/logs/nginx/*.log { + weekly + rotate 4 + compress + missingok + notifempty + copytruncate +} +``` + +`copytruncate` because nginx keeps the file open; `tail -F` in `traffic` +follows the truncation. + **Reset the database** — destructive; wipes the app database **and Gitea's**: ``` diff --git a/backend/README.md b/backend/README.md index 9344cf9..30aae45 100644 --- a/backend/README.md +++ b/backend/README.md @@ -176,7 +176,6 @@ for the things GraphQL cannot do: | `/notes/*path` | streams a file download, not JSON | | `/ws` | WebSocket upgrade | | `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working | -| `/admin/logs` | files on disk, not the data model | ## Calling the Python service diff --git a/backend/handlers/handle_admin.go b/backend/handlers/handle_admin.go deleted file mode 100644 index eecb835..0000000 --- a/backend/handlers/handle_admin.go +++ /dev/null @@ -1,92 +0,0 @@ -package handlers - -import ( - "net/http" - "os" - "strings" - - "github.com/gin-gonic/gin" -) - -// This file backs the admin diagnostics panel's log tail. It is an admin-only -// REST endpoint rather than GraphQL because it reads the filesystem — outside -// the data model the GraphQL schema describes. - -// logTailBytes and logTailLines bound how much of the log file one request -// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is -// cheap even on the Pi. -const ( - logTailBytes = 256 << 10 - logTailLines = 500 -) - -// Logs backs GET /admin/logs. It returns the tail of the backend's own log -// file (go.log — Gin traffic plus application log lines), which lives on the -// bind-mounted ./logs volume. -// -// Why tail and not offer a range: the panel wants "what happened recently", -// and the file can grow unboundedly between rotations, so anything else -// invites reading the whole thing into memory. -func (store *Store) Logs(ctx *gin.Context) { - lines, size, err := tailLogFile(logPath) - if err != nil { - // The mount being absent is a deployment problem worth surfacing - // distinctly from "log file empty". - ctx.JSON(http.StatusInternalServerError, gin.H{"error": "log unavailable: " + err.Error()}) - return - } - - ctx.JSON(http.StatusOK, gin.H{"lines": lines, "total_bytes": size}) -} - -// logPath matches the file main.go opens for gin.DefaultWriter. -const logPath = "/backend/logs/go.log" - -// tailLogFile returns the last logTailLines lines of a file, reading at most -// logTailBytes from the end. Split out from the handler so the offset and -// partial-line rules are testable without a filesystem mount. -func tailLogFile(path string) ([]string, int64, error) { - f, err := os.Open(path) - if err != nil { - return nil, 0, err - } - defer f.Close() - - info, err := f.Stat() - if err != nil { - return nil, 0, err - } - - // Read from near the end rather than head-to-toe so the read stays - // constant-size regardless of how old the file is. - start := int64(0) - if info.Size() > logTailBytes { - start = info.Size() - logTailBytes - } - buf := make([]byte, info.Size()-start) - if len(buf) > 0 { - if _, err := f.ReadAt(buf, start); err != nil { - return nil, 0, err - } - } - - // Starting mid-file almost certainly lands mid-line; drop that fragment - // so the panel never renders a truncated first entry. - text := string(buf) - if start > 0 { - if i := strings.IndexByte(text, '\n'); i >= 0 { - text = text[i+1:] - } - } - - text = strings.TrimRight(text, "\n") - if text == "" { - return []string{}, info.Size(), nil - } - - lines := strings.Split(text, "\n") - if len(lines) > logTailLines { - lines = lines[len(lines)-logTailLines:] - } - return lines, info.Size(), nil -} diff --git a/backend/handlers/handle_admin_test.go b/backend/handlers/handle_admin_test.go deleted file mode 100644 index 6f26ba2..0000000 --- a/backend/handlers/handle_admin_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package handlers - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -// tailLogFile's rules that are easy to get wrong: the line cap, and dropping -// the partial first line when the read started mid-file. - -func writeLog(t *testing.T, content string) string { - t.Helper() - path := filepath.Join(t.TempDir(), "go.log") - if err := os.WriteFile(path, []byte(content), 0o644); err != nil { - t.Fatalf("writing fixture: %v", err) - } - return path -} - -func TestTailLogFileCapsLines(t *testing.T) { - var b strings.Builder - for range logTailLines + 50 { - b.WriteString("line\n") - } - lines, _, err := tailLogFile(writeLog(t, b.String())) - if err != nil { - t.Fatalf("tailLogFile: %v", err) - } - if len(lines) != logTailLines { - t.Fatalf("got %d lines, want the cap of %d", len(lines), logTailLines) - } -} - -func TestTailLogFileDropsPartialFirstLine(t *testing.T) { - // A file larger than the byte window: the read starts mid-file, so the - // first line it sees is a fragment and must be discarded. - filler := strings.Repeat("x", 100) + "\n" - var b strings.Builder - for b.Len() < logTailBytes+len(filler) { - b.WriteString(filler) - } - b.WriteString("FINAL\n") - - lines, _, err := tailLogFile(writeLog(t, b.String())) - if err != nil { - t.Fatalf("tailLogFile: %v", err) - } - if len(lines) == 0 { - t.Fatal("expected some lines") - } - if lines[len(lines)-1] != "FINAL" { - t.Fatalf("last line = %q, want FINAL", lines[len(lines)-1]) - } - // Every surviving line must be whole, i.e. a full filler line. - if got := lines[0]; got != strings.TrimSuffix(filler, "\n") { - t.Fatalf("first line = %q, want a complete filler line", got) - } -} - -func TestTailLogFileEmpty(t *testing.T) { - lines, size, err := tailLogFile(writeLog(t, "")) - if err != nil { - t.Fatalf("tailLogFile: %v", err) - } - if len(lines) != 0 || size != 0 { - t.Fatalf("got %d lines / %d bytes, want 0 / 0", len(lines), size) - } -} - -func TestTailLogFileMissing(t *testing.T) { - if _, _, err := tailLogFile(filepath.Join(t.TempDir(), "absent.log")); err == nil { - t.Fatal("expected an error for a missing log file") - } -} diff --git a/backend/main.go b/backend/main.go index 559d171..07d141f 100644 --- a/backend/main.go +++ b/backend/main.go @@ -178,9 +178,6 @@ func main() { // NOTES admin.GET("/notes/*path", store.GetNoteFile) - // ADMIN DIAGNOSTICS: log tail for the admin panel. - admin.GET("/admin/logs", store.Logs) - // GRAPHQL // GraphQL is assembled by hand rather than with handler.NewDefaultServer // so the transports and extensions below are explicit. diff --git a/docker-compose.yml b/docker-compose.yml index c2e26a6..86304cd 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -117,6 +117,7 @@ services: - python - jobs - activity-tracker + - dozzle networks: app-network: # The site's public names, resolving to this container for everything @@ -142,6 +143,10 @@ services: - uploads:/uploads # The SPA written by the one-shot `vue` container. - vue_dist:/etc/nginx/html + # The JSON request-body log (nginx/payload_log.conf), kept on the host so + # it survives rebuilds and the `traffic` container can tail it. Grows + # without bound unless rotated — see DEPLOYMENT.md. + - ./logs/nginx:/var/log/nginx/payloads # 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 @@ -576,6 +581,40 @@ services: - TRACKER_TZ=${TRACKER_TZ:-} - AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin + # Echoes nginx's JSON request-body log to its own stdout, and does nothing + # else. It exists so Dozzle shows the payloads as a stream of their own, + # rendered as JSON fields, instead of interleaved with nginx's compact access + # log and error output. -F re-opens the file after rotation; -n0 skips the + # backlog on restart, which stays in the file on the host. + traffic: + image: busybox:1.37.0 + container_name: traffic + restart: always + command: ["tail", "-n0", "-F", "/logs/payloads.log"] + network_mode: none + volumes: + - ./logs/nginx:/logs:ro + + # Dozzle: a live, searchable web view of every container's logs, served at + # /dozzle/ behind the admin login (nginx/nginx_routes.conf.template). The + # `traffic` container is the one to watch for incoming request bodies. + # + # The Docker socket is mounted :ro, but that only stops the file being + # replaced — the API behind it is still fully usable, which is effectively + # root on the Pi. Hence: no published port, the admin auth_request in front, + # and container actions and shell left at their default of off. + dozzle: + image: amir20/dozzle:v11.2.0 + container_name: dozzle + restart: always + networks: + - app-network + environment: + - DOZZLE_BASE=/dozzle + - DOZZLE_NO_ANALYTICS=true + volumes: + - /var/run/docker.sock:/var/run/docker.sock:ro + # Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI # server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to # main, executed by the act_runner that lives outside docker (gitea-runner/). diff --git a/nginx/Dockerfile b/nginx/Dockerfile index a0d2093..67d2fd9 100644 --- a/nginx/Dockerfile +++ b/nginx/Dockerfile @@ -1,6 +1,6 @@ # ============================================================================= # nginx image — the public edge. Stock nginx plus two tools, three config -# templates and the two partials they include. +# templates, the two partials they include and two static includes. # # BASE: nginx:1.27, pinned to a minor version. Official nginx images are # multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi @@ -44,5 +44,11 @@ COPY nginx_routes.conf.template /etc/nginx/nginx_routes.conf.template # Static security-header include, referenced from nginx.conf.template (and # any location that sets its own add_header). Not templated — no envsubst. COPY security_headers.conf /etc/nginx/security_headers.conf +# Static http-level include for the JSON request-body log (both configs). Not +# templated: its $request_body etc. are nginx variables, not env vars. +COPY payload_log.conf /etc/nginx/payload_log.conf +# The payload log's directory. Normally a bind mount (./logs/nginx); created +# here so nginx still starts when run without it. +RUN mkdir -p /var/log/nginx/payloads COPY entrypoint.sh /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] diff --git a/nginx/nginx.conf.template b/nginx/nginx.conf.template index ed34021..7f6ecee 100644 --- a/nginx/nginx.conf.template +++ b/nginx/nginx.conf.template @@ -138,6 +138,9 @@ http { access_log /var/log/nginx/access.log compact; + # JSON request-body log for Dozzle; see payload_log.conf. + include /etc/nginx/payload_log.conf; + # nginx's bundled mime.types has no entry for .mjs, so ES modules would be # served as application/octet-stream and browsers refuse to execute them. # This adds the missing mapping without editing the shipped mime.types. diff --git a/nginx/nginx_dev.conf.template b/nginx/nginx_dev.conf.template index 9084c8c..c3efd9a 100644 --- a/nginx/nginx_dev.conf.template +++ b/nginx/nginx_dev.conf.template @@ -62,6 +62,9 @@ http { access_log /var/log/nginx/access.log compact; + # JSON request-body log for Dozzle; see payload_log.conf. + include /etc/nginx/payload_log.conf; + types { text/javascript mjs; } diff --git a/nginx/nginx_routes.conf.template b/nginx/nginx_routes.conf.template index 63e1e08..9cbaee4 100644 --- a/nginx/nginx_routes.conf.template +++ b/nginx/nginx_routes.conf.template @@ -81,6 +81,8 @@ set $upstream_tracker http://activity-tracker:8080; # And the USACO site's. set $upstream_usaco http://usaco:8080; + # And the Dozzle log viewer's. + set $upstream_dozzle http://dozzle:8080; # ---- Backend API ----------------------------------------------------- # Two patterns repeat through every proxied location below: @@ -174,6 +176,29 @@ return 301 /radio/; } + # Dozzle: live view of every container's logs, including the `traffic` + # container's JSON request-body log (see payload_log.conf). It reads + # the Docker socket, so it sits behind the same admin `auth_request` + # as /radio/admin/. No prefix-strip rewrite: DOZZLE_BASE=/dozzle makes + # it serve under the prefix itself. Buffering is off and the read + # timeout long because log tails stream over server-sent events. + location = /dozzle { + return 301 /dozzle/; + } + + location /dozzle/ { + auth_request /internal/auth/admin-validate; + error_page 401 403 = @auth_denied; + proxy_pass $upstream_dozzle; + proxy_http_version 1.1; + proxy_buffering off; + proxy_read_timeout 1h; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + # The icecast ADMIN UI (/radio/admin/*) is a full station-control # surface — kick sources, change metadata — protected only by the # icecast admin password, and it was reachable from the public diff --git a/nginx/payload_log.conf b/nginx/payload_log.conf new file mode 100644 index 0000000..eb39075 --- /dev/null +++ b/nginx/payload_log.conf @@ -0,0 +1,55 @@ +# ============================================================================= +# Payload log: one JSON line per request, body included, for inspecting what +# actually arrives at the edge. Included at http level by BOTH nginx.conf and +# nginx_dev.conf, so it is plain nginx (no envsubst) like security_headers.conf. +# +# WHERE IT GOES +# /var/log/nginx/payloads/ is bind-mounted from ./logs/nginx on the host. +# The `traffic` container tails the file to its stdout so Dozzle (/dozzle/) +# shows it as its own clean stream of JSON. The `compact` access log is +# untouched and still goes to the container's stdout. +# +# WHAT IS NOT CAPTURED +# - Bodies larger than client_body_buffer_size: nginx spools those to a +# temp file and leaves $request_body empty. Uploads therefore log with an +# empty body (their size is still in `len`). +# - Bodies of requests nginx answers itself (redirects, static files): it +# never reads them, so $request_body is empty there too. +# - Responses. nginx cannot log a proxied response body. +# - auth_request subrequests: log_subrequest is off by default. +# ============================================================================= + +# 64k keeps ordinary JSON/GraphQL bodies in memory (the default is 16k on +# 64-bit), which is the only case where $request_body is filled. It is a +# per-request buffer only allocated when a body arrives, so the cost is small. +client_body_buffer_size 64k; + +# Redaction: any body mentioning a password, token or secret is logged as a +# placeholder rather than having the field stripped, because nginx has no JSON +# parser. 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. +# map is evaluated lazily at log time, after the body has been read. +map $request_body $logged_body { + "~*(password|token|secret)" "[redacted]"; + default $request_body; +} + +# escape=json makes each line valid JSON (quotes, newlines and control bytes +# in the body are escaped), so Dozzle renders it as fields and `jq` reads it. +log_format payloads escape=json '{' + '"time":"$time_iso8601",' + '"ip":"$remote_addr",' + '"method":"$request_method",' + '"host":"$host",' + '"uri":"$request_uri",' + '"status":"$status",' + '"rt":"$request_time",' + '"ctype":"$content_type",' + '"len":"$content_length",' + '"referer":"$http_referer",' + '"ua":"$http_user_agent",' + '"body":"$logged_body"' +'}'; + +access_log /var/log/nginx/payloads/payloads.log payloads; diff --git a/vue/README.md b/vue/README.md index 6008db6..0f6f29b 100644 --- a/vue/README.md +++ b/vue/README.md @@ -125,7 +125,7 @@ the Vite proxy in dev). The backend's REST routes go through `src/api.js`, the same idea for plain JSON: ```js -const body = await api.get("/admin/logs", { fallback: "Failed to load logs" }); +const songs = await api.get("/radio/songs", { fallback: "Failed to load songs" }); await api.post("/radio/upload", formData, { fallback: "Upload failed" }); ``` diff --git a/vue/src/api.js b/vue/src/api.js index 87655da..68a65fe 100644 --- a/vue/src/api.js +++ b/vue/src/api.js @@ -4,7 +4,7 @@ * OAuth starts — everything backend/README.md lists as "not GraphQL"). * * It does two things a bare axios call does not: - * - prefixes `/api`, so callers name the route (`api.get("/admin/logs")`); + * - prefixes `/api`, so callers name the route (`api.get("/radio/songs")`); * - turns a failure into an ApiError whose `message` is the backend's * `{"error": "..."}` body when there is one. Every handler reports errors * in that shape, and each view used to dig it out of `err.response` itself. diff --git a/vue/src/views/admin/Admin.vue b/vue/src/views/admin/Admin.vue index baffb66..31fc575 100644 --- a/vue/src/views/admin/Admin.vue +++ b/vue/src/views/admin/Admin.vue @@ -19,7 +19,6 @@ import CreatePlace from "./CreatePlace.vue"; import ManagePages from "./ManagePages.vue"; import ManageUsers from "./ManageUsers.vue"; import ManageRadio from "./ManageRadio.vue"; -import Diagnostics from "./Diagnostics.vue"; const auth = useAuthStore(); @@ -34,7 +33,6 @@ const sections = [ { id: "pages", label: "Pages", component: ManagePages }, { id: "users", label: "Manage Users", component: ManageUsers }, { id: "radio", label: "Manage Radio", component: ManageRadio }, - { id: "diagnostics", label: "Diagnostics", component: Diagnostics }, ]; const active = ref("place"); @@ -71,6 +69,16 @@ function handleLogout() { > {{ section.label }} + + + Logs ↗ +
diff --git a/vue/src/views/admin/Diagnostics.vue b/vue/src/views/admin/Diagnostics.vue deleted file mode 100644 index 5218486..0000000 --- a/vue/src/views/admin/Diagnostics.vue +++ /dev/null @@ -1,110 +0,0 @@ - - - - -