Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99fe175ebf | ||
|
|
931b02c9e4 | ||
|
|
148b94959d | ||
|
|
da2ab9fb17 | ||
|
|
8b902350ad | ||
|
|
3764ea9c0b | ||
|
|
299b5f5224 | ||
|
|
af50e6c8ab | ||
|
|
810d3118b3 | ||
|
|
b832dd68b4 | ||
|
|
d3f722d077 | ||
|
|
71344a1f8d | ||
|
|
307268fbea | ||
|
|
2786bce022 | ||
|
|
26f312e307 | ||
|
|
b8670246a8 | ||
|
|
94eaa8e239 | ||
|
|
f8d48ba9af | ||
|
|
5827fb3ddd | ||
|
|
6dd15414e9 | ||
|
|
76735f0552 | ||
|
|
d843b0baf1 | ||
|
|
8d7606bbe8 | ||
|
|
e25fbbab96 |
@@ -0,0 +1,34 @@
|
||||
# .deprecated
|
||||
|
||||
STATUS: nothing in here is live. No compose file, nginx template or script
|
||||
references this directory. It is kept, not deleted, in line with the repo's
|
||||
"legacy is kept" convention; the full history is also in git.
|
||||
|
||||
## quartz/
|
||||
|
||||
The static-site build that used to serve `/notes/`. Replaced by the read-only
|
||||
`silverbullet-public` service (PR #6). Its compose service and nginx route were
|
||||
removed at that point; only the build context survives here.
|
||||
|
||||
## hasura/
|
||||
|
||||
Admin-only DB console that was proxied at `/hasura/`.
|
||||
|
||||
- `docker-compose.hasura.yml` — the service, verbatim.
|
||||
- `nginx-locations.conf` — the upstream variable and `location` blocks that
|
||||
were in both `nginx.conf.template` and `nginx_dev_common.conf.template`.
|
||||
|
||||
To bring it back: layer the compose file
|
||||
(`docker compose -f docker-compose.yml -f .deprecated/hasura/docker-compose.hasura.yml up`),
|
||||
paste the nginx blocks back into both templates, re-add `${HASURA_HOST}
|
||||
${HASURA_PORT}` to `ENVSUBST_VARS` in `nginx/entrypoint.sh`, and set
|
||||
`HASURA_HOST`, `HASURA_PORT` and `HASURA_GRAPHQL_ADMIN_SECRET` in `.env`. Dev
|
||||
mode additionally set `HASURA_GRAPHQL_ENABLE_CONSOLE` and
|
||||
`HASURA_GRAPHQL_DEV_MODE` to `"true"`.
|
||||
|
||||
## autoheal/
|
||||
|
||||
Watchdog that restarted any container docker marked `unhealthy` (only `backend`
|
||||
and `python` define healthchecks). It mounts the docker socket, which is
|
||||
effectively root on the host. To bring it back, layer
|
||||
`docker-compose.autoheal.yml` the same way as above.
|
||||
@@ -0,0 +1,27 @@
|
||||
# STATUS: deprecated — not part of the stack. See ../README.md for how to bring
|
||||
# it back. Kept verbatim from docker-compose.yml.
|
||||
services:
|
||||
# Watchdog: docker itself marks a container `unhealthy` but never acts on it.
|
||||
# autoheal polls the docker socket and restarts anything that goes unhealthy.
|
||||
# AUTOHEAL_CONTAINER_LABEL=all means "watch every container that defines a
|
||||
# healthcheck" (i.e. backend and python) rather than only labelled ones.
|
||||
# It mounts the docker socket, which is effectively root on the host — that
|
||||
# is the price of the feature. Because of that the image is pinned BY DIGEST,
|
||||
# not by a floating tag: `:latest` meant any future push to Docker Hub would
|
||||
# silently gain root on the Pi at the next `docker compose pull`/`up`. The
|
||||
# digest below is a multi-arch index (it includes linux/arm64, which is what
|
||||
# the Pi pulls) and was the content of `willfarrell/autoheal:latest` at the
|
||||
# time of pinning. To bump it: pull the new tag, `docker image inspect
|
||||
# willfarrell/autoheal:<tag> --format '{{index .RepoDigests 0}}'`, and paste
|
||||
# the digest here — never go back to a bare tag.
|
||||
# Deliberately NOT on app-network: it talks only to the socket.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal@sha256:4ce976e9033b41426d44633295d6a08f9bc5929b27866352d91b31d4f6b26447
|
||||
container_name: autoheal
|
||||
restart: always
|
||||
environment:
|
||||
- AUTOHEAL_CONTAINER_LABEL=all
|
||||
- AUTOHEAL_INTERVAL=30
|
||||
- AUTOHEAL_START_PERIOD=60
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
@@ -0,0 +1,23 @@
|
||||
# STATUS: deprecated — not part of the stack. See ../README.md for how to bring
|
||||
# it back. Kept verbatim from docker-compose.yml, so it still relies on that
|
||||
# file's `db` service and `app-network`, and must be layered on top of it.
|
||||
services:
|
||||
# Admin-only DB browser, reached at /hasura/. Console and dev mode are OFF in
|
||||
# production (turned on by the dev override). It is additionally gated in
|
||||
# nginx by an `auth_request` subrequest to the backend's /auth/validate-admin,
|
||||
# so an admin cookie is required before the request ever reaches Hasura —
|
||||
# the admin secret alone is not the only line of defence.
|
||||
hasura:
|
||||
image: hasura/graphql-engine:v2.44.0
|
||||
container_name: "${HASURA_HOST}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||||
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
|
||||
HASURA_GRAPHQL_DEV_MODE: "false"
|
||||
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
|
||||
@@ -0,0 +1,21 @@
|
||||
# STATUS: deprecated. The /hasura/ blocks removed from nginx.conf.template and
|
||||
# nginx_dev_common.conf.template (identical in both). See ../README.md.
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
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;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
+59
-20
@@ -5,18 +5,28 @@
|
||||
# same file, and it is worth knowing which is which:
|
||||
# 1. ${VAR} interpolation in docker-compose.yml. Done by the compose CLI when
|
||||
# it parses the file, before any container exists. This is how container
|
||||
# names, published ports and the Hasura database URL are built.
|
||||
# names and published ports are built.
|
||||
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
||||
# variables inside that container. nginx, backend, db, icecast2,
|
||||
# certbot and gitea all do this.
|
||||
# The `python` service deliberately does neither wholesale — it uses an
|
||||
# explicit `environment:` allow-list of three variables, so it never sees the
|
||||
# database password or any API key.
|
||||
# The `python` and `jobs` services deliberately do neither wholesale — each
|
||||
# uses an explicit `environment:` allow-list, so neither sees the site's
|
||||
# database password, the JWT secret, or any key it does not use.
|
||||
#
|
||||
# HOW TO USE
|
||||
# cp .env.example .env then fill in every value.
|
||||
# Distribute to the Raspberry Pi with ./sync-secrets.sh (newer file wins in
|
||||
# either direction — see that script's header before editing on both hosts).
|
||||
# On the Pi, keys and settings can also be changed from the admin panel's
|
||||
# Environment tab, which rewrites this file in place (previous version kept
|
||||
# as .env.bak) and restarts what reads the change. See "Editing from the
|
||||
# admin panel" in DEPLOYMENT.md.
|
||||
#
|
||||
# ADDING A VARIABLE
|
||||
# Add it to backend/services/env_registry.json as well. That file decides
|
||||
# whether the admin panel shows it, whether it is editable there, and which
|
||||
# services are restarted when it changes; a backend test fails if the two
|
||||
# lists differ.
|
||||
#
|
||||
# CAUTION: an unset variable does not fail loudly. envsubst renders it as an
|
||||
# empty string, which for a password field means "no password". After editing,
|
||||
@@ -27,15 +37,20 @@
|
||||
# =============================================================================
|
||||
|
||||
# --- Postgres ----------------------------------------------------------------
|
||||
# One instance, two databases: POSTGRES_DB for the Go backend, POSTGRES_GITEA_DB
|
||||
# for Gitea. Only POSTGRES_DB is auto-created on first init; the Gitea one must
|
||||
# be created by hand on a fresh volume.
|
||||
# One instance, three databases: POSTGRES_DB for the Go backend,
|
||||
# POSTGRES_GITEA_DB for Gitea, POSTGRES_JOBS_DB for the job tracker (with its
|
||||
# own role). Only POSTGRES_DB is auto-created on first init; the other two must
|
||||
# be created by hand on a fresh volume (the job tracker's README has the
|
||||
# commands).
|
||||
# POSTGRES_HOST doubles as the db container's name.
|
||||
POSTGRES_USER=
|
||||
POSTGRES_PASSWORD=
|
||||
POSTGRES_DB=
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_HOST=db
|
||||
POSTGRES_JOBS_DB=jobs
|
||||
POSTGRES_JOBS_USER=jobs
|
||||
POSTGRES_JOBS_PASSWORD=
|
||||
|
||||
# --- Gitea -------------------------------------------------------------------
|
||||
# GITEA_HOST is the container name AND the nginx upstream host.
|
||||
@@ -58,7 +73,7 @@ GITEA_RUNNER_HOST=
|
||||
GITEA_RUNNER_NAME=pi-runner
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN=
|
||||
|
||||
# --- Email ingest (backend) --------------------------------------------------
|
||||
# --- Email ingest (job tracker) -----------------------------------------------
|
||||
# EMAIL_BACKEND selects the mail source: "graph" (Microsoft Graph API, OAuth)
|
||||
# or "imap" (fallback; Microsoft has retired IMAP basic auth for outlook.com,
|
||||
# so imap+app-password only works with non-Microsoft providers like Gmail).
|
||||
@@ -67,11 +82,12 @@ GITEA_RUNNER_REGISTRATION_TOKEN=
|
||||
# (default tenant = "consumers"); add a delegated Mail.Read permission with
|
||||
# admin/user consent, and create a client secret. Redirect URI type "Web",
|
||||
# value must live behind the site's real HTTPS origin, e.g.
|
||||
# https://<YOUR_DOMAIN>/email/callback (callback route already exists in the
|
||||
# backend). Backend code exchanges a code there. TenantID must be "consumers"
|
||||
# for a personal outlook.com account.
|
||||
# The first sync prints an authorisation URL into the container log; visit it,
|
||||
# consent, and the refresh token is persisted to backend/token/msgraph_token.json.
|
||||
# https://<YOUR_DOMAIN>/jobs/api/email/callback (served by the job tracker,
|
||||
# which exchanges the code there). TenantID must be "consumers" for a personal
|
||||
# outlook.com account.
|
||||
# The tracker's Settings page (/jobs/settings) shows the authorisation link
|
||||
# until you sign in; the refresh token is persisted to
|
||||
# jobs-data/msgraph_token.json.
|
||||
# OAuth flow reference: https://learn.microsoft.com/en-us/graph/auth-v2-user
|
||||
EMAIL_BACKEND=
|
||||
MSGRAPH_CLIENT_ID=
|
||||
@@ -87,6 +103,23 @@ IMAP_PASSWORD=
|
||||
EMAIL_SYNC_INTERVAL=
|
||||
EMAIL_SYNC_ENABLED=
|
||||
|
||||
# --- Job leads (job tracker) --------------------------------------------------
|
||||
# The lead fetcher polls the sources listed on /jobs/leads and files new
|
||||
# postings in the leads inbox. JOB_LEADS_ENABLED=true runs it on a timer;
|
||||
# "Check now" on that page works whether or not it is set. JOB_LEADS_INTERVAL
|
||||
# is a Go duration (default 6h). Scoring uses CLAUDE_API_KEY, above.
|
||||
# The board sources (Greenhouse, Lever, Ashby) need no key. The two search
|
||||
# sources do, both free:
|
||||
# Adzuna: https://developer.adzuna.com/ (an application id and a key)
|
||||
# Reed: https://www.reed.co.uk/developers/jobseeker
|
||||
# A search source whose key is blank reports that on the page; nothing else
|
||||
# is affected.
|
||||
JOB_LEADS_ENABLED=
|
||||
JOB_LEADS_INTERVAL=
|
||||
ADZUNA_APP_ID=
|
||||
ADZUNA_APP_KEY=
|
||||
REED_API_KEY=
|
||||
|
||||
# --- Services that nginx substitutes but no longer runs -----------------------
|
||||
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
|
||||
# compose service uses them today. Harmless if blank.
|
||||
@@ -154,17 +187,17 @@ DOMAIN=
|
||||
EMAIL=
|
||||
|
||||
# --- Third-party API keys (backend) ------------------------------------------
|
||||
# CLAUDE_API_KEY is used by the python service, which makes every Claude call
|
||||
# in the stack: the rowing photo reader, the job posting reader and the email
|
||||
# pipeline's classifier. The backend no longer calls Claude itself.
|
||||
CLAUDE_API_KEY=
|
||||
# Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5
|
||||
# (the default when blank) or claude-opus-5-5. Editable on the admin panel's
|
||||
# Environment tab, which restarts the python service to apply it.
|
||||
CLAUDE_MODEL=
|
||||
STEAM_API_KEY=
|
||||
STEAM_ID=
|
||||
|
||||
# --- Hasura (admin-only DB console at /hasura/) ------------------------------
|
||||
# Additionally gated by an nginx auth_request against the backend's admin check,
|
||||
# so the admin secret is not the only barrier.
|
||||
HASURA_GRAPHQL_ADMIN_SECRET=
|
||||
HASURA_HOST=hasura
|
||||
HASURA_PORT=8080
|
||||
|
||||
# --- Development-only switch -------------------------------------------------
|
||||
# Leave EMPTY/false in production. docker-compose.dev.yml sets SEED_DB=true for
|
||||
# local work; setting it on the Pi would inject test data into the live site.
|
||||
@@ -174,5 +207,11 @@ SEED_DB=
|
||||
PYTHON_HOST=python
|
||||
PYTHON_PORT=8000
|
||||
|
||||
# --- Job tracker (/jobs/) -----------------------------------------------------
|
||||
# An image built and published by the job-tracker repo's CI. Blank runs
|
||||
# :latest; set a commit sha to pin. Changing it needs
|
||||
# `docker compose pull jobs && docker compose up -d jobs`.
|
||||
JOBS_IMAGE_TAG=
|
||||
|
||||
# TfL Unified API key (500 req/min); used by the Python hotel finder
|
||||
TFL_APP_KEY=
|
||||
|
||||
@@ -1,20 +1,170 @@
|
||||
name: Deploy with Docker Compose
|
||||
# =============================================================================
|
||||
# deploy.yaml — test every push; deploy pushes to main that pass.
|
||||
#
|
||||
# TWO JOBS
|
||||
# test runs on every push, to any branch: `go vet` + `go test` for the
|
||||
# backend and pytest for the Python service. These are the same
|
||||
# checks as `make check-backend` and `make check-python`.
|
||||
# deploy runs only for refs/heads/main, and only if `test` passed
|
||||
# (`needs: test`). Before this gate existed every push to main went
|
||||
# straight to the live site.
|
||||
#
|
||||
# WHERE THIS RUNS, AND WHAT THAT RULES OUT
|
||||
# A self-hosted act_runner on the Pi itself, in HOST mode (see
|
||||
# gitea-runner/run.sh): steps are shell commands on the Pi, not in a job
|
||||
# container. So:
|
||||
# - No host toolchains are assumed. The Pi is known to have git and docker
|
||||
# and nothing else; Go and Python run inside `docker run` containers
|
||||
# pinned to the same base images as backend/Dockerfile (golang:1.26) and
|
||||
# python/Dockerfile (python:3.12-slim). Bump them together.
|
||||
# - No `actions/checkout`. It is a JavaScript action and would need Node on
|
||||
# the host. The source is fetched with plain git instead, from the same
|
||||
# local Gitea SSH remote the deploy step has always used.
|
||||
#
|
||||
# THE LIVE DIRECTORY IS NOT TOUCHED UNTIL TESTS PASS
|
||||
# The site runs out of /home/adamf/deploy/web_server. The test job never
|
||||
# goes near it: it fetches into a separate bare cache repo and exports the
|
||||
# pushed commit to a scratch directory. Only the deploy job, after `test`
|
||||
# is green, does the `git reset --hard` there.
|
||||
#
|
||||
# NOT TESTED HERE: THE VUE BUILD
|
||||
# Deliberately skipped. `docker compose up --build` in the deploy job
|
||||
# already runs the full frontend build (wasm-pack + vite) while building the
|
||||
# vue image, and a failed image build aborts `up` BEFORE any container is
|
||||
# replaced, so the old site keeps serving. Building it a second time here
|
||||
# would cost the Pi several minutes per push to learn nothing new. The same
|
||||
# reasoning does not hold for Go and Python: their images build fine with
|
||||
# failing tests, which is exactly why those are gated here.
|
||||
#
|
||||
# NO pull_request TRIGGER
|
||||
# `push` with no branch filter already covers every branch, including the
|
||||
# head branch of any PR in this repo, so adding pull_request would run the
|
||||
# suite twice per push on a machine with little CPU to spare.
|
||||
# =============================================================================
|
||||
name: Test and deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: self-hosted
|
||||
env:
|
||||
# The commit and ref this push delivered. Passed through env rather
|
||||
# than interpolated into the scripts so a branch name can never be
|
||||
# parsed as shell.
|
||||
SHA: ${{ github.sha }}
|
||||
REF: ${{ github.ref }}
|
||||
REMOTE: ssh://git@localhost:2222/adamf/web_server.git
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
# Bare repo kept between runs so each fetch is incremental (the
|
||||
# history is ~140MB; a fresh clone per push would be slow on the
|
||||
# Pi's SD card). Lives outside the deploy directory on purpose.
|
||||
CACHE: /home/adamf/.cache/web_server-ci/repo.git
|
||||
# This run's source tree, exported from the cache and removed in
|
||||
# the last step. Keyed by commit so two runs cannot share a tree.
|
||||
SRC: /home/adamf/.cache/web_server-ci/src-${{ github.sha }}
|
||||
steps:
|
||||
- name: Export the pushed commit to a scratch directory
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
mkdir -p "$(dirname "$CACHE")"
|
||||
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
|
||||
# Fetch the pushed ref, then export the exact pushed commit.
|
||||
# Using $SHA rather than FETCH_HEAD means that if the branch
|
||||
# has moved on since this run was queued we still test the
|
||||
# commit this run is about, not a newer one.
|
||||
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
|
||||
rm -rf "$SRC"
|
||||
mkdir -p "$SRC"
|
||||
# `git archive` gives a clean tree of tracked files only: no
|
||||
# .git, and nothing left over from an earlier run.
|
||||
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
|
||||
# Do not rely on the shell having pipefail: if the archive
|
||||
# half failed, make sure that is noticed here.
|
||||
test -f "$SRC/backend/go.mod"
|
||||
test -f "$SRC/python/requirements-dev.txt"
|
||||
echo "Exported $SHA ($REF) to $SRC"
|
||||
|
||||
# The whole repo is mounted, not just backend/, because
|
||||
# services/env_manager_test.go reads ../../.env.example to check
|
||||
# it against env_registry.json. Read-only: tests write only to
|
||||
# t.TempDir(), and a read-only mount means the container (root)
|
||||
# cannot leave root-owned files in $SRC that the clean-up step,
|
||||
# running as the runner user, could not delete.
|
||||
#
|
||||
# The two named volumes are the Go module cache and build cache.
|
||||
# Without them every run would re-download every dependency and
|
||||
# recompile gorm, gin and gqlgen from scratch — minutes on a Pi.
|
||||
# They survive `docker image prune` and the weekly maintenance
|
||||
# job; `docker volume rm web_server_ci_gomod web_server_ci_gobuild`
|
||||
# resets them if they ever go bad.
|
||||
- name: Backend - go vet and go test
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC":/src:ro \
|
||||
-w /src/backend \
|
||||
-v web_server_ci_gomod:/go/pkg/mod \
|
||||
-v web_server_ci_gobuild:/root/.cache/go-build \
|
||||
golang:1.26 \
|
||||
sh -c 'go vet ./... && go test ./...'
|
||||
|
||||
# requirements-dev.txt pulls in requirements.txt plus pytest. The
|
||||
# install is repeated every run (the container is thrown away) but
|
||||
# the pip cache volume means it is unpacking cached wheels, not
|
||||
# downloading. Read-only source for the same reason as above, so
|
||||
# bytecode and the pytest cache are switched off rather than left
|
||||
# to fail noisily.
|
||||
- name: Python - pytest
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC":/src:ro \
|
||||
-w /src/python \
|
||||
-v web_server_ci_pip:/root/.cache/pip \
|
||||
-e PYTHONDONTWRITEBYTECODE=1 \
|
||||
python:3.12-slim \
|
||||
sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider'
|
||||
|
||||
# always(): a failed test must not leave a source tree behind per
|
||||
# push. The cache repo is kept; only this run's export goes.
|
||||
- name: Remove the scratch directory
|
||||
if: always()
|
||||
shell: bash
|
||||
run: rm -rf "$SRC"
|
||||
|
||||
deploy:
|
||||
# Both conditions matter: `needs` makes a red test job skip this one,
|
||||
# and the `if` keeps pushes to other branches from deploying at all.
|
||||
needs: test
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Pull changes
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
SHA: ${{ github.sha }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
git config --global --add safe.directory /home/adamf/deploy/web_server
|
||||
git fetch ssh://git@localhost:2222/adamf/web_server.git main
|
||||
# Deploy only the commit the test job just passed. If main
|
||||
# has moved on since this run started, FETCH_HEAD is a newer
|
||||
# commit that THIS run never tested — stop, and let that
|
||||
# commit's own run test and deploy it. Failing (rather than
|
||||
# resetting to $SHA anyway) also means re-running an old run
|
||||
# can never roll the site back to an old commit.
|
||||
if [ "$(git rev-parse FETCH_HEAD)" != "$SHA" ]; then
|
||||
echo "main is at $(git rev-parse FETCH_HEAD), but this run tested $SHA."
|
||||
echo "Not deploying: the run for the newer commit will."
|
||||
exit 1
|
||||
fi
|
||||
git reset --hard FETCH_HEAD
|
||||
|
||||
- name: Run docker compose up
|
||||
@@ -22,7 +172,10 @@ jobs:
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
COMPOSE_BAKE: "false"
|
||||
run: docker compose up -d --build --remove-orphans
|
||||
# The lock is shared with env-apply/apply.py, so a deploy and a
|
||||
# .env change made from the admin panel cannot run compose at
|
||||
# the same time.
|
||||
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker resources
|
||||
run: docker image prune -f
|
||||
|
||||
@@ -21,17 +21,28 @@ jobs:
|
||||
- name: Autoremove obsolete packages
|
||||
run: sudo apt-get -y autoremove --purge
|
||||
|
||||
# Both compose steps below take env-apply/run/lock, the same flock
|
||||
# deploy.yaml and env-apply/apply.py hold while they run compose.
|
||||
# Without it this weekly job could recreate containers at the same
|
||||
# moment a .env edit from the admin panel is being applied (or a
|
||||
# deploy is mid-build), and two `compose up`s racing over the same
|
||||
# project can each recreate a container the other just started,
|
||||
# ending with services built against a half-written .env. flock
|
||||
# blocks until the other holder finishes, so the job waits rather
|
||||
# than fails. The lock is taken per step, not across both: nothing
|
||||
# needs pull and up to be atomic, and holding it for less time
|
||||
# keeps an admin-panel change from waiting behind a long pull.
|
||||
- name: Pull latest base images
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
run: docker compose pull
|
||||
run: flock env-apply/run/lock docker compose pull
|
||||
|
||||
- name: Rebuild and restart containers
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
run: docker compose up -d --build --remove-orphans
|
||||
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker images
|
||||
run: docker image prune -af
|
||||
|
||||
+10
@@ -3,7 +3,13 @@ icecast2/fallback_music/*
|
||||
certbot/conf
|
||||
certbot/www
|
||||
backend/token/
|
||||
jobs-data/
|
||||
.env
|
||||
.env.bak
|
||||
|
||||
# Admin panel -> host hand-off (request and status files, holds secrets)
|
||||
env-apply/run/*
|
||||
!env-apply/run/.gitkeep
|
||||
|
||||
gitea/data/*
|
||||
gitea/config/app.ini
|
||||
@@ -19,6 +25,10 @@ gitea-runner/nohup.out
|
||||
# Python bytecode
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
|
||||
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
|
||||
/.venv/
|
||||
|
||||
# Generated WASM output
|
||||
vue/src/wasm/
|
||||
|
||||
@@ -4,6 +4,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Build & Run Commands
|
||||
|
||||
### Check everything
|
||||
|
||||
```
|
||||
make check
|
||||
```
|
||||
|
||||
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, and `docker compose config` for both compose files. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing.
|
||||
|
||||
### Full stack (dev mode, HTTP only)
|
||||
|
||||
```
|
||||
@@ -24,7 +32,7 @@ docker compose up --build
|
||||
cd vue && npm run dev
|
||||
```
|
||||
|
||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
||||
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`; the targets default to `localhost:8080`, `:3000`, `:8000` and `:8000` and are overridden with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (shell or `vue/.env.local`). Compose publishes none of the backend, Python or Icecast ports to the host, and `/py` and `/radio` share a default, so set these to wherever the services really are — see the comment in `vue/vite.config.js`.
|
||||
|
||||
### Frontend build
|
||||
|
||||
@@ -32,6 +40,8 @@ Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`
|
||||
cd vue && npm run build
|
||||
```
|
||||
|
||||
`npm run build` compiles the Rust crate first and needs `wasm-pack`. `npm run build:js` (plain `vite build`) is the check to use when only the JS changed and `src/wasm/` already exists.
|
||||
|
||||
### Regenerate GraphQL (after editing schema files)
|
||||
|
||||
```
|
||||
@@ -48,26 +58,30 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
|
||||
|
||||
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode).
|
||||
|
||||
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`.
|
||||
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), chosen on the admin panel's Environment tab; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
|
||||
|
||||
**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 (5/min).
|
||||
**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 in `env_registry.json` with `services: ["jobs"]`.
|
||||
|
||||
**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 (5/min). 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.
|
||||
|
||||
## Backend Structure
|
||||
|
||||
- `main.go` — entry point: wires up DB, services, router
|
||||
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, ClaudeClient, Auth, etc. Passed to all handlers
|
||||
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, Auth, Notes, etc. Passed to all handlers
|
||||
- `handlers/handle_*.go` — REST handlers grouped by domain
|
||||
- `graph/schema/*.graphql` — GraphQL schema files (source of truth)
|
||||
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
|
||||
- `graph/generated.go` — auto-generated by gqlgen, do not edit
|
||||
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
|
||||
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing)
|
||||
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, Claude client, DB seeding
|
||||
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place)
|
||||
- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns)
|
||||
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), the `.env` registry (`env_manager.go`), DB seeding. There is no Claude client in Go any more
|
||||
|
||||
## Frontend Structure
|
||||
|
||||
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData
|
||||
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places. `createCrudStore.js` is the factory behind places; `createMirrorStore.js` is the one behind the home-page slices
|
||||
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines)
|
||||
- `src/components/` — reusable UI components
|
||||
- `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`.
|
||||
@@ -75,11 +89,13 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
|
||||
## Key Patterns
|
||||
|
||||
- **GraphQL models vs GORM models**: `gqlgen.yml` maps GraphQL types directly to GORM models in `backend/models`. The `graph/model/` package has only generated input/payload types.
|
||||
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. There is no token revocation — logout only clears cookies.
|
||||
- **GraphQL resolvers authorise themselves.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. Every resolver that needs auth must check it itself. See `backend/graph/doc.go`.
|
||||
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded).
|
||||
- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`.
|
||||
- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`.
|
||||
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
|
||||
- **Environment tab**: `/admin` → Environment edits `.env` on the Pi. The backend never touches the file: it validates the edit and writes `env-apply/run/request.json`; `env-apply/apply.py`, run on the host by a systemd path unit (`env-apply/install.sh`), rewrites `.env` and recreates only the services that read the change. `backend/services/env_registry.json` is the single list of variables — **add new variables there as well as `.env.example`** (a test enforces it); a variable the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, which a second test checks against the registry, with `editable: false` for anything that renames a container, moves a port or is only read at first init. Secrets are write-only: no endpoint returns one. See "Environment tab" in `backend/README.md`.
|
||||
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail`, whose dedup must see history. Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||
|
||||
## Further documentation
|
||||
|
||||
|
||||
+106
-26
@@ -29,13 +29,13 @@ Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
|
||||
--------------------------------------------- | (same container
|
||||
| | | | | | | as icecast2)
|
||||
v v v v v v | |
|
||||
/api/ /radio/ /gitea/ /hasura/ /notes/ /py/ | |
|
||||
backend icecast2 gitea hasura sb-pub python | |
|
||||
| ^ | | |
|
||||
| | | | |
|
||||
| +------------------|--------------------|---------------+
|
||||
| | |
|
||||
+----------+-----------------+--------------------+
|
||||
/api/ /radio/ /gitea/ /sb/ /notes/ /py/ | |
|
||||
backend icecast2 gitea sb sb-pub python | |
|
||||
| ^ | |
|
||||
| | | |
|
||||
| +---------------------------------------|---------------+
|
||||
| |
|
||||
+----------+--------------------------------------+
|
||||
v
|
||||
+------+
|
||||
| db | postgres:16
|
||||
@@ -43,7 +43,6 @@ backend icecast2 gitea hasura sb-pub python | |
|
||||
|
||||
vue one-shot build container -> writes vue_dist volume -> nginx serves it
|
||||
certbot no ports; shares ./certbot/conf and ./certbot/www with nginx
|
||||
autoheal no network; watches the docker socket and restarts unhealthy containers
|
||||
```
|
||||
|
||||
### Who listens where
|
||||
@@ -53,16 +52,15 @@ backend icecast2 gitea hasura sb-pub python | |
|
||||
| nginx | `nginx` | 80, 443 | — | **80, 443** |
|
||||
| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no |
|
||||
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
|
||||
| hasura | `${HASURA_HOST}` | `${HASURA_PORT}` | `/hasura/` (admin-gated) | no |
|
||||
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
|
||||
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
|
||||
| silverbullet-git | n/a | n/a | none (timer loop) | no |
|
||||
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no |
|
||||
| jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by the app itself) | no |
|
||||
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
|
||||
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
|
||||
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
|
||||
| certbot | `certbot` | — | — | no |
|
||||
| autoheal | `autoheal` | — | — | 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
|
||||
@@ -80,7 +78,7 @@ in one step — never change one without the other.**
|
||||
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
|
||||
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
|
||||
backend down (502s until it appears) instead of refusing to start.
|
||||
- **Admin gate.** `/hasura/`, `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
|
||||
- **Admin gate.** `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
|
||||
subrequest to the backend's `/auth/validate-admin`; a failure redirects to the
|
||||
SPA login. None of these services has any auth of its own at that path.
|
||||
- **Public notes privacy boundary.** `/notes/` is public, and the only thing
|
||||
@@ -88,8 +86,8 @@ in one step — never change one without the other.**
|
||||
nginx deny blocks. SilverBullet's `SB_SPACE_IGNORE` only hides paths from its
|
||||
file *list*; direct `/.fs/` fetches and server-rendered page URLs still serve
|
||||
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
|
||||
adding it to the deny regex in both nginx templates publishes it. See the
|
||||
comment above `location /notes/` in `nginx.conf.template`.
|
||||
adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the
|
||||
comment above `location /notes/` in `nginx_routes.conf.template`.
|
||||
- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads`
|
||||
volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so
|
||||
user-supplied files cannot execute anything on our origin.
|
||||
@@ -116,9 +114,30 @@ docker compose up --build
|
||||
4. Everything else comes up in parallel; `depends_on` here is the plain list
|
||||
form, which waits only for *start*, not readiness.
|
||||
|
||||
On the Pi this is triggered automatically: `.gitea/workflows/deploy.yaml` runs on
|
||||
every push to `main`, fetches over `ssh://git@localhost:2222`, hard-resets the
|
||||
deploy checkout, and runs `docker compose up -d --build --remove-orphans`.
|
||||
On the Pi this is triggered automatically by `.gitea/workflows/deploy.yaml`,
|
||||
which has two jobs:
|
||||
|
||||
- **`test`** runs on every push to any branch. It exports the pushed commit
|
||||
(never the deploy checkout) and runs the backend's `go vet` + `go test` in
|
||||
`golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build is
|
||||
not repeated here: the image build in the deploy step does it, and a failed
|
||||
build leaves the old containers running.
|
||||
- **`deploy`** runs only on `main`, only after `test` passes, and only if the
|
||||
tested commit is still the tip of `main` (so an older run cannot deploy a
|
||||
newer, untested commit). It fetches over `ssh://git@localhost:2222`,
|
||||
hard-resets the deploy checkout, and runs
|
||||
`docker compose up -d --build --remove-orphans` under the
|
||||
`env-apply/run/lock` flock.
|
||||
|
||||
The test job keeps state on the Pi outside the deploy checkout: a bare
|
||||
repository cache at `/home/adamf/.cache/web_server-ci/` and three named
|
||||
volumes (`web_server_ci_gomod`, `web_server_ci_gobuild`, `web_server_ci_pip`).
|
||||
The weekly maintenance workflow's `docker image prune -af` removes the two
|
||||
toolchain images, so the first run after it pulls them again; the volumes
|
||||
survive. Maintenance takes the same flock around its compose steps.
|
||||
|
||||
`make check` runs the same checks locally, plus the Vue build and compose
|
||||
validation — run it before pushing, since a red `test` job blocks the deploy.
|
||||
|
||||
### Development
|
||||
|
||||
@@ -139,7 +158,6 @@ The override layer changes five services and disables one:
|
||||
`:443` serve the whole site, no HSTS, no HTTP→HTTPS redirect.
|
||||
- **backend** — `DEV_MODE`, GraphQL playground and introspection on, a localhost
|
||||
Spotify redirect URI, and **`SEED_DB=true`**.
|
||||
- **hasura** — console and dev mode on.
|
||||
- **python** — `uvicorn --reload` with `python/app` bind-mounted.
|
||||
- **certbot** — put in the `disabled` profile, so it never starts. Let's Encrypt
|
||||
cannot validate localhost anyway.
|
||||
@@ -215,6 +233,8 @@ of deleting the directory:
|
||||
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
|
||||
| `./certbot/www` | ACME challenge webroot | Transient by nature |
|
||||
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. |
|
||||
| `./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. |
|
||||
| `./env-apply/run` | The admin panel's queued `.env` change (`request.json`) and the host's report on it (`status.json`) | Gitignored. Transient, but must be owned by the deploy user, not root — see §5. |
|
||||
| `./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 | |
|
||||
@@ -235,13 +255,22 @@ All configuration lives in **`./.env`** at the repo root, which is gitignored.
|
||||
Two distinct mechanisms read it, and services use both:
|
||||
|
||||
- **`${VAR}` in `docker-compose.yml`** — substituted by the compose CLI at parse
|
||||
time. Builds container names, published ports, the Hasura database URL.
|
||||
time. Builds container names and published ports.
|
||||
- **`env_file: ./.env`** — injects the whole file into the container. Used by
|
||||
nginx, backend, db, icecast2, certbot.
|
||||
|
||||
`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own
|
||||
convention for overriding `app.ini` keys), and `python` receives an explicit
|
||||
three-variable allow-list, so it never sees the database password or any API key.
|
||||
allow-list, so it never sees the database password or any API key other than
|
||||
the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`, plus `CLAUDE_MODEL`,
|
||||
which picks the model). The Python service
|
||||
makes the site's one Claude call (the rowing photo reader); the `jobs` container
|
||||
(the job tracker, built from its own repo) makes its own, and gets a similar
|
||||
allow-list with its own database role. The backend receives `CLAUDE_API_KEY`
|
||||
through `env_file` but does not use it. A new variable for either service has
|
||||
to be added to its allow-list as well as
|
||||
`.env.example` and `backend/services/env_registry.json`; backend tests fail if
|
||||
the three disagree.
|
||||
|
||||
**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two
|
||||
things between this checkout and `adamf@stppi.local:~/deploy/web_server`:
|
||||
@@ -253,6 +282,36 @@ An unset variable is not an error: `envsubst` renders it as an empty string,
|
||||
which for a password field means *no password*. After editing `.env`, confirm
|
||||
with `docker compose config`.
|
||||
|
||||
### Editing from the admin panel
|
||||
|
||||
The **Environment** tab at `/admin` edits `.env` on the Pi without SSH. API
|
||||
keys, OAuth client settings, the email settings and the generated secrets are
|
||||
editable; anything that would rename a container, move a port or lock the
|
||||
backend out of Postgres is shown read-only.
|
||||
|
||||
The backend cannot write `.env` or reach Docker. It queues the change in
|
||||
`./env-apply/run/request.json`, and a systemd path unit on the host runs
|
||||
`env-apply/apply.py`, which:
|
||||
|
||||
1. rewrites `.env` atomically, keeping comments and order, with the previous
|
||||
version saved as **`.env.bak`**;
|
||||
2. runs `docker compose config -q` and restores the backup if compose rejects
|
||||
the file;
|
||||
3. recreates only the services that read the changed variables, plus the
|
||||
backend (`docker compose up -d --no-deps --force-recreate …`);
|
||||
4. writes the outcome to `status.json`, which the panel is polling.
|
||||
|
||||
Only those services are recreated because nginx, db, icecast2 and certbot load
|
||||
the whole file too; a plain `up -d` would restart Postgres for a Steam key.
|
||||
They pick the new file up at the next deploy, which is harmless.
|
||||
|
||||
**The watcher is installed once per host** — see the runbook. Without it the
|
||||
panel still queues the change and says nothing has picked it up.
|
||||
|
||||
A change made this way makes the Pi's `.env` the newer copy, so the next
|
||||
`./sync-secrets.sh` pulls it down to the laptop. The newer-wins caveat above
|
||||
still applies: do not also edit the local copy before syncing.
|
||||
|
||||
---
|
||||
|
||||
## 6. Rate limits
|
||||
@@ -297,6 +356,24 @@ it. By hand:
|
||||
git pull && docker compose up -d --build --remove-orphans
|
||||
```
|
||||
|
||||
**Install the `.env` watcher** (once per host; lets the admin panel's
|
||||
Environment tab apply changes):
|
||||
|
||||
```
|
||||
./env-apply/install.sh # asks for sudo
|
||||
systemctl status web-server-env-apply.path # should be active (waiting)
|
||||
journalctl -u web-server-env-apply.service # one entry per applied change
|
||||
```
|
||||
|
||||
Run it as the user that owns the checkout. `env-apply/run` must belong to that
|
||||
user: if Docker created it first it is root-owned, and the script fixes that.
|
||||
To apply a queued change by hand, or undo one:
|
||||
|
||||
```
|
||||
python3 env-apply/apply.py # apply what the panel queued
|
||||
cp .env.bak .env && docker compose up -d # roll back the last change
|
||||
```
|
||||
|
||||
**Rebuild one service** (e.g. after changing only the backend):
|
||||
|
||||
```
|
||||
@@ -377,9 +454,10 @@ icecast source password. liquidsoap pre-empts the fallback playlist immediately
|
||||
silence. Adding MP3s to `icecast2/fallback_music/` is picked up live
|
||||
(`reload_mode="watch"`) with no restart.
|
||||
|
||||
**Unhealthy containers** are restarted automatically by `autoheal`, which polls
|
||||
the docker socket every 30s. Only `backend` and `python` define healthchecks, so
|
||||
only they are covered.
|
||||
**Unhealthy containers are not restarted automatically.** `backend` and `python`
|
||||
define healthchecks, but the `autoheal` watchdog that acted on them was retired
|
||||
(`.deprecated/autoheal`), so `unhealthy` is only visible in `docker ps`.
|
||||
`restart: always` still brings back a container whose process exits.
|
||||
|
||||
---
|
||||
|
||||
@@ -397,13 +475,15 @@ Documented, not fixed — each would change deploy behaviour.
|
||||
mounted to the same in-container path as the real wrapper. It is currently
|
||||
shadowed by an explicit file mount — fragile. Deleting it would be safe but
|
||||
is a file removal.
|
||||
4. **The dev nginx template duplicates its `:80` and `:443` server blocks**
|
||||
almost verbatim (~190 lines), so a routing fix must be made twice.
|
||||
4. **The two `/uploads/` location blocks are still written twice** — once in
|
||||
`nginx.conf.template` and once in `nginx_dev_common.conf.template` —
|
||||
because production adds security headers inside an auth-gated block. Every
|
||||
other proxied route lives once in `nginx_routes.conf.template`, which both
|
||||
configs include; the `auth_request` lines on `/uploads/private/` are the
|
||||
one thing that must be kept in step by hand.
|
||||
5. **`nginx.conf.template` has a `/img/stamps/mine.gif` CORS header allowing
|
||||
only our own origin**, which defeats the point of having the header at all.
|
||||
6. **`certbot/entrypoint.sh` uses unquoted `${EMAIL}` and `${DOMAIN}`.** Inert
|
||||
today (neither contains whitespace) but a latent quoting bug.
|
||||
7. **`UPTIMEKUMA_*` and `WALLABAG_*` are substituted by nginx but no compose
|
||||
service provides them** — leftovers from removed services.
|
||||
8. **`autoheal` mounts the docker socket**, which is effectively root on the
|
||||
host, and uses the `:latest` tag.
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# =============================================================================
|
||||
# Makefile — one place for the commands that verify and run this repo.
|
||||
#
|
||||
# WHY THIS FILE EXISTS
|
||||
# The stack is four toolchains (Go, Python, Node, Docker) and the command
|
||||
# that checks each one used to live only in a gitignored notes file. `make
|
||||
# check` is the single thing to run before pushing; .gitea/workflows/
|
||||
# deploy.yaml runs the same backend and Python checks (in containers, since
|
||||
# the Pi runner has no host toolchains) before it deploys.
|
||||
#
|
||||
# WHAT IT NEEDS ON THE HOST
|
||||
# check-backend / generate Go (the version in backend/go.mod)
|
||||
# check-python python3 with the venv module
|
||||
# check-vue Node + `npm install` done in vue/, and the
|
||||
# generated vue/src/wasm/ directory (see below)
|
||||
# check-compose / dev Docker with the compose plugin
|
||||
# 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
|
||||
# its own shell, so the directory change cannot leak into the next line.
|
||||
# =============================================================================
|
||||
|
||||
# `make` with no arguments prints the target list rather than running checks.
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
# Overridable: `make check-python PYTHON=python3.12` to match the image.
|
||||
PYTHON ?= python3
|
||||
|
||||
# The virtualenv for the Python checks. At the repo root rather than inside
|
||||
# python/, because python/ is a docker build context and a venv there would be
|
||||
# sent to the daemon on every build. Gitignored (/.venv/).
|
||||
VENV := .venv
|
||||
|
||||
# Written after a successful install. Being a file target that depends on both
|
||||
# requirements files, it is what makes `check-python` re-install when either
|
||||
# changes and skip the install otherwise.
|
||||
VENV_STAMP := $(VENV)/.installed
|
||||
|
||||
.PHONY: help check check-backend check-python check-vue check-compose generate dev
|
||||
|
||||
help:
|
||||
@echo "Targets:"
|
||||
@echo " make check run every check below"
|
||||
@echo " make check-backend go vet + go test in backend/"
|
||||
@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 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-backend:
|
||||
cd backend && go vet ./... && go test ./...
|
||||
|
||||
# requirements-dev.txt `-r`-includes requirements.txt, so one install covers
|
||||
# the app's dependencies and pytest. The venv is recreated from scratch
|
||||
# whenever a requirements file changes: upgrading in place would leave behind
|
||||
# packages that were removed from the files, and the check would keep passing
|
||||
# on a dependency the image no longer has.
|
||||
$(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
|
||||
rm -rf $(VENV)
|
||||
$(PYTHON) -m venv $(VENV)
|
||||
$(VENV)/bin/python -m pip install --quiet --upgrade pip
|
||||
$(VENV)/bin/python -m pip install --quiet -r python/requirements-dev.txt
|
||||
touch $@
|
||||
|
||||
check-python: $(VENV_STAMP)
|
||||
cd python && ../$(VENV)/bin/python -m pytest tests -q
|
||||
|
||||
# `npx vite build`, NOT `npm run build`: the npm script first runs wasm-pack to
|
||||
# compile the Rust crate, which needs a Rust toolchain most machines (and the
|
||||
# Pi) do not have. The Vite half alone is enough to catch a broken import or
|
||||
# template.
|
||||
#
|
||||
# It does still need the OUTPUT of that Rust step, vue/src/wasm/, which is
|
||||
# generated and gitignored — so a fresh clone has none and Vite would fail with
|
||||
# a bare "could not resolve ../wasm/..." error. The guards below say what is
|
||||
# actually wrong instead.
|
||||
#
|
||||
# The build goes to a temp directory that is removed afterwards (success or
|
||||
# failure), so the check never leaves a vue/dist behind or overwrites one.
|
||||
check-vue:
|
||||
@test -d vue/src/wasm || { \
|
||||
echo "check-vue: vue/src/wasm/ is missing."; \
|
||||
echo " It is the generated (gitignored) output of the Rust crate in vue/crates/"; \
|
||||
echo " and the Vite build imports it. Create it with wasm-pack:"; \
|
||||
echo " cd vue && npm run build:wasm"; \
|
||||
echo " (needs a Rust toolchain; the vue image builds it for you, see vue/Dockerfile)."; \
|
||||
exit 1; }
|
||||
@test -d vue/node_modules || { \
|
||||
echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \
|
||||
exit 1; }
|
||||
@out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \
|
||||
cd vue && npx vite build --outDir "$$out" --emptyOutDir
|
||||
|
||||
# Validates the compose files: YAML, schema, and that every ${VAR} they
|
||||
# interpolate resolves to something usable.
|
||||
#
|
||||
# With a real .env present this is simply `docker compose config -q`.
|
||||
#
|
||||
# Without one (a CI checkout, a fresh clone) two things break, and
|
||||
# `--env-file .env.example` fixes neither:
|
||||
# - several services declare `env_file: ./.env`, and compose refuses to load
|
||||
# the project if that file does not exist;
|
||||
# - .env.example has blank values, and OBSIDIAN_DIR is used as a bind-mount
|
||||
# source, where an empty string is a hard "invalid spec" error.
|
||||
# So in that case the files are validated against a temporary PROJECT
|
||||
# DIRECTORY holding a copy of .env.example as its .env, with a placeholder for
|
||||
# OBSIDIAN_DIR. `config` only resolves paths, it does not need them to exist,
|
||||
# so the build contexts not being under the temp directory is fine. Nothing is
|
||||
# written to the repo, and a real .env is never created by accident.
|
||||
check-compose:
|
||||
@set -e; \
|
||||
if [ -f .env ]; then \
|
||||
pd="."; \
|
||||
else \
|
||||
echo "check-compose: no .env, validating against .env.example"; \
|
||||
pd=$$(mktemp -d); trap 'rm -rf "$$pd"' EXIT; \
|
||||
cp .env.example "$$pd/.env"; \
|
||||
echo "OBSIDIAN_DIR=/placeholder/obsidian" >> "$$pd/.env"; \
|
||||
fi; \
|
||||
echo "docker compose -f docker-compose.yml config -q"; \
|
||||
docker compose --project-directory "$$pd" -f docker-compose.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
|
||||
|
||||
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from
|
||||
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
|
||||
generate:
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
|
||||
# Dev stack: HTTP only, seeded database, Vite hot reload behind nginx.
|
||||
dev:
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
@@ -27,8 +27,6 @@ silverbullet (3000) ── Obsidian Notes Editor (SilverBullet 2.11.0)
|
||||
silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
|
||||
silverbullet-git ── Commits/pushes notes edits to the notes repo
|
||||
python (8000) ── Python API (FastAPI)
|
||||
hasura (8080) ── Hasura GraphQL Engine (Docker profile: hasura)
|
||||
autoheal ── Auto-restart unhealthy containers
|
||||
certbot ── SSL Certificate Management (disabled in dev)
|
||||
```
|
||||
|
||||
@@ -57,11 +55,10 @@ certbot ── SSL Certificate Management (disabled in dev)
|
||||
- Printable CV with role-specific sections
|
||||
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
|
||||
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
|
||||
- Hasura GraphQL console (admin-only)
|
||||
- Admin-gated routes: `/notes`, `/sb`, `/hasura` require admin JWT via Nginx `auth_request`
|
||||
- Admin-gated routes: `/notes`, `/sb` require admin JWT via Nginx `auth_request`
|
||||
- Landing page with animated stamps section
|
||||
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
||||
- Backend healthcheck with autoheal container for automatic recovery
|
||||
- Backend healthcheck (reported in `docker ps`; nothing restarts on it)
|
||||
|
||||
## Pages
|
||||
|
||||
@@ -183,13 +180,12 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
|
||||
| `/api` | backend:8080 | API (rate limited: 30r/s) |
|
||||
| `/radio` | icecast:8000 | Audio streaming |
|
||||
| `/gitea` | gitea:3000 | Git service |
|
||||
| `/hasura` | hasura:8080 | GraphQL console + WebSocket (admin-only) |
|
||||
| `/notes` | silverbullet-public:3000 | Obsidian notes (public, read-only) |
|
||||
| `/sb` | silverbullet:3000 | Obsidian notes editor (admin-only) |
|
||||
| `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) |
|
||||
| `/uploads` | local alias | User-uploaded files |
|
||||
|
||||
`/hasura` and `/sb` are protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
|
||||
`/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
|
||||
|
||||
### Deprecated Endpoints
|
||||
|
||||
@@ -246,12 +242,9 @@ Create a `.env` file in the project root. All services read from this file.
|
||||
| `LIQUIDSOAP_HARBOR_PORT` | Liquidsoap harbor port (e.g. `8005`) |
|
||||
| `DOMAIN` | Production domain name |
|
||||
| `EMAIL` | Email for Let's Encrypt registration |
|
||||
| `CLAUDE_API_KEY` | Anthropic Claude API key |
|
||||
| `CLAUDE_API_KEY` | Anthropic Claude API key (read by the Python service, which makes every Claude call) |
|
||||
| `STEAM_API_KEY` | Steam Web API key |
|
||||
| `STEAM_ID` | Steam user ID |
|
||||
| `HASURA_GRAPHQL_ADMIN_SECRET` | Hasura admin secret |
|
||||
| `HASURA_HOST` | Hasura hostname (use `hasura` for Docker) |
|
||||
| `HASURA_PORT` | Hasura port (typically `8080`) |
|
||||
| `PYTHON_HOST` | Python API hostname (defaults to `python`) |
|
||||
| `PYTHON_PORT` | Python API port (defaults to `8000`) |
|
||||
| `SEED_DB` | Set to `true` to seed test data on startup |
|
||||
@@ -319,7 +312,6 @@ This:
|
||||
- Disables certbot
|
||||
- Seeds the database with test data (`SEED_DB=true`)
|
||||
- Enables GraphQL playground and introspection
|
||||
- Enables Hasura console and dev mode
|
||||
|
||||
Visit `http://localhost` to test.
|
||||
|
||||
@@ -329,7 +321,17 @@ Visit `http://localhost` to test.
|
||||
cd vue && npm run dev
|
||||
```
|
||||
|
||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
||||
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets default to `localhost:8080`, `:3000`, `:8000` and `:8000`; override them with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (see the comment in `vue/vite.config.js` — compose does not publish the backend, Python or Icecast ports to the host).
|
||||
|
||||
### Checks
|
||||
|
||||
```sh
|
||||
make check
|
||||
```
|
||||
|
||||
Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build and `docker compose config` validation. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`.
|
||||
|
||||
The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass.
|
||||
|
||||
## Untracked Files
|
||||
|
||||
|
||||
+2
-2
@@ -46,8 +46,8 @@ FROM debian:bookworm-slim
|
||||
|
||||
# wget is not just for humans: the compose healthcheck probes the server with
|
||||
# `wget -qO- http://localhost:8080/`, and without it in the image every probe
|
||||
# fails as "executable file not found" — Docker then marks the container
|
||||
# unhealthy and autoheal kills it in a ~90s restart loop.
|
||||
# fails as "executable file not found" and Docker marks the container
|
||||
# unhealthy.
|
||||
RUN apt-get update \
|
||||
&& apt-get install --yes --no-install-recommends ca-certificates wget \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
+206
-37
@@ -2,7 +2,8 @@
|
||||
|
||||
The Go API for adam-french.co.uk. It is one process behind nginx, 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, Anthropic).
|
||||
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
|
||||
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
|
||||
@@ -18,9 +19,11 @@ handlers/ REST endpoints + the shared Store dependency container
|
||||
handle_*.go one file per domain
|
||||
services/ stateful collaborators (DB, auth, chat hub, API clients)
|
||||
graph/ GraphQL layer
|
||||
schema/*.graphql source of truth for the schema
|
||||
schema/*.graphql source of truth for the schema, including who may call what
|
||||
*.resolvers.go resolver implementations, one per schema file
|
||||
*_helpers.go hand-written mapping helpers (never regenerated)
|
||||
directives.go @admin / @signedIn: the authorisation checks, written once
|
||||
directives_test.go fails when a mutation is added without one
|
||||
context.go reading identity out of the resolver context
|
||||
middleware.go putting it in
|
||||
doc.go package overview — read this before touching resolvers
|
||||
@@ -41,9 +44,10 @@ graph/ GraphQL layer
|
||||
reached through the `admin` group can assume both.
|
||||
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
|
||||
*annotates* the request context with the Gin context and, if a valid access
|
||||
token is present, the JWT claims — and then lets everything through. Each
|
||||
resolver authorises itself with `IsAdminFromCtx` / `UserIDFromCtx`.
|
||||
**A resolver that forgets to check is public.**
|
||||
token is present, the JWT claims — and then lets everything through. A
|
||||
field is guarded by a directive on it in the schema, `@admin` or
|
||||
`@signedIn`, which runs before the resolver. **A field with neither is
|
||||
public.** See [GraphQL authorisation](#graphql-authorisation).
|
||||
5. Handlers and resolvers both reach the database and the caches through the
|
||||
single `handlers.Store` built in `main`.
|
||||
|
||||
@@ -70,6 +74,95 @@ The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
|
||||
both. They share `services.Auth` and the rate limiter, but each has its own
|
||||
cookie-writing helper — change one and you must change the other.
|
||||
|
||||
## GraphQL authorisation
|
||||
|
||||
Who may call a field is written in the schema, on the field:
|
||||
|
||||
```graphql
|
||||
extend type Query {
|
||||
bookmarks: [Bookmark!]! # public
|
||||
places: [Place!]! @signedIn # any signed-in user
|
||||
users: [User!]! @admin # admins only
|
||||
}
|
||||
```
|
||||
|
||||
| directive | passes when | error otherwise |
|
||||
| --- | --- | --- |
|
||||
| `@admin` | the access token's `admin` claim is true | `admin access required` |
|
||||
| `@signedIn` | there is a valid access token at all | `authentication required` |
|
||||
| *(none)* | always | — |
|
||||
|
||||
Both are declared in `graph/schema/schema.graphql`, implemented once in
|
||||
`graph/directives.go`, and handed to gqlgen in `main.go`
|
||||
(`graph.Config{Directives: graph.Directives()}`). gqlgen calls the directive
|
||||
before the resolver; on an error the resolver never runs and the client gets
|
||||
that message for the field. The two strings are shown as-is by the front end,
|
||||
so they are part of the API. If the `Directives` line were ever dropped from
|
||||
`main.go` the guarded fields would all fail (`directive admin is not
|
||||
implemented`), not open.
|
||||
|
||||
This replaced an `if !IsAdminFromCtx(ctx) { return ... }` that was pasted into
|
||||
the top of every guarded resolver, where leaving it out was invisible. Now a
|
||||
guarded resolver has no check in it, and the absence of a guard is something a
|
||||
test can see.
|
||||
|
||||
**What is guarded.** Queries are public and mutations are `@admin`, except:
|
||||
|
||||
- `login`, `logout`, `refreshToken` — public; they are how a session starts
|
||||
and ends.
|
||||
- `createPlace`, `updatePlace`, `deletePlace` and the `places` query —
|
||||
`@signedIn`. Places are a shared list with no per-user ownership.
|
||||
- `users`, `user` — queries, but `@admin`: private data.
|
||||
|
||||
**What a directive cannot say stays in the resolver**, using `IsAdminFromCtx` /
|
||||
`UserIDFromCtx` from `graph/context.go`:
|
||||
|
||||
- `updatePost` / `deletePost` are `@admin` *and* require the caller to be the
|
||||
post's author; `setUserAdmin` refuses to change the caller's own flag.
|
||||
- `me` has no directive: it returns its own `unauthorized` error.
|
||||
- `messages` has no directive: it filters private messages out for non-admins
|
||||
instead of refusing.
|
||||
- `spotifyNeedsReauth` has no directive: it is `false` for non-admins.
|
||||
|
||||
**The safety net** is `graph/directives_test.go`, which walks the parsed
|
||||
schema:
|
||||
|
||||
- every `Mutation` field must carry `@admin` or `@signedIn`, unless it is in
|
||||
the `publicMutations` list in that file (the three above). A new mutation
|
||||
with no directive fails the build's tests until one or the other is done;
|
||||
- the `@signedIn` mutations and the guarded queries are pinned by name, so
|
||||
loosening `@admin` to `@signedIn`, or dropping a guard from a private query,
|
||||
has to be done in the test as well;
|
||||
- the directive functions are unit-tested, and a handful of operations are run
|
||||
through the real executable schema to pin the messages on the wire.
|
||||
|
||||
One caveat: the test reads the `.graphql` files, but enforcement is in
|
||||
`generated.go`. Adding a directive to an existing field does nothing until
|
||||
gqlgen is re-run.
|
||||
|
||||
## Adding an entity
|
||||
|
||||
1. **Model** — add the struct to `models/models.go` with `ID uint`
|
||||
(`gorm:"primarykey"`) and a `gorm.DeletedAt`, and list it in `AutoMigrate`
|
||||
in `services/database.go`. There are no migration files.
|
||||
2. **Schema** — add `graph/schema/<name>.graphql` with the type, its inputs,
|
||||
and `extend type Query` / `extend type Mutation`. Put `@admin` or
|
||||
`@signedIn` on every mutation, and on any query that is not for the public.
|
||||
Use `#` comments, not `"""` descriptions.
|
||||
3. **Binding** — map the type onto the model in `gqlgen.yml`, with
|
||||
`deletedAt: resolver: false`. Without the entry gqlgen generates a second,
|
||||
unrelated struct in `graph/model/`.
|
||||
4. **Generate** — `go run github.com/99designs/gqlgen generate` (below). This
|
||||
creates `graph/<name>.resolvers.go` with a stub per query and mutation.
|
||||
5. **Resolvers** — fill the stubs in. Do not write an auth check; the
|
||||
directive has run. Do not write an `ID` resolver; `ID uint` binds by itself
|
||||
(see [IDs](#gotchas)). Put commentary inside the function bodies, since
|
||||
gqlgen rewrites what is above the signature. A delete should load the row
|
||||
first and return an error for a missing id, as the existing ones do.
|
||||
6. **Test** — `go test ./...`. `directives_test.go` will tell you if a
|
||||
mutation was left unguarded; if you added a guarded *query*, add it to the
|
||||
pinned list there.
|
||||
|
||||
## GraphQL vs REST
|
||||
|
||||
GraphQL is the default and covers essentially all the site's data. REST exists
|
||||
@@ -78,17 +171,87 @@ for the things GraphQL cannot do:
|
||||
| REST endpoint | why it is not GraphQL |
|
||||
| --- | --- |
|
||||
| `/auth/*` | cookie handling and the status-code-only admin probe |
|
||||
| `/spotify/callback`, `/email/callback` | OAuth providers redirect a *browser* here |
|
||||
| `/spotify/callback` | OAuth providers redirect a *browser* here |
|
||||
| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
||||
| `/notes/*path` | streams a file download, not JSON |
|
||||
| `/ws` | WebSocket upgrade |
|
||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||
| `/admin/env`, `/admin/logs` | process environment and files on disk, not the data model |
|
||||
|
||||
### Environment tab
|
||||
|
||||
`handlers/handle_env.go` and `services/env_manager.go` let the admin panel
|
||||
change `.env` on the Pi without SSH. The backend never reads or writes the
|
||||
file and has no Docker access: it validates an edit and leaves it for the
|
||||
host, which is the part trusted to act.
|
||||
|
||||
- **`services/env_registry.json`** lists every variable in `.env.example`
|
||||
with its group, kind, whether it is editable, and the compose services that
|
||||
read it. It is embedded in the binary and read from the checkout by the host
|
||||
script, so one file decides what the panel offers and what the host accepts.
|
||||
A test fails if it and `.env.example` disagree.
|
||||
- **The `python` and `jobs` services are a third place.** They are given an
|
||||
explicit `environment:` list in `docker-compose.yml` instead of the whole
|
||||
`.env`, so that they never hold the site's database password or the JWT
|
||||
secret. A new variable for either therefore goes in the registry (with the
|
||||
service in its `services`), in `.env.example`, *and* in that list.
|
||||
`TestEnvRegistryMatchesComposePythonEnvironment` reads the compose file and
|
||||
fails if a variable the registry says one of them reads is not passed to
|
||||
it, or if an editable variable passed to it does not list that service. Locked
|
||||
variables carry no `services` and are exempt (`PYTHON_PORT` is one).
|
||||
- `GET /admin/env` — the registry plus state from this process's own
|
||||
environment. A secret's value is never sent, only "set" and, for values of
|
||||
12+ characters, the last four.
|
||||
- `PUT /admin/env` — `{"set": {NAME: value}, "generate": [NAME]}`; `""`
|
||||
clears. The whole batch is validated first. Control characters are refused
|
||||
because `.env` is line oriented: a newline would let an edit to an allowed
|
||||
variable write a second, arbitrary one. Generated values (32 random bytes,
|
||||
hex) are returned once.
|
||||
- The change is written to `/backend/env-apply/request.json` (`./env-apply/run`
|
||||
on the host), `0600` and chowned to that directory's owner so the
|
||||
unprivileged host user can read it. `env-apply/apply.py` claims it, rewrites
|
||||
`.env`, recreates the affected services and writes `status.json`.
|
||||
- `GET /admin/env/status` — `idle`, `pending`, `applying`, `applied` or
|
||||
`failed`. `watcher: false` means a request has sat unclaimed for 15 seconds,
|
||||
i.e. nothing on the host is watching. `DELETE /admin/env/pending` withdraws
|
||||
an unclaimed request.
|
||||
|
||||
The backend is always among the recreated services, because the values the
|
||||
panel shows are the ones this process started with.
|
||||
|
||||
## Calling the Python service
|
||||
|
||||
Every Claude call the site makes lives in the Python service; this backend has
|
||||
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/`:
|
||||
|
||||
| route | caller | sends | gets back |
|
||||
| --- | --- | --- | --- |
|
||||
| `/internal/rowing/read` | `POST /rowing` (`handlers/handle_rowing.go`) | `{media_type, data}` (image, base64) | `{timeMinutes, timeSeconds, distance}` |
|
||||
Every route goes through one function, `services.CallPython[T]` in
|
||||
`services/python_call.go`: marshal the body, POST it, decode a 200 into `T`.
|
||||
It has the one HTTP client (two-minute timeout, above the Python side's own
|
||||
worst case of a retried Claude call) and the one rule for failures:
|
||||
|
||||
- a **502 whose `detail` is a string** is a message the route wrote for a
|
||||
person ("failed to parse image data"). It comes back as a
|
||||
`*services.PythonError`, and the HTTP handler relays it to the browser;
|
||||
- **anything else** — connection refused, a 422 (its `detail` is a list), a
|
||||
503 for an unset `CLAUDE_API_KEY`, a reply that will not decode — is an
|
||||
ordinary error. Callers log it and show something generic.
|
||||
|
||||
It lives in `services` so that a background job there could use it as well
|
||||
as a handler. A new internal route needs only a
|
||||
request struct, a reply struct and a one-line call.
|
||||
|
||||
## Services
|
||||
|
||||
Everything is constructed in `main` from environment variables and handed to
|
||||
`handlers.Store`. Nothing here fails start-up: a missing Spotify token, an
|
||||
unconfigured mailbox or an absent Steam key all just leave that feature
|
||||
`handlers.Store`. Nothing here fails start-up: a missing Spotify token or an
|
||||
absent Steam key all just leave that feature
|
||||
dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
|
||||
- **database.go** — Postgres via GORM. There are no migration files:
|
||||
@@ -103,12 +266,8 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are
|
||||
cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min
|
||||
(Steam).
|
||||
- **email_sync.go** / **email_imap.go** — the job-application pipeline: fetch
|
||||
recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter
|
||||
it, ask Claude to extract structured data, create or advance a
|
||||
`JobApplication`. Runs on a timer and can be triggered by an admin.
|
||||
- **claude.go** — the shared Anthropic client, used by the email pipeline and
|
||||
by the rowing photo reader.
|
||||
- **python_call.go** — `CallPython`, the one way to reach the Python service's
|
||||
internal routes. See [Calling the Python service](#calling-the-python-service).
|
||||
- **notes.go** — path-traversal-safe file lookup for the notes directory.
|
||||
- **seed.go** — dev-only test data. Creates an admin with the password
|
||||
`password`, so it must never run in production (`SEED_DB=true` is set only
|
||||
@@ -122,6 +281,10 @@ The `.graphql` files are the source of truth.
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
```
|
||||
|
||||
If that stops with `missing go.sum entry ... urfave/cli`, the generator's own
|
||||
dependencies are not in `go.sum`. `go get github.com/99designs/gqlgen@<the
|
||||
version in go.mod>` adds them.
|
||||
|
||||
This rewrites `graph/generated.go` and `graph/model/models_gen.go` and adds
|
||||
stubs for new fields to the matching `*.resolvers.go`. Existing resolver bodies
|
||||
are preserved, but hand-written code in a regenerated file can be relocated to
|
||||
@@ -132,16 +295,30 @@ the end of it — which is why shared helpers live in `*_helpers.go` instead.
|
||||
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
|
||||
generated struct rather than the model you expected.
|
||||
|
||||
One scalar-level binding in `gqlgen.yml` is worth knowing about: `ID` lists
|
||||
both `graphql.IntID` and `graphql.UintID` (see IDs under Gotchas).
|
||||
|
||||
If you delete a field or stop needing a resolver, delete the resolver function
|
||||
by hand before regenerating; otherwise gqlgen keeps it, commented out, in a
|
||||
warning block at the end of the file.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
|
||||
`gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
||||
- **Soft delete everywhere.** Every model has a `gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
||||
row out. Rows are never actually removed, and a `uniqueIndex` still collides
|
||||
with deleted rows — a soft-deleted username cannot be reused.
|
||||
- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it;
|
||||
there is no error to tell you why the field came back null.
|
||||
- **IDs.** Models use `uint`, GraphQL uses `Int`. That is why nearly every type
|
||||
has a hand-written `ID` resolver doing `int(obj.ID)`.
|
||||
- **IDs.** Models use `uint`; the schema uses `ID`. `gqlgen.yml` binds `ID` to
|
||||
`graphql.IntID` *and* `graphql.UintID`, so a model's `ID uint` field is
|
||||
served directly — there are no `ID` resolvers, and a new type does not need
|
||||
one. `IntID` is listed first, which is why resolver *arguments* are still
|
||||
`id int`. Both write an id as a quoted decimal string (`"12"`) and accept a
|
||||
string or a number, so the wire format is the same either way. Other
|
||||
unsigned fields are not IDs and still have resolvers: `Message.authorId`,
|
||||
`Rowing.time`, `Rowing.distance`.
|
||||
- **Deletes error on a missing id.** Every delete mutation loads the row
|
||||
first, so a wrong id is a `record not found` error.
|
||||
- **`Message.AuthorID` is not a user id.** It is a per-process counter handed
|
||||
out by the chat hub on connect, meaningless across restarts.
|
||||
- **The chat table is capped.** Every insert soft-deletes all but the newest
|
||||
@@ -149,19 +326,10 @@ generated struct rather than the model you expected.
|
||||
- **Store's caches are unsynchronised** and shared by all requests. The races
|
||||
are benign (at worst a duplicate upstream fetch), but do not add a field
|
||||
there that would be unsafe to tear.
|
||||
- **Claude output is parsed as JSON** after stripping a possible markdown code
|
||||
fence — via the shared `services.StripMarkdownFence`, used by both
|
||||
`handle_rowing.go` and `email_sync.go`.
|
||||
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
|
||||
A failed email is recorded with action `"error"` and an attempt counter;
|
||||
while it has attempts left the next sync reprocesses it and updates the same
|
||||
row. Because the fetch window is anchored to *processing* time, which has
|
||||
already moved past the failure, the sync also rewinds the window to the
|
||||
oldest retryable row's `ReceivedAt` — otherwise the email could never be
|
||||
re-fetched. Once the cap is reached the row is terminal, so an email Claude
|
||||
can never parse stops costing API calls.
|
||||
- **Authenticating email after start-up does not start the scheduler**, which
|
||||
only checks readiness once — restart, or trigger syncs by hand.
|
||||
- **Claude's output is never parsed here.** Prompts, the markdown-fence
|
||||
stripping and the JSON parsing are all in the Python service; this side
|
||||
receives typed JSON or an error (see
|
||||
[Calling the Python service](#calling-the-python-service)).
|
||||
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
|
||||
`GQL_INTROSPECTION` / `GQL_PLAYGROUND` are set.
|
||||
- **No graceful shutdown.** `r.Run` blocks forever and its error is ignored;
|
||||
@@ -180,14 +348,15 @@ generated struct rather than the model you expected.
|
||||
| `SEED_DB` | seed dev test data (never in production) |
|
||||
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
|
||||
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
|
||||
| `CLAUDE_API_KEY` | Anthropic API |
|
||||
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) |
|
||||
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
|
||||
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
|
||||
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
|
||||
| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend |
|
||||
| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend |
|
||||
|
||||
Paths baked into the code, all inside mounted volumes so they survive a
|
||||
container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`,
|
||||
`/backend/fallback_music`, `/backend/token/` (Spotify and Microsoft Graph
|
||||
OAuth tokens).
|
||||
`/backend/fallback_music`, `/backend/token/` (the Spotify OAuth token).
|
||||
|
||||
`CLAUDE_API_KEY` is not in the table: the backend does not read it. It is in
|
||||
the registry with `services: ["python", "jobs"]`, the two containers that use
|
||||
it. The email and job-lead variables still in `.env` belong to the job
|
||||
tracker (`jobs`), which has its own repo and README.
|
||||
|
||||
@@ -4,7 +4,6 @@ go 1.26
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.95
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
@@ -49,10 +48,6 @@ require (
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||
github.com/sosodev/duration v1.4.0 // indirect
|
||||
github.com/tidwall/gjson v1.18.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
|
||||
@@ -37,8 +37,6 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0 h1:oUTzFaUpAevfuELAP1sjL6CQJ9HHAfT7CoSYSac11PY=
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
@@ -60,8 +58,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -205,16 +201,6 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||
@@ -522,8 +508,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
|
||||
+7
-12
@@ -16,9 +16,16 @@ resolver:
|
||||
filename_template: "{name}.resolvers.go"
|
||||
|
||||
models:
|
||||
# Two bindings, tried in order. IntID comes first, so it is what gqlgen
|
||||
# picks where it has a free choice — resolver arguments stay `id int`.
|
||||
# UintID is there so a model's `ID uint` field binds to `id: ID!` directly,
|
||||
# with no hand-written resolver converting it. Both write an id as a quoted
|
||||
# decimal string ("12") and read a string or a number, so which one a field
|
||||
# uses is invisible on the wire.
|
||||
ID:
|
||||
model:
|
||||
- github.com/99designs/gqlgen/graphql.IntID
|
||||
- github.com/99designs/gqlgen/graphql.UintID
|
||||
User:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.User
|
||||
@@ -63,18 +70,6 @@ models:
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobApplication:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobApplication
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobAppReference:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobAppReference
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
Place:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Place
|
||||
|
||||
@@ -7,24 +7,16 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
// No middleware guards GraphQL, so each mutation checks for itself.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Admin-only, but there is no check to see here: the field is marked
|
||||
// @admin in the schema and the directive (directives.go) has already
|
||||
// refused anyone else by the time this runs.
|
||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -41,8 +33,3 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
}
|
||||
return ptrs(activities), nil
|
||||
}
|
||||
|
||||
// Activity returns ActivityResolver implementation.
|
||||
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
|
||||
|
||||
type activityResolver struct{ *Resolver }
|
||||
|
||||
@@ -121,6 +121,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
|
||||
// Me is the resolver for the me field.
|
||||
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
// Checked here rather than with @signedIn because the message differs:
|
||||
// this query has always answered "unauthorized", and the directive's is
|
||||
// "authentication required".
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
|
||||
@@ -7,22 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateBookmark is the resolver for the createBookmark field.
|
||||
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -32,9 +23,6 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
|
||||
|
||||
// DeleteBookmark is the resolver for the deleteBookmark field.
|
||||
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Loaded first so the deleted record can be returned to the client, and
|
||||
// so a missing id is a clean "not found" rather than a silent no-op.
|
||||
// Delete is a soft delete: deleted_at is set and the row stays.
|
||||
@@ -56,8 +44,3 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
}
|
||||
return ptrs(bookmarks), nil
|
||||
}
|
||||
|
||||
// Bookmark returns BookmarkResolver implementation.
|
||||
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
|
||||
|
||||
type bookmarkResolver struct{ *Resolver }
|
||||
|
||||
@@ -27,7 +27,8 @@ const (
|
||||
|
||||
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
|
||||
// is anonymous. nil means "not authenticated": a missing or invalid token is
|
||||
// not an error here, because many queries are public.
|
||||
// not an error here, because many queries are public. Turning "anonymous"
|
||||
// into a refusal is the job of the schema directives, per field.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -38,6 +39,10 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
|
||||
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
|
||||
// float64 because claims are decoded by encoding/json, hence the conversion.
|
||||
//
|
||||
// ok is also the test behind the @signedIn directive. A resolver calls this
|
||||
// itself when it needs the id for more than a gate: to record a post's
|
||||
// author, or to compare the caller with a row's owner.
|
||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -50,11 +55,12 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
return uint(idF), true
|
||||
}
|
||||
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. This is
|
||||
// the authorisation check for nearly every mutation — there is no middleware
|
||||
// in front of the GraphQL endpoint, so a resolver that forgets to call this
|
||||
// is public. Admin comes from the token, not the database, so a revoked admin
|
||||
// flag only bites once the access token expires.
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. It is
|
||||
// what the @admin directive tests (directives.go), which is how nearly every
|
||||
// mutation is authorised; resolvers call it directly only for the softer
|
||||
// cases a directive cannot express, such as the messages query filtering
|
||||
// rather than refusing. Admin comes from the token, not the database, so a
|
||||
// revoked admin flag only bites once the access token expires.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
)
|
||||
|
||||
// The schema's two authorisation directives. A field marked @admin or
|
||||
// @signedIn in graph/schema/*.graphql has the matching function here run
|
||||
// before its resolver; if it returns an error the resolver is never called
|
||||
// and the error is what the client receives for that field.
|
||||
//
|
||||
// This replaces a check that used to be copied into the top of every guarded
|
||||
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
|
||||
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
|
||||
// it is now declared next to the field, where a missing one can be seen and
|
||||
// tested for (directives_test.go), instead of being a line someone has to
|
||||
// remember to paste.
|
||||
//
|
||||
// The two error strings are part of the contract with the front end, which
|
||||
// shows them as they are; the tracker page, for one, explains "admin access
|
||||
// required" as a lapsed session. Do not reword them.
|
||||
//
|
||||
// This file is hand-written and never touched by gqlgen.
|
||||
|
||||
const (
|
||||
errAdminRequired = "admin access required"
|
||||
errSignedInRequired = "authentication required"
|
||||
)
|
||||
|
||||
// Directives is the set gqlgen needs in graph.Config. It is a function so
|
||||
// that main and the tests wire exactly the same implementations.
|
||||
//
|
||||
// Leaving a directive nil in the Config does not open the fields that use it:
|
||||
// the generated code answers "directive admin is not implemented" for each.
|
||||
func Directives() DirectiveRoot {
|
||||
return DirectiveRoot{
|
||||
Admin: requireAdmin,
|
||||
SignedIn: requireSignedIn,
|
||||
}
|
||||
}
|
||||
|
||||
// requireAdmin implements @admin: the request must carry an access token
|
||||
// whose admin claim is true. Admin comes from the token, not the database, so
|
||||
// demoting a user only bites once their access token is replaced.
|
||||
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf(errAdminRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
// requireSignedIn implements @signedIn: any verified access token will do,
|
||||
// admin or not. An admin is signed in, so this never needs pairing with
|
||||
// @admin.
|
||||
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf(errSignedInRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/99designs/gqlgen/graphql/handler"
|
||||
"github.com/99designs/gqlgen/graphql/handler/transport"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/vektah/gqlparser/v2/ast"
|
||||
|
||||
"adam-french.co.uk/backend/handlers"
|
||||
)
|
||||
|
||||
// Authorisation is declared in the schema (@admin / @signedIn) and enforced
|
||||
// by directives.go. These tests cover both halves: that the two functions
|
||||
// decide correctly, and that the schema marks the fields it should — the
|
||||
// second being the one that matters day to day, since the way this goes
|
||||
// wrong is a new field added without a directive.
|
||||
//
|
||||
// Nothing here needs a database: a refused field never reaches its resolver,
|
||||
// and the tests only ever drive fields that are refused or that return before
|
||||
// touching the Store.
|
||||
|
||||
// withClaims builds the context AuthContextMiddleware would for a verified
|
||||
// token. Claims are decoded from JSON in production, hence float64 for the id.
|
||||
func withClaims(id float64, admin bool) context.Context {
|
||||
claims := jwt.MapClaims{"id": id, "admin": admin}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}
|
||||
|
||||
func TestDirectives(t *testing.T) {
|
||||
anonymous := context.Background()
|
||||
user := withClaims(2, false)
|
||||
admin := withClaims(1, true)
|
||||
// A token that verified but carries no id: not something GenerateJWT
|
||||
// mints, but it must not count as signed in.
|
||||
noID := func() context.Context {
|
||||
claims := jwt.MapClaims{"admin": false}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
directive func(context.Context, any, graphql.Resolver) (any, error)
|
||||
ctx context.Context
|
||||
wantErr string // "" means the resolver must run
|
||||
}{
|
||||
{"@admin refuses an anonymous request", requireAdmin, anonymous, "admin access required"},
|
||||
{"@admin refuses a signed-in non-admin", requireAdmin, user, "admin access required"},
|
||||
{"@admin admits an admin", requireAdmin, admin, ""},
|
||||
{"@signedIn refuses an anonymous request", requireSignedIn, anonymous, "authentication required"},
|
||||
{"@signedIn refuses a token with no id", requireSignedIn, noID, "authentication required"},
|
||||
{"@signedIn admits a non-admin", requireSignedIn, user, ""},
|
||||
{"@signedIn admits an admin", requireSignedIn, admin, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
called := false
|
||||
next := func(ctx context.Context) (any, error) {
|
||||
called = true
|
||||
return "resolved", nil
|
||||
}
|
||||
res, err := c.directive(c.ctx, nil, next)
|
||||
|
||||
if c.wantErr == "" {
|
||||
if err != nil || !called || res != "resolved" {
|
||||
t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The exact strings are what the front end displays.
|
||||
if err == nil || err.Error() != c.wantErr {
|
||||
t.Fatalf("err = %v, want %q", err, c.wantErr)
|
||||
}
|
||||
if called {
|
||||
t.Fatal("the resolver ran for a refused request")
|
||||
}
|
||||
if res != nil {
|
||||
t.Fatalf("res = %v, want nil alongside the error", res)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Directives() must supply every directive the schema declares; a nil one
|
||||
// makes gqlgen fail each field that uses it.
|
||||
func TestDirectivesAreAllImplemented(t *testing.T) {
|
||||
d := Directives()
|
||||
if d.Admin == nil || d.SignedIn == nil {
|
||||
t.Fatal("Directives() left a directive unimplemented")
|
||||
}
|
||||
}
|
||||
|
||||
// guardOf reports which authorisation directive a field carries: "admin",
|
||||
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
|
||||
// nothing to @admin) and fails the test rather than being quietly accepted.
|
||||
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
|
||||
t.Helper()
|
||||
admin := field.Directives.ForName("admin") != nil
|
||||
signedIn := field.Directives.ForName("signedIn") != nil
|
||||
switch {
|
||||
case admin && signedIn:
|
||||
t.Errorf("%s carries both @admin and @signedIn", field.Name)
|
||||
return "admin"
|
||||
case admin:
|
||||
return "admin"
|
||||
case signedIn:
|
||||
return "signedIn"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func schemaUnderTest() *ast.Schema {
|
||||
return NewExecutableSchema(Config{}).Schema()
|
||||
}
|
||||
|
||||
// publicMutations is the complete list of mutations that anyone may call.
|
||||
// A mutation is public only by being named here, so adding one to the schema
|
||||
// without a directive fails TestEveryMutationIsGuarded until it is either
|
||||
// guarded or deliberately listed.
|
||||
//
|
||||
// All three are how a session is obtained or given up, so they cannot require
|
||||
// one: login checks a password, refreshToken checks the refresh cookie, and
|
||||
// logout is a no-op for a visitor who is not signed in.
|
||||
var publicMutations = []string{"login", "logout", "refreshToken"}
|
||||
|
||||
func TestEveryMutationIsGuarded(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
var seen []string
|
||||
for _, field := range schema.Mutation.Fields {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
seen = append(seen, field.Name)
|
||||
guard := guardOf(t, field)
|
||||
public := slices.Contains(publicMutations, field.Name)
|
||||
switch {
|
||||
case guard == "" && !public:
|
||||
t.Errorf("mutation %s has neither @admin nor @signedIn, so anyone can call it; "+
|
||||
"add a directive in the schema, or add it to publicMutations if that is intended", field.Name)
|
||||
case guard != "" && public:
|
||||
t.Errorf("mutation %s is listed as public but carries @%s", field.Name, guard)
|
||||
}
|
||||
}
|
||||
// A renamed or removed mutation must not leave a stale exemption behind.
|
||||
for _, name := range publicMutations {
|
||||
if !slices.Contains(seen, name) {
|
||||
t.Errorf("publicMutations lists %s, which is not in the schema", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The mutations that need only a session rather than an admin. Pinned so that
|
||||
// loosening a mutation from @admin to @signedIn — which the test above would
|
||||
// accept — has to be done here too.
|
||||
func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
want := []string{"createPlace", "deletePlace", "updatePlace"}
|
||||
var got []string
|
||||
for _, field := range schemaUnderTest().Mutation.Fields {
|
||||
if guardOf(t, field) == "signedIn" {
|
||||
got = append(got, field.Name)
|
||||
}
|
||||
}
|
||||
sort.Strings(got)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("@signedIn mutations = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Queries are public by default — the home page is built from them — so the
|
||||
// rule cannot be "every field is guarded". Instead the guarded set is pinned
|
||||
// exactly: removing a directive from one of these, or adding a query that
|
||||
// exposes private data without one, has to be a visible change to this map.
|
||||
//
|
||||
// Three queries are sensitive to who is asking without being in it, because
|
||||
// they answer rather than refuse: `me` returns "unauthorized" itself,
|
||||
// `messages` filters out private rows for non-admins, and
|
||||
// `spotifyNeedsReauth` is false for non-admins.
|
||||
func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"users": "admin",
|
||||
"user": "admin",
|
||||
"places": "signedIn",
|
||||
}
|
||||
got := map[string]string{}
|
||||
for _, field := range schemaUnderTest().Query.Fields {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
if guard := guardOf(t, field); guard != "" {
|
||||
got[field.Name] = guard
|
||||
}
|
||||
}
|
||||
for name, guard := range want {
|
||||
if got[name] != guard {
|
||||
t.Errorf("query %s: guard = %q, want @%s", name, got[name], guard)
|
||||
}
|
||||
}
|
||||
for name, guard := range got {
|
||||
if _, ok := want[name]; !ok {
|
||||
t.Errorf("query %s carries @%s but is not in the pinned list; add it there if the guard is intended", name, guard)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The directives are FIELD_DEFINITION only and are meant for the two root
|
||||
// types. One on an object's field would be enforced, but nothing above would
|
||||
// notice it being removed, so keep them where the tests look.
|
||||
func TestDirectivesOnlyOnRootFields(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
for name, def := range schema.Types {
|
||||
if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") {
|
||||
continue
|
||||
}
|
||||
for _, field := range def.Fields {
|
||||
if guardOf(t, field) != "" {
|
||||
t.Errorf("%s.%s carries an authorisation directive outside Query/Mutation", name, field.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// execute runs one operation through the real executable schema, wired the
|
||||
// way main wires it, and returns the response's error messages. The Store is
|
||||
// empty: every operation below is refused, or returns, before its resolver
|
||||
// would touch the database.
|
||||
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
|
||||
t.Helper()
|
||||
srv := handler.New(NewExecutableSchema(Config{
|
||||
Resolvers: &Resolver{Store: &handlers.Store{}},
|
||||
Directives: Directives(),
|
||||
}))
|
||||
srv.AddTransport(transport.POST{})
|
||||
|
||||
body, err := json.Marshal(map[string]any{"query": query, "variables": variables})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
|
||||
var resp struct {
|
||||
Errors []struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decoding response %s: %v", rec.Body, err)
|
||||
}
|
||||
var messages []string
|
||||
for _, e := range resp.Errors {
|
||||
messages = append(messages, e.Message)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// End to end: the message a client receives for a refused field is the bare
|
||||
// string the resolvers used to return, with nothing wrapped around it.
|
||||
func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"anonymous admin query", context.Background(), `{ users { id } }`, "admin access required"},
|
||||
{"non-admin admin query", withClaims(2, false), `{ users { id } }`, "admin access required"},
|
||||
{"anonymous admin mutation", context.Background(), `mutation { deleteBookmark(id: 1) { id } }`, "admin access required"},
|
||||
{"non-admin admin mutation", withClaims(2, false), `mutation { deleteUser(id: 1) { id } }`, "admin access required"},
|
||||
{"anonymous signed-in query", context.Background(), `{ places { id } }`, "authentication required"},
|
||||
{"anonymous signed-in mutation", context.Background(), `mutation { deletePlace(id: 1) { id } }`, "authentication required"},
|
||||
// Not a directive, and a different message on purpose.
|
||||
{"me keeps its own message", context.Background(), `{ me { id } }`, "unauthorized"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := execute(t, c.ctx, c.query, nil)
|
||||
if !slices.Equal(got, []string{c.want}) {
|
||||
t.Fatalf("errors = %q, want exactly %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// IDs: the wire form must be what it was when every type had a hand-written
|
||||
// resolver returning int. Both marshallers write a quoted decimal string and
|
||||
// both read a string or a number.
|
||||
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
|
||||
for _, id := range []uint{0, 1, 12, 4294967295} {
|
||||
var asUint, asInt bytes.Buffer
|
||||
graphql.MarshalUintID(id).MarshalGQL(&asUint)
|
||||
graphql.MarshalIntID(int(id)).MarshalGQL(&asInt)
|
||||
if asUint.String() != asInt.String() {
|
||||
t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt)
|
||||
}
|
||||
}
|
||||
if got := func() string {
|
||||
var b bytes.Buffer
|
||||
graphql.MarshalUintID(12).MarshalGQL(&b)
|
||||
return b.String()
|
||||
}(); got != `"12"` {
|
||||
t.Errorf("MarshalUintID(12) = %s, want \"12\"", got)
|
||||
}
|
||||
}
|
||||
+28
-9
@@ -9,8 +9,11 @@
|
||||
// matching *.resolvers.go. Never edit those two generated files.
|
||||
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
|
||||
// structs in backend/models, so model/ holds only input and payload
|
||||
// types. That is also why almost every type has a hand-written ID
|
||||
// resolver: model IDs are uint, GraphQL's Int is a Go int.
|
||||
// types. A model's `ID uint` binds to `id: ID!` directly, because
|
||||
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
|
||||
// needed for it. A field resolver is only written where the Go type has
|
||||
// no binding (Message.authorId and Rowing's time/distance are unsigned in
|
||||
// Go and Int in the schema).
|
||||
// - Resolvers reach the database and the third-party caches through
|
||||
// Resolver.Store, the same handlers.Store the REST endpoints use.
|
||||
// - context.go and middleware.go carry the caller's identity from Gin into
|
||||
@@ -18,13 +21,29 @@
|
||||
//
|
||||
// Authorisation, which is the thing most likely to catch out a newcomer:
|
||||
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
|
||||
// annotates the context and lets everything through, so each resolver checks
|
||||
// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that
|
||||
// check is fully public. The rule of thumb in this schema is that queries are
|
||||
// public and mutations are admin-only, with these exceptions: the job
|
||||
// application and job reference queries are admin-only (they are private
|
||||
// data), the places mutations need only a signed-in user, and the messages
|
||||
// query hides private messages from non-admins rather than refusing.
|
||||
// annotates the context and lets everything through. What guards a field is a
|
||||
// directive on it in the schema:
|
||||
//
|
||||
// createUser(input: CreateUserInput!): User! @admin
|
||||
// places: [Place!]! @signedIn
|
||||
//
|
||||
// @admin requires an admin's access token, @signedIn any valid one. Both are
|
||||
// implemented once, in directives.go, and run before the resolver, so a
|
||||
// guarded resolver contains no check of its own. A field with NEITHER
|
||||
// directive is fully public.
|
||||
//
|
||||
// The rule of thumb in this schema is that queries are public and mutations
|
||||
// are @admin, with these exceptions: login, logout and refreshToken are
|
||||
// public; the places mutations and query are @signedIn; and the users
|
||||
// queries are @admin (they are private data).
|
||||
// directives_test.go holds that list and fails when the schema departs from
|
||||
// it — in particular when a mutation is added with no directive.
|
||||
//
|
||||
// A directive is only a gate. Anything finer stays in the resolver and uses
|
||||
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
|
||||
// author, `me` answers for the caller (with its own "unauthorized" error),
|
||||
// the messages query hides private messages from non-admins rather than
|
||||
// refusing, and spotifyNeedsReauth is simply false for non-admins.
|
||||
//
|
||||
// The files ending in _helpers.go are hand-written and are not touched by
|
||||
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
|
||||
|
||||
@@ -7,23 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateFavorite is the resolver for the createFavorite field.
|
||||
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -40,8 +30,3 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
}
|
||||
return ptrs(favorites), nil
|
||||
}
|
||||
|
||||
// Favorite returns FavoriteResolver implementation.
|
||||
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
|
||||
|
||||
type favoriteResolver struct{ *Resolver }
|
||||
|
||||
+349
-2254
File diff suppressed because it is too large
Load Diff
@@ -1,95 +0,0 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobAppReference is the resolver for the createJobAppReference field.
|
||||
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
ref := models.JobAppReference{
|
||||
Category: input.Category,
|
||||
Label: input.Label,
|
||||
Value: input.Value,
|
||||
}
|
||||
if input.SortOrder != nil {
|
||||
ref.SortOrder = *input.SortOrder
|
||||
}
|
||||
if err := r.Store.DB.Create(&ref).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ref, nil
|
||||
}
|
||||
|
||||
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
|
||||
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var ref models.JobAppReference
|
||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Category != nil {
|
||||
ref.Category = *input.Category
|
||||
}
|
||||
if input.Label != nil {
|
||||
ref.Label = *input.Label
|
||||
}
|
||||
if input.Value != nil {
|
||||
ref.Value = *input.Value
|
||||
}
|
||||
if input.SortOrder != nil {
|
||||
ref.SortOrder = *input.SortOrder
|
||||
}
|
||||
if err := r.Store.DB.Save(&ref).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ref, nil
|
||||
}
|
||||
|
||||
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
|
||||
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// JobAppReferences is the resolver for the jobAppReferences field.
|
||||
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var refs []*models.JobAppReference
|
||||
// created_at is the final tie-break so entries sharing a sort_order (the
|
||||
// default 0) keep a stable, insertion-ordered sequence.
|
||||
if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
|
||||
// JobAppReference returns JobAppReferenceResolver implementation.
|
||||
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
|
||||
|
||||
type jobAppReferenceResolver struct{ *Resolver }
|
||||
@@ -1,144 +0,0 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobApplication is the resolver for the createJobApplication field.
|
||||
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// String! is non-null but not non-empty, and the columns are only
|
||||
// `not null`, so "" stores happily and then never matches the email
|
||||
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
|
||||
jobTitle := strings.TrimSpace(input.JobTitle)
|
||||
company := strings.TrimSpace(input.Company)
|
||||
if jobTitle == "" || company == "" {
|
||||
return nil, fmt.Errorf("jobTitle and company are required")
|
||||
}
|
||||
app := models.JobApplication{
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: services.NormalizeStatus(input.Status),
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
}
|
||||
if err := r.Store.DB.Create(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// UpdateJobApplication is the resolver for the updateJobApplication field.
|
||||
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Partial update: every input field is a pointer so that "not supplied"
|
||||
// is distinguishable from "set to empty". A nil field is left untouched.
|
||||
// An explicit "" on a nullable column does clear it — that is how the UI
|
||||
// empties a wrong URL or stale notes — but the same value on a required
|
||||
// column is rejected rather than blanking a live row.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.JobTitle != nil {
|
||||
if strings.TrimSpace(*input.JobTitle) == "" {
|
||||
return nil, fmt.Errorf("jobTitle cannot be empty")
|
||||
}
|
||||
app.JobTitle = strings.TrimSpace(*input.JobTitle)
|
||||
}
|
||||
if input.Company != nil {
|
||||
if strings.TrimSpace(*input.Company) == "" {
|
||||
return nil, fmt.Errorf("company cannot be empty")
|
||||
}
|
||||
app.Company = strings.TrimSpace(*input.Company)
|
||||
}
|
||||
if input.Location != nil {
|
||||
app.Location = input.Location
|
||||
}
|
||||
if input.URL != nil {
|
||||
app.URL = input.URL
|
||||
}
|
||||
if input.Status != nil {
|
||||
app.Status = services.NormalizeStatus(*input.Status)
|
||||
}
|
||||
if input.Notes != nil {
|
||||
app.Notes = input.Notes
|
||||
}
|
||||
if input.AppliedAt != nil {
|
||||
app.AppliedAt = input.AppliedAt
|
||||
}
|
||||
if err := r.Store.DB.Save(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// DeleteJobApplication is the resolver for the deleteJobApplication field.
|
||||
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Soft delete straight by id, without loading first — so deleting an id
|
||||
// that does not exist still returns true.
|
||||
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// JobApplications is the resolver for the jobApplications field.
|
||||
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
|
||||
// Admin-only even though it is a query: job applications are private.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
// id is the tie-break: one sync loop inserts several rows inside the same
|
||||
// timestamp, and Postgres gives no stable order for equal sort keys, so
|
||||
// without it the list can reshuffle between two identical page loads.
|
||||
if err := r.Store.DB.Order("created_at desc, id desc").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return apps, nil
|
||||
}
|
||||
|
||||
// JobApplication is the resolver for the jobApplication field.
|
||||
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// JobApplication returns JobApplicationResolver implementation.
|
||||
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
|
||||
|
||||
type jobApplicationResolver struct{ *Resolver }
|
||||
@@ -11,11 +11,6 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// AuthorID is the resolver for the authorId field.
|
||||
// AuthorID is the resolver for the authorId field. The value is the chat
|
||||
// hub's per-connection counter, not a User id — see models.Message.
|
||||
|
||||
@@ -13,9 +13,10 @@ import (
|
||||
// It always attaches the *gin.Context, and attaches the JWT claims only when a
|
||||
// valid access token is present. Crucially it never rejects a request: a
|
||||
// missing, expired or forged token simply leaves the context anonymous, which
|
||||
// is what lets public queries work and pushes every authorisation decision
|
||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
||||
// errors are swallowed for exactly that reason.
|
||||
// is what lets public queries work and leaves every authorisation decision
|
||||
// to the field being resolved — the @admin / @signedIn directives on it (see
|
||||
// directives.go), or the resolver itself for anything finer. Both cookie and
|
||||
// verify errors are swallowed for exactly that reason.
|
||||
//
|
||||
// It takes the database because validating a token means loading the user to
|
||||
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
|
||||
|
||||
@@ -30,23 +30,6 @@ type CreateFavoriteInput struct {
|
||||
Link *string `json:"link,omitempty"`
|
||||
}
|
||||
|
||||
type CreateJobAppReferenceInput struct {
|
||||
Category string `json:"category"`
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
SortOrder *int `json:"sortOrder,omitempty"`
|
||||
}
|
||||
|
||||
type CreateJobApplicationInput struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
}
|
||||
|
||||
type CreatePlaceInput struct {
|
||||
Title string `json:"title"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
@@ -130,23 +113,6 @@ type SteamStatus struct {
|
||||
RecentGames []*SteamGame `json:"recentGames"`
|
||||
}
|
||||
|
||||
type UpdateJobAppReferenceInput struct {
|
||||
Category *string `json:"category,omitempty"`
|
||||
Label *string `json:"label,omitempty"`
|
||||
Value *string `json:"value,omitempty"`
|
||||
SortOrder *int `json:"sortOrder,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateJobApplicationInput struct {
|
||||
JobTitle *string `json:"jobTitle,omitempty"`
|
||||
Company *string `json:"company,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
}
|
||||
|
||||
type UpdatePlaceInput struct {
|
||||
Title *string `json:"title,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
|
||||
@@ -7,7 +7,6 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
@@ -16,11 +15,9 @@ import (
|
||||
// CreatePlace is the resolver for the createPlace field.
|
||||
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
|
||||
// Any signed-in user, not just an admin — places are the one shared,
|
||||
// collaboratively edited list on the site. There is no per-user
|
||||
// ownership, so any signed-in user can edit or delete any place.
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// collaboratively edited list on the site, so the schema marks these
|
||||
// fields @signedIn rather than @admin. There is no per-user ownership, so
|
||||
// any signed-in user can edit or delete any place.
|
||||
place := models.Place{
|
||||
Title: input.Title,
|
||||
Location: input.Location,
|
||||
@@ -43,9 +40,6 @@ func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePl
|
||||
|
||||
// UpdatePlace is the resolver for the updatePlace field.
|
||||
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// Partial update, same pointer-means-supplied convention as job
|
||||
// applications: nil fields are left as they are.
|
||||
var place models.Place
|
||||
@@ -84,9 +78,6 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
||||
|
||||
// DeletePlace is the resolver for the deletePlace field.
|
||||
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var place models.Place
|
||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,24 +88,11 @@ func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Pla
|
||||
return &place, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *placeResolver) ID(ctx context.Context, obj *models.Place) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Places is the resolver for the places field.
|
||||
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var places []models.Place
|
||||
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(places), nil
|
||||
}
|
||||
|
||||
// Place returns PlaceResolver implementation.
|
||||
func (r *Resolver) Place() PlaceResolver { return &placeResolver{r} }
|
||||
|
||||
type placeResolver struct{ *Resolver }
|
||||
|
||||
@@ -15,10 +15,9 @@ import (
|
||||
|
||||
// CreatePost is the resolver for the createPost field.
|
||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// @admin has already established that there is a session; the id is read
|
||||
// here because the post needs an author, not as a second gate. The !ok
|
||||
// branch is only reachable with a token that has admin but no usable id.
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -34,10 +33,6 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
|
||||
|
||||
// UpdatePost is the resolver for the updatePost field.
|
||||
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -48,8 +43,9 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
// Admin alone is not enough: a post may only be edited by its author, so
|
||||
// one admin cannot rewrite another's posts.
|
||||
// Admin alone (the @admin on the field) is not enough: a post may only be
|
||||
// edited by its author, so one admin cannot rewrite another's posts. This
|
||||
// is the kind of rule a directive cannot express, so it stays here.
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
@@ -67,10 +63,6 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
|
||||
// DeletePost is the resolver for the deletePost field.
|
||||
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -95,11 +87,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Posts is the resolver for the posts field.
|
||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
// Preload issues a second query for the authors and fills in Post.Author.
|
||||
@@ -120,8 +107,3 @@ func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error)
|
||||
}
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Post returns PostResolver implementation.
|
||||
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
||||
|
||||
type postResolver struct{ *Resolver }
|
||||
|
||||
@@ -12,10 +12,12 @@ import "adam-french.co.uk/backend/handlers"
|
||||
// same handlers.Store the REST handlers use, so GraphQL and REST share one
|
||||
// database handle and one set of third-party caches.
|
||||
//
|
||||
// The generated code embeds *Resolver in per-type resolver structs
|
||||
// (queryResolver, mutationResolver, postResolver, ...), which is why those
|
||||
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
|
||||
// resolvers file.
|
||||
// The generated code embeds *Resolver in per-type resolver structs, which is
|
||||
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
|
||||
// resolvers files. A type only gets one when a field of it needs a resolver:
|
||||
// queryResolver and mutationResolver always, messageResolver and
|
||||
// rowingResolver for their unsigned-to-Int fields. Most object types bind
|
||||
// every field straight to the model and have none.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -20,11 +20,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
return ptrs(rows), nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Time is the resolver for the time field.
|
||||
// Time is the resolver for the time field: total session seconds, narrowed
|
||||
// from uint64 to GraphQL's Int.
|
||||
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createActivity(input: CreateActivityInput!): Activity!
|
||||
createActivity(input: CreateActivityInput!): Activity! @admin
|
||||
}
|
||||
|
||||
@@ -7,10 +7,14 @@ type AuthPayload {
|
||||
user: User!
|
||||
}
|
||||
|
||||
# `me` carries no directive although it needs a session: it answers
|
||||
# "unauthorized", not @signedIn's "authentication required", and the front end
|
||||
# relies on that query failing quietly for an anonymous visitor.
|
||||
extend type Query {
|
||||
me: User
|
||||
}
|
||||
|
||||
# Deliberately public: these are how a session is obtained and given up.
|
||||
extend type Mutation {
|
||||
login(input: LoginInput!): AuthPayload!
|
||||
logout: Boolean!
|
||||
|
||||
@@ -18,6 +18,6 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark!
|
||||
deleteBookmark(id: ID!): Bookmark!
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark! @admin
|
||||
deleteBookmark(id: ID!): Bookmark! @admin
|
||||
}
|
||||
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite!
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
type JobAppReference {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
category: String!
|
||||
label: String!
|
||||
value: String!
|
||||
sortOrder: Int!
|
||||
}
|
||||
|
||||
input CreateJobAppReferenceInput {
|
||||
category: String!
|
||||
label: String!
|
||||
value: String!
|
||||
sortOrder: Int
|
||||
}
|
||||
|
||||
input UpdateJobAppReferenceInput {
|
||||
category: String
|
||||
label: String
|
||||
value: String
|
||||
sortOrder: Int
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobAppReferences: [JobAppReference!]!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
|
||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
|
||||
deleteJobAppReference(id: ID!): Boolean!
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
# Job application tracker. Rows come from these mutations or automatically
|
||||
# from the email sync pipeline (backend/services/email_sync.go). These are
|
||||
# private data, so the queries here are admin-only as well as the mutations.
|
||||
#
|
||||
# status is a free-form String, but only the values ranked in
|
||||
# services.statusOrder can be advanced automatically by the email pipeline:
|
||||
# applied, screening, assessment, interviewing, offer, rejected, withdrawn.
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
jobTitle: String!
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
}
|
||||
|
||||
input CreateJobApplicationInput {
|
||||
jobTitle: String!
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
}
|
||||
|
||||
input UpdateJobApplicationInput {
|
||||
jobTitle: String
|
||||
company: String
|
||||
location: String
|
||||
url: String
|
||||
status: String
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobApplications: [JobApplication!]!
|
||||
jobApplication(id: ID!): JobApplication
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
|
||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
|
||||
deleteJobApplication(id: ID!): Boolean!
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
#
|
||||
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
|
||||
# User id, and private messages are silently filtered out for non-admins
|
||||
# rather than causing an error.
|
||||
# rather than causing an error — which is why the query has no @admin: the
|
||||
# resolver makes that decision per row.
|
||||
|
||||
type Message {
|
||||
id: ID!
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Places to go. Unlike most mutations these require only a signed-in user,
|
||||
# not an admin, and there is no per-user ownership: the list is shared.
|
||||
# Places to go. Unlike most mutations these require only a signed-in user
|
||||
# (@signedIn), not an admin, and there is no per-user ownership: the list is
|
||||
# shared. The query is guarded too — the list is not public.
|
||||
|
||||
type Place {
|
||||
id: ID!
|
||||
@@ -38,11 +39,11 @@ input UpdatePlaceInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
places: [Place!]!
|
||||
places: [Place!]! @signedIn
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createPlace(input: CreatePlaceInput!): Place!
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place!
|
||||
deletePlace(id: ID!): Place!
|
||||
createPlace(input: CreatePlaceInput!): Place! @signedIn
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
|
||||
deletePlace(id: ID!): Place! @signedIn
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ extend type Query {
|
||||
post(id: ID!): Post
|
||||
}
|
||||
|
||||
# @admin is only the first half of the rule for updatePost and deletePost:
|
||||
# the resolver also requires the caller to be the post's author.
|
||||
extend type Mutation {
|
||||
createPost(input: CreatePostInput!): Post!
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post!
|
||||
deletePost(id: ID!): Post!
|
||||
createPost(input: CreatePostInput!): Post! @admin
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
|
||||
deletePost(id: ID!): Post! @admin
|
||||
}
|
||||
|
||||
@@ -16,5 +16,22 @@
|
||||
|
||||
scalar Time
|
||||
|
||||
# Authorisation. There is no middleware in front of /graphql, so a field is
|
||||
# PUBLIC unless it carries one of these. Each is implemented once, in
|
||||
# graph/directives.go, and runs before the field's resolver:
|
||||
#
|
||||
# @admin the request must carry an admin's access token
|
||||
# (error: "admin access required")
|
||||
# @signedIn any valid access token will do
|
||||
# (error: "authentication required")
|
||||
#
|
||||
# Every mutation needs one of them unless it is deliberately public (login,
|
||||
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
|
||||
# which queries are guarded. Rules that are not a plain gate stay in the
|
||||
# resolver: a post is only editable by its author, `me` answers for whoever is
|
||||
# signed in, and `messages` filters private rows rather than refusing.
|
||||
directive @admin on FIELD_DEFINITION
|
||||
directive @signedIn on FIELD_DEFINITION
|
||||
|
||||
type Query
|
||||
type Mutation
|
||||
|
||||
@@ -36,6 +36,7 @@ extend type Query {
|
||||
spotifyRecent: [SpotifyRecentItem!]
|
||||
# True only for an admin session while the backend lacks a Spotify client
|
||||
# (OAuth never completed or the token was revoked), used by the Listening
|
||||
# widget to offer a reconnect link. Everyone else gets false.
|
||||
# widget to offer a reconnect link. Everyone else gets false — a soft
|
||||
# check in the resolver, not @admin, so the home page query never errors.
|
||||
spotifyNeedsReauth: Boolean!
|
||||
}
|
||||
|
||||
@@ -12,12 +12,12 @@ input CreateUserInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
users: [User!]!
|
||||
user(id: ID!): User
|
||||
users: [User!]! @admin
|
||||
user(id: ID!): User @admin
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createUser(input: CreateUserInput!): User!
|
||||
deleteUser(id: ID!): User!
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User!
|
||||
createUser(input: CreateUserInput!): User! @admin
|
||||
deleteUser(id: ID!): User! @admin
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
|
||||
}
|
||||
|
||||
@@ -61,6 +61,8 @@ func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// A soft check, deliberately not @admin: the directive would turn this
|
||||
// into an error on the public home page query.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -16,12 +16,9 @@ import (
|
||||
|
||||
// CreateUser is the resolver for the createUser field.
|
||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Only an existing admin can create accounts — there is no public
|
||||
// sign-up. New users are created non-admin; setUserAdmin promotes them.
|
||||
// Only an existing admin can create accounts (@admin in the schema) —
|
||||
// there is no public sign-up. New users are created non-admin;
|
||||
// setUserAdmin promotes them.
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -37,10 +34,6 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
||||
|
||||
// DeleteUser is the resolver for the deleteUser field.
|
||||
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
@@ -55,10 +48,6 @@ func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User
|
||||
|
||||
// SetUserAdmin is the resolver for the setUserAdmin field.
|
||||
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
callerID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -85,9 +74,6 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
||||
|
||||
// Users is the resolver for the users field.
|
||||
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var users []models.User
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,22 +83,9 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
|
||||
// User is the resolver for the user field.
|
||||
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// User returns UserResolver implementation.
|
||||
func (r *Resolver) User() UserResolver { return &userResolver{r} }
|
||||
|
||||
type userResolver struct{ *Resolver }
|
||||
|
||||
@@ -8,95 +8,10 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This file backs the admin diagnostics panel: a configuration report and a
|
||||
// log tail. Both are admin-only REST endpoints rather than GraphQL because
|
||||
// they read the process environment and the filesystem — things outside the
|
||||
// data model the GraphQL schema describes.
|
||||
|
||||
// ConfigVar describes one piece of configuration the backend can report on.
|
||||
// Required marks vars whose absence visibly breaks a feature; Optional vars
|
||||
// have a working default.
|
||||
type ConfigVar struct {
|
||||
Name string `json:"name"`
|
||||
Purpose string `json:"purpose"`
|
||||
Required bool `json:"required"`
|
||||
}
|
||||
|
||||
// configVars is the checklist the panel renders. Sensitive values are never
|
||||
// returned — only whether each var is present — so the endpoint cannot leak
|
||||
// credentials even to an admin client.
|
||||
var configVars = []ConfigVar{
|
||||
{"POSTGRES_HOST", "Database connectivity", true},
|
||||
{"POSTGRES_USER", "Database connectivity", true},
|
||||
{"POSTGRES_PASSWORD", "Database connectivity", true},
|
||||
{"POSTGRES_DB", "Database connectivity", true},
|
||||
{"DOMAIN", "Site origin, JWT cookie domain", true},
|
||||
{"AUTH_SECRET", "JWT signing", true},
|
||||
{"SPOTIFY_CLIENT_ID", "Spotify listening widget", true},
|
||||
{"SPOTIFY_CLIENT_SECRET", "Spotify listening widget", true},
|
||||
{"SPOTIFY_REDIRECT_URI", "Spotify listening widget", true},
|
||||
{"STEAM_API_KEY", "Steam status widget", false},
|
||||
{"STEAM_ID", "Steam status widget", false},
|
||||
{"CLAUDE_API_KEY", "Email summarisation", false},
|
||||
{"EMAIL_BACKEND", "Email sync (graph/imap)", false},
|
||||
{"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_REDIRECT_URI", "Email sync (Microsoft Graph)", false},
|
||||
{"MSGRAPH_TENANT_ID", "Email sync (Microsoft Graph)", false},
|
||||
{"IMAP_HOST", "Email sync (IMAP fallback)", false},
|
||||
{"IMAP_EMAIL", "Email sync (IMAP fallback)", false},
|
||||
{"IMAP_PASSWORD", "Email sync (IMAP fallback)", false},
|
||||
{"GITEA_HOST", "Gitea activity feed", false},
|
||||
{"GITEA_PORT", "Gitea activity feed", false},
|
||||
{"JWT_COOKIE_SECURE", "Cookie security in dev", false},
|
||||
{"ICECAST_URL", "Radio queue widget", false},
|
||||
}
|
||||
|
||||
// ConfigCheck backs GET /admin/config. It reports one entry per known var:
|
||||
// set or empty, plus the value only for vars flagged non-sensitive (none of
|
||||
// the credentials are). A var not in the list at all is not reported — the
|
||||
// point is a checklist, not a full env dump.
|
||||
func (store *Store) ConfigCheck(ctx *gin.Context) {
|
||||
type entry struct {
|
||||
ConfigVar
|
||||
Set bool `json:"set"`
|
||||
Value string `json:"value,omitempty"`
|
||||
Secret bool `json:"secret"`
|
||||
}
|
||||
|
||||
// Vars whose *value* may come back (bad values like "consumers" are fine;
|
||||
// they contain no credential).
|
||||
visible := map[string]bool{
|
||||
"EMAIL_BACKEND": true,
|
||||
"MSGRAPH_TENANT_ID": true,
|
||||
"ICECAST_URL": true,
|
||||
"STEAM_ID": true,
|
||||
}
|
||||
|
||||
// Explicitly-credentialled vars get the secret badge so the panel can
|
||||
// label them "present" instead of showing a masked string.
|
||||
secrets := map[string]bool{
|
||||
"POSTGRES_PASSWORD": true,
|
||||
"AUTH_SECRET": true,
|
||||
"SPOTIFY_CLIENT_SECRET": true,
|
||||
"MSGRAPH_CLIENT_SECRET": true,
|
||||
"CLAUDE_API_KEY": true,
|
||||
"STEAM_API_KEY": true,
|
||||
"IMAP_PASSWORD": true,
|
||||
}
|
||||
|
||||
result := make([]entry, 0, len(configVars))
|
||||
for _, v := range configVars {
|
||||
val := os.Getenv(v.Name)
|
||||
e := entry{ConfigVar: v, Set: strings.TrimSpace(val) != "", Secret: secrets[v.Name]}
|
||||
if e.Set && visible[v.Name] {
|
||||
e.Value = val
|
||||
}
|
||||
result = append(result, e)
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"vars": result})
|
||||
}
|
||||
// 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. The configuration report that
|
||||
// used to live here is now the Environment tab (handle_env.go).
|
||||
|
||||
// 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
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// REST endpoints for the job-application email pipeline: a manual
|
||||
// admin-triggered sync, and the OAuth redirect target (which has to be REST
|
||||
// because Microsoft redirects a browser to it).
|
||||
|
||||
// TriggerEmailSync backs the admin-only POST /email/sync and runs one sync
|
||||
// synchronously, so the response reflects the result. If the scheduler is
|
||||
// mid-sync the service refuses via TryLock and this returns 500.
|
||||
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
||||
// A nil HTTPClient is the service's readiness flag — see
|
||||
// services.EmailSyncService.
|
||||
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
|
||||
return
|
||||
}
|
||||
|
||||
err := store.EmailSync.SyncEmails(ctx.Request.Context())
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Manual sync error: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "sync failed", "details": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
|
||||
}
|
||||
|
||||
// CompleteEmailAuth handles Microsoft's OAuth redirect to
|
||||
// GET /email/callback and stores the resulting token.
|
||||
//
|
||||
// The route is unauthenticated (Microsoft's redirect carries no site cookie),
|
||||
// which is safe only because the code is worthless without the app's client
|
||||
// secret. Note that completing auth here does not start the scheduler, which
|
||||
// only checks readiness at start-up — a restart is needed for that.
|
||||
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
|
||||
if store.EmailSync == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
|
||||
return
|
||||
}
|
||||
|
||||
code := ctx.Query("code")
|
||||
if code == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "missing authorization code"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := store.EmailSync.CompleteAuth(ctx.Request.Context(), code); err != nil {
|
||||
log.Printf("[EmailSync] Auth completion error: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "email authentication successful"})
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This file backs the admin panel's Environment tab: a report on every
|
||||
// variable in .env, and a way to change the ones that are safe to change.
|
||||
//
|
||||
// The handlers never read or write .env. State is this process's own
|
||||
// environment, and a change is a request left for the host to apply (see
|
||||
// services.EnvManager). REST rather than GraphQL for the same reason as the
|
||||
// rest of the admin endpoints: this is process and host state, not the data
|
||||
// model the schema describes.
|
||||
|
||||
// envSecretHintMinLen is the shortest secret that gets its last four
|
||||
// characters shown. Below it, four characters is too much of the value.
|
||||
const envSecretHintMinLen = 12
|
||||
|
||||
type envVarView struct {
|
||||
services.EnvVar
|
||||
Secret bool `json:"secret"`
|
||||
Set bool `json:"set"`
|
||||
// Value is sent only for non-secret variables; Hint (the last four
|
||||
// characters) is all a secret ever reveals.
|
||||
Value string `json:"value,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
|
||||
type envGroupView struct {
|
||||
Name string `json:"name"`
|
||||
Vars []envVarView `json:"vars"`
|
||||
}
|
||||
|
||||
// GetEnv backs GET /admin/env: every registry variable grouped for display,
|
||||
// plus the state of the latest change.
|
||||
//
|
||||
// Values are what this process was started with, not what .env holds now —
|
||||
// the two differ between a save and the recreate that follows it, which is
|
||||
// what the status's pending list is for.
|
||||
func (store *Store) GetEnv(ctx *gin.Context) {
|
||||
var groups []envGroupView
|
||||
index := map[string]int{}
|
||||
for _, v := range store.Env.Vars() {
|
||||
value := os.Getenv(v.Name)
|
||||
view := envVarView{EnvVar: v, Secret: v.Secret(), Set: strings.TrimSpace(value) != ""}
|
||||
switch {
|
||||
case !view.Set:
|
||||
case !view.Secret:
|
||||
view.Value = value
|
||||
case len(value) >= envSecretHintMinLen:
|
||||
view.Hint = value[len(value)-4:]
|
||||
}
|
||||
|
||||
i, seen := index[v.Group]
|
||||
if !seen {
|
||||
i = len(groups)
|
||||
index[v.Group] = i
|
||||
groups = append(groups, envGroupView{Name: v.Group})
|
||||
}
|
||||
groups[i].Vars = append(groups[i].Vars, view)
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"groups": groups, "status": store.Env.Status()})
|
||||
}
|
||||
|
||||
type updateEnvRequest struct {
|
||||
// Set maps a variable to its new value; "" clears it.
|
||||
Set map[string]string `json:"set"`
|
||||
// Generate names "generated" variables to mint a random value for.
|
||||
Generate []string `json:"generate"`
|
||||
}
|
||||
|
||||
// UpdateEnv backs PUT /admin/env. It queues the change for the host and
|
||||
// returns straight away; the panel follows progress on GET /admin/env/status,
|
||||
// through the backend's own restart.
|
||||
//
|
||||
// The response is the only time a generated value is sent anywhere.
|
||||
func (store *Store) UpdateEnv(ctx *gin.Context) {
|
||||
var body updateEnvRequest
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
generated, recreates, err := store.Env.Submit(body.Set, body.Generate)
|
||||
if errors.Is(err, services.ErrEnvApplying) {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
// Validation messages name the variable, never the value.
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(body.Set)+len(body.Generate))
|
||||
for name := range body.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
names = append(names, body.Generate...)
|
||||
log.Printf("[Env] change queued for %s", strings.Join(names, ", "))
|
||||
|
||||
ctx.Header("Cache-Control", "no-store")
|
||||
ctx.JSON(http.StatusAccepted, gin.H{
|
||||
"generated": generated,
|
||||
"services": recreates,
|
||||
"status": store.Env.Status(),
|
||||
})
|
||||
}
|
||||
|
||||
// GetEnvStatus backs GET /admin/env/status.
|
||||
func (store *Store) GetEnvStatus(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
|
||||
// CancelEnv backs DELETE /admin/env/pending: withdraw a request nothing on
|
||||
// the host has picked up, so new secrets do not sit in the shared directory
|
||||
// waiting for a watcher that is not there.
|
||||
func (store *Store) CancelEnv(ctx *gin.Context) {
|
||||
if err := store.Env.Cancel(); err != nil {
|
||||
log.Println("Cancelling env request failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to cancel the request"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func envRouter(t *testing.T) (*gin.Engine, string) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dir := t.TempDir()
|
||||
env, err := services.NewEnvManager(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
store := &Store{Env: env}
|
||||
r := gin.New()
|
||||
r.GET("/admin/env", store.GetEnv)
|
||||
r.PUT("/admin/env", store.UpdateEnv)
|
||||
r.GET("/admin/env/status", store.GetEnvStatus)
|
||||
r.DELETE("/admin/env/pending", store.CancelEnv)
|
||||
return r, dir
|
||||
}
|
||||
|
||||
func envDo(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// The property the whole tab rests on: a secret's value never leaves the
|
||||
// server, while a non-secret's does so it can be edited in place.
|
||||
func TestGetEnvNeverReturnsSecrets(t *testing.T) {
|
||||
r, _ := envRouter(t)
|
||||
t.Setenv("CLAUDE_API_KEY", "sk-ant-very-secret-value-9f3a")
|
||||
t.Setenv("POSTGRES_PASSWORD", "hunter2")
|
||||
t.Setenv("STEAM_ID", "76561198000000000")
|
||||
t.Setenv("TFL_APP_KEY", "")
|
||||
|
||||
rec := envDo(r, http.MethodGet, "/admin/env", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, secret := range []string{"sk-ant-very-secret-value-9f3a", "hunter2"} {
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatalf("response contains the secret %q", secret)
|
||||
}
|
||||
}
|
||||
|
||||
var parsed struct {
|
||||
Groups []struct {
|
||||
Vars []envVarView `json:"vars"`
|
||||
} `json:"groups"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
byName := map[string]envVarView{}
|
||||
for _, g := range parsed.Groups {
|
||||
for _, v := range g.Vars {
|
||||
byName[v.Name] = v
|
||||
}
|
||||
}
|
||||
|
||||
if v := byName["CLAUDE_API_KEY"]; !v.Set || !v.Secret || v.Value != "" || v.Hint != "9f3a" {
|
||||
t.Errorf("CLAUDE_API_KEY = %+v, want set, secret, no value, hint 9f3a", v)
|
||||
}
|
||||
// Too short for four characters to be a safe hint.
|
||||
if v := byName["POSTGRES_PASSWORD"]; !v.Set || v.Hint != "" || v.Editable {
|
||||
t.Errorf("POSTGRES_PASSWORD = %+v, want set, no hint, locked", v)
|
||||
}
|
||||
if v := byName["STEAM_ID"]; v.Value != "76561198000000000" || v.Secret {
|
||||
t.Errorf("STEAM_ID = %+v, want its value shown", v)
|
||||
}
|
||||
if v := byName["TFL_APP_KEY"]; v.Set {
|
||||
t.Errorf("TFL_APP_KEY = %+v, want unset", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateEnv(t *testing.T) {
|
||||
r, dir := envRouter(t)
|
||||
requestPath := filepath.Join(dir, "request.json")
|
||||
|
||||
t.Run("a locked variable is refused and nothing is queued", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"POSTGRES_PASSWORD":"x"}}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("a refused change left a request behind")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a malformed body is refused", func(t *testing.T) {
|
||||
if rec := envDo(r, http.MethodPut, "/admin/env", `{"set":`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a valid change is queued and a generated value returned once", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"STEAM_ID":"42"},"generate":["BACKEND_SECRET"]}`)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202: %s", rec.Code, rec.Body)
|
||||
}
|
||||
var parsed struct {
|
||||
Generated map[string]string `json:"generated"`
|
||||
Status services.EnvApplyStatus `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
secret := parsed.Generated["BACKEND_SECRET"]
|
||||
if len(secret) != 64 {
|
||||
t.Fatalf("generated BACKEND_SECRET = %q, want 64 hex characters", secret)
|
||||
}
|
||||
if parsed.Status.State != "pending" {
|
||||
t.Fatalf("status = %+v, want pending", parsed.Status)
|
||||
}
|
||||
|
||||
// Reading the state back must not repeat it.
|
||||
for _, path := range []string{"/admin/env", "/admin/env/status"} {
|
||||
if strings.Contains(envDo(r, http.MethodGet, path, "").Body.String(), secret) {
|
||||
t.Fatalf("GET %s repeats the generated secret", path)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a pending change can be withdrawn", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodDelete, "/admin/env/pending", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("the request file survived the cancel")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -2,8 +2,6 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
@@ -13,7 +11,6 @@ import (
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -22,15 +19,40 @@ import (
|
||||
// the admin uploads a photo of the rowing machine display and Claude reads the
|
||||
// numbers off it. The session date comes from the photo's EXIF metadata, which
|
||||
// also doubles as the deduplication key.
|
||||
//
|
||||
// The Claude call itself lives in the Python service (python/app/rowing.py),
|
||||
// reached directly over the Docker network. Everything that needs the session
|
||||
// or the database — the admin gate, EXIF, the duplicate check, the sanity
|
||||
// bounds, the insert — stays here.
|
||||
|
||||
// ExtractedRowingData is the JSON contract for what Claude reads off the
|
||||
// display; the keys must match the prompt in CreateRowing.
|
||||
// display: the body of the Python service's reply, whose keys are the ones
|
||||
// its prompt asks the model for (RowingReading in python/app/rowing.py).
|
||||
type ExtractedRowingData struct {
|
||||
TimeMinutes uint64 `json:"timeMinutes"`
|
||||
TimeSeconds uint64 `json:"timeSeconds"`
|
||||
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
|
||||
// only way in is the direct container-to-container call services.CallPython
|
||||
// makes.
|
||||
const rowingReadPath = "/internal/rowing/read"
|
||||
|
||||
// readRowingDisplay sends the image to the Python service and returns what
|
||||
// Claude read off it. No plausibility checking happens on either side of this
|
||||
// call; that is CreateRowing's job. A failure the reader described in its own
|
||||
// words comes back as a *services.PythonError (see services.CallPython).
|
||||
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
|
||||
// Data is a []byte so that it is sent as standard base64, the encoding
|
||||
// the Anthropic API expects.
|
||||
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data []byte `json:"data"`
|
||||
}{mediaType, image})
|
||||
}
|
||||
|
||||
// GetRowing backs the public GET /rowing with every logged session, newest
|
||||
// first.
|
||||
func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
@@ -47,9 +69,10 @@ func (store *Store) GetRowing(ctx *gin.Context) {
|
||||
|
||||
// CreateRowing backs the admin-only POST /rowing: it takes a photo of the
|
||||
// rowing machine display, dates it from EXIF, has Claude read the time and
|
||||
// distance, sanity-checks the result and stores a session.
|
||||
// distance (via the Python service), sanity-checks the result and stores a
|
||||
// session.
|
||||
//
|
||||
// Note it is admin-gated and calls a paid API once per request, so the
|
||||
// Note it is admin-gated and costs a paid API call once per request, so the
|
||||
// validation below exists to catch misreadings rather than hostile input.
|
||||
func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
file, err := ctx.FormFile("image")
|
||||
@@ -81,16 +104,17 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
|
||||
// exif.Decode consumed part of the stream, so rewind before reading the
|
||||
// bytes to send to Claude.
|
||||
// bytes to send on for reading.
|
||||
if _, err := f.Seek(0, io.SeekStart); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
|
||||
return
|
||||
}
|
||||
|
||||
// Cap the upload before buffering it (and then base64-encoding it, 1.33x
|
||||
// bigger): the route is admin-only but an unbounded read would still let
|
||||
// a giant file exhaust the Pi's memory and produce a huge paid API call.
|
||||
// 10MB is well above any photo this endpoint is meant to take.
|
||||
// bigger, on its way to the Python service): the route is admin-only but
|
||||
// an unbounded read would still let a giant file exhaust the Pi's memory
|
||||
// and produce a huge paid API call. 10MB is well above any photo this
|
||||
// endpoint is meant to take; the Python side's own limit is sized from it.
|
||||
if file.Size > 10<<20 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
|
||||
return
|
||||
@@ -110,13 +134,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
}
|
||||
// This is the browser's claimed type, not a sniffed one; it is passed
|
||||
// straight through to the Anthropic API, so the allow-list is there to
|
||||
// keep the API call well-formed rather than to police the file.
|
||||
// keep the API call well-formed rather than to police the file. The
|
||||
// Python service enforces the same list; checking here first gives the
|
||||
// admin a clear 400 instead of that side's validation error.
|
||||
mediaType := file.Header.Get("Content-Type")
|
||||
if !allowedMediaTypes[mediaType] {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
|
||||
return
|
||||
}
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
|
||||
// Duplicate guard: two photos of the same session share an EXIF capture
|
||||
// time to the second. Checked before the Claude call so a re-upload costs
|
||||
@@ -137,55 +162,18 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Build the message with an image + text prompt
|
||||
message, err := store.ClaudeClient.Messages.New(context.Background(), anthropic.MessageNewParams{
|
||||
Model: anthropic.ModelClaudeHaiku4_5,
|
||||
MaxTokens: 256,
|
||||
Messages: []anthropic.MessageParam{
|
||||
{
|
||||
Role: "user",
|
||||
Content: []anthropic.ContentBlockParamUnion{
|
||||
// Image block
|
||||
anthropic.NewImageBlock(anthropic.Base64ImageSourceParam{
|
||||
Type: "base64",
|
||||
MediaType: anthropic.Base64ImageSourceMediaType(mediaType),
|
||||
Data: encoded,
|
||||
}),
|
||||
// Text prompt requesting exactly 2 variables
|
||||
anthropic.NewTextBlock(
|
||||
`Look at this rowing machine display. Extract the total elapsed time and total distance.
|
||||
|
||||
Return ONLY a JSON object with these exact keys and numeric values:
|
||||
- "timeMinutes": total minutes (e.g. 2:30 = 2)
|
||||
- "timeSeconds": total seconds (e.g. 2:30 = 30)
|
||||
- "distance": distance in meters as a number (e.g. 5000)
|
||||
|
||||
No text, no markdown, no explanation. Just the JSON object.`),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to process image"})
|
||||
return
|
||||
}
|
||||
|
||||
if len(message.Content) == 0 {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "empty response from image processor"})
|
||||
return
|
||||
}
|
||||
|
||||
// Strip a markdown code fence if the model wrapped its JSON in one
|
||||
// despite the prompt; shared with the email pipeline, which asks for bare
|
||||
// JSON in the same way and gets fenced output just as often.
|
||||
extractedData := ExtractedRowingData{}
|
||||
raw := services.StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
err = json.Unmarshal([]byte(raw), &extractedData)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse image data"})
|
||||
// The reader's own messages ("failed to parse image data", ...) are
|
||||
// passed on; anything else is a plumbing failure the admin can do
|
||||
// nothing with.
|
||||
msg := "failed to process image"
|
||||
var readErr *services.PythonError
|
||||
if errors.As(err, &readErr) {
|
||||
msg = readErr.Detail
|
||||
}
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// readRowingDisplay is the Go half of the contract with the Python service's
|
||||
// /internal/rowing/read. CreateRowing itself needs a database and a real
|
||||
// multipart photo with EXIF, so what is covered is the call: the request the
|
||||
// Python side receives, and how each kind of reply comes back.
|
||||
|
||||
func rowingReader(t *testing.T, handler http.HandlerFunc) *Store {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &Store{PythonURL: srv.URL}
|
||||
}
|
||||
|
||||
func TestReadRowingDisplayRequestAndReply(t *testing.T) {
|
||||
var got struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
var path string
|
||||
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
|
||||
// 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 {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}`))
|
||||
})
|
||||
|
||||
data, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("hello"))
|
||||
if err != nil {
|
||||
t.Fatalf("readRowingDisplay: %v", err)
|
||||
}
|
||||
if data != (ExtractedRowingData{TimeMinutes: 20, TimeSeconds: 5, Distance: 5000}) {
|
||||
t.Fatalf("got %+v", data)
|
||||
}
|
||||
if path != rowingReadPath {
|
||||
t.Fatalf("path = %q, want %q", path, rowingReadPath)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python route rejects")
|
||||
}
|
||||
// "hello" in standard base64, the encoding the Anthropic API expects.
|
||||
if got.MediaType != "image/jpeg" || got.Data != "aGVsbG8=" {
|
||||
t.Fatalf("request body = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadRowingDisplayErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a services.PythonError with this message
|
||||
}{
|
||||
{"reader failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"non-JSON 502 is not relayed", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
|
||||
{"malformed success body", http.StatusOK, `not json`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
|
||||
_, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("x"))
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *services.PythonError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.Detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/zmb3/spotify/v2"
|
||||
spotifyauth "github.com/zmb3/spotify/v2/auth"
|
||||
"gorm.io/gorm"
|
||||
@@ -30,11 +29,18 @@ type Store struct {
|
||||
DB *gorm.DB
|
||||
SpotifyAuth *spotifyauth.Authenticator
|
||||
SpotifyClient *spotify.Client
|
||||
ClaudeClient *anthropic.Client
|
||||
Auth *services.Auth
|
||||
Notes *services.Notes
|
||||
LoginLimiter *services.RateLimiter
|
||||
EmailSync *services.EmailSyncService
|
||||
|
||||
// Base URL of the Python service on the Docker network, no trailing
|
||||
// slash. Used for the calls that bypass nginx, all through
|
||||
// services.CallPython: reading a rowing display photo (handle_rowing.go).
|
||||
PythonURL string
|
||||
|
||||
// Registry of .env variables and the request/status hand-off with the
|
||||
// host that applies changes to them (handle_env.go).
|
||||
Env *services.EnvManager
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
|
||||
+45
-48
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
@@ -27,8 +26,9 @@ import (
|
||||
// setting from the environment, builds the services, packs them into one
|
||||
// handlers.Store, and registers the routes. There are three route groups —
|
||||
// open, `protected` (valid access token) and `admin` (token with admin=true)
|
||||
// — plus the GraphQL endpoint, which does its own per-resolver authorisation
|
||||
// instead of using middleware. See backend/README.md for the wider picture.
|
||||
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
|
||||
// directives in its schema instead of by middleware. See backend/README.md
|
||||
// for the wider picture.
|
||||
func main() {
|
||||
// Logs go to both stdout (so `docker compose logs` works) and a file in a
|
||||
// mounted volume (so they survive the container).
|
||||
@@ -89,10 +89,10 @@ func main() {
|
||||
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
|
||||
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
|
||||
|
||||
// CLAUDE
|
||||
claudeAPIKey := os.Getenv("CLAUDE_API_KEY")
|
||||
claudeConfig := services.ClaudeConfig{APIKey: claudeAPIKey}
|
||||
claudeClient := services.InitClaude(&claudeConfig)
|
||||
// No Claude client here: the site's one Claude call, the rowing photo
|
||||
// reader, is made by the Python service, which is the only container of
|
||||
// the site's own that reads CLAUDE_API_KEY. The backend reaches it at
|
||||
// pythonURL, below. (The job tracker, a separate container, makes its own.)
|
||||
|
||||
authSecret := os.Getenv("BACKEND_SECRET")
|
||||
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
||||
@@ -114,37 +114,33 @@ func main() {
|
||||
steamAPIKey := os.Getenv("STEAM_API_KEY")
|
||||
steamID := os.Getenv("STEAM_ID")
|
||||
|
||||
// EMAIL SYNC
|
||||
// An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30
|
||||
// minute default stands — a typo here fails quietly.
|
||||
emailSyncInterval := 30 * time.Minute
|
||||
if interval := os.Getenv("EMAIL_SYNC_INTERVAL"); interval != "" {
|
||||
if parsed, err := time.ParseDuration(interval); err == nil {
|
||||
emailSyncInterval = parsed
|
||||
}
|
||||
// PYTHON SERVICE
|
||||
// Called directly over the Docker network, not through nginx, 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")
|
||||
if pythonHost == "" {
|
||||
pythonHost = "python"
|
||||
}
|
||||
emailSyncConfig := services.EmailSyncConfig{
|
||||
Backend: os.Getenv("EMAIL_BACKEND"),
|
||||
ClientID: os.Getenv("MSGRAPH_CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("MSGRAPH_CLIENT_SECRET"),
|
||||
TenantID: os.Getenv("MSGRAPH_TENANT_ID"),
|
||||
RedirectURI: os.Getenv("MSGRAPH_REDIRECT_URI"),
|
||||
IMAP: &services.IMAPConfig{
|
||||
Host: os.Getenv("IMAP_HOST"),
|
||||
Port: os.Getenv("IMAP_PORT"),
|
||||
Email: os.Getenv("IMAP_EMAIL"),
|
||||
Password: os.Getenv("IMAP_PASSWORD"),
|
||||
},
|
||||
SyncInterval: emailSyncInterval,
|
||||
Enabled: os.Getenv("EMAIL_SYNC_ENABLED") == "true",
|
||||
pythonPort := os.Getenv("PYTHON_PORT")
|
||||
if pythonPort == "" {
|
||||
pythonPort = "8000"
|
||||
}
|
||||
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
|
||||
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
|
||||
|
||||
// 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.
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID}
|
||||
// ENVIRONMENT
|
||||
// The registry is embedded, so the only way this fails is a malformed
|
||||
// env_registry.json — a build mistake worth stopping for.
|
||||
envManager, err := services.NewEnvManager(services.ENV_APPLY_DIR)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
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, Env: envManager}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
@@ -164,10 +160,6 @@ func main() {
|
||||
r.POST("/auth/logout", store.Logout)
|
||||
r.GET("/auth/validate-admin", store.ValidateAdmin)
|
||||
|
||||
// EMAIL SYNC
|
||||
r.GET("/email/callback", store.CompleteEmailAuth)
|
||||
admin.POST("/email/sync", store.TriggerEmailSync)
|
||||
|
||||
// SPOTIFY
|
||||
// The callback must be open — Spotify redirects a logged-out browser to
|
||||
// it — and is protected by the state nonce instead. Starting the flow is
|
||||
@@ -194,19 +186,31 @@ func main() {
|
||||
// NOTES
|
||||
admin.GET("/notes/*path", store.GetNoteFile)
|
||||
|
||||
// ADMIN DIAGNOSTICS: env-var checklist and log tail for the admin panel.
|
||||
admin.GET("/admin/config", store.ConfigCheck)
|
||||
// ADMIN DIAGNOSTICS: log tail for the admin panel.
|
||||
admin.GET("/admin/logs", store.Logs)
|
||||
// ENVIRONMENT: report on .env and queue changes for the host to apply.
|
||||
admin.GET("/admin/env", store.GetEnv)
|
||||
admin.PUT("/admin/env", store.UpdateEnv)
|
||||
admin.GET("/admin/env/status", store.GetEnvStatus)
|
||||
admin.DELETE("/admin/env/pending", store.CancelEnv)
|
||||
|
||||
// GRAPHQL
|
||||
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
|
||||
// so the transports and extensions below are explicit.
|
||||
//
|
||||
// Note the whole API is one POST route with no middleware guard:
|
||||
// authorisation happens per resolver via IsAdminFromCtx / UserIDFromCtx,
|
||||
// so a new resolver is PUBLIC until it checks for itself.
|
||||
// Note the whole API is one POST route with no middleware guard.
|
||||
// Authorisation is declared in the schema instead: a field marked @admin
|
||||
// or @signedIn is refused by the matching function in graph.Directives()
|
||||
// before its resolver runs. A field with neither is PUBLIC, so a new
|
||||
// mutation needs one — graph/directives_test.go fails until it has one or
|
||||
// is added to the list of deliberately public fields there.
|
||||
//
|
||||
// Directives must stay wired here: gqlgen fails closed on a nil directive
|
||||
// (the field errors with "directive admin is not implemented"), so
|
||||
// dropping this line breaks every guarded field rather than opening it.
|
||||
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
Directives: graph.Directives(),
|
||||
}))
|
||||
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
|
||||
gqlSrv.AddTransport(transport.Options{})
|
||||
@@ -240,13 +244,6 @@ func main() {
|
||||
c.JSON(200, gin.H{"message": "Hello World"})
|
||||
})
|
||||
|
||||
// The scheduler runs until ctx is cancelled, which in practice only
|
||||
// happens if r.Run returns — there is no signal handling or graceful
|
||||
// shutdown, so the container is simply killed.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go store.EmailSync.StartScheduler(ctx)
|
||||
|
||||
port := os.Getenv("BACKEND_PORT")
|
||||
// Blocks until the server stops. Any return is a failure — a port clash,
|
||||
// most often — so it must exit non-zero, or Docker sees a clean shutdown
|
||||
|
||||
@@ -20,8 +20,9 @@ import (
|
||||
// every subsequent query silently filters those rows out. Rows are never
|
||||
// actually removed, and a uniqueIndex still sees deleted rows, so a
|
||||
// soft-deleted username cannot be reused.
|
||||
// - IDs are uint in Go but Int in GraphQL, which is why nearly every type
|
||||
// has a hand-written ID resolver doing int(obj.ID).
|
||||
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
|
||||
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
|
||||
// On the wire an id is a quoted decimal string, "12".
|
||||
|
||||
// User is an account. There is no public sign-up: users are created by an
|
||||
// existing admin through the createUser mutation, or by the dev seeder.
|
||||
@@ -137,57 +138,6 @@ type Bookmark struct {
|
||||
Link string `gorm:"not null" json:"link"`
|
||||
}
|
||||
|
||||
// JobAppReference is a reusable snippet for filling in job application forms
|
||||
// (a stock answer, a profile link, and so on), grouped by Category and
|
||||
// ordered within it by SortOrder.
|
||||
type JobAppReference struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Category string `gorm:"not null" json:"category"`
|
||||
Label string `gorm:"not null" json:"label"`
|
||||
Value string `gorm:"not null" json:"value"`
|
||||
SortOrder int `gorm:"default:0" json:"sortOrder"`
|
||||
}
|
||||
|
||||
// ProcessedEmail records that the email pipeline has already looked at a
|
||||
// message, so it is never classified twice.
|
||||
//
|
||||
// Unlike every other model it has no DeletedAt and so is NOT soft deleted —
|
||||
// the dedup check must see every historical row. Its CreatedAt also drives
|
||||
// the next sync's time window, so the most recent row here is effectively the
|
||||
// pipeline's cursor. A row is written even when classification failed, with
|
||||
// Action "error", which means failures are never retried.
|
||||
type ProcessedEmail struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
// The provider's message id: Microsoft Graph's id on the Graph backend,
|
||||
// the RFC822 Message-ID header on IMAP. Unique, which is what makes the
|
||||
// dedup check safe against a concurrent sync.
|
||||
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
|
||||
Subject string `gorm:"not null" json:"subject"`
|
||||
Action string `gorm:"not null" json:"action"`
|
||||
// The application this email created or updated, if any. A plain nullable
|
||||
// column, not a GORM association — nothing preloads it.
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
// Attempts counts how many times processing this email has been tried.
|
||||
// A row with Action "error" and Attempts below the cap is retryable: the
|
||||
// next sync re-processes it instead of skipping it. Once Attempts reaches
|
||||
// the cap the row becomes terminal, so a genuinely unprocessable email
|
||||
// (one Claude can never parse) eventually stops consuming API calls.
|
||||
// Rows written before this column existed default to 1 and so get their
|
||||
// remaining attempts.
|
||||
Attempts int `gorm:"not null;default:1" json:"attempts"`
|
||||
// ReceivedAt is the provider's own timestamp for the email, as distinct
|
||||
// from CreatedAt (when we processed it). It exists so a retryable failure
|
||||
// can pull the fetch window back far enough to actually re-fetch the
|
||||
// email: the window is otherwise anchored to processing time, which would
|
||||
// have already advanced past it. Zero for rows written before this
|
||||
// column existed, and for those the clamp is skipped.
|
||||
ReceivedAt time.Time `json:"receivedAt"`
|
||||
}
|
||||
|
||||
// Place is an entry on the places-to-go list. Creating or editing one needs
|
||||
// only a signed-in user, not an admin — the one exception to the
|
||||
// admin-writes-everything rule.
|
||||
@@ -205,25 +155,3 @@ type Place struct {
|
||||
Priority int `gorm:"default:0" json:"priority"`
|
||||
Done bool `gorm:"default:false" json:"done"`
|
||||
}
|
||||
|
||||
// JobApplication is a tracked job application. Rows are created by hand
|
||||
// through GraphQL or automatically by the email pipeline.
|
||||
//
|
||||
// Status is a free-form string, but only the values ranked in
|
||||
// services.statusOrder ("applied", "screening", "assessment",
|
||||
// "interviewing", "offer", "rejected", "withdrawn") can be advanced
|
||||
// automatically; the pipeline matches an existing application on
|
||||
// (Company, JobTitle) compared case-insensitively.
|
||||
type JobApplication struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
Status string `gorm:"not null" json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
AppliedAt *time.Time `json:"appliedAt"`
|
||||
}
|
||||
|
||||
@@ -18,7 +18,9 @@ import (
|
||||
|
||||
func testAuth() *Auth {
|
||||
return InitAuth(&AuthConfig{
|
||||
Secret: []byte("test-secret"),
|
||||
// InitAuth panics on anything under 32 bytes, so the fixture has to be
|
||||
// a realistic length even though nothing here depends on its value.
|
||||
Secret: []byte("test-secret-0123456789abcdef0123456789"),
|
||||
Domain: "example.test",
|
||||
AccessTokenLifetime: time.Hour,
|
||||
RefreshTokenLifetime: 24 * time.Hour,
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
)
|
||||
|
||||
// ClaudeConfig holds the Anthropic API credentials.
|
||||
type ClaudeConfig struct {
|
||||
APIKey string
|
||||
}
|
||||
|
||||
// InitClaude builds the shared Anthropic client. It is used in two places:
|
||||
// reading a rowing machine display from a photo (handlers.CreateRowing) and
|
||||
// classifying job-application emails (EmailSyncService.processEmail).
|
||||
//
|
||||
// No validation happens here: with an empty or wrong API key construction
|
||||
// still succeeds and the failure only surfaces on the first request.
|
||||
func InitClaude(config *ClaudeConfig) *anthropic.Client {
|
||||
// anthropic.NewClient returns a value, not a pointer, so take its address
|
||||
// to share one client across every caller.
|
||||
client := anthropic.NewClient(option.WithAPIKey(config.APIKey))
|
||||
return &client
|
||||
}
|
||||
@@ -49,11 +49,8 @@ func migrateDatabase(db *gorm.DB) error {
|
||||
&models.Favorite{},
|
||||
&models.Rowing{},
|
||||
&models.Message{},
|
||||
&models.JobApplication{},
|
||||
&models.JobAppReference{},
|
||||
&models.Bookmark{},
|
||||
&models.Place{},
|
||||
&models.ProcessedEmail{},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -1,420 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file is a hand-rolled IMAP client, used as an alternative mail source
|
||||
// to Microsoft Graph. It exists because the Graph path needs an Azure app
|
||||
// registration and admin consent, while IMAP needs only an app password.
|
||||
//
|
||||
// It implements the bare minimum of RFC 3501 — LOGIN, SELECT, SEARCH, FETCH,
|
||||
// LOGOUT — by matching on string prefixes rather than parsing IMAP's grammar
|
||||
// properly. It works against Outlook and similar servers with the response
|
||||
// shapes seen in practice; it is not a general-purpose IMAP client.
|
||||
|
||||
// IMAPConfig holds the mailbox credentials. Password is an app password, not
|
||||
// an account password.
|
||||
type IMAPConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
// imapClient is a minimal, lenient IMAP client that tolerates
|
||||
// Outlook's non-standard response formatting.
|
||||
type imapClient struct {
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
// tag numbers the commands. IMAP allows several in flight at once
|
||||
// identified by tag; this client never does that, so the atomic is
|
||||
// belt-and-braces rather than load-bearing.
|
||||
tag atomic.Int64
|
||||
}
|
||||
|
||||
// imapDial opens an implicit-TLS IMAP connection (port 993 style, TLS from the
|
||||
// first byte — there is no STARTTLS support here) and consumes the server
|
||||
// greeting, which arrives unsolicited before any command.
|
||||
func imapDial(addr string) (*imapClient, error) {
|
||||
conn, err := tls.Dial("tcp", addr, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &imapClient{
|
||||
conn: conn,
|
||||
reader: bufio.NewReader(conn),
|
||||
}
|
||||
// Read server greeting
|
||||
if _, err := c.readLine(); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("reading greeting: %w", err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Close drops the TCP connection. Callers normally send LOGOUT first.
|
||||
func (c *imapClient) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// nextTag returns the next command tag, e.g. "A0001". The width is cosmetic:
|
||||
// past 9999 the tags simply get longer, and they stay unique.
|
||||
func (c *imapClient) nextTag() string {
|
||||
return fmt.Sprintf("A%04d", c.tag.Add(1))
|
||||
}
|
||||
|
||||
// readLine reads one CRLF-terminated protocol line with the terminator
|
||||
// stripped. There is no read deadline anywhere in this client, so an
|
||||
// unresponsive server can block a sync until the TCP connection itself fails.
|
||||
func (c *imapClient) readLine() (string, error) {
|
||||
line, err := c.reader.ReadString('\n')
|
||||
return strings.TrimRight(line, "\r\n"), err
|
||||
}
|
||||
|
||||
// sendCommand sends a tagged command and reads lines until the line beginning
|
||||
// with that tag, which is the server's final status for the command.
|
||||
// Everything before it is an untagged ("* ...") response and is returned.
|
||||
//
|
||||
// This must not be used for FETCH: it reads line by line and would mistake the
|
||||
// bytes of a literal for protocol lines. Use sendFetch instead.
|
||||
func (c *imapClient) sendCommand(cmd string) (untagged []string, status string, err error) {
|
||||
tag := c.nextTag()
|
||||
_, err = fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return untagged, "", err
|
||||
}
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
return untagged, line, nil
|
||||
}
|
||||
untagged = append(untagged, line)
|
||||
}
|
||||
}
|
||||
|
||||
// sendCommandOK sends a command and returns an error if the response is not OK.
|
||||
func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
|
||||
untagged, status, err := c.sendCommand(cmd)
|
||||
if err != nil {
|
||||
return untagged, err
|
||||
}
|
||||
// Status line is "<tag> OK ..." on success, "<tag> NO ..." or
|
||||
// "<tag> BAD ..." otherwise; only the second field matters.
|
||||
parts := strings.SplitN(status, " ", 3)
|
||||
if len(parts) < 2 || parts[1] != "OK" {
|
||||
return untagged, fmt.Errorf("command %q failed: %s", cmd, status)
|
||||
}
|
||||
return untagged, nil
|
||||
}
|
||||
|
||||
// readLiteral reads exactly size bytes of an IMAP literal, i.e. the payload
|
||||
// announced by a trailing "{N}" on the preceding line. It must read by byte
|
||||
// count rather than by line because the payload is arbitrary binary data that
|
||||
// will itself contain CRLFs.
|
||||
func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
buf := make([]byte, size)
|
||||
_, err := io.ReadFull(c.reader, buf)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// fetchPart is one FETCH response line plus the literal payload that followed
|
||||
// it, if any. Pairing them in the type removes the need for callers to walk an
|
||||
// interleaved slice and manually skip every second entry — the previous shape,
|
||||
// where a literal was simply the next element and a caller that forgot to
|
||||
// advance would parse message bytes as a protocol line.
|
||||
type fetchPart struct {
|
||||
Line string
|
||||
// Literal is the payload that followed Line, valid only when HasLiteral.
|
||||
Literal string
|
||||
HasLiteral bool
|
||||
}
|
||||
|
||||
// sendFetch sends a FETCH and collects its response, handling literals.
|
||||
//
|
||||
// The literal is detected with LastIndex("{") plus a "}" suffix rather than a
|
||||
// real parse, so a line whose text merely ends in braces could be misread —
|
||||
// tolerable because only FETCH responses reach this code.
|
||||
func (c *imapClient) sendFetch(cmd string) ([]fetchPart, error) {
|
||||
tag := c.nextTag()
|
||||
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var parts []fetchPart
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return parts, err
|
||||
}
|
||||
|
||||
// Check for literal marker {N} at end of line
|
||||
if idx := strings.LastIndex(line, "{"); idx >= 0 && strings.HasSuffix(line, "}") {
|
||||
sizeStr := line[idx+1 : len(line)-1]
|
||||
var size int
|
||||
if _, err := fmt.Sscanf(sizeStr, "%d", &size); err == nil && size > 0 {
|
||||
literal, err := c.readLiteral(size)
|
||||
if err != nil {
|
||||
return parts, fmt.Errorf("reading literal of %d bytes: %w", size, err)
|
||||
}
|
||||
parts = append(parts, fetchPart{Line: line, Literal: literal, HasLiteral: true})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
// Check for OK
|
||||
fields := strings.SplitN(line, " ", 3)
|
||||
if len(fields) >= 2 && fields[1] != "OK" {
|
||||
return parts, fmt.Errorf("FETCH failed: %s", line)
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
parts = append(parts, fetchPart{Line: line})
|
||||
}
|
||||
}
|
||||
|
||||
// fetchEmailsIMAP connects to an IMAP server and retrieves emails since the given time.
|
||||
func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, error) {
|
||||
addr := fmt.Sprintf("%s:%s", s.Config.IMAP.Host, s.Config.IMAP.Port)
|
||||
|
||||
c, err := imapDial(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP connect: %w", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
// %q wraps the password in double quotes and backslash-escapes any quote
|
||||
// or backslash inside it, which happens to be exactly IMAP's quoted-string
|
||||
// syntax. The username is NOT quoted: an address needs no escaping.
|
||||
// Note this sends the password in a LOGIN command, so it is only safe
|
||||
// because the connection is TLS from the first byte.
|
||||
quotedPass := fmt.Sprintf("%q", s.Config.IMAP.Password)
|
||||
if _, err := c.sendCommandOK(fmt.Sprintf("LOGIN %s %s", s.Config.IMAP.Email, quotedPass)); err != nil {
|
||||
return nil, fmt.Errorf("IMAP login: %w", err)
|
||||
}
|
||||
|
||||
if _, err := c.sendCommandOK("SELECT INBOX"); err != nil {
|
||||
return nil, fmt.Errorf("IMAP select INBOX: %w", err)
|
||||
}
|
||||
|
||||
// SEARCH SINCE has day granularity only — the time of day is not
|
||||
// expressible — so this always over-fetches back to midnight of `since`.
|
||||
// Harmless: SyncEmails deduplicates by message id. The date must be in
|
||||
// IMAP's dd-Mon-yyyy form, hence this exact layout string.
|
||||
dateStr := since.UTC().Format("02-Jan-2006")
|
||||
untagged, err := c.sendCommandOK(fmt.Sprintf("SEARCH SINCE %s", dateStr))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP search: %w", err)
|
||||
}
|
||||
|
||||
// Parse sequence numbers from "* SEARCH 1 2 3 ...". parts[2:] skips the
|
||||
// "*" and "SEARCH" tokens; a bare "* SEARCH" (no matches) has len 2 and
|
||||
// is skipped by the length test.
|
||||
var seqNums []string
|
||||
for _, line := range untagged {
|
||||
if strings.HasPrefix(line, "* SEARCH") {
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) > 2 {
|
||||
seqNums = append(seqNums, parts[2:]...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(seqNums) == 0 {
|
||||
log.Printf("[EmailSync/IMAP] No messages found since %s", dateStr)
|
||||
c.sendCommand("LOGOUT")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync/IMAP] Found %d messages since %s", len(seqNums), dateStr)
|
||||
|
||||
// Every matching message is fetched in one command with a comma-separated
|
||||
// sequence set, and each full body is held in memory. A mailbox with a
|
||||
// very busy day could make this large — there is no batching.
|
||||
seqSet := strings.Join(seqNums, ",")
|
||||
fetchParts, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP fetch: %w", err)
|
||||
}
|
||||
|
||||
// Each body arrives as a "... BODY[] {N}" line carrying its literal, so
|
||||
// the pairing is now part of the value rather than something this loop has
|
||||
// to reconstruct by skipping entries. A message that fails to parse is
|
||||
// logged and skipped rather than failing the whole sync.
|
||||
var messages []graphMessage
|
||||
for _, part := range fetchParts {
|
||||
if part.HasLiteral && strings.Contains(part.Line, "BODY[]") {
|
||||
gm, err := parseRawEmail(part.Literal)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
continue
|
||||
}
|
||||
messages = append(messages, gm)
|
||||
}
|
||||
}
|
||||
|
||||
// LOGOUT errors are ignored: the emails are already in hand and the
|
||||
// deferred Close will drop the connection regardless.
|
||||
c.sendCommand("LOGOUT")
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// parseRawEmail parses a raw RFC822 message into the same graphMessage struct
|
||||
// the Graph API path produces, so everything downstream is source-agnostic.
|
||||
// An unparseable Date falls back to now, and a missing From leaves both name
|
||||
// and address empty rather than failing.
|
||||
func parseRawEmail(raw string) (graphMessage, error) {
|
||||
msg, err := mail.ReadMessage(strings.NewReader(raw))
|
||||
if err != nil {
|
||||
return graphMessage{}, fmt.Errorf("parsing message: %w", err)
|
||||
}
|
||||
|
||||
header := msg.Header
|
||||
|
||||
// Parse From
|
||||
var fromName, fromAddr string
|
||||
if fromList, err := header.AddressList("From"); err == nil && len(fromList) > 0 {
|
||||
fromName = fromList[0].Name
|
||||
fromAddr = fromList[0].Address
|
||||
}
|
||||
|
||||
// Parse Date
|
||||
dateStr := header.Get("Date")
|
||||
parsedDate, err := mail.ParseDate(dateStr)
|
||||
if err != nil {
|
||||
parsedDate = time.Now()
|
||||
}
|
||||
|
||||
// Extract body text
|
||||
bodyContent := extractTextBody(msg.Header, msg.Body)
|
||||
|
||||
// Dedup is keyed on GraphMessageID: a missing Message-ID header would
|
||||
// yield "", which collides every headerless message onto one shared row
|
||||
// (the first one processed, forever). Synthesise an id from stable
|
||||
// message traits instead — hashing because From/Date/Subject/size are not
|
||||
// unique alone but their combination is stable across retries.
|
||||
msgID := header.Get("Message-ID")
|
||||
if msgID == "" {
|
||||
hash := sha256.Sum256([]byte(fromAddr + "|" + dateStr + "|" + header.Get("Subject") + "|" + bodyContent))
|
||||
msgID = "synth-" + hex.EncodeToString(hash[:8])
|
||||
}
|
||||
|
||||
return graphMessage{
|
||||
ID: msgID,
|
||||
Subject: decodeHeader(header.Get("Subject")),
|
||||
ReceivedDateTime: parsedDate.Format(time.RFC3339),
|
||||
From: graphFrom{
|
||||
EmailAddress: graphEmailAddress{
|
||||
Name: fromName,
|
||||
Address: fromAddr,
|
||||
},
|
||||
},
|
||||
Body: graphBody{
|
||||
ContentType: "text",
|
||||
Content: bodyContent,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// extractTextBody pulls readable content out of a message body, preferring
|
||||
// text/plain and falling back to text/html.
|
||||
//
|
||||
// It recurses into nested multipart parts by re-wrapping the part's bytes in a
|
||||
// synthetic mail.Header carrying just its Content-Type — a shortcut that works
|
||||
// because this function only ever reads Content-Type.
|
||||
//
|
||||
// Quoted-printable and base64 transfer encodings are NOT decoded, so a
|
||||
// base64-encoded body reaches Claude as base64. Read errors on a part are
|
||||
// swallowed and the part is skipped.
|
||||
func extractTextBody(header mail.Header, body io.Reader) string {
|
||||
contentType := header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = "text/plain"
|
||||
}
|
||||
|
||||
mediaType, params, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
// Try reading as plain text
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mediaType, "multipart/") {
|
||||
boundary := params["boundary"]
|
||||
if boundary == "" {
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
mr := multipart.NewReader(body, boundary)
|
||||
var textContent, htmlContent string
|
||||
for {
|
||||
part, err := mr.NextPart()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
partType := part.Header.Get("Content-Type")
|
||||
partMedia, _, _ := mime.ParseMediaType(partType)
|
||||
b, err := io.ReadAll(part)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
switch partMedia {
|
||||
case "text/plain":
|
||||
textContent = string(b)
|
||||
case "text/html":
|
||||
htmlContent = string(b)
|
||||
case "multipart/alternative", "multipart/related", "multipart/mixed":
|
||||
// Recursively handle nested multipart
|
||||
nested := extractTextBody(
|
||||
mail.Header{"Content-Type": {partType}},
|
||||
strings.NewReader(string(b)),
|
||||
)
|
||||
if nested != "" && textContent == "" {
|
||||
textContent = nested
|
||||
}
|
||||
}
|
||||
}
|
||||
if textContent != "" {
|
||||
return textContent
|
||||
}
|
||||
return htmlContent
|
||||
}
|
||||
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// decodeHeader decodes RFC 2047 encoded-words (the "=?UTF-8?Q?...?=" form
|
||||
// used for non-ASCII subjects), returning the input unchanged if it is not
|
||||
// encoded or cannot be decoded.
|
||||
func decodeHeader(s string) string {
|
||||
dec := new(mime.WordDecoder)
|
||||
decoded, err := dec.DecodeHeader(s)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package services
|
||||
|
||||
import "testing"
|
||||
|
||||
// These tests cover the status progression rule only — statusAdvances, the
|
||||
// predicate extracted out of updateJobApplication. The rest of
|
||||
// updateJobApplication (note appending, the DB.Save, the returned counters)
|
||||
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
|
||||
// deliberately not exercised here. Nothing in this file touches Claude or the
|
||||
// Graph API either; email classification is a network call by construction.
|
||||
|
||||
func TestStatusAdvances(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
current string
|
||||
next string
|
||||
want bool
|
||||
}{
|
||||
{"one step forward is the normal case", "applied", "screening", true},
|
||||
{"skipping intermediate stages still advances", "applied", "offer", true},
|
||||
{"adjacent step backwards is refused", "interviewing", "assessment", false},
|
||||
{"a long way backwards is refused", "offer", "applied", false},
|
||||
{"same status is not progression, so a duplicate email is a no-op", "screening", "screening", false},
|
||||
|
||||
// rejected and withdrawn sit at the top of statusOrder: once an
|
||||
// application lands there, no later email may move it.
|
||||
{"rejected cannot fall back to interviewing", "rejected", "interviewing", false},
|
||||
{"rejected cannot fall back to offer", "rejected", "offer", false},
|
||||
{"rejected cannot repeat", "rejected", "rejected", false},
|
||||
{"withdrawn cannot fall back to offer", "withdrawn", "offer", false},
|
||||
{"withdrawn cannot fall back to rejected", "withdrawn", "rejected", false},
|
||||
{"withdrawn cannot repeat", "withdrawn", "withdrawn", false},
|
||||
// The one ordering asymmetry between the two terminals: withdrawn
|
||||
// ranks above rejected, so this single pair is allowed.
|
||||
{"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true},
|
||||
|
||||
{"an unknown new status is never applied", "applied", "hired", false},
|
||||
{"an empty new status is never applied", "applied", "", false},
|
||||
{"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false},
|
||||
{"a recognised status takes over from an unknown current status", "ghosted", "applied", true},
|
||||
{"a recognised status takes over from an empty current status", "", "offer", true},
|
||||
{"unknown to unknown stays put", "ghosted", "hired", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := statusAdvances(c.current, c.next); got != c.want {
|
||||
t.Errorf("statusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Guards the claim the other tests rest on: rejected and withdrawn really are
|
||||
// the top of the ranking, so adding a stage below them cannot silently make
|
||||
// them non-terminal.
|
||||
func TestTerminalStatusesRankHighest(t *testing.T) {
|
||||
for status, order := range statusOrder {
|
||||
if status == "rejected" || status == "withdrawn" {
|
||||
continue
|
||||
}
|
||||
if order >= statusOrder["rejected"] {
|
||||
t.Errorf("%q ranks %d, at or above rejected (%d)", status, order, statusOrder["rejected"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeStatus is the guard that keeps Claude's occasional casing drift
|
||||
// ("Interview", "on hold") out of the status column: an unrecognised value
|
||||
// stored verbatim makes statusAdvances treat the row's current status as
|
||||
// unknown, which switches the forward-only rule off for that row entirely.
|
||||
func TestNormalizeStatus(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"a tracked status passes through", "interviewing", "interviewing"},
|
||||
{"casing drift is lowered, not rejected", "Interviewing", "interviewing"},
|
||||
{"surrounding whitespace is trimmed", " offer ", "offer"},
|
||||
{"an untracked status falls back to the pipeline default", "on hold", "applied"},
|
||||
{"the UI's old Title Case value is recognised once lowered", "Rejected", "rejected"},
|
||||
{"a value the UI once allowed but the pipeline never had is rejected", "Interview", "applied"},
|
||||
{"empty falls back rather than storing a blank status", "", "applied"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := NormalizeStatus(c.in); got != c.want {
|
||||
t.Errorf("NormalizeStatus(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,968 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// This file is the job-application email pipeline. On a timer it fetches
|
||||
// recent mail (via Microsoft Graph or plain IMAP), keeps the ones that look
|
||||
// recruitment-related, asks Claude to turn each into structured data, and
|
||||
// creates or advances a models.JobApplication row. Every email it has looked
|
||||
// at is recorded as a models.ProcessedEmail so it is never handled twice.
|
||||
|
||||
// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token
|
||||
// survives restarts, exactly like the Spotify token.
|
||||
const MSGRAPH_TOKEN_JSON_PATH = "/backend/token/msgraph_token.json"
|
||||
|
||||
// EmailSyncConfig configures the pipeline. Backend picks the mail source;
|
||||
// anything other than "graph" or "imap" leaves the service permanently idle.
|
||||
type EmailSyncConfig struct {
|
||||
Backend string // "graph" or "imap"
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
TenantID string
|
||||
RedirectURI string
|
||||
IMAP *IMAPConfig
|
||||
SyncInterval time.Duration
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// EmailSyncService owns the sync pipeline.
|
||||
type EmailSyncService struct {
|
||||
Config *EmailSyncConfig
|
||||
OAuthConfig *oauth2.Config
|
||||
// HTTPClient doubles as the readiness flag: nil means "not configured or
|
||||
// not yet authenticated", and both the scheduler and the manual-trigger
|
||||
// handler refuse to run while it is nil. On the Graph backend it is a
|
||||
// real token-injecting client; on the IMAP backend it is set to
|
||||
// http.DefaultClient purely so this check passes (IMAP never uses it).
|
||||
HTTPClient *http.Client
|
||||
DB *gorm.DB
|
||||
ClaudeClient *anthropic.Client
|
||||
// mu is used with TryLock, not Lock: it makes a sync a no-op while
|
||||
// another one is running rather than queueing behind it, so the manual
|
||||
// admin trigger cannot pile up on top of the scheduled run.
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Microsoft Graph API response types
|
||||
|
||||
// Microsoft Graph API response types. The IMAP backend parses raw RFC822
|
||||
// messages into these same structs (see parseRawEmail) so that everything
|
||||
// downstream of fetchEmails is backend-agnostic.
|
||||
|
||||
// graphMessagesResponse is one page of /me/messages; NextLink is Graph's
|
||||
// cursor for the next page and is empty on the last one.
|
||||
type graphMessagesResponse struct {
|
||||
Value []graphMessage `json:"value"`
|
||||
NextLink string `json:"@odata.nextLink"`
|
||||
}
|
||||
|
||||
// graphMessage is a single email.
|
||||
type graphMessage struct {
|
||||
ID string `json:"id"`
|
||||
Subject string `json:"subject"`
|
||||
ReceivedDateTime string `json:"receivedDateTime"`
|
||||
From graphFrom `json:"from"`
|
||||
Body graphBody `json:"body"`
|
||||
BodyPreview string `json:"bodyPreview"`
|
||||
}
|
||||
|
||||
// graphFrom wraps the sender, which Graph nests one level deep.
|
||||
type graphFrom struct {
|
||||
EmailAddress graphEmailAddress `json:"emailAddress"`
|
||||
}
|
||||
|
||||
// graphEmailAddress is a display name plus address.
|
||||
type graphEmailAddress struct {
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
// graphBody is the message body; ContentType is "html" or "text".
|
||||
type graphBody struct {
|
||||
ContentType string `json:"contentType"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Claude response type
|
||||
|
||||
// EmailAnalysis is the JSON contract Claude is asked to return; the keys here
|
||||
// must stay in step with emailClassificationPrompt at the bottom of this file.
|
||||
// Pointer fields are the ones Claude is allowed to answer null for.
|
||||
type EmailAnalysis struct {
|
||||
IsJobEmail bool `json:"isJobEmail"`
|
||||
Action string `json:"action"`
|
||||
Company string `json:"company"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Status string `json:"status"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
AppliedAt *string `json:"appliedAt"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// Email filtering config
|
||||
|
||||
// Cheap pre-filter, applied before any Claude call so that the bulk of a
|
||||
// mailbox never costs an API request. It is intentionally over-inclusive:
|
||||
// false positives are cheap (Claude rejects them), false negatives are not
|
||||
// (the email is never looked at again once its window has passed).
|
||||
|
||||
// subjectKeywords match case-insensitively anywhere in the subject line.
|
||||
var subjectKeywords = []string{
|
||||
"application", "interview", "offer", "rejected", "assessment",
|
||||
"applied", "candidate", "position", "role", "hiring",
|
||||
"thank you for applying", "we regret", "move forward",
|
||||
"next steps", "coding challenge", "take-home",
|
||||
}
|
||||
|
||||
// senderDomains are applicant-tracking systems; mail from any of them is
|
||||
// considered job-related whatever the subject says.
|
||||
var senderDomains = []string{
|
||||
"greenhouse.io", "lever.co", "workday.com", "myworkday.com",
|
||||
"ashbyhq.com", "smartrecruiters.com", "icims.com",
|
||||
"jobvite.com", "taleo.net", "breezy.hr", "recruitee.com",
|
||||
"applytojob.com", "jazz.co", "dover.com",
|
||||
}
|
||||
|
||||
// Status progression order
|
||||
|
||||
// statusOrder ranks the application lifecycle so updates can only move an
|
||||
// application forwards (see updateJobApplication). A status missing from this
|
||||
// map is treated as unknown and never applied. Note that "rejected" and
|
||||
// "withdrawn" sit at the top, so once an application reaches them nothing can
|
||||
// move it back.
|
||||
var statusOrder = map[string]int{
|
||||
"applied": 0,
|
||||
"screening": 1,
|
||||
"assessment": 2,
|
||||
"interviewing": 3,
|
||||
"offer": 4,
|
||||
"rejected": 5,
|
||||
"withdrawn": 6,
|
||||
}
|
||||
|
||||
// Token persistence
|
||||
|
||||
// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions.
|
||||
// Like the Spotify equivalent it copies into a local struct so the on-disk
|
||||
// shape does not depend on the oauth2 package's own JSON tags.
|
||||
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||
data := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}{
|
||||
AccessToken: tok.AccessToken,
|
||||
RefreshToken: tok.RefreshToken,
|
||||
TokenType: tok.TokenType,
|
||||
Expiry: tok.Expiry,
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
return fmt.Errorf("creating token directory: %w", err)
|
||||
}
|
||||
|
||||
jsonBytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(path, jsonBytes, 0600)
|
||||
}
|
||||
|
||||
// LoadMSGraphToken reads a token written by SaveMSGraphToken. A missing file
|
||||
// is reported as an error and means "not yet authenticated".
|
||||
func LoadMSGraphToken(path string) (*oauth2.Token, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var saved struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &saved); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oauth2.Token{
|
||||
AccessToken: saved.AccessToken,
|
||||
RefreshToken: saved.RefreshToken,
|
||||
TokenType: saved.TokenType,
|
||||
Expiry: saved.Expiry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// persistingTokenSource wraps an oauth2.TokenSource to save refreshed tokens to disk.
|
||||
type persistingTokenSource struct {
|
||||
base oauth2.TokenSource
|
||||
path string
|
||||
lastToken *oauth2.Token
|
||||
}
|
||||
|
||||
// Token returns a valid token, refreshing through the wrapped source when
|
||||
// needed and writing any new token back to disk.
|
||||
//
|
||||
// Without this wrapper the oauth2 client would refresh happily in memory but
|
||||
// the file on disk would keep the original refresh token; Microsoft rotates
|
||||
// refresh tokens, so after the original expired the service would have to be
|
||||
// re-authorised by hand on the next restart.
|
||||
//
|
||||
// There is no mutex here even though oauth2's client may call Token from
|
||||
// several goroutines. In practice syncs are serialised by EmailSyncService.mu
|
||||
// so concurrent calls do not arise; the worst case if they ever did is a
|
||||
// duplicate write of the same token.
|
||||
func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
tok, err := p.base.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Save only when the token actually changed (i.e. was refreshed)
|
||||
if p.lastToken == nil || tok.AccessToken != p.lastToken.AccessToken {
|
||||
p.lastToken = tok
|
||||
if saveErr := SaveMSGraphToken(p.path, tok); saveErr != nil {
|
||||
log.Printf("[EmailSync] Warning: failed to persist refreshed token: %v", saveErr)
|
||||
}
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// InitEmailSync builds the service and, for the Graph backend, restores a
|
||||
// saved OAuth session. It never fails: a misconfigured or unauthenticated
|
||||
// service is returned with a nil HTTPClient, which leaves the pipeline idle
|
||||
// while the rest of the backend starts normally. For Graph, the authorisation
|
||||
// URL is printed to the container log for a one-off manual sign-in that
|
||||
// lands on GET /email/callback.
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService {
|
||||
svc := &EmailSyncService{
|
||||
Config: config,
|
||||
DB: db,
|
||||
ClaudeClient: claudeClient,
|
||||
}
|
||||
|
||||
switch config.Backend {
|
||||
case "imap":
|
||||
if config.IMAP == nil || config.IMAP.Email == "" {
|
||||
log.Println("[EmailSync] IMAP backend selected but not configured")
|
||||
return svc
|
||||
}
|
||||
// IMAP connects per-sync, no persistent client needed.
|
||||
// Mark as ready by setting a non-nil HTTPClient (used as readiness flag).
|
||||
svc.HTTPClient = http.DefaultClient
|
||||
log.Printf("[EmailSync] Configured with IMAP backend (%s)", config.IMAP.Host)
|
||||
|
||||
case "graph":
|
||||
oauthConfig := &oauth2.Config{
|
||||
ClientID: config.ClientID,
|
||||
ClientSecret: config.ClientSecret,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/authorize", config.TenantID),
|
||||
TokenURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", config.TenantID),
|
||||
},
|
||||
RedirectURL: config.RedirectURI,
|
||||
Scopes: []string{"https://graph.microsoft.com/Mail.Read", "offline_access"},
|
||||
}
|
||||
svc.OAuthConfig = oauthConfig
|
||||
|
||||
token, err := LoadMSGraphToken(MSGRAPH_TOKEN_JSON_PATH)
|
||||
if err != nil || token == nil {
|
||||
authURL := oauthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
log.Println("[EmailSync] No token saved. Authenticate Microsoft Graph with:")
|
||||
log.Println(authURL)
|
||||
return svc
|
||||
}
|
||||
|
||||
baseSource := oauthConfig.TokenSource(context.Background(), token)
|
||||
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
|
||||
svc.HTTPClient = oauth2.NewClient(context.Background(), persistSource)
|
||||
log.Println("[EmailSync] Authenticated with Microsoft Graph")
|
||||
|
||||
default:
|
||||
log.Printf("[EmailSync] Unknown backend %q, defaulting to disabled", config.Backend)
|
||||
}
|
||||
|
||||
return svc
|
||||
}
|
||||
|
||||
// AuthURL returns the OAuth2 authorization URL for initial setup.
|
||||
func (s *EmailSyncService) AuthURL() string {
|
||||
return s.OAuthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
}
|
||||
|
||||
// CompleteAuth exchanges an authorization code for a token and initializes the HTTP client.
|
||||
func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error {
|
||||
token, err := s.OAuthConfig.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return fmt.Errorf("token exchange failed: %w", err)
|
||||
}
|
||||
|
||||
if err := SaveMSGraphToken(MSGRAPH_TOKEN_JSON_PATH, token); err != nil {
|
||||
return fmt.Errorf("saving token: %w", err)
|
||||
}
|
||||
|
||||
baseSource := s.OAuthConfig.TokenSource(ctx, token)
|
||||
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
|
||||
s.HTTPClient = oauth2.NewClient(ctx, persistSource)
|
||||
|
||||
log.Println("[EmailSync] Authentication completed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartScheduler runs SyncEmails immediately and then on every tick until ctx
|
||||
// is cancelled. It is meant to be run in its own goroutine and returns
|
||||
// straight away when the service is disabled or unauthenticated.
|
||||
//
|
||||
// Because readiness is only checked once here, authenticating later via
|
||||
// /email/callback does NOT start the scheduler; the backend has to be
|
||||
// restarted, or syncs triggered by hand through POST /email/sync.
|
||||
func (s *EmailSyncService) StartScheduler(ctx context.Context) {
|
||||
if !s.Config.Enabled {
|
||||
log.Println("[EmailSync] Disabled, skipping scheduler")
|
||||
return
|
||||
}
|
||||
if s.HTTPClient == nil {
|
||||
log.Println("[EmailSync] Not authenticated, skipping scheduler")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Starting scheduler, interval: %s", s.Config.SyncInterval)
|
||||
|
||||
// Run once immediately on startup
|
||||
if err := s.SyncEmails(ctx); err != nil {
|
||||
log.Printf("[EmailSync] Initial sync error: %v", err)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(s.Config.SyncInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[EmailSync] Scheduler stopped")
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := s.SyncEmails(ctx); err != nil {
|
||||
log.Printf("[EmailSync] Sync error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SyncEmails is the main pipeline: fetch, filter, dedup, classify, create/update.
|
||||
func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
// TryLock, so a manual trigger during a scheduled run is rejected
|
||||
// immediately instead of blocking a request for minutes.
|
||||
if !s.mu.TryLock() {
|
||||
return fmt.Errorf("sync already in progress")
|
||||
}
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// Registered after the unlock defer, therefore it runs BEFORE it: the
|
||||
// panic is absorbed here and the mutex is still released afterwards.
|
||||
// A recovered panic makes SyncEmails return nil, so the caller sees a
|
||||
// successful sync — the log line is the only evidence.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("[EmailSync] PANIC recovered: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
log.Println("[EmailSync] Starting sync...")
|
||||
|
||||
// Window start comes from the newest email we have ever *received* (one of
|
||||
// two clocks in play) rather than from when we processed it: receive time
|
||||
// lags processing time by up to one sync duration, and a later window
|
||||
// anchored to processing time would start AFTER mail that arrived just at
|
||||
// the previous fetch — a permanent hole (the overlap the code always meant
|
||||
// to have is produced only when both edges speak the same clock).
|
||||
// Anchoring on ReceivedAt keeps the window behind the fetch, the
|
||||
// ProcessedEmail dedup absorbs the deliberate re-fetch overlap, and on a
|
||||
// cold database it falls back to the last 24 hours so the pipeline never
|
||||
// tries to ingest an entire mailbox.
|
||||
since := time.Now().Add(-24 * time.Hour)
|
||||
var latest models.ProcessedEmail
|
||||
if err := s.DB.Where("received_at > ?", time.Time{}).Order("received_at DESC").First(&latest).Error; err == nil {
|
||||
// Pull the window back one slack period so mail delivered a second or
|
||||
// two after the last fetch (or indexed late by the provider) is still
|
||||
// inside the next window; dedup makes re-processing it harmless.
|
||||
since = latest.ReceivedAt.Add(-fetchSlack)
|
||||
}
|
||||
|
||||
// Pull the window back to cover any still-retryable failure. Without this
|
||||
// the clamp above would have advanced past a failed email — the error row
|
||||
// is written now, so the next window starts after it — and the retry
|
||||
// below could never see the email again. Rows predating ReceivedAt have
|
||||
// a zero value and are ignored rather than dragging the window to 0001.
|
||||
//
|
||||
// Old failures are age-capped: attempts only advance when the email is
|
||||
// actually re-fetched, so a message that has left the mailbox would stay
|
||||
// under the cap forever and rewind every sync on this day's fetch. After
|
||||
// maxRewindAge the email is treated as gone, like any abandoned retry.
|
||||
var oldestRetryable models.ProcessedEmail
|
||||
if err := s.DB.
|
||||
Where("action = ? AND attempts < ? AND received_at > ? AND received_at > ?",
|
||||
"error", maxEmailAttempts, time.Time{}, time.Now().Add(-maxRewindAge)).
|
||||
Order("received_at ASC").
|
||||
First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) {
|
||||
log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure",
|
||||
oldestRetryable.ReceivedAt.Format(time.RFC3339))
|
||||
since = oldestRetryable.ReceivedAt
|
||||
}
|
||||
|
||||
// Fetch emails from Microsoft Graph
|
||||
emails, err := s.fetchEmails(ctx, since)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetching emails: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Fetched %d emails since %s", len(emails), since.Format(time.RFC3339))
|
||||
|
||||
// Filter by subject/sender patterns
|
||||
filtered := s.filterEmails(emails)
|
||||
log.Printf("[EmailSync] %d emails passed filters", len(filtered))
|
||||
|
||||
var created, updated, skipped, errored int
|
||||
|
||||
for _, email := range filtered {
|
||||
// Dedup check. A row is terminal — and so genuinely skippable — if it
|
||||
// succeeded, or if it failed the maximum number of times. A row that
|
||||
// failed but has attempts left is deliberately NOT skipped: it is
|
||||
// reprocessed below and the same row updated, so a transient Claude
|
||||
// or network outage no longer drops the email permanently.
|
||||
var existing models.ProcessedEmail
|
||||
found := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error == nil
|
||||
if found && !retryableFailure(&existing) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
if found {
|
||||
log.Printf("[EmailSync] Retrying previously failed email %q (attempt %d of %d)",
|
||||
email.Subject, existing.Attempts+1, maxEmailAttempts)
|
||||
}
|
||||
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
|
||||
// The row carries the outcome either way. On failure the attempt
|
||||
// counter advances, so repeated failures walk the row towards the cap
|
||||
// and it eventually stops being retried. A cancelled sync (the admin
|
||||
// closed the tab mid-backlog, or nginx cut the request) is not a
|
||||
// failure of the email, though: attempts must not advance for it, or
|
||||
// two closed tabs would strand a healthy email at the cap and skip it
|
||||
// forever. Writing nothing preserves the existing row untouched, so it
|
||||
// is simply retried at the next sync.
|
||||
if processErr != nil && errors.Is(processErr, context.Canceled) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
record := models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: action,
|
||||
JobAppID: jobAppID,
|
||||
ReceivedAt: parseReceivedAt(email.ReceivedDateTime),
|
||||
Attempts: existing.Attempts + 1,
|
||||
}
|
||||
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
record.Action = "error"
|
||||
record.JobAppID = nil
|
||||
if record.Attempts >= maxEmailAttempts {
|
||||
log.Printf("[EmailSync] Email %q has failed %d times; giving up on it",
|
||||
email.Subject, record.Attempts)
|
||||
}
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
errored++
|
||||
continue
|
||||
}
|
||||
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
|
||||
switch action {
|
||||
case "created":
|
||||
created++
|
||||
case "updated":
|
||||
updated++
|
||||
default:
|
||||
skipped++
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Sync complete: %d fetched, %d filtered, %d created, %d updated, %d skipped, %d errors",
|
||||
len(emails), len(filtered), created, updated, skipped, errored)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchEmails retrieves emails since the given time using the configured
|
||||
// backend, normalising both into []graphMessage.
|
||||
func (s *EmailSyncService) fetchEmails(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
if s.Config.Backend == "imap" {
|
||||
return s.fetchEmailsIMAP(since)
|
||||
}
|
||||
return s.fetchEmailsGraph(ctx, since)
|
||||
}
|
||||
|
||||
// fetchEmailsGraph retrieves emails from the Microsoft Graph API since the given time.
|
||||
func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
var all []graphMessage
|
||||
|
||||
sinceStr := since.UTC().Format("2006-01-02T15:04:05Z")
|
||||
params := url.Values{
|
||||
"$filter": {fmt.Sprintf("receivedDateTime ge %s", sinceStr)},
|
||||
"$select": {"id,subject,from,receivedDateTime,body,bodyPreview"},
|
||||
"$top": {"50"},
|
||||
"$orderby": {"receivedDateTime asc"},
|
||||
}
|
||||
|
||||
// Graph paginates with @odata.nextLink, which already carries every query
|
||||
// parameter, so the loop below only builds this first URL by hand.
|
||||
nextURL := fmt.Sprintf("https://graph.microsoft.com/v1.0/me/messages?%s", params.Encode())
|
||||
|
||||
for nextURL != "" {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", nextURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := s.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
// Status is checked before the read error so that a non-200 reports
|
||||
// Graph's own error body rather than a generic read failure.
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Graph API returned %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var result graphMessagesResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("parsing response: %w", err)
|
||||
}
|
||||
|
||||
all = append(all, result.Value...)
|
||||
nextURL = result.NextLink
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// filterEmails returns only emails that match subject keywords or sender domains.
|
||||
func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage {
|
||||
var matched []graphMessage
|
||||
for _, email := range emails {
|
||||
if s.matchesFilter(email) {
|
||||
matched = append(matched, email)
|
||||
}
|
||||
}
|
||||
return matched
|
||||
}
|
||||
|
||||
// matchesFilter reports whether an email looks job-related on subject or
|
||||
// sender alone. See subjectKeywords for why this errs towards including too
|
||||
// much.
|
||||
func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
|
||||
subjectLower := strings.ToLower(email.Subject)
|
||||
for _, kw := range subjectKeywords {
|
||||
if strings.Contains(subjectLower, kw) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
senderAddr := strings.ToLower(email.From.EmailAddress.Address)
|
||||
for _, domain := range senderDomains {
|
||||
if strings.HasSuffix(senderAddr, "@"+domain) || strings.HasSuffix(senderAddr, "."+domain) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// processEmail sends a single email to Claude and creates/updates a JobApplication.
|
||||
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
|
||||
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
|
||||
cleaned := cleanEmailBody(email.Body.Content, email.Body.ContentType)
|
||||
|
||||
userMsg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
|
||||
email.Subject,
|
||||
email.From.EmailAddress.Name,
|
||||
email.From.EmailAddress.Address,
|
||||
email.ReceivedDateTime,
|
||||
cleaned,
|
||||
)
|
||||
|
||||
message, err := s.ClaudeClient.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: anthropic.ModelClaudeHaiku4_5,
|
||||
MaxTokens: 512,
|
||||
System: []anthropic.TextBlockParam{
|
||||
{Text: emailClassificationPrompt},
|
||||
},
|
||||
Messages: []anthropic.MessageParam{
|
||||
{
|
||||
Role: "user",
|
||||
Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(userMsg)},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("Claude API error: %w", err)
|
||||
}
|
||||
|
||||
if len(message.Content) == 0 {
|
||||
return "", nil, fmt.Errorf("empty response from Claude")
|
||||
}
|
||||
|
||||
// Only the first content block is read, and the prompt asks for bare JSON,
|
||||
// but models still wrap output in a markdown fence often enough that it is
|
||||
// stripped defensively here.
|
||||
raw := StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
var analysis EmailAnalysis
|
||||
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
|
||||
return "", nil, fmt.Errorf("parsing Claude response: %w (raw: %s)", err, raw)
|
||||
}
|
||||
|
||||
if !analysis.IsJobEmail {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
if analysis.Company == "" || analysis.JobTitle == "" {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
// Applications are identified by (company, job title) compared
|
||||
// case-insensitively — there is no external id to match on. Claude
|
||||
// wording the same role slightly differently therefore creates a second
|
||||
// application rather than updating the first. The most recent match wins
|
||||
// when there are several.
|
||||
// The lookup is Unscoped: a deleted-with-notes row is stored, not purged
|
||||
// (see models.JobApplication), so invisibility here makes the matcher
|
||||
// believe the application never existed and a follow-up email in the same
|
||||
// thread re-creates it — the admin deletes it, it comes back. A hit on a
|
||||
// deleted row instead becomes a suppression: nothing is updated, nothing
|
||||
// is created, and the pipeline leaves the deletion to stand.
|
||||
var existing models.JobApplication
|
||||
found := s.DB.Unscoped().Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
|
||||
analysis.Company, analysis.JobTitle).
|
||||
Order("created_at DESC").
|
||||
First(&existing).Error == nil
|
||||
|
||||
if found && existing.DeletedAt.Valid {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
if found && analysis.Action == "update" {
|
||||
return s.updateJobApplication(&existing, &analysis)
|
||||
}
|
||||
|
||||
if !found {
|
||||
return s.createJobApplication(&analysis)
|
||||
}
|
||||
|
||||
// Found but action is "create" — the record already exists, skip
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
// NormalizeStatus coerces Claude's status guess into the tracked vocabulary,
|
||||
// lowering the case it occasionally drifts on and rejecting anything outside
|
||||
// statusOrder. An unrecognised status stored verbatim would disable the
|
||||
// forward-only guard for that row (updateJobApplication allows any recognised
|
||||
// status over an unknown one), so the safe fallback is the pipeline's default.
|
||||
func NormalizeStatus(s string) string {
|
||||
lowered := strings.ToLower(strings.TrimSpace(s))
|
||||
if _, ok := statusOrder[lowered]; ok {
|
||||
return lowered
|
||||
}
|
||||
return "applied"
|
||||
}
|
||||
|
||||
// createJobApplication inserts a new application from Claude's analysis.
|
||||
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
|
||||
app := models.JobApplication{
|
||||
Company: analysis.Company,
|
||||
JobTitle: analysis.JobTitle,
|
||||
Status: NormalizeStatus(analysis.Status),
|
||||
Location: analysis.Location,
|
||||
URL: analysis.URL,
|
||||
Notes: analysis.Notes,
|
||||
}
|
||||
|
||||
// The prompt asks for YYYY-MM-DD but full RFC3339 comes back often enough
|
||||
// to be worth trying first; an unparseable date is dropped silently.
|
||||
if analysis.AppliedAt != nil {
|
||||
if t, err := time.Parse(time.RFC3339, *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
} else if t, err := time.Parse("2006-01-02", *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
}
|
||||
}
|
||||
|
||||
if app.Status == "" {
|
||||
app.Status = "applied"
|
||||
}
|
||||
|
||||
if err := s.DB.Create(&app).Error; err != nil {
|
||||
return "", nil, fmt.Errorf("creating job application: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Created job application: %s at %s (status: %s)", app.JobTitle, app.Company, app.Status)
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
// statusAdvances reports whether next is a forward move from current through
|
||||
// statusOrder. Emails commonly arrive out of order (a delayed "thanks for
|
||||
// applying" after an interview invite), and this is what stops a stale email
|
||||
// dragging an application backwards. An unknown next status is never applied;
|
||||
// an unknown current status is treated as "anywhere before the start", so any
|
||||
// recognised status can take over from it.
|
||||
func statusAdvances(current, next string) bool {
|
||||
nextOrder, nextExists := statusOrder[next]
|
||||
currentOrder, currentExists := statusOrder[current]
|
||||
return nextExists && (!currentExists || nextOrder > currentOrder)
|
||||
}
|
||||
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards (see statusAdvances).
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
if !statusAdvances(existing.Status, analysis.Status) {
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
existing.Status = analysis.Status
|
||||
|
||||
// Append to notes if Claude provided any
|
||||
if analysis.Notes != nil && *analysis.Notes != "" {
|
||||
if existing.Notes != nil && *existing.Notes != "" {
|
||||
combined := *existing.Notes + "\n" + *analysis.Notes
|
||||
existing.Notes = &combined
|
||||
} else {
|
||||
existing.Notes = analysis.Notes
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.DB.Save(existing).Error; err != nil {
|
||||
return "", nil, fmt.Errorf("updating job application: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Updated job application: %s at %s (status: %s)", existing.JobTitle, existing.Company, existing.Status)
|
||||
return "updated", &existing.ID, nil
|
||||
}
|
||||
|
||||
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
||||
// Claude, cutting token cost and noise.
|
||||
//
|
||||
// The HTML handling is a regex tag-strip, not a parser: fine for extracting
|
||||
// prose, but it would mangle inline <script>/<style> content and mis-handle
|
||||
// tags inside attribute values. That is acceptable because the output is only
|
||||
// ever read by a language model, never rendered.
|
||||
func cleanEmailBody(content string, contentType string) string {
|
||||
text := content
|
||||
|
||||
if strings.EqualFold(contentType, "html") {
|
||||
// Strip HTML tags
|
||||
tagRegex := regexp.MustCompile(`<[^>]*>`)
|
||||
text = tagRegex.ReplaceAllString(text, " ")
|
||||
|
||||
// Decode common HTML entities
|
||||
replacer := strings.NewReplacer(
|
||||
" ", " ",
|
||||
"&", "&",
|
||||
"<", "<",
|
||||
">", ">",
|
||||
""", `"`,
|
||||
"'", "'",
|
||||
"'", "'",
|
||||
)
|
||||
text = replacer.Replace(text)
|
||||
}
|
||||
|
||||
// Collapse whitespace
|
||||
spaceRegex := regexp.MustCompile(`[ \t]+`)
|
||||
text = spaceRegex.ReplaceAllString(text, " ")
|
||||
nlRegex := regexp.MustCompile(`\n{3,}`)
|
||||
text = nlRegex.ReplaceAllString(text, "\n\n")
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
// Cut everything from the first signature marker onwards. The idx > 0
|
||||
// test (not >= 0) means a body that begins with a marker is left alone,
|
||||
// which avoids blanking the whole message.
|
||||
sigPatterns := []string{
|
||||
"\n-- \n",
|
||||
"\nSent from my iPhone",
|
||||
"\nSent from my iPad",
|
||||
"\nGet Outlook for",
|
||||
}
|
||||
for _, pattern := range sigPatterns {
|
||||
if idx := strings.Index(text, pattern); idx > 0 {
|
||||
text = text[:idx]
|
||||
}
|
||||
}
|
||||
|
||||
// Remove forwarded email chains
|
||||
lines := strings.Split(text, "\n")
|
||||
var cleaned []string
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(strings.TrimSpace(line), ">") {
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, line)
|
||||
}
|
||||
text = strings.Join(cleaned, "\n")
|
||||
|
||||
// Cap the prompt size. This slices by bytes, so a cut can land mid-rune
|
||||
// and leave an invalid UTF-8 tail; harmless for a model prompt.
|
||||
if len(text) > 4000 {
|
||||
text = text[:4000]
|
||||
}
|
||||
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
// truncate caps a string at maxLen bytes (not runes) before it is stored in
|
||||
// ProcessedEmail.Subject.
|
||||
func truncate(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen]
|
||||
}
|
||||
|
||||
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
|
||||
// every key it names is a field there, and the status values it lists are the
|
||||
// keys of statusOrder.
|
||||
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
|
||||
|
||||
Return ONLY a JSON object with these exact keys:
|
||||
- "isJobEmail": boolean - true if this email is about a job application
|
||||
- "action": "create" | "update" | "none" - whether this represents a new application confirmation or an update to an existing one
|
||||
- "company": string - the company name
|
||||
- "jobTitle": string - the job title/position
|
||||
- "status": string - one of: "applied", "screening", "interviewing", "assessment", "offer", "rejected", "withdrawn"
|
||||
- "location": string or null - job location if mentioned
|
||||
- "url": string or null - any application portal URL
|
||||
- "appliedAt": string or null - ISO 8601 date if an application date is mentioned (YYYY-MM-DD format)
|
||||
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
|
||||
|
||||
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
|
||||
|
||||
// StripMarkdownFence removes a surrounding markdown code fence from a model's
|
||||
// response, so text that should have been bare JSON can be unmarshalled
|
||||
// whether or not the model wrapped it.
|
||||
//
|
||||
// The two TrimPrefix calls are ordered so that "```json" is removed first and
|
||||
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
|
||||
// returned unchanged apart from surrounding whitespace.
|
||||
//
|
||||
// Shared with handlers.CreateRowing, which prompts for bare JSON in the same
|
||||
// way and gets the same fenced output.
|
||||
func StripMarkdownFence(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
|
||||
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
|
||||
// attempt costs a Claude call, so the cap is what stops one permanently
|
||||
// unparseable email billing on every sync forever. Three gives a transient
|
||||
// outage two further chances across subsequent syncs.
|
||||
const maxEmailAttempts = 3
|
||||
|
||||
// fetchSlack pulls each sync's window edge back by this much so mail that was
|
||||
// delayed between fetch and filter (or index-registered late) is still caught
|
||||
// by the next window. Consumers pay for it with deliberate re-fetches, which
|
||||
// the ProcessedEmail dedup makes free.
|
||||
const fetchSlack = 30 * time.Second
|
||||
|
||||
// maxRewindAge stops a stuck retry from pinning the window open forever. A
|
||||
// failed email is only rewound for while it is younger than this; past that it
|
||||
// has probably been deleted from the mailbox or fallen out of the provider's
|
||||
// returns, so re-fetching for it would never yield anything.
|
||||
const maxRewindAge = 7 * 24 * time.Hour
|
||||
|
||||
// retryableFailure reports whether a previously recorded email should be
|
||||
// processed again. Only failures are retried, and only while they have
|
||||
// attempts left; anything that succeeded is terminal.
|
||||
func retryableFailure(row *models.ProcessedEmail) bool {
|
||||
return row.Action == "error" && row.Attempts < maxEmailAttempts
|
||||
}
|
||||
|
||||
// parseReceivedAt converts the provider's timestamp to a time.Time, returning
|
||||
// the zero value if it is missing or malformed. A zero value is safe: it only
|
||||
// means this row cannot pull the fetch window back, so the email is retried
|
||||
// on the next sync that happens to cover it rather than being chased.
|
||||
func parseReceivedAt(raw string) time.Time {
|
||||
if raw == "" {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
received, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Unparseable receivedDateTime %q: %v", raw, err)
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
return received
|
||||
}
|
||||
|
||||
// saveProcessed writes the outcome of an attempt: updating the existing row
|
||||
// when this was a retry, inserting when it is the first attempt. Update is
|
||||
// used rather than Save so the row keeps its original CreatedAt, which the
|
||||
// fetch window depends on.
|
||||
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
|
||||
var err error
|
||||
if found {
|
||||
err = s.DB.Model(existing).Updates(map[string]any{
|
||||
"action": record.Action,
|
||||
"job_app_id": record.JobAppID,
|
||||
"attempts": record.Attempts,
|
||||
"received_at": record.ReceivedAt,
|
||||
}).Error
|
||||
} else {
|
||||
err = s.DB.Create(record).Error
|
||||
}
|
||||
|
||||
// Logged rather than returned: a bookkeeping failure must not abort the
|
||||
// rest of the batch. It does mean the email is reprocessed next sync,
|
||||
// which the dedup treats as a first attempt.
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Failed to record processed email %q: %v", record.Subject, err)
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// These tests cover only the pure helpers of the email sync: body cleaning,
|
||||
// truncation, fence stripping, timestamp parsing, the retry predicate and the
|
||||
// filter. Everything else in email_sync.go — token acquisition, the Graph
|
||||
// paging loop, processEmail and the create/update paths — needs either a live
|
||||
// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist
|
||||
// in a test run, so they are deliberately not exercised here.
|
||||
//
|
||||
// matchesFilter is a method but reads no field of the receiver (it matches
|
||||
// against the package-level subjectKeywords/senderDomains), which is why a
|
||||
// zero-value &EmailSyncService{} is a legitimate receiver below.
|
||||
|
||||
func TestCleanEmailBody(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
content string
|
||||
contentType string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"html tags are stripped and entities decoded",
|
||||
"<p>Hi Adam & team</p><b>thanks</b>",
|
||||
"html",
|
||||
"Hi Adam & team thanks",
|
||||
},
|
||||
{
|
||||
"contentType match is case-insensitive",
|
||||
"<p>hello</p>",
|
||||
"HTML",
|
||||
"hello",
|
||||
},
|
||||
{
|
||||
// Entities are only decoded on the HTML path, so plain text keeps
|
||||
// them verbatim rather than being silently rewritten.
|
||||
"text bodies are not entity-decoded",
|
||||
"a & b",
|
||||
"text",
|
||||
"a & b",
|
||||
},
|
||||
{
|
||||
"runs of spaces and tabs collapse to one space",
|
||||
"one \t two",
|
||||
"text",
|
||||
"one two",
|
||||
},
|
||||
{
|
||||
"three or more newlines collapse to a blank line",
|
||||
"a\n\n\n\n\nb",
|
||||
"text",
|
||||
"a\n\nb",
|
||||
},
|
||||
{
|
||||
"signature marker cuts the tail",
|
||||
"body text\n-- \nAdam French\n07000",
|
||||
"text",
|
||||
"body text",
|
||||
},
|
||||
{
|
||||
"Sent from my iPhone is treated as a signature",
|
||||
"see attached\nSent from my iPhone",
|
||||
"text",
|
||||
"see attached",
|
||||
},
|
||||
{
|
||||
// idx > 0, not >= 0: a body that is nothing but a signature would
|
||||
// otherwise be blanked entirely, losing the only content there is.
|
||||
"a body starting with a signature marker is left intact",
|
||||
"Sent from my iPhone\nreal content",
|
||||
"text",
|
||||
"Sent from my iPhone\nreal content",
|
||||
},
|
||||
{
|
||||
"quoted lines are dropped",
|
||||
"my reply\n> their mail\n > indented quote\nmore reply",
|
||||
"text",
|
||||
"my reply\nmore reply",
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := cleanEmailBody(c.content, c.contentType); got != c.want {
|
||||
t.Fatalf("cleanEmailBody(%q, %q) = %q, want %q", c.content, c.contentType, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The 4000-byte cap is what bounds the prompt cost, so it gets its own test:
|
||||
// the cut is by bytes and is applied before the final TrimSpace.
|
||||
func TestCleanEmailBodyCap(t *testing.T) {
|
||||
got := cleanEmailBody(strings.Repeat("a", 5000), "text")
|
||||
if len(got) != 4000 {
|
||||
t.Fatalf("len = %d, want 4000", len(got))
|
||||
}
|
||||
|
||||
// A body exactly at the cap must pass through untouched.
|
||||
exact := strings.Repeat("b", 4000)
|
||||
if got := cleanEmailBody(exact, "text"); got != exact {
|
||||
t.Fatalf("body at the cap was modified: len = %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
s string
|
||||
maxLen int
|
||||
want string
|
||||
}{
|
||||
{"shorter than the cap is unchanged", "abc", 10, "abc"},
|
||||
{"exactly at the cap is unchanged", "abcde", 5, "abcde"},
|
||||
{"longer is cut to the cap", "abcdef", 3, "abc"},
|
||||
{"zero cap yields the empty string", "abc", 0, ""},
|
||||
{"empty input", "", 5, ""},
|
||||
// Bytes, not runes: the cut can land mid-rune. Asserted so the
|
||||
// behaviour is a documented choice rather than a lurking surprise.
|
||||
{"multi-byte runes are cut by byte", "é", 1, "\xc3"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := truncate(c.s, c.maxLen); got != c.want {
|
||||
t.Fatalf("truncate(%q, %d) = %q, want %q", c.s, c.maxLen, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripMarkdownFence(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`},
|
||||
{"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`},
|
||||
{"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`},
|
||||
{"opening fence only", "```json\n{\"a\":1}", `{"a":1}`},
|
||||
{"empty input", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := StripMarkdownFence(c.raw); got != c.want {
|
||||
t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseReceivedAt(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want time.Time
|
||||
}{
|
||||
{"valid RFC3339", "2024-03-15T10:30:00Z", time.Date(2024, 3, 15, 10, 30, 0, 0, time.UTC)},
|
||||
{"empty means no timestamp", "", time.Time{}},
|
||||
{"malformed falls back to zero rather than failing the sync", "15/03/2024", time.Time{}},
|
||||
{"a date without a time is not RFC3339", "2024-03-15", time.Time{}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := parseReceivedAt(c.raw); !got.Equal(c.want) {
|
||||
t.Fatalf("parseReceivedAt(%q) = %v, want %v", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryableFailure(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
action string
|
||||
attempts int
|
||||
want bool
|
||||
}{
|
||||
{"a failure with attempts left is retried", "error", maxEmailAttempts - 1, true},
|
||||
{"a failure at the cap is abandoned", "error", maxEmailAttempts, false},
|
||||
{"a failure past the cap is abandoned", "error", maxEmailAttempts + 1, false},
|
||||
{"a success is terminal even with attempts left", "created", 0, false},
|
||||
{"a skip is terminal too", "skipped", 0, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
row := &models.ProcessedEmail{Action: c.action, Attempts: c.attempts}
|
||||
if got := retryableFailure(row); got != c.want {
|
||||
t.Fatalf("retryableFailure(%s, %d) = %v, want %v", c.action, c.attempts, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesFilter(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
subject string
|
||||
sender string
|
||||
want bool
|
||||
}{
|
||||
{"subject keyword anywhere in the line", "Your application to Acme", "[email protected]", true},
|
||||
{"subject keyword is case-insensitive", "INTERVIEW CONFIRMED", "[email protected]", true},
|
||||
{"sender on a tracked ATS domain", "hello", "[email protected]", true},
|
||||
{"sender on a subdomain of a tracked domain", "hello", "[email protected]", true},
|
||||
{"sender domain match is case-insensitive", "hello", "[email protected]", true},
|
||||
// The rule is an @ or . boundary, so a lookalike domain that merely
|
||||
// ends in the same letters must not match.
|
||||
{"lookalike domain does not match", "hello", "[email protected]", false},
|
||||
{"neither subject nor sender matches", "lunch tomorrow?", "[email protected]", false},
|
||||
}
|
||||
|
||||
s := &EmailSyncService{}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
email := graphMessage{Subject: c.subject}
|
||||
email.From.EmailAddress.Address = c.sender
|
||||
if got := s.matchesFilter(email); got != c.want {
|
||||
t.Fatalf("matchesFilter(%q, %q) = %v, want %v", c.subject, c.sender, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
_ "embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ENV_APPLY_DIR is the directory shared with the host (./env-apply/run in the
|
||||
// checkout, bind-mounted by docker-compose). It is the whole interface
|
||||
// between this process and the host script that edits .env.
|
||||
const ENV_APPLY_DIR = "/backend/env-apply"
|
||||
|
||||
// The registry is JSON rather than a Go literal because the host script
|
||||
// (env-apply/apply.py) reads the same file from the checkout: one list
|
||||
// decides both what the panel offers and what the host will accept.
|
||||
//
|
||||
//go:embed env_registry.json
|
||||
var envRegistryJSON []byte
|
||||
|
||||
// EnvVar is one registry entry.
|
||||
//
|
||||
// Kind decides how a value is validated and how the panel renders it:
|
||||
// "secret" and "generated" are never sent to the browser; "generated" can
|
||||
// also be minted here. Services lists the compose services that read the
|
||||
// variable, which is what the host recreates after a change.
|
||||
type EnvVar struct {
|
||||
Name string `json:"name"`
|
||||
Group string `json:"group"`
|
||||
Purpose string `json:"purpose"`
|
||||
Kind string `json:"kind"`
|
||||
Editable bool `json:"editable"`
|
||||
LockedReason string `json:"lockedReason,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
DocsURL string `json:"docsUrl,omitempty"`
|
||||
Options []string `json:"options,omitempty"`
|
||||
Warning string `json:"warning,omitempty"`
|
||||
}
|
||||
|
||||
// Secret reports whether the variable's value must stay on the server.
|
||||
func (v EnvVar) Secret() bool {
|
||||
return v.Kind == "secret" || v.Kind == "generated"
|
||||
}
|
||||
|
||||
// EnvManager turns an edit made in the admin panel into a request for the
|
||||
// host to apply.
|
||||
//
|
||||
// The backend deliberately cannot write .env or restart containers itself:
|
||||
// it is the internet-facing process, and either ability would make a
|
||||
// compromised admin session a compromised host. Instead it validates the
|
||||
// change and leaves request.json in the shared directory; the host's watcher
|
||||
// (env-apply/apply.py, run by a systemd path unit) merges it into .env,
|
||||
// recreates the affected containers and reports back through status.json.
|
||||
type EnvManager struct {
|
||||
dir string
|
||||
vars []EnvVar
|
||||
byName map[string]EnvVar
|
||||
|
||||
// Serialises Submit and Cancel so two requests cannot interleave their
|
||||
// read-merge-write of request.json. The host is a separate process and is
|
||||
// handled by renames instead (see Submit).
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// envApplyRequest is request.json. Clearing a variable is setting it to "".
|
||||
type envApplyRequest struct {
|
||||
ID string `json:"id"`
|
||||
RequestedAt time.Time `json:"requestedAt"`
|
||||
Set map[string]string `json:"set"`
|
||||
}
|
||||
|
||||
// EnvApplyStatus is what the panel polls. State is one of idle, pending
|
||||
// (request written, host has not picked it up), applying, applied, failed.
|
||||
type EnvApplyStatus struct {
|
||||
State string `json:"state"`
|
||||
ID string `json:"id,omitempty"`
|
||||
// When the state was entered.
|
||||
At *time.Time `json:"at,omitempty"`
|
||||
// Names in a pending request. Values are never reported.
|
||||
Pending []string `json:"pending,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
Changed []string `json:"changed,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
// False once a request has waited long enough that nothing on the host
|
||||
// can be watching for it (a dev machine, or the units not installed).
|
||||
Watcher bool `json:"watcher"`
|
||||
}
|
||||
|
||||
const (
|
||||
envRequestFile = "request.json"
|
||||
envStatusFile = "status.json"
|
||||
|
||||
// The path unit fires within a second, so a request still unclaimed
|
||||
// after this long means there is no watcher.
|
||||
envWatcherGrace = 15 * time.Second
|
||||
// An "applying" status older than this is a host script that died
|
||||
// mid-run; stop letting it block new requests.
|
||||
envApplyingStale = 5 * time.Minute
|
||||
|
||||
envValueMaxLen = 4096
|
||||
)
|
||||
|
||||
// ErrEnvApplying is returned by Submit while the host is mid-apply.
|
||||
var ErrEnvApplying = errors.New("a change is being applied; try again in a moment")
|
||||
|
||||
// NewEnvManager parses the embedded registry. dir need not exist yet: without
|
||||
// the bind mount, reads report "idle" and Submit fails with a clear error.
|
||||
func NewEnvManager(dir string) (*EnvManager, error) {
|
||||
var vars []EnvVar
|
||||
if err := json.Unmarshal(envRegistryJSON, &vars); err != nil {
|
||||
return nil, fmt.Errorf("parsing env registry: %w", err)
|
||||
}
|
||||
byName := make(map[string]EnvVar, len(vars))
|
||||
for _, v := range vars {
|
||||
if _, dup := byName[v.Name]; dup {
|
||||
return nil, fmt.Errorf("env registry lists %s twice", v.Name)
|
||||
}
|
||||
byName[v.Name] = v
|
||||
}
|
||||
return &EnvManager{dir: dir, vars: vars, byName: byName}, nil
|
||||
}
|
||||
|
||||
// Vars returns the registry in file order, which is the order the panel
|
||||
// shows.
|
||||
func (m *EnvManager) Vars() []EnvVar {
|
||||
return m.vars
|
||||
}
|
||||
|
||||
// Validate checks one proposed value. The empty string clears the variable
|
||||
// and is always acceptable for an editable one.
|
||||
//
|
||||
// The control-character rule is the security-relevant one: .env is line
|
||||
// oriented, so a newline in a value would let an edit to an allowed variable
|
||||
// write a second, arbitrary one.
|
||||
func (m *EnvManager) Validate(name, value string) error {
|
||||
v, ok := m.byName[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("%s is not a known variable", name)
|
||||
}
|
||||
if !v.Editable {
|
||||
return fmt.Errorf("%s cannot be changed from the panel", name)
|
||||
}
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
if len(value) > envValueMaxLen {
|
||||
return fmt.Errorf("%s is too long", name)
|
||||
}
|
||||
for _, r := range value {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return fmt.Errorf("%s contains a control character", name)
|
||||
}
|
||||
}
|
||||
// The host writes values single-quoted, and a dotenv single-quoted
|
||||
// string has no escape for the quote itself.
|
||||
if strings.ContainsRune(value, '\'') {
|
||||
return fmt.Errorf("%s cannot contain a single quote", name)
|
||||
}
|
||||
|
||||
switch v.Kind {
|
||||
case "url":
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return fmt.Errorf("%s must be an http(s) URL", name)
|
||||
}
|
||||
case "bool":
|
||||
if value != "true" && value != "false" {
|
||||
return fmt.Errorf("%s must be true or false", name)
|
||||
}
|
||||
case "duration":
|
||||
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
|
||||
return fmt.Errorf("%s must be a duration such as 30m", name)
|
||||
}
|
||||
case "number":
|
||||
if n, err := strconv.Atoi(value); err != nil || n <= 0 {
|
||||
return fmt.Errorf("%s must be a positive whole number", name)
|
||||
}
|
||||
case "enum":
|
||||
if !slices.Contains(v.Options, value) {
|
||||
return fmt.Errorf("%s must be one of: %s", name, strings.Join(v.Options, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ServicesFor is the set of compose services a change to names recreates.
|
||||
// The backend is always among them: the panel reports state from this
|
||||
// process's own environment, which only a recreate refreshes.
|
||||
func (m *EnvManager) ServicesFor(names []string) []string {
|
||||
services := []string{"backend"}
|
||||
for _, name := range names {
|
||||
for _, s := range m.byName[name].Services {
|
||||
if !slices.Contains(services, s) {
|
||||
services = append(services, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(services)
|
||||
return services
|
||||
}
|
||||
|
||||
// Submit validates a batch of edits and hands it to the host. set holds
|
||||
// explicit values ("" clears); generate names variables to mint a random
|
||||
// value for. The generated values are returned and exist nowhere else on
|
||||
// this side — the caller shows them once.
|
||||
//
|
||||
// Nothing is written unless the whole batch is valid.
|
||||
//
|
||||
// A request the host has not yet claimed is merged into rather than
|
||||
// refused, so edits are not stuck behind an absent watcher. The host claims
|
||||
// a request by renaming it, so the worst a race can do is hand it values it
|
||||
// has already applied.
|
||||
func (m *EnvManager) Submit(set map[string]string, generate []string) (map[string]string, []string, error) {
|
||||
changes := make(map[string]string, len(set)+len(generate))
|
||||
for name, value := range set {
|
||||
value = strings.TrimSpace(value)
|
||||
if err := m.Validate(name, value); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
changes[name] = value
|
||||
}
|
||||
generated := make(map[string]string, len(generate))
|
||||
for _, name := range generate {
|
||||
if v, ok := m.byName[name]; !ok || !v.Editable || v.Kind != "generated" {
|
||||
return nil, nil, fmt.Errorf("%s cannot be generated", name)
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
generated[name] = hex.EncodeToString(raw)
|
||||
changes[name] = generated[name]
|
||||
}
|
||||
if len(changes) == 0 {
|
||||
return nil, nil, errors.New("no changes given")
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if status := m.readStatus(); status != nil && status.State == "applying" &&
|
||||
status.At != nil && time.Since(*status.At) < envApplyingStale {
|
||||
return nil, nil, ErrEnvApplying
|
||||
}
|
||||
|
||||
request := envApplyRequest{Set: changes}
|
||||
if pending := m.readRequest(); pending != nil {
|
||||
for name, value := range pending.Set {
|
||||
if _, replaced := changes[name]; !replaced {
|
||||
request.Set[name] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
id := make([]byte, 8)
|
||||
if _, err := rand.Read(id); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
request.ID = hex.EncodeToString(id)
|
||||
request.RequestedAt = time.Now().UTC()
|
||||
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
return generated, m.ServicesFor(names), nil
|
||||
}
|
||||
|
||||
// writeRequest writes request.json so the host only ever sees a complete
|
||||
// file it can read: temp name, owner and mode set, then rename.
|
||||
//
|
||||
// This process runs as root in the container while the host script runs as
|
||||
// the checkout's owner, so the file is handed to whoever owns the shared
|
||||
// directory. 0600 because it holds the new secrets in the clear until the
|
||||
// host consumes it.
|
||||
func (m *EnvManager) writeRequest(request *envApplyRequest) error {
|
||||
info, err := os.Stat(m.dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the env-apply directory is not mounted: %w", err)
|
||||
}
|
||||
data, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := filepath.Join(m.dir, envRequestFile+".tmp")
|
||||
if err := os.WriteFile(tmp, data, 0600); err != nil {
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
if err := os.Chown(tmp, int(stat.Uid), int(stat.Gid)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("handing env request to the host user: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tmp, filepath.Join(m.dir, envRequestFile)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cancel withdraws a request the host has not claimed. Once claimed it is
|
||||
// too late, and this is a no-op.
|
||||
func (m *EnvManager) Cancel() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := os.Remove(filepath.Join(m.dir, envRequestFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("removing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EnvManager) readRequest() *envApplyRequest {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var request envApplyRequest
|
||||
if json.Unmarshal(raw, &request) != nil {
|
||||
return nil
|
||||
}
|
||||
return &request
|
||||
}
|
||||
|
||||
func (m *EnvManager) readStatus() *EnvApplyStatus {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envStatusFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var status EnvApplyStatus
|
||||
if json.Unmarshal(raw, &status) != nil {
|
||||
return nil
|
||||
}
|
||||
return &status
|
||||
}
|
||||
|
||||
// Status reports where the latest change has got to. An unclaimed request
|
||||
// takes precedence over status.json, which then describes an older change.
|
||||
func (m *EnvManager) Status() EnvApplyStatus {
|
||||
if request := m.readRequest(); request != nil {
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
at := request.RequestedAt
|
||||
return EnvApplyStatus{
|
||||
State: "pending",
|
||||
ID: request.ID,
|
||||
At: &at,
|
||||
Pending: names,
|
||||
Services: m.ServicesFor(names),
|
||||
Watcher: time.Since(at) < envWatcherGrace,
|
||||
}
|
||||
}
|
||||
if status := m.readStatus(); status != nil {
|
||||
status.Watcher = true
|
||||
return *status
|
||||
}
|
||||
return EnvApplyStatus{State: "idle", Watcher: true}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newEnvManager(t *testing.T) *EnvManager {
|
||||
t.Helper()
|
||||
m, err := NewEnvManager(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func readRequestFile(t *testing.T, m *EnvManager) envApplyRequest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatalf("reading request: %v", err)
|
||||
}
|
||||
var request envApplyRequest
|
||||
if err := json.Unmarshal(raw, &request); err != nil {
|
||||
t.Fatalf("parsing request: %v", err)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
// The registry and .env.example describe the same variables; a name added to
|
||||
// one and not the other is either invisible in the panel or undocumented.
|
||||
func TestEnvRegistryMatchesEnvExample(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../.env.example")
|
||||
if err != nil {
|
||||
t.Fatalf("reading .env.example: %v", err)
|
||||
}
|
||||
var example []string
|
||||
for _, match := range regexp.MustCompile(`(?m)^([A-Z][A-Z0-9_]*)=`).FindAllStringSubmatch(string(raw), -1) {
|
||||
example = append(example, match[1])
|
||||
}
|
||||
|
||||
var registry []string
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
registry = append(registry, v.Name)
|
||||
}
|
||||
|
||||
for _, name := range example {
|
||||
if !slices.Contains(registry, name) {
|
||||
t.Errorf("%s is in .env.example but not in env_registry.json", name)
|
||||
}
|
||||
}
|
||||
for _, name := range registry {
|
||||
if !slices.Contains(example, name) {
|
||||
t.Errorf("%s is in env_registry.json but not in .env.example", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// composeServiceEnv returns the variable names in the `environment:` list of
|
||||
// one service in docker-compose.yml.
|
||||
//
|
||||
// It reads the file as text rather than through a YAML library — there is
|
||||
// none among this module's direct dependencies, and the shape needed is
|
||||
// narrow: a two-space-indented `<service>:` key under `services:`, a
|
||||
// four-space-indented `environment:` under it, and `- NAME=value` items. If
|
||||
// the compose file is ever restructured so that this finds nothing, the test
|
||||
// below fails loudly rather than passing on an empty list.
|
||||
func composeServiceEnv(t *testing.T, service string) []string {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("../../docker-compose.yml")
|
||||
if err != nil {
|
||||
t.Fatalf("reading docker-compose.yml: %v", err)
|
||||
}
|
||||
|
||||
item := regexp.MustCompile(`^ - ["']?([A-Z][A-Z0-9_]*)(=|["']?\s*$)`)
|
||||
var names []string
|
||||
inService, inEnvironment := false, false
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
continue
|
||||
}
|
||||
indent := len(line) - len(strings.TrimLeft(line, " "))
|
||||
switch {
|
||||
case indent <= 2:
|
||||
// A new service (or a top-level key) ends the block.
|
||||
inService, inEnvironment = line == " "+service+":", false
|
||||
case inService && indent == 4:
|
||||
inEnvironment = trimmed == "environment:"
|
||||
case inService && inEnvironment:
|
||||
match := item.FindStringSubmatch(line)
|
||||
if match == nil {
|
||||
t.Fatalf("%s.environment has an entry this test cannot read: %q", service, line)
|
||||
}
|
||||
names = append(names, match[1])
|
||||
}
|
||||
}
|
||||
if len(names) == 0 {
|
||||
t.Fatalf("found no %s.environment list in docker-compose.yml; has the file's layout changed?", service)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// explicitEnvServices are the containers given an explicit `environment:`
|
||||
// list instead of the whole .env, so that they never hold the database
|
||||
// password or the JWT secret: the Python service, and the job tracker (an
|
||||
// image from its own repo, which gets its own database role besides). The
|
||||
// cost is a third place a new variable for one of them has to be added — the
|
||||
// registry, .env.example and that list — and forgetting the third is silent:
|
||||
// the variable is simply empty inside the container.
|
||||
var explicitEnvServices = []string{"python", "jobs"}
|
||||
|
||||
// So the registry's claim "this service reads this" and the compose list must
|
||||
// agree, in both directions:
|
||||
//
|
||||
// - a variable the registry says the service reads must be passed to it;
|
||||
// - an editable variable that is passed to it must say so in the registry,
|
||||
// or changing it in the admin panel would not recreate the container.
|
||||
//
|
||||
// Locked variables are exempt from the second rule. They are never applied
|
||||
// through the panel, so the registry gives none of them a services list
|
||||
// (PYTHON_PORT is passed to python and is one of these). Names in the compose
|
||||
// list that are not registry variables at all, such as the literal ROOT_PATH
|
||||
// or the jobs service's composed DATABASE_URL, are not this test's business.
|
||||
func TestEnvRegistryMatchesComposeEnvironments(t *testing.T) {
|
||||
registry := map[string]EnvVar{}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
registry[v.Name] = v
|
||||
}
|
||||
|
||||
for _, service := range explicitEnvServices {
|
||||
compose := composeServiceEnv(t, service)
|
||||
|
||||
for _, v := range registry {
|
||||
if slices.Contains(v.Services, service) && !slices.Contains(compose, v.Name) {
|
||||
t.Errorf("%s lists the %s service in env_registry.json but is not in "+
|
||||
"%s.environment in docker-compose.yml, so the container never receives it", v.Name, service, service)
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range compose {
|
||||
v, known := registry[name]
|
||||
if !known || !v.Editable {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(v.Services, service) {
|
||||
t.Errorf("%s is passed to the %s service in docker-compose.yml but env_registry.json "+
|
||||
"does not list %s among its services, so editing it would not recreate the container", name, service, service)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvRegistryEntriesAreWellFormed(t *testing.T) {
|
||||
kinds := []string{"secret", "generated", "text", "url", "bool", "duration", "number", "enum"}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
if !slices.Contains(kinds, v.Kind) {
|
||||
t.Errorf("%s has unknown kind %q", v.Name, v.Kind)
|
||||
}
|
||||
if v.Group == "" || v.Purpose == "" {
|
||||
t.Errorf("%s is missing its group or purpose", v.Name)
|
||||
}
|
||||
if v.Editable && len(v.Services) == 0 {
|
||||
t.Errorf("%s is editable but names no service to recreate", v.Name)
|
||||
}
|
||||
if !v.Editable && v.LockedReason == "" {
|
||||
t.Errorf("%s is locked without a reason", v.Name)
|
||||
}
|
||||
if v.Kind == "enum" && len(v.Options) == 0 {
|
||||
t.Errorf("%s is an enum with no options", v.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvValidate(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name, value string
|
||||
ok bool
|
||||
}{
|
||||
{"CLAUDE_API_KEY", "sk-ant-abc123", true},
|
||||
{"CLAUDE_API_KEY", "", true},
|
||||
// The injection case: a newline would start a second variable.
|
||||
{"CLAUDE_API_KEY", "x\nPOSTGRES_PASSWORD=owned", false},
|
||||
{"CLAUDE_API_KEY", "x\rY", false},
|
||||
{"CLAUDE_API_KEY", "it's", false},
|
||||
{"CLAUDE_API_KEY", strings.Repeat("a", envValueMaxLen+1), false},
|
||||
{"POSTGRES_PASSWORD", "anything", false},
|
||||
{"NOT_A_VARIABLE", "anything", false},
|
||||
{"EMAIL_BACKEND", "graph", true},
|
||||
{"EMAIL_BACKEND", "pop3", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "45m", true},
|
||||
{"EMAIL_SYNC_INTERVAL", "soon", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "-5m", false},
|
||||
{"EMAIL_SYNC_ENABLED", "true", true},
|
||||
{"EMAIL_SYNC_ENABLED", "yes", false},
|
||||
{"IMAP_PORT", "993", true},
|
||||
{"IMAP_PORT", "imaps", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "https://example.com/api/spotify/callback", true},
|
||||
{"SPOTIFY_REDIRECT_URI", "example.com/callback", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "javascript:alert(1)", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
err := m.Validate(c.name, c.value)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("Validate(%s, %q) error = %v, want ok = %v", c.name, c.value, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWritesRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
generated, services, err := m.Submit(
|
||||
map[string]string{"TFL_APP_KEY": " tfl-key ", "STEAM_ID": ""},
|
||||
[]string{"ICECAST_RELAY_PASSWORD"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
if len(generated["ICECAST_RELAY_PASSWORD"]) != 64 {
|
||||
t.Fatalf("generated value = %q, want 64 hex characters", generated["ICECAST_RELAY_PASSWORD"])
|
||||
}
|
||||
if want := []string{"backend", "icecast2", "python"}; !slices.Equal(services, want) {
|
||||
t.Fatalf("services = %v, want %v", services, want)
|
||||
}
|
||||
|
||||
request := readRequestFile(t, m)
|
||||
want := map[string]string{
|
||||
"TFL_APP_KEY": "tfl-key", // surrounding whitespace from a paste is dropped
|
||||
"STEAM_ID": "",
|
||||
"ICECAST_RELAY_PASSWORD": generated["ICECAST_RELAY_PASSWORD"],
|
||||
}
|
||||
if len(request.Set) != len(want) {
|
||||
t.Fatalf("request.Set = %v, want %v", request.Set, want)
|
||||
}
|
||||
for name, value := range want {
|
||||
if request.Set[name] != value {
|
||||
t.Errorf("request.Set[%s] = %q, want %q", name, request.Set[name], value)
|
||||
}
|
||||
}
|
||||
|
||||
info, err := os.Stat(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Errorf("request mode = %v, want 0600: it holds secrets in the clear", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRejectsWholeBatch(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
set map[string]string
|
||||
generate []string
|
||||
}{
|
||||
{"one bad value", map[string]string{"STEAM_ID": "1", "EMAIL_BACKEND": "pop3"}, nil},
|
||||
{"a locked variable", map[string]string{"STEAM_ID": "1", "DOMAIN": "evil.example"}, nil},
|
||||
{"generating a pasted secret", nil, []string{"CLAUDE_API_KEY"}},
|
||||
{"generating a locked secret", nil, []string{"POSTGRES_PASSWORD"}},
|
||||
{"nothing at all", nil, nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if _, _, err := m.Submit(c.set, c.generate); err == nil {
|
||||
t.Fatal("Submit succeeded, want an error")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(m.dir, envRequestFile)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("a rejected batch left a request file behind")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitMergesUnclaimedRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1", "TFL_APP_KEY": "old"}, nil); err != nil {
|
||||
t.Fatalf("first Submit: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"TFL_APP_KEY": "new"}, nil); err != nil {
|
||||
t.Fatalf("second Submit: %v", err)
|
||||
}
|
||||
request := readRequestFile(t, m)
|
||||
if request.Set["STEAM_ID"] != "1" || request.Set["TFL_APP_KEY"] != "new" {
|
||||
t.Fatalf("merged request = %v, want the earlier STEAM_ID kept and TFL_APP_KEY replaced", request.Set)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWithoutMount(t *testing.T) {
|
||||
m, err := NewEnvManager(filepath.Join(t.TempDir(), "absent"))
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err == nil {
|
||||
t.Fatal("Submit succeeded with no shared directory")
|
||||
}
|
||||
if got := m.Status().State; got != "idle" {
|
||||
t.Fatalf("Status().State = %q, want idle", got)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatusFile(t *testing.T, m *EnvManager, state string, at time.Time) {
|
||||
t.Helper()
|
||||
data, _ := json.Marshal(EnvApplyStatus{State: state, ID: "abc", At: &at})
|
||||
if err := os.WriteFile(filepath.Join(m.dir, envStatusFile), data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvStatus(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if got := m.Status(); got.State != "idle" || !got.Watcher {
|
||||
t.Fatalf("fresh status = %+v, want idle with watcher assumed", got)
|
||||
}
|
||||
|
||||
writeStatusFile(t, m, "applied", time.Now())
|
||||
if got := m.Status(); got.State != "applied" || got.ID != "abc" {
|
||||
t.Fatalf("status = %+v, want the host's applied report", got)
|
||||
}
|
||||
|
||||
// An unclaimed request outranks the report of an older change.
|
||||
if _, _, err := m.Submit(map[string]string{"CLAUDE_API_KEY": "sk-secret"}, nil); err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
got := m.Status()
|
||||
if got.State != "pending" || !slices.Equal(got.Pending, []string{"CLAUDE_API_KEY"}) || !got.Watcher {
|
||||
t.Fatalf("status = %+v, want pending CLAUDE_API_KEY", got)
|
||||
}
|
||||
if encoded, _ := json.Marshal(got); strings.Contains(string(encoded), "sk-secret") {
|
||||
t.Fatal("the status leaks a pending value")
|
||||
}
|
||||
|
||||
// Backdate the request past the grace period: nothing is watching.
|
||||
request := readRequestFile(t, m)
|
||||
request.RequestedAt = time.Now().Add(-2 * envWatcherGrace)
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Status().Watcher {
|
||||
t.Fatal("a long-unclaimed request still reports a watcher")
|
||||
}
|
||||
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel: %v", err)
|
||||
}
|
||||
if got := m.Status().State; got != "applied" {
|
||||
t.Fatalf("after Cancel state = %q, want the earlier applied report", got)
|
||||
}
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel with nothing pending: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRefusedWhileApplying(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
writeStatusFile(t, m, "applying", time.Now())
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); !errors.Is(err, ErrEnvApplying) {
|
||||
t.Fatalf("Submit error = %v, want ErrEnvApplying", err)
|
||||
}
|
||||
|
||||
// A host script that died mid-run must not block the panel for ever.
|
||||
writeStatusFile(t, m, "applying", time.Now().Add(-2*envApplyingStale))
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err != nil {
|
||||
t.Fatalf("Submit after a stale applying status: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
[
|
||||
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls: the job tracker (lead scorer, email classifier, posting reader) and the Python service (rowing photo reader)", "kind": "secret", "editable": true, "services": ["python", "jobs"], "docsUrl": "https://console.anthropic.com/settings/keys"},
|
||||
{"name": "CLAUDE_MODEL", "group": "API keys", "purpose": "Model for every Claude call: lead scoring, email classifier, posting reader (job tracker), rowing photo reader (Python). Blank uses claude-sonnet-5-5. Rough cost per million tokens in/out: Haiku $1/$5, Sonnet $2/$10, Opus $4/$20", "kind": "enum", "options": ["claude-haiku-4-5", "claude-sonnet-5-5", "claude-opus-5-5"], "editable": true, "services": ["python", "jobs"]},
|
||||
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
|
||||
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
|
||||
|
||||
{"name": "SPOTIFY_CLIENT_ID", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_CLIENT_SECRET", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_REDIRECT_URI", "group": "Spotify", "purpose": "Must match the URI registered in the Spotify dashboard exactly", "kind": "url", "editable": true, "services": ["backend"]},
|
||||
{"name": "SPOTIFY_AUTH_STATE", "group": "Spotify", "purpose": "Former fixed OAuth state", "kind": "secret", "editable": false, "lockedReason": "No longer read: the OAuth state is a per-request nonce."},
|
||||
|
||||
{"name": "EMAIL_BACKEND", "group": "Email ingest", "purpose": "Mail source for the email pipeline", "kind": "enum", "options": ["graph", "imap"], "editable": true, "services": ["jobs"]},
|
||||
{"name": "EMAIL_SYNC_ENABLED", "group": "Email ingest", "purpose": "Run the periodic email sync", "kind": "bool", "editable": true, "services": ["jobs"]},
|
||||
{"name": "EMAIL_SYNC_INTERVAL", "group": "Email ingest", "purpose": "Time between syncs, as a Go duration such as 30m (default 30m)", "kind": "duration", "editable": true, "services": ["jobs"]},
|
||||
{"name": "MSGRAPH_CLIENT_ID", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "text", "editable": true, "services": ["jobs"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_CLIENT_SECRET", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "secret", "editable": true, "services": ["jobs"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_TENANT_ID", "group": "Email ingest", "purpose": "\"consumers\" for a personal outlook.com account", "kind": "text", "editable": true, "services": ["jobs"]},
|
||||
{"name": "MSGRAPH_REDIRECT_URI", "group": "Email ingest", "purpose": "OAuth callback: https://<domain>/jobs/api/email/callback, registered in Entra", "kind": "url", "editable": true, "services": ["jobs"]},
|
||||
{"name": "IMAP_HOST", "group": "Email ingest", "purpose": "IMAP fallback server", "kind": "text", "editable": true, "services": ["jobs"]},
|
||||
{"name": "IMAP_PORT", "group": "Email ingest", "purpose": "IMAP fallback port (993)", "kind": "number", "editable": true, "services": ["jobs"]},
|
||||
{"name": "IMAP_EMAIL", "group": "Email ingest", "purpose": "IMAP fallback account", "kind": "text", "editable": true, "services": ["jobs"]},
|
||||
{"name": "IMAP_PASSWORD", "group": "Email ingest", "purpose": "App-specific password, not the account password", "kind": "secret", "editable": true, "services": ["jobs"]},
|
||||
|
||||
{"name": "JOB_LEADS_ENABLED", "group": "Job leads", "purpose": "Run the periodic job-lead fetch; \"Check now\" on /jobs/leads works either way", "kind": "bool", "editable": true, "services": ["jobs"]},
|
||||
{"name": "JOB_LEADS_INTERVAL", "group": "Job leads", "purpose": "Time between fetches, as a Go duration such as 6h (default 6h)", "kind": "duration", "editable": true, "services": ["jobs"]},
|
||||
{"name": "ADZUNA_APP_ID", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "text", "editable": true, "services": ["jobs"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
|
||||
{"name": "ADZUNA_APP_KEY", "group": "Job leads", "purpose": "Adzuna job search, for adzuna lead sources", "kind": "secret", "editable": true, "services": ["jobs"], "docsUrl": "https://developer.adzuna.com/admin/access_details"},
|
||||
{"name": "REED_API_KEY", "group": "Job leads", "purpose": "Reed job search, for reed lead sources", "kind": "secret", "editable": true, "services": ["jobs"], "docsUrl": "https://www.reed.co.uk/developers/jobseeker"},
|
||||
|
||||
{"name": "ICECAST_SOURCE_PASSWORD", "group": "Radio", "purpose": "Liquidsoap to Icecast, and live broadcasters to the harbor port", "kind": "generated", "editable": true, "services": ["icecast2"], "warning": "Live broadcasting clients must be given the new password."},
|
||||
{"name": "ICECAST_RELAY_PASSWORD", "group": "Radio", "purpose": "Icecast relay clients", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_USER", "group": "Radio", "purpose": "Icecast web admin login", "kind": "text", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_PASSWORD", "group": "Radio", "purpose": "Icecast web admin login", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
|
||||
{"name": "BACKEND_SECRET", "group": "Backend", "purpose": "Signs the JWTs in the auth cookies", "kind": "generated", "editable": true, "services": ["backend"], "warning": "Rotating this logs everyone out, including you."},
|
||||
{"name": "SILVERBULLET_GIT_INTERVAL", "group": "Backend", "purpose": "Seconds between notes commit/push cycles (default 300)", "kind": "number", "editable": true, "services": ["silverbullet-git"]},
|
||||
|
||||
{"name": "DOMAIN", "group": "Infrastructure", "purpose": "Apex domain: TLS certificate, cookie domain, nginx server name", "kind": "text", "editable": false, "lockedReason": "Changing the domain needs a new certificate and a full restart."},
|
||||
{"name": "EMAIL", "group": "Infrastructure", "purpose": "Let's Encrypt account address", "kind": "text", "editable": false, "lockedReason": "Only read by certbot when it registers the account."},
|
||||
{"name": "OBSIDIAN_DIR", "group": "Infrastructure", "purpose": "Host path of the notes vault", "kind": "text", "editable": false, "lockedReason": "A bind-mount path: a wrong value stops the stack from starting."},
|
||||
{"name": "SEED_DB", "group": "Infrastructure", "purpose": "Development-only test data switch", "kind": "bool", "editable": false, "lockedReason": "Would inject test data into the live site."},
|
||||
{"name": "BACKEND_HOST", "group": "Infrastructure", "purpose": "Backend container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "BACKEND_PORT", "group": "Infrastructure", "purpose": "Backend listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "BACKEND_ENDPOINT", "group": "Infrastructure", "purpose": "URL prefix nginx mounts the API at", "kind": "text", "editable": false, "lockedReason": "The Vue app assumes /api."},
|
||||
{"name": "PYTHON_HOST", "group": "Infrastructure", "purpose": "Python container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "PYTHON_PORT", "group": "Infrastructure", "purpose": "Python listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "JOBS_IMAGE_TAG", "group": "Infrastructure", "purpose": "Job tracker image tag to run (default latest)", "kind": "text", "editable": false, "lockedReason": "Changing it needs a pull: docker compose pull jobs && docker compose up -d jobs."},
|
||||
{"name": "ICECAST_HOST", "group": "Infrastructure", "purpose": "Icecast container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "ICECAST_PORT", "group": "Infrastructure", "purpose": "Icecast listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "ICECAST_MOUNT", "group": "Infrastructure", "purpose": "Listener-facing stream mount", "kind": "text", "editable": false, "lockedReason": "The player and nginx both assume this mount."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_MOUNT", "group": "Infrastructure", "purpose": "Live broadcast mount", "kind": "text", "editable": false, "lockedReason": "Broadcasting clients are configured against it."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_PORT", "group": "Infrastructure", "purpose": "Live broadcast port, published to the host", "kind": "text", "editable": false, "lockedReason": "A published port: changing it needs the router and clients updated."},
|
||||
{"name": "SILVERBULLET_HOST", "group": "Infrastructure", "purpose": "Notes editor container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PORT", "group": "Infrastructure", "purpose": "Notes editor port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_HOST", "group": "Infrastructure", "purpose": "Public notes container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_PORT", "group": "Infrastructure", "purpose": "Public notes port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
|
||||
{"name": "POSTGRES_HOST", "group": "Database", "purpose": "Database container name", "kind": "text", "editable": false, "lockedReason": "Renames the database container."},
|
||||
{"name": "POSTGRES_PORT", "group": "Database", "purpose": "Database port", "kind": "text", "editable": false, "lockedReason": "Every client of the database assumes it."},
|
||||
{"name": "POSTGRES_USER", "group": "Database", "purpose": "Database role", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_PASSWORD", "group": "Database", "purpose": "Database password", "kind": "secret", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_DB", "group": "Database", "purpose": "Backend database name", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised."},
|
||||
{"name": "POSTGRES_GITEA_DB", "group": "Database", "purpose": "Gitea database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on a fresh volume."},
|
||||
{"name": "POSTGRES_JOBS_DB", "group": "Database", "purpose": "Job tracker database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on first install; see the job-tracker README."},
|
||||
{"name": "POSTGRES_JOBS_USER", "group": "Database", "purpose": "Job tracker database role", "kind": "text", "editable": false, "lockedReason": "Created by hand on first install; changing it here locks the tracker out."},
|
||||
{"name": "POSTGRES_JOBS_PASSWORD", "group": "Database", "purpose": "Job tracker database password", "kind": "secret", "editable": false, "lockedReason": "Set on the role by hand; changing it here locks the tracker out."},
|
||||
|
||||
{"name": "GITEA_HOST", "group": "Gitea", "purpose": "Gitea container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "GITEA_PORT", "group": "Gitea", "purpose": "Gitea HTTP port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "GITEA_INTERNAL_TOKEN", "group": "Gitea", "purpose": "Gitea internal API token", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_LFS_JWT_SECRET", "group": "Gitea", "purpose": "Gitea LFS token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_OAUTH2_JWT_SECRET", "group": "Gitea", "purpose": "Gitea OAuth2 token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_RUNNER_HOST", "group": "Gitea", "purpose": "Gitea URL the Actions runner registers against", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_NAME", "group": "Gitea", "purpose": "Actions runner name", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_REGISTRATION_TOKEN", "group": "Gitea", "purpose": "Single-use runner registration token", "kind": "secret", "editable": false, "lockedReason": "Single-use, and ignored once the runner is registered."}
|
||||
]
|
||||
@@ -0,0 +1,96 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Every Claude call the site makes lives in the Python service, behind an
|
||||
// /internal/ route. This file is the one way the Go backend reaches those
|
||||
// routes. The only caller now is the rowing photo reader
|
||||
// (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
|
||||
// /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.
|
||||
|
||||
// pythonClient bounds the wait on the Python service. Two minutes sits above
|
||||
// that side's own worst case (a 30s Claude timeout, retried twice with
|
||||
// backoff), so a slow Claude surfaces as Python's error rather than as a
|
||||
// timeout here. One client for every route, so they share a connection pool.
|
||||
var pythonClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// PythonError is a failure the Python service reported in words that are safe
|
||||
// and useful to show a person: the string `detail` of a 502, which is always
|
||||
// one of that route's own fixed messages ("failed to parse image data", ...).
|
||||
//
|
||||
// Everything else — a refused connection, a 422, a 503 for a missing API key,
|
||||
// a reply that will not decode — comes back as an ordinary error instead. The
|
||||
// distinction is the point: a caller relays a PythonError and only logs the
|
||||
// rest, because the rest describe plumbing the user can do nothing about and
|
||||
// may quote internals.
|
||||
type PythonError struct{ Detail string }
|
||||
|
||||
func (e *PythonError) Error() string { return e.Detail }
|
||||
|
||||
// CallPython POSTs body as JSON to baseURL+path and decodes a 200 reply into
|
||||
// T. baseURL is the service's address on the Docker network with no trailing
|
||||
// slash (handlers.Store.PythonURL); path is the route, starting with a slash.
|
||||
//
|
||||
// Any non-200 is an error. See PythonError for which ones are relayable. A
|
||||
// cancelled ctx is wrapped, not replaced, so errors.Is(err, context.Canceled)
|
||||
// still holds.
|
||||
func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) {
|
||||
var out T
|
||||
|
||||
// Note for callers sending bytes: encoding/json writes a []byte as
|
||||
// standard base64, which is the form the Anthropic API wants and so what
|
||||
// the Python side passes straight through.
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("encoding request for %s: %w", path, err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+path, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := pythonClient.Do(req)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("calling %s: %w", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
|
||||
// route's own fixed messages; a 422's detail is a list, which fails
|
||||
// to decode into the string and falls through to the generic error,
|
||||
// and a 503's detail names an environment variable, which is for the
|
||||
// log rather than the page. The body is capped because it is only
|
||||
// ever quoted in a log line.
|
||||
var failure struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
||||
return out, &PythonError{Detail: failure.Detail}
|
||||
}
|
||||
return out, fmt.Errorf("%s returned %d: %s", path, resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
// A fresh zero value, so a half-decoded T never escapes with an error.
|
||||
var zero T
|
||||
return zero, fmt.Errorf("decoding %s response: %w", path, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// CallPython is the one path from this backend to the Python service's
|
||||
// internal routes, so its contract is tested here once rather than per
|
||||
// caller: what the request looks like, and which replies come back as a
|
||||
// relayable *PythonError, which as a plain error.
|
||||
|
||||
type pythonReply struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
Note *string `json:"note"`
|
||||
}
|
||||
|
||||
func pythonStub(t *testing.T, handler http.HandlerFunc) string {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv.URL
|
||||
}
|
||||
|
||||
func TestCallPythonRequestAndReply(t *testing.T) {
|
||||
var (
|
||||
method, path, contentType string
|
||||
forwarded bool
|
||||
got map[string]any
|
||||
)
|
||||
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
|
||||
// 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 {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"name": "x", "count": 3, "note": null}`))
|
||||
})
|
||||
|
||||
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct {
|
||||
Text string `json:"text"`
|
||||
Data []byte `json:"data"`
|
||||
}{"hello", []byte("hello")})
|
||||
if err != nil {
|
||||
t.Fatalf("CallPython: %v", err)
|
||||
}
|
||||
if reply.Name != "x" || reply.Count != 3 || reply.Note != nil {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
if method != http.MethodPost || path != "/internal/thing" || contentType != "application/json" {
|
||||
t.Fatalf("request was %s %s (%s)", method, path, contentType)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python routes reject")
|
||||
}
|
||||
// A []byte travels as standard base64, which is what the rowing reader
|
||||
// relies on for the image.
|
||||
if got["text"] != "hello" || got["data"] != "aGVsbG8=" {
|
||||
t.Fatalf("request body = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a *PythonError with this message
|
||||
}{
|
||||
{"a 502's string detail is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
|
||||
{"a 502 with an empty detail is not", http.StatusBadGateway, `{"detail": ""}`, ""},
|
||||
{"a 502 that is not JSON is not", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
|
||||
// A 422's detail is a list of validation errors, not a message.
|
||||
{"a validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
// Its detail is a string, but it names an environment variable: for
|
||||
// the log, not for the page.
|
||||
{"a missing API key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"a 404 is not relayed", http.StatusNotFound, `{"detail": "Not Found"}`, ""},
|
||||
{"a malformed success body is an error", http.StatusOK, `not json`, ""},
|
||||
{"a success body of the wrong shape is an error", http.StatusOK, `{"count": "three"}`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
|
||||
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct{}{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if reply != (pythonReply{}) {
|
||||
t.Fatalf("reply = %+v alongside an error, want the zero value", reply)
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if relayed := errors.As(err, &pyErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if pyErr != nil && (pyErr.Detail != c.wantDetail || pyErr.Error() != c.wantDetail) {
|
||||
t.Fatalf("detail = %q, want %q", pyErr.Detail, c.wantDetail)
|
||||
}
|
||||
// A plumbing error names the route, so the log line says which
|
||||
// of the three calls it was.
|
||||
if pyErr == nil && !strings.Contains(err.Error(), "/internal/thing") {
|
||||
t.Fatalf("err = %v, want it to name the route", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonUnreachable(t *testing.T) {
|
||||
url := pythonStub(t, func(http.ResponseWriter, *http.Request) {})
|
||||
// Port 1 on localhost: nothing listens there.
|
||||
_, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", struct{}{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if errors.As(err, &pyErr) {
|
||||
t.Fatalf("a transport failure was reported as relayable: %v", err)
|
||||
}
|
||||
|
||||
// A cancelled call must still read as context.Canceled: the email
|
||||
// pipeline uses that to avoid counting an abandoned sync as a failure.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := CallPython[pythonReply](ctx, url, "/internal/thing", struct{}{}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("err = %v, want it to wrap context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonUnencodableBody(t *testing.T) {
|
||||
// Channels cannot be marshalled; the point is that this fails before any
|
||||
// request is made, so the URL is never dialled.
|
||||
if _, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", make(chan int)); err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,6 @@ import (
|
||||
// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only
|
||||
// logic beyond the request is the empty-feed nil,nil case, and testing it
|
||||
// would mean either a network or an injected client that does not exist.
|
||||
// - claude.go: InitClaude is a single SDK constructor with no validation and
|
||||
// no prompt building; there is nothing to assert that is not the SDK's.
|
||||
// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here.
|
||||
// - RateLimiter's window expiry uses the real clock (Allow calls time.Now
|
||||
// directly and there is no injectable clock), so the expiry case below
|
||||
|
||||
+10
-5
@@ -14,7 +14,6 @@
|
||||
# - backend : dev flags on, including database seeding.
|
||||
# - nginx : DEV_MODE=true, which makes its entrypoint render
|
||||
# nginx_dev.conf.template and self-sign a localhost certificate.
|
||||
# - hasura : console and dev mode enabled so the GraphQL console is usable.
|
||||
# - python : uvicorn --reload with the app source bind-mounted.
|
||||
# - certbot : disabled entirely.
|
||||
#
|
||||
@@ -68,10 +67,6 @@ services:
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
hasura:
|
||||
environment:
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "true"
|
||||
HASURA_GRAPHQL_DEV_MODE: "true"
|
||||
python:
|
||||
# Same command as the Dockerfile's CMD plus --reload, paired with the
|
||||
# source bind mount below so editing python/app/ restarts uvicorn.
|
||||
@@ -80,6 +75,16 @@ services:
|
||||
command: ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PYTHON_PORT:-8000} --root-path /py --reload"]
|
||||
volumes:
|
||||
- ./python/app:/app/app
|
||||
# The tracker's image ships no hot reload; for that, run its own repo's
|
||||
# `npm run dev`. Seeded like the backend, with the GraphQL playground at
|
||||
# /jobs/api/graphql. Login still goes through the backend's seeded admin.
|
||||
jobs:
|
||||
environment:
|
||||
- DEV_MODE=true
|
||||
- SEED_DB=true
|
||||
- GQL_PLAYGROUND=true
|
||||
- GQL_INTROSPECTION=true
|
||||
- MSGRAPH_REDIRECT_URI=https://localhost/jobs/api/email/callback
|
||||
certbot:
|
||||
# Profiles are opt-in: a service with a profile is only started when
|
||||
# that profile is explicitly requested. Nothing ever requests
|
||||
|
||||
+68
-54
@@ -21,7 +21,7 @@
|
||||
# app config from env_file.
|
||||
#
|
||||
# Required by this file: POSTGRES_{USER,PASSWORD,DB,PORT,HOST},
|
||||
# POSTGRES_GITEA_DB, BACKEND_HOST, HASURA_HOST, HASURA_GRAPHQL_ADMIN_SECRET,
|
||||
# POSTGRES_GITEA_DB, BACKEND_HOST,
|
||||
# ICECAST_HOST, GITEA_HOST, OBSIDIAN_DIR, and the GITEA_*
|
||||
# secrets. PYTHON_HOST/PYTHON_PORT/TFL_APP_KEY/LIQUIDSOAP_HARBOR_PORT have
|
||||
# inline defaults.
|
||||
@@ -36,7 +36,7 @@
|
||||
# WHAT IS PUBLISHED TO THE HOST
|
||||
# Only nginx (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor
|
||||
# port. Everything else is reachable only from inside app-network, which is
|
||||
# why the backend, db, hasura, silverbullet and python have no `ports:` — they are
|
||||
# why the backend, db, silverbullet and python have no `ports:` — they are
|
||||
# deliberately not exposed and are reached through nginx.
|
||||
# =============================================================================
|
||||
|
||||
@@ -111,10 +111,10 @@ services:
|
||||
- backend
|
||||
- icecast2
|
||||
- gitea
|
||||
- hasura
|
||||
- silverbullet
|
||||
- silverbullet-public
|
||||
- python
|
||||
- jobs
|
||||
networks:
|
||||
- app-network
|
||||
ports:
|
||||
@@ -177,6 +177,10 @@ services:
|
||||
# rebuild, forcing a manual re-authorisation of Spotify after each
|
||||
# deploy. Gitignored (it is a credential).
|
||||
- ./backend/token/:/backend/token
|
||||
# Hand-off directory for the admin panel's Environment tab: the backend
|
||||
# queues a change here and env-apply/apply.py on the host applies it.
|
||||
# The backend gets this instead of .env itself or the Docker socket.
|
||||
- ./env-apply/run:/backend/env-apply
|
||||
# The Obsidian vault on the host, read by the backend for the notes API.
|
||||
# Same directory is mounted read-write into silverbullet (the editor) and
|
||||
# read-only into silverbullet-public (the /notes/ site).
|
||||
@@ -187,9 +191,11 @@ services:
|
||||
# Shared with icecast2, which plays these as the radio fallback playlist;
|
||||
# the backend reads them to report what is queued.
|
||||
- ./icecast2/fallback_music:/backend/fallback_music
|
||||
# Reported to docker (and therefore to autoheal, below), which restarts the
|
||||
# container after 3 consecutive failures ~90s apart. start_period gives the
|
||||
# Go process 10s to bind before failures start counting.
|
||||
# Reported to docker only: nothing acts on `unhealthy` since the autoheal
|
||||
# watchdog was retired (.deprecated/autoheal), so this just shows up in
|
||||
# `docker ps`. `restart: always` covers a crashed process, not a hung one.
|
||||
# start_period gives the Go process 10s to bind before failures start
|
||||
# counting.
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:8080/"]
|
||||
interval: 30s
|
||||
@@ -197,31 +203,6 @@ services:
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
# Watchdog: docker itself marks a container `unhealthy` but never acts on it.
|
||||
# autoheal polls the docker socket and restarts anything that goes unhealthy.
|
||||
# AUTOHEAL_CONTAINER_LABEL=all means "watch every container that defines a
|
||||
# healthcheck" (i.e. backend and python) rather than only labelled ones.
|
||||
# It mounts the docker socket, which is effectively root on the host — that
|
||||
# is the price of the feature. Because of that the image is pinned BY DIGEST,
|
||||
# not by a floating tag: `:latest` meant any future push to Docker Hub would
|
||||
# silently gain root on the Pi at the next `docker compose pull`/`up`. The
|
||||
# digest below is a multi-arch index (it includes linux/arm64, which is what
|
||||
# the Pi pulls) and was the content of `willfarrell/autoheal:latest` at the
|
||||
# time of pinning. To bump it: pull the new tag, `docker image inspect
|
||||
# willfarrell/autoheal:<tag> --format '{{index .RepoDigests 0}}'`, and paste
|
||||
# the digest here — never go back to a bare tag.
|
||||
# Deliberately NOT on app-network: it talks only to the socket.
|
||||
autoheal:
|
||||
image: willfarrell/autoheal@sha256:4ce976e9033b41426d44633295d6a08f9bc5929b27866352d91b31d4f6b26447
|
||||
container_name: autoheal
|
||||
restart: always
|
||||
environment:
|
||||
- AUTOHEAL_CONTAINER_LABEL=all
|
||||
- AUTOHEAL_INTERVAL=30
|
||||
- AUTOHEAL_START_PERIOD=60
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
# Single Postgres instance serving TWO databases: ${POSTGRES_DB} for the Go
|
||||
# backend and ${POSTGRES_GITEA_DB} for Gitea. The postgres image only creates
|
||||
# POSTGRES_DB on first init, so the Gitea database was created by hand once;
|
||||
@@ -259,26 +240,6 @@ services:
|
||||
retries: 10
|
||||
start_period: 90s
|
||||
|
||||
# Admin-only DB browser, reached at /hasura/. Console and dev mode are OFF in
|
||||
# production (turned on by the dev override). It is additionally gated in
|
||||
# nginx by an `auth_request` subrequest to the backend's /auth/validate-admin,
|
||||
# so an admin cookie is required before the request ever reaches Hasura —
|
||||
# the admin secret alone is not the only line of defence.
|
||||
hasura:
|
||||
image: hasura/graphql-engine:v2.44.0
|
||||
container_name: "${HASURA_HOST}"
|
||||
restart: always
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
HASURA_GRAPHQL_DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
|
||||
HASURA_GRAPHQL_ADMIN_SECRET: "${HASURA_GRAPHQL_ADMIN_SECRET}"
|
||||
HASURA_GRAPHQL_ENABLE_CONSOLE: "false"
|
||||
HASURA_GRAPHQL_DEV_MODE: "false"
|
||||
HASURA_GRAPHQL_ENABLED_LOG_TYPES: "startup, http-log, webhook-log, websocket-log, query-log"
|
||||
|
||||
# Internet radio: one container running BOTH icecast2 (the streaming server
|
||||
# listeners connect to, proxied at /radio/) and liquidsoap (the source that
|
||||
# feeds it). See icecast2/entrypoint.sh.
|
||||
@@ -389,7 +350,7 @@ services:
|
||||
SB_REVISIONS: disabled
|
||||
# Newline separated (commas are silently ignored). Gitignore semantics,
|
||||
# so these match at any depth. Must match the folder list in the
|
||||
# /notes/ deny regex in BOTH nginx templates, or a new entry here is
|
||||
# /notes/ deny regex in nginx/nginx_routes.conf.template, or a new entry here is
|
||||
# hidden from the list but still publicly fetchable.
|
||||
SB_SPACE_IGNORE: |
|
||||
private/
|
||||
@@ -438,8 +399,11 @@ services:
|
||||
# OpenAPI/Swagger URLs (/py/docs) are correct even though the app's own
|
||||
# routes are written relative to /.
|
||||
# Note this service uses `environment:` with an explicit allow-list rather
|
||||
# than `env_file: ./.env` — it only gets the three variables it needs and
|
||||
# never sees the database password, Spotify secrets, or API keys.
|
||||
# than `env_file: ./.env` — it only gets the variables it needs and never
|
||||
# sees the database password, Spotify secrets, or the other API keys.
|
||||
# CLAUDE_API_KEY is the one secret on the list: the rowing photo reader
|
||||
# (POST /internal/rowing/read, called by the backend, blocked at nginx)
|
||||
# makes its Claude call here.
|
||||
python:
|
||||
build:
|
||||
context: ./python
|
||||
@@ -452,6 +416,8 @@ services:
|
||||
- PYTHON_PORT=${PYTHON_PORT:-8000}
|
||||
- ROOT_PATH=/py
|
||||
- TFL_APP_KEY=${TFL_APP_KEY:-}
|
||||
- CLAUDE_API_KEY=${CLAUDE_API_KEY:-}
|
||||
- CLAUDE_MODEL=${CLAUDE_MODEL:-}
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request,os; urllib.request.urlopen(f\"http://localhost:{os.environ.get('PYTHON_PORT','8000')}/health\")"]
|
||||
interval: 30s
|
||||
@@ -459,6 +425,54 @@ services:
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
|
||||
# The job application tracker, served at /jobs/. Built and published by its
|
||||
# own repo (adamf/job-tracker on this Gitea), whose README covers the
|
||||
# first-time database setup and the cutover from the old in-backend tracker.
|
||||
#
|
||||
# Like python, it gets an explicit `environment:` list rather than the whole
|
||||
# .env: it never sees the site's database password or JWT secret, and has a
|
||||
# database role of its own. backend/services/env_manager_test.go checks the
|
||||
# list against env_registry.json.
|
||||
#
|
||||
# It has no login. AUTH_VALIDATE_URL is the backend's validate-admin route
|
||||
# (the one nginx's auth_request uses), which the tracker asks with the
|
||||
# visitor's cookies on each admin request.
|
||||
#
|
||||
# ./jobs-data holds the Microsoft Graph session and the capture token. The
|
||||
# image runs as uid 1000, so the directory must be owned by it.
|
||||
jobs:
|
||||
image: adam-french.co.uk/adamf/job-tracker:${JOBS_IMAGE_TAG:-latest}
|
||||
container_name: jobs
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- app-network
|
||||
environment:
|
||||
- DATABASE_URL=postgres://${POSTGRES_JOBS_USER:-jobs}:${POSTGRES_JOBS_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_JOBS_DB:-jobs}?sslmode=disable
|
||||
- AUTH_VALIDATE_URL=http://${BACKEND_HOST}:${BACKEND_PORT}/auth/validate-admin
|
||||
- CLAUDE_API_KEY=${CLAUDE_API_KEY:-}
|
||||
- CLAUDE_MODEL=${CLAUDE_MODEL:-}
|
||||
- EMAIL_BACKEND=${EMAIL_BACKEND:-}
|
||||
- EMAIL_SYNC_ENABLED=${EMAIL_SYNC_ENABLED:-}
|
||||
- EMAIL_SYNC_INTERVAL=${EMAIL_SYNC_INTERVAL:-}
|
||||
- MSGRAPH_CLIENT_ID=${MSGRAPH_CLIENT_ID:-}
|
||||
- MSGRAPH_CLIENT_SECRET=${MSGRAPH_CLIENT_SECRET:-}
|
||||
- MSGRAPH_TENANT_ID=${MSGRAPH_TENANT_ID:-}
|
||||
- MSGRAPH_REDIRECT_URI=${MSGRAPH_REDIRECT_URI:-}
|
||||
- IMAP_HOST=${IMAP_HOST:-}
|
||||
- IMAP_PORT=${IMAP_PORT:-}
|
||||
- IMAP_EMAIL=${IMAP_EMAIL:-}
|
||||
- IMAP_PASSWORD=${IMAP_PASSWORD:-}
|
||||
- JOB_LEADS_ENABLED=${JOB_LEADS_ENABLED:-}
|
||||
- JOB_LEADS_INTERVAL=${JOB_LEADS_INTERVAL:-}
|
||||
- ADZUNA_APP_ID=${ADZUNA_APP_ID:-}
|
||||
- ADZUNA_APP_KEY=${ADZUNA_APP_KEY:-}
|
||||
- REED_API_KEY=${REED_API_KEY:-}
|
||||
volumes:
|
||||
- ./jobs-data:/data
|
||||
|
||||
# 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/).
|
||||
|
||||
Executable
+266
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env python3
|
||||
# =============================================================================
|
||||
# apply.py — the host half of the admin panel's Environment tab.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Takes the change the backend queued in env-apply/run/request.json, merges
|
||||
# it into ./.env, recreates the containers that read the changed variables,
|
||||
# and reports the outcome in env-apply/run/status.json for the panel to show.
|
||||
#
|
||||
# WHY IT RUNS ON THE HOST
|
||||
# The backend is the internet-facing process. It is given neither write
|
||||
# access to .env nor the Docker socket, so the most a hijacked admin session
|
||||
# can do is ask for a change to a variable this script agrees is editable.
|
||||
# The list of those is backend/services/env_registry.json, read here from
|
||||
# the checkout — the same file the backend embeds.
|
||||
#
|
||||
# WHEN IT RUNS
|
||||
# On the Pi, started by the systemd path unit that install.sh sets up, the
|
||||
# moment request.json appears. By hand anywhere else:
|
||||
# python3 env-apply/apply.py
|
||||
# On a dev machine pass the compose files the stack was started with:
|
||||
# python3 env-apply/apply.py \
|
||||
# --compose-cmd "docker compose -f docker-compose.yml -f docker-compose.dev.yml"
|
||||
#
|
||||
# SAFETY
|
||||
# - The request is claimed by rename before anything else, so it is consumed
|
||||
# exactly once and its secrets leave the shared directory even on failure.
|
||||
# - .env is replaced atomically (temp file + rename) and the previous
|
||||
# version kept as .env.bak. If compose then rejects the file, the backup
|
||||
# is put back before anything is recreated.
|
||||
# - Only the services that read a changed variable are recreated (plus the
|
||||
# backend, whose own environment is what the panel reports). A plain
|
||||
# `docker compose up -d` would restart Postgres and nginx for any edit,
|
||||
# because they load the whole file too; the next deploy catches them up.
|
||||
# - An flock on run/lock keeps this from overlapping itself or the deploy
|
||||
# workflow, which takes the same lock.
|
||||
#
|
||||
# Standard library only: it has to run on a bare Raspberry Pi OS.
|
||||
# =============================================================================
|
||||
import argparse
|
||||
import datetime
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Values made only of these are written bare; anything else is single-quoted,
|
||||
# which dotenv reads literally (no $ interpolation, no # comments).
|
||||
BARE_VALUE = re.compile(r"^[A-Za-z0-9_./:@+,=-]*$")
|
||||
|
||||
# How much compose output a failed run reports back to the panel.
|
||||
OUTPUT_TAIL_LINES = 40
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def format_line(name, value):
|
||||
if BARE_VALUE.match(value):
|
||||
return f"{name}={value}"
|
||||
return f"{name}='{value}'"
|
||||
|
||||
|
||||
def merge(text, changes):
|
||||
"""Return .env text with each changed variable's line replaced in place.
|
||||
|
||||
Comments, blank lines and ordering are kept. A variable with no line yet
|
||||
is appended.
|
||||
"""
|
||||
remaining = dict(changes)
|
||||
out = []
|
||||
for line in text.splitlines():
|
||||
match = re.match(r"^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=", line)
|
||||
if match and match.group(2) in changes:
|
||||
name = match.group(2)
|
||||
out.append((match.group(1) or "") + format_line(name, changes[name]))
|
||||
remaining.pop(name, None)
|
||||
else:
|
||||
out.append(line)
|
||||
if remaining:
|
||||
if out and out[-1].strip():
|
||||
out.append("")
|
||||
out.append("# Added from the admin panel")
|
||||
for name in sorted(remaining):
|
||||
out.append(format_line(name, remaining[name]))
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def write_atomically(path, text):
|
||||
"""Replace path, keeping its mode and owner."""
|
||||
stat = os.stat(path)
|
||||
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".env.tmp.")
|
||||
try:
|
||||
with os.fdopen(fd, "w") as handle:
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.chmod(tmp, stat.st_mode & 0o7777)
|
||||
try:
|
||||
os.chown(tmp, stat.st_uid, stat.st_gid)
|
||||
except PermissionError:
|
||||
pass # not root and not the owner; the rename below still works
|
||||
os.replace(tmp, path)
|
||||
except BaseException:
|
||||
if os.path.exists(tmp):
|
||||
os.unlink(tmp)
|
||||
raise
|
||||
|
||||
|
||||
def load_registry(path):
|
||||
with open(path) as handle:
|
||||
return {entry["name"]: entry for entry in json.load(handle)}
|
||||
|
||||
|
||||
def check(changes, registry):
|
||||
"""Refuse anything the backend should never have asked for."""
|
||||
if not isinstance(changes, dict) or not changes:
|
||||
raise ValueError("the request changes nothing")
|
||||
for name, value in changes.items():
|
||||
entry = registry.get(name)
|
||||
if entry is None or not entry.get("editable"):
|
||||
raise ValueError(f"{name} is not editable")
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"{name} is not a string")
|
||||
if "'" in value or any(ord(c) < 0x20 or ord(c) == 0x7F for c in value):
|
||||
raise ValueError(f"{name} holds a character .env cannot carry")
|
||||
|
||||
|
||||
def services_for(names, registry):
|
||||
services = {"backend"}
|
||||
for name in names:
|
||||
services.update(registry[name].get("services", []))
|
||||
return sorted(services)
|
||||
|
||||
|
||||
def run(cmd, cwd):
|
||||
result = subprocess.run(
|
||||
cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True
|
||||
)
|
||||
return result.returncode, result.stdout
|
||||
|
||||
|
||||
def tail(text):
|
||||
return "\n".join(text.strip().splitlines()[-OUTPUT_TAIL_LINES:])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--env-file", default=os.path.join(ROOT, ".env"))
|
||||
parser.add_argument("--run-dir", default=os.path.join(ROOT, "env-apply", "run"))
|
||||
parser.add_argument(
|
||||
"--registry",
|
||||
default=os.path.join(ROOT, "backend", "services", "env_registry.json"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--compose-cmd",
|
||||
default="docker compose",
|
||||
help="compose invocation, e.g. to add -f files for a dev stack",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="report what would change and leave everything untouched",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
compose = shlex.split(args.compose_cmd)
|
||||
compose_dir = os.path.dirname(os.path.abspath(args.env_file))
|
||||
request_path = os.path.join(args.run_dir, "request.json")
|
||||
claimed_path = os.path.join(args.run_dir, "request.claimed")
|
||||
status_path = os.path.join(args.run_dir, "status.json")
|
||||
backup_path = args.env_file + ".bak"
|
||||
|
||||
def report(state, request_id, **extra):
|
||||
body = {"state": state, "id": request_id, "at": now(), **extra}
|
||||
tmp = status_path + ".tmp"
|
||||
with open(tmp, "w") as handle:
|
||||
json.dump(body, handle)
|
||||
os.chmod(tmp, 0o644)
|
||||
os.replace(tmp, status_path)
|
||||
|
||||
if args.dry_run:
|
||||
if not os.path.exists(request_path):
|
||||
print("No request pending.")
|
||||
return 0
|
||||
with open(request_path) as handle:
|
||||
request = json.load(handle)
|
||||
registry = load_registry(args.registry)
|
||||
check(request.get("set"), registry)
|
||||
names = sorted(request["set"])
|
||||
print("Would set:", ", ".join(names))
|
||||
print("Would recreate:", ", ".join(services_for(names, registry)))
|
||||
return 0
|
||||
|
||||
with open(os.path.join(args.run_dir, "lock"), "w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
|
||||
# Claim first: after this rename the request cannot be applied twice,
|
||||
# and a crash below leaves no secrets where the backend can read them.
|
||||
try:
|
||||
os.replace(request_path, claimed_path)
|
||||
except FileNotFoundError:
|
||||
print("No request pending.")
|
||||
return 0
|
||||
try:
|
||||
with open(claimed_path) as handle:
|
||||
request = json.load(handle)
|
||||
finally:
|
||||
os.unlink(claimed_path)
|
||||
|
||||
request_id = str(request.get("id", ""))
|
||||
try:
|
||||
registry = load_registry(args.registry)
|
||||
changes = request.get("set")
|
||||
check(changes, registry)
|
||||
names = sorted(changes)
|
||||
services = services_for(names, registry)
|
||||
report("applying", request_id, changed=names, services=services)
|
||||
|
||||
with open(args.env_file) as handle:
|
||||
before = handle.read()
|
||||
shutil.copy2(args.env_file, backup_path)
|
||||
os.chmod(backup_path, 0o600)
|
||||
write_atomically(args.env_file, merge(before, changes))
|
||||
|
||||
# Catch a file compose cannot parse before any container is
|
||||
# stopped for it.
|
||||
code, output = run(compose + ["config", "-q"], compose_dir)
|
||||
if code != 0:
|
||||
write_atomically(args.env_file, before)
|
||||
raise RuntimeError(
|
||||
"compose rejected the new .env; it was restored.\n" + tail(output)
|
||||
)
|
||||
|
||||
code, output = run(
|
||||
compose + ["up", "-d", "--no-deps", "--force-recreate"] + services,
|
||||
compose_dir,
|
||||
)
|
||||
if code != 0:
|
||||
# .env keeps the new values: they are valid, and the usual
|
||||
# cause here is a container that would not start, which the
|
||||
# old values would not fix.
|
||||
raise RuntimeError(
|
||||
".env was updated but recreating the containers failed.\n"
|
||||
+ tail(output)
|
||||
)
|
||||
except Exception as error: # noqa: BLE001 - everything is reported
|
||||
report("failed", request_id, output=str(error))
|
||||
print(f"Failed: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
report("applied", request_id, changed=names, services=services)
|
||||
print(f"Applied {', '.join(names)}; recreated {', '.join(services)}.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# install.sh — one-time setup, on the Pi, of the watcher behind the admin
|
||||
# panel's Environment tab.
|
||||
#
|
||||
# WHAT IT DOES
|
||||
# Installs two systemd units:
|
||||
# web-server-env-apply.path watches env-apply/run/request.json
|
||||
# web-server-env-apply.service runs apply.py when that file appears
|
||||
# The units are generated here rather than committed because they need this
|
||||
# checkout's absolute path and the user that owns it.
|
||||
#
|
||||
# HOW TO RUN
|
||||
# From the deploy checkout, as the user that runs docker compose there:
|
||||
# ./env-apply/install.sh
|
||||
# It calls sudo for the three steps that need root. Re-running is safe and
|
||||
# is how to pick up a change to the units below.
|
||||
#
|
||||
# WHY A PATH UNIT
|
||||
# PathExists fires as soon as the backend writes the request, and also at
|
||||
# boot if a request was queued while the Pi was down. apply.py renames the
|
||||
# request away before doing anything else, so the unit cannot retrigger on
|
||||
# the same file.
|
||||
#
|
||||
# The service runs as the checkout's owner, not root: it needs exactly what
|
||||
# the deploy workflow has (write .env, run docker compose) and no more.
|
||||
# DOCKER_API_VERSION and COMPOSE_BAKE mirror .gitea/workflows/deploy.yaml.
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
RUN_USER="$(id -un)"
|
||||
RUN_DIR="${ROOT}/env-apply/run"
|
||||
|
||||
if [ "$RUN_USER" = "root" ]; then
|
||||
echo "Run this as the user that owns the checkout, not root." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! command -v python3 >/dev/null; then
|
||||
echo "python3 is required." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The backend bind-mounts this directory. If Docker creates it first it is
|
||||
# root-owned and apply.py cannot write its status there.
|
||||
mkdir -p "$RUN_DIR"
|
||||
if [ "$(stat -c %U "$RUN_DIR")" != "$RUN_USER" ]; then
|
||||
sudo chown "$RUN_USER" "$RUN_DIR"
|
||||
fi
|
||||
|
||||
sudo tee /etc/systemd/system/web-server-env-apply.path >/dev/null <<EOF
|
||||
[Unit]
|
||||
Description=Watch for .env changes queued from the admin panel
|
||||
|
||||
[Path]
|
||||
PathExists=${RUN_DIR}/request.json
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
sudo tee /etc/systemd/system/web-server-env-apply.service >/dev/null <<EOF
|
||||
[Unit]
|
||||
Description=Apply a .env change queued from the admin panel
|
||||
After=docker.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=${RUN_USER}
|
||||
WorkingDirectory=${ROOT}
|
||||
Environment=DOCKER_API_VERSION=1.41
|
||||
Environment=COMPOSE_BAKE=false
|
||||
ExecStart=/usr/bin/env python3 ${ROOT}/env-apply/apply.py
|
||||
EOF
|
||||
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now web-server-env-apply.path
|
||||
|
||||
echo "Installed. Watching ${RUN_DIR}/request.json as ${RUN_USER}."
|
||||
echo "Logs: journalctl -u web-server-env-apply.service"
|
||||
@@ -20,6 +20,10 @@
|
||||
; 22 and cannot use the host's sshd, so Gitea runs its own Go SSH server.
|
||||
; 2222 is published in docker-compose.yml; the deploy workflow clones over
|
||||
; ssh://git@localhost:2222.
|
||||
; SSH_DOMAIN is the Pi's Tailscale MagicDNS name, not the public domain: SSH
|
||||
; (22 and 2222) is not forwarded by the router, so the SSH clone URL Gitea
|
||||
; shows only works from a device on the tailnet. HTTPS clones go through
|
||||
; nginx at ROOT_URL and stay public.
|
||||
; REVERSE_PROXY_LIMIT = 1 / TRUSTED_PROXIES = * : trust exactly one hop of
|
||||
; X-Forwarded-For, i.e. our nginx, so Gitea logs real client IPs. This is
|
||||
; only safe because nginx is the sole edge.
|
||||
@@ -46,7 +50,7 @@ TEMP_PATH = /tmp/gitea/uploads
|
||||
|
||||
[server]
|
||||
APP_DATA_PATH = /var/lib/gitea
|
||||
SSH_DOMAIN = adam-french.co.uk
|
||||
SSH_DOMAIN = stppi.tailf20278.ts.net
|
||||
HTTP_PORT = 3000
|
||||
ROOT_URL = https://adam-french.co.uk/gitea/
|
||||
DISABLE_SSH = false
|
||||
|
||||
+10
-3
@@ -1,5 +1,6 @@
|
||||
# =============================================================================
|
||||
# nginx image — the public edge. Stock nginx plus two tools and three templates.
|
||||
# nginx image — the public edge. Stock nginx plus two tools, three config
|
||||
# templates and the two partials they include.
|
||||
#
|
||||
# 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
|
||||
@@ -19,9 +20,11 @@
|
||||
#
|
||||
# apt lists are deleted in the SAME RUN layer so they never end up in the image.
|
||||
#
|
||||
# NO nginx.conf IS COPIED IN. All three templates (plus the dev partial) are,
|
||||
# NO nginx.conf IS COPIED IN. All three templates (plus the two partials) are,
|
||||
# and entrypoint.sh picks one at container start. See nginx/entrypoint.sh for
|
||||
# that decision.
|
||||
# that decision. A new partial needs BOTH a COPY here and an envsubst render in
|
||||
# the entrypoint, or nginx fails at start with "open() ... failed" on the
|
||||
# include.
|
||||
# =============================================================================
|
||||
FROM nginx:1.27
|
||||
RUN rm -rf /etc/nginx/html/* && \
|
||||
@@ -34,6 +37,10 @@ COPY nginx_dev.conf.template /etc/nginx/nginx_dev.conf.template
|
||||
# (same envsubst allow-list) to /etc/nginx/nginx_dev_common.conf, which is the
|
||||
# path both `include` directives in nginx_dev.conf.template point at.
|
||||
COPY nginx_dev_common.conf.template /etc/nginx/nginx_dev_common.conf.template
|
||||
# The proxy route table shared by production and dev. entrypoint.sh renders it
|
||||
# (same envsubst allow-list) to /etc/nginx/nginx_routes.conf, the path
|
||||
# nginx.conf.template and nginx_dev_common.conf.template both `include`.
|
||||
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
|
||||
|
||||
+51
-9
@@ -6,8 +6,11 @@
|
||||
# WHAT IT DOES
|
||||
# nginx.conf is not shipped in the image. Instead three *templates* are baked
|
||||
# in (see nginx/Dockerfile) and this script renders exactly one of them to
|
||||
# /etc/nginx/nginx.conf before starting nginx in the foreground. In dev it
|
||||
# also renders the shared server-block partial the dev template includes.
|
||||
# /etc/nginx/nginx.conf before starting nginx in the foreground. It also
|
||||
# renders the PARTIALS those templates `include`: the proxy route table
|
||||
# shared by production and dev (nginx_routes.conf, every boot path) and, in
|
||||
# dev only, the body shared by the two dev server blocks
|
||||
# (nginx_dev_common.conf). See RENDERED FILES below.
|
||||
# After nginx starts, a background watcher handles certificates appearing or
|
||||
# being renewed — see CERTIFICATE WATCHER at the bottom of this file.
|
||||
#
|
||||
@@ -47,6 +50,19 @@
|
||||
# Step (c) IS automatic now. A first deploy on a new domain no longer needs a
|
||||
# manual `docker compose restart nginx`; a restart remains a valid fallback.
|
||||
#
|
||||
# RENDERED FILES (template in the image -> path nginx reads)
|
||||
# nginx.conf.template | nginx_dev.conf.template | nginx_setup.conf.template
|
||||
# -> /etc/nginx/nginx.conf (one of three)
|
||||
# nginx_routes.conf.template -> /etc/nginx/nginx_routes.conf
|
||||
# The reverse-proxy locations common to production and dev. Included
|
||||
# by nginx.conf.template directly and by nginx_dev_common.conf. This is
|
||||
# where a new proxied route goes.
|
||||
# nginx_dev_common.conf.template -> /etc/nginx/nginx_dev_common.conf
|
||||
# Dev only: included by both server blocks of nginx_dev.conf.template.
|
||||
# The `include` directives name those rendered paths literally, so a partial
|
||||
# must be written BEFORE anything runs nginx (or `nginx -t`) against a config
|
||||
# that includes it.
|
||||
#
|
||||
# THE envsubst TEMPLATING PATTERN
|
||||
# The templates are plain nginx configs containing $VARIABLES. Two different
|
||||
# kinds of $VAR live in the same file:
|
||||
@@ -67,7 +83,6 @@
|
||||
# BACKEND_ENDPOINT URL prefix the API is mounted at (e.g. /api)
|
||||
# ICECAST_HOST / ICECAST_PORT radio stream upstream
|
||||
# GITEA_HOST / GITEA_PORT git server upstream
|
||||
# HASURA_HOST / HASURA_PORT Hasura console upstream
|
||||
# SILVERBULLET_HOST / _PORT notes editor upstream (defaulted below)
|
||||
# SILVERBULLET_PUBLIC_HOST / _PORT
|
||||
# public notes viewer upstream (defaulted below)
|
||||
@@ -94,9 +109,26 @@ export SILVERBULLET_PUBLIC_HOST="${SILVERBULLET_PUBLIC_HOST:-silverbullet-public
|
||||
export SILVERBULLET_PUBLIC_PORT="${SILVERBULLET_PUBLIC_PORT:-3000}"
|
||||
|
||||
# The envsubst allow-list, defined once and reused by both full-config branches
|
||||
# so the two lists cannot drift apart. It MUST stay single-quoted here and be
|
||||
# passed as "$ENVSUBST_VARS" (one argument) below.
|
||||
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${HASURA_HOST} ${HASURA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
||||
# and by every partial, so the lists cannot drift apart. It MUST stay
|
||||
# single-quoted here and be passed as "$ENVSUBST_VARS" (one argument) below.
|
||||
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
||||
|
||||
# Render the shared proxy route table. Done ONCE, here, ahead of the three-way
|
||||
# decision, rather than inside each branch:
|
||||
# - dev and production both include it, so both need it before nginx starts;
|
||||
# - the setup branch does not include it, but the certificate watcher at the
|
||||
# bottom of this file later switches setup -> production by validating a
|
||||
# candidate production config with `nginx -t`, and that candidate includes
|
||||
# this path. Having it already on disk means the watcher has nothing extra
|
||||
# to render and no ordering to get wrong.
|
||||
# It is safe to write straight to the live path (no temp file + validate, as
|
||||
# the watcher does for nginx.conf): this runs before nginx has started, and
|
||||
# its content depends only on the image's template and the container's
|
||||
# environment, neither of which can change while the container lives — so
|
||||
# there is never a newer version to swap in under a running nginx.
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx_routes.conf.template \
|
||||
>/etc/nginx/nginx_routes.conf
|
||||
|
||||
# Check if DEV_MODE
|
||||
if [ "$DEV_MODE" = "true" ]; then
|
||||
@@ -113,7 +145,8 @@ if [ "$DEV_MODE" = "true" ]; then
|
||||
fi
|
||||
# In dev mode, so use nginx_dev.conf.template. Its two server blocks both
|
||||
# `include /etc/nginx/nginx_dev_common.conf`, so the shared partial has to be
|
||||
# rendered through the SAME allow-list, into exactly that path, first.
|
||||
# rendered through the SAME allow-list, into exactly that path, first. (That
|
||||
# partial in turn includes nginx_routes.conf, rendered above.)
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx_dev_common.conf.template \
|
||||
>/etc/nginx/nginx_dev_common.conf
|
||||
@@ -123,7 +156,8 @@ if [ "$DEV_MODE" = "true" ]; then
|
||||
CONFIG_MODE=dev
|
||||
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
||||
echo "Certificates found. Using production nginx config."
|
||||
# In production with certificates already existing, so use nginx.conf.template
|
||||
# In production with certificates already existing, so use nginx.conf.template.
|
||||
# It includes nginx_routes.conf, rendered above.
|
||||
envsubst "$ENVSUBST_VARS" \
|
||||
</etc/nginx/nginx.conf.template \
|
||||
>/etc/nginx/nginx.conf
|
||||
@@ -131,7 +165,9 @@ elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencr
|
||||
else
|
||||
echo "Certificates NOT found. Using setup nginx config."
|
||||
# In production with no certificates, so use nginx_setup.conf.template and will need restart after generation
|
||||
# Only ${DOMAIN} is substituted: the setup config has no upstreams at all.
|
||||
# Only ${DOMAIN} is substituted: the setup config has no upstreams at all
|
||||
# (and does not include nginx_routes.conf — that file is on disk only so the
|
||||
# certificate watcher can switch to the production config later).
|
||||
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
||||
CONFIG_MODE=setup
|
||||
fi
|
||||
@@ -203,6 +239,12 @@ CERT_WATCH_INTERVAL="${CERT_WATCH_INTERVAL:-60}"
|
||||
|
||||
# Render the production template to a temp file, validate it, and only then
|
||||
# install it. Returns non-zero (installing nothing) if either step fails.
|
||||
# The candidate `include`s /etc/nginx/nginx_routes.conf by absolute path, so
|
||||
# `nginx -t` here validates the shared route table too; that file was rendered
|
||||
# once at the top of this script and is deliberately NOT re-rendered here (it
|
||||
# cannot have changed — see the comment where it is rendered — and rewriting a
|
||||
# file the running nginx may be about to re-read would only add a window in
|
||||
# which it is truncated).
|
||||
render_prod_config() {
|
||||
_candidate=/tmp/nginx.conf.candidate
|
||||
envsubst "$ENVSUBST_VARS" </etc/nginx/nginx.conf.template >"$_candidate" 2>/dev/null || return 1
|
||||
|
||||
+75
-303
@@ -11,7 +11,7 @@
|
||||
# TEMPLATING
|
||||
# Only the names in the envsubst allow-list in nginx/entrypoint.sh are
|
||||
# substituted: DOMAIN, BACKEND_HOST/PORT/ENDPOINT, ICECAST_*, GITEA_*,
|
||||
# HASURA_*, SILVERBULLET_*, PYTHON_*, UPTIMEKUMA_*, WALLABAG_*. Every other dollar
|
||||
# SILVERBULLET_*, PYTHON_*. Every other dollar
|
||||
# token in this file is an nginx RUNTIME variable (host, remote_addr, uri,
|
||||
# http_upgrade, proxy_add_x_forwarded_for, binary_remote_addr, request_uri,
|
||||
# scheme, http_cookie) and must be left alone — that restriction is the whole
|
||||
@@ -25,6 +25,16 @@
|
||||
# is exactly one canonical origin (important: cookies,
|
||||
# CORS and the SPA all assume www).
|
||||
# 3. :443 www -> the real site.
|
||||
#
|
||||
# WHERE THE PROXY ROUTES ARE
|
||||
# Not in this file. The reverse-proxied locations (/api, /radio, /gitea,
|
||||
# /notes, /sb, /py and the admin-gate subrequest) and the `set $upstream_*`
|
||||
# variables are shared with dev and live in nginx_routes.conf.template,
|
||||
# which the www server block includes. ADD NEW PROXIED ROUTES THERE. What
|
||||
# stays here is what only production has: TLS, the redirects, the security
|
||||
# headers, static-asset caching, the SPA fallback, the /uploads/ blocks
|
||||
# (which carry the security headers), the `graphql` rate-limit zone and its
|
||||
# location, and the limit_req_zone declarations the shared routes refer to.
|
||||
# =============================================================================
|
||||
events {
|
||||
worker_connections 1024;
|
||||
@@ -76,7 +86,9 @@ http {
|
||||
# This is an abuse ceiling, not a quota.
|
||||
# graphql 10r/s burst=10 - tighter than REST because a single GraphQL
|
||||
# query can be arbitrarily expensive to resolve.
|
||||
# (Production only; the dev template omits it.)
|
||||
# (Production only; the dev template omits it.
|
||||
# Its location is at the bottom of this file,
|
||||
# not in the shared route table.)
|
||||
# upload 5r/m burst=3 - uploads are 50MB-capable and hit disk; this
|
||||
# bounds how fast one IP can fill the volume.
|
||||
# hotel_search 3r/m burst=2 - each request holds an upstream call to
|
||||
@@ -89,6 +101,11 @@ http {
|
||||
# CDN or upstream proxy in front), that is correct. If anything is ever put
|
||||
# in front, these zones must switch to a trusted X-Forwarded-For or every
|
||||
# visitor will share one bucket.
|
||||
#
|
||||
# login, api, upload and hotel_search are USED from
|
||||
# nginx_routes.conf.template, which dev includes too — so
|
||||
# nginx_dev.conf.template must declare the same four zones, or the dev
|
||||
# config fails to load with "zero size shared memory zone".
|
||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
|
||||
limit_req_zone $binary_remote_addr zone=graphql:10m rate=10r/s;
|
||||
@@ -153,7 +170,38 @@ http {
|
||||
|
||||
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
|
||||
|
||||
return 301 https://www.$DOMAIN$request_uri;
|
||||
# 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. Everything else still goes to www.
|
||||
#
|
||||
# The redirect is a `location /` rather than the server-level return
|
||||
# it used to be, because a server-level return runs before any
|
||||
# location is chosen. The HSTS add_header above is inherited by both
|
||||
# locations, which declare none of their own.
|
||||
location /v2/ {
|
||||
# Image layers are far larger than the http block's 50M, and are
|
||||
# streamed to Gitea rather than spooled to disk first.
|
||||
client_max_body_size 0;
|
||||
proxy_request_buffering off;
|
||||
proxy_read_timeout 900s;
|
||||
proxy_send_timeout 900s;
|
||||
# $upstream_gitea is set in nginx_routes.conf, which only the www
|
||||
# server includes.
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
proxy_pass $upstream_gitea;
|
||||
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;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://www.$DOMAIN$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
@@ -161,13 +209,9 @@ http {
|
||||
http2 on;
|
||||
server_name www.$DOMAIN;
|
||||
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_silverbullet http://$SILVERBULLET_HOST:$SILVERBULLET_PORT;
|
||||
set $upstream_silverbullet_public http://$SILVERBULLET_PUBLIC_HOST:$SILVERBULLET_PUBLIC_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
# The `set $upstream_*` variables used by proxy_pass are declared in
|
||||
# nginx_routes.conf (included below), alongside the routes that use
|
||||
# them.
|
||||
|
||||
root /etc/nginx/html;
|
||||
index index.html;
|
||||
@@ -179,6 +223,9 @@ http {
|
||||
# included there instead of here, because any location that declares
|
||||
# so much as one add_header of its own otherwise inherits none of
|
||||
# these (nginx's add_header inheritance is all-or-nothing).
|
||||
# The shared proxy routes in nginx_routes.conf rely on exactly this
|
||||
# server-level include: none of them declares an add_header, so they
|
||||
# all inherit these headers here, and inherit nothing in dev.
|
||||
include /etc/nginx/security_headers.conf;
|
||||
|
||||
# Vite hashed assets - immutable, cache 1 year
|
||||
@@ -205,7 +252,7 @@ http {
|
||||
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||
# messages are written by the backend to /backend/uploads/private/ and
|
||||
# must not be readable by the public, so this subpath is put behind the
|
||||
# same admin `auth_request` used for /hasura/ and /sb/. nginx picks
|
||||
# same admin `auth_request` used for /sb/. nginx picks
|
||||
# the LONGEST matching prefix location, so this block wins over the
|
||||
# public /uploads/ block below for /uploads/private/* regardless of
|
||||
# ordering. Same three hardening headers as the public block, because
|
||||
@@ -274,80 +321,25 @@ http {
|
||||
include /etc/nginx/security_headers.conf;
|
||||
}
|
||||
|
||||
# ---- Backend API -----------------------------------------------------
|
||||
# Two patterns repeat through every proxied location below:
|
||||
# ---- Shared proxy route table ----------------------------------------
|
||||
# Every reverse-proxied location (/api, /radio, /gitea, /notes, /sb,
|
||||
# /py), the admin auth_request gate and the `set $upstream_*` variables
|
||||
# come from nginx_routes.conf.template, rendered by the entrypoint to
|
||||
# this path and shared with the dev config. The prefix-strip rewrite,
|
||||
# the forwarding headers and the websocket upgrade are annotated there.
|
||||
#
|
||||
# 1. THE PREFIX-STRIP REWRITE
|
||||
# rewrite ^<PREFIX>/(.*)$ /$1 break;
|
||||
# The public URL carries a prefix (/api, /radio, /gitea, /py) but the upstream service serves its routes from /. The
|
||||
# rewrite strips the prefix and `break` stops rewrite processing so
|
||||
# the request stays in this location and goes to proxy_pass with the
|
||||
# rewritten URI. (This is why proxy_pass here has no trailing path —
|
||||
# with a variable upstream, nginx would not do the strip for us.)
|
||||
# The bare `location <PREFIX>` blocks that 301 to `<PREFIX>/` exist
|
||||
# only so a user typing /gitea without the slash lands correctly.
|
||||
#
|
||||
# 2. THE FOUR FORWARDING HEADERS
|
||||
# Host preserve the browser's hostname so the app
|
||||
# builds correct absolute URLs and cookies.
|
||||
# X-Real-IP the true client IP (the upstream otherwise
|
||||
# sees only nginx's container IP).
|
||||
# X-Forwarded-For appends the client to any existing chain.
|
||||
# X-Forwarded-Proto tells the app the ORIGINAL request was
|
||||
# https even though this hop is plain http.
|
||||
# Without it the backend would issue
|
||||
# non-Secure cookies and http:// redirects,
|
||||
# breaking auth behind TLS termination.
|
||||
#
|
||||
# Ordering matters: nginx picks the longest matching prefix location,
|
||||
# so the specific /ws, /auth/login, /messages/upload and /graphql blocks
|
||||
# win over the catch-all <PREFIX>/ block regardless of file order.
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
# WebSocket endpoint (live chat / activity feed).
|
||||
# The three lines that make an upgrade work, and why each is needed:
|
||||
# proxy_http_version 1.1 - HTTP/1.0 has no Upgrade mechanism at all.
|
||||
# Upgrade $http_upgrade - hop-by-hop headers are NOT forwarded by
|
||||
# Connection "upgrade" default, so they must be re-set by hand.
|
||||
# Note the Connection value is hardcoded rather than using the usual
|
||||
# $connection_upgrade map: this location only ever serves websockets, so
|
||||
# there is no plain-HTTP case to fall back to.
|
||||
# Deliberately NOT rate limited — a websocket is one long-lived request
|
||||
# and a limit_req here would drop reconnect storms, not abuse.
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
# Position matters for one thing only: regex locations are tried in
|
||||
# file order, so the ACME regex above stays ahead of the /notes and
|
||||
# /py/hotels regexes inside this include, as it always was.
|
||||
include /etc/nginx/nginx_routes.conf;
|
||||
|
||||
# GraphQL, PRODUCTION ONLY — which is why it is here and not in the
|
||||
# shared table. Longest-prefix matching makes it win over the shared
|
||||
# $BACKEND_ENDPOINT/ catch-all, swapping the general `api` limit for
|
||||
# the tighter `graphql` zone declared at the top of this file. Dev has
|
||||
# no such location, so GraphQL there falls under `api`. Apart from the
|
||||
# limit_req line the body must stay identical to $BACKEND_ENDPOINT/ in
|
||||
# nginx_routes.conf.template.
|
||||
location $BACKEND_ENDPOINT/graphql {
|
||||
limit_req zone=graphql burst=10 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
@@ -358,226 +350,6 @@ http {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
# 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
|
||||
# internet through this proxy. Put it behind the same admin
|
||||
# `auth_request` as /hasura/ and /sb/ so an admin session cookie is
|
||||
# required before the request ever reaches icecast. Longest-prefix
|
||||
# matching means this wins over /radio/ below; listener traffic
|
||||
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||
location /radio/admin/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
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;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
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;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
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;
|
||||
}
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
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;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
# PUBLIC notes viewer: a second, read-only SilverBullet over the same
|
||||
# vault the /sb/ editor edits. No auth_request — this is the public
|
||||
# site. See the silverbullet-public service in docker-compose.yml.
|
||||
#
|
||||
# THE DENY BLOCKS BELOW ARE THE PRIVACY BOUNDARY, not decoration.
|
||||
# SB_SPACE_IGNORE only hides paths from the file LIST. Everything else
|
||||
# happily 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 from the list, so the block must too.
|
||||
#
|
||||
# 1. private/ or templates/ as any path segment, page URL or /.fs/.
|
||||
# ~* 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.
|
||||
# nginx matches against the normalised URI (percent-decoded, `..`
|
||||
# resolved, slashes merged), so %2F, // or ../ tricks cannot slip past.
|
||||
# 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.
|
||||
location ~* ^/notes/(.*/)?(private|templates)(/|$) {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ~ ^/notes/.+/\. {
|
||||
return 404;
|
||||
}
|
||||
|
||||
# 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. ^~ so no regex
|
||||
# location can take precedence.
|
||||
location ^~ /notes/.revisions {
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Same as /sb/: deliberately NO prefix-strip rewrite. The app is told
|
||||
# its base path via SB_URL_PREFIX=/notes and builds its service worker
|
||||
# scope and asset URLs from it; strip the prefix and it loads blank.
|
||||
# Upgrade/Connection are for its live-update event stream.
|
||||
location /notes/ {
|
||||
proxy_pass $upstream_silverbullet_public;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location /sb {
|
||||
return 301 /sb/;
|
||||
}
|
||||
|
||||
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes.
|
||||
# Deliberately NO prefix-strip rewrite, unlike every other proxied app
|
||||
# here. SilverBullet is a PWA told its own base path via SB_URL_PREFIX=/sb,
|
||||
# and its service worker scope and asset URLs are built from that. Strip
|
||||
# the prefix and the app loads a blank page with no error in the log.
|
||||
# Upgrade/Connection are for its sync websocket.
|
||||
location /sb/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
proxy_pass $upstream_silverbullet;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
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;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
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;
|
||||
}
|
||||
|
||||
# ---- Admin gate (/hasura/, /sb/, /radio/admin/, /uploads/private/) ----
|
||||
# `auth_request` makes nginx fire a subrequest here before serving the
|
||||
# real one; a 2xx lets it through, 401/403 triggers error_page ->
|
||||
# @auth_denied -> redirect to the SPA login. This puts the Go backend's
|
||||
# session cookie in front of services that have no idea it exists.
|
||||
# internal; - unreachable from outside, subrequest only.
|
||||
# proxy_pass_request_body off + Content-Length ""
|
||||
# - the subrequest must not replay the
|
||||
# original body (it could be a 50MB
|
||||
# upload); clearing Content-Length stops
|
||||
# the backend waiting for a body that is
|
||||
# not coming.
|
||||
# Cookie $http_cookie - the whole point: forward the session
|
||||
# cookie so the backend can validate it.
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
# for Vite's HMR websocket, not for the app.
|
||||
# - No HTTP->HTTPS redirect and no apex->www redirect: BOTH :80 and :443
|
||||
# serve the full site, so http://localhost just works. The two server
|
||||
# blocks are therefore near-identical copies of each other (see the
|
||||
# duplication note in DEPLOYMENT.md).
|
||||
# blocks therefore share one body, nginx_dev_common.conf.template.
|
||||
# - TLS uses the self-signed /etc/letsencrypt/live/localhost/ certificate that
|
||||
# the entrypoint generates, not a Let's Encrypt one. Browsers will warn.
|
||||
# - No HSTS or other security headers — HSTS on localhost would poison the
|
||||
@@ -26,10 +25,13 @@
|
||||
# Same envsubst allow-list as production. Every other dollar token is an
|
||||
# nginx runtime variable and must survive substitution untouched.
|
||||
#
|
||||
# For the rate-limit reasoning, the prefix-strip rewrite, the four forwarding
|
||||
# headers, the websocket upgrade block and the auth_request admin gate, see the
|
||||
# fully-annotated equivalents in nginx.conf.template — the mechanics here are
|
||||
# identical.
|
||||
# INCLUDE CHAIN
|
||||
# this file -> nginx_dev_common.conf (once per server block: the dev-only
|
||||
# /uploads/ and `/` locations) -> nginx_routes.conf (the proxy route table
|
||||
# shared with production). The prefix-strip rewrite, the four forwarding
|
||||
# headers, the websocket upgrade block and the auth_request admin gate are
|
||||
# annotated in nginx_routes.conf.template; the rate-limit reasoning is in
|
||||
# nginx.conf.template.
|
||||
# =============================================================================
|
||||
events {
|
||||
worker_connections 1024;
|
||||
@@ -46,6 +48,10 @@ http {
|
||||
|
||||
client_max_body_size 50M;
|
||||
|
||||
# These four zones are referenced by limit_req lines in the SHARED
|
||||
# nginx_routes.conf.template, so they must exist here with the same names
|
||||
# as in nginx.conf.template or nginx refuses to load the config. Rates are
|
||||
# kept equal to production so a limit that would bite there bites here too.
|
||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
|
||||
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# =============================================================================
|
||||
# nginx_dev.conf.template — SHARED BODY of the dev :80 and :443 server blocks.
|
||||
# nginx_dev_common.conf.template — SHARED BODY of the dev :80 and :443 server
|
||||
# blocks.
|
||||
#
|
||||
# WHY THIS FILE EXISTS
|
||||
# In dev the :80 and :443 server blocks are byte-for-byte identical apart
|
||||
@@ -16,26 +17,23 @@
|
||||
# the entrypoint, or it will reach nginx unsubstituted.
|
||||
#
|
||||
# WHAT BELONGS HERE
|
||||
# Everything inside a `server { ... }` block: the `set $upstream_*` vars and
|
||||
# every `location`. NOT `listen`, `server_name` or the ssl_certificate lines
|
||||
# (those differ between the two blocks), and NOT the enclosing braces — this
|
||||
# file must be brace-balanced on its own.
|
||||
# Only what dev does DIFFERENTLY from production inside a server block: the
|
||||
# /uploads/ locations without security headers, and `/` proxied to Vite.
|
||||
# Everything else — the `set $upstream_*` vars and every reverse-proxied
|
||||
# route — is in nginx_routes.conf.template, shared with production and
|
||||
# included at the bottom of this file. ADD NEW PROXIED ROUTES THERE, not
|
||||
# here.
|
||||
# NOT `listen`, `server_name` or the ssl_certificate lines (those differ
|
||||
# between the two blocks), and NOT the enclosing braces — this file must be
|
||||
# brace-balanced on its own.
|
||||
#
|
||||
# This is the DEV file only. Production uses a single :443 server block in
|
||||
# nginx.conf.template and needs no partial.
|
||||
# This is the DEV file only. Production's single :443 www server block in
|
||||
# nginx.conf.template includes nginx_routes.conf directly.
|
||||
# =============================================================================
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_hasura http://$HASURA_HOST:$HASURA_PORT;
|
||||
set $upstream_silverbullet http://$SILVERBULLET_HOST:$SILVERBULLET_PORT;
|
||||
set $upstream_silverbullet_public http://$SILVERBULLET_PUBLIC_HOST:$SILVERBULLET_PUBLIC_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
|
||||
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||
# messages are written by the backend to /backend/uploads/private/ and
|
||||
# must not be readable by the public, so this subpath is put behind the
|
||||
# same admin `auth_request` used for /hasura/ and /sb/. nginx picks
|
||||
# same admin `auth_request` used for /sb/. nginx picks
|
||||
# the LONGEST matching prefix location, so this block wins over the
|
||||
# public /uploads/ block below for /uploads/private/* regardless of
|
||||
# ordering. Same three hardening headers as the public block, because
|
||||
@@ -49,6 +47,12 @@
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
# Both /uploads/ blocks are the production ones MINUS
|
||||
# `include security_headers.conf`: that file carries HSTS, which must
|
||||
# never be sent from localhost. That one line is why they are not in
|
||||
# the shared route table (see WHAT DOES NOT in
|
||||
# nginx_routes.conf.template). Keep the rest in step with
|
||||
# nginx.conf.template.
|
||||
location /uploads/ {
|
||||
alias /uploads/;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
@@ -56,6 +60,7 @@
|
||||
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||
}
|
||||
|
||||
# The Vite dev server; Upgrade/Connection carry its HMR websocket.
|
||||
location / {
|
||||
proxy_pass http://vue:5173;
|
||||
proxy_http_version 1.1;
|
||||
@@ -64,214 +69,6 @@
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
# 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
|
||||
# internet through this proxy. Put it behind the same admin
|
||||
# `auth_request` as /hasura/ and /sb/ so an admin session cookie is
|
||||
# required before the request ever reaches icecast. Longest-prefix
|
||||
# matching means this wins over /radio/ below; listener traffic
|
||||
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||
location /radio/admin/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
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;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
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;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
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;
|
||||
}
|
||||
|
||||
location /hasura {
|
||||
return 301 /hasura/;
|
||||
}
|
||||
|
||||
location /hasura/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/hasura/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_hasura;
|
||||
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;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
# PUBLIC notes viewer (read-only SilverBullet). The deny blocks are
|
||||
# the privacy boundary: SB_SPACE_IGNORE hides files from the list but
|
||||
# NOT from a direct /.fs/ fetch, a page URL (server-rendered), or
|
||||
# /.fs/.git/. Full explanation in nginx.conf.template; keep the two in
|
||||
# step.
|
||||
location ~* ^/notes/(.*/)?(private|templates)(/|$) {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ~ ^/notes/.+/\. {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ^~ /notes/.revisions {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location /notes/ {
|
||||
proxy_pass $upstream_silverbullet_public;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location /sb {
|
||||
return 301 /sb/;
|
||||
}
|
||||
|
||||
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes.
|
||||
# Deliberately NO prefix-strip rewrite, unlike every other proxied app
|
||||
# here. SilverBullet is a PWA told its own base path via SB_URL_PREFIX=/sb,
|
||||
# and its service worker scope and asset URLs are built from that. Strip
|
||||
# the prefix and the app loads a blank page with no error in the log.
|
||||
# Upgrade/Connection are for its sync websocket.
|
||||
location /sb/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
proxy_pass $upstream_silverbullet;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
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;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
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;
|
||||
}
|
||||
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
# Every other route, shared with production. This file has no regex
|
||||
# locations of its own, so where the include sits is cosmetic.
|
||||
include /etc/nginx/nginx_routes.conf;
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
# =============================================================================
|
||||
# nginx_routes.conf.template — the PROXY ROUTE TABLE shared by production and
|
||||
# dev. Add a new proxied route HERE, once.
|
||||
#
|
||||
# WHY THIS FILE EXISTS
|
||||
# nginx.conf.template (production) and nginx_dev_common.conf.template (dev)
|
||||
# used to each carry their own copy of these ~25 locations, so every new
|
||||
# route was two edits and the copies could drift — which matters more than
|
||||
# usual here, because this table holds the admin auth gates (/sb/,
|
||||
# /radio/admin/), the /py/internal/ 404 and the /notes privacy denials. A
|
||||
# route that exists in one copy but not the other is a hole that only shows
|
||||
# up in the environment you were not testing.
|
||||
#
|
||||
# WHO INCLUDES IT
|
||||
# - nginx.conf.template, inside its :443 www server block.
|
||||
# - nginx_dev_common.conf.template, which is itself included by BOTH dev
|
||||
# server blocks — so in dev this file is pulled in twice. That is fine:
|
||||
# each inclusion lands in a different `server`, and everything below is
|
||||
# server-scoped.
|
||||
#
|
||||
# HOW IT IS RENDERED
|
||||
# nginx/entrypoint.sh runs the SAME envsubst allow-list over this file as
|
||||
# over the main templates and writes the result to
|
||||
# /etc/nginx/nginx_routes.conf, the path the `include` directives name. It
|
||||
# does so on every boot path, before the main config is chosen. A new
|
||||
# substituted variable used here must be added to ENVSUBST_VARS in the
|
||||
# entrypoint, or it reaches nginx unsubstituted.
|
||||
#
|
||||
# WHAT BELONGS HERE
|
||||
# The `set $upstream_*` variables and every reverse-proxied location that
|
||||
# behaves the same in production and dev, plus the admin-gate subrequest
|
||||
# they rely on. It must stay brace-balanced on its own (no enclosing
|
||||
# `server {`).
|
||||
#
|
||||
# WHAT DOES NOT, AND WHY
|
||||
# - add_header, in any location here. nginx's add_header inheritance is
|
||||
# all-or-nothing: a location with none of its own inherits the including
|
||||
# server block's set. Production's server block includes
|
||||
# security_headers.conf (HSTS etc.) and dev's deliberately does not, so
|
||||
# leaving these locations header-free is what lets the same text carry
|
||||
# security headers in production and none on localhost. Adding a single
|
||||
# add_header to a location below would silently drop production's
|
||||
# security headers from it.
|
||||
# - /uploads/ and /uploads/private/. They need add_header lines of their
|
||||
# own AND, in production only, security_headers.conf alongside them, so
|
||||
# for the reason above they cannot be shared. Each template has its copy;
|
||||
# keep the auth_request pair on /uploads/private/ identical in both.
|
||||
# - `location /`. Production serves the built SPA from disk, dev proxies to
|
||||
# the Vite dev server.
|
||||
# - $BACKEND_ENDPOINT/graphql. Production-only, with its own tighter
|
||||
# rate-limit zone; in dev GraphQL falls through to $BACKEND_ENDPOINT/
|
||||
# below. It lives in nginx.conf.template.
|
||||
# - Static asset caching, robots.txt, the ACME challenge and TLS: production
|
||||
# only, in nginx.conf.template.
|
||||
#
|
||||
# RATE LIMITS
|
||||
# The limit_req lines below name the zones `login`, `upload`, `api` and
|
||||
# `hotel_search`. A zone must be declared with limit_req_zone in the `http`
|
||||
# block of whichever config includes this file, or nginx refuses to load it
|
||||
# — so BOTH nginx.conf.template and nginx_dev.conf.template declare all
|
||||
# four (same rates; the reasoning is annotated in the production one). If
|
||||
# you use a new zone here, declare it in both.
|
||||
#
|
||||
# ORDER
|
||||
# Prefix locations are matched longest-first, so their order here is
|
||||
# cosmetic. REGEX locations (`~`, `~*`) are tried in file order and the
|
||||
# first match wins: keep the two /notes deny regexes ahead of the
|
||||
# /py/hotels one, and remember production's ACME regex location is declared
|
||||
# before this file is included.
|
||||
# =============================================================================
|
||||
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||
set $upstream_silverbullet http://$SILVERBULLET_HOST:$SILVERBULLET_PORT;
|
||||
set $upstream_silverbullet_public http://$SILVERBULLET_PUBLIC_HOST:$SILVERBULLET_PUBLIC_PORT;
|
||||
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||
# The job tracker's container name is fixed in docker-compose.yml, so
|
||||
# it needs no variable (and no ENVSUBST_VARS entry).
|
||||
set $upstream_jobs http://jobs:8080;
|
||||
|
||||
# ---- Backend API -----------------------------------------------------
|
||||
# Two patterns repeat through every proxied location below:
|
||||
#
|
||||
# 1. THE PREFIX-STRIP REWRITE
|
||||
# rewrite ^<PREFIX>/(.*)$ /$1 break;
|
||||
# The public URL carries a prefix (/api, /radio, /gitea, /py) but the upstream service serves its routes from /. The
|
||||
# rewrite strips the prefix and `break` stops rewrite processing so
|
||||
# the request stays in this location and goes to proxy_pass with the
|
||||
# rewritten URI. (This is why proxy_pass here has no trailing path —
|
||||
# with a variable upstream, nginx would not do the strip for us.)
|
||||
# The bare `location <PREFIX>` blocks that 301 to `<PREFIX>/` exist
|
||||
# only so a user typing /gitea without the slash lands correctly.
|
||||
#
|
||||
# 2. THE FOUR FORWARDING HEADERS
|
||||
# Host preserve the browser's hostname so the app
|
||||
# builds correct absolute URLs and cookies.
|
||||
# X-Real-IP the true client IP (the upstream otherwise
|
||||
# sees only nginx's container IP).
|
||||
# X-Forwarded-For appends the client to any existing chain.
|
||||
# X-Forwarded-Proto tells the app the ORIGINAL request was
|
||||
# https even though this hop is plain http.
|
||||
# Without it the backend would issue
|
||||
# non-Secure cookies and http:// redirects,
|
||||
# breaking auth behind TLS termination.
|
||||
#
|
||||
# Ordering matters: nginx picks the longest matching prefix location,
|
||||
# so the specific /ws, /auth/login and /messages/upload blocks (and
|
||||
# production's /graphql block in nginx.conf.template) win over the
|
||||
# catch-all <PREFIX>/ block regardless of file order.
|
||||
location $BACKEND_ENDPOINT {
|
||||
return 301 $BACKEND_ENDPOINT/;
|
||||
}
|
||||
|
||||
# WebSocket endpoint (live chat / activity feed).
|
||||
# The three lines that make an upgrade work, and why each is needed:
|
||||
# proxy_http_version 1.1 - HTTP/1.0 has no Upgrade mechanism at all.
|
||||
# Upgrade $http_upgrade - hop-by-hop headers are NOT forwarded by
|
||||
# Connection "upgrade" default, so they must be re-set by hand.
|
||||
# Note the Connection value is hardcoded rather than using the usual
|
||||
# $connection_upgrade map: this location only ever serves websockets, so
|
||||
# there is no plain-HTTP case to fall back to.
|
||||
# Deliberately NOT rate limited — a websocket is one long-lived request
|
||||
# and a limit_req here would drop reconnect storms, not abuse.
|
||||
location $BACKEND_ENDPOINT/ws {
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/auth/login {
|
||||
limit_req zone=login burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
location $BACKEND_ENDPOINT/messages/upload {
|
||||
limit_req zone=upload burst=3 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
# Catch-all for the REST API. In production GraphQL does NOT land here:
|
||||
# nginx.conf.template declares a longer $BACKEND_ENDPOINT/graphql
|
||||
# location with a tighter zone. In dev it does.
|
||||
location $BACKEND_ENDPOINT/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_backend;
|
||||
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;
|
||||
}
|
||||
|
||||
location /radio {
|
||||
return 301 /radio/;
|
||||
}
|
||||
|
||||
# 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
|
||||
# internet through this proxy. Put it behind the same admin
|
||||
# `auth_request` as /sb/ so an admin session cookie is
|
||||
# required before the request ever reaches icecast. Longest-prefix
|
||||
# matching means this wins over /radio/ below; listener traffic
|
||||
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||
location /radio/admin/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
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;
|
||||
}
|
||||
|
||||
location /radio/ {
|
||||
rewrite ^/radio/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_icecast;
|
||||
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;
|
||||
}
|
||||
|
||||
location /gitea {
|
||||
return 301 /gitea/;
|
||||
}
|
||||
|
||||
location /gitea/ {
|
||||
rewrite ^/gitea/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_gitea;
|
||||
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;
|
||||
}
|
||||
|
||||
location /notes {
|
||||
return 301 /notes/;
|
||||
}
|
||||
|
||||
# PUBLIC notes viewer: a second, read-only SilverBullet over the same
|
||||
# vault the /sb/ editor edits. No auth_request — this is the public
|
||||
# site. See the silverbullet-public service in docker-compose.yml.
|
||||
#
|
||||
# THE DENY BLOCKS BELOW ARE THE PRIVACY BOUNDARY, not decoration.
|
||||
# SB_SPACE_IGNORE only hides paths from the file LIST. Everything else
|
||||
# happily 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 from the list, so the block must too.
|
||||
#
|
||||
# 1. private/ or templates/ as any path segment, page URL or /.fs/.
|
||||
# ~* 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.
|
||||
# nginx matches against the normalised URI (percent-decoded, `..`
|
||||
# resolved, slashes merged), so %2F, // or ../ tricks cannot slip past.
|
||||
# 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.
|
||||
location ~* ^/notes/(.*/)?(private|templates)(/|$) {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location ~ ^/notes/.+/\. {
|
||||
return 404;
|
||||
}
|
||||
|
||||
# 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. ^~ so no regex
|
||||
# location can take precedence.
|
||||
location ^~ /notes/.revisions {
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Same as /sb/: deliberately NO prefix-strip rewrite. The app is told
|
||||
# its base path via SB_URL_PREFIX=/notes and builds its service worker
|
||||
# scope and asset URLs from it; strip the prefix and it loads blank.
|
||||
# Upgrade/Connection are for its live-update event stream.
|
||||
location /notes/ {
|
||||
proxy_pass $upstream_silverbullet_public;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location /sb {
|
||||
return 301 /sb/;
|
||||
}
|
||||
|
||||
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes.
|
||||
# Deliberately NO prefix-strip rewrite, unlike every other proxied app
|
||||
# here. SilverBullet is a PWA told its own base path via SB_URL_PREFIX=/sb,
|
||||
# and its service worker scope and asset URLs are built from that. Strip
|
||||
# the prefix and the app loads a blank page with no error in the log.
|
||||
# Upgrade/Connection are for its sync websocket.
|
||||
location /sb/ {
|
||||
auth_request /internal/auth/admin-validate;
|
||||
error_page 401 403 = @auth_denied;
|
||||
proxy_pass $upstream_silverbullet;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
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;
|
||||
}
|
||||
|
||||
location /py {
|
||||
return 301 /py/;
|
||||
}
|
||||
|
||||
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||
location ~ ^/py/hotels/(search|scan) {
|
||||
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||
limit_req zone=hotel_search burst=2 nodelay;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
gzip off;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
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;
|
||||
}
|
||||
|
||||
# /py/internal/: routes the Go backend calls directly over app-network
|
||||
# (the rowing photo reader and the job posting reader, which spend a
|
||||
# paid Claude call and have no auth of their own). Never proxied. ^~ so no regex location can claim
|
||||
# the path first. The Python side also refuses anything carrying the
|
||||
# X-Real-IP / X-Forwarded-For headers set below, as a second layer.
|
||||
location ^~ /py/internal/ {
|
||||
return 404;
|
||||
}
|
||||
|
||||
location /py/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
rewrite ^/py/(.*)$ /$1 break;
|
||||
proxy_pass $upstream_python;
|
||||
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;
|
||||
}
|
||||
|
||||
# ---- Job tracker (/jobs/) ----
|
||||
# Its own container (the adamf/job-tracker repo), which serves its SPA
|
||||
# and its API from the same prefix. The prefix is NOT stripped: the
|
||||
# app is built to live at /jobs/. There is no auth_request here: the
|
||||
# SPA's files are public, and every API route that is not checks the
|
||||
# session itself, by asking the backend's validate-admin with the
|
||||
# visitor's cookies. ^~ so no regex location can claim a /jobs/ path.
|
||||
location = /jobs {
|
||||
return 301 /jobs/;
|
||||
}
|
||||
|
||||
location ^~ /jobs/ {
|
||||
limit_req zone=api burst=20 nodelay;
|
||||
# "Sync now" on the Settings page runs a whole email sync before
|
||||
# answering.
|
||||
proxy_read_timeout 300s;
|
||||
proxy_pass $upstream_jobs;
|
||||
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;
|
||||
}
|
||||
|
||||
# Where the 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.
|
||||
location = /cv/jobs {
|
||||
return 301 /jobs/;
|
||||
}
|
||||
location = /cv/leads {
|
||||
return 301 /jobs/leads;
|
||||
}
|
||||
location = /job-capture.user.js {
|
||||
return 301 /jobs/job-capture.user.js;
|
||||
}
|
||||
|
||||
# ---- Admin gate (/sb/, /radio/admin/, /uploads/private/) ----
|
||||
# (/uploads/private/ is declared in the including template, not here;
|
||||
# it points at the two locations below by name.)
|
||||
# `auth_request` makes nginx fire a subrequest here before serving the
|
||||
# real one; a 2xx lets it through, 401/403 triggers error_page ->
|
||||
# @auth_denied -> redirect to the SPA login. This puts the Go backend's
|
||||
# session cookie in front of services that have no idea it exists.
|
||||
# internal; - unreachable from outside, subrequest only.
|
||||
# proxy_pass_request_body off + Content-Length ""
|
||||
# - the subrequest must not replay the
|
||||
# original body (it could be a 50MB
|
||||
# upload); clearing Content-Length stops
|
||||
# the backend waiting for a body that is
|
||||
# not coming.
|
||||
# Cookie $http_cookie - the whole point: forward the session
|
||||
# cookie so the backend can validate it.
|
||||
location = /internal/auth/admin-validate {
|
||||
internal;
|
||||
rewrite ^ /auth/validate-admin break;
|
||||
proxy_pass $upstream_backend;
|
||||
proxy_pass_request_body off;
|
||||
proxy_set_header Content-Length "";
|
||||
proxy_set_header Cookie $http_cookie;
|
||||
}
|
||||
|
||||
location @auth_denied {
|
||||
return 302 /admin/login?redirect=$request_uri;
|
||||
}
|
||||
Generated
-1308
File diff suppressed because it is too large
Load Diff
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"@vueuse/core": "^14.2.0",
|
||||
"vite": "^7.3.1"
|
||||
}
|
||||
}
|
||||
+115
-5
@@ -1,7 +1,10 @@
|
||||
# Python API service
|
||||
|
||||
A small FastAPI app (`app/main.py`) served by uvicorn on port 8000 inside the
|
||||
`python` container. Most of it is one feature: **cheap Travelodge finder** —
|
||||
`python` container. It also hosts the site's one Claude call, as an internal
|
||||
route: the **rowing display reader** (see below). (The job tracker at `/jobs/`
|
||||
is a separate app, `adamf/job-tracker`, with its own Claude calls.) Most of it
|
||||
is one feature: **cheap Travelodge finder** —
|
||||
given a London location and dates it pulls live room prices from Travelodge and
|
||||
adds the cost of getting there from a chosen station on TfL, so you can rank
|
||||
hotels by what the night *actually* costs, not just the room.
|
||||
@@ -12,9 +15,13 @@ hotels by what the night *actually* costs, not just the room.
|
||||
| --- | --- |
|
||||
| `app/main.py` | HTTP skin: request models/validation, response cache, one-at-a-time guard, NDJSON framing, route handlers |
|
||||
| `app/travelodge.py` | All the real work: upstream calls, caching, rate limiting, fare maths, the two search generators |
|
||||
| `app/rowing.py` | The Claude call that reads time and distance off a photo of a rowing machine display |
|
||||
| `app/claude.py` | What a Claude caller needs: the lazily built Anthropic client, the error types, and `ask_json` — the call itself |
|
||||
| `app/__init__.py` | Empty; makes `app` a package so `app.main:app` resolves |
|
||||
| `tests/` | pytest suite; needs `requirements-dev.txt` (see *Tests*) |
|
||||
|
||||
`travelodge.py` never imports FastAPI and can be driven from a plain script.
|
||||
`travelodge.py`, `rowing.py` and `claude.py` never import FastAPI and can be
|
||||
driven from a plain script.
|
||||
|
||||
## Endpoints
|
||||
|
||||
@@ -30,6 +37,7 @@ Paths below are as the service sees them; from a browser prefix everything with
|
||||
| POST | `/hotels/search` | Blocking search; returns once every shortlisted hotel is priced |
|
||||
| POST | `/hotels/search/stream` | Same search as NDJSON progress lines |
|
||||
| POST | `/hotels/scan/stream` | Cheapest night across a date range, NDJSON |
|
||||
| POST | `/internal/rowing/read` | **Internal.** Read a rowing display photo with Claude |
|
||||
|
||||
Interactive schema: `/py/docs` (Swagger UI), `/py/openapi.json`.
|
||||
|
||||
@@ -59,6 +67,88 @@ already running and 502 on upstream failure.
|
||||
Only **one** live search or scan runs process-wide at a time (the TfL budget
|
||||
can't be shared), and identical requests are cached for 10 minutes.
|
||||
|
||||
### Internal routes
|
||||
|
||||
Routes under `/internal/` (today only the rowing reader) are the only ones in
|
||||
this service that are **not public**. Each spends a paid Claude call and has no
|
||||
auth of its own — the admin check happens in the Go backend, which calls the container
|
||||
directly (`http://python:8000/...`). Two things keep them internal: nginx
|
||||
answers `/py/internal/` with a 404, and the route itself 404s any request
|
||||
carrying the `X-Real-IP` / `X-Forwarded-For` headers nginx adds to everything
|
||||
it proxies (the Go backend sends neither).
|
||||
|
||||
Their plumbing is in two places, shared by any route added later:
|
||||
|
||||
- **`claude.ask_json`** (`app/claude.py`) is the whole Claude call: send one
|
||||
prompt that asks for a bare JSON object, take the first text block, strip a
|
||||
markdown fence, validate into a pydantic model. The caller supplies the model
|
||||
class, the messages, an optional system prompt and three fixed error strings
|
||||
(`failed`, `empty`, `unparseable`). It raises `NotConfigured` when
|
||||
`CLAUDE_API_KEY` is unset and `ReadError` with one of those three strings
|
||||
otherwise. The API's own error text and the model's reply go to the log,
|
||||
never into the message, because the Go backend relays the message verbatim.
|
||||
- **`_internal_claude_route`** (`app/main.py`) is `app.post` plus the
|
||||
internal-only guard and the 502/503 entries in the docs. An exception handler
|
||||
beside it turns `ReadError` into a 502 and `NotConfigured` into a 503, both
|
||||
with a string `detail`. The guard runs as a dependency, so a request from
|
||||
outside is a 404 before its body is validated.
|
||||
|
||||
Every route uses one model, `MODEL` in `claude.py`: the `CLAUDE_MODEL` variable,
|
||||
or `claude-sonnet-5-5` when it is blank. It is chosen on the admin panel's
|
||||
Environment tab from `claude-haiku-4-5`, `claude-sonnet-5-5` and
|
||||
`claude-opus-5-5`, and saving it there restarts this service. The request is
|
||||
shaped per model by `_model_options`: a model that thinks gets
|
||||
`output_config.effort: "low"` and 4,000 tokens of headroom on top of the
|
||||
caller's `max_tokens`, because thinking is billed against it; Haiku 4.5 gets
|
||||
neither, since it rejects the effort setting. A refusal (`stop_reason:
|
||||
"refusal"`) is reported as the route's `failed` message. The Go callers set
|
||||
their own timeout above this side's (30s per attempt, two SDK retries), so
|
||||
they see this service's error rather than their own.
|
||||
|
||||
#### Adding another Claude-backed internal route
|
||||
|
||||
1. **A module** `app/<thing>.py`, shaped like `rowing.py`: the prompt, a
|
||||
pydantic model whose field names are the keys the prompt asks for (give
|
||||
every field a default — the model leaves keys out), and one function that
|
||||
returns `ask_json(Model, max_tokens=..., system=..., messages=[...],
|
||||
failed="...", empty="...", unparseable="...", get_client=_client)`. Import
|
||||
the client as `from .claude import client as _client`; that name is the
|
||||
seam tests replace. No FastAPI imports.
|
||||
2. **A route** in `main.py`: a request model with length bounds, then
|
||||
|
||||
```python
|
||||
@_internal_claude_route("/internal/<thing>/<verb>", response_model=thing.Model, summary="...", description="...")
|
||||
def thing_verb(req: ThingRequest) -> thing.Model:
|
||||
return thing.do_it(req.field)
|
||||
```
|
||||
|
||||
A plain `def`, so the blocking call runs in the threadpool. No `try`, no
|
||||
guard call — the wrapper supplies both. Add the route to the endpoint list
|
||||
in `main.py`'s docstring and bump the FastAPI `version`.
|
||||
3. **Tests** `tests/test_<thing>.py`, copied from `test_rowing.py`: fake the
|
||||
client with `monkeypatch.setattr(thing, "_client", ...)`.
|
||||
4. **Docs**: the endpoint table and a section here. Nothing to do in nginx —
|
||||
it already 404s everything under `/py/internal/`.
|
||||
|
||||
If third-party text goes into the prompt (a web page, an email), say in the
|
||||
system prompt that it is data and not instructions (the job tracker's
|
||||
prompts, in its own repo, are examples) — and keep the output to fields that are stored or
|
||||
shown, never acted on.
|
||||
|
||||
### Rowing display reader (internal)
|
||||
|
||||
`POST /internal/rowing/read` takes `{"media_type": "image/jpeg", "data":
|
||||
"<base64>"}` and returns `{"timeMinutes", "timeSeconds", "distance"}` as read
|
||||
by Claude. It is the image half of the Go backend's
|
||||
admin-only `POST /api/rowing`: the Go handler does the admin check, the EXIF
|
||||
date, the duplicate check, the sanity bounds and the insert, and calls this
|
||||
only once it has decided the paid call is worth making. Nothing here judges
|
||||
whether the numbers are plausible.
|
||||
|
||||
Errors: 502 with a fixed `detail` (`failed to process image`, `empty response
|
||||
from image processor`, `failed to parse image data`) that the Go handler
|
||||
relays to the admin; 503 if `CLAUDE_API_KEY` is unset.
|
||||
|
||||
## Behind nginx
|
||||
|
||||
`nginx/nginx.conf.template` proxies `/py/` to this container and **strips the
|
||||
@@ -73,8 +163,8 @@ braces version of the same thing. The internal deadlines in `travelodge.py`
|
||||
(200s for a search, 240s for a scan) exist to finish *before* that 300s cut, and
|
||||
return partial results with `summary.truncated = true` instead of dying.
|
||||
|
||||
Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, and the
|
||||
optional `TFL_APP_KEY` (see below). Dev mode mounts `python/app` and runs
|
||||
Env vars (from `docker-compose.yml`): `PYTHON_PORT`, `ROOT_PATH`, the optional
|
||||
`TFL_APP_KEY` (see below), and `CLAUDE_API_KEY` and `CLAUDE_MODEL` for the internal Claude route. Dev mode mounts `python/app` and runs
|
||||
uvicorn with `--reload`.
|
||||
|
||||
## Running locally
|
||||
@@ -96,7 +186,27 @@ uvicorn app.main:app --reload --port 8000
|
||||
# http://localhost:8000/docs (no /py prefix when run directly)
|
||||
```
|
||||
|
||||
Dependencies are `fastapi`, `uvicorn[standard]` and `requests` — nothing else.
|
||||
Runtime dependencies are `fastapi`, `uvicorn[standard]`, `requests` and
|
||||
`anthropic` — nothing else. `requirements.txt` is all the Docker image
|
||||
installs.
|
||||
|
||||
## Tests
|
||||
|
||||
`requirements-dev.txt` is `requirements.txt` plus what the suite needs:
|
||||
`pytest`, and `httpx`, which FastAPI's `TestClient` will not import without.
|
||||
|
||||
```
|
||||
cd python
|
||||
python3 -m venv .venv && . .venv/bin/activate
|
||||
pip install -r requirements-dev.txt
|
||||
python -m pytest tests -q
|
||||
```
|
||||
|
||||
Nothing in the suite touches the network. The Claude tests replace the
|
||||
Anthropic client with a fake (`monkeypatch.setattr(<module>, "_client", ...)`),
|
||||
so they cover the request that is built, how the reply is parsed, the status
|
||||
code each failure maps to and the internal-only guard — not what the model
|
||||
actually answers. `test_claude.py` covers `ask_json` on its own.
|
||||
|
||||
## How the pricing works
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""The Anthropic client and the one call every Claude caller here makes.
|
||||
|
||||
`rowing` (a photo in, three numbers out) is a call of a general shape: one
|
||||
prompt asking for bare JSON, one reply to parse. That whole sequence is
|
||||
`ask_json` below, so a caller is a prompt, a pydantic model and three error
|
||||
strings, and another caller would get the same handling around the call. Also
|
||||
here: the lazily built client and the two exception types `main` maps to 502
|
||||
and 503.
|
||||
|
||||
Like the modules that use it, this never imports FastAPI.
|
||||
"""
|
||||
|
||||
import functools
|
||||
import logging
|
||||
import os
|
||||
from typing import Callable, Optional, TypeVar
|
||||
|
||||
import anthropic
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
T = TypeVar("T", bound=BaseModel)
|
||||
|
||||
# Which model every call uses. CLAUDE_MODEL is set from the admin panel's
|
||||
# Environment tab (it is in backend/services/env_registry.json, whose `options`
|
||||
# list is what the panel offers); changing it there recreates this container,
|
||||
# which is why reading it once at import is enough. Blank means the default.
|
||||
#
|
||||
# The registry's options are the ids this module has been written for. Another
|
||||
# id is passed through as it is, treated as a model that thinks (see below);
|
||||
# if the API does not know it, every call fails with its `failed` message and
|
||||
# the reason is in this service's log.
|
||||
DEFAULT_MODEL = "claude-sonnet-5-5"
|
||||
MODEL = os.environ.get("CLAUDE_MODEL", "").strip() or DEFAULT_MODEL
|
||||
|
||||
# Models that take no `output_config.effort` and do not think unless asked to.
|
||||
# Everything newer thinks by default, and that changes two things in the
|
||||
# request - see _model_options.
|
||||
_NO_EFFORT_PREFIXES = ("claude-haiku-4-5",)
|
||||
|
||||
# Thinking is billed against `max_tokens` like the reply is, and the callers'
|
||||
# ceilings are sized for the reply alone (a few hundred tokens of JSON). On a
|
||||
# model that thinks, this is added on top so that a posting worth a moment's
|
||||
# thought cannot use the whole allowance and leave no room for the answer.
|
||||
THINKING_HEADROOM = 4000
|
||||
|
||||
# Every call here is extraction or classification: read something, return a
|
||||
# small JSON object. "low" is the level meant for that - the model skips
|
||||
# thinking on most simple requests - and it is set explicitly because the
|
||||
# default differs between models.
|
||||
EFFORT = "low"
|
||||
|
||||
# Seconds per attempt. The SDK retries twice on top (429/5xx/connection), so
|
||||
# the worst case is roughly three of these plus backoff; the Go callers' own
|
||||
# timeout is set above that so they see this side's error, not their own.
|
||||
TIMEOUT_S = 30.0
|
||||
|
||||
|
||||
class ReadError(Exception):
|
||||
"""Claude could not produce the answer; the message is safe to show the admin."""
|
||||
|
||||
|
||||
class NotConfigured(ReadError):
|
||||
"""CLAUDE_API_KEY is not set in this container."""
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=1)
|
||||
def client() -> anthropic.Anthropic:
|
||||
"""Build the Anthropic client on first use.
|
||||
|
||||
Lazy so that a missing key only breaks the Claude features: the hotel
|
||||
finder must still boot without it. The key is passed explicitly because the
|
||||
stack's variable is CLAUDE_API_KEY, not the ANTHROPIC_API_KEY the SDK looks
|
||||
for.
|
||||
"""
|
||||
key = os.environ.get("CLAUDE_API_KEY", "")
|
||||
if not key:
|
||||
raise NotConfigured("CLAUDE_API_KEY is not set")
|
||||
return anthropic.Anthropic(api_key=key, timeout=TIMEOUT_S)
|
||||
|
||||
|
||||
def strip_markdown_fence(raw: str) -> str:
|
||||
"""Remove a surrounding markdown code fence from a model's response.
|
||||
|
||||
The prompts ask for bare JSON and the model fences it anyway often enough
|
||||
to matter. "```json" is tried before a plain "```", and unfenced input
|
||||
comes back unchanged apart from surrounding whitespace. This is the only
|
||||
copy: the Go backend had its own while it still called Claude itself, and
|
||||
every Claude call now goes through this service.
|
||||
"""
|
||||
raw = raw.strip()
|
||||
raw = raw.removeprefix("```json")
|
||||
raw = raw.removeprefix("```")
|
||||
raw = raw.removesuffix("```")
|
||||
return raw.strip()
|
||||
|
||||
|
||||
def _model_options(model: str, max_tokens: int) -> dict:
|
||||
"""The parts of the request that depend on which model is configured.
|
||||
|
||||
`max_tokens` is the caller's ceiling on the reply. A model that thinks
|
||||
gets THINKING_HEADROOM on top and an explicit effort level; Haiku 4.5
|
||||
gets neither, because it rejects `output_config.effort` and does not think
|
||||
unless a budget is requested, which nothing here does.
|
||||
"""
|
||||
if model.startswith(_NO_EFFORT_PREFIXES):
|
||||
return {"max_tokens": max_tokens}
|
||||
return {"max_tokens": max_tokens + THINKING_HEADROOM, "output_config": {"effort": EFFORT}}
|
||||
|
||||
|
||||
def ask_json(
|
||||
model_cls: type[T],
|
||||
*,
|
||||
max_tokens: int,
|
||||
messages: list,
|
||||
system: Optional[str] = None,
|
||||
failed: str,
|
||||
empty: str,
|
||||
unparseable: str,
|
||||
get_client: Optional[Callable[[], anthropic.Anthropic]] = None,
|
||||
) -> T:
|
||||
"""Send one prompt that asks for a bare JSON object and validate the reply.
|
||||
|
||||
The three message arguments are what the caller's user ends up reading:
|
||||
the Go backend relays a ReadError's text verbatim, so each caller words
|
||||
its own and nothing from the API or the model's reply leaks into it. The
|
||||
detail goes to the log instead.
|
||||
|
||||
Args:
|
||||
model_cls: the pydantic model the reply must validate as; its field
|
||||
names are the keys the caller's prompt asks for.
|
||||
max_tokens: ceiling on the reply; see _model_options for what is
|
||||
actually sent.
|
||||
messages: the `messages` list, passed to the API as is.
|
||||
system: the system prompt, left out of the request when None.
|
||||
failed: ReadError text when the API call itself failed.
|
||||
empty: ReadError text when the reply has no text block.
|
||||
unparseable: ReadError text when the reply is not JSON, or is JSON
|
||||
that `model_cls` rejects.
|
||||
get_client: returns the Anthropic client. Callers pass their own
|
||||
module-level `_client` so that a test can replace the client for
|
||||
one module; resolved here, per call, when not given.
|
||||
|
||||
Raises:
|
||||
NotConfigured: no API key.
|
||||
ReadError: with one of the three messages above.
|
||||
"""
|
||||
request = {"model": MODEL, "messages": messages, **_model_options(MODEL, max_tokens)}
|
||||
if system is not None:
|
||||
request["system"] = system
|
||||
|
||||
# Outside the try: NotConfigured is not an API failure and must reach
|
||||
# `main` as itself, to become the 503.
|
||||
api = (get_client or client)()
|
||||
try:
|
||||
message = api.messages.create(**request)
|
||||
except anthropic.APIStatusError as e:
|
||||
log.warning("Claude API error %s: %s", e.status_code, e.message)
|
||||
raise ReadError(failed) from e
|
||||
except anthropic.APIConnectionError as e:
|
||||
log.warning("Claude API unreachable: %s", e)
|
||||
raise ReadError(failed) from e
|
||||
|
||||
# A refusal is an ordinary 200 whose content is not the answer. Say so in
|
||||
# the log rather than letting it surface as an "empty" or "unparseable"
|
||||
# reply, which would point at the prompt instead of at the classifier.
|
||||
if getattr(message, "stop_reason", None) == "refusal":
|
||||
log.warning("Claude declined the request: %s", getattr(message, "stop_details", None))
|
||||
raise ReadError(failed)
|
||||
|
||||
# By type, not position: on a model that thinks, the first block can be a
|
||||
# (possibly empty) thinking block.
|
||||
text = next((block.text for block in message.content if block.type == "text"), None)
|
||||
if text is None:
|
||||
if getattr(message, "stop_reason", None) == "max_tokens":
|
||||
log.warning("Claude ran out of tokens before answering (max_tokens=%s)", request["max_tokens"])
|
||||
raise ReadError(empty)
|
||||
|
||||
try:
|
||||
return model_cls.model_validate_json(strip_markdown_fence(text))
|
||||
except ValidationError as e:
|
||||
log.warning("unparseable model output %r: %s", text, e)
|
||||
raise ReadError(unparseable) from e
|
||||
+115
-6
@@ -13,10 +13,15 @@ Endpoints
|
||||
POST /hotels/search blocking cheapest-Travelodge search
|
||||
POST /hotels/search/stream same search, streamed as NDJSON
|
||||
POST /hotels/scan/stream cheapest-night-in-a-range scan, NDJSON
|
||||
POST /internal/rowing/read read a rowing display photo with Claude
|
||||
(Go backend only - not reachable through nginx)
|
||||
|
||||
All the hotel work lives in `travelodge`; this module is the HTTP skin around
|
||||
it - request validation, a response cache, the one-search-at-a-time guard, and
|
||||
the NDJSON framing. Consumed by vue/src/views/hotels/ (SingleStayPanel.vue,
|
||||
the NDJSON framing. The rowing reader (`rowing`) is the one route here that
|
||||
is not public: see the "Internal" sections at the bottom, which open with the
|
||||
wrapper it is registered through. The hotel routes are consumed by
|
||||
vue/src/views/hotels/ (SingleStayPanel.vue,
|
||||
CheapestNightPanel.vue, useHotelForm.js), which fetch these paths with the /py
|
||||
prefix. Field names in the models below are part of that contract.
|
||||
"""
|
||||
@@ -25,18 +30,18 @@ import json
|
||||
import re
|
||||
import threading
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
from typing import Literal, Optional
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
from fastapi import Depends, FastAPI, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
from . import travelodge
|
||||
from . import claude, rowing, travelodge
|
||||
|
||||
app = FastAPI(
|
||||
title="Python API",
|
||||
version="0.3.0",
|
||||
version="0.6.0",
|
||||
docs_url="/docs",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
@@ -640,3 +645,107 @@ def hotel_scan_stream(req: HotelScanRequest) -> StreamingResponse:
|
||||
as a final "error" line.
|
||||
"""
|
||||
return _ndjson(_scan_events(req))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Internal: the routes the Go backend calls
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _internal_only(request: Request) -> None:
|
||||
"""Refuse a request that arrived through nginx.
|
||||
|
||||
Every other route in this service is public, but the internal ones spend
|
||||
a paid Claude call per request and have no auth of their own - the admin
|
||||
or token check happens in the Go backend, which calls this container
|
||||
directly over app-network. Two layers keep the outside world off it,
|
||||
because either alone is one config edit away from being lost:
|
||||
|
||||
1. nginx answers /py/internal/ with a 404 (both templates).
|
||||
2. nginx stamps X-Real-IP and X-Forwarded-For on everything it proxies
|
||||
here, and a client cannot make it omit them; the Go backend sends
|
||||
neither. So their presence means the request came from outside.
|
||||
|
||||
404 rather than 403, so the route is indistinguishable from one that does
|
||||
not exist.
|
||||
"""
|
||||
if "x-real-ip" in request.headers or "x-forwarded-for" in request.headers:
|
||||
raise HTTPException(status_code=404, detail="Not Found")
|
||||
|
||||
|
||||
def _internal_claude_route(path: str, **kwargs):
|
||||
"""`app.post` for a route that makes a Claude call on the Go backend's behalf.
|
||||
|
||||
Adds the two things every such route needs, so a new one cannot forget
|
||||
either: the `_internal_only` guard, and the 502/503 entries in the docs.
|
||||
The handler itself then only calls its module and returns the result - the
|
||||
errors it can raise are turned into those responses by `_claude_failed`
|
||||
below.
|
||||
|
||||
The guard is a dependency rather than a call in the handler because
|
||||
dependencies are resolved before the body is validated: a request from
|
||||
outside gets the 404 whatever it posted, instead of a 422 that confirms
|
||||
the route exists and describes its fields.
|
||||
"""
|
||||
return app.post(
|
||||
path,
|
||||
dependencies=[Depends(_internal_only)],
|
||||
responses={
|
||||
502: {"description": "Claude failed, or its reply was not the expected JSON"},
|
||||
503: {"description": "CLAUDE_API_KEY is not set"},
|
||||
},
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(claude.ReadError)
|
||||
def _claude_failed(request: Request, exc: claude.ReadError) -> JSONResponse:
|
||||
"""Turn a Claude module's failure into the response the Go backend expects.
|
||||
|
||||
503 when the API key is missing (NotConfigured, a ReadError subclass, so
|
||||
one handler sees both), 502 for everything else. The body is the same
|
||||
`{"detail": ...}` an HTTPException produces, and the detail is one of the
|
||||
module's fixed messages - the Go handlers pass it on to their own caller
|
||||
verbatim, which is why nothing from the API or the model's reply is ever
|
||||
put in it.
|
||||
"""
|
||||
status = 503 if isinstance(exc, claude.NotConfigured) else 502
|
||||
return JSONResponse(status_code=status, content={"detail": str(exc)})
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Internal: rowing display reader
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 10MB of image (the Go handler's upload cap) once base64-encoded, rounded up.
|
||||
MAX_IMAGE_B64_CHARS = 14_000_000
|
||||
|
||||
|
||||
class RowingReadRequest(BaseModel):
|
||||
"""An image for Claude to read, as the Go backend sends it."""
|
||||
|
||||
# The types the Anthropic API accepts for an image block. The Go handler
|
||||
# checks the same list first so the admin gets its friendlier 400.
|
||||
media_type: Literal["image/jpeg", "image/png", "image/gif", "image/webp"]
|
||||
data: str = Field(..., min_length=1, max_length=MAX_IMAGE_B64_CHARS, description="Base64 image bytes")
|
||||
|
||||
|
||||
@_internal_claude_route(
|
||||
"/internal/rowing/read",
|
||||
response_model=rowing.RowingReading,
|
||||
summary="Read time and distance off a rowing machine display",
|
||||
description=(
|
||||
"Internal to the Go backend's admin-only `POST /api/rowing`; not reachable through nginx. "
|
||||
"Sends the image to Claude and returns the three numbers it read. No plausibility checking "
|
||||
"happens here - the caller owns the sanity bounds."
|
||||
),
|
||||
)
|
||||
def rowing_read(req: RowingReadRequest) -> rowing.RowingReading:
|
||||
"""Read a rowing display photo.
|
||||
|
||||
A plain `def`, so FastAPI runs it in the threadpool and the blocking Claude
|
||||
call does not stall the event loop the hotel streams are served from.
|
||||
|
||||
Responds 404 (came through nginx), 503 (no API key) or 502 (Claude failed
|
||||
or returned something unparseable) by way of `_internal_claude_route`. The
|
||||
502 detail is one of rowing.read_display's fixed messages, which the Go
|
||||
handler passes on to the admin verbatim.
|
||||
"""
|
||||
return rowing.read_display(req.media_type, req.data)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Read a rowing machine display from a photo with Claude.
|
||||
|
||||
This is the image half of the Go backend's admin-only POST /rowing. The Go
|
||||
handler keeps everything that needs the database or the session cookie - the
|
||||
admin gate, the EXIF date, the duplicate check, the sanity bounds, the insert -
|
||||
and hands the image here only once it has decided the Claude call is worth
|
||||
paying for. This module just turns pixels into three numbers.
|
||||
|
||||
Like `travelodge`, it never imports FastAPI; `main` is the HTTP skin.
|
||||
"""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# Re-exported under the names this module has always had: the tests reach the
|
||||
# exceptions and the fence stripping through `rowing`. `_client` is the seam
|
||||
# they replace to fake the API, which is why it is handed to ask_json below
|
||||
# rather than left to its default.
|
||||
from .claude import MODEL, NotConfigured, ReadError, ask_json, strip_markdown_fence
|
||||
from .claude import client as _client
|
||||
|
||||
__all__ = ["MODEL", "NotConfigured", "ReadError", "RowingReading", "read_display", "strip_markdown_fence"]
|
||||
|
||||
# The answer is a three-key JSON object, so this is a ceiling, not a target.
|
||||
MAX_TOKENS = 256
|
||||
|
||||
# The keys named here are the JSON contract: RowingReading's field names below
|
||||
# and ExtractedRowingData in backend/handlers/handle_rowing.go must match them.
|
||||
PROMPT = """Look at this rowing machine display. Extract the total elapsed time and total distance.
|
||||
|
||||
Return ONLY a JSON object with these exact keys and numeric values:
|
||||
- "timeMinutes": total minutes (e.g. 2:30 = 2)
|
||||
- "timeSeconds": total seconds (e.g. 2:30 = 30)
|
||||
- "distance": distance in meters as a number (e.g. 5000)
|
||||
|
||||
No text, no markdown, no explanation. Just the JSON object."""
|
||||
|
||||
|
||||
class RowingReading(BaseModel):
|
||||
"""What Claude read off the display.
|
||||
|
||||
camelCase on purpose: these are the keys the prompt asks for and the Go
|
||||
handler unmarshals. A key the model left out defaults to 0, which the Go
|
||||
side's sanity bounds then reject - the same outcome as when Go parsed the
|
||||
model's output itself.
|
||||
"""
|
||||
|
||||
timeMinutes: int = Field(0, ge=0)
|
||||
timeSeconds: int = Field(0, ge=0)
|
||||
distance: int = Field(0, ge=0)
|
||||
|
||||
|
||||
def read_display(media_type: str, data: str) -> RowingReading:
|
||||
"""Ask Claude for the elapsed time and distance shown in an image.
|
||||
|
||||
Args:
|
||||
media_type: one of the image types the Anthropic API accepts; the
|
||||
caller is responsible for the allow-list.
|
||||
data: the image, base64-encoded (no data: prefix).
|
||||
|
||||
Raises:
|
||||
NotConfigured: no API key.
|
||||
ReadError: the API call failed, or the reply was empty or not the JSON
|
||||
object that was asked for.
|
||||
"""
|
||||
return ask_json(
|
||||
RowingReading,
|
||||
max_tokens=MAX_TOKENS,
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "image",
|
||||
"source": {"type": "base64", "media_type": media_type, "data": data},
|
||||
},
|
||||
{"type": "text", "text": PROMPT},
|
||||
],
|
||||
}
|
||||
],
|
||||
failed="failed to process image",
|
||||
empty="empty response from image processor",
|
||||
unparseable="failed to parse image data",
|
||||
get_client=_client,
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
# What the test suite (python/tests) needs on top of the runtime dependencies.
|
||||
# Kept out of requirements.txt so the image stays slim: the Dockerfile installs
|
||||
# only that file. Locally:
|
||||
#
|
||||
# pip install -r requirements-dev.txt
|
||||
# python -m pytest tests -q
|
||||
-r requirements.txt
|
||||
|
||||
pytest==9.0.3
|
||||
# fastapi.testclient.TestClient is built on httpx and refuses to import
|
||||
# without it. Nothing at runtime pulls it in: the Anthropic SDK brings httpx2,
|
||||
# a different package, which is what the tests import for request objects.
|
||||
httpx==0.28.1
|
||||
@@ -1,8 +1,7 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
requests==2.32.3
|
||||
anthropic==1.12.1
|
||||
|
||||
# Dev only, deliberately commented out so the image stays slim: the test suite
|
||||
# (python/tests) needs pytest. Install it with `pip install pytest` locally and
|
||||
# run `python -m pytest` from this directory.
|
||||
# pytest==9.0.3
|
||||
# Runtime only - this is all the Docker image installs. What the test suite
|
||||
# (python/tests) needs on top lives in requirements-dev.txt.
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Tests for `ask_json`, the Claude call every caller goes through.
|
||||
|
||||
test_rowing covers its own prompt,
|
||||
model and messages through this function; what is pinned here is the function's
|
||||
own contract - what it sends, which failure produces which of the caller's
|
||||
three messages, and where it gets its client from.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import anthropic
|
||||
import httpx2 as httpx
|
||||
import pytest
|
||||
from pydantic import BaseModel
|
||||
|
||||
from app import claude
|
||||
|
||||
REQUEST = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
|
||||
MESSAGES = [{"role": "user", "content": "how many?"}]
|
||||
ERRORS = {"failed": "call failed", "empty": "nothing came back", "unparseable": "could not parse"}
|
||||
|
||||
|
||||
class Count(BaseModel):
|
||||
n: int = 0
|
||||
|
||||
|
||||
def text_reply(text):
|
||||
return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)])
|
||||
|
||||
|
||||
def fake_client(reply):
|
||||
"""A client whose `messages.create` records its kwargs and returns or raises `reply`."""
|
||||
calls = []
|
||||
|
||||
def create(**kwargs):
|
||||
calls.append(kwargs)
|
||||
if isinstance(reply, Exception):
|
||||
raise reply
|
||||
return reply
|
||||
|
||||
return SimpleNamespace(messages=SimpleNamespace(create=create), calls=calls)
|
||||
|
||||
|
||||
def ask(reply, **kwargs):
|
||||
client = fake_client(reply)
|
||||
result = claude.ask_json(Count, max_tokens=64, messages=MESSAGES, get_client=lambda: client, **ERRORS, **kwargs)
|
||||
return result, client.calls
|
||||
|
||||
|
||||
def test_sends_the_request_and_validates_the_reply():
|
||||
result, (call,) = ask(text_reply('{"n": 3}'))
|
||||
|
||||
assert result == Count(n=3)
|
||||
# No system prompt was given, so the key is absent rather than None: the
|
||||
# SDK would send a null the API rejects.
|
||||
assert call == {"model": claude.MODEL, "messages": MESSAGES, **claude._model_options(claude.MODEL, 64)}
|
||||
|
||||
|
||||
def test_a_thinking_model_gets_headroom_and_low_effort(monkeypatch):
|
||||
"""Thinking is billed against max_tokens, so the caller's reply ceiling alone would starve the answer."""
|
||||
monkeypatch.setattr(claude, "MODEL", "claude-sonnet-5-5")
|
||||
_, (call,) = ask(text_reply("{}"))
|
||||
|
||||
assert call["model"] == "claude-sonnet-5-5"
|
||||
assert call["max_tokens"] == 64 + claude.THINKING_HEADROOM
|
||||
assert call["output_config"] == {"effort": "low"}
|
||||
# Nothing these models reject: no thinking override, sampling or forced tool.
|
||||
assert not {"thinking", "temperature", "top_p", "top_k", "tool_choice"} & call.keys()
|
||||
|
||||
|
||||
def test_haiku_gets_the_plain_request(monkeypatch):
|
||||
"""Haiku 4.5 rejects output_config.effort and does not think unless asked to."""
|
||||
monkeypatch.setattr(claude, "MODEL", "claude-haiku-4-5")
|
||||
_, (call,) = ask(text_reply("{}"))
|
||||
|
||||
assert call == {"model": "claude-haiku-4-5", "max_tokens": 64, "messages": MESSAGES}
|
||||
|
||||
|
||||
def test_the_default_model_is_one_the_admin_panel_offers():
|
||||
"""CLAUDE_MODEL's options in the env registry are what the Environment tab lets an admin pick."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
registry = json.loads((Path(__file__).parents[2] / "backend/services/env_registry.json").read_text())
|
||||
(entry,) = [v for v in registry if v["name"] == "CLAUDE_MODEL"]
|
||||
assert claude.DEFAULT_MODEL in entry["options"]
|
||||
assert "python" in entry["services"]
|
||||
|
||||
|
||||
def test_the_answer_is_found_after_a_thinking_block():
|
||||
reply = SimpleNamespace(
|
||||
stop_reason="end_turn",
|
||||
content=[SimpleNamespace(type="thinking", thinking=""), SimpleNamespace(type="text", text='{"n": 7}')],
|
||||
)
|
||||
result, _ = ask(reply)
|
||||
assert result == Count(n=7)
|
||||
|
||||
|
||||
def test_a_refusal_is_a_failed_call_not_an_empty_reply():
|
||||
reply = SimpleNamespace(stop_reason="refusal", stop_details=SimpleNamespace(category="general_harms"), content=[])
|
||||
with pytest.raises(claude.ReadError, match="call failed"):
|
||||
ask(reply)
|
||||
|
||||
|
||||
def test_running_out_of_tokens_while_thinking_is_an_empty_reply():
|
||||
reply = SimpleNamespace(stop_reason="max_tokens", content=[SimpleNamespace(type="thinking", thinking="")])
|
||||
with pytest.raises(claude.ReadError, match="nothing came back"):
|
||||
ask(reply)
|
||||
|
||||
|
||||
def test_passes_a_system_prompt_through():
|
||||
_, (call,) = ask(text_reply("{}"), system="count things")
|
||||
assert call["system"] == "count things"
|
||||
|
||||
|
||||
def test_accepts_fenced_json():
|
||||
result, _ = ask(text_reply('```json\n{"n": 3}\n```'))
|
||||
assert result.n == 3
|
||||
|
||||
|
||||
def test_reads_the_first_text_block():
|
||||
"""Anything that is not text (a thinking block, say) is stepped over."""
|
||||
reply = SimpleNamespace(
|
||||
content=[SimpleNamespace(type="thinking"), SimpleNamespace(type="text", text='{"n": 3}')]
|
||||
)
|
||||
result, _ = ask(reply)
|
||||
assert result.n == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reply, message",
|
||||
[
|
||||
(anthropic.APIConnectionError(request=REQUEST), "call failed"),
|
||||
(anthropic.APITimeoutError(request=REQUEST), "call failed"),
|
||||
(
|
||||
anthropic.APIStatusError("overloaded", response=httpx.Response(529, request=REQUEST), body=None),
|
||||
"call failed",
|
||||
),
|
||||
(SimpleNamespace(content=[]), "nothing came back"),
|
||||
(SimpleNamespace(content=[SimpleNamespace(type="thinking")]), "nothing came back"),
|
||||
(text_reply("three, I think"), "could not parse"),
|
||||
# Valid JSON that the model class rejects is the same failure.
|
||||
(text_reply('{"n": "lots"}'), "could not parse"),
|
||||
(text_reply("[3]"), "could not parse"),
|
||||
],
|
||||
)
|
||||
def test_each_failure_raises_the_callers_message(reply, message):
|
||||
with pytest.raises(claude.ReadError) as raised:
|
||||
ask(reply)
|
||||
# Exactly the caller's text: the Go backend relays it verbatim, so nothing
|
||||
# from the API error or the model's reply may be appended to it.
|
||||
assert str(raised.value) == message
|
||||
assert not isinstance(raised.value, claude.NotConfigured)
|
||||
|
||||
|
||||
def test_missing_api_key_is_not_configured_not_a_failed_call(monkeypatch):
|
||||
"""`main` tells the two apart by type to choose between 503 and 502."""
|
||||
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
|
||||
claude.client.cache_clear()
|
||||
with pytest.raises(claude.NotConfigured):
|
||||
claude.ask_json(Count, max_tokens=64, messages=MESSAGES, **ERRORS)
|
||||
|
||||
|
||||
def test_uses_the_shared_client_when_none_is_given(monkeypatch):
|
||||
client = fake_client(text_reply('{"n": 3}'))
|
||||
monkeypatch.setattr(claude, "client", lambda: client)
|
||||
|
||||
assert claude.ask_json(Count, max_tokens=64, messages=MESSAGES, **ERRORS).n == 3
|
||||
assert len(client.calls) == 1
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Tests for the rowing display reader and its internal-only route.
|
||||
|
||||
No Claude call happens here: `rowing._client` is replaced with a fake whose
|
||||
`messages.create` returns a canned reply, so what is under test is everything
|
||||
around the call - the request that is built, how the reply is parsed, how
|
||||
failures map to status codes, and the guard that keeps the route off the public
|
||||
internet.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import anthropic
|
||||
import httpx2 as httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main, rowing
|
||||
|
||||
BODY = {"media_type": "image/jpeg", "data": "aGVsbG8="}
|
||||
|
||||
|
||||
def text_reply(text):
|
||||
return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_claude(monkeypatch):
|
||||
"""Stand in for the Anthropic client; returns the list of calls it received.
|
||||
|
||||
Set `fake_claude.reply` to a message-like object, or to an exception
|
||||
instance to have the call raise it.
|
||||
"""
|
||||
state = SimpleNamespace(calls=[], reply=text_reply('{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}'))
|
||||
|
||||
def create(**kwargs):
|
||||
state.calls.append(kwargs)
|
||||
if isinstance(state.reply, Exception):
|
||||
raise state.reply
|
||||
return state.reply
|
||||
|
||||
client = SimpleNamespace(messages=SimpleNamespace(create=create))
|
||||
monkeypatch.setattr(rowing, "_client", lambda: client)
|
||||
return state
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def http():
|
||||
return TestClient(main.app)
|
||||
|
||||
|
||||
# --- fence stripping ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw, want",
|
||||
[
|
||||
('{"a": 1}', '{"a": 1}'),
|
||||
(' {"a": 1}\n', '{"a": 1}'),
|
||||
('```json\n{"a": 1}\n```', '{"a": 1}'),
|
||||
('```\n{"a": 1}\n```', '{"a": 1}'),
|
||||
('```json\n{"a": 1}', '{"a": 1}'),
|
||||
],
|
||||
)
|
||||
def test_strip_markdown_fence(raw, want):
|
||||
assert rowing.strip_markdown_fence(raw) == want
|
||||
|
||||
|
||||
# --- read_display ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_read_display_sends_image_then_prompt(fake_claude):
|
||||
reading = rowing.read_display("image/png", "QUJD")
|
||||
|
||||
assert (reading.timeMinutes, reading.timeSeconds, reading.distance) == (20, 5, 5000)
|
||||
(call,) = fake_claude.calls
|
||||
assert call["model"] == rowing.MODEL
|
||||
image, prompt = call["messages"][0]["content"]
|
||||
assert image == {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "QUJD"}}
|
||||
assert prompt == {"type": "text", "text": rowing.PROMPT}
|
||||
|
||||
|
||||
def test_read_display_accepts_fenced_json(fake_claude):
|
||||
fake_claude.reply = text_reply('```json\n{"timeMinutes": 1, "timeSeconds": 2, "distance": 300}\n```')
|
||||
assert rowing.read_display("image/jpeg", "QUJD").distance == 300
|
||||
|
||||
|
||||
def test_read_display_missing_key_defaults_to_zero(fake_claude):
|
||||
"""The Go side turns a zero distance into its own 400; it must not fail here."""
|
||||
fake_claude.reply = text_reply('{"timeMinutes": 1, "timeSeconds": 2}')
|
||||
assert rowing.read_display("image/jpeg", "QUJD").distance == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reply, message",
|
||||
[
|
||||
(SimpleNamespace(content=[]), "empty response from image processor"),
|
||||
(text_reply("I can't read that display."), "failed to parse image data"),
|
||||
(text_reply('{"timeMinutes": -1, "timeSeconds": 2, "distance": 300}'), "failed to parse image data"),
|
||||
(
|
||||
anthropic.APIConnectionError(request=httpx.Request("POST", "https://api.anthropic.com/v1/messages")),
|
||||
"failed to process image",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_read_display_failures(fake_claude, reply, message):
|
||||
fake_claude.reply = reply
|
||||
with pytest.raises(rowing.ReadError, match=message):
|
||||
rowing.read_display("image/jpeg", "QUJD")
|
||||
|
||||
|
||||
def test_missing_api_key_is_not_configured(monkeypatch):
|
||||
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
|
||||
rowing._client.cache_clear()
|
||||
with pytest.raises(rowing.NotConfigured):
|
||||
rowing.read_display("image/jpeg", "QUJD")
|
||||
|
||||
|
||||
# --- the route ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_route_returns_reading(fake_claude, http):
|
||||
res = http.post("/internal/rowing/read", json=BODY)
|
||||
assert res.status_code == 200
|
||||
assert res.json() == {"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header", ["X-Real-IP", "X-Forwarded-For"])
|
||||
def test_route_refuses_requests_proxied_by_nginx(fake_claude, http, header):
|
||||
"""nginx sets these on everything it forwards; the Go backend sets neither."""
|
||||
res = http.post("/internal/rowing/read", json=BODY, headers={header: "203.0.113.9"})
|
||||
assert res.status_code == 404
|
||||
assert fake_claude.calls == []
|
||||
|
||||
|
||||
def test_route_rejects_unsupported_media_type(fake_claude, http):
|
||||
res = http.post("/internal/rowing/read", json={**BODY, "media_type": "image/heic"})
|
||||
assert res.status_code == 422
|
||||
assert fake_claude.calls == []
|
||||
|
||||
|
||||
def test_route_maps_read_error_to_502(fake_claude, http):
|
||||
fake_claude.reply = text_reply("no numbers here")
|
||||
res = http.post("/internal/rowing/read", json=BODY)
|
||||
assert res.status_code == 502
|
||||
assert res.json() == {"detail": "failed to parse image data"}
|
||||
|
||||
|
||||
def test_route_maps_missing_key_to_503(monkeypatch, http):
|
||||
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
|
||||
rowing._client.cache_clear()
|
||||
res = http.post("/internal/rowing/read", json=BODY)
|
||||
assert res.status_code == 503
|
||||
+119
-20
@@ -14,11 +14,31 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The Vite dev server proxies API requests:
|
||||
- `/api` -> `http://localhost:8080` (Go backend)
|
||||
- `/gitea` -> `http://localhost:3000` (Gitea)
|
||||
- `/radio` -> `http://localhost:8000` (Icecast2)
|
||||
- `/py` -> `http://localhost:8000` (FastAPI; the `/py` prefix is stripped, as nginx does in production)
|
||||
The Vite dev server stands in for nginx and proxies four prefixes. Each target
|
||||
is an environment variable, read in `vite.config.js` from the shell or from
|
||||
`vue/.env.local`:
|
||||
|
||||
| Prefix | Variable | Default | Service |
|
||||
| --- | --- | --- | --- |
|
||||
| `/api` | `VITE_PROXY_API` | `http://localhost:8080` | Go backend |
|
||||
| `/gitea` | `VITE_PROXY_GITEA` | `http://localhost:3000` | Gitea |
|
||||
| `/py` | `VITE_PROXY_PY` | `http://localhost:8000` | FastAPI (the `/py` prefix is stripped, as nginx does in production) |
|
||||
| `/radio` | `VITE_PROXY_RADIO` | `http://localhost:8000` | Icecast2 |
|
||||
|
||||
**The defaults are not "where the compose stack is".** The stack publishes only
|
||||
nginx (80/443), Gitea (3000) and the liquidsoap harbor port to the host; the
|
||||
backend, the Python service and Icecast are reachable only inside the Docker
|
||||
network. The defaults are each service's own port, i.e. where it listens when
|
||||
you run it directly on the host (`go run .`, `uvicorn app.main:app`). `/py` and
|
||||
`/radio` both default to 8000 because both services do, so at most one of them
|
||||
can be right at a time — normally `/py`, with the radio simply reading as
|
||||
offline.
|
||||
|
||||
To use a running compose stack instead, point the prefix at its nginx, e.g.
|
||||
`VITE_PROXY_API=http://localhost npm run dev`. That works for `/api`, `/gitea`
|
||||
and `/radio`, which are forwarded with the path intact. It does not work for
|
||||
`/py`, because the proxy strips the prefix nginx routes on — `VITE_PROXY_PY`
|
||||
has to be a bare uvicorn.
|
||||
|
||||
## Structure
|
||||
|
||||
@@ -28,6 +48,7 @@ src/
|
||||
App.vue empty shell; all chrome lives in the layouts
|
||||
router/index.js route table + the single admin route guard
|
||||
graphql.js the entire GraphQL client (one axios POST)
|
||||
api.js the REST client for the backend's JSON routes under /api
|
||||
layouts/ DefaultLayout (dark, navbar+footer) and CVLayout (light, print)
|
||||
stores/ Pinia stores
|
||||
components/ reusable UI — text/, input/, util/, borders/, elle/
|
||||
@@ -48,7 +69,7 @@ Two layout shells, defined in `src/router/index.js`:
|
||||
| `/stp` | DefaultLayout | The personal home page: the widget grid |
|
||||
| `/admin`, `/admin/login` | DefaultLayout | `/admin` is guarded by `meta.requiresAdmin` |
|
||||
| `/automata`, `/hotels`, `/shrines/*` | DefaultLayout | |
|
||||
| `/cv`, `/cv/jobs` | CVLayout | Light print theme; `/cv/jobs` is admin-only |
|
||||
| `/cv` | CVLayout | Light print theme. Its Jobs button goes to `/jobs/`, the separate job tracker app (`adamf/job-tracker`); nginx redirects the old `/cv/jobs` and `/cv/leads` there |
|
||||
| `/stp2` | (none) | Bare full-bleed mock, deliberately outside both layouts |
|
||||
| `:pathMatch(.*)*` | DefaultLayout | 404 |
|
||||
|
||||
@@ -58,11 +79,34 @@ view its own chunk.
|
||||
Route `name`s are contracts used by `RouterLink`/`router.push` — renaming one
|
||||
breaks every link to it.
|
||||
|
||||
**The admin guard** (`router.beforeEach`) has one subtlety: the admin flag comes
|
||||
from the `me` field of the home-data query, which arrives asynchronously.
|
||||
Navigating straight to `/admin` on a cold load would otherwise read an empty
|
||||
user and bounce a real admin to the login page, so the guard first awaits
|
||||
`homeData.loaded` via a self-stopping watcher.
|
||||
**The admin guard** (`router.beforeEach`) has one subtlety: who is signed in is
|
||||
learned asynchronously. Navigating straight to `/admin` on a cold load would
|
||||
otherwise read an empty user and bounce a real admin to the login page, so the
|
||||
guard first awaits `auth.ensureLoaded()` and then reads `auth.user.admin`.
|
||||
|
||||
`ensureLoaded()` (in `stores/auth.js`) resolves once the session user is known:
|
||||
|
||||
- If nothing has supplied it yet, it issues a standalone
|
||||
`query { me { id username admin } }` — at most one in flight, and not again
|
||||
once answered.
|
||||
- On `/stp` it usually has nothing to do: the home query also returns `me`, and
|
||||
`homeData` hands it to the auth store (`auth.adoptSession()`), so that page
|
||||
does not fire a second request.
|
||||
- `logIn()`, `logOut()` and `refreshToken()` set the user directly and mark it
|
||||
known, so a change of session mid-visit is what the next navigation sees. An
|
||||
answer that was requested before such a change is discarded.
|
||||
- It **never rejects and never hangs**. A failed `me` query settles as "not
|
||||
signed in" (the guard redirects to the login page) and is retried on the next
|
||||
call.
|
||||
|
||||
The guard deliberately does not wait on the home query. It used to, via
|
||||
`homeData.loaded`, which is only set on success — so when that query failed
|
||||
(it fans out to Spotify, Steam and Gitea) navigation to `/admin`
|
||||
never resolved. The auth store does not import `homeData` at all; the
|
||||
dependency runs the other way.
|
||||
|
||||
`/admin/login` is not guarded, so `Login.vue` calls `ensureLoaded()` itself to
|
||||
show its "Already signed in" card.
|
||||
|
||||
## Data flow
|
||||
|
||||
@@ -77,26 +121,78 @@ rides along in **HTTP-only cookies** set by the Go backend, so nothing here
|
||||
touches tokens — the request just has to be same-origin (nginx in production,
|
||||
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" });
|
||||
await api.post("/radio/upload", formData, { fallback: "Upload failed" });
|
||||
```
|
||||
|
||||
It prefixes `/api`, resolves to the response body, and on failure throws an
|
||||
`ApiError` whose `message` is the backend's `{"error": "..."}` string when there
|
||||
is one, otherwise the `fallback` the caller passed. `err.status` carries the
|
||||
HTTP status for the few callers that branch on it (the Environment tab treats a
|
||||
401/403 while polling as "the apply rotated my session"). Any other option is
|
||||
passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
|
||||
|
||||
### Which one to use
|
||||
|
||||
| You are… | Use |
|
||||
| --- | --- |
|
||||
| reading or writing the site's data model | `gql()`, from a store |
|
||||
| doing list/create/update/delete on one GraphQL type | a store built with `createCrudStore()` |
|
||||
| calling a backend REST route (uploads, admin tooling, OAuth start) | `api` |
|
||||
| reading the Python service's NDJSON streams | `views/hotels/hotelsStream.js` — incremental `fetch`, not `api` |
|
||||
| probing `/radio/stream` | bare `axios.head` — it is Icecast, not the API |
|
||||
|
||||
New views should not call `gql()` or `axios` directly (a few small admin forms
|
||||
still call `gql()` for a one-off mutation). A view that needs data gets a
|
||||
store; a view that needs a REST route calls `api`.
|
||||
|
||||
### Stores
|
||||
|
||||
**`stores/homeData.js` is the hub.** It issues *one* query for everything the
|
||||
`/stp` page needs (posts, favourites, activities, Spotify, rowing, bookmarks,
|
||||
Gitea feed, Steam status, current user) instead of letting a dozen widgets each
|
||||
fire their own request. That fetch is kicked off as a side effect of the first
|
||||
`useHomeDataStore()` call, so no component has to start it.
|
||||
|
||||
The other stores are thin views over it:
|
||||
`homeData` exposes two flags, because "finished" and "succeeded" are different
|
||||
questions. **`settled`** turns true when a fetch completes either way — a
|
||||
loading state or anything that waits must key off this one. **`loaded`** turns
|
||||
true only once a fetch has succeeded, meaning the data is real. Waiting on
|
||||
`loaded` alone waits forever when the query fails.
|
||||
|
||||
| Store | Role |
|
||||
| --- | --- |
|
||||
| `homeData` | the one query; owns `loaded` / `error` |
|
||||
| `auth` | current user; mirrors `homeData.me`, plus login/logout mutations |
|
||||
| `homeData` | the one query; owns `settled` / `loaded` / `error`, and pushes `me` to `auth` |
|
||||
| `auth` | current user (`ensureLoaded()`, see Routing), plus login/logout mutations |
|
||||
| `posts`, `favorites`, `activity`, `songs`, `steam` | mirror one slice of `homeData` via an `immediate` watch, and keep a placeholder value until real data arrives |
|
||||
| `places` | independent CRUD; sign-in only, so it is fetched lazily |
|
||||
| `places` | CRUD via `createCrudStore`; sign-in only, so it is fetched lazily |
|
||||
| `messages` | the chat WebSocket — not GraphQL at all |
|
||||
| `models` | dormant; not imported anywhere |
|
||||
|
||||
The mirroring watches are `immediate` on purpose: a store created *after*
|
||||
`homeData` has already loaded would never see the existing value otherwise.
|
||||
|
||||
Two factories keep the repeated shapes in one place:
|
||||
|
||||
- **`createMirrorStore`** — the body of a store that mirrors a `homeData` slice.
|
||||
- **`createCrudStore(id, { type, list, fields, ... })`** — a whole store for one
|
||||
GraphQL type that has the schema's usual `create<Type>` / `update<Type>` /
|
||||
`delete<Type>` mutations and a list query. It gives `fetch`, `create`,
|
||||
`update`, `remove` and `loaded` / `loading` / `error`, and patches the local
|
||||
array after each mutation rather than refetching. `fields` is interpolated
|
||||
into every operation so the selection sets cannot drift. Options cover the
|
||||
differences between types: `itemsKey` (the name the array is
|
||||
exposed under), `insert` (`"prepend"` or `"append"`), `deleteReturns`
|
||||
(`"object"` for `deletePlace`, `"boolean"` for a delete that returns a
|
||||
scalar — a scalar must not be given a selection set) and `extend` for extra actions.
|
||||
|
||||
The error contract is deliberate: `fetch()` never throws and records the
|
||||
failure on `error`; the mutations throw, so the form that called them can
|
||||
show the message and keep what was typed.
|
||||
|
||||
## Component conventions
|
||||
|
||||
- Layout and one-off tweaks go in Tailwind utilities; reach for a scoped
|
||||
@@ -121,14 +217,16 @@ The mirroring watches are `immediate` on purpose: a store created *after*
|
||||
## Dev vs production
|
||||
|
||||
- **Dev** (`npm run dev`): Vite serves the SPA and proxies `/api`, `/gitea`,
|
||||
`/radio` and `/py` (see the table above and `vite.config.js`). The `/py`
|
||||
proxy strips the prefix, matching what nginx does in production.
|
||||
`/radio` and `/py` to the `VITE_PROXY_*` targets (see Development above and
|
||||
`vite.config.js`). The `/py` proxy strips the prefix, matching what nginx
|
||||
does in production.
|
||||
- **Production** (`npm run build`): `dist/` is built into the nginx container
|
||||
and served as static files, with nginx doing the same reverse-proxying.
|
||||
|
||||
Note `npm run build` runs `build:wasm` first, which needs **wasm-pack** on the
|
||||
PATH. If you only want the Vue bundle and `src/wasm/` is already populated,
|
||||
`npx vite build` skips that step.
|
||||
`npm run build:js` (plain `vite build`) skips that step. It is also the local
|
||||
check that the app still compiles — there is no test runner or linter.
|
||||
|
||||
## Live vs legacy views
|
||||
|
||||
@@ -157,13 +255,14 @@ tree-shaken out. They are kept deliberately; don't delete without asking.
|
||||
|
||||
## Styling
|
||||
|
||||
Everything visual is defined in three places:
|
||||
Everything visual is defined in a handful of places:
|
||||
|
||||
| File | What it holds |
|
||||
| --- | --- |
|
||||
| `src/assets/styles.css` | Fonts, **design tokens**, default element styles (dark theme), reusable classes (`bdr-1`, `bdr-2`, `page-a4`, `halftone`), the `slide` and `fade` transitions, print rules |
|
||||
| `src/layouts/CVLayout.vue` | The **light theme** for `/cv` and `/cv/jobs`: re-points the colour tokens to ink-on-paper values and holds the shared `.cv-btn` styles |
|
||||
| `src/layouts/CVLayout.vue` | The **light theme** for `/cv`: re-points the colour tokens to ink-on-paper values and holds the shared `.cv-btn` styles |
|
||||
| `src/views/CV/cv-shared.css` | Typography and page layout for the CV templates (`.cv-template`, `.cv-page`, `--cv-*` size variables) |
|
||||
|
||||
| `src/views/hotels/hotels-shared.css` | Panels, forms, tables and tab strip for `/hotels`, shared by the single-stay and cheapest-night panels; every selector is prefixed with the page's `.hotels` root class |
|
||||
|
||||
### Tokens
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"build:wasm": "wasm-pack build crates/stp_wasm --target web --out-dir ../../src/wasm",
|
||||
"dev": "vite",
|
||||
"build": "npm run build:wasm && vite build",
|
||||
"build:js": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* The REST half of the API client, beside graphql.js: a thin axios wrapper for
|
||||
* the Go backend's JSON endpoints under /api (file uploads, admin tooling,
|
||||
* 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")`);
|
||||
* - 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.
|
||||
*
|
||||
* Resolves to the parsed response body, not the axios response.
|
||||
*
|
||||
* Auth is the same HTTP-only cookies graphql.js relies on; nothing here handles
|
||||
* tokens.
|
||||
*
|
||||
* NOT for: the Python service's NDJSON streams (views/hotels/hotelsStream.js
|
||||
* reads those incrementally with fetch) or the `/radio/stream` HEAD probe —
|
||||
* neither is under /api nor answers with this error shape.
|
||||
*/
|
||||
|
||||
import axios from "axios";
|
||||
|
||||
export class ApiError extends Error {
|
||||
/**
|
||||
* @param {string} message
|
||||
* @param {number|undefined} status HTTP status; undefined when no response
|
||||
* arrived at all (network down, backend restarting)
|
||||
* @param {*} data the parsed error body, if any
|
||||
*/
|
||||
constructor(message, status, data) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} method
|
||||
* @param {string} path route below /api, with its leading slash
|
||||
* @param {object} [options]
|
||||
* @param {*} [options.body] JSON-serialisable body, or a FormData for
|
||||
* multipart uploads (axios sets the boundary itself)
|
||||
* @param {string} [options.fallback] message to use when the backend sent no
|
||||
* `error` string — callers pass the sentence their UI shows
|
||||
* Any other option (`headers`, `params`, `onUploadProgress`, `signal`, …) is
|
||||
* handed to axios unchanged.
|
||||
*/
|
||||
async function request(method, path, { body, fallback, ...config } = {}) {
|
||||
try {
|
||||
const res = await axios.request({
|
||||
method,
|
||||
url: `/api${path}`,
|
||||
data: body,
|
||||
...config,
|
||||
});
|
||||
return res.data;
|
||||
} catch (err) {
|
||||
const data = err.response?.data;
|
||||
const serverMessage = typeof data?.error === "string" ? data.error : "";
|
||||
throw new ApiError(
|
||||
serverMessage || fallback || err.message,
|
||||
err.response?.status,
|
||||
data,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (path, options) => request("get", path, options),
|
||||
delete: (path, options) => request("delete", path, options),
|
||||
post: (path, body, options) => request("post", path, { ...options, body }),
|
||||
put: (path, body, options) => request("put", path, { ...options, body }),
|
||||
patch: (path, body, options) => request("patch", path, { ...options, body }),
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user