diff --git a/.env.dev b/.env.dev index c936d30..1a463d9 100644 --- a/.env.dev +++ b/.env.dev @@ -16,12 +16,11 @@ # # Keep it in step with .env.example: a new variable goes in both. Settings that # are not secrets (hosts, ports, timezone) keep .env.example's defaults; values -# a service parses (Garage's hex secrets, Gitea's base64 JWT keys, the S3 key -# id) are dummies in the exact shape it requires, or that service won't start. +# a service parses (Garage's hex secrets, the S3 key id) are dummies in the exact shape it requires, or that service won't start. # # The dummy Postgres credentials only work on a database volume created with # them: an existing dbdata volume keeps whatever password it was initialised -# with. Only POSTGRES_DB is created on a fresh volume; the gitea, jobs and +# with. Only POSTGRES_DB is created on a fresh volume; the jobs and # tracker databases and roles still have to be created by hand (.env.example). # ============================================================================= @@ -39,16 +38,11 @@ POSTGRES_TRACKER_USER=tracker POSTGRES_TRACKER_PASSWORD=dev-tracker-password # --- Gitea ------------------------------------------------------------------- -# The two JWT secrets must decode as base64url of 32 bytes; these decode to -# the text "dev-only-not-a-secret-0123456789". +# Dev has no Gitea: the forwarder points at a TEST-NET address that never +# answers, so /gitea/ is a 502 and the home page's git feed is empty. GITEA_HOST=gitea GITEA_PORT=3000 -GITEA_INTERNAL_TOKEN=dev-gitea-internal-token -GITEA_LFS_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk -GITEA_OAUTH2_JWT_SECRET=ZGV2LW9ubHktbm90LWEtc2VjcmV0LTAxMjM0NTY3ODk -POSTGRES_GITEA_DB=gitea -# Blank means localhost. -GITEA_SSH_DOMAIN= +GITEA_UPSTREAM=192.0.2.1 # --- Gitea Actions runner ---------------------------------------------------- # The runner is not part of the compose stack; nothing in dev reads these. diff --git a/.env.example b/.env.example index 7e61dd0..4935afa 100644 --- a/.env.example +++ b/.env.example @@ -33,10 +33,10 @@ # ============================================================================= # --- Postgres ---------------------------------------------------------------- -# One instance, four databases: POSTGRES_DB for the Go backend, -# POSTGRES_GITEA_DB for Gitea, POSTGRES_JOBS_DB for the job tracker and -# POSTGRES_TRACKER_DB for the activity tracker (each of the last two with its -# own role). Only POSTGRES_DB is auto-created on first init; the others must +# One instance, three databases: POSTGRES_DB for the Go backend, +# POSTGRES_JOBS_DB for the job tracker and POSTGRES_TRACKER_DB for the +# activity tracker (each of the last two with its own role). Gitea's database +# is in the Gitea LXC's own Postgres. Only POSTGRES_DB is auto-created on first init; the others must # be created by hand on a fresh volume (the job-tracker and ccp READMEs have # the commands). # POSTGRES_HOST doubles as the db container's name. @@ -53,23 +53,17 @@ POSTGRES_TRACKER_USER=tracker POSTGRES_TRACKER_PASSWORD= # --- Gitea ------------------------------------------------------------------- -# GITEA_HOST is the container name AND the Caddy upstream host. -# The three secrets below are passed as GITEA__section__KEY overrides so the -# committed app.ini.template can keep those fields blank. Generate each as a -# long random hex string. +# Gitea runs in its own LXC (gitea/docker-compose.yml, whose variables are in +# gitea/.env.example). This stack's `gitea` service is a TCP forwarder to it. +# GITEA_HOST is that forwarder's container name AND the upstream host for +# Caddy, the backend's feed and usaco. GITEA_UPSTREAM is the LXC's LAN IP +# (an IP, not a name: Docker's DNS cannot see LAN or tailnet names). GITEA_HOST=gitea GITEA_PORT=3000 -GITEA_INTERNAL_TOKEN= -GITEA_LFS_JWT_SECRET= -GITEA_OAUTH2_JWT_SECRET= -POSTGRES_GITEA_DB=gitea -# The host's Tailscale MagicDNS name (e.g. stpvm.tailf20278.ts.net), shown in -# Gitea's SSH clone URLs. Not the public domain: 2222 is reachable only over -# the tailnet. Becomes Gitea's SSH_DOMAIN and DOMAIN. Blank means localhost. -GITEA_SSH_DOMAIN= +GITEA_UPSTREAM= # --- Gitea Actions runner ---------------------------------------------------- -# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh. +# The runner is NOT a container; it runs on stpvm via gitea-runner/run.sh. # The registration token is SINGLE-USE: it is exchanged for a permanent # identity in gitea-runner/.runner on first registration, after which this # value is ignored. Mint it in Site Administration -> Actions -> Runners. diff --git a/.gitignore b/.gitignore index 88dcdea..a7922d9 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ usaco-data/ gitea/data/* gitea/config/app.ini +gitea/.env # Gitea runner gitea-runner/.runner diff --git a/CLAUDE.md b/CLAUDE.md index 3171c02..cc72a41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -63,6 +63,8 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun **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/`; Caddy redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`. +**Gitea** (`gitea/`): git, Actions and the image registry (`/adamf/...`) run in their own Proxmox LXC since 2026-11-24, from `gitea/docker-compose.yml` with their own Postgres (`gitea-db`) and `gitea/.env`, deployed by hand there and never by CI. This stack's `gitea` service is an haproxy TCP forwarder (`gitea/forwarder.cfg`) from stpvm's 3000/2222 to the LXC's LAN IP (`GITEA_UPSTREAM`), so `gitea:3000`, `localhost:3000` and `localhost:2222` still work for Caddy, the backend feed, usaco, the runner and every repo's CI. The act_runner stays on stpvm. Runbook: "Gitea LXC" in `DEPLOYMENT.md` §7. + **Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). Caddy serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7. **Caddy** (`caddy/`): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into `./caddy/data`), so there is no certbot. `caddy/Caddyfile` holds the global options and the shared snippets (`proxy`, `limit`, `admin_gate`, `permission_gate`, the upload headers, logging); `caddy/routes.caddy` is the one route table both modes use — add a new route there, in the right place, because inside its `route` block the first matching `handle` wins; `caddy/sites/prod.caddy` and `sites/dev.caddy` hold what differs (TLS, security headers, the apex, static caching, `/`), picked by `CADDY_SITE`. Every variable the config reads goes through the caddy service's explicit `environment:` list. The image build runs `caddy validate`, so `make check-caddy` (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (`import limit `) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/caddy/payloads.log`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. Caddy has a healthcheck (`http://127.0.0.1/caddy-health`); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea's commit-pinned history views and archives are admin-gated at the edge because a crawler swarm hammers them; the branch views stay public. `caddy/edge_test.sh` checks the privacy denials and every gate against a running edge. The pre-cutover nginx and certbot configs are in `.deprecated/nginx/` and `.deprecated/certbot/`, kept for the rollback in `DEPLOYMENT.md` §7. diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index b1ca0e3..9acee1e 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -14,7 +14,7 @@ network, behind one Caddy (nginx and certbot until 2026-11-17). ## 1. Service topology Only three things are reachable from outside the host: Caddy on 80/443, Gitea on -3000/2222, and the liquidsoap harbor port. Everything else is internal. Web +3000/2222 (a forwarder to the Gitea LXC, below), and the liquidsoap harbor port. Everything else is internal. Web traffic can also come in through the Cloudflare tunnel (`cloudflared`), which dials out and publishes no port; see "Cloudflare Tunnel" in §3. @@ -25,29 +25,54 @@ dials out and publishes no port; see "Cloudflare Tunnel" in §3. v v v +--------------+ +--------+ +-------------+ | caddy | | gitea | | liquidsoap | - | (TLS, SPA, | | (git + | | harbor | - | reverse | | CI) | | (live DJ) | - | proxy) | +--------+ +------+------+ - +------+-------+ | | - | | | - --------------------------------------------- | (same container - | | | | | | | as icecast2) - v v v v v v | | -/api/ /radio/ /gitea/ /sb/ /notes/ /py/ | | -backend icecast2 gitea sb sb-pub python | | - | ^ | | - | | | | - | +---------------------------------------|---------------+ - | | - +----------+--------------------------------------+ + | (TLS, SPA, | | (fwd | | harbor | + | reverse | | to | | (live DJ) | + | proxy) | | LXC) | +------+------+ + | | +--------+ | + +------+-------+ | + | | + --------------------------------------------- (same container + | | | | | | as icecast2) + v v v v v v | +/api/ /radio/ /gitea/ /sb/ /notes/ /py/ | +backend icecast2 gitea sb sb-pub python | + | ^ | + | | | + | +-------------------------------------------------------+ + | + +----------+ v +------+ | db | postgres:16 - +------+ (app database + gitea database) + +------+ (app database + the trackers' databases) vue one-shot build container -> writes vue_dist volume -> caddy serves it ``` +### Gitea runs in its own LXC + +Gitea (git, Actions, the image registry) is not in this stack. It runs on a +separate Proxmox LXC, from `gitea/docker-compose.yml`, with its own Postgres +(`gitea-db`); the runbook is "Gitea LXC" in §7. The `gitea` service here is +an haproxy TCP forwarder (`gitea/forwarder.cfg`) from this host's 3000 and +2222 to the LXC's LAN IP (`GITEA_UPSTREAM`), under the old container name, so +everything that reached Gitea on stpvm still does at the same address: + +``` + stpvm Gitea LXC (LAN IP) + caddy /gitea/, /v2/ --+ +------------------+ + backend feed ----------+--> gitea:3000 (haproxy) ---> | gitea :3000 | + usaco pulls -----------+ :2222 ------------> | :2222 | + runner, Renovate localhost:3000 | gitea-db | + CI, obsidian localhost:2222 / DOMAIN:2222 +--------+---------+ + usaco <-- caddy <-- https://www.DOMAIN/usaco/api/hooks/gitea --+ (webhook, + over the LAN) +``` + +The LXC is also on the tailnet, so a laptop can use its own name directly. +Deploys of this stack never restart Gitea; recreating the forwarder only +drops connections in flight. + ### Who listens where | Service | Container name | Internal port | Public route | Published to host | @@ -62,7 +87,7 @@ backend icecast2 gitea sb sb-pub python | | | jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by Caddy `forward_auth`; capture API and userscript public, bearer-token) | no | | activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by Caddy `forward_auth`; `/api/v1/` bearer/app-checked) | no | | icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** | -| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** | +| gitea (haproxy forwarder to the Gitea LXC) | `${GITEA_HOST}` | 3000, 2222 | `/gitea/`, and the registry at the apex `/v2/` | **3000, 2222** | | vue | `vue` | 5173 (dev only) | `/` (dev only) | no | | cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of Caddy, via Cloudflare | no (outbound only) | | dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by Caddy `forward_auth`; reads the Docker socket) | no | @@ -162,7 +187,8 @@ which has two jobs: 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`, + newer, untested commit). It fetches over `ssh://git@localhost:2222` (the + forwarder to the Gitea LXC), hard-resets the deploy checkout, and runs `docker compose up -d --build --remove-orphans` under the `.compose.lock` flock, shared with the weekly maintenance workflow. @@ -374,7 +400,7 @@ Setup, once: | Volume | Holds | Losing it means | | ---------- | ----------------------------------------------------- | -------------------------------------------------- | -| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata | +| `dbdata` | Postgres: the app database and the trackers' databases | All posts, users and messages, and the trackers' data | | `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files | | `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) | | `garage_data` | The bucket's object bytes | Every upload stored in Garage | @@ -390,12 +416,14 @@ of deleting the directory: | `./certbot/conf` | The old certbot certificate and keys | Unused since 2026-11-17; kept as the rollback until it is cleaned up (§7). | | `./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. | -| `./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 (`go.log`); Caddy's JSON request-body log in `logs/caddy/payloads.log` | Caddy rotates the payload log itself (50 MiB, five kept). `logs/nginx/` is nginx's, finished. | | `./icecast2/fallback_music` | Radio fallback MP3s | Copied to the host by hand, not git | | `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public | +Gitea's state (`gitea/data`, `gitea/config`, the `gitea_db` volume) is on +the Gitea LXC, not here; see "Gitea LXC" in §7. stpvm's own `gitea/data` and +`gitea/config` are the pre-move copy, kept as the rollback. + **Ephemeral:** anything else inside a container. Notably the Vue build, the rendered icecast config, and the Gitea runner's downloaded binary are all regenerated. @@ -414,8 +442,9 @@ Two distinct mechanisms read it, and services use both: - **`env_file: ./.env`** — injects the whole file into the container. Used by backend, db and icecast2. -`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own -convention for overriding `app.ini` keys), and `python` receives an explicit +Gitea's own variables are in `gitea/.env` on the Gitea LXC (`gitea/.env.example`); +there it receives explicit `GITEA__section__KEY` variables (Gitea's own +convention for overriding `app.ini` keys). Here, `python` receives an explicit allow-list (as do `jobs`, `caddy` and the rest), 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 @@ -576,7 +605,8 @@ in `traffic` follows the rotation, so it needs no logrotate entry. The `logs/nginx/*.log` stanza in `/etc/logrotate.d/web_server` is nginx's and can go when `logs/nginx/` does. -**Reset the database** — destructive; wipes the app database **and Gitea's**: +**Reset the database** — destructive; wipes the app database (Gitea's is on +the Gitea LXC and is not affected): ``` docker compose down @@ -585,13 +615,8 @@ docker compose up -d ``` The app schema is recreated by GORM auto-migration on backend start (there are no -migration files). **Gitea's database is not auto-created** — the Postgres image -only creates `POSTGRES_DB` on first init, so create `${POSTGRES_GITEA_DB}` -manually before Gitea will start: - -``` -docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB" -``` +migration files). The job and activity trackers' databases are not +auto-created; their READMEs have the commands. **Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket, with the `uploads` volume as a safety net. Nothing breaks while Garage is down @@ -652,6 +677,42 @@ Back up `garage_meta` and `garage_data` together (meta without data, or the reverse, is useless); Garage also snapshots its metadata every 6h inside `garage_meta`. +**Gitea LXC.** Gitea runs in its own Proxmox LXC (§1), from +`gitea/docker-compose.yml` in a checkout of this repo, with its secrets in +`gitea/.env`. It is deployed by hand, never by CI: + +``` +cd ~/deploy/web_server/gitea && git pull && docker compose up -d +``` + +That includes a Renovate PR that bumps its image: merging deploys stpvm, not +the LXC, so pull and `up -d` here afterwards. + +- *The container.* Debian, unprivileged, with `nesting=1,keyctl=1` (Docker + needs both), a static LAN IP on stpvm's bridge, Docker and Tailscale. + `GITEA_UPSTREAM` in stpvm's `.env` is that LAN IP; `GITEA_SSH_DOMAIN` in + `gitea/.env` is its tailnet name, which Gitea prints in SSH clone URLs. +- *Webhooks to the site* (usaco's push hook, + `https://www./usaco/api/hooks/gitea`) go straight to stpvm's Caddy + over the LAN: `extra_hosts` pins `www.` to `EDGE_IP`, and + `ALLOWED_HOST_LIST` allows that name, since its address is private. +- *Backups.* A Proxmox `vzdump` of the whole LXC covers the git data and the + database together. `gitea/data` alone is not a backup: the issues, PRs, + users and registry index are in `gitea_db`. +- *If it is down,* `/gitea/` and the registry are 502, CI does not run, and + image pulls fail; the site itself keeps serving. +- *Moving it again* (or the first move, from stpvm): stop Gitea, `pg_dump -Fc` + its database and restore it with `pg_restore --no-owner --role=gitea` into + a fresh `gitea-db`, copy `gitea/data` and `gitea/config` with + `tar --numeric-owner` (owned by uid 1000), start it, then point + `GITEA_UPSTREAM` at the new address and `docker compose up -d gitea` on + stpvm. The SSH host key is in `gitea/data`, so clients' `known_hosts` still + match. +- *Rollback to running it on stpvm:* revert the commit that made `gitea` a + forwarder, restore its database into stpvm's `db`, and `docker compose up + -d gitea` with stpvm's own `gitea/data` (the pre-move copy, so anything + pushed since the move has to be copied back from the LXC first). + **Set up the CI runner on a fresh host:** ``` diff --git a/Makefile b/Makefile index 9f166c9..0b72b80 100644 --- a/Makefile +++ b/Makefile @@ -111,7 +111,9 @@ check-compose: 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 + docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q; \ + echo "docker compose -f gitea/docker-compose.yml config -q (the Gitea LXC, against gitea/.env.example)"; \ + docker compose -f gitea/docker-compose.yml --env-file gitea/.env.example config -q # The edge config is validated by the image build itself (the last RUN in # caddy/Dockerfile runs `caddy validate` for the production and dev sites), so diff --git a/caddy/routes.caddy b/caddy/routes.caddy index a2f0956..6fe0085 100644 --- a/caddy/routes.caddy +++ b/caddy/routes.caddy @@ -327,8 +327,8 @@ handle /jobs/* { # Its own container (the usaco repo's site/), shaped like /jobs/: SPA and API # under one prefix that is NOT stripped, and no gate, because most of it is # public and the app checks the session itself for the admin's edits. Gitea's -# push webhook does not come through here: it calls the container directly -# on the Docker network. +# push webhook (/usaco/api/hooks/gitea) comes through here too, from the +# Gitea LXC over the LAN; it is signed with USACO_WEBHOOK_SECRET. handle /usaco/* { import limit api 30 1s reverse_proxy usaco:8080 { diff --git a/docker-compose.yml b/docker-compose.yml index 386cd90..15df140 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,7 +8,7 @@ # Dev layers docker-compose.dev.yml on top of it (see that file). # # WHEN IT RUNS -# On the Raspberry Pi, via the Gitea Actions deploy workflow +# On stpvm, via the Gitea Actions deploy workflow # (.gitea/workflows/deploy.yaml) on every push to main, and by hand. # # ENV VARS @@ -21,9 +21,8 @@ # app config from env_file. # # Required by this file: POSTGRES_{USER,PASSWORD,DB,PORT,HOST}, -# 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 +# BACKEND_HOST, ICECAST_HOST, GITEA_HOST, GITEA_UPSTREAM and +# OBSIDIAN_DIR. PYTHON_HOST/PYTHON_PORT/TFL_APP_KEY/LIQUIDSOAP_HARBOR_PORT have # inline defaults. # # NAMING CONVENTION / WHY container_name IS SET FROM env @@ -35,8 +34,8 @@ # the other. # # WHAT IS PUBLISHED TO THE HOST -# Only caddy (80, 443), gitea (3000 HTTP, 2222 SSH) and the liquidsoap harbor -# port. Everything else is reachable only from inside app-network, which is +# Only caddy (80, 443), gitea (3000 HTTP, 2222 SSH: the forwarder to the +# Gitea LXC) and the liquidsoap harbor port. Everything else is reachable only from inside app-network, which is # why the backend, db, silverbullet and python have no `ports:` — they are # deliberately not exposed and are reached through Caddy. Web traffic can # also arrive through the `cloudflared` tunnel, which publishes nothing. @@ -63,13 +62,14 @@ networks: # PERSISTENT vs EPHEMERAL state # Named volumes below survive `docker compose down` and container rebuilds; # they are only destroyed by `docker compose down -v` or an explicit -# `docker volume rm`. Bind mounts (./gitea/data, ./backend/token, ./logs, -# ./caddy/data) live in the repo checkout on the Pi and survive everything +# `docker volume rm`. Bind mounts (./backend/token, ./logs, ./caddy/data) +# live in the repo checkout on the host and survive everything # short of deleting the directory. Anything inside a container's own # filesystem is ephemeral and gone on rebuild. volumes: - # Postgres database — PERSISTENT. Holds the app DB *and* the Gitea DB. - # Deleting this wipes posts, users, messages and every git repo's metadata. + # Postgres database — PERSISTENT. Holds the app DB and the job and activity + # trackers' DBs. Deleting this wipes posts, users and messages. (Gitea's + # database moved to its own Postgres in the Gitea LXC.) dbdata: # File upload — PERSISTENT. Written by the backend at /backend/uploads, # served read-only by Caddy at /uploads/. Shared so Caddy can serve user @@ -299,10 +299,11 @@ services: retries: 3 start_period: 10s - # 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; - # a from-scratch restore must `createdb` it before Gitea will start. + # Single Postgres instance: ${POSTGRES_DB} for the Go backend, plus the job + # and activity trackers' databases. The postgres image only creates + # POSTGRES_DB on first init; the others are created by hand (see their + # READMEs). Gitea's database is not here any more: it has its own Postgres + # in the Gitea LXC (gitea/docker-compose.yml). # Schema for the app DB comes from GORM auto-migration at backend start — # there are no migration files. db: @@ -474,7 +475,8 @@ services: # The vault's remotes are ssh://git@DOMAIN:2222/..., but Caddy's network # aliases make DOMAIN resolve to Caddy on app-network, which has no :2222, # so every pull and push was refused. /etc/hosts wins over Docker's DNS, so - # this sends DOMAIN back to the host, where gitea publishes 2222. The name + # this sends DOMAIN back to the host, where the gitea forwarder publishes + # 2222. The name # is unchanged, so known_hosts still matches. extra_hosts: - "${DOMAIN}:host-gateway" @@ -834,71 +836,38 @@ services: volumes: - ./garage/garage.toml:/etc/garage.toml:ro - # Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI - # server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to - # main, executed by the act_runner that lives outside docker (gitea-runner/). + # Gitea's ports on this host, forwarded to Gitea itself, which runs in its + # own LXC (gitea/docker-compose.yml; DEPLOYMENT.md §7, "Gitea LXC"). A + # plain TCP forwarder (gitea/forwarder.cfg), kept under the old service and + # container name so nothing that talked to Gitea here had to change: + # Caddy's /gitea/ and /v2/ upstream and the backend's feed (GITEA_HOST, + # GITEA_PORT), usaco's pulls, and on the host the runner and Renovate + # (localhost:3000) and every repo's CI and the obsidian checkout + # (localhost:2222, or DOMAIN:2222 pinned to the host). # - # ROOTLESS image: runs as an unprivileged user, so config lives in /etc/gitea - # and data in /var/lib/gitea (not /data as in the root image) — that is why - # the bind mounts look unlike most Gitea compose examples. + # Gitea is 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/). Recreating this container drops git and + # registry connections in flight for a moment, which is why its config is + # small and rarely changes; Gitea itself is never restarted by a deploy. # - # The GITEA__section__KEY environment convention is Gitea's own: each maps to - # an app.ini key and overrides the file at runtime, which is how the secrets - # stay in .env instead of in the committed app.ini.template. - # - # entrypoint is overridden to run our wrapper (which materialises app.ini - # from the template on first boot) before handing off to Gitea's real - # docker-entrypoint.sh. dumb-init is kept as PID 1 for correct signal/zombie - # handling, exactly as the stock image does it. + # GITEA_UPSTREAM is the LXC's LAN IP. Dev has no Gitea: it points at a dummy + # address and /gitea/ answers 502. gitea: - image: docker.gitea.com/gitea:1.25.4-rootless + image: haproxy:3.2.27-alpine container_name: "${GITEA_HOST}" - entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"] + restart: always networks: - app-network environment: - - GITEA__database__DB_TYPE=postgres - - GITEA__database__HOST=${POSTGRES_HOST} - - GITEA__database__NAME=${POSTGRES_GITEA_DB} - - GITEA__database__USER=${POSTGRES_USER} - - GITEA__database__PASSWD=${POSTGRES_PASSWORD} - - GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET} - - GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN} - - GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET} - # The host's own name, which Gitea prints in SSH clone URLs. It lives in - # .env, not app.ini, so moving to another host is a one-line change; - # environment-to-ini writes it into the live app.ini on every start. - # localhost suits dev. - - GITEA__server__SSH_DOMAIN=${GITEA_SSH_DOMAIN:-localhost} - - GITEA__server__DOMAIN=${GITEA_SSH_DOMAIN:-localhost} - # Webhooks are refused to private addresses by default ("external"). - # The usaco site's push hook targets http://usaco:8080 on the Docker - # network, so that one host is allowed by name. - - GITEA__webhook__ALLOWED_HOST_LIST=external,usaco - - USER_UID=1000 - - USER_GID=1000 - restart: always + - GITEA_UPSTREAM=${GITEA_UPSTREAM:?set GITEA_UPSTREAM in .env to the Gitea LXC's LAN IP} volumes: - # PERSISTENT: repositories, LFS objects, avatars, sessions. The git data - # itself. (Gitea's *relational* data is in Postgres, not here.) - - ./gitea/data:/var/lib/gitea - # PERSISTENT: app.ini is generated into this host directory on first boot - # and then edited by Gitea itself, so it is gitignored — only the - # template is committed. - - ./gitea/config:/etc/gitea - # Mounted over the config dir so the wrapper script is available at the - # path the overridden entrypoint points at. - - ./gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro - # Match the Pi's clock/zone so commit and CI timestamps are local time. - - /etc/timezone:/etc/timezone:ro - - /etc/localtime:/etc/localtime:ro + - ./gitea/forwarder.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro ports: - # 2222 = Gitea's *built-in* SSH server (the rootless image cannot use 22). - # Clones use ssh://git@host:2222/... — including the deploy workflow, - # which fetches from ssh://git@localhost:2222. + # 2222 = Gitea's built-in SSH server; clones use ssh://git@host:2222/... + # — including the deploy workflow, which fetches from + # ssh://git@localhost:2222. - "2222:2222" - # 3000 = HTTP, published directly as well as proxied at /gitea/, because - # the act_runner registers against http://localhost:3000 from the host. + # 3000 = HTTP, published as well as proxied at /gitea/, because the + # act_runner registers against http://localhost:3000 from the host. - "3000:3000" - depends_on: - - db diff --git a/gitea/.env.example b/gitea/.env.example new file mode 100644 index 0000000..dde6b49 --- /dev/null +++ b/gitea/.env.example @@ -0,0 +1,30 @@ +# ============================================================================= +# gitea/.env.example — variables for gitea/docker-compose.yml (the Gitea LXC). +# +# Copy to gitea/.env on the LXC and fill in. Separate from the site's .env on +# purpose: the LXC holds Gitea's secrets and nothing of the site's. +# NOTHING IN THIS FILE HAS A REAL VALUE. +# ============================================================================= + +# Gitea's own Postgres (the gitea-db service). Created on first init. +GITEA_DB_NAME=gitea +GITEA_DB_USER=gitea +GITEA_DB_PASSWORD= + +# Passed as GITEA__section__KEY overrides so the committed app.ini.template +# can keep those fields blank. Moving from stpvm, copy the existing values +# from the site's .env (they had the same names there); a fresh install +# generates each as a long random string. +GITEA_INTERNAL_TOKEN= +GITEA_LFS_JWT_SECRET= +GITEA_OAUTH2_JWT_SECRET= + +# This LXC's Tailscale MagicDNS name (e.g. stpgit.tailf20278.ts.net), shown in +# Gitea's SSH clone URLs. Becomes Gitea's SSH_DOMAIN and DOMAIN. +GITEA_SSH_DOMAIN= + +# The site's public domain (no www), and stpvm's LAN IP, where Caddy listens. +# Webhooks to https://www.DOMAIN/... are sent there directly (see the compose +# file's extra_hosts). +DOMAIN= +EDGE_IP= diff --git a/gitea/config/app.ini.template b/gitea/config/app.ini.template index bea5889..844752e 100644 --- a/gitea/config/app.ini.template +++ b/gitea/config/app.ini.template @@ -9,8 +9,8 @@ ; SECRET FIELDS ARE DELIBERATELY BLANK HERE ; LFS_JWT_SECRET, PASSWD, SECRET_KEY and JWT_SECRET are empty on purpose so ; nothing sensitive is committed. Real values arrive at runtime as -; GITEA__section__KEY environment variables from ./.env (see -; docker-compose.yml), which override app.ini. SECRET_KEY is the exception — +; GITEA__section__KEY environment variables from gitea/.env (see +; gitea/docker-compose.yml), which override app.ini. SECRET_KEY is the exception — ; Gitea generates one itself on first run and writes it into the live app.ini. ; ; SETTINGS WORTH KNOWING @@ -18,23 +18,27 @@ ; every link, clone URL and OAuth redirect Gitea emits will be wrong. ; START_SSH_SERVER = true with SSH_PORT 2222: the rootless image cannot bind ; 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 +; 2222 is published in gitea/docker-compose.yml (on the Gitea LXC) and +; forwarded on stpvm, so the deploy workflow still clones over ; ssh://git@localhost:2222. ; SSH_DOMAIN and DOMAIN are not set here: they come from GITEA_SSH_DOMAIN in -; ./.env (see docker-compose.yml). The value is the host's Tailscale +; gitea/.env (see gitea/docker-compose.yml). The value is the Gitea LXC'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 ; Caddy at ROOT_URL and stay public. ; REVERSE_PROXY_LIMIT = 1 / TRUSTED_PROXIES = * : trust exactly one hop of ; X-Forwarded-For, i.e. our Caddy, so Gitea logs real client IPs. Caddy -; sends a single entry, the visitor (its `proxy` snippet). This is only -; safe because Caddy is the sole edge. +; sends a single entry, the visitor (its `proxy` snippet). stpvm's +; forwarder is TCP-level and adds no hop. This is only safe because Caddy +; is the sole edge (3000 on the LXC is reachable from the LAN and the +; tailnet, never from the internet). ; INSTALL_LOCK = true skips the first-run web installer. ; DISABLE_REGISTRATION = true — single-user instance; nobody can sign up. ; OFFLINE_MODE = true — no calls out to gravatar/CDNs. -; DB_TYPE postgres pointing at the shared `db` container, in its own database -; alongside the app's. WORK_PATH/APP_DATA_PATH are /var/lib/gitea, the +; DB_TYPE postgres; the host, name and credentials come from gitea/.env +; (gitea/docker-compose.yml), pointing at its own `gitea-db` container. +; The HOST below is only the seed value. WORK_PATH/APP_DATA_PATH are /var/lib/gitea, the ; rootless image's layout (the root image uses /data instead). ; ============================================================================= APP_NAME = Gitea: Git with a cup of tea @@ -68,9 +72,9 @@ OFFLINE_MODE = true [database] PATH = /var/lib/gitea/data/gitea.db DB_TYPE = postgres -HOST = db +HOST = gitea-db:5432 NAME = gitea -USER = postgres +USER = gitea PASSWD = SCHEMA = SSL_MODE = disable diff --git a/gitea/docker-compose.yml b/gitea/docker-compose.yml new file mode 100644 index 0000000..076e95d --- /dev/null +++ b/gitea/docker-compose.yml @@ -0,0 +1,126 @@ +# ============================================================================= +# gitea/docker-compose.yml — Gitea and its database, on the Gitea LXC. +# +# WHAT IT DOES +# Runs the self-hosted git server (also the Actions server and the image +# registry) and a Postgres that holds nothing but Gitea's database. It does +# NOT run on stpvm: it runs in its own Proxmox LXC, so a bad deploy of the +# site stack, a site Postgres problem or load on stpvm cannot take down the +# git server and CI you would use to fix them. DEPLOYMENT.md §7, "Gitea +# LXC", is the runbook (setup, upgrade, backup, rollback). +# +# WHEN IT RUNS +# By hand, on the LXC, from this directory: +# cd ~/deploy/web_server/gitea && git pull && docker compose up -d +# Deliberately NOT by CI. The runner that would deploy it lives on stpvm and +# deploys stpvm; letting CI redeploy the server CI itself runs on is the +# coupling this split exists to remove. A Renovate PR that bumps the image +# below is therefore deployed by hand here after it merges. +# +# HOW THE SITE REACHES IT +# stpvm's stack keeps a `gitea` service, but it is a TCP forwarder +# (haproxy, gitea/forwarder.cfg) pointed at this host's LAN IP. So the Caddy +# routes, the registry at /v2/, the backend's activity feed, usaco's pulls, +# and everything on stpvm that says localhost:3000 or localhost:2222 (the +# runner, every repo's CI, Renovate, the obsidian checkout) still work +# unchanged. Clients on the tailnet can also use this host's own name. +# +# ENV VARS +# Read from ./.env in THIS directory (gitea/.env, gitignored), not the +# site's .env. gitea/.env.example lists them. +# ============================================================================= + +volumes: + # PERSISTENT: Gitea's relational data (users, issues, PRs, Actions runs, + # registry metadata). The git objects themselves are in ./data. Back the two + # up together: Proxmox's vzdump of the whole LXC does that. + gitea_db: + +services: + # Postgres 16, the same major as the site's `db`, so the pg_dump taken + # there restores here with no surprises. Owned by its own `gitea` role, and + # POSTGRES_DB means the image creates the database on first init (it had to + # be created by hand in the shared instance). + gitea-db: + image: postgres:16 + container_name: gitea-db + restart: always + environment: + - POSTGRES_USER=${GITEA_DB_USER:-gitea} + - POSTGRES_PASSWORD=${GITEA_DB_PASSWORD} + - POSTGRES_DB=${GITEA_DB_NAME:-gitea} + volumes: + - gitea_db:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER}"] + interval: 10s + timeout: 5s + retries: 10 + start_period: 30s + + # ROOTLESS image: runs as an unprivileged user, so config lives in /etc/gitea + # and data in /var/lib/gitea (not /data as in the root image) — that is why + # the bind mounts look unlike most Gitea compose examples. + # + # The GITEA__section__KEY environment convention is Gitea's own: each maps to + # an app.ini key and overrides the file at runtime, which is how the secrets + # stay in .env instead of in the committed app.ini.template. + # + # entrypoint is overridden to run our wrapper (which materialises app.ini + # from the template on first boot) before handing off to Gitea's real + # docker-entrypoint.sh. dumb-init is kept as PID 1 for correct signal/zombie + # handling, exactly as the stock image does it. + gitea: + image: docker.gitea.com/gitea:1.25.4-rootless + container_name: gitea + entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"] + environment: + - GITEA__database__DB_TYPE=postgres + - GITEA__database__HOST=gitea-db:5432 + - GITEA__database__NAME=${GITEA_DB_NAME:-gitea} + - GITEA__database__USER=${GITEA_DB_USER:-gitea} + - GITEA__database__PASSWD=${GITEA_DB_PASSWORD} + - GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET} + - GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN} + - GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET} + # The name Gitea prints in SSH clone URLs: a tailnet MagicDNS name, since + # 2222 is not reachable from the internet. Blank means localhost. + - GITEA__server__SSH_DOMAIN=${GITEA_SSH_DOMAIN:-localhost} + - GITEA__server__DOMAIN=${GITEA_SSH_DOMAIN:-localhost} + # Webhooks are refused to private addresses by default ("external"). + # The usaco site's push hook goes to https://www.DOMAIN/usaco/..., which + # extra_hosts below sends to stpvm's Caddy on the LAN, a private address, + # so that one name is allowed explicitly. + - GITEA__webhook__ALLOWED_HOST_LIST=external,www.${DOMAIN} + - USER_UID=1000 + - USER_GID=1000 + # Webhooks to the site go straight to Caddy on stpvm over the LAN rather + # than out through Cloudflare and back down the tunnel. Caddy still + # terminates TLS with the real certificate, so the name has to be the + # public one. The container does not read the LXC's /etc/hosts, hence here. + extra_hosts: + - "www.${DOMAIN}:${EDGE_IP}" + restart: always + volumes: + # PERSISTENT: repositories, LFS objects, avatars, sessions, the SSH host + # key, registry blobs. The git data itself. + - ./data:/var/lib/gitea + # PERSISTENT: app.ini is generated into this host directory on first boot + # and then edited by Gitea itself, so it is gitignored — only the + # template is committed. + - ./config:/etc/gitea + # Mounted over the config dir so the wrapper script is available at the + # path the overridden entrypoint points at. + - ./entrypoint.sh:/etc/gitea/entrypoint.sh:ro + # Match the host's clock/zone so commit and CI timestamps are local time. + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + ports: + # 2222 = Gitea's *built-in* SSH server (the rootless image cannot use 22). + # 3000 = HTTP. Both are reached by stpvm's forwarder over the LAN and by + # tailnet clients directly; neither is forwarded by the router. + - "2222:2222" + - "3000:3000" + depends_on: + gitea-db: + condition: service_healthy diff --git a/gitea/entrypoint.sh b/gitea/entrypoint.sh index 2b72cd9..970956d 100755 --- a/gitea/entrypoint.sh +++ b/gitea/entrypoint.sh @@ -17,15 +17,15 @@ # it to re-seed, which loses any UI-made settings). # # WHEN IT RUNS -# Container start. docker-compose.yml overrides gitea's entrypoint to +# Container start. gitea/docker-compose.yml overrides gitea's entrypoint to # ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"], keeping dumb-init # as PID 1 for signal handling exactly as the stock image does, and inserting # this script ahead of Gitea's own docker-entrypoint.sh. # # WHERE THE SECRETS ACTUALLY COME FROM -# Not from the template. docker-compose.yml passes GITEA__section__KEY +# Not from the template. gitea/docker-compose.yml passes GITEA__section__KEY # environment variables (database credentials, LFS_JWT_SECRET, -# INTERNAL_TOKEN, OAUTH2 JWT_SECRET) sourced from ./.env; Gitea applies those +# INTERNAL_TOKEN, OAUTH2 JWT_SECRET) sourced from gitea/.env; Gitea applies those # over whatever app.ini says. That is why the template can safely ship with # those fields empty. # diff --git a/gitea/forwarder.cfg b/gitea/forwarder.cfg new file mode 100644 index 0000000..9ca6880 --- /dev/null +++ b/gitea/forwarder.cfg @@ -0,0 +1,50 @@ +# ============================================================================= +# gitea/forwarder.cfg — haproxy config for the `gitea` service on stpvm. +# +# Gitea itself runs in its own LXC (gitea/docker-compose.yml). This forwards +# stpvm's Gitea ports to it, unchanged, at the TCP level: +# :3000 HTTP — Caddy's /gitea/ and /v2/ routes, the backend's activity +# feed and usaco's pulls reach it as gitea:3000 on +# app-network; the runner and Renovate as localhost:3000. +# :2222 SSH — every repo's CI (ssh://git@localhost:2222), the obsidian +# checkout and silverbullet-git (DOMAIN:2222, pinned to this +# host), and laptops using stpvm's tailnet name. +# So nothing that talked to Gitea on stpvm had to change address. +# +# TCP mode, not HTTP: the bytes are passed through untouched, so Caddy's +# X-Forwarded-For still reaches Gitea (which trusts one hop of it), SSH just +# works, and there is no second body-size limit on registry uploads. +# +# GITEA_UPSTREAM is the LXC's LAN IP, set in the site's .env. An IP and not a +# name: Docker's DNS cannot see tailnet or LAN names. +# ============================================================================= +global + log stdout format raw local0 notice + +defaults + mode tcp + log global + option tcplog + timeout connect 5s + # Inactivity timeouts, not total ones. A large clone or image layer upload + # keeps bytes moving; an idle `git` waiting on a slow server-side pack + # should not be cut off at a minute, so these are generous. + timeout client 1h + timeout server 1h + # Start even if the upstream does not resolve yet (dev has no Gitea at + # all); connections then fail rather than the container. + default-server init-addr last,libc,none + +frontend http + bind :3000 + default_backend gitea_http + +frontend ssh + bind :2222 + default_backend gitea_ssh + +backend gitea_http + server gitea "${GITEA_UPSTREAM}:3000" + +backend gitea_ssh + server gitea "${GITEA_UPSTREAM}:2222"