Files
ukmesh/docs/runbook-backup-restore.md

12 KiB
Raw Permalink Blame History

Backup and restore runbook

The backup set contains the analytics and owner-auth databases, Redis durable state, Mosquitto persistence and credentials, Health Check observer profiles and retained session results, and the configuration needed to reconstruct the release. The configuration payload includes the protected .env recovery secrets, Compose/Docker build definitions, edge policies, monitoring rules, database schema/migrations, and the recovery/deployment tools themselves. It contains both app Compose overlays and the separately managed meshcore-infra Compose file/configuration; data-plane reads are addressed only through the explicit meshcore-infra project. .env files must be regular files with no group/world permissions. The set is encrypted before leaving its access-controlled temporary storage and has a detached signed receipt. The initial objective is RPO 24 hours and RTO four hours.

The single archive file uses CMS-AES-256-CBC-CHUNKED-v1: a signed, length-framed sequence of independently encrypted 128 MiB CMS records. This keeps both encryption and restore memory bounded below OpenSSL's 2 GiB attached CMS parsing ceiling. The detached receipt authenticates the exact complete archive before any chunk is decrypted.

One-time keys and target

Generate separate encryption and receipt-signing keys on a protected operator host. Keep private keys out of the repository and away from the backup target.

install -d -m 0700 /secure/meshcore-backup-keys
openssl req -x509 -newkey rsa:3072 -nodes -days 3650 \
  -subj '/CN=MeshCore backup encryption/' \
  -keyout /secure/meshcore-backup-keys/decrypt.pem \
  -out /secure/meshcore-backup-keys/encrypt.pem
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 \
  -out /secure/meshcore-backup-keys/receipt-signing.pem
openssl pkey -in /secure/meshcore-backup-keys/receipt-signing.pem \
  -pubout -out /secure/meshcore-backup-keys/receipt-verify.pem
