# Backup and Restore

> **Status: IMPLEMENTED in Phase 9** (D-61, D-132); failure recovery added in **Phase 9 Revision 1** (D-136). Tested with a local folder, a local fake S3 server and a real backup → restore drill against the E2E database. **Not yet tested against a real storage bucket** (P-08: no account yet).
> Baseline: SRS §3.1, §14.2, §18 and §19 (weekly automatic backups, 8-week retention, Admin can view status, restore by technical operator only, restore tested periodically). Decision IDs refer to `docs/DECISIONS.md`.

## 1. Requirements (approved)

| Requirement                                                                                           | Source         | How it is met                                                                                                                 |
| ----------------------------------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Automatic scheduled **weekly** database backups                                                       | C-35           | Scheduler job `backup`, Sundays 03:00 Asia/Karachi, under a job lock                                                          |
| **8-week** retention                                                                                  | C-35           | The 8 newest successful backups are kept; older ones are pruned                                                               |
| Admin can **view backup status**                                                                      | C-35           | `GET /api/v1/backups`, **Settings → Backups**, dashboard warning                                                              |
| Restore is performed by the **technical operator only**, not through a normal Admin dashboard control | C-35, SRS §3.1 | `server/scripts/restore.js`; **no restore endpoint or button exists**                                                         |
| Restore actions are protected, confirmed and logged in the operational runbook                        | SRS §19        | Full validation first, typed confirmation, checksum, empty target only, restore marker, safe resume; §5 below; restore record |
| Restore is tested periodically in a safe environment                                                  | SRS §14.2, §19 | §6 below; automated drill in the server and browser test suites                                                               |

## 2. Why the backups are scripted (D-61)

Atlas cloud backups are not available on the free M0 tier, and the production tier is not decided yet (P-04). A scripted backup works on **any** Atlas tier, runs inside the existing Render service and needs no `mongodump` binaries. If a paid Atlas tier with Cloud Backup is chosen later, both can run: Atlas snapshots as an extra layer, and the script as the documented SRS mechanism.

## 3. Backup process

**Schedule:** every Sunday at 03:00 Asia/Karachi, run by the scheduler under a job lock (only one run at a time, even with several instances). The operator can also take one by hand: `npm run backup -w server` (same environment variables as the server).

Steps (`server/src/modules/backups/backup.service.js`):

1. Insert a `BackupRun { status: running, trigger }` record.
2. Read every application collection, in `_id` order, as **canonical Extended JSON** (ObjectIds, dates and number types are kept exactly), together with a manifest (app version, environment, time, document count per collection and the index definitions).
3. Compress with gzip.
4. **Encrypt** with AES-256-GCM using `BACKUP_ENCRYPTION_KEY` (32 bytes). File layout: `GMSBAK1\n` header, 12-byte IV, 16-byte authentication tag, ciphertext. The header is authenticated too, so any change to the file, or a wrong key, is detected instead of restoring bad data.
5. Store it as `gms_<YYYY-MM-DD>_<HHMMSSmmm>.gmsbak` (Karachi time) in the configured storage: `gym/<env>/backups/` in the S3-compatible bucket. An existing file is **never overwritten**.
6. Record the SHA-256 checksum, size and counts on the `BackupRun`.
7. **Prune:** keep the newest **8** successful backups; remove older ones from storage and mark their runs as pruned. Only files this service recorded are ever removed. **A failed run never prunes.**

On any error the run is marked `failed` with a short error text (anything that looks like a secret is removed), and the Admin sees a warning.

