Backup and restore

Fiscal Fox backups contain PostgreSQL application data and the SeaweedFS volume. They are authenticated with an external HMAC-SHA256 key before they are accepted for restore. Plain SHA-256 checksums detect accidental damage but do not authenticate a backup.

Create a random key of at least 32 bytes on the backup host:

install -d -m 700 /etc/fiscal-fox
openssl rand 48 > /etc/fiscal-fox/backup-hmac.key
chmod 600 /etc/fiscal-fox/backup-hmac.key
export BACKUP_HMAC_KEY_FILE=/etc/fiscal-fox/backup-hmac.key
export BACKUP_HMAC_KEY_ID=backup-key-2026-01
export BACKUP_CATALOG_FILE=/var/lib/fiscal-fox-catalog/backup-catalog.json
export BACKUP_CATALOG_HEAD_FILE=/var/lib/fiscal-fox-catalog-head/backup-catalog-head.json
corepack pnpm backup

The key, catalog, and catalog head must remain outside the application directory, Docker build context, and backup directory tree. The head must also be outside the catalog directory. Store the key in a secret manager and the head checkpoint in a separately protected path; never copy either beside a backup. BACKUP_HMAC_KEY_ID is a non-secret rotation label. Retain each old key securely until every backup signed by it expires, and test restoration before retiring it.

Production refuses unsigned backup creation and restore. Development/test may use the explicit --allow-unsigned flag, which emits a warning:

corepack pnpm backup -- --allow-unsigned
corepack pnpm backup:verify -- --allow-unsigned ../fiscal-fox-backups/<backup-id>

Backup and restore acquire the same deployment-wide atomic directory lock before catalog or quiescence work. Concurrent backup/backup and backup/restore attempts fail safely. The default lock is beside the application directory; production should set FISCAL_FOX_OPERATION_LOCK_DIR to an operator-owned location. A dead or remote lock is never removed automatically; inspect it before explicitly setting FISCAL_FOX_OPERATION_LOCK_BREAK_STALE=1.

Each backup uses its random UUID backupId as an exclusively created directory; second-resolution names and mkdir -p reuse are not used. The backup command quiesces API and worker writes, dumps PostgreSQL in custom format, stops SeaweedFS while streaming its numeric-owner archive, and writes:

  • postgres.dump
  • seaweedfs.tar
  • manifest.json
  • migrations.json, containing the release's migration count and hashes
  • SHA256SUMS
  • SHA256SUMS.hmac

Directories are mode 700; files are mode 600. Environment values, interpolated Compose configuration, catalog, generation, and HMAC key material are never persisted in a backup. FISCAL_FOX_RELEASE_REVISION may provide a non-secret release identifier.

Trusted restore architecture

Restore requires the same application release and its migration set:

export BACKUP_HMAC_KEY_FILE=/etc/fiscal-fox/backup-hmac.key
export BACKUP_CATALOG_FILE=/var/lib/fiscal-fox-catalog/backup-catalog.json
export BACKUP_CATALOG_HEAD_FILE=/var/lib/fiscal-fox-catalog-head/backup-catalog-head.json
corepack pnpm restore -- ../fiscal-fox-backups/<backup-id> --backup-id <manifest-backup-id> --force

Before stopping services or replacing data, restore:

  1. opens each required source artifact without following symlinks and copies it into a cryptographically random, mode-700, operator-owned staging directory;
  2. fsyncs mode-600 staged copies and the staging directory;
  3. verifies the HMAC, exact checksum manifest, permissions, and release migration attestation over the staged copies;
  4. verifies the manifest ID and digest against the external, chained, HMAC-authenticated backup catalog and requires its final entry to exactly match the separately stored HMAC-authenticated head checkpoint;
  5. validates the staged PostgreSQL and SeaweedFS archive structure.

After authentication, restore builds a uniquely named temporary database and SeaweedFS volume while the original database remains active. It applies trusted migrations, restores allowlisted data, invalidates credentials, reconciles ACLs and jobs, and completes migration/integrity checks against that temporary database. A failure in this phase removes only temporary state and leaves the original database and services restartable.

Only after the temporary target passes does restore stop web, API, worker, and migration services and confirm both health endpoints are down. It acquires a cluster-wide PostgreSQL advisory restore lock, temporarily changes the app and worker roles to NOLOGIN, terminates and verifies the absence of their database sessions, then captures the live security overlay in a read-only repeatable-read transaction and applies it to the temporary database. The overlay includes a fresh operator nonce and capture timestamp and is HMAC-authenticated immediately. Any stop, lock, freshness, capture, overlay, or final pre-swap validation failure aborts without renaming the original database.

The source directory must contain only the exact backup artifact set. Symlinks, non-regular files, unexpected entries, unsafe checksum paths, and files not owned by the restore operator are rejected. Restore never reads the source directory again after staging, so replacing an original archive cannot change the verified restore input. The private staging directory is removed by an exit trap.

The PostgreSQL archive is never trusted as schema or executable code. Admin is used only to create the temporary database and perform the final database rename; all migration, data, ACL, and validation work runs as fiscal_fox_migrator. Restore then:

  1. runs the release's migrations as fiscal_fox_migrator into a clean database;
  2. validates the resulting migration journal count and every migration checksum;
  3. derives an allowlist from trusted public tables and sequences;
  4. temporarily removes trusted foreign keys and disables trusted user triggers;
  5. runs pg_restore --data-only --no-owner --no-privileges as the migrator;
  6. invalidates restored credentials and tokenized deliveries before constraints are re-enabled or any application service starts;
  7. recreates trusted constraints, enables triggers, and revalidates migrations;
  8. applies the release's direct ACL SQL—never an archive-provided function;
  9. rejects unexpected SECURITY DEFINER functions, event triggers, extensions, procedural languages, schemas, owners, or runtime-role memberships;
  10. reconciles queue state and validates the complete temporary target;
  11. under quiescence and the advisory lock, renames the original database to a retained rollback name and the validated temporary database to the configured target name;
  12. activates staged SeaweedFS, clears Valkey, rotates session generation, and health-checks API and web.

