Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,10 @@ dotnet test --filter "Category!=Integration" # unit tests only, no Docker neede

Integration tests use Testcontainers to start a disposable PostgreSQL 17 container, so Docker Desktop (or Docker Engine) must be running.

## Database backups

[infra/db-backup/backup.sh](infra/db-backup/backup.sh) backs up the database: the backup is encrypted, stored in Azure Blob Storage and kept 30 days (temporary value). In Azure, a scheduled job runs it every day. [infra/db-backup/restore.sh](infra/db-backup/restore.sh) restores it into an empty database and checks every table. Restoring a 39 MB database takes under one second.

See [docs/azure/backup-restore.md](docs/azure/backup-restore.md) for the backup and restore procedures, the settings and the measured times.


152 changes: 152 additions & 0 deletions docs/azure/backup-restore.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# Database backups and restore

The database holds donations, price grids, donor records and issued tax receipts. A backup is made every day by a scheduled job, encrypted, stored outside the application server, and kept for a limited time. A backup can be restored into an empty database, and the restore checks that nothing is missing.

The scripts are in [infra/db-backup](../../infra/db-backup). They run in a Docker image built from its [Dockerfile](../../infra/db-backup/Dockerfile), the same way on a developer's machine and in Azure.

## How it works

A backup ([backup.sh](../../infra/db-backup/backup.sh)) does these steps, in this order:

