Skip to content

Latest commit

 

History

History
359 lines (295 loc) · 19.5 KB

SECRETS.md

File metadata and controls

359 lines (295 loc) · 19.5 KB

Secrets

How the secrets of the stack are made, kept, restored and rotated. The runtime model is simple: eight files in the SECRETS_DIR directory of .env, generated on the host by make -C deploy secrets and given to the containers as Compose file secrets. This page adds what happens around them: where the off-host copy lives, how to restore it and how to rotate each secret.

No secret, encrypted or not, is ever committed: this repository is public and its history cannot be rotated.

In the commands below, dc is docker compose --project-directory deploy/compose --env-file deploy/compose/.env -f deploy/compose/compose.yaml -f deploy/compose/compose.prod.yaml, and every command runs as the service account, from the repository root. The make targets (secrets, secret-set, secrets-check) read SECRETS_DIR from .env (deploy/compose/secrets when it is unset), like Compose; a SECRETS_DIR= on the make command line wins. In the commands, $SECRETS_DIR is a shell variable set once per session with SECRETS_DIR=$(make -s -C deploy secrets-dir) (an absolute path on a production host).

1. Inventory

Secret Used by Generated by Needed to restore? Effect of rotating
pg_password PostgreSQL superuser (read by the image only to create the cluster), web, worker, beat make secrets (random, 48 bytes base64) Only if role passwords are restored from a dump; otherwise it can be regenerated and set in the database The role is changed inside PostgreSQL first, then the file, then the containers are recreated
elastic_password Elasticsearch elastic user, web, worker, beat make secrets No: the indexes are rebuilt (es reindex_database) Changed through the Elasticsearch security API first, then the file and the containers
django_secret_key web, worker, beat (sessions, password-reset links, IIIF tokens, invitation links) make secrets (secrets.token_urlsafe(64)) Optional: a new key logs everyone out Everyone is logged out; password-reset links, IIIF tokens and invitation links in flight stop working. Two-factor authentication is on: Arches stores each user's TOTP secret AES-encrypted with SECRET_KEY (UserProfile.encrypted_mfa_hash, arches/app/views/auth.py), so a new key makes every enrolled secret unreadable: the secrets are cleared before web serves sign-ins on the new key, then everyone re-enrols through the link the admin mails (section 6, ADMIN.md). Plan the rotation as a re-enrolment of every account, and do it only when the key leaked
email_password web, worker, beat (SMTP relay) make secrets creates it empty (relay without authentication) Yes, when the relay needs a password Changed at the mail provider, then the file
admin_password init and web only (make init, make admin-password) make secrets No: its hash comes back with the database; the vault is the reference Written to the file, then applied with make admin-password
restic_password the restic service only (profile backup: backups, restore test, restore) make secrets (random, 48 bytes base64) Yes, always: without it no backup can be read; it is the one secret that must be in the vault before any restore Not by rewriting the file: the repository holds the old key. Add the new key to the repository first (restic key add), then the file, then remove the old key (section 6)
grafana_admin_password the grafana service only (profile observability) make secrets (random, 48 bytes base64) No: Grafana keeps its own accounts in its volume; the vault is the reference Written to the file, then applied inside Grafana (grafana cli admin reset-admin-password, password through stdin)
pg_monitor_password the postgres-exporter service only (profile observability); the ms_monitor role make secrets (random, 48 bytes base64) No: regenerate and apply to the role Written to the file, then set on the role (monitoring-init) and the exporter recreated

restic_password is the key of the backup repository: every snapshot is encrypted with it, so it must live outside that repository, in the vault item of section 3. A restore on a new host reads the vault before anything else. For that reason the backup leaves restic_password out of the repository (the vault is its source of truth); every other file of SECRETS_DIR is in the snapshots. The full moving-day order and the backup procedures are in BACKUP.md.

2. Rules

  • Never in Git, even encrypted. A test (test_every_secret_is_documented) fails when a secret has no row above; another one ties the list to the Compose file.
  • No registry credential on the host: the application image is public on GHCR and is pulled anonymously by the release watch and the update (RELEASES.md, « On the host »). Never run docker login for it on a host.
  • Never in an argument list (ps), a log line, an error message or a clear-text backup. secret-set reads a value from the terminal or from stdin, and secrets-check prints names and problems, never values.
  • On the production host SECRETS_DIR is /srv/manuspectrum/secrets, outside the directories the provider's TSM client backs up by default (/etc, /home, /opt, /root, /var/log...): the checkout lives under /home, and a secret there would be copied in clear. Before make secrets, create the parent once: sudo install -d -o <account> -g <account> -m 0750 /srv/manuspectrum. The secrets stay in the encrypted restic repository and in the vault.
  • Only the service account reads SECRETS_DIR (directory 0700, files 0444 because several container uids read them: the directory mode is the barrier). Check it any time with make -C deploy secrets-check.

