Remove the admin panel's Environment tab and env-apply
.env is edited by hand again. Drops the /admin/env endpoints, EnvManager and its registry, the host-side apply.py watcher and its install script, the backend's env-apply bind mount, and the Environment tab. The deploy and maintenance workflows still serialise docker compose, now on .compose.lock in the checkout instead of env-apply/run/lock. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+7
-10
@@ -17,16 +17,13 @@
|
||||
# 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.
|
||||
# After changing a value on the Pi, recreate the services that read it:
|
||||
# docker compose up -d <service>.
|
||||
#
|
||||
# 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.
|
||||
# If the python or jobs service reads it, add it to that service's
|
||||
# `environment:` list in docker-compose.yml too, or the container never
|
||||
# receives it.
|
||||
#
|
||||
# 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,
|
||||
@@ -209,8 +206,8 @@ CLOUDFLARE_DNS_API_TOKEN=
|
||||
# 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.
|
||||
# (the default when blank) or claude-opus-5-5. Recreate the python service
|
||||
# to apply a change.
|
||||
CLAUDE_MODEL=
|
||||
STEAM_API_KEY=
|
||||
STEAM_ID=
|
||||
|
||||
@@ -87,9 +87,7 @@ jobs:
|
||||
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
|
||||
# The whole repo is mounted 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.
|
||||
@@ -172,10 +170,9 @@ jobs:
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
COMPOSE_BAKE: "false"
|
||||
# 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
|
||||
# The lock is shared with maintenance.yaml, so a deploy and the
|
||||
# weekly rebuild cannot run compose at the same time.
|
||||
run: flock .compose.lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker resources
|
||||
run: docker image prune -f
|
||||
|
||||
@@ -21,28 +21,26 @@ 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.
|
||||
# Both compose steps below take .compose.lock, the same flock
|
||||
# deploy.yaml holds while it runs compose. Without it this weekly
|
||||
# job could recreate containers while a deploy is mid-build, and
|
||||
# two `compose up`s racing over the same project can each recreate
|
||||
# a container the other just started. 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 a deploy 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: flock env-apply/run/lock docker compose pull
|
||||
run: flock .compose.lock docker compose pull
|
||||
|
||||
- name: Rebuild and restart containers
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
|
||||
run: flock .compose.lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker images
|
||||
run: docker image prune -af
|
||||
|
||||
+2
-3
@@ -9,9 +9,8 @@ usaco-data/
|
||||
.env
|
||||
.env.bak
|
||||
|
||||
# Admin panel -> host hand-off (request and status files, holds secrets)
|
||||
env-apply/run/*
|
||||
!env-apply/run/.gitkeep
|
||||
# flock taken by the deploy and maintenance workflows around docker compose
|
||||
.compose.lock
|
||||
|
||||
gitea/data/*
|
||||
gitea/config/app.ini
|
||||
|
||||
@@ -58,9 +58,9 @@ 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`. **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").
|
||||
**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`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
|
||||
|
||||
**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"]`.
|
||||
**Job tracker** (`jobs` service, `/jobs/`): the job application tracker, leads inbox, email pipeline and capture userscript now live in their own repo (`adamf/job-tracker` on Gitea) and run here as a published image, with their own Postgres database and role. It has no login: it asks the backend's `/auth/validate-admin` with the visitor's cookies. Nothing of it is left in `backend/`, `python/` or `vue/`; nginx redirects the old `/cv/jobs`, `/cv/leads` and userscript URLs to `/jobs/`. A push to that repo's `main` publishes the image and rolls this stack's `jobs` container onto it; pin `JOBS_IMAGE_TAG` in `.env` to hold a version. Its variables are passed through the `jobs` service's explicit `environment:` list in `docker-compose.yml`.
|
||||
|
||||
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (30/min, burst 20). Proxied routes are written once, in `nginx/nginx_routes.conf.template`, which both the production and dev configs include — add a new route there. Production-only pieces (TLS, static asset caching, the GraphQL rate-limit zone, security headers) stay in `nginx.conf.template`; a new rate-limit zone must be declared in both `http` blocks.
|
||||
|
||||
@@ -93,7 +93,7 @@ Dockerized multi-service personal website self-hosted on a Raspberry Pi.
|
||||
- **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`.
|
||||
- **Environment variables**: every variable goes in `.env.example`. One 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`, or the container never receives it. `.env` is edited by hand on the Pi (or synced with `sync-secrets.sh`); there is no admin-panel editor.
|
||||
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||
|
||||
|
||||
+10
-53
@@ -131,7 +131,7 @@ which has two jobs:
|
||||
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.
|
||||
`.compose.lock` flock, shared with the weekly maintenance workflow.
|
||||
|
||||
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
|
||||
@@ -227,7 +227,7 @@ cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
|
||||
The `cloudflared` container holds an outbound connection to Cloudflare and
|
||||
forwards requests for the site's hostnames down it to nginx. It is a
|
||||
_remotely managed_ tunnel: the only thing in this repo is the token
|
||||
(`CLOUDFLARE_TUNNEL_TOKEN`, editable from the Environment tab); hostnames and
|
||||
(`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and
|
||||
origin settings live in the dashboard.
|
||||
|
||||
**Origin: `https://www.<DOMAIN>`, the site's own name.** Cloudflare
|
||||
@@ -250,8 +250,8 @@ Setup, once:
|
||||
1. Cloudflare dashboard → the domain must be on Cloudflare DNS.
|
||||
2. Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared. Copy the
|
||||
token from the install command (the long string after `--token`).
|
||||
3. Put it in `.env` as `CLOUDFLARE_TUNNEL_TOKEN` (or set it from the
|
||||
Environment tab), then `docker compose up -d cloudflared`. The tunnel
|
||||
3. Put it in `.env` as `CLOUDFLARE_TUNNEL_TOKEN`, then
|
||||
`docker compose up -d cloudflared`. The tunnel
|
||||
shows as Healthy in the dashboard.
|
||||
4. Add a public hostname per name, each with service `HTTPS` and its own
|
||||
name as the URL, and no other settings:
|
||||
@@ -331,7 +331,6 @@ of deleting the directory:
|
||||
| `./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 | |
|
||||
@@ -366,8 +365,7 @@ makes the site's one Claude call (the rowing photo reader); the `jobs` container
|
||||
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.example`.
|
||||
|
||||
**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two
|
||||
things between this checkout and `adamf@stppi.local:~/deploy/web_server`:
|
||||
@@ -379,35 +377,12 @@ 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
|
||||
### Changing a value on the Pi
|
||||
|
||||
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.
|
||||
Edit `.env` (on the laptop, then `./sync-secrets.sh`; or on the Pi directly,
|
||||
then sync back), and recreate only the services that read the variable:
|
||||
`docker compose up -d <service>`. A plain `up -d` would also restart Postgres,
|
||||
since nginx, db, icecast2 and certbot load the whole file.
|
||||
|
||||
---
|
||||
|
||||
@@ -456,24 +431,6 @@ 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):
|
||||
|
||||
```
|
||||
|
||||
+4
-45
@@ -176,48 +176,7 @@ for the things GraphQL cannot do:
|
||||
| `/notes/*path` | streams a file download, not JSON |
|
||||
| `/ws` | WebSocket upgrade |
|
||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||
| `/admin/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.
|
||||
| `/admin/logs` | files on disk, not the data model |
|
||||
|
||||
## Calling the Python service
|
||||
|
||||
@@ -356,7 +315,7 @@ 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/` (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
|
||||
`CLAUDE_API_KEY` is not in the table: the backend does not read it. The
|
||||
`python` and `jobs` containers, the two that use it, get it through their
|
||||
explicit `environment:` lists in `docker-compose.yml`. The email and job-lead variables still in `.env` belong to the job
|
||||
tracker (`jobs`), which has its own repo and README.
|
||||
|
||||
@@ -10,8 +10,7 @@ import (
|
||||
|
||||
// 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).
|
||||
// the data model the GraphQL schema describes.
|
||||
|
||||
// logTailBytes and logTailLines bound how much of the log file one request
|
||||
// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
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())
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
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")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -38,10 +38,6 @@ type Store struct {
|
||||
// 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
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
|
||||
+1
-14
@@ -132,15 +132,7 @@ func main() {
|
||||
// and the GraphQL login mutation. Nginx rate-limits the login route too.
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
// 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}
|
||||
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}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
@@ -188,11 +180,6 @@ func main() {
|
||||
|
||||
// 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
|
||||
|
||||
@@ -1,377 +0,0 @@
|
||||
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}
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
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, the job and activity
|
||||
// trackers (images from their own repos, each with its own database role) and
|
||||
// the USACO site (an image from its own repo, with no database at all). 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", "activity-tracker", "usaco"}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
[
|
||||
{"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": "CLOUDFLARE_TUNNEL_TOKEN", "group": "Infrastructure", "purpose": "Cloudflare Tunnel the cloudflared container connects (hostnames are set in the Cloudflare dashboard)", "kind": "secret", "editable": true, "services": ["cloudflared"], "docsUrl": "https://one.dash.cloudflare.com/", "warning": "A wrong token takes the site offline for anyone reaching it through Cloudflare."},
|
||||
{"name": "CLOUDFLARE_DNS_API_TOKEN", "group": "Infrastructure", "purpose": "Lets certbot renew the TLS certificate over DNS instead of port 80 (Cloudflare API token, Zone: DNS: Edit). Blank uses the port-80 method", "kind": "secret", "editable": true, "services": ["certbot"], "docsUrl": "https://dash.cloudflare.com/profile/api-tokens"},
|
||||
{"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": "ACTIVITY_TRACKER_IMAGE_TAG", "group": "Infrastructure", "purpose": "Activity tracker image tag to run (default latest)", "kind": "text", "editable": false, "lockedReason": "Changing it needs a pull: docker compose pull activity-tracker && docker compose up -d activity-tracker."},
|
||||
{"name": "USACO_IMAGE_TAG", "group": "Infrastructure", "purpose": "USACO site image tag to run (default latest)", "kind": "text", "editable": false, "lockedReason": "Changing it needs a pull: docker compose pull usaco && docker compose up -d usaco."},
|
||||
{"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": "POSTGRES_TRACKER_DB", "group": "Database", "purpose": "Activity tracker database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on first install; see the ccp README."},
|
||||
{"name": "POSTGRES_TRACKER_USER", "group": "Database", "purpose": "Activity tracker database role", "kind": "text", "editable": false, "lockedReason": "Created by hand on first install; changing it here locks the activity tracker out."},
|
||||
{"name": "POSTGRES_TRACKER_PASSWORD", "group": "Database", "purpose": "Activity tracker database password", "kind": "secret", "editable": false, "lockedReason": "Set on the role by hand; changing it here locks the activity tracker out."},
|
||||
{"name": "USACO_GIT_TOKEN", "group": "USACO site", "purpose": "Gitea token (repository read and write on adamf/usaco) the site clones and pushes edits with", "kind": "secret", "editable": false, "lockedReason": "Made in Gitea (Settings, Applications); rotate it there, then set it here and run docker compose up -d usaco.", "docsUrl": "https://adam-french.co.uk/gitea/user/settings/applications"},
|
||||
{"name": "USACO_WEBHOOK_SECRET", "group": "USACO site", "purpose": "Shared secret of the usaco repo's Gitea push webhook", "kind": "secret", "editable": false, "lockedReason": "Must match the secret on the webhook in Gitea; change both together by hand."},
|
||||
{"name": "TRACKER_TZ", "group": "Activity tracker", "purpose": "Timezone where the activity tracker's day starts, e.g. Europe/London (blank is UTC)", "kind": "text", "editable": true, "services": ["activity-tracker"]},
|
||||
|
||||
{"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."}
|
||||
]
|
||||
+2
-6
@@ -223,10 +223,6 @@ 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).
|
||||
@@ -478,8 +474,8 @@ services:
|
||||
#
|
||||
# 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.
|
||||
# database role of its own. A variable the tracker reads must be added to
|
||||
# the list below as well as .env.example.
|
||||
#
|
||||
# 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
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
#!/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())
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/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"
|
||||
+3
-3
@@ -94,9 +94,9 @@ Their plumbing is in two places, shared by any route added later:
|
||||
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
|
||||
or `claude-sonnet-5-5` when it is blank. It is set in `.env` to one of
|
||||
`claude-haiku-4-5`, `claude-sonnet-5-5` and `claude-opus-5-5`; recreate this
|
||||
service after changing it. 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
|
||||
|
||||
@@ -22,12 +22,11 @@ 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.
|
||||
# Which model every call uses. CLAUDE_MODEL comes from .env; changing it means
|
||||
# recreating 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
|
||||
# The ids listed in .env.example are the ones 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.
|
||||
|
||||
@@ -76,17 +76,6 @@ def test_haiku_gets_the_plain_request(monkeypatch):
|
||||
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",
|
||||
|
||||
+1
-2
@@ -132,8 +132,7 @@ 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
|
||||
HTTP status for callers that need to branch on it. Any other option is
|
||||
passed to axios, so multipart bodies and `onUploadProgress` work unchanged.
|
||||
|
||||
### Which one to use
|
||||
|
||||
@@ -19,7 +19,6 @@ import CreatePlace from "./CreatePlace.vue";
|
||||
import ManagePages from "./ManagePages.vue";
|
||||
import ManageUsers from "./ManageUsers.vue";
|
||||
import ManageRadio from "./ManageRadio.vue";
|
||||
import Environment from "./Environment.vue";
|
||||
import Diagnostics from "./Diagnostics.vue";
|
||||
|
||||
const auth = useAuthStore();
|
||||
@@ -35,7 +34,6 @@ const sections = [
|
||||
{ id: "pages", label: "Pages", component: ManagePages },
|
||||
{ id: "users", label: "Manage Users", component: ManageUsers },
|
||||
{ id: "radio", label: "Manage Radio", component: ManageRadio },
|
||||
{ id: "environment", label: "Environment", component: Environment },
|
||||
{ id: "diagnostics", label: "Diagnostics", component: Diagnostics },
|
||||
];
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
* Admin panel: tail of the backend log.
|
||||
*
|
||||
* GET /api/admin/logs returns JSON read from the filesystem, not GraphQL —
|
||||
* it is not part of the site's data model. Configuration, which used to share
|
||||
* this tab, is on the Environment tab.
|
||||
* it is not part of the site's data model.
|
||||
*
|
||||
* An admin who remounts the component via tab switches re-triggers
|
||||
* onMounted, which is the desired "refresh on tab change" behaviour.
|
||||
|
||||
@@ -1,565 +0,0 @@
|
||||
<script setup>
|
||||
/**
|
||||
* Admin Environment tab: every variable in .env, grouped, with the ones that
|
||||
* are safe to change editable in place.
|
||||
*
|
||||
* Nothing here writes .env directly, and neither does the backend. Applying
|
||||
* sends the staged edits to PUT /api/admin/env, which queues them for a
|
||||
* script on the host (env-apply/apply.py) that rewrites the file and
|
||||
* recreates the containers that read the changed variables. This component
|
||||
* then polls GET /api/admin/env/status until the host reports back — through
|
||||
* the backend's own restart, which is why failed polls are expected and
|
||||
* ignored rather than shown.
|
||||
*
|
||||
* Secrets are write-only: the server sends "set" and at most the last four
|
||||
* characters, never the value. A generated secret is the one exception, shown
|
||||
* once from the response that created it.
|
||||
*/
|
||||
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
|
||||
import { api } from "@/api";
|
||||
import Button from "@/components/input/Button.vue";
|
||||
import SecretReveal from "@/components/admin/SecretReveal.vue";
|
||||
import ConfirmDialog from "@/components/util/ConfirmDialog.vue";
|
||||
import "./env.css";
|
||||
|
||||
const groups = ref([]);
|
||||
const status = ref(null);
|
||||
const error = ref("");
|
||||
const loading = ref(true);
|
||||
const applyConfirmationOpen = ref(false);
|
||||
const applyConfirmation = ref({ title: "Apply changes", message: "", confirmLabel: "Apply" });
|
||||
|
||||
// Staged edits, none of which exist anywhere but this component until Apply.
|
||||
// drafts: name -> text in the row's input
|
||||
// generating: names to have the server mint a value for
|
||||
// clearing: secrets to blank (a secret's empty input means "unchanged",
|
||||
// so clearing one needs saying explicitly)
|
||||
const drafts = reactive({});
|
||||
const generating = reactive(new Set());
|
||||
const clearing = reactive(new Set());
|
||||
|
||||
// Values the server generated in the last apply, shown once.
|
||||
const revealed = ref({});
|
||||
|
||||
const applying = ref(false);
|
||||
const outcome = ref(null); // { ok, text, output }
|
||||
const awaitedId = ref("");
|
||||
let pollTimer = null;
|
||||
|
||||
const allVars = computed(() => groups.value.flatMap((g) => g.vars));
|
||||
|
||||
function resetDrafts() {
|
||||
for (const v of allVars.value) drafts[v.name] = v.secret ? "" : v.value || "";
|
||||
generating.clear();
|
||||
clearing.clear();
|
||||
}
|
||||
|
||||
async function fetchEnv() {
|
||||
try {
|
||||
const res = await api.get("/admin/env", {
|
||||
fallback: "Failed to load the environment",
|
||||
});
|
||||
groups.value = res.groups;
|
||||
status.value = res.status;
|
||||
error.value = "";
|
||||
resetDrafts();
|
||||
} catch (err) {
|
||||
error.value = err.message;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// What a row would send: null when it is untouched.
|
||||
function changeFor(v) {
|
||||
if (!v.editable) return null;
|
||||
if (generating.has(v.name)) return { name: v.name, type: "generate" };
|
||||
if (clearing.has(v.name)) return { name: v.name, type: "clear" };
|
||||
const draft = (drafts[v.name] ?? "").trim();
|
||||
if (v.secret) return draft ? { name: v.name, type: "set", value: draft } : null;
|
||||
if (draft === (v.value || "")) return null;
|
||||
return { name: v.name, type: draft ? "set" : "clear", value: draft };
|
||||
}
|
||||
|
||||
const changes = computed(() =>
|
||||
allVars.value.map((v) => ({ v, change: changeFor(v) })).filter((c) => c.change),
|
||||
);
|
||||
|
||||
// Mirrors EnvManager.ServicesFor: the backend is always recreated.
|
||||
const affectedServices = computed(() => {
|
||||
const services = new Set(["backend"]);
|
||||
for (const { v } of changes.value)
|
||||
for (const s of v.services || []) services.add(s);
|
||||
return [...services].sort();
|
||||
});
|
||||
|
||||
const pendingNames = computed(() => new Set(status.value?.pending || []));
|
||||
|
||||
function toggleGenerate(v) {
|
||||
if (generating.has(v.name)) return generating.delete(v.name);
|
||||
generating.add(v.name);
|
||||
clearing.delete(v.name);
|
||||
drafts[v.name] = "";
|
||||
}
|
||||
|
||||
function toggleClear(v) {
|
||||
if (clearing.has(v.name)) return clearing.delete(v.name);
|
||||
clearing.add(v.name);
|
||||
generating.delete(v.name);
|
||||
drafts[v.name] = "";
|
||||
}
|
||||
|
||||
// Typing a value withdraws a staged generate or clear for the same row.
|
||||
function onInput(v) {
|
||||
generating.delete(v.name);
|
||||
clearing.delete(v.name);
|
||||
}
|
||||
|
||||
function pillFor(v) {
|
||||
if (changeFor(v)) return { text: "changed", cls: "is-changed" };
|
||||
if (pendingNames.value.has(v.name)) return { text: "pending", cls: "is-changed" };
|
||||
if (!v.set) return { text: "unset", cls: "is-unset" };
|
||||
if (v.secret) return { text: v.hint ? `set ••••${v.hint}` : "set", cls: "is-set" };
|
||||
return { text: "set", cls: "is-set" };
|
||||
}
|
||||
|
||||
async function apply() {
|
||||
const warnings = changes.value.filter((c) => c.v.warning).map((c) => `• ${c.v.warning}`);
|
||||
const lines = [
|
||||
`Apply ${changes.value.length} change(s)?`,
|
||||
`This recreates: ${affectedServices.value.join(", ")}. The site's API is unavailable for a few seconds.`,
|
||||
...warnings,
|
||||
];
|
||||
applyConfirmation.value = { title: "Apply environment changes", message: lines.join("\n"), confirmLabel: "Apply" };
|
||||
applyConfirmationOpen.value = true;
|
||||
}
|
||||
|
||||
async function confirmApply() {
|
||||
applyConfirmationOpen.value = false;
|
||||
|
||||
const body = { set: {}, generate: [] };
|
||||
for (const { change } of changes.value) {
|
||||
if (change.type === "generate") body.generate.push(change.name);
|
||||
else body.set[change.name] = change.type === "clear" ? "" : change.value;
|
||||
}
|
||||
|
||||
applying.value = true;
|
||||
outcome.value = null;
|
||||
try {
|
||||
const res = await api.put("/admin/env", body, {
|
||||
fallback: "Failed to queue the change",
|
||||
});
|
||||
revealed.value = res.generated || {};
|
||||
status.value = res.status;
|
||||
awaitedId.value = res.status.id;
|
||||
// Staged secrets have been sent; do not keep them in the inputs.
|
||||
resetDrafts();
|
||||
startPolling();
|
||||
} catch (err) {
|
||||
applying.value = false;
|
||||
outcome.value = { ok: false, text: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling();
|
||||
pollTimer = setInterval(poll, 2000);
|
||||
}
|
||||
function stopPolling() {
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
let next;
|
||||
try {
|
||||
next = await api.get("/admin/env/status");
|
||||
} catch (err) {
|
||||
// 401/403 after an apply means the change invalidated this session
|
||||
// (rotating BACKEND_SECRET does). Anything else is the backend
|
||||
// restarting, which is the apply working.
|
||||
if ([401, 403].includes(err.status)) {
|
||||
stopPolling();
|
||||
applying.value = false;
|
||||
outcome.value = {
|
||||
ok: true,
|
||||
text: "Applied. Your session was signed with the old secret — log in again.",
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
status.value = next;
|
||||
if (next.id !== awaitedId.value) return;
|
||||
if (next.state === "applied") {
|
||||
stopPolling();
|
||||
applying.value = false;
|
||||
outcome.value = {
|
||||
ok: true,
|
||||
text: `Applied. Recreated ${(next.services || []).join(", ")}.`,
|
||||
};
|
||||
await fetchEnv();
|
||||
} else if (next.state === "failed") {
|
||||
stopPolling();
|
||||
applying.value = false;
|
||||
outcome.value = { ok: false, text: "The host could not apply the change.", output: next.output };
|
||||
await fetchEnv();
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelPending() {
|
||||
try {
|
||||
status.value = await api.delete("/admin/env/pending", {
|
||||
fallback: "Failed to withdraw the change",
|
||||
});
|
||||
stopPolling();
|
||||
applying.value = false;
|
||||
outcome.value = { ok: true, text: "Pending change withdrawn. Nothing was applied." };
|
||||
} catch (err) {
|
||||
outcome.value = { ok: false, text: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
const progressText = computed(() => {
|
||||
const s = status.value;
|
||||
if (!s) return "";
|
||||
if (s.state === "pending") return "Queued — waiting for the host to pick it up…";
|
||||
if (s.state === "applying")
|
||||
return `Recreating ${(s.services || []).join(", ")}…`;
|
||||
return "";
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchEnv();
|
||||
// A change queued before this tab was opened is still worth following.
|
||||
if (["pending", "applying"].includes(status.value?.state)) {
|
||||
awaitedId.value = status.value.id;
|
||||
applying.value = true;
|
||||
startPolling();
|
||||
}
|
||||
});
|
||||
onUnmounted(stopPolling);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="env">
|
||||
<h1>Environment</h1>
|
||||
<p class="env-hint">
|
||||
The site's <code>.env</code>. Edits are staged here, then applied on the
|
||||
server, which restarts only the services that read what changed. Secrets
|
||||
can be replaced but never read back.
|
||||
</p>
|
||||
<p v-if="error" class="env-error">{{ error }}</p>
|
||||
<p v-if="loading" class="env-hint">Loading…</p>
|
||||
|
||||
<div v-if="Object.keys(revealed).length" class="env-revealed">
|
||||
<SecretReveal
|
||||
v-for="(value, name) in revealed"
|
||||
:key="name"
|
||||
:label="name"
|
||||
:value="value"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="applying" class="env-banner">
|
||||
<p>{{ progressText || "Applying…" }}</p>
|
||||
<template v-if="status?.state === 'pending' && !status.watcher">
|
||||
<p class="env-hint">
|
||||
Nothing on the host has picked this up. On the Pi, run
|
||||
<code>./env-apply/install.sh</code> once to install the watcher. To
|
||||
apply this change by hand, from the repo root:
|
||||
</p>
|
||||
<code class="env-command">python3 env-apply/apply.py</code>
|
||||
<Button class="px-2" @click="cancelPending">Withdraw change</Button>
|
||||
</template>
|
||||
</div>
|
||||
<div v-else-if="outcome" class="env-banner" :class="outcome.ok ? 'is-ok' : 'is-failed'">
|
||||
<p>{{ outcome.text }}</p>
|
||||
<pre v-if="outcome.output" class="env-output">{{ outcome.output }}</pre>
|
||||
</div>
|
||||
|
||||
<section v-for="group in groups" :key="group.name" class="env-card">
|
||||
<header class="env-card-head">
|
||||
<h2>{{ group.name }}</h2>
|
||||
<span class="env-hint">
|
||||
{{ group.vars.filter((v) => v.set).length }}/{{ group.vars.length }} set
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-for="v in group.vars"
|
||||
:key="v.name"
|
||||
class="env-row"
|
||||
:class="{ 'is-locked': !v.editable, 'is-dirty': !!changeFor(v) }"
|
||||
>
|
||||
<div class="env-meta">
|
||||
<div class="env-name">
|
||||
<code>{{ v.name }}</code>
|
||||
<span class="env-pill" :class="pillFor(v).cls">{{ pillFor(v).text }}</span>
|
||||
</div>
|
||||
<p class="env-hint">
|
||||
{{ v.purpose }}
|
||||
<a
|
||||
v-if="v.docsUrl && v.editable"
|
||||
:href="v.docsUrl"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="env-docs"
|
||||
>{{ v.secret ? "Get a key" : "Open" }} ↗</a
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="v.editable" class="env-control">
|
||||
<select
|
||||
v-if="v.kind === 'enum' || v.kind === 'bool'"
|
||||
v-model="drafts[v.name]"
|
||||
:disabled="applying"
|
||||
>
|
||||
<option value="">(unset)</option>
|
||||
<option
|
||||
v-for="option in v.kind === 'bool' ? ['true', 'false'] : v.options"
|
||||
:key="option"
|
||||
:value="option"
|
||||
>
|
||||
{{ option }}
|
||||
</option>
|
||||
</select>
|
||||
<template v-else>
|
||||
<input
|
||||
v-model="drafts[v.name]"
|
||||
:type="v.secret ? 'password' : 'text'"
|
||||
:placeholder="
|
||||
generating.has(v.name)
|
||||
? 'A new value will be generated'
|
||||
: clearing.has(v.name)
|
||||
? 'Will be cleared'
|
||||
: v.secret
|
||||
? v.set
|
||||
? 'Paste a replacement'
|
||||
: 'Paste a value'
|
||||
: ''
|
||||
"
|
||||
:disabled="applying"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
@input="onInput(v)"
|
||||
/>
|
||||
<Button
|
||||
v-if="v.kind === 'generated'"
|
||||
class="px-2"
|
||||
:class="{ 'is-on': generating.has(v.name) }"
|
||||
:disabled="applying"
|
||||
@click="toggleGenerate(v)"
|
||||
>
|
||||
{{ v.set ? "Regenerate" : "Generate" }}
|
||||
</Button>
|
||||
<Button
|
||||
v-if="v.secret && v.set"
|
||||
class="px-2"
|
||||
:class="{ 'is-on': clearing.has(v.name) }"
|
||||
:disabled="applying"
|
||||
@click="toggleClear(v)"
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</template>
|
||||
<p v-if="v.warning && changeFor(v)" class="env-warning">
|
||||
{{ v.warning }}
|
||||
</p>
|
||||
</div>
|
||||
<p v-else class="env-control env-locked" :title="v.lockedReason">
|
||||
<span v-if="!v.secret && v.set" class="env-value">{{ v.value }}</span>
|
||||
<span class="env-hint">🔒 {{ v.lockedReason }}</span>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<footer v-if="changes.length && !applying" class="env-apply-bar">
|
||||
<p>
|
||||
<strong>{{ changes.length }}</strong>
|
||||
{{ changes.length === 1 ? "change" : "changes" }} — recreates
|
||||
{{ affectedServices.join(", ") }}
|
||||
</p>
|
||||
<div class="env-apply-actions">
|
||||
<Button class="px-2" @click="resetDrafts">Discard</Button>
|
||||
<Button class="px-2 env-apply" @click="apply">Apply</Button>
|
||||
</div>
|
||||
</footer>
|
||||
<ConfirmDialog
|
||||
v-if="applyConfirmationOpen"
|
||||
v-model="applyConfirmationOpen"
|
||||
:title="applyConfirmation.title"
|
||||
:message="applyConfirmation.message"
|
||||
:confirm-label="applyConfirmation.confirmLabel"
|
||||
@confirm="confirmApply"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.env {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.env-revealed {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.env-banner {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--color-primary);
|
||||
background: var(--color-surface-tint);
|
||||
}
|
||||
.env-banner p {
|
||||
margin: 0;
|
||||
}
|
||||
.env-banner.is-failed {
|
||||
border-color: var(--color-error, #f87171);
|
||||
}
|
||||
.env-banner.is-failed > p {
|
||||
color: var(--color-error, #f87171);
|
||||
}
|
||||
.env-command {
|
||||
user-select: all;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.env-output {
|
||||
width: 100%;
|
||||
max-height: 200px;
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding: 6px;
|
||||
font-size: 0.75rem;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
color: var(--color-primary);
|
||||
background: var(--color-surface-deep);
|
||||
}
|
||||
|
||||
.env-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1.1fr);
|
||||
gap: 4px 12px;
|
||||
align-items: center;
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--color-quaternary);
|
||||
border-left: 2px solid transparent;
|
||||
}
|
||||
.env-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.env-row.is-dirty {
|
||||
border-left-color: var(--color-tertiary);
|
||||
background: var(--color-surface-tint);
|
||||
}
|
||||
.env-row.is-locked .env-meta {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.env-name {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.env-name code {
|
||||
font-size: 0.8rem;
|
||||
word-break: break-all;
|
||||
}
|
||||
.env-docs {
|
||||
margin-left: 4px;
|
||||
padding: 0 4px;
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.env-control {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
}
|
||||
.env-control input,
|
||||
.env-control select {
|
||||
flex: 1;
|
||||
min-width: 120px;
|
||||
padding: 3px 6px;
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-primary);
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-quaternary);
|
||||
}
|
||||
.env-control input:focus,
|
||||
.env-control select:focus {
|
||||
border-color: var(--color-primary);
|
||||
outline: none;
|
||||
}
|
||||
.env-control :deep(button.is-on) {
|
||||
color: var(--color-tertiary);
|
||||
border-color: var(--color-tertiary);
|
||||
}
|
||||
.env-control :deep(button:disabled),
|
||||
.env-control input:disabled,
|
||||
.env-control select:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.env-warning {
|
||||
flex-basis: 100%;
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
.env-locked {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 0;
|
||||
}
|
||||
.env-value {
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-primary);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
/* Stays in view while scrolling a long list of rows, so the count of staged
|
||||
changes and the Apply button are never off-screen. */
|
||||
.env-apply-bar {
|
||||
position: sticky;
|
||||
bottom: 8px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--color-tertiary);
|
||||
background: var(--color-surface);
|
||||
box-shadow: 0 0 12px var(--color-surface-deep);
|
||||
}
|
||||
.env-apply-bar p {
|
||||
margin: 0;
|
||||
}
|
||||
.env-apply-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.env-apply-actions :deep(.env-apply) {
|
||||
color: var(--color-surface-deep);
|
||||
background: var(--color-primary);
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.env-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,54 +0,0 @@
|
||||
/*
|
||||
* Card, pill and message styles for the admin Environment tab
|
||||
* (Environment.vue) and any card it hosts as a child component. A plain
|
||||
* stylesheet rather than a scoped block because scoped styles stop at a child
|
||||
* component's root; the env- prefix is what keeps these from leaking.
|
||||
*/
|
||||
.env-card {
|
||||
border: 1px solid var(--color-quaternary);
|
||||
background: var(--color-surface-deep);
|
||||
}
|
||||
.env-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 4px 10px;
|
||||
border-bottom: 1px solid var(--color-quaternary);
|
||||
background: var(--color-surface-tint);
|
||||
}
|
||||
.env-card-head h2 {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.env-pill {
|
||||
flex: none;
|
||||
padding: 0 8px;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 999px;
|
||||
font-size: 0.7rem;
|
||||
line-height: 1.5;
|
||||
white-space: nowrap;
|
||||
color: var(--color-muted);
|
||||
}
|
||||
.env-pill.is-set {
|
||||
color: var(--color-secondary);
|
||||
}
|
||||
.env-pill.is-unset {
|
||||
color: var(--color-muted);
|
||||
opacity: 0.6;
|
||||
}
|
||||
.env-pill.is-changed {
|
||||
color: var(--color-tertiary);
|
||||
}
|
||||
|
||||
.env-hint {
|
||||
margin: 0;
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.75;
|
||||
}
|
||||
.env-error {
|
||||
margin: 0;
|
||||
color: var(--color-error, #f87171);
|
||||
}
|
||||
Reference in New Issue
Block a user