1. **dump**: `pg_dump` saves the whole database in the compressed custom format of PostgreSQL.
2. **manifest**: the number of rows of every table is read from the dump and saved next to it.
3. **encrypt**: the dump and the manifest are put in one file and encrypted with [age](https://age-encryption.org), with a public key. Only the matching private key can open it.
4. **checksum**: a SHA-256 checksum of the encrypted file is computed.
5. **upload**: the encrypted file, then its checksum, are sent to a Blob Storage container. The checksum is sent last, so a backup without its checksum is known to be incomplete.
6. **purge**: the backups older than the retention period are deleted. This only happens after a successful upload, so a failing job never deletes the last good backups.

A backup is named after the time it was made, in UTC: `moisson-20261202T070000Z.tar.age`, with `moisson-20261202T070000Z.tar.age.sha256` next to it.

A restore ([restore.sh](../../infra/db-backup/restore.sh)) does these steps, in this order:

1. **download**: if the backup is not a local file, it and its checksum are downloaded from the storage.
2. **checksum**: the file must match its checksum. A damaged or incomplete backup stops here.
3. **decrypt**: the private key opens the backup. A backup changed after it was made also stops here, because age detects it.
4. **target**: the target database must be empty, unless `--confirm` is given.
5. **restore**: `pg_restore` runs in a single transaction. If anything fails, nothing is changed in the target database.
6. **row counts**: every table must have the number of rows written in the manifest.

The target database is only touched at step 5, after every check that can be done without it.

## Settings

The scripts read their settings from environment variables, never from a file of the repository.

| Variable | Used by | Secret | Meaning |
| --- | --- | --- | --- |
| `PGHOST`, `PGPORT`, `PGUSER`, `PGDATABASE` | both | no | Connection to the database (standard PostgreSQL variables) |
| `PGPASSWORD` | both | **yes** | Password of the database user |
| `BACKUP_AGE_RECIPIENT` | backup | no | Public age key that encrypts the backups (starts with `age1`) |
| `BACKUP_AGE_IDENTITY` | restore | **yes** (the file) | Path of the file that holds the private age key |
| `BACKUP_STORAGE_URL` | both | no | URL of the Blob Storage container, such as `https://<account>.blob.core.windows.net/db-backups` |
| `BACKUP_STORAGE_SAS` | both | **yes** | SAS token of that container. The backup needs read, write, list and delete. A restore only needs read |
| `BACKUP_RETENTION_DAYS` | backup | no | Days a backup is kept. **30 by default, a temporary value until Moisson Montréal confirms the retention** |

## Encryption keys

The key pair is made once, with the image:

```bash
docker build -t moisson-db-backup infra/db-backup
docker run --rm --entrypoint age-keygen moisson-db-backup
```

- The **private key** (the line that starts with `AGE-SECRET-KEY-`) goes into the shared Vaultwarden of the project, with the other keys, and nowhere else. Without it, no backup can ever be restored.
- The **public key** (the line `# public key: age1...`) is the value of `BACKUP_AGE_RECIPIENT`. It is not a secret: it can encrypt but not decrypt.

The daily job only knows the public key. Someone who reads the settings or the storage of the job still cannot read a backup.

## Restore procedure

Restore into a separate database, never directly into production. To replace production after a loss, restore into a new empty database, check it as below, then point the API to it.

1. **Get the private key** from Vaultwarden and save it in a file that only you can read:
```bash
mkdir -p ~/restore-key && chmod 700 ~/restore-key
# paste the private key into ~/restore-key/backup.key, then:
chmod 600 ~/restore-key/backup.key
```
2. **Get a read-only SAS token** for the container (`rl` permissions, expiring within the day), from the Azure portal or with the Azure CLI:
```bash
az storage container generate-sas --account-name <account> --name db-backups \
--permissions rl --expiry <today, such as 2026-12-02T23:00:00Z> --auth-mode login --as-user --output tsv
```
3. **Pick a backup.** The most recent one is the last name in the list:
```bash
az storage blob list --account-name <account> --container-name db-backups \
--prefix moisson- --query "[].name" --auth-mode login --output tsv | grep 'Z.tar.age$' | sort | tail -1
```
4. **Create an empty target database** on the server you restore to.
5. **Run the restore:**
```bash
docker run --rm --entrypoint restore.sh \
-e PGHOST=<server> -e PGUSER=<user> -e PGPASSWORD=<password> -e PGDATABASE=<empty database> -e PGSSLMODE=require \
-e BACKUP_AGE_IDENTITY=/keys/backup.key -v ~/restore-key:/keys:ro \
-e BACKUP_STORAGE_URL=https://<account>.blob.core.windows.net/db-backups -e BACKUP_STORAGE_SAS="<read-only SAS>" \
moisson-db-backup <backup name>
```
The last line must be `SUCCESS restored=<backup name> tables=<n> seconds=<s>`. Any other end means the restore did not finish: read the `FAILED` line below.
6. **Start the API on the restored database** and open `/health`: it must answer `Healthy`.
7. **Delete the private key** from your machine: `rm -r ~/restore-key`.

A local backup file can also be restored: give its path instead of its name. Its `.sha256` file must be in the same folder.

### Restoring over a database that is not empty

`restore.sh` refuses a database that already has tables, unless `--confirm` is added after the backup name. With `--confirm`, every table of the backup is replaced. A table that exists only in the target database is kept, so for an exact copy, restore into an empty database.

## Log lines

Every run ends with one line, which Azure keeps in the logs of the job:

| Line | Meaning |
| --- | --- |
| `SUCCESS backup=... bytes=... tables=... purged=... seconds=...` | The backup is stored, and `purged` old backups were deleted |
| `PURGED blob=...` | One old backup file was deleted |
| `SUCCESS restored=... tables=... seconds=...` | The backup is restored and every table has the expected number of rows |
| `MISMATCH table=... expected=... actual=...` | One table does not have the number of rows of the manifest |
| `FAILED step=<step> reason=...` | The run stopped at this step. The exit code is 1 |

| Failed step | What to check |
| --- | --- |
| `settings` | A variable is missing or wrong, see `missing=` or `reason=` |
| `dump`, `target` | The connection to the database: server, user, password, firewall |
| `manifest` | `no tables found`: `PGDATABASE` points to an empty database |
| `encrypt` | `BACKUP_AGE_RECIPIENT` is not a valid public key |
| `upload`, `purge`, `download` | The storage URL, the SAS token, its permissions and its expiry |
| `checksum` | The backup is damaged or incomplete: use another backup |
| `decrypt` | Wrong private key, or the backup was changed after it was made |
| `restore` | `pg_restore` failed and the target database was left unchanged. The error is printed above |
| `row counts` | The restored data does not match the backup: do not use this database |

## Measured time

Measured by the tests on a MacBook (Apple silicon), with Docker Desktop:

| Database | Backup | Restore, checks included | Encrypted file |
| --- | --- | --- | --- |
| 39 MB: 10,000 receipts, 50,000 receipt lines, 2,000 donors | 0.4 s | 0.6 s | 5.6 MB |

A restore by hand also takes the time to get the key, the SAS token and the target database ready. The time on the real database in Azure, with these steps, will be measured during the first restore test in Azure and added here.

## Tests

The tests in [tests/MoissonMontreal.Tests/DbBackup](../../tests/MoissonMontreal.Tests/DbBackup) run both scripts in the image, against PostgreSQL and Azurite (the Blob Storage emulator) started by Testcontainers. The source database is built from the migrations and filled with [BackupTestData.sql](../../tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql).

```bash
dotnet test --filter "FullyQualifiedName~MoissonMontreal.Tests.DbBackup"
```

They check that a restored database is identical to the source, row by row, with its indexes and constraints, that the control totals match (issued receipts total, receipts per status, last receipt number, value of the receipt lines), that every migration is present and that the API reports it healthy. They also check every refusal above: damaged, incomplete or changed backups, the wrong key, a database that is not empty, a restore that fails halfway, and wrong settings.

## Deployment in Azure

The daily job needs these Azure resources:

1. **Storage account** in Canada Central, with geo-redundant storage so a copy is kept in Canada East, and a private container `db-backups`.
2. **Image** pushed to the Azure Container Registry of the project, as the API image.
3. **Container Apps Job** with a schedule trigger, such as `0 7 * * *` (07:00 UTC, 2:00 or 3:00 in Montréal). Its settings are the variables above, with `PGSSLMODE=require`. `PGPASSWORD` and `BACKUP_STORAGE_SAS` are secrets of the job, never in the image or the repository.
4. **Access to the storage**: either a SAS token kept as a secret of the job, which expires and must be renewed, or a managed identity of the job, which needs no secret. A managed identity is better, and needs a small change in the `storage` and `list_backups` functions of `backup.sh` to send its token instead of a SAS token.
5. **Access to the database**: the job must reach the PostgreSQL server (firewall or private network).
6. **Alert**: an Azure Monitor alert sends an email when a job execution fails, so a failure does not go unnoticed.
7. **Restore test**: after the first backup, restore it into a separate database with the procedure above, and add the measured time to this page.
1 change: 1 addition & 0 deletions infra/db-backup/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.sh text eol=lf
10 changes: 10 additions & 0 deletions infra/db-backup/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM postgres:17-bookworm

RUN apt-get update \
&& apt-get install --yes --no-install-recommends age ca-certificates curl \
&& rm -rf /var/lib/apt/lists/*

COPY backup.sh restore.sh /usr/local/bin/

USER postgres
ENTRYPOINT ["backup.sh"]
96 changes: 96 additions & 0 deletions infra/db-backup/backup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#!/usr/bin/env bash
# Backs up the PostgreSQL database into one encrypted file with its checksum, sends both to Azure Blob Storage,
# then deletes the backups older than the retention period.
#
# Reads its settings from environment variables, never from this file:
# PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE connection to the database (standard PostgreSQL variables)
# BACKUP_AGE_RECIPIENT public age key that encrypts the backup
# BACKUP_STORAGE_URL URL of the Blob Storage container that keeps the backups
# BACKUP_STORAGE_SAS SAS token that gives access to that container
# BACKUP_RETENTION_DAYS number of days a backup is kept (default: 30, temporary value)
set -Eeuo pipefail

log() {
echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) $*"
}

# Prints the seconds since the start, with 3 decimals.
elapsed() {
local milliseconds=$(( ($(date +%s%N) - started) / 1000000 ))
printf '%d.%03d' $((milliseconds / 1000)) $((milliseconds % 1000))
}

fail() {
log "FAILED step=${step} $*"
exit 1
}

step="settings"
for setting in PGHOST PGUSER PGDATABASE BACKUP_AGE_RECIPIENT BACKUP_STORAGE_URL BACKUP_STORAGE_SAS; do
[ -n "${!setting:-}" ] || fail "missing=${setting}"
done
retention_days="${BACKUP_RETENTION_DAYS:-30}"
[[ "${retention_days}" =~ ^[1-9][0-9]*$ ]] || fail "reason=BACKUP_RETENTION_DAYS must be a whole number of days, at least 1"

# Sends one request to the Blob Storage container. Extra curl options can be added after the blob name.
storage() {
local method="$1" blob="$2"
shift 2
curl --silent --show-error --fail --request "${method}" --header "x-ms-version: 2021-08-06" "$@" \
"${BACKUP_STORAGE_URL}/${blob}?${BACKUP_STORAGE_SAS}"
}

# Prints the name of every backup file in the container, one per line.
list_backups() {
curl --silent --show-error --fail --header "x-ms-version: 2021-08-06" \
"${BACKUP_STORAGE_URL}?restype=container&comp=list&prefix=moisson-&${BACKUP_STORAGE_SAS}" \
| { grep --only-matching '<Name>[^<]*</Name>' || true; } | sed 's/<[^>]*>//g'
}

work_dir="$(mktemp -d)"
trap 'rm -rf "${work_dir}"' EXIT
trap 'log "FAILED step=${step}"; exit 1' ERR

started=$(date +%s%N)
name="moisson-$(date -u +%Y%m%dT%H%M%SZ)"

step="dump"
pg_dump --format=custom --file="${work_dir}/database.dump"

step="manifest"
pg_restore --data-only --file=- "${work_dir}/database.dump" \
| awk '/^COPY / { table = $2; rows = 0; next }
/^\\\.$/ { print table "\t" rows; table = ""; next }
table != "" { rows++ }' \
> "${work_dir}/manifest.tsv"
[ -s "${work_dir}/manifest.tsv" ] || fail "reason=no tables found in database ${PGDATABASE}"

step="encrypt"
tar --create --directory="${work_dir}" database.dump manifest.tsv \
| age --encrypt --recipient="${BACKUP_AGE_RECIPIENT}" \
> "${work_dir}/${name}.tar.age"

step="checksum"
(cd "${work_dir}" && sha256sum "${name}.tar.age" > "${name}.tar.age.sha256")

# The checksum is sent last: a backup without its checksum file is incomplete and restore.sh refuses it.
step="upload"
storage PUT "${name}.tar.age" --header "x-ms-blob-type: BlockBlob" --upload-file "${work_dir}/${name}.tar.age"
storage PUT "${name}.tar.age.sha256" --header "x-ms-blob-type: BlockBlob" --upload-file "${work_dir}/${name}.tar.age.sha256"

# Runs only after a successful upload, so a failing job never deletes the last good backups.
step="purge"
oldest_kept=$(date -u --date="-${retention_days} days" +%Y%m%dT%H%M%SZ)
backups=$(list_backups)
purged=0
for blob in ${backups}; do
blob_date="${blob:8:16}"
if [[ "${blob_date}" =~ ^[0-9]{8}T[0-9]{6}Z$ ]] && [[ "${blob_date}" < "${oldest_kept}" ]]; then
storage DELETE "${blob}"
log "PURGED blob=${blob}"
purged=$((purged + 1))
fi
done

size=$(stat --format=%s "${work_dir}/${name}.tar.age")
log "SUCCESS backup=${name}.tar.age bytes=${size} tables=$(wc -l < "${work_dir}/manifest.tsv") purged=${purged} seconds=$(elapsed)"
17 changes: 17 additions & 0 deletions infra/db-backup/compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Local services for testing the backup and restore scripts.
# The app database comes from the compose.yaml at the root of the repository.
services:
restore-target:
image: postgres:17
environment:
POSTGRES_USER: moisson
POSTGRES_PASSWORD: moisson
POSTGRES_DB: moisson_restore
ports:
- "5433:5432"

azurite:
image: mcr.microsoft.com/azure-storage/azurite
command: azurite-blob --blobHost 0.0.0.0
ports:
- "10000:10000"
87 changes: 87 additions & 0 deletions infra/db-backup/restore.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# Restores a backup made by backup.sh into a PostgreSQL database, then checks that every table has the same
# number of rows as when the backup was made.
#
# Usage: restore.sh <backup .tar.age> [--confirm]
# <backup .tar.age> a local file, or the name of a backup in Blob Storage if no such file exists
# --confirm allows replacing the tables of a database that is not empty
#
# Reads its settings from environment variables, never from this file:
# PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE connection to the target database (standard PostgreSQL variables)
# BACKUP_AGE_IDENTITY path of the file holding the private age key
# BACKUP_STORAGE_URL, BACKUP_STORAGE_SAS Blob Storage container and its SAS token, to download a backup
set -Eeuo pipefail

log() {
echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) $*"
}

# Prints the seconds since the start, with 3 decimals.
elapsed() {
local milliseconds=$(( ($(date +%s%N) - started) / 1000000 ))
printf '%d.%03d' $((milliseconds / 1000)) $((milliseconds % 1000))
}

fail() {
log "FAILED step=${step} $*"
exit 1
}

step="settings"
backup_file="${1:-}"
confirm="${2:-}"
[ -n "${backup_file}" ] || fail "reason=no backup file given"
[ -z "${confirm}" ] || [ "${confirm}" = "--confirm" ] || fail "reason=unknown option ${confirm}"
for setting in PGHOST PGUSER PGDATABASE BACKUP_AGE_IDENTITY; do
[ -n "${!setting:-}" ] || fail "missing=${setting}"
done

work_dir="$(mktemp -d)"
trap 'rm -rf "${work_dir}"' EXIT
trap 'log "FAILED step=${step}"; exit 1' ERR
started=$(date +%s%N)

if [ ! -f "${backup_file}" ]; then
step="download"
[ -n "${BACKUP_STORAGE_URL:-}" ] && [ -n "${BACKUP_STORAGE_SAS:-}" ] \
|| fail "reason=${backup_file} is not a local file and BACKUP_STORAGE_URL or BACKUP_STORAGE_SAS is not set"
blob="$(basename "${backup_file}")"
for file in "${blob}" "${blob}.sha256"; do
curl --silent --show-error --fail --header "x-ms-version: 2021-08-06" --output "${work_dir}/${file}" \
"${BACKUP_STORAGE_URL}/${file}?${BACKUP_STORAGE_SAS}" \
|| fail "reason=${file} could not be downloaded from the storage"
done
backup_file="${work_dir}/${blob}"
fi

step="checksum"
[ -f "${backup_file}.sha256" ] || fail "reason=checksum file ${backup_file}.sha256 not found"
(cd "$(dirname "${backup_file}")" && sha256sum --check --status "$(basename "${backup_file}").sha256") \
|| fail "reason=the backup file does not match its checksum"

step="decrypt"
age --decrypt --identity="${BACKUP_AGE_IDENTITY}" "${backup_file}" | tar --extract --directory="${work_dir}"

step="target"
tables=$(psql --no-psqlrc --tuples-only --no-align --command \
"SELECT count(*) FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')")
if [ "${tables}" -gt 0 ] && [ "${confirm}" != "--confirm" ]; then
fail "reason=the target database has ${tables} tables, add --confirm to replace them"
fi

step="restore"
pg_restore --dbname="${PGDATABASE}" --no-owner --no-acl --exit-on-error --single-transaction \
--clean --if-exists "${work_dir}/database.dump"

step="row counts"
mismatches=0
while IFS=$'\t' read -r table expected; do
actual=$(psql --no-psqlrc --tuples-only --no-align --command "SELECT count(*) FROM ${table}")
if [ "${actual}" != "${expected}" ]; then
log "MISMATCH table=${table} expected=${expected} actual=${actual}"
mismatches=$((mismatches + 1))
fi
done < "${work_dir}/manifest.tsv"
[ "${mismatches}" -eq 0 ] || fail "reason=${mismatches} tables do not have the expected number of rows"

log "SUCCESS restored=$(basename "${backup_file}") tables=$(wc -l < "${work_dir}/manifest.tsv") seconds=$(elapsed)"
Loading
Loading