3. The vault item

The secrets exist on the host and nowhere else, so the off-host copy is a single entry in the project's password manager (Bitwarden):

  • One item per host, named ManuSpectrum <host> secrets, in an organization collection shared by the two administrators. Production and rehearsal each have their own item.
  • One hidden custom field per secret, named exactly like the file (pg_password, elastic_password, django_secret_key, email_password, admin_password, restic_password, grafana_admin_password, pg_monitor_password), holding the value without a trailing newline. An empty email_password is recorded as empty. No file attachment.
  • Fill it once, after the first make secrets: read each value as the service account (cat "$SECRETS_DIR/<name>", in a terminal nobody watches) and paste it into the field. Update the field after every rotation (section 6).
  • Access: exactly the two administrators, through the collection. Each administrator keeps the account's recovery code in their own safe place; it is the break-glass access if a person or a device is lost. A person who leaves is removed from the collection and the secrets are rotated (section 7).

4. Checking the files

make -C deploy secrets-check

One line per file: ok, or what is wrong (missing, mode other than 0444, trailing newline, empty, django_secret_key under 50 characters, admin_password under 16, restic_password under 32, grafana_admin_password under 16, pg_monitor_password under 32), then the directory mode (0700). Exit 1 on any problem. It never prints a value.

5. Restore on a new host

  1. make -C deploy secrets-check shows what is missing. The backup restore never writes SECRETS_DIR, and it needs restic_password to read any backup: set that file first from the vault item, before make secrets.

  2. Set each file from the vault item, one at a time (a copy of the directory is in the restic snapshots, restore-files can pull it for comparison):

    make -C deploy secret-set NAME=pg_password

    The value is typed twice without echo (or piped on stdin, one value, the trailing newline removed). Do the eight names; for email_password, press Enter twice when the relay needs no password. An existing file with another value is refused unless you add FORCE=yes; the same value is reported as kept, so a run can be repeated safely.

  3. make -C deploy secrets-check → eight ok. On a host that runs the monitoring (profile observability), once the stack is up, make -C deploy monitoring-init gives the restored ms_monitor role the password of pg_monitor_password (the dumps carry the role, not its password).

  4. Without the vault, make -C deploy secrets creates fresh values for the missing files. That is a new installation of the secrets, not a restore: pg_password and elastic_password then no longer match what the data volumes hold. PostgreSQL is aligned with the pg_password procedure of section 6 (the local socket asks for no password). For Elasticsearch use the recovery at the end of its section: the old password is not needed.

6. Rotation

Compose file secrets are bind mounts of the host files. The procedures replace a file with a new one, and a running container keeps the old content: every procedure ends with recreating the containers, which stops the site for a few minutes (announce it).

make -C deploy down up
deploy/compose/smoke.sh check     # only "ok:" lines

Then update the field of the vault item with the new value. Generate a new value into a .new file of the directory (0600, ignored by Git), copy it into the vault, apply it, and delete the .new file at the end.

django_secret_key

The two-factor secrets are cleared while only PostgreSQL runs, in the same maintenance window: web never serves a sign-in on the new key while a secret encrypted with the old one is still stored.

python3 -c 'import secrets; print(secrets.token_urlsafe(64), end="")' |
  make -C deploy secret-set NAME=django_secret_key FORCE=yes
make -C deploy down
dc up -d --wait postgres
make -C deploy manage ARGS='shell -c "from arches.app.models.models import UserProfile; print(UserProfile.objects.update(encrypted_mfa_hash=None))"'
make -C deploy manage ARGS='shell -c "from django.contrib.sessions.models import Session; Session.objects.all().delete()"'
make -C deploy up
deploy/compose/smoke.sh check

The first manage command clears every two-factor secret (it prints the number of profiles). The second clears the sessions signed with the old key: left in django_session, each one logs « Session data corrupted » whenever the anonymisation pass decodes it. (load-snapshot and restore clear them themselves.)