Migration journal attestation matches trusted entries by chronological created_at, hash, and order. Serial ID gaps are accepted; unknown, future, missing, reordered, or hash-mismatched entries are rejected.

If a failure occurs after database rename starts, restore never creates or drops an empty replacement. It preserves the restored target, retained rollback database, and any unswapped temporary state, leaves application services stopped, and keeps runtime roles NOLOGIN. The operator must inspect both databases, activate one deliberately, restore role login, and restart Compose. Successful restore also retains the rollback database until deliberate post-validation cleanup.

Credential invalidation policy

Every restore forces all users to authenticate again. These ephemeral bearer credentials are not restored, or are cleared before application startup:

  • auth_session sessions and cookies;
  • auth_verification password-reset, email-verification, OAuth-state, and other transient verification values;
  • organization_invitations invitation tokens;
  • public_document_tokens quotation, invoice, payment, signing, and download links;
  • contract_public_tokens built-in contract signing links;
  • OAuth access, refresh, and ID tokens stored on auth_account rows.

When the current database is accessible, restore captures a private, HMAC-authenticated security overlay after every application writer is quiesced. The exact current users, password hashes, passkey factors, memberships, and roles are reapplied, so post-backup deletions, revocations, and role reductions dominate older backup state. A revocation committed before the quiescence boundary is in the overlay; attempts after the boundary cannot open a runtime-role connection. Backup-only identities are left inert.

Disaster recovery (--disaster-recovery), or inability to authenticate current security state, securely quarantines all restored identities: password/provider accounts and passkeys are deleted, memberships are removed, and verification state remains empty. Recover exactly one deliberate owner with a private mode-600 password file:

scripts/recover-bootstrap-owner.sh user@example.com <organization-id> \
  /secure/recovery-password --force

The dangerous --preserve-backup-identities option is available only with --confirm-preserve-backup-identities; it should not be used for normal recovery. It is audited operationally and still does not restore sessions or bearer tokens.

The live security overlay also captures current calendar, Stripe, AI, and signature-provider security state. Current revocations, disabled capabilities, credential rotations, and provider changes override older backup state. Disaster recovery and the identity-preservation override securely quarantine external integrations: calendar tokens and source URLs are cleared, Stripe charges and payouts are disabled, external AI credentials are removed, and DocuSign use is reset to the built-in provider. Historical business identifiers and non-secret configuration remain available for review. Operators must reauthorize or re-enter credentials before provider use resumes.

Restore never automatically republishes backed-up work. Background jobs are cancelled, inbox/outbox events are dead-lettered, recurring schedules are disabled, exports cannot retry, and tokenized deliveries/reminders are marked uncertain. This includes calendar, Stripe, DocuSign, mail, AI, map, and document provider work. Pure internal deterministic jobs also require explicit operator review before republishing. Each organization receives a restore.credentials_invalidated audit event listing quarantined integrations, blocked work, and required operator actions.

On a fresh Compose volume, session-generation-init creates the private random value with mode 600 and API ownership before API starts; API mounts it read-only. Before application restart, restore atomically rotates the private session-generation Docker volume mounted read-only by the API and uses its value as the session cookie-cache version. The volume is outside PostgreSQL, the backup set, and the image/build context. Host deployments may instead provide SESSION_GENERATION_FILE or SESSION_GENERATION. Cached signed session cookies from before restore are therefore rejected even when AUTH_SECRET is unchanged.

Each signed backup has a random backupId, parent ID, release/migration metadata, and manifest digest in the external mode-600 catalog. Backup atomically appends the catalog and then atomically updates the separate mode-600 head with the final backup ID, sequence, and entry digest. Restore rejects a truncated or older catalog even when every remaining entry has a valid HMAC. A crash between the two atomic updates fails closed and requires operator reconciliation.

Store the head in a WORM store, secret manager, or remote monotonic checkpoint service for stronger rollback resistance; materialize the expected checkpoint as BACKUP_CATALOG_HEAD_FILE before backup or restore. Restore requires the exact ID and accepts the catalog latest by default. An older catalog entry requires both --allow-rollback and --confirm-rollback <backup-id>. Intentional catalog rollback additionally requires an independently selected old catalog and an explicit checkpoint update:

node scripts/backup-catalog.mjs checkpoint \
  "$BACKUP_CATALOG_FILE" "$BACKUP_HMAC_KEY_FILE" \
  "$BACKUP_CATALOG_HEAD_FILE" <expected-backup-id> true

Record and approve that checkpoint operation separately. Replacing a backup directory or catalog with an older signed set cannot satisfy the requested ID and head checkpoint without this operator-controlled rollback flow.

This data-only design intentionally rejects backups from a different migration set. Cross-version recovery requires first restoring with the matching release, then upgrading normally through reviewed migrations.

Restore drill

Use a disposable host or Compose project:

  1. Verify with corepack pnpm backup:verify -- <backup-directory>.
  2. Restore with the matching release and external HMAC key.
  3. Confirm API/web health and compare organization, journal, and artifact counts.
  4. Sample stored objects and compare their SHA-256 values with stored_files.sha256 and immutable_artifacts.sha256.
  5. Exercise sign-in, a report, an artifact download, and a queued worker action.
  6. Record recovery time, recovery point, discrepancies, and corrective actions.

Restore changes the active database and storage only at its validated swap boundary and refuses to run without --force. Never run a drill against valued production or local data.