**Excluded:** `sessions`, `passwordResetTokens`, `jobLocks` (short-lived and security-sensitive) and `restoreState` (a restore's own marker, D-136). Documents are read without number promotion, so every number type (int, double, long) is kept exactly. **Included:** everything else, including the audit collections, consent history and WhatsApp history. `backupRuns` is included but not restored over a target.

**Images:** Cloudinary keeps the images. The database backup stores their public IDs and URLs. The operator can download the Cloudinary assets manually if needed (not required by the SRS).

**Size:** the backup is built in memory, which is fine for a single gym (a few MB). Revisit if the database grows past a few hundred MB.

## 4. Admin visibility

- **Settings → Backups** (`GET /api/v1/backups`, `backups.status.read`, Admin only): on/off, schedule, how many are kept (n of 8), last successful backup, storage kind, encryption, and the latest 20 runs (date, status, trigger, size, records, file name, checksum, error, pruned). No key, bucket name, endpoint or credential is ever returned.
- The **Admin dashboard** shows a warning when backups are not set up, the last run failed, none has run yet, or the newest successful backup is more than 8 days old.
- **There is no restore button or endpoint in the app** (C-35). Trainers get 403.

## 5. Restore runbook (technical operator only)

> Run this only from a trusted machine with the encryption key. A restore **never deletes, drops or overwrites anything**: it only writes into an **empty** database, or resumes its own partial restore of the same backup after checking every document already there (D-132, D-136). Rolling back production means restoring into a new database and pointing the app at it; the current database stays untouched until you remove it yourself, later, deliberately.

1. **Decide and record.** In the operational log write who is restoring, why, which backup, and the approval from the gym owner or Admin.
2. **Pick the backup** in Settings → Backups (file name and SHA-256).
3. **Check the file first (writes nothing):**

   ```bash
   BACKUP_ENCRYPTION_KEY=<key> npm run restore -w server -- --check \
     --name gms_2026-11-22_030000000.gmsbak \        # or --file ./path/to/file.gmsbak
     --target-uri "mongodb+srv://…/gms_restore_2026_11_23" \
     --sha256 <checksum from Settings → Backups>
   ```

   It decrypts and validates the whole backup (manifest, every document, every count) and reports the target as `empty`, `not_empty`, `partial_restore` (with which file, status and completed collections) or `restored`.

4. **Restore into a new, empty database in staging first:** the same command without `--check`, plus `--confirm-target gms_restore_2026_11_23`. `--name` downloads from the configured `BACKUP_STORAGE` (set `BACKUP_STORAGE` and `BACKUP_S3_*`). In a terminal the script asks you to **type the database name again**. Before writing anything it refuses a wrong checksum, a wrong key, a changed or invalid file, a wrong confirmation or a non-empty target. Its first write is a **restore marker** (`restoreState`) in the target; it then creates every collection and index, inserts the documents, checks every count against the manifest, writes a `restore` record into `backupRuns` and marks the restore `complete`.

   **If it stops part-way** (connection lost, disk full, the process killed), the script prints `[PARTIAL_RESTORE]` and the database stays **marked as a partial restore**: the app and every operator script refuse to run on it. Recover in one of two ways; **nothing is ever deleted**:

   - **Resume:** fix the cause and run the same command with `--resume` and the **same file**. It only continues if every document already in the database is exactly this backup's data and nothing else is there; then it adds only what is missing. If the database was changed in between, or a different file is given, it refuses and writes nothing. A run that crashed holds a 10-minute lease; wait for it to expire.
   - **Start again elsewhere:** restore into another new, empty database. The partial one can be inspected and removed by hand later (`dropDatabase` in the Atlas UI or shell, after checking its name twice). The scripts never do this.

5. **Verify** in staging: point a staging API at the restored database, sign in, check member counts, a sample of member profiles, payment balances and receipts, and the latest Activity Log dates.
6. **Production** (only if needed): put the app into maintenance (scale Render to 0), take a fresh backup of the current production database (`npm run backup -w server`), restore into a **new** production database name, set `MONGODB_URI` to it and start the app. Repeat the verification. Keep the old database until the gym owner agrees it can go.
7. **Afterwards:** sessions are not in backups, so everyone signs in again. Record the outcome in the operational log. Check WhatsApp → Messages: messages still queued in the backup keep their idempotency keys and are not sent twice.

## 6. Restore testing

- **Automated:** the server suite backs up, restores into a fresh database and compares documents (number types included) and indexes exactly, and checks every refusal (wrong key, changed file, wrong checksum, invalid manifest or documents, wrong confirmation, non-empty target). Revision 1 adds failures part-way through (also inside a collection and several in a row), resume, refusal to resume over changed, extra or unknown data or with another file, the lease after a crash, two simultaneous restores, the start-up refusal of the server and the scripts, and `--check`. The browser suite runs the real `backup.js` and `restore.js` (`--check` and a restore) against the E2E database.
- **Quarterly drill** into staging from the latest production backup, following §5 steps 1–5, with the results in the operational log.
- **Before go-live (Phase 10):** one full drill with the real bucket (AC-26, P-08).

## 7. Recovery objectives (informational)

- **RPO (data loss window):** up to 7 days, because backups are weekly (an approved requirement). Daily backups or Atlas Cloud Backup on a paid tier would shorten this; that would be the user's decision.
- **RTO (time to restore):** expected under 1 hour for a single gym, once the operator has the key and storage access.

## 8. Pending

- P-08: storage provider account, bucket and a key limited to it; first real backup and drill.
- Custody of the encryption key: who holds the offline copy (gym owner and technical operator). **Losing the key means the backups cannot be restored.**