Everyone is logged out; reset links, IIIF tokens and invitation links in flight become invalid. A superuser then signs in, enrols again on account/two-factor when asked, and mails everyone their enrolment link: Users list, select every active account, Send the two-factor enrolment link (superuser) (ADMIN.md). Update the vault item, copying the value from "$SECRETS_DIR/django_secret_key".

pg_password

PostgreSQL reads POSTGRES_PASSWORD_FILE only when it creates the cluster, so the role is changed inside the database first. The new value reaches psql through stdin (printf is a shell builtin: nothing appears in ps), and the session turns statement logging off before ALTER ROLE.

[ -e "$SECRETS_DIR/pg_password.new" ] || ( umask 077; openssl rand -base64 48 | tr -d '\n' > "$SECRETS_DIR/pg_password.new" )
{ printf '\\set pw %s\n' "$(cat "$SECRETS_DIR/pg_password.new")"
  cat <<'SQL'
SET log_statement = 'none';
SET log_min_duration_statement = -1;
SET log_min_error_statement = panic;
ALTER ROLE :"user" PASSWORD :'pw';
SQL
} | dc exec -T postgres sh -c 'psql -v ON_ERROR_STOP=1 -v user="$POSTGRES_USER" -U "$POSTGRES_USER" -d postgres' &&
  make -C deploy secret-set NAME=pg_password FORCE=yes < "$SECRETS_DIR/pg_password.new" &&
  rm "${SECRETS_DIR:?}/pg_password.new" &&
  make -C deploy down up &&
  deploy/compose/smoke.sh check

$POSTGRES_USER is the superuser the application connects as (PGUSERNAME); the container's local socket does not ask for a password, so the old value is not needed. Until the containers are recreated the application still sends the old password: do the last four lines without delay. Check that the new value is not in the logs: dc logs postgres --since 10m | grep -cFf <(head -c 12 "$SECRETS_DIR/pg_password") → 0.

elastic_password

[ -e "$SECRETS_DIR/elastic_password.new" ] || ( umask 077; openssl rand -base64 48 | tr -d '\n' > "$SECRETS_DIR/elastic_password.new" )
printf '{"password":"%s"}' "$(cat "$SECRETS_DIR/elastic_password.new")" |
  dc exec -T elasticsearch sh -c 'curl -fsS -u "elastic:$(cat /run/secrets/elastic_password)" -H "Content-Type: application/json" -X POST http://localhost:9200/_security/user/elastic/_password --data-binary @-' &&
  make -C deploy secret-set NAME=elastic_password FORCE=yes < "$SECRETS_DIR/elastic_password.new" &&
  rm "${SECRETS_DIR:?}/elastic_password.new" &&
  make -C deploy down up &&
  deploy/compose/smoke.sh check

The call answers {}. The new value travels on stdin; the old one is in the curl arguments inside the Elasticsearch container only, as in its health check. The keystore password the image wrote at the first start no longer matters once the security index exists.

The .new file is generated only when absent and each step runs only when the one before succeeded, so the block can be run again after a failure without losing the value the service may already hold. Until the containers are recreated the health check reads the old mounted file and web/worker get 401: do the last four lines without delay.

If the mounted elastic_password no longer matches what Elasticsearch stores (secrets recreated without the vault, a failed rotation), the API call above answers 401. Reset the password through the file realm, which needs no old password, typing the value from the file when asked:

dc exec elasticsearch bin/elasticsearch-reset-password -u elastic -i   # interactive: no -T

Which value to type:

  • elastic_password.new exists (a rotation was under way): type its value, then run the last four lines of the block above (secret-set from the .new file, rm, down up, smoke.sh check);
  • otherwise (secrets recreated without the vault): type the value of the mounted elastic_password, then make -C deploy down up alone.

The alternative is a fresh es_data volume followed by es reindex_database (the index is rebuilt from the database).

email_password

Change it at the mail provider, then:

make -C deploy secret-set NAME=email_password FORCE=yes
make -C deploy down up
deploy/compose/smoke.sh check

admin_password

make -C deploy secret-set NAME=admin_password FORCE=yes
make -C deploy admin-password

Only a one-off container reads this file, so the stack is not recreated. Sign in as admin with the new password, then run deploy/compose/smoke.sh check. The vault is the reference for this account; if the password was changed from the profile page, the file no longer matches and the vault item is the only truth.

