diff --git a/README.md b/README.md index 2e7ed91..58cfaae 100644 --- a/README.md +++ b/README.md @@ -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. + diff --git a/docs/azure/backup-restore.md b/docs/azure/backup-restore.md new file mode 100644 index 0000000..500f8dd --- /dev/null +++ b/docs/azure/backup-restore.md @@ -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://.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 --name db-backups \ + --permissions rl --expiry --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 --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= -e PGUSER= -e PGPASSWORD= -e PGDATABASE= -e PGSSLMODE=require \ + -e BACKUP_AGE_IDENTITY=/keys/backup.key -v ~/restore-key:/keys:ro \ + -e BACKUP_STORAGE_URL=https://.blob.core.windows.net/db-backups -e BACKUP_STORAGE_SAS="" \ + moisson-db-backup + ``` + The last line must be `SUCCESS restored= tables= seconds=`. 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= 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. diff --git a/infra/db-backup/.gitattributes b/infra/db-backup/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/infra/db-backup/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/infra/db-backup/Dockerfile b/infra/db-backup/Dockerfile new file mode 100644 index 0000000..9c7f966 --- /dev/null +++ b/infra/db-backup/Dockerfile @@ -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"] diff --git a/infra/db-backup/backup.sh b/infra/db-backup/backup.sh new file mode 100755 index 0000000..effa222 --- /dev/null +++ b/infra/db-backup/backup.sh @@ -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 '[^<]*' || 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)" diff --git a/infra/db-backup/compose.yaml b/infra/db-backup/compose.yaml new file mode 100644 index 0000000..abb7ffe --- /dev/null +++ b/infra/db-backup/compose.yaml @@ -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" diff --git a/infra/db-backup/restore.sh b/infra/db-backup/restore.sh new file mode 100755 index 0000000..fd1a8af --- /dev/null +++ b/infra/db-backup/restore.sh @@ -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 [--confirm] +# 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)" diff --git a/tests/MoissonMontreal.Tests/DbBackup/BackupRestoreTests.cs b/tests/MoissonMontreal.Tests/DbBackup/BackupRestoreTests.cs new file mode 100644 index 0000000..b1e0f68 --- /dev/null +++ b/tests/MoissonMontreal.Tests/DbBackup/BackupRestoreTests.cs @@ -0,0 +1,476 @@ +using System.Net; +using System.Text; + +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; + +using MoissonMontreal.Api.Data; +using MoissonMontreal.Tests.Fixtures; + +using Xunit.Abstractions; + +namespace MoissonMontreal.Tests.DbBackup; + +/// +/// Tests infra/db-backup/backup.sh and restore.sh end to end. Every test uses its own storage container and its own +/// target database, so the tests do not depend on each other. +/// +[Trait("Category", "Integration")] +public class BackupRestoreTests(BackupFixture fixture, ITestOutputHelper output) : IClassFixture +{ + [Fact] + public async Task Backup_SendsTheBackupAndItsChecksumToTheStorage() + { + var storage = await fixture.CreateStorageAsync(); + + var result = await fixture.BackupAsync(storage); + + Assert.Equal(0, result.ExitCode); + var name = result.Value("backup"); + Assert.Matches(@"^moisson-\d{8}T\d{6}Z\.tar\.age$", name); + Assert.Equal([name, name + ".sha256"], (await storage.NamesAsync()).Order()); + } + + [Fact] + public async Task Backup_PurgesOnlyTheDatedBackupsOlderThanTheRetention() + { + var storage = await fixture.CreateStorageAsync(); + var old = BackupName(DateTime.UtcNow.AddDays(-62)); + var recent = BackupName(DateTime.UtcNow.AddDays(-17)); + string[] others = [old, old + ".sha256", recent, recent + ".sha256", "notes.txt", "moisson-latest.txt"]; + foreach (var name in others) + { + await storage.WriteAsync(name, [1]); + } + + var result = await fixture.BackupAsync(storage); + + Assert.Equal(0, result.ExitCode); + Assert.Equal("2", result.Value("purged")); + var names = await storage.NamesAsync(); + Assert.DoesNotContain(old, names); + Assert.DoesNotContain(old + ".sha256", names); + Assert.Contains(recent, names); + Assert.Contains("notes.txt", names); + Assert.Contains("moisson-latest.txt", names); + Assert.Contains(result.Value("backup"), names); + } + + [Fact] + public async Task Backup_KeepsOnlyTodaysBackups_WhenTheRetentionIsOneDay() + { + var storage = await fixture.CreateStorageAsync(); + var recent = BackupName(DateTime.UtcNow.AddDays(-17)); + await storage.WriteAsync(recent, [1]); + + var result = await fixture.BackupAsync(storage, ("BACKUP_RETENTION_DAYS", "1")); + + Assert.Equal(0, result.ExitCode); + var names = await storage.NamesAsync(); + Assert.DoesNotContain(recent, names); + Assert.Contains(result.Value("backup"), names); + } + + [Fact] + public async Task Backup_FailsWithoutPurging_WhenTheUploadIsRefused() + { + var storage = await fixture.CreateStorageAsync(); + var old = BackupName(DateTime.UtcNow.AddDays(-62)); + await storage.WriteAsync(old, [1]); + + var result = await fixture.BackupAsync(storage, ("BACKUP_STORAGE_SAS", "sv=2021-08-06&sig=wrong")); + + AssertFailedAt("upload", result); + Assert.Equal([old], await storage.NamesAsync()); + } + + [Fact] + public async Task Backup_FailsAtUpload_WhenTheSasTokenIsReadOnly() + { + var storage = await fixture.CreateStorageAsync(); + + var result = await fixture.BackupAsync(storage, ("BACKUP_STORAGE_SAS", storage.ReadOnlySas)); + + AssertFailedAt("upload", result); + Assert.Empty(await storage.NamesAsync()); + } + + [Theory] + [InlineData("PGHOST")] + [InlineData("PGUSER")] + [InlineData("PGDATABASE")] + [InlineData("BACKUP_AGE_RECIPIENT")] + [InlineData("BACKUP_STORAGE_URL")] + [InlineData("BACKUP_STORAGE_SAS")] + public async Task Backup_FailsAtSettings_WhenASettingIsMissing(string setting) + { + var storage = await fixture.CreateStorageAsync(); + + var result = await fixture.BackupAsync(storage, (setting, "")); + + AssertFailedAt("settings", result, $"missing={setting}"); + Assert.Empty(await storage.NamesAsync()); + } + + [Theory] + [InlineData("0")] + [InlineData("-1")] + [InlineData("1.5")] + [InlineData("abc")] + public async Task Backup_FailsAtSettings_WhenTheRetentionIsNotAWholeNumberOfDays(string days) + { + var storage = await fixture.CreateStorageAsync(); + + var result = await fixture.BackupAsync(storage, ("BACKUP_RETENTION_DAYS", days)); + + AssertFailedAt("settings", result, "BACKUP_RETENTION_DAYS must be a whole number of days"); + } + + [Fact] + public async Task Backup_FailsAtEncrypt_WhenThePublicKeyIsInvalid() + { + var storage = await fixture.CreateStorageAsync(); + + var result = await fixture.BackupAsync(storage, ("BACKUP_AGE_RECIPIENT", "age1notavalidkey")); + + AssertFailedAt("encrypt", result); + Assert.Empty(await storage.NamesAsync()); + } + + [Fact] + public async Task Backup_FailsAtManifest_WhenTheDatabaseHasNoTables() + { + var storage = await fixture.CreateStorageAsync(); + + var result = await fixture.BackupAsync(storage, ("PGDATABASE", "empty")); + + AssertFailedAt("manifest", result, "no tables found in database empty"); + Assert.Empty(await storage.NamesAsync()); + } + + [Fact] + public async Task Backup_FailsAtDump_WhenThePasswordIsWrong() + { + var storage = await fixture.CreateStorageAsync(); + + var result = await fixture.BackupAsync(storage, ("PGPASSWORD", "wrong")); + + AssertFailedAt("dump", result); + Assert.Empty(await storage.NamesAsync()); + } + + [Fact] + public async Task Restore_RecreatesEveryRowIndexAndConstraintOfTheSource() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + + Assert.Equal(0, result.ExitCode); + Assert.Equal(fixture.SourceFingerprints, await fixture.FingerprintsAsync(database)); + output.WriteLine($"source database: {await fixture.QueryAsync("source", "SELECT pg_size_pretty(pg_database_size('source'))")}, " + + $"{await fixture.QueryAsync("source", "SELECT count(*) FROM receipts")} receipts, " + + $"{await fixture.QueryAsync("source", "SELECT count(*) FROM receipt_items")} receipt lines"); + output.WriteLine($"backup: {fixture.ReferenceResult.Value("seconds")} s, " + + $"encrypted file of {long.Parse(fixture.ReferenceResult.Value("bytes")) / 1024} KB"); + output.WriteLine($"restore: {result.Value("seconds")} s, row count checks included"); + } + + [Fact] + public async Task Restore_GivesTheSameControlTotalsAsTheSource() + { + var (database, storage) = await PrepareAsync(); + + await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + + var totals = await fixture.ControlTotalsAsync(database); + Assert.Equal(await fixture.ControlTotalsAsync("source"), totals); + output.WriteLine(totals); + } + + [Fact] + public async Task Restore_HasEveryMigrationOfTheApi() + { + var (database, storage) = await PrepareAsync(); + + await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + + var options = new DbContextOptionsBuilder().UseNpgsql(fixture.ConnectionString(database)).Options; + await using var context = new MoissonDbContext(options); + Assert.Empty(await context.Database.GetPendingMigrationsAsync()); + Assert.Equal(context.Database.GetMigrations(), await context.Database.GetAppliedMigrationsAsync()); + } + + [Fact] + public async Task Api_ReportsHealthy_WhenItRunsOnTheRestoredDatabase() + { + var (database, storage) = await PrepareAsync(); + await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + await using var factory = new WebApplicationFactory().WithWebHostBuilder(builder => builder + .UseEnvironment("Testing") + .UseSetting("ConnectionStrings:Moisson", fixture.ConnectionString(database))); + using var client = factory.CreateClient(); + + var response = await client.GetAsync("/health"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task Restore_LeavesADatabaseThatIsNotEmptyUnchanged_WithoutConfirm() + { + var (database, storage) = await PrepareRestoredAsync(); + await fixture.ExecuteAsync(database, "UPDATE donors SET notes = 'changed after the restore' WHERE name = 'Donor 1'"); + var changed = await fixture.FingerprintsAsync(database); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + + AssertFailedAt("target", result, $"the target database has {await fixture.TableCountAsync("source")} tables, add --confirm to replace them"); + Assert.Equal(changed, await fixture.FingerprintsAsync(database)); + } + + [Fact] + public async Task Restore_ChangesNothing_WhenItFailsHalfway() + { + var (database, storage) = await PrepareRestoredAsync(); + await fixture.ExecuteAsync(database, "UPDATE donors SET notes = 'changed after the restore' WHERE name = 'Donor 1'"); + // pg_restore drops the tables in reverse alphabetical order, so this view stops it after the other tables are dropped. + await fixture.ExecuteAsync(database, """CREATE VIEW blocks_the_restore AS SELECT * FROM "__EFMigrationsHistory" """); + var changed = await fixture.FingerprintsAsync(database); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName, "--confirm"]); + + AssertFailedAt("restore", result); + Assert.Equal(changed, await fixture.FingerprintsAsync(database)); + } + + [Fact] + public async Task Restore_ReplacesADatabaseThatIsNotEmpty_WithConfirm() + { + var (database, storage) = await PrepareRestoredAsync(); + await fixture.ExecuteAsync(database, "UPDATE donors SET notes = 'changed after the restore' WHERE name = 'Donor 1'"); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName, "--confirm"]); + + Assert.Equal(0, result.ExitCode); + Assert.Equal(fixture.SourceFingerprints, await fixture.FingerprintsAsync(database)); + } + + [Fact] + public async Task Restore_KeepsATableThatIsNotInTheBackup_WithConfirm() + { + var (database, storage) = await PrepareRestoredAsync(); + await fixture.ExecuteAsync(database, "CREATE TABLE not_in_the_backup (id int)"); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName, "--confirm"]); + + Assert.Equal(0, result.ExitCode); + Assert.Equal("1", await fixture.QueryAsync(database, "SELECT count(*) FROM pg_tables WHERE tablename = 'not_in_the_backup'")); + } + + [Fact] + public async Task Restore_FailsAtDownload_WhenTheBackupIsNotInTheStorage() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync(database, storage, ["moisson-20000101T000000Z.tar.age"]); + + AssertFailedAt("download", result); + Assert.Equal(0, await fixture.TableCountAsync(database)); + } + + [Fact] + public async Task Restore_FailsAtDownload_WhenTheChecksumFileIsMissing() + { + var database = await fixture.CreateDatabaseAsync(); + var storage = await fixture.CreateStorageAsync(); + await storage.WriteAsync(fixture.ReferenceName, fixture.ReferenceBackup); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + + AssertFailedAt("download", result, $"reason={fixture.ReferenceName}.sha256 could not be downloaded"); + Assert.Equal(0, await fixture.TableCountAsync(database)); + } + + [Fact] + public async Task Restore_FailsAtChecksum_WhenTheBackupIsDamaged() + { + var database = await fixture.CreateDatabaseAsync(); + var storage = await fixture.CreateStorageAsync(); + await storage.WriteAsync(fixture.ReferenceName, Damaged(fixture.ReferenceBackup)); + await storage.WriteAsync(fixture.ReferenceName + ".sha256", fixture.ReferenceChecksum); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + + AssertFailedAt("checksum", result, "the backup file does not match its checksum"); + Assert.Equal(0, await fixture.TableCountAsync(database)); + } + + [Fact] + public async Task Restore_FailsAtDecrypt_WhenTheBackupIsDamagedAndItsChecksumRecalculated() + { + var database = await fixture.CreateDatabaseAsync(); + var storage = await fixture.CreateStorageAsync(); + await fixture.WriteFileAsync("/tmp/damaged/damaged.tar.age", Damaged(fixture.ReferenceBackup)); + await fixture.ShellAsync("cd /tmp/damaged && sha256sum damaged.tar.age > damaged.tar.age.sha256"); + + var result = await fixture.RestoreAsync(database, storage, ["/tmp/damaged/damaged.tar.age"]); + + AssertFailedAt("decrypt", result); + Assert.Equal(0, await fixture.TableCountAsync(database)); + } + + [Fact] + public async Task Restore_FailsAtDecrypt_WithTheWrongPrivateKey() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync( + database, storage, [fixture.ReferenceName], ("BACKUP_AGE_IDENTITY", "/tmp/keys/other.key")); + + AssertFailedAt("decrypt", result); + Assert.Equal(0, await fixture.TableCountAsync(database)); + } + + [Fact] + public async Task Restore_ReportsTheTable_WhenItsRowCountDiffersFromTheManifest() + { + var (database, storage) = await PrepareAsync(); + await fixture.WriteFileAsync("/tmp/counts/reference.tar.age", fixture.ReferenceBackup); + await fixture.ShellAsync($""" + cd /tmp/counts && age --decrypt --identity /tmp/keys/test.key reference.tar.age | tar --extract \ + && sed -i 's/^public.users\t.*/public.users\t999/' manifest.tsv \ + && tar --create database.dump manifest.tsv | age --encrypt --recipient {fixture.PublicKey} > wrong-counts.tar.age \ + && sha256sum wrong-counts.tar.age > wrong-counts.tar.age.sha256 + """); + + var result = await fixture.RestoreAsync(database, storage, ["/tmp/counts/wrong-counts.tar.age"]); + + AssertFailedAt("row counts", result, "1 tables do not have the expected number of rows"); + Assert.Contains("MISMATCH table=public.users expected=999 actual=20", result.Output); + } + + [Fact] + public async Task Restore_RestoresALocalFile() + { + var (database, storage) = await PrepareAsync(); + await fixture.WriteFileAsync("/tmp/local/backup.tar.age", fixture.ReferenceBackup); + await fixture.WriteFileAsync("/tmp/local/backup.tar.age.sha256", + Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(fixture.ReferenceChecksum).Replace(fixture.ReferenceName, "backup.tar.age"))); + + var result = await fixture.RestoreAsync(database, storage, ["/tmp/local/backup.tar.age"]); + + Assert.Equal(0, result.ExitCode); + Assert.Equal(fixture.SourceFingerprints, await fixture.FingerprintsAsync(database)); + } + + [Fact] + public async Task Restore_FailsAtChecksum_WhenALocalFileHasNoChecksumFile() + { + var (database, storage) = await PrepareAsync(); + await fixture.WriteFileAsync("/tmp/no-checksum/backup.tar.age", fixture.ReferenceBackup); + + var result = await fixture.RestoreAsync(database, storage, ["/tmp/no-checksum/backup.tar.age"]); + + AssertFailedAt("checksum", result, "checksum file /tmp/no-checksum/backup.tar.age.sha256 not found"); + Assert.Equal(0, await fixture.TableCountAsync(database)); + } + + [Fact] + public async Task Restore_FailsAtSettings_WhenNoBackupIsGiven() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync(database, storage, []); + + AssertFailedAt("settings", result, "no backup file given"); + } + + [Fact] + public async Task Restore_FailsAtSettings_WhenTheOptionIsUnknown() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName, "--force"]); + + AssertFailedAt("settings", result, "unknown option --force"); + Assert.Equal(0, await fixture.TableCountAsync(database)); + } + + [Fact] + public async Task Restore_FailsAtSettings_WhenThePrivateKeyIsMissing() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName], ("BACKUP_AGE_IDENTITY", "")); + + AssertFailedAt("settings", result, "missing=BACKUP_AGE_IDENTITY"); + } + + [Fact] + public async Task Restore_FailsAtDownload_WhenTheBackupIsNeitherLocalNorReachable() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName], ("BACKUP_STORAGE_SAS", "")); + + AssertFailedAt("download", result, "is not a local file and BACKUP_STORAGE_URL or BACKUP_STORAGE_SAS is not set"); + } + + [Fact] + public async Task Restore_Succeeds_WithAReadOnlySasToken() + { + var (database, storage) = await PrepareAsync(); + + var result = await fixture.RestoreAsync( + database, storage, [fixture.ReferenceName], ("BACKUP_STORAGE_SAS", storage.ReadOnlySas)); + + Assert.Equal(0, result.ExitCode); + Assert.Equal(fixture.SourceFingerprints, await fixture.FingerprintsAsync(database)); + } + + private static string BackupName(DateTime date) => $"moisson-{date:yyyyMMdd'T'HHmmss'Z'}.tar.age"; + + private static byte[] Damaged(byte[] backup) + { + var damaged = backup.ToArray(); + for (var i = 30_000; i < 30_004; i++) + { + damaged[i] = 0xFF; + } + + return damaged; + } + + private static void AssertFailedAt(string step, ScriptResult result, string reason = "") + { + Assert.True(result.ExitCode == 1, $"expected exit code 1, got {result.ExitCode}:\n{result.Output}"); + Assert.Contains($"FAILED step={step}", result.Output); + Assert.Contains(reason, result.Output); + } + + /// + /// Creates an empty target database and a storage container holding the reference backup and its checksum. + /// + private async Task<(string Database, TestStorage Storage)> PrepareAsync() + { + var database = await fixture.CreateDatabaseAsync(); + var storage = await fixture.CreateStorageAsync(); + await storage.WriteAsync(fixture.ReferenceName, fixture.ReferenceBackup); + await storage.WriteAsync(fixture.ReferenceName + ".sha256", fixture.ReferenceChecksum); + return (database, storage); + } + + /// + /// Same as , with the reference backup already restored into the target database. + /// + private async Task<(string Database, TestStorage Storage)> PrepareRestoredAsync() + { + var (database, storage) = await PrepareAsync(); + var result = await fixture.RestoreAsync(database, storage, [fixture.ReferenceName]); + Assert.True(result.ExitCode == 0, $"the reference backup could not be restored:\n{result.Output}"); + return (database, storage); + } +} \ No newline at end of file diff --git a/tests/MoissonMontreal.Tests/Fixtures/BackupFixture.cs b/tests/MoissonMontreal.Tests/Fixtures/BackupFixture.cs new file mode 100644 index 0000000..1da3731 --- /dev/null +++ b/tests/MoissonMontreal.Tests/Fixtures/BackupFixture.cs @@ -0,0 +1,307 @@ +using System.Text; + +using Azure.Storage.Blobs; +using Azure.Storage.Sas; + +using DotNet.Testcontainers.Builders; +using DotNet.Testcontainers.Containers; +using DotNet.Testcontainers.Images; +using DotNet.Testcontainers.Networks; + +using Microsoft.EntityFrameworkCore; + +using MoissonMontreal.Api.Data; +using MoissonMontreal.Tests.Docs; + +using Npgsql; + +using Testcontainers.Azurite; +using Testcontainers.PostgreSql; + +namespace MoissonMontreal.Tests.Fixtures; + +/// +/// Starts PostgreSQL, Azurite and the image of infra/db-backup on one Docker network, fills a source database from the +/// migrations and BackupTestData.sql, and makes one reference backup of it. The scripts run inside a container of the +/// image, exactly as the daily job does. +/// +public sealed class BackupFixture : IAsyncLifetime +{ + private readonly INetwork _network = new NetworkBuilder().Build(); + private readonly PostgreSqlContainer _postgres; + private readonly AzuriteContainer _azurite; + private readonly IFutureDockerImage _image; + private IContainer _scripts = null!; + private int _lastDatabase; + private int _lastStorage; + + public BackupFixture() + { + _postgres = new PostgreSqlBuilder("postgres:17").WithNetwork(_network).WithNetworkAliases("postgres").Build(); + _azurite = new AzuriteBuilder("mcr.microsoft.com/azure-storage/azurite:latest") + .WithNetwork(_network).WithNetworkAliases("azurite").WithCommand("--skipApiVersionCheck").Build(); + _image = new ImageFromDockerfileBuilder() + .WithDockerfileDirectory(Path.Combine(RepositoryPaths.Root, "infra", "db-backup")) + .WithName("moisson-db-backup:test") + .WithCleanUp(false) + .Build(); + } + + public string PublicKey { get; private set; } = ""; + + public string ReferenceName { get; private set; } = ""; + + public byte[] ReferenceBackup { get; private set; } = []; + + public byte[] ReferenceChecksum { get; private set; } = []; + + public ScriptResult ReferenceResult { get; private set; } = new(0, ""); + + public string SourceFingerprints { get; private set; } = ""; + + public async Task InitializeAsync() + { + await _network.CreateAsync(); + await Task.WhenAll(_postgres.StartAsync(), _azurite.StartAsync(), _image.CreateAsync()); + _scripts = new ContainerBuilder(_image).WithNetwork(_network).WithEntrypoint("sleep").WithCommand("infinity").Build(); + await _scripts.StartAsync(); + + PublicKey = await CreateKeyAsync("test"); + await CreateKeyAsync("other"); + + await ExecuteAsync("postgres", "CREATE DATABASE source"); + await ExecuteAsync("postgres", "CREATE DATABASE empty"); + var options = new DbContextOptionsBuilder().UseNpgsql(ConnectionString("source")).Options; + await using (var context = new MoissonDbContext(options)) + { + await context.Database.MigrateAsync(); + } + + await ExecuteAsync("source", await File.ReadAllTextAsync(Path.Combine(RepositoryPaths.Root, "tests", "MoissonMontreal.Tests", "Fixtures", "BackupTestData.sql"))); + SourceFingerprints = await FingerprintsAsync("source"); + + var storage = await CreateStorageAsync(); + ReferenceResult = await BackupAsync(storage); + if (ReferenceResult.ExitCode != 0) + { + throw new InvalidOperationException($"the reference backup failed:\n{ReferenceResult.Output}"); + } + + ReferenceName = ReferenceResult.Value("backup"); + ReferenceBackup = await storage.ReadAsync(ReferenceName); + ReferenceChecksum = await storage.ReadAsync(ReferenceName + ".sha256"); + } + + public async Task DisposeAsync() + { + await _scripts.DisposeAsync(); + await Task.WhenAll(_postgres.DisposeAsync().AsTask(), _azurite.DisposeAsync().AsTask()); + await _network.DisposeAsync(); + } + + /// + /// Connection string of a database of the PostgreSQL container, seen from this machine. + /// + public string ConnectionString(string database) => + new NpgsqlConnectionStringBuilder(_postgres.GetConnectionString()) { Database = database }.ConnectionString; + + /// + /// Creates an empty database with a name that no other test uses. + /// + public async Task CreateDatabaseAsync() + { + var name = $"target_{Interlocked.Increment(ref _lastDatabase)}"; + await ExecuteAsync("postgres", $"CREATE DATABASE {name}"); + return name; + } + + /// + /// Creates an empty Blob Storage container with a name that no other test uses, and its SAS tokens. + /// + public async Task CreateStorageAsync() + { + var name = $"backups-{Interlocked.Increment(ref _lastStorage)}"; + var client = new BlobContainerClient(_azurite.GetConnectionString(), name); + await client.CreateAsync(); + var expiry = DateTimeOffset.UtcNow.AddDays(1); + return new TestStorage( + client, + $"http://azurite:10000/devstoreaccount1/{name}", + client.GenerateSasUri(BlobContainerSasPermissions.All, expiry).Query.TrimStart('?'), + client.GenerateSasUri(BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List, expiry).Query.TrimStart('?')); + } + + /// + /// Runs backup.sh on the source database. A setting given in replaces the default one. + /// + public Task BackupAsync(TestStorage storage, params (string Name, string Value)[] settings) + { + var defaults = new Dictionary + { + ["PGHOST"] = "postgres", + ["PGUSER"] = PostgreSqlBuilder.DefaultUsername, + ["PGPASSWORD"] = PostgreSqlBuilder.DefaultPassword, + ["PGDATABASE"] = "source", + ["BACKUP_AGE_RECIPIENT"] = PublicKey, + ["BACKUP_STORAGE_URL"] = storage.Url, + ["BACKUP_STORAGE_SAS"] = storage.Sas, + }; + return RunAsync("backup.sh", defaults, settings, []); + } + + /// + /// Runs restore.sh into a database. A setting given in replaces the default one. + /// + public Task RestoreAsync( + string database, TestStorage storage, string[] arguments, params (string Name, string Value)[] settings) + { + var defaults = new Dictionary + { + ["PGHOST"] = "postgres", + ["PGUSER"] = PostgreSqlBuilder.DefaultUsername, + ["PGPASSWORD"] = PostgreSqlBuilder.DefaultPassword, + ["PGDATABASE"] = database, + ["BACKUP_AGE_IDENTITY"] = "/tmp/keys/test.key", + ["BACKUP_STORAGE_URL"] = storage.Url, + ["BACKUP_STORAGE_SAS"] = storage.Sas, + }; + return RunAsync("restore.sh", defaults, settings, arguments); + } + + /// + /// Writes a file inside the container that runs the scripts, so restore.sh can read it as a local backup. The + /// folder is created first by the user of the image, so the scripts can also write next to the file. + /// The folder is cut at the last '/' instead of using Path.GetDirectoryName, which gives a Windows path with + /// backslashes when the tests run on Windows. + /// + public async Task WriteFileAsync(string path, byte[] content) + { + await ShellAsync($"mkdir -p {path[..path.LastIndexOf('/')]}"); + await _scripts.CopyAsync(content, path); + } + + /// + /// Runs a shell command inside the container that runs the scripts, and fails if it does not succeed. + /// Line endings are turned into \n first: on a Windows checkout, a multi-line command written in a test file has + /// \r\n line endings, and bash refuses the \r. + /// + public async Task ShellAsync(string command) + { + var result = await _scripts.ExecAsync(["bash", "-c", command.ReplaceLineEndings("\n")]); + if (result.ExitCode != 0) + { + throw new InvalidOperationException($"{command}\n{result.Stdout}{result.Stderr}"); + } + } + + public async Task ExecuteAsync(string database, string sql) + { + await using var connection = new NpgsqlConnection(ConnectionString(database)); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand(sql, connection); + await command.ExecuteNonQueryAsync(); + } + + public async Task QueryAsync(string database, string sql) + { + await using var connection = new NpgsqlConnection(ConnectionString(database)); + await connection.OpenAsync(); + await using var command = new NpgsqlCommand(sql, connection); + return Convert.ToString(await command.ExecuteScalarAsync(), System.Globalization.CultureInfo.InvariantCulture) ?? ""; + } + + public async Task TableCountAsync(string database) => int.Parse(await QueryAsync(database, + "SELECT count(*) FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')")); + + /// + /// Returns one line per table with a fingerprint of all its rows, and one line for the indexes and constraints, so + /// two databases can be compared value by value. Constraints are compared by name and type only, because + /// PostgreSQL rewrites the text of a CHECK constraint when it restores it. + /// + public async Task FingerprintsAsync(string database) + { + var lines = new StringBuilder(); + lines.AppendLine("indexes and constraints " + await QueryAsync(database, """ + SELECT md5(string_agg(definition, E'\n' ORDER BY definition)) FROM ( + SELECT indexdef AS definition FROM pg_indexes WHERE schemaname = 'public' + UNION ALL + SELECT conname || ' ' || contype::text FROM pg_constraint WHERE connamespace = 'public'::regnamespace) AS d + """)); + var tables = (await QueryAsync(database, + "SELECT string_agg(tablename, ',' ORDER BY tablename) FROM pg_tables WHERE schemaname = 'public'")).Split(','); + foreach (var table in tables) + { + lines.AppendLine($"{table} " + await QueryAsync(database, $""" + SELECT count(*) || ' rows ' || md5(coalesce(string_agg(t::text, E'\n' ORDER BY t::text), '')) + FROM public."{table}" AS t + """)); + } + + return lines.ToString(); + } + + /// + /// Returns totals that the business relies on, to compare the source and a restored database. + /// + public async Task ControlTotalsAsync(string database) => string.Join("\n", + await QueryAsync(database, "SELECT 'issued receipts total: ' || sum(total_amount) FROM receipts WHERE status = 'Issued'"), + await QueryAsync(database, "SELECT 'receipts per status: ' || string_agg(status || '=' || n, ' ' ORDER BY status) FROM (SELECT status, count(*) AS n FROM receipts GROUP BY status) AS s"), + await QueryAsync(database, "SELECT 'last receipt number: ' || max(receipt_number) || ', counter: ' || (SELECT last_number FROM receipt_number_counters WHERE series = 'DEN') FROM receipts"), + await QueryAsync(database, "SELECT 'receipt lines value: ' || sum(quantity * unit_price * quality_percent / 100) FROM receipt_items")); + + private async Task CreateKeyAsync(string name) + { + await ShellAsync($"mkdir -p /tmp/keys && age-keygen -o /tmp/keys/{name}.key"); + var key = Encoding.UTF8.GetString(await _scripts.ReadFileAsync($"/tmp/keys/{name}.key")); + return key.Split('\n').Single(line => line.StartsWith("# public key: ")).Replace("# public key: ", ""); + } + + private async Task RunAsync( + string script, Dictionary defaults, (string Name, string Value)[] settings, string[] arguments) + { + foreach (var (name, value) in settings) + { + defaults[name] = value; + } + + var command = new List { "env" }; + command.AddRange(defaults.Select(setting => $"{setting.Key}={setting.Value}")); + command.Add(script); + command.AddRange(arguments); + var result = await _scripts.ExecAsync(command); + return new ScriptResult(result.ExitCode ?? -1, result.Stdout + result.Stderr); + } +} + +/// +/// Exit code and output (standard output then errors) of backup.sh or restore.sh. +/// +public sealed record ScriptResult(long ExitCode, string Output) +{ + /// + /// Reads a value written as name=value on the SUCCESS line, such as the name of the backup or the seconds it took. + /// + public string Value(string name) => Output.Split('\n').Single(line => line.Contains(" SUCCESS ")) + .Split(' ').Single(part => part.StartsWith(name + "="))[(name.Length + 1)..]; +} + +/// +/// A Blob Storage container of Azurite, with its URL seen from the scripts and its SAS tokens. +/// +public sealed record TestStorage(BlobContainerClient Client, string Url, string Sas, string ReadOnlySas) +{ + public async Task> NamesAsync() + { + var names = new List(); + await foreach (var blob in Client.GetBlobsAsync()) + { + names.Add(blob.Name); + } + + return names; + } + + public async Task ReadAsync(string name) => (await Client.GetBlobClient(name).DownloadContentAsync()).Value.Content.ToArray(); + + public Task WriteAsync(string name, byte[] content) => Client.GetBlobClient(name).UploadAsync(new BinaryData(content), overwrite: true); +} \ No newline at end of file diff --git a/tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql b/tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql new file mode 100644 index 0000000..d1abee2 --- /dev/null +++ b/tests/MoissonMontreal.Tests/Fixtures/BackupTestData.sql @@ -0,0 +1,71 @@ +-- Test data for BackupFixture, loaded into a database created from the migrations. +-- 20 employees, 2,000 donors, 2,000 catalog items with their prices, 10,000 receipts with 5 donated food items each, +-- and text that is hard to copy (line breaks, tabs, backslashes, accents). + +INSERT INTO users (email, display_name, role_id) +SELECT 'employee' || i || '@example.org', 'Employee ' || i, i % 4 + 1 +FROM generate_series(1, 20) AS i; + +INSERT INTO donors (id, name, type, business_central_code, city, notes) +SELECT md5('donor' || i)::uuid, + 'Donor ' || i, + CASE WHEN i % 3 = 0 THEN 'individual' ELSE 'organization' END, + 'D' || lpad(i::text, 6, '0'), + 'Montréal', + CASE i % 4 WHEN 0 THEN E'Line one\nLine two' WHEN 1 THEN E'Tab\there' WHEN 2 THEN E'Back\\slash' ELSE E'\\.' END +FROM generate_series(1, 2000) AS i; + +INSERT INTO catalog_items (id, name, business_central_code, category, unit, quality_class) +SELECT md5('catalog' || i)::uuid, 'Article ' || i, 'BC' || lpad(i::text, 7, '0'), 'Category ' || i % 20, 'kg', + (ARRAY['A', 'B', 'C', NULL])[i % 4 + 1] +FROM generate_series(1, 2000) AS i; + +INSERT INTO prices (catalog_item_id, unit_price, effective_date) +SELECT md5('catalog' || i)::uuid, round((i % 500 + 1) / 100.0 + 0.99, 2), DATE '2026-01-01' +FROM generate_series(1, 2000) AS i; + +INSERT INTO bc_item_mappings (business_central_code, catalog_item_id, confirmed_by_user_id, confirmed_at) +SELECT 'BCX' || i, md5('catalog' || i)::uuid, (SELECT min(id) FROM users), TIMESTAMPTZ '2026-01-01 12:00:00+00' +FROM generate_series(1, 500) AS i; + +INSERT INTO bc_item_mapping_changes (business_central_code, action, new_catalog_item_id, changed_by_user_id) +SELECT 'BCX' || i, 'Created', md5('catalog' || i)::uuid, (SELECT min(id) FROM users) +FROM generate_series(1, 500) AS i; + +-- One receipt in four is issued and gets a receipt number; the others are at an earlier status. +INSERT INTO receipts (id, donor_id, total_amount, receipt_date, status, receipt_number) +SELECT md5('receipt' || r)::uuid, + md5('donor' || ((r - 1) % 2000 + 1))::uuid, + round((r * 37 % 100000) / 100.0, 2), + DATE '2026-01-01' + r % 300, + (ARRAY['Issued', 'Draft', 'PendingFinanceApproval', 'Approved'])[r % 4 + 1], + CASE WHEN r % 4 = 0 THEN 'DEN_' || lpad((r / 4)::text, 6, '0') END +FROM generate_series(1, 10000) AS r; + +UPDATE receipt_number_counters SET last_number = 2500 WHERE series = 'DEN'; + +INSERT INTO receipt_status_changes (receipt_id, from_status, to_status, changed_by_user_id) +SELECT md5('receipt' || r)::uuid, 'Approved', 'Issued', (SELECT min(id) FROM users) +FROM generate_series(4, 10000, 4) AS r; + +-- Food item f belongs to receipt (f - 1) / 5 + 1, so it has the same donor as its receipt. +INSERT INTO food_items (id, donor_id, name, quantity, unit, donation_date, quality, catalog_item_id) +SELECT md5('food' || f)::uuid, + md5('donor' || ((f - 1) / 5 % 2000 + 1))::uuid, + 'Food ' || f, + f % 50 + 0.5, + 'kg', + DATE '2026-01-01' + f % 300, + (ARRAY['A', 'B', 'C'])[f % 3 + 1], + md5('catalog' || (f % 2000 + 1))::uuid +FROM generate_series(1, 50000) AS f; + +INSERT INTO receipt_items (receipt_id, food_item_id, donor_id, quantity, unit, unit_price, quality_percent) +SELECT md5('receipt' || ((f - 1) / 5 + 1))::uuid, + md5('food' || f)::uuid, + md5('donor' || ((f - 1) / 5 % 2000 + 1))::uuid, + f % 50 + 0.5, + 'kg', + round((f % 500 + 1) / 100.0 + 0.99, 2), + (ARRAY[100, 50, 0])[f % 3 + 1] +FROM generate_series(1, 50000) AS f; diff --git a/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj b/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj index 4aae91e..4c752b6 100644 --- a/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj +++ b/tests/MoissonMontreal.Tests/MoissonMontreal.Tests.csproj @@ -8,9 +8,11 @@ + +