chmod 0600 /secure/meshcore-backup-keys/*

When enrolling the signing key, record its public-key fingerprint in the protected release settings used by the workstation and the deployment host. Provision those settings separately from the key and receipts. Retain the recorded value for future drills and releases, and update it when rotating the key.

openssl pkey -pubin -in /secure/meshcore-backup-keys/receipt-verify.pem -outform DER | sha256sum

Mount an off-host backup target and attest it once:

install -d -m 0700 /mnt/offsite/meshcore
touch /mnt/offsite/meshcore/.meshcore-offsite-target
chmod 0600 /mnt/offsite/meshcore/.meshcore-offsite-target

The script rejects a target on the application filesystem unless BACKUP_ALLOW_LOCAL_STAGING=true is explicitly set for a drill.

Create and verify a backup

export BACKUP_OUTPUT_DIR=/mnt/offsite/meshcore
export BACKUP_ENCRYPTION_CERT=/secure/meshcore-backup-keys/encrypt.pem
export BACKUP_RECEIPT_SIGNING_KEY=/secure/meshcore-backup-keys/receipt-signing.pem
# The default infrastructure checkout is meshcore-infra alongside this repository.
export MESHCORE_INFRA_PROJECT_NAME=meshcore-infra
scripts/backup.sh

MESHCORE_INFRA_COMPOSE_FILE can select a non-default external Compose file; MESHCORE_INFRA_PROJECT_DIR can set its project directory explicitly. The shared resolver checks that Compose project and requires one running container for each exact timescaledb, redis, and mosquitto service. It does not search container names across projects.

For the returned receipt and archive:

openssl dgst -sha256 \
  -verify /secure/meshcore-backup-keys/receipt-verify.pem \
  -signature "$RECEIPT.sig" "$RECEIPT"
test "$(jq -r .status "$RECEIPT")" = complete
test "$(sha256sum "$ARCHIVE" | cut -d' ' -f1)" = \
  "$(jq -r .archive_sha256 "$RECEIPT")"

Copy the receipt, signature, and public verification key alongside the encrypted archive. Alert if any required dataset lacks a verified receipt or the newest receipt is older than 24 hours.

If backup creation stages under the operator’s home directory, publish the newest complete set to a separately mounted and attested filesystem with atomic names and an independently checked checksum manifest:

export BACKUP_SOURCE_DIR="${HOME}/ukmesh/backups"
export BACKUP_SYNC_TARGET_DIR=/mnt/offsite/meshcore
export BACKUP_RECEIPT_VERIFY_KEY=/secure/meshcore-backup-keys/receipt-verify.pem
scripts/sync-latest.sh
(cd /mnt/offsite/meshcore && sha256sum --check latest.sha256)

BACKUP_SYNC_ALLOW_LOCAL_TEST=true is drill-only; it does not satisfy the off-host pre-reset gate.

Owner authorization reset gate

Before the backup, export every active grant (including database-only and legacy/null-method rows) without changing operator configuration:

export OWNER_AUTH_INVENTORY_HOST_DIR="${HOME}/ukmesh/backups"
install -d -m 0700 "$OWNER_AUTH_INVENTORY_HOST_DIR"
cd backend && npm run build
node --env-file=../.env dist/tools/inventoryOwnerAuthorization.js \
  --export="$OWNER_AUTH_INVENTORY_HOST_DIR/owner-grants-YYYY-MM-DDTHHMMSSZ.json"

The export is secret, mode 0600, checksum-bearing, and must never be committed. The legacy disposition is explicit preservation pending the operator's promote/revoke decision. Restore owner-auth.dump, mount the export read-only, and set:

OWNER_AUTH_INVENTORY_HOST_DIR=${HOME}/ukmesh/backups
OWNER_AUTH_INVENTORY_BASELINE_PATH=/owner-auth-inventory/owner-grants-YYYY-MM-DDTHHMMSSZ.json

Before public admission, run owner-auth:inventory -- --baseline=<host-path> --require-complete. /readyz also fails closed until active account/grant and per-method counts, configured/desired/rendered/applied generations, last error, and ACL readback exactly match the pre-reset baseline. Do not rewrite OWNER_MQTT_USERNAME_MAP as part of this preservation step.

Companion stores

When the projection services exist, the same encrypted archive includes the CoreScope projection, native Beacon database and Beacon projection database. The backup identifies the CoreScope configuration and data mounts from the ingestor container. It copies the committed source cursors before taking the online SQLite snapshot, so a resumed cursor can repeat a committed batch. The snapshot must contain the dedicated public projection metadata.

Set BACKUP_REQUIRE_COMPANIONS=true for companion release, backup and restore commands. Set BACKUP_BEACON_POSTGRES_CONTAINER, BACKUP_BEACON_POSTGRES_USER and BACKUP_BEACON_DATABASE from the deployed native Beacon inventory. The projection database name comes from the listener. If it uses a separate PostgreSQL service or backup role, also set BACKUP_BEACON_PROJECTION_CONTAINER and BACKUP_BEACON_PROJECTION_USER. Match these containers to the deployed endpoints before running a drill. Co-located native and projection schemas share a single database snapshot. Independent databases have separate snapshots and capture times.

The drill reconstructs CoreScope into a new private directory and verifies SQLite integrity. It restores each Beacon archive to an isolated database and compares counts and ordered sample hashes to the dump snapshot. The scratch data check restores without ACLs. Prove the deployed read-only and projection roles on the candidate separately before cutting over. Private configs, cursor files and rows stay in the encrypted archive and temporary drill directory. The signed receipts list the three dataset names.

Isolated restore drill

The drill requires a clean candidate checkout and creates an internal Docker network and disposable PostgreSQL, Redis, and Mosquitto volumes. It restores every dataset, migrates the restored schema, boots the current backend read-only, checks readiness and stats, samples data integrity and owner lookups, signs a restore receipt, then removes the isolated containers and volumes.

The backup records whether the rendered backend configuration keeps owner accounts in the analytics database or in a separate database. Both database URLs must identify the backed-up server. For a legacy archive, set RESTORE_OWNER_DATABASE=meshcore for consolidated accounts or RESTORE_OWNER_DATABASE=meshcore_owner_auth for a separate owner store. The restore cluster bootstraps backend and reader roles before migrations. It verifies a generated owner relationship, creates and revokes a session through the candidate owner module, and connects as the owner portal role.

The Health Check drill reconstructs both state files in a private temporary directory. It accepts the legacy results array and the current sessions object. Only the dataset name and pass status enter the receipt. A release requires a fresh archive containing both files from the running Health Check volume.

Each dump's inventory determines whether Timescale restore hooks are needed, including the owner database when it contains the extension. The drill creates the extension, enters timescaledb_pre_restore, restores serially, records the restored job scheduling inventory, disables jobs in the disposable copy, and calls timescaledb_post_restore. It verifies that restore mode is off and the restored jobs remain unscheduled. Production lifecycle activation follows its separate receipt/allowlist procedure.

The signed receipt records the backup's source_revision separately from the current application_source_revision and local immutable application_image_id. The drill verifies archive and payload checksums and compares restored packet and node counts and ordered sample hashes with the analytics dump's exported PostgreSQL snapshot. Expected-empty datasets pass when both sides agree. Create a new backup to qualify an older archive that lacks this baseline. Deployment requires a receipt from a drill run against the release revision. Current dumps retain database ACLs. The drill restores these after bootstrapping the shipped roles and verifies the owner session privileges against existing objects. An archive that references additional deployment-specific roles needs equivalent role provisioning. Previous-image compatibility requires the separate upgrade rehearsal.

export BACKUP_RECEIPT_VERIFY_KEY=/secure/meshcore-backup-keys/receipt-verify.pem
export BACKUP_DECRYPTION_CERT=/secure/meshcore-backup-keys/encrypt.pem
export BACKUP_DECRYPTION_KEY=/secure/meshcore-backup-keys/decrypt.pem
export RESTORE_RECEIPT_SIGNING_KEY=/secure/meshcore-backup-keys/receipt-signing.pem
export RESTORE_RECEIPT_VERIFY_KEY=/secure/meshcore-backup-keys/receipt-verify.pem
# Out-of-band pin of the verify key. Required: the drill refuses to verify a
# receipt when the key is absent, unpinned, or co-located with the receipt.
export RESTORE_RECEIPT_VERIFY_KEY_SHA256="${RESTORE_RECEIPT_VERIFY_KEY_SHA256:?load the enrolled fingerprint from protected operator settings}"
export RESTORE_RECEIPT_DIR=/secure/meshcore-restore-receipts

scripts/restore-drill.sh "$ARCHIVE" "$RECEIPT"

Verify latest.json and latest.json.sig against the separately provisioned verify key (pinned by sha256), then set BACKUP_RECEIPT_HOST_DIR to that receipt directory so backend health and destructive lifecycle gates see the same signed evidence. The verifier key is mounted from its own directory (RESTORE_RECEIPT_TRUST_HOST_DIR), never from the receipts directory.

Disaster recovery

Do not restore directly over a running production volume.

  1. Declare the incident and stop external ingest and every writer.
  2. Select the newest receipt whose signature and encrypted checksum verify.
  3. Run the isolated drill and record its demonstrated RPO/RTO.
  4. Create fresh production volumes and restore using the same ordered dataset procedure as the drill.
  5. Run migrations from the signed target backend image.
  6. Restore owner-auth.dump and the owner inventory baseline before starting the reconciler. Boot with MQTT ingest disabled; require the CLI baseline validation and /readyz, then verify privacy-scoped stats, owner lookup, queue invariants, and Mosquitto authentication.
  7. Reopen public reads, then workers, then MQTT ingest.
  8. Preserve the failed volumes read-only until incident review completes.

If no verified backup satisfies the objective, report the actual recovery point; never silently substitute an unsigned or untested archive.