grafana_admin_password

Grafana reads GF_SECURITY_ADMIN_PASSWORD__FILE only when it creates its database; afterwards the password lives in the grafana_data volume. The file is rotated first, then the value is applied inside Grafana through stdin (--password-from-stdin, checked against the pinned image), then the container is recreated so the mounted file is the new one.

[ -e "$SECRETS_DIR/grafana_admin_password.new" ] || ( umask 077; openssl rand -base64 48 | tr -d '\n' > "$SECRETS_DIR/grafana_admin_password.new" )
make -C deploy secret-set NAME=grafana_admin_password FORCE=yes < "$SECRETS_DIR/grafana_admin_password.new" &&
  dc --profile observability exec -T grafana grafana cli admin reset-admin-password --password-from-stdin < "$SECRETS_DIR/grafana_admin_password.new" &&
  rm "${SECRETS_DIR:?}/grafana_admin_password.new" &&
  dc --profile observability up -d --force-recreate --no-deps grafana

Sign in through the SSH tunnel with the new password. The other Grafana users are untouched. Update the vault item. The password never appears in an argument list: it travels on stdin.

pg_monitor_password

The password of the ms_monitor role (pg_monitor membership, nothing else), read by postgres-exporter only. monitoring-init sets it on the role from the file through stdin, redacts any error that quotes the statement, and is idempotent, so the block can be run again after a failure.

[ -e "$SECRETS_DIR/pg_monitor_password.new" ] || ( umask 077; openssl rand -base64 48 | tr -d '\n' > "$SECRETS_DIR/pg_monitor_password.new" )
make -C deploy secret-set NAME=pg_monitor_password FORCE=yes < "$SECRETS_DIR/pg_monitor_password.new" &&
  rm "${SECRETS_DIR:?}/pg_monitor_password.new" &&
  make -C deploy monitoring-init &&
  dc --profile observability up -d --force-recreate --no-deps postgres-exporter

Until the exporter is recreated it still sends the old password and Prometheus shows the PostgreSQL target down: run the last two lines without delay. The web application is not touched. Update the vault item.

restic_password

A restic repository holds its master key encrypted by one or more passwords (keys). Rewriting the file alone would lock the repository: the old password is the only one it knows. Add the new key, switch the file, then remove the old key. The repository is mounted read-write by the restic service; run restic through it (the container sees RESTIC_PASSWORD_FILE and /repo).

[ -e "$SECRETS_DIR/restic_password.new" ] || ( umask 077; openssl rand -base64 48 | tr -d '\n' > "$SECRETS_DIR/restic_password.new" )
dc run --rm --no-deps -T -v "${SECRETS_DIR:?}/restic_password.new:/run/restic_new:ro" restic key add --new-password-file /run/restic_new &&
  make -C deploy secret-set NAME=restic_password FORCE=yes < "$SECRETS_DIR/restic_password.new" &&
  rm "${SECRETS_DIR:?}/restic_password.new"
dc run --rm --no-deps -T restic key list

key list marks the key in use with *. Remove the old key by its id, with the new file now in place:

dc run --rm --no-deps -T restic key remove <old id>

No stack is recreated: only one-off containers read this file. Update the vault item. If the file and the vault disagree, the vault is the truth; nothing in the repository can recover a lost password.

7. When to rotate

  • No periodic rotation: a password nobody has seen leave is not made safer by age (NIST SP 800-63B).
  • Someone with access to the host or to the vault item leaves: remove them from the collection and the host, then rotate all eight secrets with section 6 (about 15 minutes).
  • A secret leaks (pasted in a chat, printed in a log, committed): rotate that one at once.
  • A secret committed to Git: rotate it at once. Rewriting history does not help, the repository is public and forked. Then remove it from the tree. GitHub secret scanning alerts are the second source of this event.

8. Scanning

  • Startup guard. web and init run manage.py check --deploy --tag security --fail-level WARNING before anything else and refuse to start on any warning (a weak or development SECRET_KEY among them).
  • Before a commit. pre-commit install once per clone: the gitleaks hook scans the staged changes with a pinned image (it needs Docker and fails closed without it). SKIP=gitleaks git commit bypasses it and is only for a deliberate, reviewed case.
  • On every pull request. The secret-scan workflow scans the whole tree and every commit of the pull request.
  • On GitHub. Secret scanning with push protection is a repository setting, enabled by the repository owner.