Files
term_portal/dev/ci/README.md
T

353 lines
18 KiB
Markdown

# CI/CD — pipeline internals
This directory holds the runner-side scripts the Gitea Actions workflows in
`.gitea/workflows/` call:
- `build.sh` — `docker buildx` build + push of the three custom images, with registry layer cache.
- `promote.sh` — retag an already-built image set to a new tag (no rebuild), for staging→prod promotion.
- `deploy.sh` — runner side: SSH the target host the tag to deploy (nothing more).
- `ci-deploy-wrapper.sh` — host side: the forced command that validates the tag and runs
`git checkout` + `run-prod.sh pull` + `up -d`.
The end-to-end pipeline (what triggers what, the registry model, rollback) is documented in the
main [README](../../README.md#automated-deployment-cicd). This file covers two operational tasks in
depth: **standing up the runner on a build host**, and **hardening deploy access** to each host.
## Setting up the Gitea Runner on a VPS
The runner formerly known as `act_runner` was rebranded to **Gitea Runner** at the runner project's
own **v1.0.0** (separate versioning from the Gitea *server*). Use the `gitea/runner` image;
`gitea/act_runner` still works but is deprecated.
Pick a build host that is **not** your public production server but has Docker, disk, and internet
(the concordancer build downloads a large lexicon). Our own choice is the private ~24/7 VPS. The
runner needs **outbound HTTPS** to Gitea, and later **outbound SSH** to the deploy targets.
### 0. Prerequisites (on the VPS)
```bash
docker --version && docker ps # Docker present, your user can reach the daemon
```
### 1. Get a registration token
In Gitea: **repository → Settings → Actions → Runners → Create new runner**. Note your Gitea URL
and the (single-use, short-lived) **registration token**. Using the *repo's* runner page — not the
admin/org one — makes the runner **repo-scoped**, so no Gitea admin access is needed.
### 2. Create the runner (Docker Compose)
```bash
sudo mkdir -p /opt/gitea-runner/data
cd /opt/gitea-runner
```
`/opt/gitea-runner/docker-compose.yml`:
```yaml
services:
runner:
image: gitea/runner:latest # NOT gitea/act_runner (deprecated)
restart: always
environment:
GITEA_INSTANCE_URL: https://gitea.example.tld # ← your Gitea
GITEA_RUNNER_REGISTRATION_TOKEN: "PASTE_TOKEN_HERE" # ← from step 1
GITEA_RUNNER_NAME: vps-builder
# Maps the `self-hosted` label our workflows target to an image that already
# ships git, node, docker CLI and ssh.
GITEA_RUNNER_LABELS: "self-hosted:docker://catthehacker/ubuntu:act-latest"
volumes:
- ./data:/data
- /var/run/docker.sock:/var/run/docker.sock # jobs run docker/buildx on the host daemon
```
Two details that matter for this pipeline:
- `self-hosted:docker://…` runs each job inside that image, which supplies `node` (required by
`actions/checkout`) plus `git`, `docker`, `ssh`.
- The socket mount is what lets the `docker buildx` / `docker login` calls in `build.sh` and
`promote.sh` reach a real daemon.
### 3. Start and confirm registration
```bash
docker compose up -d
docker compose logs -f
```
Wait for `runner registered successfully` → `waiting for tasks…`. The token is now consumed; the
runner identity persists in `./data/.runner`. To re-register later, wipe `./data` and use a fresh
token.
### 4. Confirm in Gitea
Back on **Settings → Actions → Runners**, `vps-builder` should show **Idle / online** (green) with
the `self-hosted` label.
> **Binary / systemd alternative.** Instead of Docker, fetch the `gitea/runner` release binary and
> run `./runner register --no-interactive --instance <url> --token <token> --name vps-builder
> --labels "self-hosted:host"` then `./runner daemon`. Simpler socket story, but the VPS itself must
> then have `git`, `node`, `docker`, and `ssh` installed, since jobs won't inherit them from an image.
## Smoke tests
**A — online status (step 4).** Green = registration + Gitea↔runner networking are good.
**B — it claims a job and has the toolchain (the real test).** On a scratch branch add
`.gitea/workflows/smoke.yml`, push it, watch the **Actions** tab, then delete it:
```yaml
name: smoke
on: [push]
jobs:
check:
runs-on: [self-hosted]
steps:
- uses: actions/checkout@v4
- run: |
git --version && node --version && ssh -V
docker version && docker buildx version
docker ps # proves the socket mount reaches the host daemon
echo OK
```
Green proves the runner runs jobs, `checkout` works, and `docker`/`buildx`/`ssh` + host socket are
all present — exactly what `build.sh`, `promote.sh`, and `deploy.sh` rely on.
**C — registry push path (optional, once `REGISTRY_TOKEN` is set).** Validates registry auth
**and** the buildx `docker-container` cache driver together — the two things most likely to bite:
```yaml
- run: |
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login gitea.example.tld -u "${{ github.actor }}" --password-stdin
docker buildx create --name ci --driver docker-container --use 2>/dev/null || docker buildx use ci
printf 'FROM alpine\nRUN echo hi\n' > /tmp/Dockerfile
docker buildx build -f /tmp/Dockerfile -t gitea.example.tld/<owner>/smoke:test --push /tmp
```
Notes learned the hard way (validated against a real Gitea instance):
- **`REGISTRY_TOKEN`, not the automatic `GITEA_TOKEN`.** The auto token is repo-scoped and returns
`unauthorized` at the registry; you need a PAT with `write:package`.
- **The registry ignores the username** — it authenticates on the token alone, so `github.actor`
is safe (works whoever triggers the run).
- **Don't add a job-level `permissions:` block** — on Gitea it becomes a complete allow-list and
drops `contents: read`, breaking `actions/checkout` with `Repository not found`.
- **`<owner>` must be lowercase** — OCI repository paths reject uppercase, so a mixed-case Gitea
org/user (e.g. `Amebis`) must be lowercased (`amebis`). The real workflows do this in their
`meta` step via `${owner,,}`.
## Troubleshooting quick hits
- **Never turns green:** wrong `GITEA_INSTANCE_URL`, blocked outbound 443, or a reused token
(regenerate, wipe `./data`, retry) — check `docker compose logs`.
- **`docker ps` fails in-job / permission denied:** socket mount missing or host socket perms too tight.
- **`--cache-to type=registry` errors:** the default docker driver doesn't support registry cache —
that's why the workflow creates the `docker-container` builder first.
- **Config errors on first `up`:** verify env var names against the current `gitea/runner` docs and
`docker run --rm gitea/runner:latest --help`.
## Hardened deploy access
Gitea Actions secrets are **encrypted, not hashed** — they must be decryptable to be injected into
jobs. So the SSH private key you store is recoverable by anyone holding the Gitea server's
`SECRET_KEY` (a Gitea admin) and by anyone with write access to this repo (a workflow can print a
secret). You cannot hide it. The strategy is instead: **expose a key that is worth as little as
possible and is trivial to revoke.** Three measures, in priority order.
### 1. A dedicated CI keypair (do this)
Never put your personal key in Gitea. Generate a passphraseless key used only by this pipeline, so
a leak is revoked in isolation:
```bash
ssh-keygen -t ed25519 -f ci_deploy_key -N "" -C "gitea-ci-deploy"
# private half (ci_deploy_key) -> Gitea secret STAGING_SSH_KEY / PROD_SSH_KEY
# public half (ci_deploy_key.pub) -> the deploy user's authorized_keys on each host (step 3)
```
Paste the **entire** `ci_deploy_key` file into `STAGING_SSH_KEY` / `PROD_SSH_KEY` — **including**
the `-----BEGIN OPENSSH PRIVATE KEY-----` and `-----END OPENSSH PRIVATE KEY-----` lines and the
trailing newline. Stripping the armor lines makes the key unparseable (`error in libcrypto` /
`invalid format` at deploy time).
### 2. A dedicated `deploy` user per host
Keeps automation out of your personal account → clean audit logs and clean revocation (delete the
user, the access is gone). It needs Docker, which means the `docker` group — and **docker group ≈
root**, so this is about isolation/auditability, not privilege reduction.
```bash
export DEPLOY_USER=deploy # the account these steps create — pick your own
export DEPLOY_DIR=/opt/termportal-prod # this host's repo checkout path — pick your own
sudo adduser --disabled-password --gecos "" "$DEPLOY_USER" # no password login (key/console only)
sudo usermod -aG docker "$DEPLOY_USER" # lets it run docker/compose without sudo
export DEPLOY_HOME="$(getent passwd "$DEPLOY_USER" | cut -d: -f6)" # its home, e.g. /home/deploy
```
> `DEPLOY_USER`, `DEPLOY_DIR`, and `DEPLOY_HOME` live in **this admin shell**. The commands below run
> as the deploy user via `sudo -H -u "$DEPLOY_USER"` — your shell expands these vars *before* the
> user switch, and `-H` sets the deploy user's `$HOME` so git/docker write their credentials under
> that account, not yours.
> **This host involves two credentials — don't mix them up:**
> - the **CI SSH key** from step 1 (runner → this host): its *public* half goes into the deploy
> user's `authorized_keys` in step 3; its private half is the Gitea secret.
> - a **read-only PAT** (this host → Gitea, over HTTPS): lets the deploy user `clone`/`fetch` the
> repo **and** `docker pull` images. Created just below.
**Create one read-only token** for the deploy user in Gitea → **Settings → Applications → Generate
New Token**, with scopes **`read:repository`** + **`read:package`** (older Gitea: `repo` + `package`
read). One token covers both git and the registry, so there's a single low-value credential to
rotate.
**Clone the repo over HTTPS** to this host's checkout path, owned by the deploy user (`/opt` needs
root just to create the directory):
```bash
sudo mkdir -p "$DEPLOY_DIR"
sudo chown "$DEPLOY_USER:$DEPLOY_USER" "$DEPLOY_DIR"
sudo -H -u "$DEPLOY_USER" git config --global credential.helper store # cache creds in ~deploy/.git-credentials (mode 600)
sudo -H -u "$DEPLOY_USER" git clone https://gitea.example.tld/<owner>/<repo>.git "$DEPLOY_DIR"
# Username: <your-gitea-user>
# Password: <the read PAT> -> stored, so the wrapper's `git fetch` runs non-interactively later
```
**Place host-only files and log in to the registry** as the deploy user, reusing the same token:
```bash
sudo -H -u "$DEPLOY_USER" cp "$DEPLOY_DIR/dev/.env" "$DEPLOY_DIR/.env"
sudo -H -u "$DEPLOY_USER" "${EDITOR:-nano}" "$DEPLOY_DIR/.env" # fill in real secrets, incl. the REGISTRY line (gitea.example.tld/<owner-lowercase>)
# optional per-host tweaks:
# sudo -H -u "$DEPLOY_USER" cp "$DEPLOY_DIR/docker-compose.prod.override.example.yml" "$DEPLOY_DIR/docker-compose.prod.override.yml"
sudo -H -u "$DEPLOY_USER" docker login gitea.example.tld -u <your-gitea-user> # paste the SAME read PAT at the prompt
```
`.env` and `docker-compose.prod.override.yml` are gitignored, so the deploy-time `git checkout`
never touches them. The stored git credential and the cached `docker login` (in the deploy user's
`~/.git-credentials` and `~/.docker/config.json`, both mode 600) let deploy-time `git fetch` and
`docker pull` run without prompts.
`docker login` prints a "credentials are stored unencrypted … Configure a credential helper"
warning — that's expected and fine here: the value is a read-only `read:package` token in a
mode-600 file under a dedicated account. A credential helper isn't worth the `pass`/GPG or
secret-service plumbing on a headless host.
> **SSH instead of HTTPS (only if your Gitea has SSH enabled).** If the instance allows it, you can
> use a read-only **Deploy Key** rather than a PAT for git: as the deploy user,
> `ssh-keygen -t ed25519 -f ~/.ssh/gitea_ro -N ""`, add the `.pub` under repo → Settings → Deploy
> Keys (write access off), add a `Host` stanza in `~/.ssh/config` pointing at `gitea_ro`, and clone
> `git@gitea.example.tld:<owner>/<repo>.git`. You'd still need a `read:package` token for
> `docker login`. If Deploy Keys show "SSH Disabled", the admin has turned SSH off instance-wide —
> use the HTTPS path above.
### 3. Pin the key to a forced command (this is what shrinks a leaked key)
Install the wrapper **outside the git checkout** (so `git checkout` never rewrites the running
script) and tell it this host's checkout path:
```bash
sudo -u "$DEPLOY_USER" cp "$DEPLOY_DIR/dev/ci/ci-deploy-wrapper.sh" "$DEPLOY_HOME/ci-deploy-wrapper.sh"
sudo -u "$DEPLOY_USER" chmod 755 "$DEPLOY_HOME/ci-deploy-wrapper.sh"
echo "DEPLOY_DIR=$DEPLOY_DIR" | sudo -u "$DEPLOY_USER" tee "$DEPLOY_HOME/ci-deploy.conf" # the wrapper reads this
```
Then add the pinned CI key to the deploy user's `authorized_keys`. Open it in an editor (creating
the `.ssh` dir first if needed) — that way you can paste the key now and reopen the same file to add
`from=` later:
```bash
sudo -u "$DEPLOY_USER" install -d -m 700 "$DEPLOY_HOME/.ssh"
sudo -H -u "$DEPLOY_USER" "${EDITOR:-nano}" "$DEPLOY_HOME/.ssh/authorized_keys"
```
Paste the CI **public** key as one line, prefixed with the forced-command options. The paths here
are **literal** (`authorized_keys` doesn't expand variables), so use the deploy user's real home for
`command=` — print it with `echo "$DEPLOY_HOME"`. Leave `from=` off for now (you add it once you
know the runner's source IP — see *Verify it*):
```
restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA...CI-public-key... gitea-ci-deploy
```
Later, reopen the file with the same editor command and prepend `from="<source>",`:
```
from="<source>",restrict,command="/home/deploy/ci-deploy-wrapper.sh" ssh-ed25519 AAAA...CI-public-key... gitea-ci-deploy
```
- `command="…"` — a **forced command**: this key can *only* run the wrapper. The tag the runner
sends arrives as `$SSH_ORIGINAL_COMMAND`; the wrapper allow-lists it to `[A-Za-z0-9._-]`, so even
a fully compromised Gitea/workflow can at most deploy some existing tag — never a shell.
- `from="<source>"` — the key works only from the address the **target's** `sshd` sees for the
runner's connection, so a leaked key is useless elsewhere. That address depends on topology:
- **Runner reaches this host over the network** (e.g. remote prod): it's the runner's public
egress IP — `curl -s ifconfig.me` from the runner.
- **Runner and this host are the same machine** (e.g. co-located staging): jobs run in a
container, so `sshd` sees a Docker-network address, not the public IP — and it can vary per
job, so pin the subnet, e.g. `from="172.16.0.0/12"`. (`DEPLOY_HOST` for such a host must also
be an address the container can reach — its routable IP, **not** `127.0.0.1`.)
When unsure, read the real value from the target after one test connection (see *Verify it*):
`sudo journalctl -u ssh | grep Accepted` (or `/var/log/auth.log`) shows `… from <IP> …`.
- `restrict` — no PTY, no port/agent forwarding, nothing but the command.
Because you can't make the key un-leakable, keep rotation cheap: to revoke, delete the
`authorized_keys` line (and/or the `deploy` user) and replace the Gitea secret with a fresh key.
### Verify it
The private key lives in the Gitea secret, so drive the checks from the runner via the
**`deploy-dispatch`** workflow (Actions → Run workflow), not a local `ssh`.
1. **Probe — no deploy.** Run `deploy-dispatch` with `environment` set to this host and
`image_tag = probe/invalid` (any character outside `[A-Za-z0-9._-]`). The job **should go red at
the deploy step, and that is the pass**: the key authenticates, then the wrapper refuses the
invalid tag *before* any `git fetch`/`pull`/`up`, so nothing deploys — one run verifies both auth
and the allow-list lock.
2. **Read the source IP** the target saw and pin it in `from=` (reopen `authorized_keys` with the
editor command above; use the subnet CIDR if it's a per-job Docker address):
```bash
sudo journalctl -u ssh | grep 'Accepted publickey' | tail -1 # -> ... from <IP> port ...
```
3. **Full path.** When you actually want to deploy, run `deploy-dispatch` with a **valid** existing
tag (e.g. a `sha-…` already in the registry) to exercise checkout → pull → `up -d`.
> **Stronger option if the admin threat is the real concern.** All of the above still exposes the
> key to the Gitea admin. If that is unacceptable, switch to **pull-based** deploy: the host pulls
> images itself (a cron or webhook running the wrapper), and Gitea holds only a read-only registry
> token — far lower value than an SSH key into prod. More setup, but no deploy key in Gitea at all.
## Registry retention
Every push to the default branch mints three `sha-<short>` image tags (one per service), forever —
so without a policy the registry grows unbounded. The `v*` release tags grow slowly and are
meaningful, and `buildcache` is a single tag that is *overwritten* each build (it doesn't pile up).
So the only thing worth pruning is **old `sha-*` tags**.
Use Gitea's built-in package **Cleanup Rules** (no scripting; runs on Gitea's package-cleanup cron):
org → **Settings → Packages → Cleanup Rules → Add Cleanup Rule** (needs org-owner access). Recommended:
| Field (labels vary slightly by Gitea version) | Value |
|---|---|
| Package type | **Container** |
| Keep the most recent | **10** |
| Remove versions older than | **30 days** |
| **Keep** versions matching (regex) | `^(v.*\|buildcache\|latest)$` |
| **Remove** versions matching (regex) | `^sha-` |
A version is deleted only if it matches **Remove** (`^sha-…`), is **not** among the 10 newest, is
older than 30 days, **and** doesn't match **Keep** — the patterns match the full tag name. Rationale:
- **`v*` kept forever** — release tags are rollback targets; never let one you might revert to be
reaped. The `Keep` pattern protects them absolutely.
- **`buildcache` kept** — it warms rebuilds (notably the ~5-min concordancer); pruning it just makes
the next build cold.
- **`sha-*` bounded** — keeping ~10 recent (and anything under 30 days) still lets you roll a few
commits back while capping growth. Tune the two numbers to how often you deploy.
- **`Remove` restricted to `^sha-`** — belt-and-suspenders so the rule can only ever touch CI
artifacts, never a release or the cache.
Caveat: a container tag also has underlying `sha256:…` manifest entries. `^sha-` doesn't match
`sha256:…`, so after the first cleanup run, check the package list — if orphaned `sha256:` digests
visibly accumulate, revisit it (carefully; don't delete a digest a kept tag still references).