Documents in a bucket of Garage, still encrypted by the app
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 52s

Asked for on November 19, 2026: the uploaded files land in an S3 bucket of
the fleet's Garage instead of a directory on cnx01, as the fleet's other
apps keep theirs. The app encrypts each file exactly as before (AES-256-GCM
under a key from HKDF, the document's id authenticated), so the bucket holds
the same VISADOC1 files and Garage never sees a key or a document in the
clear. Garage's SSE-C stays off: its key would come from the same secret.

src/s3.rs is a small S3 client on reqwest and ring, as in proplan: SigV4
(checked against AWS's two published examples), path-style PUT, GET, HEAD,
DELETE and ListObjectsV2 page by page, three attempts when the server is
away or busy. It asks before it writes, so no object is replaced; it sends
If-None-Match: * as well, which Garage 2.5 ignores (seen in tests/garage.rs).

The store (src/files.rs) keeps the files as documents/<id>.vdoc in the
bucket, or as <id>.vdoc in a directory for development and the tests. Its
calls are async now. VISA_S3_BUCKET, _ENDPOINT, _REGION and _ACCESS_KEY_ID
name the bucket, the secret comes from VISA_S3_SECRET_ACCESS_KEY_FILE or the
credential s3-secret; the bucket and a directory together are refused. At
the start the app checks the bucket in the background and only warns.

New commands: `visa files-migrate --from DIR` copies the files of a
directory into the store, each opened and compared with its upload before
and after, 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 it.

Tests: an S3 server inside the test process that checks every request's
signature and pages its listings (tests/common/fake_s3.rs); uploads, views,
downloads and deletions through it, the check finding swapped, missing and
stray objects, the move from a directory (again, missing, other bytes,
damaged), the mirror and a restore from it, a busy server and a wrong key.
tests/garage.rs runs the store against Garage 2.5.0, the version cnx01 runs,
which scripts/dev-garage.sh starts in Docker; VISA_DEV_S3=1 scripts/dev.sh
runs the dev server on it. The 14 demo documents moved into it with
files-migrate and a browser upload landed there.
This commit is contained in:
grabowski committed 2026-11-19 20:35:32 +07:00
1 parent 17426dba12
commit 0370e0154f
20 files changed
+2558 -218

No files matched your search

+12 -7
View File
@@ -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 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 the token itself, which must be the form's first field, before it reads a
file (`src/web/documents.rs`). file (`src/web/documents.rs`).
- **Documents** are encrypted files in `VISA_FILES_DIR` (`src/files.rs`); - **Documents** are files the app encrypts before it stores them
never write a document's file another way, and never log its contents or (`src/files.rs`): in a bucket of the fleet's Garage on the server
its name. Opening a file is a `view` of the document, saving it a (`VISA_S3_*`, `src/s3.rs`), in a directory in development
`download`. Local files and their key live in `.dev/`, which git ignores. (`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; - **No inline script or style.** The Content Security Policy refuses them;
`tests/pages.rs` checks the templates. `tests/pages.rs` checks the templates.
- **Migrations** are never edited once they are on `main`; add a new file. - **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 | | 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/config.rs` | settings from the environment and credentials |
| `src/oidc.rs` | OpenID Connect against Kanidm (PKCE, nonce, ES256), from the fleet overview | | `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 | | `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/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/companies.rs` | what only companies need: list, archive, selections, employees |
| `src/mrz.rs` | reading the passport's machine-readable zone (ICAO 9303, TD3) | | `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/files.rs` | the encrypted document store (a bucket or a directory): sealing, opening, the mirror for backups, checking a file's type |
| `src/documents.rs` | documents of people and companies: kinds, records, SQL, `files-check` | | `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 | | `src/web/` | routes, the login gate, pages |
| `templates/` | minijinja templates, compiled in by `build.rs` | | `templates/` | minijinja templates, compiled in by `build.rs` |
| `static/` | CSS and JavaScript, compiled in; the URL carries a content hash | | `static/` | CSS and JavaScript, compiled in; the URL carries a content hash |
+44 -20
View File
@@ -33,8 +33,10 @@ Data Protection Act (PDPA) asks.
- Documents: scans and photos of the passport pages, the TDAC, receipts and - 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 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 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 extension packs. The app encrypts each file before it stores it in a
browser's viewer, and every upload, view and download is in the log. 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: - 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 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 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 ignores. The demo command refuses to run when a login provider is
configured. 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: The tests need the same database; each test gets its own:
```sh ```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 The server reads its settings from the environment. Secrets are read from
files or systemd credentials and never from a variable's value. files or systemd credentials and never from a variable's value.
| Variable | Meaning | | Variable | Meaning |
| ------------------------------ | -------------------------------------------------------------- | | -------------------------------- | --------------------------------------------------------------- |
| `VISA_LISTEN` | address to listen on, default `127.0.0.1:8040` | | `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_PUBLIC_URL` | `https://visa.buildfor.life`, for the login's redirect |
| `VISA_DATABASE_URL` | `postgres://visa@host/visa` | | `VISA_DATABASE_URL` | `postgres://visa@host/visa` |
| `VISA_DATABASE_PASSWORD_FILE` | the role's password; else the credential `db-password` | | `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_ISSUER` | `https://id.cnx.network/oauth2/openid/visa-web` |
| `VISA_OIDC_CLIENT_ID` | default `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_CLIENT_SECRET_FILE` | the client secret; else the credential `oidc-client-secret` |
| `VISA_OIDC_GROUP` | default `visa` | | `VISA_OIDC_GROUP` | default `visa` |
| `VISA_INSECURE_NO_LOGIN` | `1` runs without a login, on loopback addresses only | | `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_S3_BUCKET` | the bucket the encrypted documents lie in (`visa-documents`) |
| `VISA_FILES_KEY_FILE` | the file key, 64 hex digits; else the credential `files-key` | | `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 With the login on, the app does not start without a place for the documents
the file key. Local development may go without them, and documents are then (the bucket, or a directory) and the file key. Local development may go
switched off. The key never changes: the files cannot be read without it. 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 serve` (the default) applies pending migrations before it listens,
`visa migrate` applies them alone, `visa seed-demo` adds the demo people and `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 documents, and `visa files-check` reads every document's file back, compares
it with its upload and lists files that belong to no document. 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 ## Where it runs
Since November 17, 2026 the app runs on cnx01 in the office, like proplan and 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 lampbench-web: the database `visa` on cnx01's PostgreSQL, the documents in the
bkk01 publishing https://visa.buildfor.life. Passport data stays on B4L's own 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 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` 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`. get in; members are set in the fleet's `identity/people.nix`.
+54 -23
View File
@@ -1,10 +1,11 @@
# visa.buildfor.life: plan # visa.buildfor.life: plan
> Phases 1 to 3 built on November 17, 2026, phase 4's app side and phase 5 > Phases 1 to 3 built on November 17, 2026, phases 4 and 5 on November 18,
> on November 18, 2026. The live app at https://visa.buildfor.life has phases > 2026, all live at https://visa.buildfor.life. On November 19, 2026 the
> 1 to 3 until cnx-network-clan PR #126 (task 4.6) is deployed and the fleet's > documents moved from a directory on cnx01 into a bucket of cnx01's Garage
> `visa` input is updated to the newest commit. **Resume here: phase 6, the > (task 4.8); the app side is built, and the fleet side (task 4.9) goes live
> Non-B extension pack.** > 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 visa.buildfor.life keeps the immigration records of the foreigners that B4L
looks after: their passports, addresses in Thailand, arrivals with the Thailand 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 | | 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 | | 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 | | 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 | | 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` (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 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. values. The table refuses updates and deletes. The Activity page lists it.
- **Documents.** Scans and photos lie in a files directory on the server, - **Documents.** Scans and photos lie in the bucket `visa-documents` of
one file per document, encrypted by the app with AES-256-GCM. Each file has cnx01's Garage, one object per document, encrypted by the app with
a key of its own, derived with HKDF-SHA256 from the app's file key and a AES-256-GCM before they leave it. Each file has a key of its own, derived
random salt in the file's header, and the document's id is authenticated with HKDF-SHA256 from the app's file key and a random salt in the file's
with it, so a file renamed to another document's id does not open. The header, and the document's id is authenticated with it, so a file renamed
file key is a systemd credential that is never in the database, so neither to another document's id does not open. The file key is a systemd
the files nor their backups can be read without it. The database holds what credential that is never in the database or in Garage, so neither the
is known about each file: its kind, the record it belongs to, the date on bucket nor its backups can be read without it. A small S3 client of the
it, a note, its name, type, size and SHA-256. 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) - **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, 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 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 | | `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 | | `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 | | `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 ## 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 | | 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 | | 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 | | 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 | | 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 | | | 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 | | | 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 (`audit_log.company_id`). `visa files-check` reads every file back and
lists damaged, missing and stray files. `visa seed-demo` adds demo lists damaged, missing and stray files. `visa seed-demo` adds demo
documents: PDFs marked as demos and PNGs of shapes. 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 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 borg backups, and the VM test uploading a scan through the login
and checked in cnx-network-clan PR #126 (branch `visa-files`, opened (cnx-network-clan PR #126, merged and deployed on November 18, 2026).
Nov 18, 2026); Alex merges and deploys it, together with the flake By November 19 four real documents had arrived on the live app, and
update #125 that cnx01 and control do not run yet. After the deploy: `visa-admin files-check` on cnx01 read all four back without a
`visa-admin files-check` on cnx01 and an upload on the live app. problem.
- [x] 4.7 A company's office, asked for on November 18, 2026: its GPS - [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 position on the company form, read from the numbers Google Maps
copies, a link to the place on Google Maps or OpenStreetMap, or 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. 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 The photos are documents of the kind "Photo of the office", so they
are encrypted and audited like every other file. 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 ### Phase 5: filled-in forms
+67
View File
@@ -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 <<EOF
metadata_dir = "/var/lib/garage/meta"
data_dir = "/var/lib/garage/data"
db_engine = "sqlite"
replication_factor = 1
rpc_bind_addr = "[::]:3901"
rpc_public_addr = "127.0.0.1:3901"
rpc_secret = "$rpc"
[s3_api]
s3_region = "garage"
api_bind_addr = "[::]:3900"
EOF
# Docker Desktop wants a Windows path from Git Bash
conf="$(cd .dev/garage && (pwd -W 2>/dev/null || pwd))/garage.toml"
docker run -d --name "$NAME" -p "127.0.0.1:$PORT:3900" \
-v "$conf:/etc/garage.toml" dxflrs/garage:v2.5.0 >/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 <<EOF
export VISA_TEST_S3_ENDPOINT=http://127.0.0.1:$PORT
export VISA_TEST_S3_BUCKET=$BUCKET
export VISA_TEST_S3_ACCESS_KEY_ID=$id
export VISA_TEST_S3_SECRET_FILE=.dev/s3-secret
EOF
echo "Garage on http://127.0.0.1:$PORT, bucket $BUCKET, key ${id:0:8}... (secret in .dev/s3-secret, $(wc -c <.dev/s3-secret) characters)"
echo "settings: . .dev/garage.env"
+16 -3
View File
@@ -1,8 +1,11 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# The development server on http://127.0.0.1:8040 without login, with the # The development server on http://127.0.0.1:8040 without login, with the
# invented demo people and their documents, against the database of # invented demo people and their documents, against the database of
# scripts/dev-db.sh. The documents lie in .dev/ (git ignores it) under a file # scripts/dev-db.sh. The documents lie in .dev/files (git ignores .dev/) under
# key made on the first run. # a file key made on the first run. With VISA_DEV_S3=1 they lie in the bucket
# of scripts/dev-garage.sh instead, as on the server; files that lay in
# .dev/files before move there with
# `./target/debug/visa files-migrate --from .dev/files` under the same settings.
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
export VISA_DATABASE_URL=${VISA_DATABASE_URL:-postgres://visa:visa-dev@127.0.0.1:55438/visa} export VISA_DATABASE_URL=${VISA_DATABASE_URL:-postgres://visa:visa-dev@127.0.0.1:55438/visa}
@@ -11,8 +14,18 @@ export VISA_LISTEN=${VISA_LISTEN:-127.0.0.1:8040}
mkdir -p .dev mkdir -p .dev
[ -s .dev/files.key ] || od -An -N32 -tx1 /dev/urandom | tr -d ' \n' > .dev/files.key [ -s .dev/files.key ] || od -An -N32 -tx1 /dev/urandom | tr -d ' \n' > .dev/files.key
# relative paths: a Windows build reads them the same # 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} 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 cargo build -q
./target/debug/visa seed-demo ./target/debug/visa seed-demo
exec ./target/debug/visa serve exec ./target/debug/visa serve
+145 -15
View File
@@ -12,11 +12,17 @@
//! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` | //! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` |
//! | `VISA_OIDC_GROUP` | default `visa` | //! | `VISA_OIDC_GROUP` | default `visa` |
//! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only | //! | `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`) | //! | `VISA_FILES_KEY_FILE` | the file key (else credential `files-key`) |
//! //!
//! With the login on, documents are required: the files directory and the //! With the login on, documents are required: a place for them (the bucket,
//! file key. Local development may go without them; uploads are then off. //! or a directory) and the file key. Local development may go without them;
//! uploads are then off.
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::PathBuf; use std::path::PathBuf;
@@ -24,6 +30,7 @@ use std::path::PathBuf;
use anyhow::{Context, Result, bail, ensure}; use anyhow::{Context, Result, bail, ensure};
use crate::files::FileKey; use crate::files::FileKey;
use crate::s3::S3Config;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Config { pub struct Config {
@@ -33,16 +40,33 @@ pub struct Config {
pub database_url: String, pub database_url: String,
pub database_password: Option<String>, pub database_password: Option<String>,
pub auth: Auth, 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<FilesConfig>, pub files: Option<FilesConfig>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct FilesConfig { pub struct FilesConfig {
pub dir: PathBuf, pub place: FilesPlace,
pub key: FileKey, 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)] #[derive(Clone, Debug)]
pub enum Auth { pub enum Auth {
Oidc(OidcConfig), Oidc(OidcConfig),
@@ -127,22 +151,39 @@ impl Config {
Some(path) => Some(read_file(&PathBuf::from(path), "the file key")?), Some(path) => Some(read_file(&PathBuf::from(path), "the file key")?),
None => credential(var, "files-key")?, None => credential(var, "files-key")?,
}; };
let files = match (var("VISA_FILES_DIR"), key) { let place = match (var("VISA_S3_BUCKET"), var("VISA_FILES_DIR")) {
(Some(dir), Some(key)) => Some(FilesConfig { (Some(_), Some(_)) => bail!(
dir: PathBuf::from(dir), "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")?, key: FileKey::from_hex(&key).context("reading the file key")?,
}), }),
(None, None) => None, (None, None) => None,
(Some(_), None) => bail!( (Some(_), None) => bail!(
"VISA_FILES_DIR is set but there is no file key: set VISA_FILES_KEY_FILE or pass \ "the documents have a place but there is no file key: set VISA_FILES_KEY_FILE or \
the credential files-key" 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() { if matches!(auth, Auth::Oidc(_)) && files.is_none() {
bail!( bail!(
"documents are not set up: with the login on, set VISA_FILES_DIR and the file \ "documents are not set up: with the login on, set VISA_S3_BUCKET with the S3 \
key (VISA_FILES_KEY_FILE or the credential files-key)" settings (or VISA_FILES_DIR) and the file key (VISA_FILES_KEY_FILE or the \
credential files-key)"
); );
} }
Ok(Config { 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<String>, bucket: String) -> Result<S3Config> {
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. /// A systemd credential (`LoadCredential=`), when the unit passes one.
fn credential(var: &dyn Fn(&str) -> Option<String>, name: &str) -> Result<Option<String>> { fn credential(var: &dyn Fn(&str) -> Option<String>, name: &str) -> Result<Option<String>> {
let Some(dir) = var("CREDENTIALS_DIRECTORY") else { let Some(dir) = var("CREDENTIALS_DIRECTORY") else {
@@ -276,7 +341,7 @@ mod tests {
.unwrap_err(); .unwrap_err();
assert!(e.to_string().contains("documents are not set up"), "{e}"); assert!(e.to_string().contains("documents are not set up"), "{e}");
let files = c.files.unwrap(); 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")); assert!(!format!("{files:?}").contains("abab"));
std::fs::remove_dir_all(&dir).ok(); std::fs::remove_dir_all(&dir).ok();
} }
@@ -315,7 +380,72 @@ mod tests {
.unwrap(); .unwrap();
assert!(c.files.is_some()); assert!(c.files.is_some());
let e = with(&[("CREDENTIALS_DIRECTORY", dir.to_str().unwrap())]).unwrap_err(); 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(); std::fs::remove_dir_all(&dir).ok();
} }
} }
+121 -15
View File
@@ -1,16 +1,19 @@
//! Documents: scans and photos of a person's papers, and the company //! 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 //! 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 //! 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. //! 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 chrono::{DateTime, NaiveDate, Utc};
use sqlx::{PgPool, Postgres, Transaction}; use sqlx::{PgPool, Postgres, Transaction};
use crate::files::{self, Store}; use crate::files::{self, Store};
use crate::s3::Put;
/// Whose document it is. /// Whose document it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[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 /// size and checksum recorded at the upload; lists files that belong to no
/// document. /// document.
pub async fn check(db: &PgPool, store: &Store) -> Result<Check> { pub async fn check(db: &PgPool, store: &Store) -> Result<Check> {
let rows: Vec<(i64, i32, String)> = let rows = uploads(db).await?;
sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id") let entries = store.entries().await?;
.fetch_all(db)
.await?;
let (ids, other) = store.entries()?;
let mut out = Check { let mut out = Check {
documents: rows.len(), documents: rows.len(),
..Check::default() ..Check::default()
}; };
let known: BTreeSet<i64> = rows.iter().map(|r| r.0).collect(); for (id, (size, sha)) in &rows {
for (id, size, sha) in &rows { match store.get(*id).await {
match store.get(*id) {
Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {} Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {}
Ok(_) => out.problems.push(format!( Ok(_) => out.problems.push(format!(
"document {id}: the file does not match the size and checksum of its upload" "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<Check> {
Err(e) => out.problems.push(format!("document {id}: {e:#}")), Err(e) => out.problems.push(format!("document {id}: {e:#}")),
} }
} }
for id in ids.iter().filter(|id| !known.contains(id)) { for (id, _) in entries
out.problems .files
.push(format!("{id}.vdoc: a file without its document")); .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 out.problems
.push(format!("{name}: not a file of the store")); .push(format!("{name}: not a file of the store"));
} }
Ok(out) Ok(out)
} }
/// Every document's size and SHA-256 as recorded at its upload.
async fn uploads(db: &PgPool) -> Result<BTreeMap<i64, (i32, String)>> {
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<String>,
/// Documents whose file is neither in the directory nor in the store.
pub missing: Vec<i64>,
}
/// 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<Moved> {
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<i64> = 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+440 -89
View File
@@ -1,25 +1,34 @@
//! The document store. Each uploaded file lies in the files directory as //! The document store. Each uploaded file is encrypted with AES-256-GCM
//! `<id>.vdoc`, encrypted with AES-256-GCM under a key of its own: HKDF-SHA256 //! before it is stored, under a key of its own: HKDF-SHA256 derives it from
//! derives it from the app's file key and a random salt kept in the file's //! the app's file key and a random salt kept in the file's header. The
//! header. The document's id is authenticated with the file, so a file //! document's id is authenticated with the file, so a file renamed to
//! renamed to another id does not open. The file key is a systemd //! another id does not open. The file key is a systemd credential and is
//! credential and is never in the database or its dumps: without it the //! never in the database or its dumps: without it the files and their
//! files and their backups cannot be read. //! backups cannot be read.
//!
//! The encrypted files lie in a bucket of an S3 store (on the server, the
//! fleet's Garage) as `documents/<id>.vdoc`, or in a directory as `<id>.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 //! 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 //! 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. //! file, so a wrong key is reported as such and not as damage.
use std::collections::BTreeMap;
use std::fmt; use std::fmt;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::{self, Write}; use std::io::{self, Write};
use std::path::{Path, PathBuf}; 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::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey};
use ring::rand::{SecureRandom, SystemRandom}; use ring::rand::{SecureRandom, SystemRandom};
use ring::{digest, hkdf}; use ring::{digest, hkdf};
use crate::config::{FilesConfig, FilesPlace};
use crate::s3::{Bucket, Put, S3Config};
const MAGIC: &[u8; 8] = b"VISADOC1"; const MAGIC: &[u8; 8] = b"VISADOC1";
const KEY_ID: usize = 8; const KEY_ID: usize = 8;
const SALT: usize = 32; const SALT: usize = 32;
@@ -211,103 +220,364 @@ pub fn is_image(content_type: &str) -> bool {
content_type.starts_with("image/") 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<i64> {
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 `<id>.vdoc` files: local development and the tests.
Dir(PathBuf),
/// A bucket of an S3 store, objects `documents/<id>.vdoc`: the server.
Bucket(Bucket),
}
/// The document store with its key; cheap to clone.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Store { pub struct Store {
dir: PathBuf, place: Place,
key: FileKey, key: FileKey,
} }
impl Store { /// What a store holds: the documents' files with their sizes in bytes, and
/// The files directory, created (only its owner may enter) when missing. /// the names of anything else (a part file left by a crash, say).
pub fn open(dir: PathBuf, key: FileKey) -> Result<Store> { #[derive(Debug, Default, PartialEq, Eq)]
fs::create_dir_all(&dir) pub struct Entries {
.with_context(|| format!("creating the files directory {}", dir.display()))?; pub files: Vec<(i64, u64)>,
#[cfg(unix)] pub other: Vec<String>,
{ }
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)) /// File work off the async threads.
.with_context(|| format!("closing the files directory {}", dir.display()))?; async fn blocking<T: Send + 'static>(f: impl FnOnce() -> Result<T> + Send + 'static) -> Result<T> {
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 `<id>.vdoc` files of a directory with their sizes, and the names of
/// everything else in it.
fn list_dir(dir: &Path) -> Result<Entries> {
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<Store> {
private_dir(&dir)?;
Ok(Store {
place: Place::Dir(dir),
key,
})
} }
pub fn dir(&self) -> &Path { /// A bucket; nothing is asked of the server until the first file.
&self.dir pub fn in_bucket(cfg: &S3Config, key: FileKey) -> Result<Store> {
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<Store> {
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 { pub fn key_id(&self) -> String {
self.key.id_hex() self.key.id_hex()
} }
pub fn path(&self, id: i64) -> PathBuf { pub fn file_key(&self) -> &FileKey {
self.dir.join(format!("{id}.vdoc")) &self.key
} }
/// Encrypts and writes the file of document `id`: to a part file first, fn object(id: i64) -> String {
/// on disk before it takes its name. An existing file is never replaced. format!("{PREFIX}{}", file_name(id))
pub fn put(&self, id: i64, plain: &[u8]) -> Result<()> { }
let path = self.path(id);
ensure!( /// Where document `id`'s file is, for messages.
!path.exists(), pub fn location(&self, id: i64) -> String {
"{} is there already without its document (after a restore?); `visa files-check` \ match &self.place {
lists such files", Place::Dir(dir) => dir.join(file_name(id)).display().to_string(),
path.display() Place::Bucket(b) => format!("{} in bucket {}", Store::object(id), b.name()),
); }
let sealed = seal(&self.key, id, plain); }
let part = self.dir.join(format!(".{id}.vdoc.part"));
let write = || -> io::Result<()> { /// Encrypts and stores the file of document `id`. An existing file is
let mut f = File::create(&part)?; /// never replaced.
f.write_all(&sealed)?; pub async fn put(&self, id: i64, plain: Vec<u8>) -> Result<()> {
f.sync_all()?; let key = self.key.clone();
fs::rename(&part, &path)?; let sealed = blocking(move || Ok(seal(&key, id, &plain))).await?;
sync_dir(&self.dir) self.put_sealed(id, sealed).await.map(|_| ())
}; }
write()
.inspect_err(|_| { /// Stores an encrypted file as it is (a copy from another place). An
fs::remove_file(&part).ok(); /// existing file is never replaced: one with the same bytes counts as
}) /// stored ([`Put::Same`]), one with other bytes is an error.
.with_context(|| format!("writing {}", path.display())) pub async fn put_sealed(&self, id: i64, sealed: Vec<u8>) -> Result<Put> {
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<Option<Vec<u8>>> {
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`. /// The decrypted file of document `id`.
pub fn get(&self, id: i64) -> Result<Vec<u8>> { pub async fn get(&self, id: i64) -> Result<Vec<u8>> {
let path = self.path(id); let at = self.location(id);
let sealed = fs::read(&path).with_context(|| format!("reading {}", path.display()))?; let sealed = self
open(&self.key, id, &sealed).with_context(|| format!("opening {}", path.display())) .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. /// Removes the file of document `id`; a file that is gone already is fine.
pub fn remove(&self, id: i64) -> Result<()> { pub async fn remove(&self, id: i64) -> Result<()> {
let path = self.path(id); match &self.place {
match fs::remove_file(&path) { Place::Dir(dir) => {
Ok(()) => sync_dir(&self.dir).with_context(|| format!("removing {}", path.display())), let dir = dir.clone();
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), blocking(move || {
Err(e) => Err(e).with_context(|| format!("removing {}", path.display())), 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 /// What the store holds. In a bucket, every object outside
/// anything else (a part file left by a crash, say). /// `documents/<id>.vdoc` counts as something else.
pub fn entries(&self) -> Result<(Vec<i64>, Vec<String>)> { pub async fn entries(&self) -> Result<Entries> {
let mut ids = Vec::new(); match &self.place {
let mut other = Vec::new(); Place::Dir(dir) => {
for entry in let dir = dir.clone();
fs::read_dir(&self.dir).with_context(|| format!("listing {}", self.dir.display()))? blocking(move || list_dir(&dir)).await
{ }
let name = entry?.file_name().to_string_lossy().into_owned(); Place::Bucket(b) => {
match name let mut out = Entries::default();
.strip_suffix(".vdoc") for o in b.list("").await? {
.and_then(|n| n.parse::<i64>().ok()) match o.key.strip_prefix(PREFIX).and_then(id_of) {
{ Some(id) => out.files.push((id, o.size)),
Some(id) if id > 0 => ids.push(id), None => out.other.push(o.key),
_ => other.push(name), }
}
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 <dir>`.
pub async fn mirror(from: &Store, dir: &Path) -> Result<Mirrored> {
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<i64, u64> = 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<i64, u64> = want.into_iter().collect();
let stale: Vec<String> = 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<String> = 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. /// A rename is on disk only once its directory is.
@@ -387,24 +657,105 @@ mod tests {
} }
#[test] #[test]
fn the_store_writes_reads_and_removes() { fn only_a_documents_own_name_is_its_file() {
let dir = std::env::temp_dir().join(format!("visa-store-{}", std::process::id())); 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(); fs::remove_dir_all(&dir).ok();
let store = Store::open(dir.clone(), FileKey::random()).unwrap(); dir
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(); #[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")); 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}"); 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(); fs::write(dir.join(".9.vdoc.part"), b"left over").unwrap();
assert_eq!( assert_eq!(
store.entries().unwrap(), store.entries().await.unwrap(),
(vec![3], vec![".9.vdoc.part".to_string()]) Entries {
files: vec![(3, on_disk.len() as u64)],
other: vec![".9.vdoc.part".to_string()]
}
); );
store.remove(3).unwrap(); store.remove(3).await.unwrap();
store.remove(3).unwrap(); store.remove(3).await.unwrap();
assert!(store.get(3).is_err()); assert!(store.get(3).await.is_err());
assert!(store.get_sealed(3).await.unwrap().is_none());
fs::remove_dir_all(&dir).ok(); 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<String> = 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();
}
} }
+1
View File
@@ -18,6 +18,7 @@ pub mod oidc;
pub mod papers; pub mod papers;
pub mod people; pub mod people;
pub mod records; pub mod records;
pub mod s3;
pub mod seed; pub mod seed;
pub mod session; pub mod session;
pub mod web; pub mod web;
+91 -19
View File
@@ -1,13 +1,14 @@
//! `visa [serve|migrate|seed-demo|files-check|help]`: the server and its admin //! `visa [serve|migrate|seed-demo|files-check|files-migrate|files-mirror|help]`:
//! commands. //! the server and its admin commands.
use std::path::PathBuf;
use std::process::ExitCode; use std::process::ExitCode;
use anyhow::{Context, Result, bail, ensure}; use anyhow::{Context, Result, bail, ensure};
use tracing::info; use tracing::{info, warn};
use visa::config::Config; use visa::config::Config;
use visa::files::Store; use visa::files::{self, Store};
use visa::{dates, db, documents, seed, web}; use visa::{dates, db, documents, seed, web};
const USAGE: &str = "\ const USAGE: &str = "\
@@ -21,6 +22,13 @@ Commands:
seed-demo add invented demo people and documents (local development only) 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; 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) 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 help show this text
Settings come from the environment; see src/config.rs or README.md."; 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<PathBuf> {
let args: Vec<String> = 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<Store> {
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<()> { async fn run(cmd: &str) -> Result<()> {
match cmd { match cmd {
"serve" => serve().await, "serve" => serve().await,
@@ -66,22 +92,18 @@ async fn run(cmd: &str) -> Result<()> {
println!("demo people are there already"); println!("demo people are there already");
} }
match &cfg.files { match &cfg.files {
Some(f) => { Some(_) => {
let store = Store::open(f.dir.clone(), f.key.clone())?; let store = store(&cfg)?;
let n = seed::demo_documents(&pool, &store, dates::today()).await?; let n = seed::demo_documents(&pool, &store, dates::today()).await?;
println!("demo documents added: {n}"); 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(()) Ok(())
} }
"files-check" => { "files-check" => {
let cfg = Config::from_env()?; let cfg = Config::from_env()?;
let f = cfg let store = store(&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 pool = db::connect(&cfg).await?; let pool = db::connect(&cfg).await?;
let check = documents::check(&pool, &store).await?; let check = documents::check(&pool, &store).await?;
for p in &check.problems { for p in &check.problems {
@@ -90,13 +112,55 @@ async fn run(cmd: &str) -> Result<()> {
println!( println!(
"{} documents checked in {} (file key {}): {} problems", "{} documents checked in {} (file key {}): {} problems",
check.documents, check.documents,
store.dir().display(), store.describe(),
store.key_id(), store.key_id(),
check.problems.len() check.problems.len()
); );
ensure!(check.problems.is_empty(), "the files need attention"); ensure!(check.problems.is_empty(), "the files need attention");
Ok(()) 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" => { "help" | "--help" | "-h" => {
println!("{USAGE}"); println!("{USAGE}");
Ok(()) Ok(())
@@ -113,12 +177,20 @@ async fn serve() -> Result<()> {
let login = cfg.login_enabled(); let login = cfg.login_enabled();
let st = web::AppState::new(cfg, pool)?; let st = web::AppState::new(cfg, pool)?;
match &st.files { match &st.files {
Some(s) => info!( Some(s) => {
"documents in {} (file key {})", info!("documents in {} (file key {})", s.describe(), s.key_id());
s.dir().display(), // A store that is not there yet (Garage starting) costs the
s.key_id() // documents, not the records: the check only warns, and the
), // server listens meanwhile.
None => info!("documents are off: no VISA_FILES_DIR (local development)"), 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()); web::spawn_background(st.clone());
let app = web::router(st); let app = web::router(st);
+712
View File
@@ -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<u8>,
}
/// 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<Bucket> {
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<Answer> {
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::<Vec<_>>()
.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<Put> {
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<bool> {
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<Put> {
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<Option<Vec<u8>>> {
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<Option<u64>> {
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<Vec<Object>> {
let mut out = Vec::new();
let mut token: Option<String> = 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<Object>,
pub truncated: bool,
pub next: Option<String>,
}
/// Reads a ListObjectsV2 answer.
pub fn parse_list(xml: &str) -> Result<Page> {
ensure!(
xml.contains("<ListBucketResult"),
"S3 LIST: the answer is not a listing"
);
let mut page = Page {
truncated: tag(xml, "IsTruncated").as_deref() == Some("true"),
next: tag(xml, "NextContinuationToken").filter(|t| !t.is_empty()),
..Page::default()
};
for part in xml.split("<Contents>").skip(1) {
let part = part.split("</Contents>").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 `<name>` element, unescaped.
fn tag(xml: &str, name: &str) -> Option<String> {
let open = format!("<{name}>");
let close = format!("</{name}>");
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("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&apos;", "'")
.replace("&#39;", "'")
.replace("&amp;", "&")
}
pub fn amz_date(t: DateTime<Utc>) -> 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<u8> {
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::<Vec<_>>().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::<Vec<_>>()
.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 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
<Name>visa-documents</Name><Prefix>documents/</Prefix><KeyCount>2</KeyCount>\
<MaxKeys>2</MaxKeys><IsTruncated>true</IsTruncated>\
<Contents><Key>documents/1.vdoc</Key><LastModified>2026-11-19T10:00:00.000Z</LastModified>\
<ETag>&quot;9b2cf535f27731c974343645a3985328&quot;</ETag><Size>1234</Size>\
<StorageClass>STANDARD</StorageClass></Contents>\
<Contents><Key>documents/a&amp;b.vdoc</Key><Size>0</Size></Contents>\
<NextContinuationToken>tok+/=</NextContinuationToken></ListBucketResult>";
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(
"<ListBucketResult><IsTruncated>false</IsTruncated><KeyCount>0</KeyCount></ListBucketResult>",
)
.unwrap();
assert_eq!(last, Page::default());
assert!(parse_list("<Error><Code>AccessDenied</Code></Error>").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}");
}
}
+1 -1
View File
@@ -818,7 +818,7 @@ pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Res
sha256: &sha256, sha256: &sha256,
}; };
let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?; let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?;
store.put(id, bytes)?; store.put(id, bytes.clone()).await?;
written.push(id); written.push(id);
audit::record( audit::record(
&mut *tx, &mut *tx,
+4 -6
View File
@@ -663,9 +663,7 @@ async fn save(
sha256: &f.sha256, sha256: &f.sha256,
}; };
let id = documents::insert(&mut tx, owner, meta, &file, &user.login).await?; let id = documents::insert(&mut tx, owner, meta, &file, &user.login).await?;
let s = store.clone(); store.put(id, f.bytes).await?;
let bytes = f.bytes;
tokio::task::spawn_blocking(move || s.put(id, &bytes)).await??;
written.push(id); written.push(id);
audit::record( audit::record(
&mut *tx, &mut *tx,
@@ -690,7 +688,7 @@ async fn save(
}; };
if let Err(e) = result { if let Err(e) = result {
for id in &written { 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:#}"); error!("removing the file of the failed upload {id}: {r:#}");
} }
} }
@@ -822,7 +820,7 @@ pub async fn file(st: Arc<AppState>, user: User, owner: Owner, id: i64, q: FileQ
let Some(store) = st.files.clone() else { let Some(store) = st.files.clone() else {
return Ok(files_off(&st)); 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(b) if files::sha256_hex(&b) == d.sha256 => b,
Ok(_) => { Ok(_) => {
error!("document {id}: the file does not match the checksum of its upload"); error!("document {id}: the file does not match the checksum of its upload");
@@ -1029,7 +1027,7 @@ pub async fn delete(st: Arc<AppState>, user: User, owner: Owner, id: i64) -> Res
) )
.await?; .await?;
tx.commit().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:#}"); error!("document {id} is deleted, but not its file: {e:#}");
} }
Ok(Redirect::to(&list_page(owner)).into_response()) Ok(Redirect::to(&list_page(owner)).into_response())
+3 -6
View File
@@ -39,7 +39,8 @@ pub struct AppState {
provider: RwLock<Option<Arc<oidc::Provider>>>, provider: RwLock<Option<Arc<oidc::Provider>>>,
/// The form token of local development, which has no sessions. /// The form token of local development, which has no sessions.
local_csrf: String, 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<Store>, pub files: Option<Store>,
} }
@@ -50,11 +51,7 @@ impl AppState {
.connect_timeout(Duration::from_secs(5)) .connect_timeout(Duration::from_secs(5))
.user_agent(concat!("visa/", env!("CARGO_PKG_VERSION"))) .user_agent(concat!("visa/", env!("CARGO_PKG_VERSION")))
.build()?; .build()?;
let files = cfg let files = cfg.files.as_ref().map(Store::open).transpose()?;
.files
.as_ref()
.map(|f| Store::open(f.dir.clone(), f.key.clone()))
.transpose()?;
Ok(Arc::new(AppState { Ok(Arc::new(AppState {
templates: templates()?, templates: templates()?,
files, files,
+333
View File
@@ -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<i64> {
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));
}
+379
View File
@@ -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<BTreeMap<String, Vec<u8>>>,
requests: Mutex<Vec<String>>,
fail_next: Mutex<usize>,
}
pub struct FakeS3 {
pub endpoint: String,
shared: Arc<Shared>,
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<Vec<u8>> {
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<String> {
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<String> {
self.shared.requests.lock().unwrap().clone()
}
}
fn answer(status: StatusCode, body: Vec<u8>) -> Response {
Response::builder()
.status(status)
.body(Body::from(body))
.unwrap()
}
fn error(status: StatusCode, code: &str) -> Response {
let xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>{code}</Code>\
<Message>{code}</Message></Error>"
);
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('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
fn hex(s: &str) -> String {
s.bytes().map(|b| format!("{b:02x}")).collect()
}
fn unhex(s: &str) -> Option<String> {
let bytes: Option<Vec<u8>> = (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::<Vec<_>>()
.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<Arc<Shared>>, 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<String, String> = 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<u8>)> = objects
.iter()
.filter(|(k, _)| k.starts_with(&prefix) && **k >= start)
.collect();
let page = &keys[..keys.len().min(max)];
let mut xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
<Name>{BUCKET}</Name><Prefix>{}</Prefix><KeyCount>{}</KeyCount>\
<MaxKeys>{max}</MaxKeys><IsTruncated>{}</IsTruncated>",
xml_escape(&prefix),
page.len(),
keys.len() > page.len()
);
for (k, v) in page {
xml.push_str(&format!(
"<Contents><Key>{}</Key><Size>{}</Size><StorageClass>STANDARD</StorageClass></Contents>",
xml_escape(k),
v.len()
));
}
if keys.len() > page.len() {
xml.push_str(&format!(
"<NextContinuationToken>tok+/={}</NextContinuationToken>",
hex(keys[page.len()].0)
));
}
xml.push_str("</ListBucketResult>");
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"),
}
}
+21 -4
View File
@@ -1,5 +1,7 @@
#![allow(dead_code)] #![allow(dead_code)]
pub mod fake_s3;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
@@ -11,12 +13,12 @@ use chrono::NaiveDate;
use http_body_util::BodyExt; use http_body_util::BodyExt;
use sqlx::PgPool; use sqlx::PgPool;
use tower::ServiceExt; use tower::ServiceExt;
use visa::config::{Auth, Config, FilesConfig, OidcConfig}; use visa::config::{Auth, Config, FilesConfig, FilesPlace, OidcConfig};
use visa::files::FileKey; use visa::files::FileKey;
use visa::web::{self, AppState}; use visa::web::{self, AppState};
/// A files directory of its own for each app, under the target directory. /// 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); static N: AtomicUsize = AtomicUsize::new(0);
PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!( PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
"files-{}-{}", "files-{}-{}",
@@ -34,12 +36,23 @@ pub fn config(auth: Auth) -> Config {
database_password: None, database_password: None,
auth, auth,
files: Some(FilesConfig { files: Some(FilesConfig {
dir: files_dir(), place: FilesPlace::Dir(files_dir()),
key: FileKey::random(), 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 { pub fn oidc_config(issuer: &str) -> OidcConfig {
OidcConfig { OidcConfig {
issuer: issuer.into(), issuer: issuer.into(),
@@ -58,7 +71,11 @@ pub struct App {
// The test's files go with it. // The test's files go with it.
impl Drop for App { impl Drop for App {
fn drop(&mut self) { 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(); std::fs::remove_dir_all(dir).ok();
} }
} }
+14 -10
View File
@@ -10,7 +10,7 @@ use visa::web::documents::FILE_LIMIT;
use crate::common::{App, Part, config, id_from, local, pdf, with_config}; 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 let r = app
.post( .post(
"/people", "/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. /// A forged upload: its parts, its headers, the answer and what it says.
type Forged<'a> = (Vec<Part<'a>>, &'a [(&'a str, &'a str)], StatusCode, &'a str); type Forged<'a> = (Vec<Part<'a>>, &'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 store = app.st.files.as_ref().unwrap();
let (ids, other) = store.entries().unwrap(); let e = store.entries().await.unwrap();
ids.len() + other.len() e.files.len() + e.other.len()
} }
#[sqlx::test(migrator = "visa::db::MIGRATOR")] #[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 // on the disk only encrypted, under the document's id
let store = app.st.files.as_ref().unwrap(); 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.starts_with(b"VISADOC1"));
assert!(!on_disk.windows(10).any(|w| w == b"photo page")); 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"), &[]) .post(&format!("/people/{id}/documents/{did}/delete"), &[])
.await; .await;
assert_eq!(r.status, StatusCode::SEE_OTHER); 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!(count(&pool).await, 0);
assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND); 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!(t.contains("Nothing was uploaded"), "{want}");
} }
assert_eq!(count(&pool).await, 0); 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 // the same file again for the same person
let r = app let r = app
@@ -363,7 +363,7 @@ async fn an_upload_needs_the_form_token_first_and_this_site(pool: PgPool) {
.await; .await;
assert_eq!(r.status, StatusCode::NOT_FOUND); assert_eq!(r.status, StatusCode::NOT_FOUND);
assert_eq!(count(&pool).await, 0); assert_eq!(count(&pool).await, 0);
assert_eq!(stored(&app), 0); assert_eq!(stored(&app).await, 0);
} }
#[sqlx::test(migrator = "visa::db::MIGRATOR")] #[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 // 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"); let tmp = pa.with_extension("swap");
std::fs::rename(&pa, &tmp).unwrap(); std::fs::rename(&pa, &tmp).unwrap();
std::fs::rename(&pb, &pa).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_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR);
assert!(r.text().contains("cannot be opened"), "{}", r.body); assert!(r.text().contains("cannot be opened"), "{}", r.body);
assert!(!r.bytes.windows(6).any(|w| w == b"second")); 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(); let check = documents::check(&pool, store).await.unwrap();
assert_eq!(check.documents, 2); assert_eq!(check.documents, 2);
assert_eq!(check.problems.len(), 3, "{:?}", check.problems); assert_eq!(check.problems.len(), 3, "{:?}", check.problems);
+98
View File
@@ -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<S3Config> {
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<i64> {
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());
}
}
+2
View File
@@ -3,10 +3,12 @@
//! databases); each `#[sqlx::test]` gets its own database. //! databases); each `#[sqlx::test]` gets its own database.
mod auth; mod auth;
mod bucket;
mod common; mod common;
mod companies; mod companies;
mod deadlines; mod deadlines;
mod documents; mod documents;
mod garage;
mod pages; mod pages;
mod papers; mod papers;
mod people; mod people;