diff --git a/AGENTS.md b/AGENTS.md index 68d4f0c..b426cbd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,10 +20,14 @@ visa.buildfor.life holds passport data of real people. Read this file and upload (multipart) is the one exception in the guard: its handler checks the token itself, which must be the form's first field, before it reads a file (`src/web/documents.rs`). -- **Documents** are encrypted files in `VISA_FILES_DIR` (`src/files.rs`); - never write a document's file another way, and never log its contents or - its name. Opening a file is a `view` of the document, saving it a - `download`. Local files and their key live in `.dev/`, which git ignores. +- **Documents** are files the app encrypts before it stores them + (`src/files.rs`): in a bucket of the fleet's Garage on the server + (`VISA_S3_*`, `src/s3.rs`), in a directory in development + (`VISA_FILES_DIR`). Never write a document's file another way, never send + one unencrypted to the bucket, and never log its contents or its name. + Opening a file is a `view` of the document, saving it a `download`. Local + files, the dev Garage's key and the file key live in `.dev/`, which git + ignores. - **No inline script or style.** The Content Security Policy refuses them; `tests/pages.rs` checks the templates. - **Migrations** are never edited once they are on `main`; add a new file. @@ -57,7 +61,7 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | Path | What | | --------------------- | --------------------------------------------------------------------- | -| `src/main.rs` | the commands `serve`, `migrate`, `seed-demo`, `files-check` | +| `src/main.rs` | the commands `serve`, `migrate`, `seed-demo`, `files-check`, `files-migrate`, `files-mirror` | | `src/config.rs` | settings from the environment and credentials | | `src/oidc.rs` | OpenID Connect against Kanidm (PKCE, nonce, ES256), from the fleet overview | | `src/session.rs` | sessions in PostgreSQL, keyed by the SHA-256 of the cookie | @@ -67,8 +71,9 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | `src/deadlines.rs` | the deadline rules as a pure function (`assess`), and loading their facts | | `src/companies.rs` | what only companies need: list, archive, selections, employees | | `src/mrz.rs` | reading the passport's machine-readable zone (ICAO 9303, TD3) | -| `src/files.rs` | the encrypted document store: sealing, opening, checking a file's type | -| `src/documents.rs` | documents of people and companies: kinds, records, SQL, `files-check` | +| `src/files.rs` | the encrypted document store (a bucket or a directory): sealing, opening, the mirror for backups, checking a file's type | +| `src/s3.rs` | a small S3 client with SigV4 signing, for the bucket in Garage | +| `src/documents.rs` | documents of people and companies: kinds, records, SQL, `files-check`, `files-migrate` | | `src/web/` | routes, the login gate, pages | | `templates/` | minijinja templates, compiled in by `build.rs` | | `static/` | CSS and JavaScript, compiled in; the URL carries a content hash | diff --git a/README.md b/README.md index 4ccfdfb..1b4f873 100644 --- a/README.md +++ b/README.md @@ -33,8 +33,10 @@ Data Protection Act (PDPA) asks. - Documents: scans and photos of the passport pages, the TDAC, receipts and the photo, dropped on a dashed strip, several at a time, and filed under the record they belong to. A company keeps its own documents for the - extension packs. The files are encrypted on the server, open in the - browser's viewer, and every upload, view and download is in the log. + extension packs. The app encrypts each file before it stores it in a + bucket of the fleet's Garage, so the bucket and its backups hold no + document in the clear. The files open in the browser's viewer, and every + upload, view and download is in the log. - Forms, filled in from the records on the Immigration Bureau's own pages: TM.7, STM.2, STM.9, STM.11 and STM.1 for an extension of stay, TM.47 for a 90-day report and TM.8 for a re-entry permit. Each opens as a PDF or @@ -73,6 +75,15 @@ demo documents. The documents and their key lie in `.dev/`, which git ignores. The demo command refuses to run when a login provider is configured. +On the server the documents lie in a bucket of Garage, the fleet's S3 store. +`bash scripts/dev-garage.sh` starts the same Garage version in Docker on +127.0.0.1:3920 with a bucket and a key; `VISA_DEV_S3=1 bash scripts/dev.sh` +then keeps the demo documents there, and `. .dev/garage.env` before +`cargo test` adds the test against it (`tests/garage.rs`), which is skipped +otherwise. Every other test of the bucket runs against a small S3 server +inside the test (`tests/common/fake_s3.rs`) that checks each request's +signature. + The tests need the same database; each test gets its own: ```sh @@ -85,34 +96,47 @@ cargo fmt --all --check && cargo clippy --all-targets -- -D warnings && cargo te The server reads its settings from the environment. Secrets are read from files or systemd credentials and never from a variable's value. -| Variable | Meaning | -| ------------------------------ | -------------------------------------------------------------- | -| `VISA_LISTEN` | address to listen on, default `127.0.0.1:8040` | -| `VISA_PUBLIC_URL` | `https://visa.buildfor.life`, for the login's redirect | -| `VISA_DATABASE_URL` | `postgres://visa@host/visa` | -| `VISA_DATABASE_PASSWORD_FILE` | the role's password; else the credential `db-password` | -| `VISA_OIDC_ISSUER` | `https://id.cnx.network/oauth2/openid/visa-web` | -| `VISA_OIDC_CLIENT_ID` | default `visa-web` | -| `VISA_OIDC_CLIENT_SECRET_FILE` | the client secret; else the credential `oidc-client-secret` | -| `VISA_OIDC_GROUP` | default `visa` | -| `VISA_INSECURE_NO_LOGIN` | `1` runs without a login, on loopback addresses only | -| `VISA_FILES_DIR` | where the encrypted documents lie (`/var/lib/visa/files`) | -| `VISA_FILES_KEY_FILE` | the file key, 64 hex digits; else the credential `files-key` | +| Variable | Meaning | +| -------------------------------- | --------------------------------------------------------------- | +| `VISA_LISTEN` | address to listen on, default `127.0.0.1:8040` | +| `VISA_PUBLIC_URL` | `https://visa.buildfor.life`, for the login's redirect | +| `VISA_DATABASE_URL` | `postgres://visa@host/visa` | +| `VISA_DATABASE_PASSWORD_FILE` | the role's password; else the credential `db-password` | +| `VISA_OIDC_ISSUER` | `https://id.cnx.network/oauth2/openid/visa-web` | +| `VISA_OIDC_CLIENT_ID` | default `visa-web` | +| `VISA_OIDC_CLIENT_SECRET_FILE` | the client secret; else the credential `oidc-client-secret` | +| `VISA_OIDC_GROUP` | default `visa` | +| `VISA_INSECURE_NO_LOGIN` | `1` runs without a login, on loopback addresses only | +| `VISA_S3_BUCKET` | the bucket the encrypted documents lie in (`visa-documents`) | +| `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` for cnx01's Garage | +| `VISA_S3_REGION` | default `garage` | +| `VISA_S3_ACCESS_KEY_ID` | the bucket key's id | +| `VISA_S3_SECRET_ACCESS_KEY_FILE` | the bucket key's secret; else the credential `s3-secret` | +| `VISA_FILES_DIR` | a directory for the documents instead of a bucket (development) | +| `VISA_FILES_KEY_FILE` | the file key, 64 hex digits; else the credential `files-key` | -With the login on, the app does not start without the files directory and -the file key. Local development may go without them, and documents are then -switched off. The key never changes: the files cannot be read without it. +With the login on, the app does not start without a place for the documents +(the bucket, or a directory) and the file key. Local development may go +without them, and documents are then switched off. The key never changes: the +files cannot be read without it. The bucket only ever receives files the app +has encrypted, so Garage holds no key and no document in the clear. `visa serve` (the default) applies pending migrations before it listens, `visa migrate` applies them alone, `visa seed-demo` adds the demo people and documents, and `visa files-check` reads every document's file back, compares it with its upload and lists files that belong to no document. +`visa files-migrate --from DIR` copies the documents' files from a directory +into the bucket, each checked against its upload, and may run again; +`visa files-mirror --to DIR` makes a directory hold exactly the bucket's +files, still encrypted, for the backups, and a restore is `files-migrate` +from that directory. ## Where it runs Since November 17, 2026 the app runs on cnx01 in the office, like proplan and -lampbench-web: the database `visa` on cnx01's PostgreSQL, backups by borg, and -bkk01 publishing https://visa.buildfor.life. Passport data stays on B4L's own +lampbench-web: the database `visa` on cnx01's PostgreSQL, the documents in the +bucket `visa-documents` of cnx01's Garage, backups by borg, and bkk01 +publishing https://visa.buildfor.life. Passport data stays on B4L's own servers. The fleet's module is `modules/visa` in cnx-network-clan, with its runbook in `docs/src/visa.md` there. Only members of the Kanidm group `visa` get in; members are set in the fleet's `identity/people.nix`. diff --git a/docs/PLAN.md b/docs/PLAN.md index 9238268..06d46ee 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,10 +1,11 @@ # visa.buildfor.life: plan -> Phases 1 to 3 built on November 17, 2026, phase 4's app side and phase 5 -> on November 18, 2026. The live app at https://visa.buildfor.life has phases -> 1 to 3 until cnx-network-clan PR #126 (task 4.6) is deployed and the fleet's -> `visa` input is updated to the newest commit. **Resume here: phase 6, the -> Non-B extension pack.** +> Phases 1 to 3 built on November 17, 2026, phases 4 and 5 on November 18, +> 2026, all live at https://visa.buildfor.life. On November 19, 2026 the +> documents moved from a directory on cnx01 into a bucket of cnx01's Garage +> (task 4.8); the app side is built, and the fleet side (task 4.9) goes live +> once its cnx-network-clan pull request is deployed. **Resume here: phase 6, +> the Non-B extension pack.** visa.buildfor.life keeps the immigration records of the foreigners that B4L looks after: their passports, addresses in Thailand, arrivals with the Thailand @@ -25,7 +26,8 @@ The first round of questions was answered on November 17, 2026. | Question | Decision | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Where it runs | cnx01, installed on the host like proplan and lampbench: database `visa` on cnx01's PostgreSQL, files in a ZFS dataset, encrypted by the app, borg backups to juliet | +| Where it runs | cnx01, installed on the host like proplan and lampbench: database `visa` on cnx01's PostgreSQL, documents in its Garage, encrypted by the app, borg backups to juliet | +| Documents in Garage | bucket `visa-documents` on cnx01's Garage, 10 GB (Nov 19, 2026); the app encrypts each file before it leaves the app, so Garage holds no key; Garage's SSE-C is off | | How it is published | bkk01 publishes `visa.buildfor.life` through a `modules/web-sites` app entry | | Login | Kanidm at id.cnx.network, OAuth2 client `visa-web`, group `visa` with grabowski and oltmanns | | Who sees what | every member of `visa` sees and edits every record, as agency staff would; a view for clients comes later | @@ -60,15 +62,19 @@ inline script or style. (PDPA). Every view of a person and every change is written to `audit_log` with the login, the record and the names of the changed fields, never their values. The table refuses updates and deletes. The Activity page lists it. -- **Documents.** Scans and photos lie in a files directory on the server, - one file per document, encrypted by the app with AES-256-GCM. Each file has - a key of its own, derived with HKDF-SHA256 from the app's file key and a - random salt in the file's header, and the document's id is authenticated - with it, so a file renamed to another document's id does not open. The - file key is a systemd credential that is never in the database, so neither - the files nor their backups can be read without it. The database holds what - is known about each file: its kind, the record it belongs to, the date on - it, a note, its name, type, size and SHA-256. +- **Documents.** Scans and photos lie in the bucket `visa-documents` of + cnx01's Garage, one object per document, encrypted by the app with + AES-256-GCM before they leave it. Each file has a key of its own, derived + with HKDF-SHA256 from the app's file key and a random salt in the file's + header, and the document's id is authenticated with it, so a file renamed + to another document's id does not open. The file key is a systemd + credential that is never in the database or in Garage, so neither the + bucket nor its backups can be read without it. A small S3 client of the + app's own (SigV4 signing on reqwest and ring, as proplan does) talks to the + bucket and never replaces an object; in local development the same files + lie in a directory instead. What is known about each file is in the + database: its kind, the record it belongs to, the date on it, a note, its + name, type, size and SHA-256. - **Passport data entry.** The two lines of the machine-readable zone (MRZ) at the bottom of the photo page fill the name, nationality, date of birth, sex, passport number, issuing state and expiry date. Their check digits @@ -93,7 +99,7 @@ made of. | `reentry_permits` | TM.8 permits, single or multiple, valid until | 2 | | `ninety_day_reports` | the report date, the way it was filed, the receipt and the next due date printed on it | 2 | | `work_permits` | number, employer (a company), position, validity | 2 | -| `documents` | uploads of a person (tied to one of their records, or none) or of a company: kind, date on the document, note, file name, type, size, SHA-256; the file itself is encrypted on disk | 4 | +| `documents` | uploads of a person (tied to one of their records, or none) or of a company: kind, date on the document, note, file name, type, size, SHA-256; the file itself lies encrypted in the bucket | 4 | ## Deadline rules @@ -170,7 +176,7 @@ dark at desktop and phone width, a commit and a push. | 1 | App, Kanidm login, people, passports with MRZ reading, addresses in Thailand, audit log, demo data, CI | built Nov 17, 2026 | | 2 | Companies; stays: visas, arrivals with TDAC, extensions, re-entry permits, 90-day reports, work permits; deadlines | built Nov 17, 2026 | | 3 | On cnx01: flake package, fleet module, Kanidm client and group, bkk01 site, backups; real data from here on | live Nov 17, 2026 | -| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) on the dataset `zroot/visa` with a key var, viewing and download, all audited; the office's GPS position and photo | app built Nov 18, 2026; fleet in PR #126 | +| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) in a bucket of cnx01's Garage (first on the dataset `zroot/visa`) with a key var, viewing and download, all audited; the office's GPS position and photo | live Nov 18, 2026; Garage built Nov 19, 2026 | | 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment (STM.9), STM.11, STM.1, TM.47 and TM.8 as PDF | built Nov 18, 2026 | | 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | | | 7 | Reminders by Matrix room message and by email | | @@ -259,13 +265,13 @@ one `Kind`. (`audit_log.company_id`). `visa files-check` reads every file back and lists damaged, missing and stray files. `visa seed-demo` adds demo documents: PDFs marked as demos and PNGs of shapes. -- [ ] 4.6 Fleet: the dataset `zroot/visa` at `/var/lib/visa` with the files +- [x] 4.6 Fleet: the dataset `zroot/visa` at `/var/lib/visa` with the files in `files/`, the var `visa-files` with the key, the files in cnx01's - borg backups, and the VM test uploading a scan through the login. Built - and checked in cnx-network-clan PR #126 (branch `visa-files`, opened - Nov 18, 2026); Alex merges and deploys it, together with the flake - update #125 that cnx01 and control do not run yet. After the deploy: - `visa-admin files-check` on cnx01 and an upload on the live app. + borg backups, and the VM test uploading a scan through the login + (cnx-network-clan PR #126, merged and deployed on November 18, 2026). + By November 19 four real documents had arrived on the live app, and + `visa-admin files-check` on cnx01 read all four back without a + problem. - [x] 4.7 A company's office, asked for on November 18, 2026: its GPS position on the company form, read from the numbers Google Maps copies, a link to the place on Google Maps or OpenStreetMap, or @@ -275,6 +281,31 @@ one `Kind`. of the office, and a strip that adds a photo and returns to the card. The photos are documents of the kind "Photo of the office", so they are encrypted and audited like every other file. +- [x] 4.8 Documents in Garage, asked for on November 19, 2026: the files + lie in the bucket `visa-documents` of cnx01's Garage instead of the + dataset, as the fleet's other apps keep theirs, so the app can later + move into a guest of its own without its files. The app encrypts each + file exactly as before, so the bucket holds the same `VISADOC1` files + and never a key; Garage's SSE-C stays off, since its key would come + from the same secret. A small S3 client (`src/s3.rs`, SigV4 on reqwest + and ring, as in proplan) asks before it writes, so no object is ever + replaced (Garage 2.5 ignores the `If-None-Match: *` it sends as well), + and tries a busy server three times. `VISA_S3_*` name the bucket and the key; the secret + comes from the credential `s3-secret`. `visa files-migrate --from DIR` + copies the files of a directory into the bucket, each opened and + compared with its upload before and after, and may run again; + `visa files-mirror --to DIR` keeps a copy of the bucket, still + encrypted, for the backups, and a restore is `files-migrate` from it. + The tests run against an S3 server inside the test that checks every + signature (`tests/common/fake_s3.rs`), and `tests/garage.rs` against + the Garage version cnx01 runs (`scripts/dev-garage.sh`). +- [ ] 4.9 Fleet: the key `visa` and the bucket `visa-documents` (10 GB) in + cnx01's Garage, the app's S3 settings, the four live documents moved + into the bucket at the first start (`files/` then becomes + `files-before-s3`, kept a week), `visa-mirror` before each borg run + into `/var/lib/visa/s3-mirror`, and the VM test moving a scan from the + directory into the bucket through the deploy. After the deploy: + `visa-admin files-check` on cnx01 and an upload on the live app. ### Phase 5: filled-in forms diff --git a/scripts/dev-garage.sh b/scripts/dev-garage.sh new file mode 100755 index 0000000..d67e1c1 --- /dev/null +++ b/scripts/dev-garage.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# A Garage in Docker for local development and tests/garage.rs, the version +# cnx01 runs (dxflrs/garage:v2.5.0), on 127.0.0.1:3920: bucket visa-documents +# with the key visa-dev. It writes .dev/garage.env (git ignores .dev/) with +# the VISA_TEST_S3_* settings; the key's secret goes to .dev/s3-secret and +# never to the terminal. Run it again at any time: it starts what is stopped +# and keeps what exists. +# +# bash scripts/dev-garage.sh +# . .dev/garage.env && cargo test garage # the store against Garage +# VISA_DEV_S3=1 bash scripts/dev.sh # the dev server on the bucket +set -euo pipefail +cd "$(dirname "$0")/.." +NAME=visa-garage +PORT=${VISA_GARAGE_PORT:-3920} +BUCKET=visa-documents +mkdir -p .dev/garage +if ! docker inspect "$NAME" >/dev/null 2>&1; then + rpc=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n') + cat >.dev/garage/garage.toml </dev/null +else + docker start "$NAME" >/dev/null +fi +g() { docker exec -e RUST_LOG=warn "$NAME" /garage "$@"; } +for _ in $(seq 30); do + g status >/dev/null 2>&1 && break + sleep 1 +done +if ! g layout show 2>/dev/null | grep -q 'dc1'; then + node=$(g status 2>/dev/null | awk '/^[0-9a-f]{16}/ {print $1; exit}') + g layout assign -z dc1 -c 1G "$node" >/dev/null + g layout apply --version 1 >/dev/null +fi +g bucket info "$BUCKET" >/dev/null 2>&1 || g bucket create "$BUCKET" >/dev/null +id=$(cat .dev/s3-key-id 2>/dev/null || true) +if [ -z "$id" ] || [ ! -s .dev/s3-secret ] || ! g key info "$id" >/dev/null 2>&1; then + out=$(g key create visa-dev) + awk -F': *' 'tolower($1) ~ /key id/ {print $2; exit}' <<<"$out" | tr -d '\r\n ' >.dev/s3-key-id + (umask 077 && awk -F': *' 'tolower($1) ~ /secret key/ {print $2; exit}' <<<"$out" | + tr -d '\r\n ' >.dev/s3-secret) + id=$(cat .dev/s3-key-id) +fi +g bucket allow --read --write --owner "$BUCKET" --key "$id" >/dev/null +cat >.dev/garage.env < .dev/files.key # relative paths: a Windows build reads them the same -export VISA_FILES_DIR=${VISA_FILES_DIR:-.dev/files} export VISA_FILES_KEY_FILE=${VISA_FILES_KEY_FILE:-.dev/files.key} +if [ "${VISA_DEV_S3:-}" = 1 ]; then + bash scripts/dev-garage.sh # starts it when it is stopped + . .dev/garage.env + export VISA_S3_ENDPOINT=$VISA_TEST_S3_ENDPOINT + export VISA_S3_BUCKET=$VISA_TEST_S3_BUCKET + export VISA_S3_ACCESS_KEY_ID=$VISA_TEST_S3_ACCESS_KEY_ID + export VISA_S3_SECRET_ACCESS_KEY_FILE=$VISA_TEST_S3_SECRET_FILE + unset VISA_FILES_DIR +else + export VISA_FILES_DIR=${VISA_FILES_DIR:-.dev/files} +fi cargo build -q ./target/debug/visa seed-demo exec ./target/debug/visa serve diff --git a/src/config.rs b/src/config.rs index 79c7247..c8d6b12 100644 --- a/src/config.rs +++ b/src/config.rs @@ -12,11 +12,17 @@ //! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` | //! | `VISA_OIDC_GROUP` | default `visa` | //! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only | -//! | `VISA_FILES_DIR` | where the encrypted documents lie | +//! | `VISA_S3_BUCKET` | the bucket the encrypted documents lie in | +//! | `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` (Garage) | +//! | `VISA_S3_REGION` | default `garage` | +//! | `VISA_S3_ACCESS_KEY_ID` | the bucket key's id | +//! | `VISA_S3_SECRET_ACCESS_KEY_FILE` | its secret (else credential `s3-secret`) | +//! | `VISA_FILES_DIR` | a directory for them instead (development) | //! | `VISA_FILES_KEY_FILE` | the file key (else credential `files-key`) | //! -//! With the login on, documents are required: the files directory and the -//! file key. Local development may go without them; uploads are then off. +//! With the login on, documents are required: a place for them (the bucket, +//! or a directory) and the file key. Local development may go without them; +//! uploads are then off. use std::net::SocketAddr; use std::path::PathBuf; @@ -24,6 +30,7 @@ use std::path::PathBuf; use anyhow::{Context, Result, bail, ensure}; use crate::files::FileKey; +use crate::s3::S3Config; #[derive(Clone, Debug)] pub struct Config { @@ -33,16 +40,33 @@ pub struct Config { pub database_url: String, pub database_password: Option, pub auth: Auth, - /// Documents: off in local development without a files directory. + /// Documents: off in local development without a place for them. pub files: Option, } #[derive(Clone, Debug)] pub struct FilesConfig { - pub dir: PathBuf, + pub place: FilesPlace, pub key: FileKey, } +/// Where the encrypted files lie. +#[derive(Clone, Debug)] +pub enum FilesPlace { + /// A bucket of an S3 store: the fleet's Garage. + Bucket(S3Config), + /// A directory: local development and the tests. + Dir(PathBuf), +} + +/// The S3 settings that only mean something with `VISA_S3_BUCKET`. +const S3_VARS: [&str; 4] = [ + "VISA_S3_ENDPOINT", + "VISA_S3_REGION", + "VISA_S3_ACCESS_KEY_ID", + "VISA_S3_SECRET_ACCESS_KEY_FILE", +]; + #[derive(Clone, Debug)] pub enum Auth { Oidc(OidcConfig), @@ -127,22 +151,39 @@ impl Config { Some(path) => Some(read_file(&PathBuf::from(path), "the file key")?), None => credential(var, "files-key")?, }; - let files = match (var("VISA_FILES_DIR"), key) { - (Some(dir), Some(key)) => Some(FilesConfig { - dir: PathBuf::from(dir), + let place = match (var("VISA_S3_BUCKET"), var("VISA_FILES_DIR")) { + (Some(_), Some(_)) => bail!( + "VISA_S3_BUCKET and VISA_FILES_DIR are both set: the documents lie in one place, \ + the bucket or the directory" + ), + (Some(bucket), None) => Some(FilesPlace::Bucket(s3_config(var, bucket)?)), + (None, dir) => { + if let Some(v) = S3_VARS.iter().find(|v| var(v).is_some()) { + bail!("{v} is set but VISA_S3_BUCKET is not"); + } + dir.map(|d| FilesPlace::Dir(PathBuf::from(d))) + } + }; + let files = match (place, key) { + (Some(place), Some(key)) => Some(FilesConfig { + place, key: FileKey::from_hex(&key).context("reading the file key")?, }), (None, None) => None, (Some(_), None) => bail!( - "VISA_FILES_DIR is set but there is no file key: set VISA_FILES_KEY_FILE or pass \ - the credential files-key" + "the documents have a place but there is no file key: set VISA_FILES_KEY_FILE or \ + pass the credential files-key" + ), + (None, Some(_)) => bail!( + "there is a file key but no place for the documents: set VISA_S3_BUCKET with the \ + S3 settings, or VISA_FILES_DIR" ), - (None, Some(_)) => bail!("there is a file key but no VISA_FILES_DIR"), }; if matches!(auth, Auth::Oidc(_)) && files.is_none() { bail!( - "documents are not set up: with the login on, set VISA_FILES_DIR and the file \ - key (VISA_FILES_KEY_FILE or the credential files-key)" + "documents are not set up: with the login on, set VISA_S3_BUCKET with the S3 \ + settings (or VISA_FILES_DIR) and the file key (VISA_FILES_KEY_FILE or the \ + credential files-key)" ); } Ok(Config { @@ -164,6 +205,30 @@ impl Config { } } +/// The bucket's settings; the secret from its file or the credential +/// `s3-secret`. +fn s3_config(var: &dyn Fn(&str) -> Option, bucket: String) -> Result { + let need = + |name: &str| var(name).with_context(|| format!("VISA_S3_BUCKET is set but {name} is not")); + let secret_access_key = match var("VISA_S3_SECRET_ACCESS_KEY_FILE") { + Some(path) => read_file(&PathBuf::from(path), "the S3 secret key")?, + None => credential(var, "s3-secret")?.context( + "VISA_S3_BUCKET is set but there is no S3 secret key: set \ + VISA_S3_SECRET_ACCESS_KEY_FILE or pass the credential s3-secret", + )?, + }; + let cfg = S3Config { + endpoint: need("VISA_S3_ENDPOINT")?, + bucket, + region: var("VISA_S3_REGION").unwrap_or_else(|| "garage".into()), + access_key_id: need("VISA_S3_ACCESS_KEY_ID")?, + secret_access_key, + }; + // the endpoint and the name are checked now, not at the first upload + crate::s3::Bucket::new(&cfg)?; + Ok(cfg) +} + /// A systemd credential (`LoadCredential=`), when the unit passes one. fn credential(var: &dyn Fn(&str) -> Option, name: &str) -> Result> { let Some(dir) = var("CREDENTIALS_DIRECTORY") else { @@ -276,7 +341,7 @@ mod tests { .unwrap_err(); assert!(e.to_string().contains("documents are not set up"), "{e}"); let files = c.files.unwrap(); - assert_eq!(files.dir, files_dir); + assert!(matches!(&files.place, FilesPlace::Dir(d) if *d == files_dir)); assert!(!format!("{files:?}").contains("abab")); std::fs::remove_dir_all(&dir).ok(); } @@ -315,7 +380,72 @@ mod tests { .unwrap(); assert!(c.files.is_some()); let e = with(&[("CREDENTIALS_DIRECTORY", dir.to_str().unwrap())]).unwrap_err(); - assert!(e.to_string().contains("no VISA_FILES_DIR"), "{e}"); + assert!(e.to_string().contains("no place for the documents"), "{e}"); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn documents_in_a_bucket_take_its_settings_and_the_secret_from_a_credential() { + let dir = std::env::temp_dir().join(format!("visa-cfg-s3-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap(); + std::fs::write(dir.join("s3-secret"), "s3-secret-value\n").unwrap(); + let creds = dir.to_str().unwrap(); + let base = [ + ("VISA_DATABASE_URL", "postgres://x/y"), + ("VISA_INSECURE_NO_LOGIN", "1"), + ("CREDENTIALS_DIRECTORY", creds), + ]; + let with = |extra: &[(&str, &str)]| { + let mut all = base.to_vec(); + all.extend_from_slice(extra); + cfg(&all) + }; + let bucket = [ + ("VISA_S3_BUCKET", "visa-documents"), + ("VISA_S3_ENDPOINT", "http://127.0.0.1:3900"), + ("VISA_S3_ACCESS_KEY_ID", "GK00112233"), + ]; + let c = with(&bucket).unwrap(); + let Some(FilesConfig { + place: FilesPlace::Bucket(b), + .. + }) = &c.files + else { + panic!("a bucket expected: {:?}", c.files) + }; + assert_eq!(b.bucket, "visa-documents"); + assert_eq!(b.region, "garage"); + assert_eq!(b.secret_access_key, "s3-secret-value"); + assert!(!format!("{c:?}").contains("s3-secret-value")); + // every part is needed, and one place only + for missing in ["VISA_S3_ENDPOINT", "VISA_S3_ACCESS_KEY_ID"] { + let some: Vec<_> = bucket + .iter() + .copied() + .filter(|(k, _)| *k != missing) + .collect(); + let e = with(&some).unwrap_err(); + assert!(e.to_string().contains(missing), "{e}"); + } + let mut both = bucket.to_vec(); + both.push(("VISA_FILES_DIR", "/srv/files")); + let e = with(&both).unwrap_err(); + assert!(e.to_string().contains("both set"), "{e}"); + let e = with(&[("VISA_S3_ENDPOINT", "http://127.0.0.1:3900")]).unwrap_err(); + assert!(e.to_string().contains("VISA_S3_BUCKET is not"), "{e}"); + let mut bad = bucket.to_vec(); + bad[1] = ("VISA_S3_ENDPOINT", "127.0.0.1:3900"); + assert!(with(&bad).is_err()); + // without the credential, the secret's file must be named + std::fs::remove_file(dir.join("s3-secret")).unwrap(); + let e = with(&bucket).unwrap_err(); + assert!(e.to_string().contains("no S3 secret key"), "{e}"); + let f = dir.join("secret-file"); + std::fs::write(&f, "from-a-file").unwrap(); + let mut named = bucket.to_vec(); + named.push(("VISA_S3_SECRET_ACCESS_KEY_FILE", f.to_str().unwrap())); + assert!(with(&named).is_ok()); std::fs::remove_dir_all(&dir).ok(); } } diff --git a/src/documents.rs b/src/documents.rs index 9af7808..e14f96a 100644 --- a/src/documents.rs +++ b/src/documents.rs @@ -1,16 +1,19 @@ //! Documents: scans and photos of a person's papers, and the company //! documents the extension packs need. A row holds what is known about a -//! file; the file itself lies encrypted in the store (`files.rs`). A +//! file; the file itself lies encrypted in the store (`files.rs`), on the +//! server a bucket of the fleet's Garage. A //! person's document may belong to one of their records (a passport, an //! arrival, a 90-day report ...), and then shows next to that record too. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; -use anyhow::Result; +use anyhow::{Context, Result, bail, ensure}; use chrono::{DateTime, NaiveDate, Utc}; use sqlx::{PgPool, Postgres, Transaction}; use crate::files::{self, Store}; +use crate::s3::Put; /// Whose document it is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -498,18 +501,14 @@ pub struct Check { /// size and checksum recorded at the upload; lists files that belong to no /// document. pub async fn check(db: &PgPool, store: &Store) -> Result { - let rows: Vec<(i64, i32, String)> = - sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id") - .fetch_all(db) - .await?; - let (ids, other) = store.entries()?; + let rows = uploads(db).await?; + let entries = store.entries().await?; let mut out = Check { documents: rows.len(), ..Check::default() }; - let known: BTreeSet = rows.iter().map(|r| r.0).collect(); - for (id, size, sha) in &rows { - match store.get(*id) { + for (id, (size, sha)) in &rows { + match store.get(*id).await { Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {} Ok(_) => out.problems.push(format!( "document {id}: the file does not match the size and checksum of its upload" @@ -517,17 +516,124 @@ pub async fn check(db: &PgPool, store: &Store) -> Result { Err(e) => out.problems.push(format!("document {id}: {e:#}")), } } - for id in ids.iter().filter(|id| !known.contains(id)) { - out.problems - .push(format!("{id}.vdoc: a file without its document")); + for (id, _) in entries + .files + .iter() + .filter(|(id, _)| !rows.contains_key(id)) + { + out.problems.push(format!( + "{}: a file without its document", + files::file_name(*id) + )); } - for name in other { + for name in entries.other { out.problems .push(format!("{name}: not a file of the store")); } Ok(out) } +/// Every document's size and SHA-256 as recorded at its upload. +async fn uploads(db: &PgPool) -> Result> { + let rows: Vec<(i64, i32, String)> = + sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id") + .fetch_all(db) + .await?; + Ok(rows + .into_iter() + .map(|(id, size, sha)| (id, (size, sha))) + .collect()) +} + +/// What `visa files-migrate` did. +#[derive(Debug, Default)] +pub struct Moved { + /// Files copied into the store. + pub copied: usize, + /// Files the store had already, with the same bytes. + pub there: usize, + /// Files in the directory that belong to no document, left there. + pub strays: Vec, + /// Documents whose file is neither in the directory nor in the store. + pub missing: Vec, +} + +/// Copies the documents' files from a files directory (where they lay +/// before the bucket, or a mirror the backups hold) into the store, as they +/// are: still encrypted. Each file is opened with the key and compared with +/// the size and checksum of its upload before it is copied, and read back +/// from the store and compared again after. A file the store has already +/// with the same bytes is counted and skipped, so the copy can run again; a +/// file the store has with other bytes, or one that does not open, stops it +/// with an error. Files of no document stay in the directory, listed. +pub async fn migrate(db: &PgPool, from: &Path, to: &Store) -> Result { + if let Some(d) = to.dir() { + ensure!( + !files::same_dir(d, from), + "{} is the store itself: files-migrate copies from another directory", + from.display() + ); + } + ensure!(from.is_dir(), "{} is not a directory", from.display()); + let src = Store::in_dir(from.to_path_buf(), to.file_key().clone())?; + let rows = uploads(db).await?; + let present = src.entries().await?; + let in_dir: BTreeSet = present.files.iter().map(|(id, _)| *id).collect(); + let mut out = Moved::default(); + for (id, (size, sha)) in &rows { + let matches = + |bytes: &[u8]| bytes.len() == *size as usize && files::sha256_hex(bytes) == *sha; + if !in_dir.contains(id) { + if to.get_sealed(*id).await?.is_some() { + out.there += 1; + } else { + out.missing.push(*id); + } + continue; + } + let plain = src + .get(*id) + .await + .with_context(|| format!("document {id}: its file in the directory"))?; + if !matches(&plain) { + bail!( + "document {id}: the file in {} does not match the size and checksum of its upload", + from.display() + ); + } + let sealed = src + .get_sealed(*id) + .await? + .with_context(|| format!("document {id}: its file went missing"))?; + match to + .put_sealed(*id, sealed) + .await + .with_context(|| format!("document {id}: copying its file"))? + { + Put::Written => out.copied += 1, + Put::Same => out.there += 1, + } + let back = to + .get(*id) + .await + .with_context(|| format!("document {id}: reading the copy back"))?; + if !matches(&back) { + bail!( + "document {id}: the copy in {} does not match its upload", + to.describe() + ); + } + } + out.strays = present + .files + .iter() + .filter(|(id, _)| !rows.contains_key(id)) + .map(|(id, _)| files::file_name(*id)) + .chain(present.other) + .collect(); + Ok(out) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/files.rs b/src/files.rs index b5f20cf..9356590 100644 --- a/src/files.rs +++ b/src/files.rs @@ -1,25 +1,34 @@ -//! The document store. Each uploaded file lies in the files directory as -//! `.vdoc`, encrypted with AES-256-GCM under a key of its own: HKDF-SHA256 -//! derives it from the app's file key and a random salt kept in the file's -//! header. The document's id is authenticated with the file, so a file -//! renamed to another id does not open. The file key is a systemd -//! credential and is never in the database or its dumps: without it the -//! files and their backups cannot be read. +//! The document store. Each uploaded file is encrypted with AES-256-GCM +//! before it is stored, under a key of its own: HKDF-SHA256 derives it from +//! the app's file key and a random salt kept in the file's header. The +//! document's id is authenticated with the file, so a file renamed to +//! another id does not open. The file key is a systemd credential and is +//! never in the database or its dumps: without it the files and their +//! backups cannot be read. +//! +//! The encrypted files lie in a bucket of an S3 store (on the server, the +//! fleet's Garage) as `documents/.vdoc`, or in a directory as `.vdoc` +//! (local development and the tests). Only encrypted bytes ever leave the +//! app, so the store holds no document in the clear. //! //! A file is `VISADOC1`, the key id (8 bytes), the salt (32 bytes), the //! ciphertext and the tag (16 bytes). The key id names the key that sealed a //! file, so a wrong key is reported as such and not as damage. +use std::collections::BTreeMap; use std::fmt; use std::fs::{self, File}; use std::io::{self, Write}; use std::path::{Path, PathBuf}; -use anyhow::{Context, Result, ensure}; +use anyhow::{Context, Result, bail, ensure}; use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey}; use ring::rand::{SecureRandom, SystemRandom}; use ring::{digest, hkdf}; +use crate::config::{FilesConfig, FilesPlace}; +use crate::s3::{Bucket, Put, S3Config}; + const MAGIC: &[u8; 8] = b"VISADOC1"; const KEY_ID: usize = 8; const SALT: usize = 32; @@ -211,103 +220,364 @@ pub fn is_image(content_type: &str) -> bool { content_type.starts_with("image/") } -/// The files directory with the key; cheap to clone into a blocking task. +/// The objects' key prefix in a bucket. +pub const PREFIX: &str = "documents/"; + +/// The name of document `id`'s file. +pub fn file_name(id: i64) -> String { + format!("{id}.vdoc") +} + +/// The document whose file has this name (`7.vdoc`, not `07.vdoc`). +pub fn id_of(name: &str) -> Option { + let id: i64 = name.strip_suffix(".vdoc")?.parse().ok()?; + (id > 0 && file_name(id) == name).then_some(id) +} + +/// Where the encrypted files lie. +#[derive(Clone, Debug)] +enum Place { + /// A directory of `.vdoc` files: local development and the tests. + Dir(PathBuf), + /// A bucket of an S3 store, objects `documents/.vdoc`: the server. + Bucket(Bucket), +} + +/// The document store with its key; cheap to clone. #[derive(Clone, Debug)] pub struct Store { - dir: PathBuf, + place: Place, key: FileKey, } -impl Store { - /// The files directory, created (only its owner may enter) when missing. - pub fn open(dir: PathBuf, key: FileKey) -> Result { - fs::create_dir_all(&dir) - .with_context(|| format!("creating the files directory {}", dir.display()))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)) - .with_context(|| format!("closing the files directory {}", dir.display()))?; +/// What a store holds: the documents' files with their sizes in bytes, and +/// the names of anything else (a part file left by a crash, say). +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Entries { + pub files: Vec<(i64, u64)>, + pub other: Vec, +} + +/// File work off the async threads. +async fn blocking(f: impl FnOnce() -> Result + Send + 'static) -> Result { + tokio::task::spawn_blocking(f) + .await + .context("a file task stopped")? +} + +/// A directory only its owner may enter, created when missing. +fn private_dir(dir: &Path) -> Result<()> { + fs::create_dir_all(dir).with_context(|| format!("creating the directory {}", dir.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(dir, fs::Permissions::from_mode(0o700)) + .with_context(|| format!("closing the directory {}", dir.display()))?; + } + Ok(()) +} + +/// Writes `bytes` as `dir/name`: to a part file first, on disk before it +/// takes its name (replacing a file of that name). +fn write_file(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> { + let path = dir.join(name); + let part = dir.join(format!(".{name}.part")); + let write = || -> io::Result<()> { + let mut f = File::create(&part)?; + f.write_all(bytes)?; + f.sync_all()?; + fs::rename(&part, &path)?; + sync_dir(dir) + }; + write() + .inspect_err(|_| { + fs::remove_file(&part).ok(); + }) + .with_context(|| format!("writing {}", path.display())) +} + +/// The `.vdoc` files of a directory with their sizes, and the names of +/// everything else in it. +fn list_dir(dir: &Path) -> Result { + let mut out = Entries::default(); + for entry in fs::read_dir(dir).with_context(|| format!("listing {}", dir.display()))? { + let entry = entry?; + let name = entry.file_name().to_string_lossy().into_owned(); + match id_of(&name) { + Some(id) if entry.file_type()?.is_file() => { + out.files.push((id, entry.metadata()?.len())) + } + _ => out.other.push(name), } - Ok(Store { dir, key }) + } + out.files.sort_unstable(); + out.other.sort(); + Ok(out) +} + +/// Whether two paths name the same directory. +pub fn same_dir(a: &Path, b: &Path) -> bool { + match (fs::canonicalize(a), fs::canonicalize(b)) { + (Ok(a), Ok(b)) => a == b, + _ => a == b, + } +} + +impl Store { + /// A files directory, created (only its owner may enter) when missing. + pub fn in_dir(dir: PathBuf, key: FileKey) -> Result { + private_dir(&dir)?; + Ok(Store { + place: Place::Dir(dir), + key, + }) } - pub fn dir(&self) -> &Path { - &self.dir + /// A bucket; nothing is asked of the server until the first file. + pub fn in_bucket(cfg: &S3Config, key: FileKey) -> Result { + Ok(Store::with_bucket(Bucket::new(cfg)?, key)) + } + + pub fn with_bucket(bucket: Bucket, key: FileKey) -> Store { + Store { + place: Place::Bucket(bucket), + key, + } + } + + pub fn open(cfg: &FilesConfig) -> Result { + match &cfg.place { + FilesPlace::Dir(dir) => Store::in_dir(dir.clone(), cfg.key.clone()), + FilesPlace::Bucket(b) => Store::in_bucket(b, cfg.key.clone()), + } + } + + /// Where the files are, for the log and the admin commands. + pub fn describe(&self) -> String { + match &self.place { + Place::Dir(dir) => format!("the directory {}", dir.display()), + Place::Bucket(b) => format!("bucket {} at {}", b.name(), b.endpoint()), + } + } + + /// The files directory, when the files lie in one. + pub fn dir(&self) -> Option<&Path> { + match &self.place { + Place::Dir(dir) => Some(dir), + Place::Bucket(_) => None, + } } pub fn key_id(&self) -> String { self.key.id_hex() } - pub fn path(&self, id: i64) -> PathBuf { - self.dir.join(format!("{id}.vdoc")) + pub fn file_key(&self) -> &FileKey { + &self.key } - /// Encrypts and writes the file of document `id`: to a part file first, - /// on disk before it takes its name. An existing file is never replaced. - pub fn put(&self, id: i64, plain: &[u8]) -> Result<()> { - let path = self.path(id); - ensure!( - !path.exists(), - "{} is there already without its document (after a restore?); `visa files-check` \ - lists such files", - path.display() - ); - let sealed = seal(&self.key, id, plain); - let part = self.dir.join(format!(".{id}.vdoc.part")); - let write = || -> io::Result<()> { - let mut f = File::create(&part)?; - f.write_all(&sealed)?; - f.sync_all()?; - fs::rename(&part, &path)?; - sync_dir(&self.dir) - }; - write() - .inspect_err(|_| { - fs::remove_file(&part).ok(); - }) - .with_context(|| format!("writing {}", path.display())) + fn object(id: i64) -> String { + format!("{PREFIX}{}", file_name(id)) + } + + /// Where document `id`'s file is, for messages. + pub fn location(&self, id: i64) -> String { + match &self.place { + Place::Dir(dir) => dir.join(file_name(id)).display().to_string(), + Place::Bucket(b) => format!("{} in bucket {}", Store::object(id), b.name()), + } + } + + /// Encrypts and stores the file of document `id`. An existing file is + /// never replaced. + pub async fn put(&self, id: i64, plain: Vec) -> Result<()> { + let key = self.key.clone(); + let sealed = blocking(move || Ok(seal(&key, id, &plain))).await?; + self.put_sealed(id, sealed).await.map(|_| ()) + } + + /// Stores an encrypted file as it is (a copy from another place). An + /// existing file is never replaced: one with the same bytes counts as + /// stored ([`Put::Same`]), one with other bytes is an error. + pub async fn put_sealed(&self, id: i64, sealed: Vec) -> Result { + match &self.place { + Place::Dir(dir) => { + let dir = dir.clone(); + blocking(move || { + let path = dir.join(file_name(id)); + if path.exists() { + let there = fs::read(&path) + .with_context(|| format!("reading {}", path.display()))?; + if there == sealed { + return Ok(Put::Same); + } + bail!( + "{} is there already without its document (after a restore?); \ + `visa files-check` lists such files", + path.display() + ); + } + write_file(&dir, &file_name(id), &sealed)?; + Ok(Put::Written) + }) + .await + } + Place::Bucket(b) => b.put_new(&Store::object(id), &sealed).await, + } + } + + /// The encrypted file of document `id` as it is stored, or None. + pub async fn get_sealed(&self, id: i64) -> Result>> { + match &self.place { + Place::Dir(dir) => { + let path = dir.join(file_name(id)); + blocking(move || match fs::read(&path) { + Ok(b) => Ok(Some(b)), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e).with_context(|| format!("reading {}", path.display())), + }) + .await + } + Place::Bucket(b) => b.get(&Store::object(id)).await, + } } /// The decrypted file of document `id`. - pub fn get(&self, id: i64) -> Result> { - let path = self.path(id); - let sealed = fs::read(&path).with_context(|| format!("reading {}", path.display()))?; - open(&self.key, id, &sealed).with_context(|| format!("opening {}", path.display())) + pub async fn get(&self, id: i64) -> Result> { + let at = self.location(id); + let sealed = self + .get_sealed(id) + .await? + .with_context(|| format!("{at} is missing"))?; + let key = self.key.clone(); + blocking(move || open(&key, id, &sealed).with_context(|| format!("opening {at}"))).await } /// Removes the file of document `id`; a file that is gone already is fine. - pub fn remove(&self, id: i64) -> Result<()> { - let path = self.path(id); - match fs::remove_file(&path) { - Ok(()) => sync_dir(&self.dir).with_context(|| format!("removing {}", path.display())), - Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), - Err(e) => Err(e).with_context(|| format!("removing {}", path.display())), + pub async fn remove(&self, id: i64) -> Result<()> { + match &self.place { + Place::Dir(dir) => { + let dir = dir.clone(); + blocking(move || { + let path = dir.join(file_name(id)); + match fs::remove_file(&path) { + Ok(()) => { + sync_dir(&dir).with_context(|| format!("removing {}", path.display())) + } + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e).with_context(|| format!("removing {}", path.display())), + } + }) + .await + } + Place::Bucket(b) => b.delete(&Store::object(id)).await, } } - /// What lies in the directory: the documents' ids, and the names of - /// anything else (a part file left by a crash, say). - pub fn entries(&self) -> Result<(Vec, Vec)> { - let mut ids = Vec::new(); - let mut other = Vec::new(); - for entry in - fs::read_dir(&self.dir).with_context(|| format!("listing {}", self.dir.display()))? - { - let name = entry?.file_name().to_string_lossy().into_owned(); - match name - .strip_suffix(".vdoc") - .and_then(|n| n.parse::().ok()) - { - Some(id) if id > 0 => ids.push(id), - _ => other.push(name), + /// What the store holds. In a bucket, every object outside + /// `documents/.vdoc` counts as something else. + pub async fn entries(&self) -> Result { + match &self.place { + Place::Dir(dir) => { + let dir = dir.clone(); + blocking(move || list_dir(&dir)).await + } + Place::Bucket(b) => { + let mut out = Entries::default(); + for o in b.list("").await? { + match o.key.strip_prefix(PREFIX).and_then(id_of) { + Some(id) => out.files.push((id, o.size)), + None => out.other.push(o.key), + } + } + out.files.sort_unstable(); + Ok(out) } } - ids.sort_unstable(); - other.sort(); - Ok((ids, other)) } + + /// The store answers: the directory is there, or the bucket answers to + /// the key. + pub async fn check(&self) -> Result<()> { + match &self.place { + Place::Dir(dir) => { + ensure!(dir.is_dir(), "{} is not a directory", dir.display()); + Ok(()) + } + Place::Bucket(b) => b.check().await, + } + } +} + +/// What [`mirror`] did. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Mirrored { + pub copied: usize, + pub kept: usize, + pub removed: usize, +} + +/// Makes `dir` hold exactly the store's files, still encrypted, for the +/// backups: a file the store has and `dir` lacks, or holds at another size, +/// is copied (to a part file, synced, then renamed), and a file the store no +/// longer has is removed. The store's files never change once written, so +/// the size tells a copy apart. `dir` then reads like a files directory, and +/// a restore is `visa files-migrate --from `. +pub async fn mirror(from: &Store, dir: &Path) -> Result { + if let Some(d) = from.dir() { + ensure!( + !same_dir(d, dir), + "the mirror cannot be the store's own directory {}", + d.display() + ); + } + let target = dir.to_path_buf(); + let have = blocking(move || { + private_dir(&target)?; + list_dir(&target) + }) + .await?; + let want = from.entries().await?.files; + let have_sizes: BTreeMap = have.files.iter().copied().collect(); + let mut out = Mirrored::default(); + for (id, size) in &want { + if have_sizes.get(id) == Some(size) { + out.kept += 1; + continue; + } + let sealed = from + .get_sealed(*id) + .await? + .with_context(|| format!("{} went missing while it was copied", from.location(*id)))?; + let target = dir.to_path_buf(); + let id = *id; + blocking(move || write_file(&target, &file_name(id), &sealed)).await?; + out.copied += 1; + } + let keep: BTreeMap = want.into_iter().collect(); + let stale: Vec = have + .files + .iter() + .filter(|(id, _)| !keep.contains_key(id)) + .map(|(id, _)| file_name(*id)) + .collect(); + out.removed = stale.len(); + // and part files a stopped copy left behind + let parts = have + .other + .into_iter() + .filter(|n| n.starts_with('.') && n.ends_with(".vdoc.part")); + let gone: Vec = stale.into_iter().chain(parts).collect(); + let target = dir.to_path_buf(); + blocking(move || { + for name in &gone { + let path = target.join(name); + fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?; + } + sync_dir(&target).with_context(|| format!("syncing {}", target.display())) + }) + .await?; + Ok(out) } /// A rename is on disk only once its directory is. @@ -387,24 +657,105 @@ mod tests { } #[test] - fn the_store_writes_reads_and_removes() { - let dir = std::env::temp_dir().join(format!("visa-store-{}", std::process::id())); + fn only_a_documents_own_name_is_its_file() { + assert_eq!(id_of("7.vdoc"), Some(7)); + assert_eq!(id_of("1234.vdoc"), Some(1234)); + for bad in [ + "07.vdoc", + "0.vdoc", + "-3.vdoc", + "7.vdoc.part", + ".7.vdoc.part", + "x.vdoc", + "7", + ] { + assert_eq!(id_of(bad), None, "{bad}"); + } + } + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("visa-{name}-{}", std::process::id())); fs::remove_dir_all(&dir).ok(); - let store = Store::open(dir.clone(), FileKey::random()).unwrap(); - store.put(3, b"%PDF-1.4 three").unwrap(); - assert_eq!(store.get(3).unwrap(), b"%PDF-1.4 three"); - let on_disk = fs::read(store.path(3)).unwrap(); + dir + } + + #[tokio::test] + async fn the_store_writes_reads_and_removes() { + let dir = temp_dir("store"); + let store = Store::in_dir(dir.clone(), FileKey::random()).unwrap(); + store.put(3, b"%PDF-1.4 three".to_vec()).await.unwrap(); + assert_eq!(store.get(3).await.unwrap(), b"%PDF-1.4 three"); + let on_disk = fs::read(dir.join("3.vdoc")).unwrap(); assert!(!on_disk.windows(5).any(|w| w == b"three")); - let e = store.put(3, b"%PDF-1.4 again").unwrap_err(); + let e = store.put(3, b"%PDF-1.4 again".to_vec()).await.unwrap_err(); assert!(e.to_string().contains("there already"), "{e}"); + // the same bytes again: a copy that ran before + assert_eq!( + store.put_sealed(3, on_disk.clone()).await.unwrap(), + Put::Same + ); fs::write(dir.join(".9.vdoc.part"), b"left over").unwrap(); assert_eq!( - store.entries().unwrap(), - (vec![3], vec![".9.vdoc.part".to_string()]) + store.entries().await.unwrap(), + Entries { + files: vec![(3, on_disk.len() as u64)], + other: vec![".9.vdoc.part".to_string()] + } ); - store.remove(3).unwrap(); - store.remove(3).unwrap(); - assert!(store.get(3).is_err()); + store.remove(3).await.unwrap(); + store.remove(3).await.unwrap(); + assert!(store.get(3).await.is_err()); + assert!(store.get_sealed(3).await.unwrap().is_none()); fs::remove_dir_all(&dir).ok(); } + + #[tokio::test] + async fn the_mirror_follows_the_store() { + let (src, dst) = (temp_dir("mirror-src"), temp_dir("mirror-dst")); + let store = Store::in_dir(src.clone(), FileKey::random()).unwrap(); + for id in [1, 2, 3] { + store + .put(id, format!("%PDF-1.4 file {id}").into_bytes()) + .await + .unwrap(); + } + assert_eq!( + mirror(&store, &dst).await.unwrap(), + Mirrored { + copied: 3, + kept: 0, + removed: 0 + } + ); + for id in [1, 2, 3] { + assert_eq!( + fs::read(dst.join(file_name(id))).unwrap(), + store.get_sealed(id).await.unwrap().unwrap() + ); + } + store.remove(2).await.unwrap(); + store.put(4, b"%PDF-1.4 file 4".to_vec()).await.unwrap(); + fs::write(dst.join("1.vdoc"), b"cut short").unwrap(); + fs::write(dst.join(".5.vdoc.part"), b"left over").unwrap(); + assert_eq!( + mirror(&store, &dst).await.unwrap(), + Mirrored { + copied: 2, + kept: 1, + removed: 1 + } + ); + let mut names: Vec = fs::read_dir(&dst) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + assert_eq!(names, ["1.vdoc", "3.vdoc", "4.vdoc"]); + assert!( + mirror(&store, &src).await.is_err(), + "not into the store itself" + ); + fs::remove_dir_all(&src).ok(); + fs::remove_dir_all(&dst).ok(); + } } diff --git a/src/lib.rs b/src/lib.rs index 086482c..40bf496 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,6 +18,7 @@ pub mod oidc; pub mod papers; pub mod people; pub mod records; +pub mod s3; pub mod seed; pub mod session; pub mod web; diff --git a/src/main.rs b/src/main.rs index 4fb0b6a..c721239 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,13 +1,14 @@ -//! `visa [serve|migrate|seed-demo|files-check|help]`: the server and its admin -//! commands. +//! `visa [serve|migrate|seed-demo|files-check|files-migrate|files-mirror|help]`: +//! the server and its admin commands. +use std::path::PathBuf; use std::process::ExitCode; use anyhow::{Context, Result, bail, ensure}; -use tracing::info; +use tracing::{info, warn}; use visa::config::Config; -use visa::files::Store; +use visa::files::{self, Store}; use visa::{dates, db, documents, seed, web}; const USAGE: &str = "\ @@ -21,6 +22,13 @@ Commands: seed-demo add invented demo people and documents (local development only) files-check read every document's file back and compare it with its upload; list files without a document (exit status 1 on any problem) + files-migrate --from DIR + copy the documents' files from a files directory (the store + before the bucket, or a backup's mirror) into the store, each + checked against its upload; again is harmless + files-mirror --to DIR + make DIR hold exactly the store's files, still encrypted, for + the backups help show this text Settings come from the environment; see src/config.rs or README.md."; @@ -41,6 +49,24 @@ async fn main() -> ExitCode { } } +/// The directory after `flag` on the command line. +fn dir_arg(flag: &str) -> Result { + let args: Vec = std::env::args().skip(2).collect(); + match args.as_slice() { + [f, dir] if f == flag && !dir.is_empty() => Ok(PathBuf::from(dir)), + _ => bail!("give the directory as {flag} DIR; `visa help` lists the commands"), + } +} + +/// The store the settings name; an error when documents are off. +fn store(cfg: &Config) -> Result { + let f = cfg + .files + .as_ref() + .context("documents are off here: no VISA_S3_BUCKET (or VISA_FILES_DIR) and file key")?; + Store::open(f) +} + async fn run(cmd: &str) -> Result<()> { match cmd { "serve" => serve().await, @@ -66,22 +92,18 @@ async fn run(cmd: &str) -> Result<()> { println!("demo people are there already"); } match &cfg.files { - Some(f) => { - let store = Store::open(f.dir.clone(), f.key.clone())?; + Some(_) => { + let store = store(&cfg)?; let n = seed::demo_documents(&pool, &store, dates::today()).await?; println!("demo documents added: {n}"); } - None => println!("no demo documents: documents are off (no VISA_FILES_DIR)"), + None => println!("no demo documents: documents are off (no place for them)"), } Ok(()) } "files-check" => { let cfg = Config::from_env()?; - let f = cfg - .files - .as_ref() - .context("documents are off here: no VISA_FILES_DIR and file key")?; - let store = Store::open(f.dir.clone(), f.key.clone())?; + let store = store(&cfg)?; let pool = db::connect(&cfg).await?; let check = documents::check(&pool, &store).await?; for p in &check.problems { @@ -90,13 +112,55 @@ async fn run(cmd: &str) -> Result<()> { println!( "{} documents checked in {} (file key {}): {} problems", check.documents, - store.dir().display(), + store.describe(), store.key_id(), check.problems.len() ); ensure!(check.problems.is_empty(), "the files need attention"); Ok(()) } + "files-migrate" => { + let from = dir_arg("--from")?; + let cfg = Config::from_env()?; + let store = store(&cfg)?; + let pool = db::connect(&cfg).await?; + let moved = documents::migrate(&pool, &from, &store).await?; + for name in &moved.strays { + println!( + "left in {}: {name}, which is no document's file", + from.display() + ); + } + for id in &moved.missing { + println!( + "problem: document {id} has no file in {} and none in the store", + from.display() + ); + } + println!( + "{} files copied into {}, {} there already (file key {})", + moved.copied, + store.describe(), + moved.there, + store.key_id() + ); + Ok(()) + } + "files-mirror" => { + let to = dir_arg("--to")?; + let cfg = Config::from_env()?; + let store = store(&cfg)?; + let m = files::mirror(&store, &to).await?; + println!( + "{} mirrored into {}: {} copied, {} kept, {} removed", + store.describe(), + to.display(), + m.copied, + m.kept, + m.removed + ); + Ok(()) + } "help" | "--help" | "-h" => { println!("{USAGE}"); Ok(()) @@ -113,12 +177,20 @@ async fn serve() -> Result<()> { let login = cfg.login_enabled(); let st = web::AppState::new(cfg, pool)?; match &st.files { - Some(s) => info!( - "documents in {} (file key {})", - s.dir().display(), - s.key_id() - ), - None => info!("documents are off: no VISA_FILES_DIR (local development)"), + Some(s) => { + info!("documents in {} (file key {})", s.describe(), s.key_id()); + // A store that is not there yet (Garage starting) costs the + // documents, not the records: the check only warns, and the + // server listens meanwhile. + let s = s.clone(); + tokio::spawn(async move { + match s.check().await { + Ok(()) => info!("documents: {} answers", s.describe()), + Err(e) => warn!("documents: {} does not answer yet: {e:#}", s.describe()), + } + }); + } + None => info!("documents are off: no place for them (local development)"), } web::spawn_background(st.clone()); let app = web::router(st); diff --git a/src/s3.rs b/src/s3.rs new file mode 100644 index 0000000..6612fde --- /dev/null +++ b/src/s3.rs @@ -0,0 +1,712 @@ +//! A small S3 client for the document store: path-style requests (the +//! bucket is the first part of the path) signed with AWS Signature Version 4, +//! on reqwest and ring, as in proplan. It makes the five calls the store +//! needs: PUT, GET, HEAD, DELETE and ListObjectsV2. Garage, the fleet's +//! object store, answers them as AWS does. +//! +//! The objects are the store's encrypted files: this client never sees a +//! document's contents in the clear, and its errors name the object and the +//! answer, never the secret key. + +use std::fmt; +use std::time::Duration; + +use anyhow::{Context, Result, bail, ensure}; +use chrono::{DateTime, Utc}; +use reqwest::{Method, StatusCode, Url}; +use ring::{digest, hmac}; + +/// Where the bucket is, and the key to it. +#[derive(Clone)] +pub struct S3Config { + /// The server, without a path: `http://127.0.0.1:3900`. + pub endpoint: String, + pub bucket: String, + /// Garage's is `garage`. + pub region: String, + pub access_key_id: String, + pub secret_access_key: String, +} + +// The secret stays out of logs and panics. +impl fmt::Debug for S3Config { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("S3Config") + .field("endpoint", &self.endpoint) + .field("bucket", &self.bucket) + .field("region", &self.region) + .field("access_key_id", &self.access_key_id) + .field( + "secret_access_key", + &format_args!("<{} bytes>", self.secret_access_key.len()), + ) + .finish() + } +} + +/// An object as a listing names it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Object { + pub key: String, + pub size: u64, +} + +/// What [`Bucket::put_new`] did. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Put { + Written, + /// The object was there already with exactly these bytes (a retry, or a + /// copy that ran before). + Same, +} + +#[derive(Clone)] +pub struct Bucket { + endpoint: String, + bucket: String, + region: String, + key_id: String, + secret: String, + /// `host[:port]` as the request's Host header carries it. + host: String, + http: reqwest::Client, + /// Between attempts at a request the server could not answer. + pause: Duration, +} + +impl fmt::Debug for Bucket { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Bucket({} at {})", self.bucket, self.endpoint) + } +} + +/// An answer, read in full. +struct Answer { + status: StatusCode, + headers: reqwest::header::HeaderMap, + body: Vec, +} + +/// How often a request is tried when the server is away or busy. +const ATTEMPTS: u32 = 3; + +impl Bucket { + pub fn new(cfg: &S3Config) -> Result { + let endpoint = cfg.endpoint.trim().trim_end_matches('/').to_string(); + let url = Url::parse(&endpoint) + .with_context(|| format!("the S3 endpoint {endpoint:?} is not a URL"))?; + ensure!( + matches!(url.scheme(), "http" | "https"), + "the S3 endpoint {endpoint:?} must start with http:// or https://" + ); + ensure!( + url.path() == "/" && url.query().is_none(), + "the S3 endpoint {endpoint:?} is a server's address, without a path" + ); + let name = url + .host_str() + .with_context(|| format!("the S3 endpoint {endpoint:?} has no host"))?; + let host = match url.port() { + Some(p) => format!("{name}:{p}"), + None => name.to_string(), + }; + ensure!( + valid_bucket_name(&cfg.bucket), + "{:?} is not a bucket name (3 to 63 lowercase letters, digits, dots and hyphens)", + cfg.bucket + ); + ensure!( + !cfg.access_key_id.trim().is_empty(), + "the S3 key id is empty" + ); + ensure!( + !cfg.secret_access_key.is_empty(), + "the S3 secret key is empty" + ); + let http = reqwest::Client::builder() + .connect_timeout(Duration::from_secs(5)) + .timeout(Duration::from_secs(120)) + .user_agent(concat!("visa/", env!("CARGO_PKG_VERSION"))) + .build()?; + Ok(Bucket { + endpoint, + bucket: cfg.bucket.clone(), + region: if cfg.region.trim().is_empty() { + "garage".into() + } else { + cfg.region.trim().to_string() + }, + key_id: cfg.access_key_id.trim().to_string(), + secret: cfg.secret_access_key.clone(), + host, + http, + pause: Duration::from_millis(500), + }) + } + + /// A shorter pause between attempts, for the tests. + pub fn with_pause(mut self, pause: Duration) -> Bucket { + self.pause = pause; + self + } + + pub fn name(&self) -> &str { + &self.bucket + } + + pub fn endpoint(&self) -> &str { + &self.endpoint + } + + /// The canonical path of an object, or of the bucket for an empty key. + fn path(&self, key: &str) -> String { + format!("/{}/{}", self.bucket, uri_encode(key, true)) + } + + /// One request, signed, sent and read in full. A connection that fails + /// and the answers 500, 502, 503 and 504 are tried again, signed anew. + async fn send( + &self, + method: Method, + key: &str, + query: &[(&str, &str)], + body: &[u8], + extra: &[(&str, &str)], + ) -> Result { + let path = self.path(key); + let mut q: Vec<(String, String)> = query + .iter() + .map(|(k, v)| (uri_encode(k, false), uri_encode(v, false))) + .collect(); + q.sort(); + let qs = q + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("&"); + let url = if qs.is_empty() { + format!("{}{path}", self.endpoint) + } else { + format!("{}{path}?{qs}", self.endpoint) + }; + let payload = sha256_hex(body); + let mut attempt = 0; + loop { + attempt += 1; + let amz_date = amz_date(Utc::now()); + let mut headers: Vec<(String, String)> = vec![ + ("host".into(), self.host.clone()), + ("x-amz-content-sha256".into(), payload.clone()), + ("x-amz-date".into(), amz_date.clone()), + ]; + for (k, v) in extra { + headers.push((k.to_ascii_lowercase(), (*v).to_string())); + } + let auth = sigv4( + method.as_str(), + &path, + &qs, + &headers, + &payload, + &amz_date, + &self.region, + &self.key_id, + &self.secret, + ); + let mut rb = self + .http + .request(method.clone(), &url) + .header("authorization", auth); + for (k, v) in headers.iter().filter(|(k, _)| k != "host") { + rb = rb.header(k, v); + } + if !body.is_empty() || method == Method::PUT { + rb = rb.body(body.to_vec()); + } + let what = || format!("S3 {method} {}", self.object_name(key)); + match rb.send().await { + Ok(res) => { + let status = res.status(); + let headers = res.headers().clone(); + let busy = matches!(status.as_u16(), 500 | 502 | 503 | 504); + match res.bytes().await { + Ok(b) if !busy || attempt >= ATTEMPTS => { + return Ok(Answer { + status, + headers, + body: b.to_vec(), + }); + } + Ok(_) => {} + Err(e) if attempt >= ATTEMPTS => { + return Err(e) + .with_context(|| format!("{}: reading the answer", what())); + } + Err(_) => {} + } + } + Err(e) if attempt >= ATTEMPTS => { + return Err(e) + .with_context(|| format!("{}: no answer from {}", what(), self.endpoint)); + } + Err(_) => {} + } + tokio::time::sleep(self.pause * attempt).await; + } + } + + fn object_name(&self, key: &str) -> String { + if key.is_empty() { + format!("bucket {}", self.bucket) + } else { + format!("{key} in bucket {}", self.bucket) + } + } + + /// The error for an answer that is not what was asked for: the status + /// and the S3 error code (`AccessDenied`, `NoSuchBucket` ...). + fn failed(&self, what: &str, key: &str, a: &Answer) -> anyhow::Error { + let text = String::from_utf8_lossy(&a.body); + let code = tag(&text, "Code").unwrap_or_default(); + anyhow::anyhow!( + "S3 {what} {}: HTTP {} {code}", + self.object_name(key), + a.status.as_u16() + ) + } + + /// Writes an object that must not exist yet. One that exists with the + /// same bytes counts as written before ([`Put::Same`]), one with other + /// bytes is an error and stays as it is. The server is asked first: that + /// question is the guard on Garage, which ignores the write's condition + /// ([`Bucket::put_if_absent`]). The store's ids are unique, so only a + /// restore that brought an old id back could meet an object here. + pub async fn put_new(&self, key: &str, bytes: &[u8]) -> Result { + if self.head(key).await?.is_none() && self.put_if_absent(key, bytes).await? { + return Ok(Put::Written); + } + self.same_or_refuse(key, bytes).await + } + + /// A PUT with `If-None-Match: *`: true when the object was written, + /// false when the server refused because it exists (HTTP 412). AWS and + /// MinIO honor the header; Garage 2.5 ignores it and writes (seen in + /// tests/garage.rs on Nov 19, 2026), so on Garage this is a plain PUT. + pub async fn put_if_absent(&self, key: &str, bytes: &[u8]) -> Result { + let a = self + .send( + Method::PUT, + key, + &[], + bytes, + &[ + ("content-type", "application/octet-stream"), + ("if-none-match", "*"), + ], + ) + .await?; + if a.status.is_success() { + Ok(true) + } else if a.status == StatusCode::PRECONDITION_FAILED { + Ok(false) + } else { + Err(self.failed("PUT", key, &a)) + } + } + + async fn same_or_refuse(&self, key: &str, bytes: &[u8]) -> Result { + match self.get(key).await? { + Some(there) if there == bytes => Ok(Put::Same), + Some(_) => bail!( + "{} is there already with other bytes; it stays as it is", + self.object_name(key) + ), + None => bail!( + "{} was there a moment ago and is gone now; try again", + self.object_name(key) + ), + } + } + + /// The object's bytes, or None when there is no such object. + pub async fn get(&self, key: &str) -> Result>> { + let a = self.send(Method::GET, key, &[], &[], &[]).await?; + match a.status { + s if s.is_success() => Ok(Some(a.body)), + StatusCode::NOT_FOUND + if tag(&String::from_utf8_lossy(&a.body), "Code").as_deref() + != Some("NoSuchBucket") => + { + Ok(None) + } + _ => Err(self.failed("GET", key, &a)), + } + } + + /// The object's size, or None when there is no such object. + pub async fn head(&self, key: &str) -> Result> { + let a = self.send(Method::HEAD, key, &[], &[], &[]).await?; + match a.status { + s if s.is_success() => Ok(Some( + a.headers + .get(reqwest::header::CONTENT_LENGTH) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse().ok()) + .unwrap_or_default(), + )), + StatusCode::NOT_FOUND => Ok(None), + _ => Err(self.failed("HEAD", key, &a)), + } + } + + /// Removes an object; one that is gone already is fine. + pub async fn delete(&self, key: &str) -> Result<()> { + let a = self.send(Method::DELETE, key, &[], &[], &[]).await?; + if a.status.is_success() || a.status == StatusCode::NOT_FOUND { + Ok(()) + } else { + Err(self.failed("DELETE", key, &a)) + } + } + + /// Every object whose key starts with `prefix`, sorted by key; read + /// page by page. + pub async fn list(&self, prefix: &str) -> Result> { + let mut out = Vec::new(); + let mut token: Option = None; + loop { + let mut q = vec![("list-type", "2"), ("prefix", prefix)]; + if let Some(t) = &token { + q.push(("continuation-token", t.as_str())); + } + let a = self.send(Method::GET, "", &q, &[], &[]).await?; + if !a.status.is_success() { + return Err(self.failed("LIST", "", &a)); + } + let page = parse_list(&String::from_utf8_lossy(&a.body))?; + out.extend(page.objects); + match (page.truncated, page.next) { + (true, Some(next)) if Some(&next) != token.as_ref() => token = Some(next), + (true, _) => bail!( + "S3 LIST {}: a page says more follow but gives no new token", + self.object_name("") + ), + (false, _) => break, + } + } + out.sort_by(|a, b| a.key.cmp(&b.key)); + Ok(out) + } + + /// The bucket answers to this key (at the start and in `files-check`). + pub async fn check(&self) -> Result<()> { + let a = self + .send( + Method::GET, + "", + &[("list-type", "2"), ("max-keys", "1")], + &[], + &[], + ) + .await?; + if a.status.is_success() { + Ok(()) + } else { + Err(self.failed("LIST", "", &a)) + } + } +} + +/// S3's rule for bucket names, as Garage applies it. +fn valid_bucket_name(name: &str) -> bool { + (3..=63).contains(&name.len()) + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-') + && name.as_bytes()[0].is_ascii_alphanumeric() + && name.as_bytes()[name.len() - 1].is_ascii_alphanumeric() +} + +/// One page of a listing. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Page { + pub objects: Vec, + pub truncated: bool, + pub next: Option, +} + +/// Reads a ListObjectsV2 answer. +pub fn parse_list(xml: &str) -> Result { + ensure!( + xml.contains("").skip(1) { + let part = part.split("").next().unwrap_or_default(); + let key = tag(part, "Key").context("S3 LIST: an object without a key")?; + let size = tag(part, "Size") + .and_then(|s| s.parse().ok()) + .with_context(|| format!("S3 LIST: {key} without a size"))?; + page.objects.push(Object { key, size }); + } + Ok(page) +} + +/// The text of the first `` element, unescaped. +fn tag(xml: &str, name: &str) -> Option { + let open = format!("<{name}>"); + let close = format!(""); + let start = xml.find(&open)? + open.len(); + let len = xml[start..].find(&close)?; + Some(xml_unescape(&xml[start..start + len])) +} + +fn xml_unescape(s: &str) -> String { + s.replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace("'", "'") + .replace("&", "&") +} + +pub fn amz_date(t: DateTime) -> String { + t.format("%Y%m%dT%H%M%SZ").to_string() +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +pub fn sha256_hex(b: &[u8]) -> String { + hex(digest::digest(&digest::SHA256, b).as_ref()) +} + +fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec { + hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, key), data) + .as_ref() + .to_vec() +} + +/// URI-encodes as SigV4 wants: unreserved characters stay, every other byte +/// becomes `%XX` in upper case; `/` stays in paths. +pub fn uri_encode(s: &str, keep_slash: bool) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) || (keep_slash && b == b'/') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +/// The `Authorization` header of one request (SigV4): pure, so the tests +/// check it against AWS's published example and the test server checks +/// every request with it. `headers` are the signed ones; names may come in +/// any case and order. +#[allow(clippy::too_many_arguments)] +pub fn sigv4( + method: &str, + canonical_path: &str, + canonical_query: &str, + headers: &[(String, String)], + payload_hash: &str, + amz_date: &str, + region: &str, + key_id: &str, + secret: &str, +) -> String { + let date = &amz_date[..8.min(amz_date.len())]; + let mut hs: Vec<(String, String)> = headers + .iter() + .map(|(k, v)| { + ( + k.to_ascii_lowercase(), + v.split_whitespace().collect::>().join(" "), + ) + }) + .collect(); + hs.sort(); + let canonical_headers: String = hs.iter().map(|(k, v)| format!("{k}:{v}\n")).collect(); + let signed = hs + .iter() + .map(|(k, _)| k.as_str()) + .collect::>() + .join(";"); + let canonical = format!( + "{method}\n{canonical_path}\n{canonical_query}\n{canonical_headers}\n{signed}\n{payload_hash}" + ); + let scope = format!("{date}/{region}/s3/aws4_request"); + let to_sign = format!( + "AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}", + sha256_hex(canonical.as_bytes()) + ); + let k = hmac_sha256(format!("AWS4{secret}").as_bytes(), date.as_bytes()); + let k = hmac_sha256(&k, region.as_bytes()); + let k = hmac_sha256(&k, b"s3"); + let k = hmac_sha256(&k, b"aws4_request"); + let signature = hex(&hmac_sha256(&k, to_sign.as_bytes())); + format!( + "AWS4-HMAC-SHA256 Credential={key_id}/{scope}, SignedHeaders={signed}, Signature={signature}" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + const EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + /// The secret key of AWS's documented examples. + const AWS_EXAMPLE_SECRET: &str = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; + + fn signature(auth: &str) -> &str { + auth.rsplit("Signature=").next().unwrap() + } + + /// AWS's example "GET Object" (Signature Calculations for the + /// Authorization Header: Transferring Payload in a Single Chunk). The + /// signature depends on the secret alone, not on the key id. + #[test] + fn sigv4_matches_the_aws_get_example() { + let auth = sigv4( + "GET", + "/test.txt", + "", + &[ + ("Host".into(), "examplebucket.s3.amazonaws.com".into()), + ("Range".into(), "bytes=0-9".into()), + ("x-amz-content-sha256".into(), EMPTY.into()), + ("x-amz-date".into(), "20130524T000000Z".into()), + ], + EMPTY, + "20130524T000000Z", + "us-east-1", + "EXAMPLE-KEY-ID", + AWS_EXAMPLE_SECRET, + ); + assert!( + auth.starts_with( + "AWS4-HMAC-SHA256 Credential=EXAMPLE-KEY-ID/20130524/us-east-1/s3/aws4_request, \ + SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, " + ), + "{auth}" + ); + assert_eq!( + signature(&auth), + "f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41" + ); + } + + /// AWS's example "GET Bucket (List Objects)": a query string. + #[test] + fn sigv4_matches_the_aws_list_example() { + let auth = sigv4( + "GET", + "/", + "max-keys=2&prefix=J", + &[ + ("host".into(), "examplebucket.s3.amazonaws.com".into()), + ("x-amz-content-sha256".into(), EMPTY.into()), + ("x-amz-date".into(), "20130524T000000Z".into()), + ], + EMPTY, + "20130524T000000Z", + "us-east-1", + "EXAMPLE-KEY-ID", + AWS_EXAMPLE_SECRET, + ); + assert_eq!( + signature(&auth), + "34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7" + ); + } + + #[test] + fn names_and_values_are_encoded_as_sigv4_wants() { + assert_eq!(uri_encode("documents/7.vdoc", true), "documents/7.vdoc"); + assert_eq!(uri_encode("a b/c~d", true), "a%20b/c~d"); + assert_eq!(uri_encode("a b/c", false), "a%20b%2Fc"); + assert_eq!(uri_encode("tok+/=", false), "tok%2B%2F%3D"); + assert_eq!(uri_encode("ไ", false), "%E0%B9%84"); + for good in ["visa-documents", "proplan.lol", "abc"] { + assert!(valid_bucket_name(good), "{good}"); + } + for bad in ["", "ab", "Visa", "visa_documents", "-visa", "visa-", "a/b"] { + assert!(!valid_bucket_name(bad), "{bad}"); + } + } + + #[test] + fn a_listing_reads_keys_sizes_and_the_next_page() { + let xml = "\ + \ + visa-documentsdocuments/2\ + 2true\ + documents/1.vdoc2026-11-19T10:00:00.000Z\ + "9b2cf535f27731c974343645a3985328"1234\ + STANDARD\ + documents/a&b.vdoc0\ + tok+/="; + let page = parse_list(xml).unwrap(); + assert_eq!( + page.objects, + [ + Object { + key: "documents/1.vdoc".into(), + size: 1234 + }, + Object { + key: "documents/a&b.vdoc".into(), + size: 0 + } + ] + ); + assert!(page.truncated); + assert_eq!(page.next.as_deref(), Some("tok+/=")); + let last = parse_list( + "false0", + ) + .unwrap(); + assert_eq!(last, Page::default()); + assert!(parse_list("AccessDenied").is_err()); + } + + #[test] + fn the_endpoint_is_a_server_and_the_secret_is_never_shown() { + let cfg = |endpoint: &str| S3Config { + endpoint: endpoint.into(), + bucket: "visa-documents".into(), + region: String::new(), + access_key_id: "GK0011".into(), + secret_access_key: "very-secret-value".into(), + }; + let b = Bucket::new(&cfg("http://127.0.0.1:3900/")).unwrap(); + assert_eq!(b.host, "127.0.0.1:3900"); + assert_eq!(b.region, "garage"); + assert_eq!(b.endpoint(), "http://127.0.0.1:3900"); + assert_eq!( + b.path("documents/7.vdoc"), + "/visa-documents/documents/7.vdoc" + ); + assert_eq!(b.path(""), "/visa-documents/"); + let b = Bucket::new(&cfg("http://[::1]:3900")).unwrap(); + assert_eq!(b.host, "[::1]:3900"); + for bad in [ + "127.0.0.1:3900", + "ftp://x", + "http://x/visa-documents", + "nonsense", + ] { + assert!(Bucket::new(&cfg(bad)).is_err(), "{bad}"); + } + let shown = format!("{:?} {:?}", cfg("http://x"), b); + assert!(!shown.contains("very-secret"), "{shown}"); + } +} diff --git a/src/seed.rs b/src/seed.rs index 0d2a2c9..41b54d2 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -818,7 +818,7 @@ pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Res sha256: &sha256, }; let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?; - store.put(id, bytes)?; + store.put(id, bytes.clone()).await?; written.push(id); audit::record( &mut *tx, diff --git a/src/web/documents.rs b/src/web/documents.rs index 8d257a1..f74ec90 100644 --- a/src/web/documents.rs +++ b/src/web/documents.rs @@ -663,9 +663,7 @@ async fn save( sha256: &f.sha256, }; let id = documents::insert(&mut tx, owner, meta, &file, &user.login).await?; - let s = store.clone(); - let bytes = f.bytes; - tokio::task::spawn_blocking(move || s.put(id, &bytes)).await??; + store.put(id, f.bytes).await?; written.push(id); audit::record( &mut *tx, @@ -690,7 +688,7 @@ async fn save( }; if let Err(e) = result { for id in &written { - if let Err(r) = store.remove(*id) { + if let Err(r) = store.remove(*id).await { error!("removing the file of the failed upload {id}: {r:#}"); } } @@ -822,7 +820,7 @@ pub async fn file(st: Arc, user: User, owner: Owner, id: i64, q: FileQ let Some(store) = st.files.clone() else { return Ok(files_off(&st)); }; - let bytes = match tokio::task::spawn_blocking(move || store.get(id)).await? { + let bytes = match store.get(id).await { Ok(b) if files::sha256_hex(&b) == d.sha256 => b, Ok(_) => { error!("document {id}: the file does not match the checksum of its upload"); @@ -1029,7 +1027,7 @@ pub async fn delete(st: Arc, user: User, owner: Owner, id: i64) -> Res ) .await?; tx.commit().await?; - if let Err(e) = tokio::task::spawn_blocking(move || store.remove(id)).await? { + if let Err(e) = store.remove(id).await { error!("document {id} is deleted, but not its file: {e:#}"); } Ok(Redirect::to(&list_page(owner)).into_response()) diff --git a/src/web/mod.rs b/src/web/mod.rs index 97fb7e4..e105652 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -39,7 +39,8 @@ pub struct AppState { provider: RwLock>>, /// The form token of local development, which has no sessions. local_csrf: String, - /// The documents' files; none in local development without a key. + /// The documents' files; none in local development without a place + /// and a key for them. pub files: Option, } @@ -50,11 +51,7 @@ impl AppState { .connect_timeout(Duration::from_secs(5)) .user_agent(concat!("visa/", env!("CARGO_PKG_VERSION"))) .build()?; - let files = cfg - .files - .as_ref() - .map(|f| Store::open(f.dir.clone(), f.key.clone())) - .transpose()?; + let files = cfg.files.as_ref().map(Store::open).transpose()?; Ok(Arc::new(AppState { templates: templates()?, files, diff --git a/tests/bucket.rs b/tests/bucket.rs new file mode 100644 index 0000000..d35a393 --- /dev/null +++ b/tests/bucket.rs @@ -0,0 +1,333 @@ +//! Documents in a bucket, where the server keeps them: an upload lands there +//! encrypted and opens, downloads and goes again; the check finds what is +//! wrong; the files of a directory move into the bucket, again and again +//! without harm; the mirror for the backups follows the bucket and fills a +//! new one; a busy server is asked again and a wrong key is an error. + +use std::time::Duration; + +use axum::http::StatusCode; +use sqlx::PgPool; +use visa::config::{Auth, Config, FilesConfig, FilesPlace}; +use visa::documents; +use visa::files::{self, FileKey, Mirrored, Store}; +use visa::s3::Bucket; + +use crate::common::fake_s3::FakeS3; +use crate::common::{App, bucket_config, config, files_dir, local, pdf, with_config}; +use crate::documents::person; + +fn on_bucket(pool: &PgPool, s3: &FakeS3) -> App { + with_config(pool.clone(), bucket_config(Auth::Disabled, s3)) +} + +fn object(id: i64) -> String { + format!("documents/{id}.vdoc") +} + +async fn ids(pool: &PgPool) -> Vec { + sqlx::query_scalar("SELECT id FROM documents ORDER BY id") + .fetch_all(pool) + .await + .unwrap() +} + +/// Uploads one PDF per text to the person's documents. +async fn upload(app: &App, person: i64, texts: &[&str]) { + for t in texts { + let r = app + .upload( + &format!("/people/{person}/documents"), + &[("kind", "other")], + &[(&format!("{t}.pdf"), &pdf(t))], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + } +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn an_upload_lies_encrypted_in_the_bucket_and_goes_with_its_document(pool: PgPool) { + let s3 = FakeS3::start().await; + let app = on_bucket(&pool, &s3); + let id = person(&app, "Doe").await; + let base = format!("/people/{id}/documents"); + let scan = pdf("the photo page of a passport"); + let r = app + .upload( + &base, + &[("kind", "passport-photo-page")], + &[("scan.pdf", &scan)], + ) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); + let did = ids(&pool).await[0]; + + // in the bucket under its id, encrypted, and nothing else there + assert_eq!(s3.keys(), [object(did)]); + let stored = s3.object(&object(did)).unwrap(); + assert!(stored.starts_with(b"VISADOC1")); + assert!(!stored.windows(10).any(|w| w == b"photo page")); + // the write asked the server not to replace anything + let put = format!("PUT /visa-documents/{} if-none-match", object(did)); + assert!(s3.requests().contains(&put), "{:?}", s3.requests()); + + // it opens and downloads as it was uploaded + let file = format!("{base}/{did}/file"); + let r = app.get(&file).await; + assert_eq!(r.status, StatusCode::OK); + assert_eq!(r.bytes, scan); + let r = app.get(&format!("{file}?download=1")).await; + assert_eq!(r.status, StatusCode::OK); + assert_eq!(r.bytes, scan); + + // the check reads it back from the bucket + let store = app.st.files.as_ref().unwrap(); + assert!( + store + .describe() + .starts_with("bucket visa-documents at http://127.0.0.1:") + ); + store.check().await.unwrap(); + let check = documents::check(&pool, store).await.unwrap(); + assert_eq!(check.documents, 1); + assert!(check.problems.is_empty(), "{:?}", check.problems); + + // deleted: the object goes with the row + let r = app.post(&format!("{base}/{did}/delete"), &[]).await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + assert!(s3.keys().is_empty(), "{:?}", s3.keys()); + assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND); +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_check_finds_swapped_missing_and_stray_objects(pool: PgPool) { + let s3 = FakeS3::start().await; + let app = on_bucket(&pool, &s3); + let id = person(&app, "Doe").await; + upload(&app, id, &["first", "second", "third", "fourth"]).await; + let ids = ids(&pool).await; + let store = app.st.files.as_ref().unwrap(); + assert!( + documents::check(&pool, store) + .await + .unwrap() + .problems + .is_empty() + ); + + // the first two swapped, the third gone, two objects of no document + let (a, b) = ( + s3.object(&object(ids[0])).unwrap(), + s3.object(&object(ids[1])).unwrap(), + ); + s3.put(&object(ids[0]), &b); + s3.put(&object(ids[1]), &a); + s3.remove(&object(ids[2])); + s3.put(&object(77), b"left over"); + s3.put("notes.txt", b"not ours"); + + let r = app + .get(&format!("/people/{id}/documents/{}/file", ids[0])) + .await; + assert_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR); + assert!(r.text().contains("cannot be opened"), "{}", r.body); + assert!(!r.bytes.windows(6).any(|w| w == b"second")); + + // five objects, read in pages of two + let check = documents::check(&pool, store).await.unwrap(); + let p = &check.problems; + assert_eq!(p.len(), 5, "{p:?}"); + assert!( + p[0].contains("damaged, or the file of another document"), + "{p:?}" + ); + assert!( + p[1].contains("damaged, or the file of another document"), + "{p:?}" + ); + assert!(p[2].contains("is missing"), "{p:?}"); + assert!( + p[3].contains("77.vdoc: a file without its document"), + "{p:?}" + ); + assert!(p[4].contains("notes.txt: not a file of the store"), "{p:?}"); + let lists = s3 + .requests() + .iter() + .filter(|r| r.contains("list-type=2")) + .count(); + assert!(lists >= 3, "{:?}", s3.requests()); +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_files_move_from_their_directory_into_the_bucket(pool: PgPool) { + // before: the files in a directory, as on the server until now + let before = local(pool.clone()); + let id = person(&before, "Doe").await; + upload(&before, id, &["passport", "receipt"]).await; + let ids = ids(&pool).await; + let old = before.st.files.as_ref().unwrap(); + let dir = old.dir().unwrap().to_path_buf(); + let key = old.file_key().clone(); + std::fs::write(dir.join("99.vdoc"), b"no document's").unwrap(); + std::fs::write(dir.join(".98.vdoc.part"), b"cut short").unwrap(); + let e = documents::migrate(&pool, &dir, old).await.unwrap_err(); + assert!(e.to_string().contains("the store itself"), "{e}"); + + // after: the same key, the files in the bucket, byte for byte + let s3 = FakeS3::start().await; + let store = Store::in_bucket(&s3.config(), key.clone()).unwrap(); + let moved = documents::migrate(&pool, &dir, &store).await.unwrap(); + assert_eq!((moved.copied, moved.there), (2, 0)); + assert_eq!(moved.strays, ["99.vdoc", ".98.vdoc.part"]); + assert!(moved.missing.is_empty()); + for id in &ids { + let on_disk = std::fs::read(dir.join(files::file_name(*id))).unwrap(); + assert_eq!(s3.object(&object(*id)).unwrap(), on_disk); + } + assert!(s3.object(&object(99)).is_none(), "strays stay behind"); + + // the app on the bucket opens them + let after = with_config( + pool.clone(), + Config { + files: Some(FilesConfig { + place: FilesPlace::Bucket(s3.config()), + key: key.clone(), + }), + ..config(Auth::Disabled) + }, + ); + for (id_, text) in ids.iter().zip(["passport", "receipt"]) { + let r = after + .get(&format!("/people/{id}/documents/{id_}/file")) + .await; + assert_eq!(r.status, StatusCode::OK); + assert_eq!(r.bytes, pdf(text)); + } + + // again: nothing to copy, so a stopped run can simply start over + let moved = documents::migrate(&pool, &dir, &store).await.unwrap(); + assert_eq!((moved.copied, moved.there), (0, 2)); + + // a file in neither place is reported, not invented + std::fs::remove_file(dir.join(files::file_name(ids[1]))).unwrap(); + s3.remove(&object(ids[1])); + let moved = documents::migrate(&pool, &dir, &store).await.unwrap(); + assert_eq!(moved.missing, [ids[1]]); + + // the bucket holding other bytes for a document stops the copy, and + // the object stays as it is + s3.put(&object(ids[0]), b"other bytes"); + let e = documents::migrate(&pool, &dir, &store).await.unwrap_err(); + assert!(format!("{e:#}").contains("other bytes"), "{e:#}"); + assert_eq!(s3.object(&object(ids[0])).unwrap(), b"other bytes"); + + // a damaged file in the directory is never copied + s3.remove(&object(ids[0])); + let path = dir.join(files::file_name(ids[0])); + let mut damaged = std::fs::read(&path).unwrap(); + let last = damaged.len() - 20; + damaged[last] ^= 1; + std::fs::write(&path, damaged).unwrap(); + let e = documents::migrate(&pool, &dir, &store).await.unwrap_err(); + assert!(format!("{e:#}").contains("damaged"), "{e:#}"); + assert!(s3.object(&object(ids[0])).is_none()); +} + +#[sqlx::test(migrator = "visa::db::MIGRATOR")] +async fn the_mirror_follows_the_bucket_and_fills_a_new_one(pool: PgPool) { + let s3 = FakeS3::start().await; + let app = on_bucket(&pool, &s3); + let id = person(&app, "Doe").await; + upload(&app, id, &["one", "two", "three"]).await; + let ids = ids(&pool).await; + let store = app.st.files.as_ref().unwrap(); + let mirror = files_dir(); + + let m = files::mirror(store, &mirror).await.unwrap(); + assert_eq!( + m, + Mirrored { + copied: 3, + kept: 0, + removed: 0 + } + ); + for id in &ids { + assert_eq!( + std::fs::read(mirror.join(files::file_name(*id))).unwrap(), + s3.object(&object(*id)).unwrap() + ); + } + + // a deletion reaches the mirror at its next run + let r = app + .post(&format!("/people/{id}/documents/{}/delete", ids[2]), &[]) + .await; + assert_eq!(r.status, StatusCode::SEE_OTHER); + let m = files::mirror(store, &mirror).await.unwrap(); + assert_eq!( + m, + Mirrored { + copied: 0, + kept: 2, + removed: 1 + } + ); + + // the bucket is lost: a new one is filled from the mirror and checks + // out against the database + let fresh = FakeS3::start().await; + let restored = Store::in_bucket(&fresh.config(), store.file_key().clone()).unwrap(); + let moved = documents::migrate(&pool, &mirror, &restored).await.unwrap(); + assert_eq!((moved.copied, moved.there), (2, 0)); + let check = documents::check(&pool, &restored).await.unwrap(); + assert_eq!(check.documents, 2); + assert!(check.problems.is_empty(), "{:?}", check.problems); + std::fs::remove_dir_all(&mirror).ok(); +} + +#[tokio::test] +async fn a_busy_server_is_asked_again_and_a_wrong_key_is_an_error() { + let s3 = FakeS3::start().await; + let key = FileKey::random(); + let bucket = Bucket::new(&s3.config()) + .unwrap() + .with_pause(Duration::from_millis(10)); + let store = Store::with_bucket(bucket, key.clone()); + + // two refusals, then an answer: the third attempt goes through + s3.fail_next(2); + store.put(5, pdf("five")).await.unwrap(); + assert_eq!(store.get(5).await.unwrap(), pdf("five")); + // three refusals are an error that says what happened + s3.fail_next(3); + let e = store.get(5).await.unwrap_err(); + assert!(format!("{e:#}").contains("HTTP 503 SlowDown"), "{e:#}"); + + // the same id again: refused, and the object stays + let e = store.put(5, pdf("other")).await.unwrap_err(); + assert!(format!("{e:#}").contains("other bytes"), "{e:#}"); + assert_eq!(store.get(5).await.unwrap(), pdf("five")); + + // a wrong secret is refused, never taken for a missing file + let mut cfg = s3.config(); + cfg.secret_access_key = "wrong".into(); + let wrong = Store::in_bucket(&cfg, key.clone()).unwrap(); + let e = wrong.get(5).await.unwrap_err(); + assert!(format!("{e:#}").contains("SignatureDoesNotMatch"), "{e:#}"); + assert!(wrong.check().await.is_err()); + assert!(store.check().await.is_ok()); + + // a bucket that does not exist is not a missing file either + let mut cfg = s3.config(); + cfg.bucket = "other-bucket".into(); + let other = Store::in_bucket(&cfg, key).unwrap(); + let e = other.get_sealed(5).await.unwrap_err(); + assert!(format!("{e:#}").contains("NoSuchBucket"), "{e:#}"); + + // no secret in any of these messages + assert!(!format!("{e:#}").contains(crate::common::fake_s3::SECRET)); +} diff --git a/tests/common/fake_s3.rs b/tests/common/fake_s3.rs new file mode 100644 index 0000000..41a9c9d --- /dev/null +++ b/tests/common/fake_s3.rs @@ -0,0 +1,379 @@ +//! An S3 server inside the test process: path-style, one bucket, objects in +//! memory. It checks every request's SigV4 signature as Garage does, from +//! the request as it arrived (method, path, query, the signed headers and +//! the payload's hash, which must match the body), so a client that signs +//! one thing and sends another fails here. A listing comes in pages of two +//! keys with tokens that need encoding, so the client's paging is +//! exercised. `fail_next` makes it answer 503 to the next requests. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + +use axum::Router; +use axum::body::Body; +use axum::extract::{Request, State}; +use axum::http::{HeaderMap, Method, StatusCode, header}; +use axum::response::Response; +use visa::s3::{S3Config, sha256_hex, sigv4, uri_encode}; + +pub const KEY_ID: &str = "GK0123456789abcdef01234567"; +pub const SECRET: &str = "test-s3-secret-not-secret"; +pub const BUCKET: &str = "visa-documents"; + +struct Shared { + objects: Mutex>>, + requests: Mutex>, + fail_next: Mutex, +} + +pub struct FakeS3 { + pub endpoint: String, + shared: Arc, + task: tokio::task::JoinHandle<()>, +} + +impl Drop for FakeS3 { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl FakeS3 { + pub async fn start() -> FakeS3 { + let shared = Arc::new(Shared { + objects: Mutex::new(BTreeMap::new()), + requests: Mutex::new(Vec::new()), + fail_next: Mutex::new(0), + }); + let app = Router::new().fallback(handle).with_state(shared.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let task = tokio::spawn(async move { + axum::serve(listener, app).await.ok(); + }); + FakeS3 { + endpoint: format!("http://{addr}"), + shared, + task, + } + } + + pub fn config(&self) -> S3Config { + S3Config { + endpoint: self.endpoint.clone(), + bucket: BUCKET.into(), + region: "garage".into(), + access_key_id: KEY_ID.into(), + secret_access_key: SECRET.into(), + } + } + + pub fn object(&self, key: &str) -> Option> { + self.shared.objects.lock().unwrap().get(key).cloned() + } + + pub fn put(&self, key: &str, bytes: &[u8]) { + self.shared + .objects + .lock() + .unwrap() + .insert(key.to_string(), bytes.to_vec()); + } + + pub fn remove(&self, key: &str) { + self.shared.objects.lock().unwrap().remove(key); + } + + pub fn keys(&self) -> Vec { + self.shared + .objects + .lock() + .unwrap() + .keys() + .cloned() + .collect() + } + + /// Answer 503 to the next `n` requests. + pub fn fail_next(&self, n: usize) { + *self.shared.fail_next.lock().unwrap() = n; + } + + /// The requests so far: `METHOD path?query`, with ` if-none-match` when + /// a PUT carried it. + pub fn requests(&self) -> Vec { + self.shared.requests.lock().unwrap().clone() + } +} + +fn answer(status: StatusCode, body: Vec) -> Response { + Response::builder() + .status(status) + .body(Body::from(body)) + .unwrap() +} + +fn error(status: StatusCode, code: &str) -> Response { + let xml = format!( + "{code}\ + {code}" + ); + Response::builder() + .status(status) + .header(header::CONTENT_TYPE, "application/xml") + .body(Body::from(xml)) + .unwrap() +} + +fn decode(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' + && i + 3 <= b.len() + && let Some(v) = std::str::from_utf8(&b[i + 1..i + 3]) + .ok() + .and_then(|h| u8::from_str_radix(h, 16).ok()) + { + out.push(v); + i += 3; + continue; + } + out.push(b[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +fn xml_escape(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +fn hex(s: &str) -> String { + s.bytes().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(s: &str) -> Option { + let bytes: Option> = (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()) + .collect(); + String::from_utf8(bytes?).ok() +} + +/// The signature check: what Garage refuses, this refuses. The error is +/// the answer to send. +#[allow(clippy::result_large_err)] +fn verify( + method: &Method, + path: &str, + query: &str, + headers: &HeaderMap, + body: &[u8], +) -> Result<(), Response> { + let deny = |code: &str| error(StatusCode::FORBIDDEN, code); + let h = |name: &str| { + headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + }; + let auth = h("authorization").ok_or_else(|| deny("AccessDenied"))?; + let rest = auth + .strip_prefix("AWS4-HMAC-SHA256 ") + .ok_or_else(|| deny("AccessDenied"))?; + let mut credential = ""; + let mut signed = ""; + let mut signature = ""; + for part in rest.split(", ") { + if let Some(v) = part.strip_prefix("Credential=") { + credential = v; + } else if let Some(v) = part.strip_prefix("SignedHeaders=") { + signed = v; + } else if let Some(v) = part.strip_prefix("Signature=") { + signature = v; + } + } + let scope: Vec<&str> = credential.split('/').collect(); + let [key_id, date, region, "s3", "aws4_request"] = scope.as_slice() else { + return Err(deny("AuthorizationHeaderMalformed")); + }; + if *key_id != KEY_ID { + return Err(deny("InvalidAccessKeyId")); + } + let amz_date = h("x-amz-date").unwrap_or_default(); + if !amz_date.starts_with(date) || *region != "garage" { + return Err(deny("SignatureDoesNotMatch")); + } + let payload = h("x-amz-content-sha256").unwrap_or_default(); + if payload != sha256_hex(body) { + return Err(error(StatusCode::BAD_REQUEST, "XAmzContentSHA256Mismatch")); + } + let names: Vec<&str> = signed.split(';').collect(); + for must in ["host", "x-amz-content-sha256", "x-amz-date"] { + if !names.contains(&must) { + return Err(deny("SignatureDoesNotMatch")); + } + } + for (name, _) in headers { + if name.as_str().starts_with("x-amz-") && !names.contains(&name.as_str()) { + return Err(deny("SignatureDoesNotMatch")); + } + } + let signed_headers: Vec<(String, String)> = names + .iter() + .map(|n| (n.to_string(), h(n).unwrap_or_default())) + .collect(); + let mut q: Vec<(String, String)> = query + .split('&') + .filter(|p| !p.is_empty()) + .map(|p| { + let (k, v) = p.split_once('=').unwrap_or((p, "")); + (uri_encode(&decode(k), false), uri_encode(&decode(v), false)) + }) + .collect(); + q.sort(); + let canonical_query = q + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("&"); + let want = sigv4( + method.as_str(), + &uri_encode(&decode(path), true), + &canonical_query, + &signed_headers, + &payload, + &amz_date, + region, + key_id, + SECRET, + ); + if want.rsplit("Signature=").next() != Some(signature) { + return Err(deny("SignatureDoesNotMatch")); + } + Ok(()) +} + +async fn handle(State(s): State>, req: Request) -> Response { + let (parts, body) = req.into_parts(); + let body = axum::body::to_bytes(body, usize::MAX) + .await + .unwrap() + .to_vec(); + let path = parts.uri.path().to_string(); + let query = parts.uri.query().unwrap_or_default().to_string(); + let method = parts.method.clone(); + let conditional = parts.headers.contains_key(header::IF_NONE_MATCH); + s.requests.lock().unwrap().push(format!( + "{method} {path}{}{}", + if query.is_empty() { + String::new() + } else { + format!("?{query}") + }, + if conditional { " if-none-match" } else { "" } + )); + let busy = { + let mut n = s.fail_next.lock().unwrap(); + let busy = *n > 0; + *n = n.saturating_sub(1); + busy + }; + if busy { + return error(StatusCode::SERVICE_UNAVAILABLE, "SlowDown"); + } + if let Err(r) = verify(&method, &path, &query, &parts.headers, &body) { + return r; + } + let rest = match path.strip_prefix(&format!("/{BUCKET}")) { + Some("") => String::new(), + Some(r) if r.starts_with('/') => decode(&r[1..]), + _ => return error(StatusCode::NOT_FOUND, "NoSuchBucket"), + }; + let params: BTreeMap = query + .split('&') + .filter(|p| !p.is_empty()) + .map(|p| { + let (k, v) = p.split_once('=').unwrap_or((p, "")); + (decode(k), decode(v)) + }) + .collect(); + let mut objects = s.objects.lock().unwrap(); + if rest.is_empty() { + if method != Method::GET || params.get("list-type").map(String::as_str) != Some("2") { + return error(StatusCode::NOT_IMPLEMENTED, "NotImplemented"); + } + let prefix = params.get("prefix").cloned().unwrap_or_default(); + let max: usize = params + .get("max-keys") + .and_then(|m| m.parse().ok()) + .unwrap_or(1000) + .min(2); + let start = match params.get("continuation-token") { + Some(t) => match t.strip_prefix("tok+/=").and_then(unhex) { + Some(k) => k, + None => return error(StatusCode::BAD_REQUEST, "InvalidArgument"), + }, + None => String::new(), + }; + let keys: Vec<(&String, &Vec)> = objects + .iter() + .filter(|(k, _)| k.starts_with(&prefix) && **k >= start) + .collect(); + let page = &keys[..keys.len().min(max)]; + let mut xml = format!( + "\ + \ + {BUCKET}{}{}\ + {max}{}", + xml_escape(&prefix), + page.len(), + keys.len() > page.len() + ); + for (k, v) in page { + xml.push_str(&format!( + "{}{}STANDARD", + xml_escape(k), + v.len() + )); + } + if keys.len() > page.len() { + xml.push_str(&format!( + "tok+/={}", + hex(keys[page.len()].0) + )); + } + xml.push_str(""); + return answer(StatusCode::OK, xml.into_bytes()); + } + match method { + Method::PUT => { + if conditional && objects.contains_key(&rest) { + return error(StatusCode::PRECONDITION_FAILED, "PreconditionFailed"); + } + objects.insert(rest, body); + answer(StatusCode::OK, Vec::new()) + } + Method::GET => match objects.get(&rest) { + Some(b) => answer(StatusCode::OK, b.clone()), + None => error(StatusCode::NOT_FOUND, "NoSuchKey"), + }, + Method::HEAD => match objects.get(&rest) { + Some(b) => Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_LENGTH, b.len()) + .body(Body::empty()) + .unwrap(), + None => answer(StatusCode::NOT_FOUND, Vec::new()), + }, + Method::DELETE => { + objects.remove(&rest); + answer(StatusCode::NO_CONTENT, Vec::new()) + } + _ => error(StatusCode::NOT_IMPLEMENTED, "NotImplemented"), + } +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 934eb6b..7a86e40 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,5 +1,7 @@ #![allow(dead_code)] +pub mod fake_s3; + use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -11,12 +13,12 @@ use chrono::NaiveDate; use http_body_util::BodyExt; use sqlx::PgPool; use tower::ServiceExt; -use visa::config::{Auth, Config, FilesConfig, OidcConfig}; +use visa::config::{Auth, Config, FilesConfig, FilesPlace, OidcConfig}; use visa::files::FileKey; use visa::web::{self, AppState}; /// A files directory of its own for each app, under the target directory. -fn files_dir() -> PathBuf { +pub fn files_dir() -> PathBuf { static N: AtomicUsize = AtomicUsize::new(0); PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!( "files-{}-{}", @@ -34,12 +36,23 @@ pub fn config(auth: Auth) -> Config { database_password: None, auth, files: Some(FilesConfig { - dir: files_dir(), + place: FilesPlace::Dir(files_dir()), key: FileKey::random(), }), } } +/// Documents on, in the test server's bucket, with a fresh key. +pub fn bucket_config(auth: Auth, s3: &fake_s3::FakeS3) -> Config { + Config { + files: Some(FilesConfig { + place: FilesPlace::Bucket(s3.config()), + key: FileKey::random(), + }), + ..config(auth) + } +} + pub fn oidc_config(issuer: &str) -> OidcConfig { OidcConfig { issuer: issuer.into(), @@ -58,7 +71,11 @@ pub struct App { // The test's files go with it. impl Drop for App { fn drop(&mut self) { - if let Some(dir) = self.st.cfg.files.as_ref().map(|f| f.dir.clone()) { + if let Some(FilesConfig { + place: FilesPlace::Dir(dir), + .. + }) = &self.st.cfg.files + { std::fs::remove_dir_all(dir).ok(); } } diff --git a/tests/documents.rs b/tests/documents.rs index 713a718..b5d57a2 100644 --- a/tests/documents.rs +++ b/tests/documents.rs @@ -10,7 +10,7 @@ use visa::web::documents::FILE_LIMIT; use crate::common::{App, Part, config, id_from, local, pdf, with_config}; -async fn person(app: &App, surname: &str) -> i64 { +pub async fn person(app: &App, surname: &str) -> i64 { let r = app .post( "/people", @@ -70,10 +70,10 @@ type Refusal<'a> = (Vec<(&'a str, &'a str)>, Vec<(&'a str, &'a [u8])>, &'a str); /// A forged upload: its parts, its headers, the answer and what it says. type Forged<'a> = (Vec>, &'a [(&'a str, &'a str)], StatusCode, &'a str); -fn stored(app: &App) -> usize { +async fn stored(app: &App) -> usize { let store = app.st.files.as_ref().unwrap(); - let (ids, other) = store.entries().unwrap(); - ids.len() + other.len() + let e = store.entries().await.unwrap(); + e.files.len() + e.other.len() } #[sqlx::test(migrator = "visa::db::MIGRATOR")] @@ -105,7 +105,7 @@ async fn a_scan_is_stored_encrypted_and_every_step_is_audited(pool: PgPool) { // on the disk only encrypted, under the document's id let store = app.st.files.as_ref().unwrap(); - let on_disk = std::fs::read(store.path(did)).unwrap(); + let on_disk = std::fs::read(store.dir().unwrap().join(format!("{did}.vdoc"))).unwrap(); assert!(on_disk.starts_with(b"VISADOC1")); assert!(!on_disk.windows(10).any(|w| w == b"photo page")); @@ -167,7 +167,7 @@ async fn a_scan_is_stored_encrypted_and_every_step_is_audited(pool: PgPool) { .post(&format!("/people/{id}/documents/{did}/delete"), &[]) .await; assert_eq!(r.status, StatusCode::SEE_OTHER); - assert!(!store.path(did).exists()); + assert!(store.get_sealed(did).await.unwrap().is_none()); assert_eq!(count(&pool).await, 0); assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND); @@ -262,7 +262,7 @@ async fn uploads_are_checked_before_anything_is_stored(pool: PgPool) { assert!(t.contains("Nothing was uploaded"), "{want}"); } assert_eq!(count(&pool).await, 0); - assert_eq!(stored(&app), 0); + assert_eq!(stored(&app).await, 0); // the same file again for the same person let r = app @@ -363,7 +363,7 @@ async fn an_upload_needs_the_form_token_first_and_this_site(pool: PgPool) { .await; assert_eq!(r.status, StatusCode::NOT_FOUND); assert_eq!(count(&pool).await, 0); - assert_eq!(stored(&app), 0); + assert_eq!(stored(&app).await, 0); } #[sqlx::test(migrator = "visa::db::MIGRATOR")] @@ -527,7 +527,11 @@ async fn a_file_cannot_pass_for_another_and_the_check_finds_it(pool: PgPool) { ); // the two files swapped on the disk - let (pa, pb) = (store.path(ids[0]), store.path(ids[1])); + let dir = store.dir().unwrap(); + let (pa, pb) = ( + dir.join(format!("{}.vdoc", ids[0])), + dir.join(format!("{}.vdoc", ids[1])), + ); let tmp = pa.with_extension("swap"); std::fs::rename(&pa, &tmp).unwrap(); std::fs::rename(&pb, &pa).unwrap(); @@ -536,7 +540,7 @@ async fn a_file_cannot_pass_for_another_and_the_check_finds_it(pool: PgPool) { assert_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR); assert!(r.text().contains("cannot be opened"), "{}", r.body); assert!(!r.bytes.windows(6).any(|w| w == b"second")); - std::fs::write(store.dir().join("77.vdoc"), b"left over").unwrap(); + std::fs::write(dir.join("77.vdoc"), b"left over").unwrap(); let check = documents::check(&pool, store).await.unwrap(); assert_eq!(check.documents, 2); assert_eq!(check.problems.len(), 3, "{:?}", check.problems); diff --git a/tests/garage.rs b/tests/garage.rs new file mode 100644 index 0000000..1244dbc --- /dev/null +++ b/tests/garage.rs @@ -0,0 +1,98 @@ +//! The store against a real Garage, the version cnx01 runs: +//! `bash scripts/dev-garage.sh` starts one in Docker and writes +//! `.dev/garage.env`; `. .dev/garage.env` before `cargo test` runs this. +//! Without VISA_TEST_S3_* set it is skipped (CI has no Garage; the test +//! server in tests/common/fake_s3.rs covers the same calls there). + +use visa::files::{FileKey, Store}; +use visa::s3::{Bucket, Put, S3Config}; + +use crate::common::pdf; + +fn garage() -> Option { + let v = |n: &str| std::env::var(n).ok().filter(|s| !s.is_empty()); + let secret = std::fs::read_to_string(v("VISA_TEST_S3_SECRET_FILE")?).ok()?; + Some(S3Config { + endpoint: v("VISA_TEST_S3_ENDPOINT")?, + bucket: v("VISA_TEST_S3_BUCKET")?, + region: v("VISA_TEST_S3_REGION").unwrap_or_else(|| "garage".into()), + access_key_id: v("VISA_TEST_S3_ACCESS_KEY_ID")?, + secret_access_key: secret.trim().to_string(), + }) +} + +/// Ids no other run uses at the same time: the bucket is shared. +fn fresh_ids(n: i64) -> Vec { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .subsec_nanos() as i64; + let base = 1_000_000_000 + (std::process::id() as i64 % 1000) * 1_000_000 + nanos % 1_000_000; + (0..n).map(|i| base + i * 7).collect() +} + +#[tokio::test] +async fn the_store_works_against_a_real_garage() { + let Some(cfg) = garage() else { + eprintln!("VISA_TEST_S3_* not set: skipped (scripts/dev-garage.sh)"); + return; + }; + let key = FileKey::random(); + let store = Store::in_bucket(&cfg, key.clone()).unwrap(); + store.check().await.unwrap(); + let ids = fresh_ids(3); + for id in &ids { + store + .put(*id, pdf(&format!("document {id}"))) + .await + .unwrap(); + } + for id in &ids { + assert_eq!( + store.get(*id).await.unwrap(), + pdf(&format!("document {id}")) + ); + } + // the listing names them with their sizes, page after page + let entries = store.entries().await.unwrap(); + for id in &ids { + let size = store.get_sealed(*id).await.unwrap().unwrap().len() as u64; + assert!(entries.files.contains(&(*id, size)), "{id}: {entries:?}"); + } + // never replaced: the same bytes count as stored, others are refused + let sealed = store.get_sealed(ids[0]).await.unwrap().unwrap(); + assert_eq!( + store.put_sealed(ids[0], sealed.clone()).await.unwrap(), + Put::Same + ); + let e = store.put(ids[0], pdf("other")).await.unwrap_err(); + assert!(format!("{e:#}").contains("other bytes"), "{e:#}"); + assert_eq!(store.get_sealed(ids[0]).await.unwrap().unwrap(), sealed); + // Garage 2.5 ignores If-None-Match on a PUT and writes (seen on Nov 19, + // 2026): on a scratch object of this run, never on a document's + let bucket = Bucket::new(&cfg).unwrap(); + let scratch = format!("scratch/{}.probe", ids[0]); + assert!(bucket.put_if_absent(&scratch, b"first").await.unwrap()); + let honored = !bucket.put_if_absent(&scratch, b"second").await.unwrap(); + let kept = bucket.get(&scratch).await.unwrap().unwrap(); + assert_eq!( + (honored, kept.as_slice()), + (false, b"second".as_slice()), + "Garage now honors If-None-Match: update the comment on Bucket::put_if_absent" + ); + bucket.delete(&scratch).await.unwrap(); + // a wrong secret is refused, not taken for a missing file + let mut wrong = cfg.clone(); + wrong.secret_access_key = "wrong".into(); + let e = Store::in_bucket(&wrong, key) + .unwrap() + .get(ids[0]) + .await + .unwrap_err(); + assert!(format!("{e:#}").contains("HTTP 403"), "{e:#}"); + for id in &ids { + store.remove(*id).await.unwrap(); + store.remove(*id).await.unwrap(); + assert!(store.get_sealed(*id).await.unwrap().is_none()); + } +} diff --git a/tests/main.rs b/tests/main.rs index 5c3fb0f..90b5b6d 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -3,10 +3,12 @@ //! databases); each `#[sqlx::test]` gets its own database. mod auth; +mod bucket; mod common; mod companies; mod deadlines; mod documents; +mod garage; mod pages; mod papers; mod people;