Compare commits

..

86 Commits

Author SHA1 Message Date
e44213599c style: rustfmt after merging the release branches
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:41:51 +07:00
1909803df7 merge: worktree-agent-a3b66cf8ba01274e5 2026-11-16 21:37:44 +07:00
f012e664a7 merge: worktree-agent-ae4267aa66ffa0b0a 2026-11-16 21:37:44 +07:00
facaa43753 merge: worktree-agent-ac03eb441ec9759b0
# Conflicts:
#	docs/auth-endpoint-contract.md
2026-11-16 21:37:44 +07:00
6ab788fcda test: cover legacy-import with a stand-in aws (inventory, import, resume, history)
The AWS program becomes a skipped clap field so tests can substitute a fake; run is split
into reconcile (returns the report) and a printing wrapper. No behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:30:24 +07:00
d98d8354db test: pairing negatives (auth, bad names, malformed bodies, replay, expiry, audit)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:28:19 +07:00
460f6f4db6 fix: reserve disk for admitted exports so concurrent downloads cannot share the same free space
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:26:32 +07:00
f4e42178e6 test: boundary and property tests for the retention and decay evaluators
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:24:40 +07:00
ed6296a9c5 fix: a failed heartbeat no longer abandons a restore once the apply permit is spent
Before the permit the lease is still given up on; after it the failure is logged and the
apply runs to its terminal report instead of being killed mid-flight.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:22:52 +07:00
d14b27669a fix: evict finished reconstitute sessions, keep the mTLS listener alive on accept errors, drop dead code
Also removes OperatorActor.browser, unused since reconstitute targets are confined for every caller.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:58 +07:00
6d2b882b3d fix: use a reserved example.invalid host in the postgres URL test fixture
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:58 +07:00
8a025b10e4 fix: require 16 characters for a new vault passphrase and warn when an existing one is weaker
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:19 +07:00
7d7ebdc172 fix: describe the OpenAPI route as sign-in only in the endpoint contract
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:19:19 +07:00
5b8aec0591 fix: require sign-in for the OpenAPI document unless TESSERA_PUBLIC_OPENAPI is set
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:15:31 +07:00
63a70b9eb8 build: verified image runs non-root on a read-only rootfs; drop --system uid warning; plain Rest Server restart instruction
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:13:58 +07:00
06cfb91434 fix: log request paths only, never query strings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:13:29 +07:00
3fa9a765ce fix: add security headers, correct MIME types and long-cache hashed assets
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:12:48 +07:00
edc74d79c0 fix: confine every reconstitute target to the exports directory and never overwrite an existing file
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:11:34 +07:00
c18815eb5d fix: give each auth-contract request its own source so the token throttle cannot mask a 401
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:11:34 +07:00
9219319ff3 fix: refuse admin tokens under 32 characters and throttle wrong token attempts per source
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:07:37 +07:00
0c141b7038 build: digest-pinned, non-root image with healthcheck; hardened compose with full env passthrough
NOT yet built or run: the Docker daemon's storage was failing at commit time.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:05:31 +07:00
4804ac1f61 docs: Docker deployment notes, admin token length, session lifetime, reverse proxy example
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:05:27 +07:00
a16ff48000 ci: pin actions to commit SHAs, restrict token permissions, add tag-driven release workflow
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:05:01 +07:00
2931032ab7 fix: throttle denied-authentication audit rows per source, never turn a denial into a 500, prune old audit events
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 21:04:46 +07:00
30ec762324 test: cover the agent restore sequence with fakes
Safety failure never applies, identity and source guards, rollback
exception, per-step timeouts, lost apply permit, crash after permit,
poll lease checks, and the heartbeat-failure behaviour.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:58:32 +07:00
5f7a702a34 fix: avoid self-matching and version-pin false positives in the export checks
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:55:56 +07:00
70ebaed8a2 fix: make the public export fail closed and add e-mail, host and tooling checks
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:55:15 +07:00
b2d5e4d71a test: add trait seams to the agent restore flow (no behaviour change)
RestoreTarget, RestoreHub and BackupSource let the destructive restore
sequence be driven by fakes. poll takes the heartbeat interval as a
parameter instead of reading the constant.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:55:13 +07:00
7953876689 docs: drop the published passphrase from the spec and bring the auth section up to date
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:44 +07:00
a46020c123 fix: allow pinch zoom by dropping the viewport zoom lock
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
a423f6c064 docs: restructure the changelog as Keep a Changelog for 0.1.0
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
24cc721e41 docs: point vulnerability reports at GitHub private reporting and add a support window
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
57738ce714 chore: use a neutral crate author
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:43 +07:00
8c5256ca26 chore: remove tooling leftovers and the dev prototype page from the tree
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:54:37 +07:00
d99da607b3 chore: use a neutral application name and time zone in the download-name tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:53:17 +07:00
a4fc35a5ea docs: translate the authorization contract to English and drop internal milestone codes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:53:17 +07:00
170b4130d9 chore: rustfmt the refresh modules
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:48:44 +07:00
d356c313ce feat: restore history, undo and redo in the Activity log for everyone who may refresh
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
- Activity lists restores from refresh runs, so the Refresh permission is enough to see them; an administrator's
  restore jobs add the database, the person and the snapshot
- an undo is listed under the restore it reverses, and a redo under that undo; opening a restore or an undo opens
  its undo or redo dialog
- the dialog has an explicit undo mode: it describes what is put back instead of the snapshot that was open, and
  an interrupted restore offers Roll back
- a restore whose safety backup retention has forgotten shows "Safety backup expired" instead of a link, and the
  dialog says how long a safety copy is kept

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:37:21 +07:00
62f0c68e89 feat: roll back a failed restore and say when a safety copy is gone
- a restore whose apply failed can be undone from its safety copy, which is its recovery: the failed apply stops
  fencing the target in the transaction that starts the undo (job phase rolled_back, audited restore.rolled_back);
  an apply whose agent went silent still waits for an administrator to reconcile it; reconciled restores can be undone
- run views carry undo_state (available, superseded, expired), undo_kept_until, undo_of and restore_job_id
- undo state for a list is worked out in one database pass and a file lookup per copy; the vault is read only for the
  newest restore of each target
- eligibility is checked again inside the transaction that creates the run

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 20:37:21 +07:00
648c8c6a2a feat: undo a restore from the safety copy it took
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
- POST /refresh-runs accepts undo_of: restores the safety copy of a completed restore back onto the same
  target through the normal run engine (checks, countdown, progress, and a new safety copy so the undo can be
  undone); refused when something was restored after it or the copy is gone
- a safety copy is accepted as a source only for the target it was taken from (hub and agent both check)
- run views carry undo and undo_available; audited as refresh.undo_started
- the modal offers Undo last restore and, after a restore, Undo this restore
- proven with a real agent and PostgreSQL: restore, undo back to the original contents, undo of the undo

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 16:47:02 +07:00
854e3572e9 chore: take deployment-specific material out of the repository for the first release
- MBU parity map, cutover runbook and the tasks/ planning notes move outside the repo
- tests/mbu becomes tests/fixtures with generic application names and no placement inventory
- test fixtures in Rust and web use neutral names
- scripts/export-public.sh checks an external list of private terms instead of naming them

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 21:50:27 +07:00
c938afe1b5 feat: access console with a permission tree, grouped grants and effective access
Some checks failed
ci / rust (push) Has been cancelled
ci / supply-chain (push) Has been cancelled
ci / web (push) Has been cancelled
Backend: grants accept a list of permissions; PUT /access/grants edits or renews a set atomically; refusals carry a reason; the grant list includes refresh grants per relation and the administrator-only permissions; users keep their last groups and admin flag; the emergency operator cannot hold grants.

Frontend: the Access screen shows the grantable permissions as a checkbox tree with dependencies, rows grouped by person or group, orbit and end date, expiry and no-effect states, and what each person can do right now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 20:20:25 +07:00
3bd0a1c9a3 feat: restore inside the Vault; the Refresh page and file export UI are gone
- POST /refresh-runs accepts snapshot_id: restore a snapshot somebody picked (a restorable capture of the
  relation's own source, never a safety copy or another orbit's) through the same run engine
- refresh-relations carries source_orbit_id; snapshots carry kind (capture|safety), and the UI hides safety copies
- snapshot detail: Restore replaces Export file on hub (disabled with No restore point without a relation);
  modal with a restore point selector, a ten second countdown with Abort, and a four step progress view
- administrators keep Other registered target; the Refresh menu and refresh-only screen are removed
- proven with a real agent and PostgreSQL in the browser: capture, restore to Development, abort, no relation

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 16:13:44 +07:00
f52fc1930f feat: rename orbits; snapshots and downloads show the orbit's current name
PUT /api/v1/orbits/:id changes only the name (admin, validated, case-insensitively unique, audited).
Snapshot metadata is immutable, so the list and the download file name look the orbit up by id and
fall back to the written name only when the orbit is gone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 15:01:49 +07:00
c6dd52c700 feat: rename restore targets and show the application next to them
- PUT /api/v1/restore-targets/:id changes only the display name (admin, validated, audited); ids,
  identity, relations and jobs are untouched
- Relations console: Application column, inline rename, application in the target pickers
- Refresh screen: the application on each card
- registering a target suggests '<application> · <database>'

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:57:46 +07:00
76999f06b8 feat: version-specific pg_restore failure reasons, keep pg_stat_statements, explain reconcile conflicts
- pg_restore's stderr is kept; the archive header names the pg_dump that wrote it, and a newer one than
  the local client gives 'install a PostgreSQL client >= N' before any safety backup is taken
- omit_pg_stat_statements recreates the extension the target had, where it lived
- reconcile on a job that needs no recovery answers 409 with a reason
- proven against a real PostgreSQL server (real archive header, extension kept, mutation caught)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:46:37 +07:00
b104aa8053 fix: restore safety copies no longer compete with production captures in retention
A safety copy of a restore target was stored in the application's orbit and weighed by the same
retention as captures, so the newest copy (the target's) could push the production capture that had
just been restored out of the keep set, whatever the rule (GFS, count or age). Safety copies are now
separated: they have their own per-target rule (newest three plus anything under seven days) and
never count for or against captures. Proven red on the old behaviour with a real refresh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:35:28 +07:00
43709aeeab feat: say why a restore failed, and add the user_schemas reset mode
- the agent reports the client's primary ERROR/FATAL line with a failed restore step; the hub keeps it
  as failure_reason (administrators only), logs it and audits restore.failed. psql runs with
  VERBOSITY=terse and DETAIL/CONTEXT/statement text is dropped so row data never travels
- reset mode user_schemas empties every non-system schema in the restore transaction, so multi-schema
  databases restore without DROP DATABASE; proven against a real PostgreSQL server

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:29:48 +07:00
fb277249f7 feat: readable download names and PUT /capture-profiles/:id
- downloads are named <orbit>_<time>_<engine>_<id8>.<ext> (schedule zone or UTC), orbit names are
  reduced to [a-z0-9_-], and the header carries filename and filename*
- operators can change a profile's schedule and retention (absent = keep, null = clear), validated
  like registration, audited, and a changed schedule never replays slots that already passed

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 12:19:32 +07:00
1bff2ab234 fix: off-site copies survive slow object stores and say why they fail
- limits sized for WAN S3 (probe/list 120s, init 90s, retries 3, stuck-request 60s)
- a finished copy (tagged snapshot present) is accepted instead of copied again;
  the verification listing is retried before the copy is called failed
- a missing off-site repository is no longer a listing error
- restic's stderr tail is kept and the hub logs the failure reason

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 03:48:27 +07:00
176c335630 docs: pair with --credentials so the token never reaches the terminal; writable credentials location
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 02:37:47 +07:00
0cfda108da docs: Rest Server htpasswd format, CLI binary name, image scope and cross-build caveat
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 23:16:17 +07:00
4b896532d9 docs: record the release hold and what remains before going public
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 19:25:43 +07:00
7a5b45427e ci: build the web bundle before the Rust jobs (the hub embeds it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 19:22:47 +07:00
37a319680c docs: move the auth endpoint contract to docs so the public tree builds without tasks/
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 19:21:21 +07:00
e421c13859 chore: tune the public export check 2026-11-14 19:20:08 +07:00
68c87fa914 docs: update README for the new auth model; add SECURITY, CHANGELOG, CI and a public export script
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 19:20:01 +07:00
f13f0e6953 chore: rustfmt the workspace and make clippy -D warnings pass
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 19:19:21 +07:00
d7fe99edd7 feat: refresh console for QA and refresh-only access (auth M6d)
- web: Refresh console (relation cards, overwrite confirmation, progress,
  cancel, distinct failure messages), rail item, and a single-screen view
  for people who may only refresh
- hub: refresh-only users are authorized; /me exposes refresh_relations
- docs and auth plan record the real rehearsal (Postgres, agent, Keycloak,
  browser) and what was not verified

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 19:03:47 +07:00
da46453c13 feat: durable refresh runs from a source to a staging target (auth M6c)
A refresh captures a new dump of the relation's source, then restores exactly that
snapshot onto the relation's target through the existing restore path.

- refresh_runs in SQLite, one active run per target, per-requester idempotency keys,
  a cap on concurrent runs and a TTL that only applies until the restore starts overwriting
- the run and its capture job are created in one transaction; the run follows its own
  capture job, never the latest snapshot, and pins that snapshot until it ends
- the restore is queued and linked in one guarded transaction; every step is safe to repeat
  after a crash; a background driver only reads the database
- authorize_apply re-checks, in the transaction that allows the overwrite, that the relation
  is still usable, the requester is still active, the authorising grant still exists, the
  deadline has not passed and the target is not the source; otherwise the restore is
  cancelled, the run is blocked and the agent gets 409. Administrator restores are untouched
- POST/GET/DELETE /api/v1/refresh-runs: confirmation names source, target and version;
  non-administrators never see the snapshot id, the requester or the database identity
- audit refresh.* per run

Tests drive the agent through the real Outpost endpoints and cover revocation at every
stage; the access matrix gains a RunRow kind.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:23:13 +07:00
5c4e0bf4a9 feat: environments and production-to-staging relations (auth M6b)
- environment (production/staging/development) on source orbits and on restore targets;
  an unlabelled target fails closed and a production target is refused
- directed, versioned relations from a managed source orbit to a restore target: one
  active relation per pair, retargeting makes a new id and ends the old one
- refusals name the rule: unknown or unlabelled source/target, not a managed capture
  profile, not restore-ready, application or engine mismatch, inactive Outpost, and a
  target whose identity matches a database captured as production in any snapshot
- relations end in the same transaction when their target is relabelled production or an
  Outpost is revoked; usability is re-read live
- refresh.run is granted per relation id in its own table (user or group, expiry), never
  global, never carried to a new version, and never accepted by the orbit gate
- admin API under /api/v1/relations plus environment endpoints; people holding only a
  relation grant see names and environments, never identity, host, Outpost or application
- Relations console; sign-in form without SSO no longer shows a stray "Details" label

Tests extend the access matrix with relation fixtures and a caller that holds only a
relation grant.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 17:46:08 +07:00
e72b72111d feat: download snapshots as real compressed archives (auth M6a)
- the download format follows the file's first bytes and manifest hints: plain SQL ->
  .sql.gz, tar -> .tar.gz, SQLite -> .sqlite.gz, hub filesystem archive -> .tessera-fs.gz,
  unknown -> .dump.gz; pg_dump -Fc stays .dump; gzip/zstd/xz/bzip2/zip pass through
- gzip is streamed (async-compression) in 64 KiB frames; no Content-Encoding, no
  Content-Length on compressed bodies, application/gzip, nosniff, no-store; HEAD is 405
- order: authenticate, find, permission, then admission (export slots and free disk), so a
  caller without permission cannot use up the slots
- the export directory, the slot and the audit end-of-download row live with the response
  body: finished, client disconnect, and a sweep of tessera-export-* at start after a crash
- audit export.requested / ready / finished / disconnected

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 17:27:06 +07:00
228ca42801 feat: turn the camera by dragging the map, and put big-screen labels on glass
Dragging the map walks the camera round the black hole (yaw) and raises or
lowers it (lift); clicking the hole springs back to the default view. The
shader takes an azimuth and an elevation, and the orbit overlay is projected
through the same view (orbitPose, trailAngle and project take a View), so rings,
stars, trails and rockets turn with the disk. A star behind the hole's shadow is
hidden by it. Labels and moons wait until the camera rests. A camera at rest
costs nothing, and the still quality tier still draws while it turns.

Big-screen map labels sit on dark glass chips so the radar grid cannot swallow
them, and the picked label and its status read as one chip.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 17:02:50 +07:00
5773f42d90 feat: make Big Screen a holographic visor
The map fills the viewport and every control is light: thin mint lines and
glowing text over a vignette, a faint scan, corner brackets and a glass edge.
Brand and mode sit top left, telemetry top right, the legend bottom left, the
systems as text tabs bottom centre, and view, motion, search and sign out as
outlined keys bottom right with the hub's state above them.

Each piece springs between the workspace and the big screen with
useScreenTransition. Every orbit is labelled on the big screen, and the picked
orbit's label stands off its star on an elbowed leader line with its status.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 16:47:23 +07:00
64d916db4e chore: add preview launch config and Serena project settings
Kept in their own commit so it is easy to drop if these should stay local.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 15:56:08 +07:00
88d3fa665b feat: let rockets plunge into the black hole core
Inside the shadow a rocket's velocity now turns toward the centre, so it falls to the
singularity instead of swinging round it, and the trail of a rocket that reaches the
core lingers and fades briefly.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 15:56:08 +07:00
45497c0993 docs: break auth M6 into four sub-milestones
M6a compressed download, M6b environments and relations, M6c durable refresh run,
M6d refresh UI and rehearsal with a real database.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 15:56:08 +07:00
d12472ba02 feat: per-orbit access grants and an Access console (auth M5)
Authorization
- one gate for every human endpoint: authenticate, resolve the resource, then
  admin_only / scoped / visible; require_admin* removed so each handler must choose
- grants (user or IdP group; global or one orbit; optional end date) read live on
  every request; only orbit.read, snapshot.read, capture.run and snapshot.download
  can be granted, everything else stays with configured administrators
- an orbit without orbit.read is 404, a visible one without the permission is 403,
  a caller with nothing to see gets 403 on lists; job history is filtered before LIMIT
- jobs and audit record the stable principal id, not the IdP display name
- restore targets and restore history are admin-only until self-service (M6)
- sessions keep the groups verified at sign-in

Administration
- /api/v1/access grants and users (enable, disable, sign out everywhere), validated
  and audited by id; admins cannot disable themselves or the emergency operator
- Access console with the shared Select and a themed DatePicker; non-administrators
  only see Vault and Activity and never call administrator endpoints
- the Window/Radar view is stored per account (/api/v1/me/preferences)
- UI tolerates older hubs and mocks (missing admin/grants) and a console that fails
  to render no longer blanks the app

Tests: a matrix generated from the endpoint contract exercises every human route
against real resources in two orbits for each kind of caller.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 14:45:41 +07:00
54abd02250 feat: store Outpost credentials as digests and rate limit public endpoints (auth M4)
Credentials
- pairing codes and Outpost upload tokens are stored only as SHA-256 digests; the
  token is minted at claim (256-bit OsRng) and returned once
- the old clear-text wormhole_tokens table is migrated in place and dropped with
  secure_delete; active tokens keep working with a fresh lifetime
- admin rotate (with grace window) and revoke endpoints, audited; a revoked
  Outpost is refused on its next request
- optional end date for the shared admin token (TESSERA_ADMIN_TOKEN_EXPIRES)

Limits
- governor per-source limits for emergency login, pairing claim and SSO
  start/callback; X-Forwarded-For only from TESSERA_TRUSTED_PROXIES; IPv6 by /64
- at most two concurrent Argon2 verifications, refused immediately when busy
- denials audited at most once a minute per source
- the mTLS listener now supplies the peer address to handlers

Existing hubs: rotate every Outpost token after upgrading; old database copies
still contain the clear-text tokens.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 14:06:18 +07:00
618681fa7f feat: persistent sessions and OIDC sign-in (auth M2 + M3)
Sessions and users (M2)
- users and sessions tables in SQLite; only a digest of the session ID is stored
- idle 30 min / absolute 8 h deadlines, UPDATE-only touch, per-user revoke by generation
- emergency operator is a users row (issuer local:emergency); its sessions are
  bound to the operator hash fingerprint, so unsetting or rotating it ends them
- CSRF derived from the session ID; GET /api/v1/me

OIDC login (M3)
- openidconnect 4.1: authorization code + PKCE S256, static redirect URI, no redirects
- one-time login transactions bound to the browser by a Lax correlation cookie
- identity is (issuer, subject); admin only from configured subjects/groups;
  a signed-in user without a grant gets 403 on management APIs
- OIDC sessions are bound to the OIDC configuration fingerprint
- SSO button, no-access page and fixed error codes in the web UI
- tests against a mock IdP with signed and malformed tokens; rehearsed against
  Keycloak 26.1 in a real browser
- rsa 0.9 advisory (RUSTSEC-2023-0071) excepted with a written reason: runtime
  code only verifies signatures with public keys

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 13:43:09 +07:00
a9ebded5ba feat: require authentication and own uploads per Outpost (auth M0)
- auth is mandatory by default, including loopback and local proxies; startup refuses a hub with no credentials; TESSERA_LOCAL_DEVELOPMENT is explicit and loopback-only
- legacy uploads are bound to an owning Outpost (PUT /api/v1/orbits/:id/outpost); unowned orbits and sessions fail closed
- typed Principal and payload-free audit_events table
- endpoint authorization contract with tests comparing it to the router
- A00 compatibility spike (tests/auth-compat) and library research
- archive the superseded A00-A25 plan

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 12:59:08 +07:00
f6a41ee702 chore: raise the dependency baseline for OIDC (auth M1)
Clears every RustSec vulnerability in the workspace so openidconnect can be added without inheriting known issues.

- rustls 0.23.23 -> 0.23.46 (webpki 0.103.17), tokio 1.40 -> 1.54
- rusqlite 0.31 -> 0.41.1 (SQLite binding 0.39.1); Rust 1.88 -> 1.89 as 0.41 requires
- drop unmaintained rustls-pemfile in favour of rustls::pki_types::pem
- add deny.toml (advisories, licenses, bans, sources); mark crates publish = false
- add tasks/auth-plan.md with per-milestone auth plan and M1 results

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 12:58:46 +07:00
c74694cf1f feat: restyle the web UI as a spaceship cockpit
The map is a canopy with a bezel, an inset window and a sill carrying a
Window | Radar view switch. Consoles open as centered screens; Orbits,
Outposts, Activity and the snapshot sheet follow one vocabulary of recessed
fields, bevelled keys and lamps that stay distinct by shape.

- Activity replaces the Restore tab with one log of backups and restores.
  Rows lead to a snapshot or an orbit; restores and exports start from the
  snapshot. The model is a pure function with tests.
- Restore opens from a snapshot as a two column screen: choose and confirm on
  the left, job progress or countdown on the right.
- Add Segmented and a themed Select (portal list, keyboard and form support).
- Add a spotlight-style search panel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 12:23:31 +07:00
34b2f346af feat: list recent restore jobs across all snapshots
Add GET /api/v1/restore-jobs?limit= (admin only, newest first, default 50,
at most 200) so the activity log can show restores without asking snapshot by
snapshot. The existing history test now also covers ordering and the limit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 12:23:22 +07:00
8b6efe1eaa feat: show what each backup is doing as a light that moves like a rocket
Replace the single-shot meteor with a per-orbit activity system. A backup's state
is read from how a small glowing triangle moves, not from a drawing of a rocket.

- Events come from status changes between polls, so scheduled backups animate
  too. A click shows its own verdict until a poll that began after it has landed,
  which keeps one backup from being animated twice or flipping through a stale
  status. Loading the page only sets a baseline and never replays history.
- Queued waits on its star. Running circles it, climbing and spinning up.
- Success waits for a launch window, where the light's own motion already carries
  it round the black hole, then departs with that velocity. It falls under a
  pseudo-Newtonian pull after a burn that trims angular momentum to just under
  the capture limit, so the path spirals with the orbits, always arrives, and
  never slows on the way in. Near the shadow it reddens, dims and stretches, and
  the disk spins up as it feeds.
- Failure explodes in place or, when the hub says the transfer failed, launches,
  loses power and falls back. The star keeps its busy look until the outcome and
  then turns red. Rehearsal is a faint dashed light that lands on its star.
- Position and velocity are integrated and a mode change only swaps forces, so
  every transition is continuous and interruptible. Parameters use the shared
  spring tokens. Trails follow the path actually flown.
- At most ten lights are drawn; reduced motion draws none and shows outcomes at once.
- Pure modules with tests for activity, physics and trails. The Playwright capture
  script now checks lights by data-orbit. The animation guideline in docs/UI.md
  describes the simulation approach in place of the old single progress value.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 23:04:25 +07:00
d0f22c4ad0 feat: draw orbits as stars in the realistic look and follow the radar wave
The orbit overlay fit the radar look but read as a diagram laid over the
realistic one. Give each look its own grammar over the same data.

- Realistic look: each orbit is a star with a bright core, a status-tinted
  glow and four tapered diffraction spikes, which the sky's own stars never
  have. Status still shows by shape as well as colour. Tracks recede to a faint
  trace, hovering a marker reveals its shell, and the selected orbit keeps its
  dashed ring. Moving markers trail a tapered comet tail along their orbit.
- Stars shimmer out of phase on the scene loop that already runs, more for
  working and failed ones. A stopped map is still, and reduced motion turns it
  off. Hovering a star enlarges it with the shared spring.
- Radar look: plain instrument dots and full-strength tracks, as before.
- The overlay takes the look at each marker's and ring's own distance from the
  hole, so it changes as the radar wave front passes. The renderer exposes this
  as signal.lookAt and calls signal.onLook while the wave runs.
- Slow the wave spring so the front takes about 0.4 s to cross the orbit area
  instead of 0.2 s, and end it at 99.5% progress.
- Test that a marker's trail points back along its motion.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 22:11:49 +07:00
34e9afc8a4 feat: render the black hole and sky with a WebGL2 ray tracer
Replace the SVG core and backdrop with one shader that traces each pixel
through Schwarzschild spacetime. The shadow, the arch of the far side of the
disk, the second image and the Einstein ring come from the physics rather than
artwork. The disk is a thin disk seen from a low angle, about five times the
shadow's radius, with Doppler beaming and a filtered, cloud-like texture.

- Sky: a procedural galaxy baked once into a cubemap. Point sources are small,
  few and brightness-capped so they never rival the orbit markers, which now
  carry a dark backing disc and outline.
- Quality: tiers from high to still, a startup calibration cached per canvas
  size, an fps cap, and an idle sleep. A locked realistic map draws nothing.
- Integration: the canvas follows the galaxy frame through Big Screen, draws in
  Motion's post-render step, takes the disk clock and capture absorption from
  the galaxy loop, and falls back to the SVG core without WebGL2.
- Radar view: a toolbar toggle switches to a radar look that spreads outward
  from the hole as a wave, with a sweep on its own clock. The choice is
  remembered per browser; reduced motion switches at once and holds the sweep.
- Tests for the geodesics, quality governor, look spring and layout, plus a
  standalone preview page (web/blackhole-proto.html) for tuning the look.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 21:51:35 +07:00
6320b6f244 feat: add managed database capture and operator restore
PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 23:26:49 +07:00
30a1a9b8f0 feat: add configurable GFS retention per orbit 2026-11-10 11:16:03 +07:00
749c4cc828 feat: use Restic for encrypted incremental backups
Keep legacy restores readable while using Restic for new captures, scoped Wormhole repositories, and chunk garbage collection.
2026-11-10 10:48:05 +07:00
95778d54e4 fix: harden the vault before release
Require a private passphrase and loopback-or-token admin auth. New vaults use Argon2id; existing PBKDF2 vaults still open, and new snapshot metadata is encrypted. Wormhole tokens survive restart, offset uploads seal into the vault, and client-certificate uploads are real. Reject the command provider and keep Postgres passwords off the process arguments. Keep the interruptible canvas motion.
2026-11-10 09:53:06 +07:00
60ba8fed88 feat: add immersive big screen mode 2026-11-09 22:48:21 +07:00
3a0259cbdd feat: animate the vault accretion disk 2026-11-09 22:40:09 +07:00
34154b2ef1 feat: seed production-like backup histories 2026-11-09 22:23:03 +07:00
fba4a1e628 feat: rebuild the orbital vault as an operational map 2026-11-09 22:01:14 +07:00
2129e80c38 fix: report verified orbit capture outcomes 2026-11-09 22:01:14 +07:00
188 changed files with 49882 additions and 2331 deletions

5
.cargo/audit.toml Normal file
View File

@@ -0,0 +1,5 @@
# Mirrors deny.toml. Reason: Tessera only verifies RSA signatures with public keys
# (openidconnect core/crypto.rs); runtime code never performs RSA private-key operations
# (test fixtures sign tokens with throwaway keys).
[advisories]
ignore = ["RUSTSEC-2023-0071"]

12
.dockerignore Normal file
View File

@@ -0,0 +1,12 @@
.git
target
data
graft
node_modules
web/node_modules
web/dist
**/.DS_Store
*.db
*.part
.env
.env.*

37
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,37 @@
name: ci
on: [push, pull_request]
permissions:
contents: read
jobs:
rust:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json }
- run: npm ci && npm run build
working-directory: web
- uses: dtolnay/rust-toolchain@d92bbbb03544f480ed5c7ba4b54020e4ed2c4f65 # 1.89.0
with: { components: "rustfmt, clippy" }
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2
- run: sudo apt-get update && sudo apt-get install -y restic postgresql-client
- run: cargo fmt --all -- --check
- run: cargo clippy --workspace --all-targets -- -D warnings
- run: cargo test --workspace
supply-chain:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2
- run: cargo install cargo-audit --version 0.23.0 --locked && cargo audit
web:
runs-on: ubuntu-latest
defaults: { run: { working-directory: web } }
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json }
- run: npm ci
- run: npm run typecheck
- run: npm test
- run: npm run build

68
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,68 @@
name: release
on:
push:
tags: ["v*"]
permissions:
contents: read
jobs:
image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
binaries:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with: { node-version: 22, cache: npm, cache-dependency-path: web/package-lock.json }
- run: npm ci && npm run build
working-directory: web
- uses: dtolnay/rust-toolchain@d92bbbb03544f480ed5c7ba4b54020e4ed2c4f65 # 1.89.0
- run: cargo build --release --locked -p tessera-hub -p tessera-cli -p tessera-agent
- run: |
mkdir dist
cp target/release/tessera-hub target/release/tessera target/release/tessera-agent dist/
tar -C dist -czf "tessera-${GITHUB_REF_NAME}-linux-x86_64.tar.gz" .
sha256sum "tessera-${GITHUB_REF_NAME}-linux-x86_64.tar.gz" > SHA256SUMS
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: linux-x86_64
path: |
tessera-*.tar.gz
SHA256SUMS
publish:
needs: [image, binaries]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with: { name: linux-x86_64 }
- uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2
with:
files: |
tessera-*.tar.gz
SHA256SUMS
generate_release_notes: true

9
.gitignore vendored
View File

@@ -8,3 +8,12 @@ web/dist/
*.db
*.part
.DS_Store
# Local tooling and editor/agent state: never part of the repository.
/.serena/
/.claude/
/.ignore
/graft/
/floorplan/
/web/AGENTS.md
/web/blackhole-proto.html

30
CHANGELOG.md Normal file
View File

@@ -0,0 +1,30 @@
# Changelog
All notable changes to this project are documented in this file. The format is based on
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.1.0] - 2026-11-16
First public release.
### Added
- Authentication rebuilt: server-side sessions, emergency operator, OIDC (authorization code + PKCE), digest-only
Outpost tokens and pairing codes, rate limiting, central access gate with per-orbit grants.
- Downloads as real, streamed archives with concurrency and disk limits.
- Environments, production-to-staging relations and durable refresh runs with re-authorisation before overwrite.
- Refresh console for QA and a refresh-only access mode.
- Managed PostgreSQL/MySQL capture and restore through Outposts, Restic deduplication, GFS retention.
### Security
- Security headers on every response, and a CSRF check on cookie-authenticated mutations.
- Audit log hardening: denials are throttled per source and audit records are subject to a retention window.
- Rate limiting per client address, with `X-Forwarded-For` honoured only from `TESSERA_TRUSTED_PROXIES`.
- The published development vault passphrase is refused for new vaults.
### Packaging
- The container image runs as a non-root user.
- A release workflow builds and publishes the release artifacts.

2279
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,7 +14,7 @@ members = [
version = "0.1.0"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = ["Senkensha"]
authors = ["The Tessera contributors"]
[workspace.dependencies]
anyhow = "1.0"
@@ -29,9 +29,9 @@ rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha2 = "=0.10.8"
rusqlite = { version = "=0.31.0", features = ["bundled"] }
rusqlite = { version = "=0.41.1", features = ["bundled"] }
thiserror = "1.0"
tokio = { version = "=1.40.0", features = ["full"] }
tokio = { version = "1.51.6", features = ["full"] }
tokio-cron-scheduler = "0.13"
tower = "0.5"
tower-http = { version = "0.6", features = ["fs", "trace", "cors"] }
@@ -39,8 +39,8 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
utoipa = { version = "4.2", features = ["axum_extras", "chrono"] }
uuid = { version = "=1.10.0", features = ["v4", "serde"] }
aes-gcm = "=0.9.4"
pbkdf2 = { version = "=0.10.1", features = ["simple"] }
aes-gcm = "=0.10.3"
argon2 = "=0.5.3"
hmac = "0.12"
tempfile = "3.12"
walkdir = "2.5"

View File

@@ -1,22 +1,55 @@
FROM node:22-bookworm AS web
# syntax=docker/dockerfile:1
# Base images are pinned by multi-arch index digest. To update, run
# `docker buildx imagetools inspect <image:tag>` and replace the digest.
FROM node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb AS web
WORKDIR /build
COPY web/package.json web/package-lock.json* ./
RUN npm ci 2>/dev/null || npm install
RUN npm ci
COPY web/ ./
RUN npm run build
FROM rust:1.88-bookworm AS rust
FROM rust:1.89-bookworm@sha256:948f9b08a66e7fe01b03a98ef1c7568292e07ec2e4fe90d88c07bb14563c84ff AS rust
WORKDIR /build
COPY Cargo.toml Cargo.lock* ./
COPY crates ./crates
COPY --from=web /build/dist ./web/dist
RUN cargo build --release -p tessera-hub
RUN cargo build --release --locked -p tessera-hub -p tessera-cli
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/
FROM restic/restic:0.19.1@sha256:136600b6ff6843d61d355f7f71f460a166429f35de6fd11b568fece3c9a4d510 AS restic
FROM mysql:8.4@sha256:a81d043930e51745522bd5c430961cf8286f0a23f0a9a2a6e0108f7ea71b0902 AS mysql-client
FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc
# Bookworm ships pg_dump 15, which refuses to dump a newer server. Install a
# current client from the PostgreSQL project's apt repository (PGDG) instead.
# pg_dump 17 dumps servers 9.2 through 17.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates curl gnupg libstdc++6 \
&& install -d /usr/share/keyrings \
&& curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /usr/share/keyrings/pgdg.gpg \
&& echo "deb [signed-by=/usr/share/keyrings/pgdg.gpg] https://apt.postgresql.org/pub/repos/apt bookworm-pgdg main" > /etc/apt/sources.list.d/pgdg.list \
&& apt-get update \
&& apt-get install -y --no-install-recommends postgresql-client-17 \
&& apt-get purge -y --auto-remove curl gnupg \
&& rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /build/target/release/tessera /usr/local/bin/
COPY --from=restic /usr/bin/restic /usr/local/bin/restic
COPY --from=mysql-client /usr/bin/mysqldump /usr/local/bin/mysqldump
COPY --chmod=0755 <<'EOF2' /usr/local/bin/tessera-healthcheck
#!/bin/bash
# Minimal HTTP GET /health using bash's /dev/tcp, so the slim image needs no curl.
port="${TESSERA_LISTEN##*:}"
exec 3<>"/dev/tcp/127.0.0.1/${port:-8787}" || exit 1
printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3
IFS= read -r status <&3
[[ "$status" == HTTP/*" 200 "* ]]
EOF2
RUN restic version && mysqldump --version && pg_dump --version && tessera --help >/dev/null \
&& useradd --uid 10001 --user-group --home-dir /home/tessera --create-home tessera \
&& install -d -o tessera -g tessera /data
ENV TESSERA_LISTEN=0.0.0.0:8787
ENV TESSERA_DATA_DIR=/data
EXPOSE 8787
VOLUME ["/data"]
USER tessera
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["/usr/local/bin/tessera-healthcheck"]
ENTRYPOINT ["tessera-hub"]

100
README.md
View File

@@ -4,46 +4,128 @@ Self-hosted backup vault with a space-themed canvas: **orbits**, **snapshots**,
## Quick start
For a native install, put [Restic 0.19.1 or newer](https://restic.readthedocs.io/en/stable/020_installation.html) on the hub and CLI's `PATH`. The Docker image includes Restic.
```bash
# Build UI then hub
cd web && npm ci && npm run build && cd ..
cargo build --release -p tessera-hub
export TESSERA_DATA_DIR=./data
export TESSERA_VAULT_PASSPHRASE=dev-vault-key
export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera-hub
```
Open [http://127.0.0.1:8787](http://127.0.0.1:8787) — API docs at `/swagger-ui`.
The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json` for signed-in operators (set `TESSERA_PUBLIC_OPENAPI=true` to publish it). There is no default passphrase, and new vaults refuse the old published value `dev-vault-key`. Leave `TESSERA_SEED_DEMO` unset; `TESSERA_SEED_DEMO=1` writes demo backup history into the data directory.
Authentication is required by default, including on loopback. Configure at least one of: the emergency operator
(`TESSERA_OPERATOR_PASSWORD_HASH`), a shared API token (`TESSERA_ADMIN_TOKEN`, at least 32 characters, optionally with
`TESSERA_ADMIN_TOKEN_EXPIRES`), or OIDC single sign-on. The hub refuses to start with none of them. For synthetic local
development only, `TESSERA_LOCAL_DEVELOPMENT=true` allows anonymous loopback access. See
[docs/DATABASE-CAPTURE.md](docs/DATABASE-CAPTURE.md) for operator sign-in, OIDC, per-orbit access grants, downloads,
production-to-staging relations and refresh runs.
### Docker Compose
```bash
export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
docker compose up --build
```
Hub listens on **8787**.
Compose publishes **127.0.0.1:8787** only. The process inside the container listens on `0.0.0.0:8787` so that published port can reach it. Compose also needs operator, token or OIDC credentials (see above); pass them through the environment. `compose.yaml` forwards the `TESSERA_*` settings documented here.
The image runs as the non-root user `tessera` (uid 10001) with a read-only root filesystem, no capabilities and a health check on `/health`. All state lives in the `/data` volume, and database dumps are staged there too (`TMPDIR=/data`), so size that volume for one full dump per concurrent capture. It ships `tessera-hub`, the `tessera` CLI, Restic, `mysqldump` and `pg_dump` 17. Base images are pinned by digest.
Requirements and limits to know before exposing it:
- `TESSERA_ADMIN_TOKEN` must be at least 32 characters (`openssl rand -base64 32`).
- Audit records are kept for `TESSERA_AUDIT_RETENTION_DAYS` days (default 90).
- `TESSERA_TRUSTED_PROXIES` takes a comma-separated list of exact proxy IP addresses, not CIDR ranges. Set it when a reverse proxy terminates TLS in front of the hub, along with `TESSERA_PUBLIC_URL`; otherwise the hub sees the proxy as every client.
- Run decay's space reclamation with `docker compose exec tessera-hub tessera gc`.
- Create the operator hash with `printf '%s\n' "$pw" | docker run --rm -i --entrypoint tessera-hub <image> --hash-operator-password`.
Example reverse proxy (Caddy on the same host, TLS handled by Caddy; set `TESSERA_PUBLIC_URL=https://tessera.example.org` and `TESSERA_TRUSTED_PROXIES=127.0.0.1`):
```
tessera.example.org {
reverse_proxy 127.0.0.1:8787
}
```
### CLI
```bash
cargo build --release -p tessera-cli
cargo build --release -p tessera-cli # the binary is named `tessera`
export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera init
./target/release/tessera orbit nightly --path ./docs --dry-run
./target/release/tessera orbit nightly --path ./docs
./target/release/tessera snap
./target/release/tessera list
```
## Deduplicated backups
New captures use Restic. Orbits select **Filesystem / Folder** or **Database**, then **Via Hub** or **Via Outpost**. Filesystem orbits executed by the hub back up files directly and share encrypted chunks in `vault/restic`. Each successful run creates a complete restore point. The API reports `size_bytes` for the logical backup, `stored_bytes` for new packed data and metadata, and `new_data_chunks` for newly stored payload chunks. An identical backup can add metadata while reporting zero new data chunks.
Restore a new filesystem or Restic outpost snapshot to a file such as `restore.tar`. PostgreSQL and legacy upload restores still produce the original payload bytes. Existing snapshots use their original storage and restore format. Keep the entire `vault` directory and its passphrase together when moving a Tessera installation.
Decay removes expired snapshots from Tessera's list. Run `tessera gc` periodically from the host or container with the same data directory and vault passphrase to let Restic reclaim their unreferenced chunks. Run it during a quiet period so Restic can acquire its repository locks. Legacy packs and Restic snapshots created outside Tessera's catalog require separate maintenance.
### Custom retention
Choose **Custom (GFS)** in an orbit's retention settings. Each count selects the newest snapshot in each of the most recent occupied UTC days, ISO weeks (Monday to Sunday), months, or years. Empty periods do not use up a count. A snapshot can satisfy more than one tier. Set a tier to zero to skip it and keep at least one tier above zero. Existing presets keep their original behavior.
To set 7 daily, 2 weekly, 6 monthly, and 3 yearly snapshots from the CLI:
```bash
tessera orbit archive --path /srv/archive --keep-daily 7 --keep-weekly 2 --keep-monthly 6 --keep-yearly 3
tessera retention <orbit-id> --keep-daily 7 --keep-weekly 2 --keep-monthly 6 --keep-yearly 3
```
The API accepts `{"retention":{"keep_daily":7,"keep_weekly":2,"keep_monthly":6,"keep_yearly":3}}` as part of `POST /api/v1/orbits` or as the body of `PUT /api/v1/orbits/{id}/retention`. Omitted tiers default to zero. To switch back to a preset, send `{"decay_preset":"week-of-dailies"}` to the same `PUT` endpoint or use `tessera retention <orbit-id> --preset week-of-dailies`. Saving applies the policy after the next successful capture. The separate `tessera decay --preset` command applies its selected preset to legacy snapshots. Managed captures use their profile policy.
### Managed database backups
[Pair an agent and register a capture profile](docs/DATABASE-CAPTURE.md) for PostgreSQL or MySQL. Profiles support direct connections and pinned SSH, scheduled capture, job history, downloads, and optional S3 copies. The managed path stores dumps in the hub's existing Restic repository.
### Incremental Wormhole transfers for filesystem archives
The same repository setup is used by new [Outpost backup profiles](docs/DATABASE-CAPTURE.md).
Rest Server's `.htpasswd` must use bcrypt entries (`htpasswd -B`); Apache `apr1` hashes from `openssl passwd -apr1` are rejected with "Invalid htpasswd entry". Restart Rest Server (do not just signal a reload) after changing the file.
Run [Rest Server](https://github.com/restic/rest-server#usage) with TLS, authentication, `--append-only`, and `--private-repos`. Point its storage at the hub's `vault/outposts` directory. Both processes need filesystem access to that directory. Give Rest Server access only to `outposts`, with a separate location for its TLS and authentication files.
1. Pair the agent as usual. Save the outpost UUID and upload token from the pairing response. Create an orbit with `tessera orbit <name> --provider wormhole`. The agent's `run` command handles scheduling.
2. Initialize a Restic repository at `vault/outposts/<orbit-id>` with a unique repository password. Create a Rest Server login named `<orbit-id>` with a separate HTTP password. Put a mode `0600` file named `vault/keys/outpost-<orbit-id>.json` on the hub with the fields `outpost_id` (the paired UUID) and `password` (that repository's password). Back up this configuration with the vault.
3. On the agent, set `TESSERA_HUB_URL`, `TESSERA_UPLOAD_TOKEN`, `TESSERA_ORBIT_ID`, and `TESSERA_RESTIC_REPOSITORY` (for example, `rest:https://backup.example.org/<orbit-id>/`). Supply the repository password via `RESTIC_PASSWORD_FILE` or `RESTIC_PASSWORD`, and Rest Server credentials via `RESTIC_REST_USERNAME` and `RESTIC_REST_PASSWORD`. Run `tessera-agent beam` from the directory to back up. For a private Rest Server CA, set `RESTIC_CACERT` on the agent.
The agent reads files to detect changes, sends missing chunks and metadata through Restic, and then registers the successful snapshot with Tessera. Agents using the original Wormhole upload mode still send their full archive. The hub deduplicates that archive on disk.
If the Restic backup succeeds and registration fails, retry `POST /api/v1/wormhole/restic/commit` with the paired `X-Tessera-Upload-Token` and a JSON body containing `orbit_id` and the Restic `snapshot_id` from the error. Repeating registration for the same snapshot returns the same Tessera snapshot ID.
## Access model
Browser users sign in with OIDC (or the emergency operator) and receive only the permissions an administrator granted:
`orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download`, globally or per orbit. Everything else is
administrator-only. A person may also be allowed to refresh one staging database from its production source through a
relation grant; they see no other data. Outposts authenticate with their own digest-stored tokens. Production and
staging are separated by explicit, versioned relations, and an overwrite is re-authorised right before it is applied.
## Architecture
See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tessera-store`, `tessera-providers`, `tessera-hub`, `tessera-agent`, `tessera-cli`.
## Limitations (v1)
- Vault engine uses a **restic-compatible directory layout** with Tessera’s own chunk encryption (Rust 1.83 cannot yet depend on `rustic_core` 0.13+). Emergency tooling may use external `rustic`/`restic` as formats converge.
- Wormhole uploads are **token-authenticated**; mTLS is optional via env hook (`TESSERA_WORMHOLE_MTLS`) without bundled CA generation.
- Postgres provider requires `pg_dump` on `PATH`.
- OIDC admin auth is stubbed; v1 uses open local API when hub is bound to localhost.
- New vaults derive the key with Argon2id (19 MiB, 2 iterations, parallelism 1) and record `keys/kdf.json`. A vault that already has a salt and no `kdf.json` still opens with PBKDF2-HMAC-SHA256, 100,000 iterations. New snapshot metadata is written as `{id}.json.enc`. Existing `{id}.json` files still list and restore.
- Wormhole pairing codes and upload tokens are stored in SQLite and survive a hub restart. Chunks are written at the given offset. When the bytes cover `total_bytes`, the hub seals them into the vault and deletes the `.part` file. `total_bytes` is required.
- Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent needs `TESSERA_WORMHOLE_CLIENT_CERT` and `TESSERA_WORMHOLE_CLIENT_KEY` for that listener. Configure `TESSERA_WORMHOLE_CA` when the hub certificate uses a private CA.
- PostgreSQL captures still run a full `pg_dump` into a private temporary file. Restic can deduplicate matching bytes in the resulting dump. Allow temporary disk space for one full dump per concurrent capture. The Docker image contains only the hub (plus Restic and the database clients): build `tessera-agent` and the `tessera` CLI separately and install them on the hosts that need them. On non-x86 hosts build x86_64 binaries natively or in CI, not under QEMU emulation (`aws-lc-sys` crashes the compiler there).
A native hub needs `pg_dump` and `mysqldump` on `PATH`; the Docker image includes them.
- The command provider is outside this release. Creating a command orbit and running it returns `command provider is outside this release; use filesystem or postgres`.
- OIDC supports a single issuer (authorization code with PKCE). Administrators come only from configuration (`TESSERA_OIDC_ADMIN_SUBJECTS` / `TESSERA_OIDC_ADMIN_GROUPS`); there is no first-user-becomes-admin and no self-registration. Group grants are not re-checked against the IdP during a session.
## License

30
SECURITY.md Normal file
View File

@@ -0,0 +1,30 @@
# Security policy
## Reporting a vulnerability
Please report vulnerabilities privately. Use GitHub private vulnerability reporting: open the repository's **Security**
tab and choose **Report a vulnerability**. Do not open a public issue or pull request for a vulnerability.
<!-- Owner: add a security contact email on the next line if you want an alternative to GitHub reporting. -->
Security contact email: not configured yet.
We aim to acknowledge a report within a few days, agree on a fix and disclosure timeline with you, and credit you in the
release notes if you wish. Please give us a reasonable window to ship a fix before you disclose publicly.
## Supported versions
Only the latest 0.1.x release receives security fixes. Upgrade to the newest patch release before reporting an issue
that may already be fixed.
## Deploying safely
Tessera holds encrypted backups. Keep `TESSERA_VAULT_PASSPHRASE` and the `vault` directory together and backed up
separately from the hub's host, and serve the hub over HTTPS outside loopback.
When the hub runs behind a reverse proxy, set `TESSERA_TRUSTED_PROXIES` (comma-separated IPs) to the proxies you
operate and nothing else. The hub rate-limits and audits by client address: `X-Forwarded-For` is only trusted when the
connecting peer is listed there. Left unset, every user shares the proxy's address and its rate-limit budget; listing an
address you do not control lets that peer pick the client address the hub records.
Hardening notes are in `docs/DATABASE-CAPTURE.md`; the authorization design and the per-route matrix are in
`docs/auth-endpoint-contract.md`.

View File

@@ -2,15 +2,61 @@ services:
tessera-hub:
build: .
ports:
- "8787:8787"
- "127.0.0.1:8787:8787"
environment:
TESSERA_LISTEN: "0.0.0.0:8787"
TESSERA_LOCAL_DEVELOPMENT: "false"
TESSERA_DATA_DIR: /data
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:-dev-vault-key}
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE}
TESSERA_ADMIN_TOKEN:
TESSERA_ADMIN_TOKEN_EXPIRES:
TESSERA_OPERATOR_PASSWORD_HASH:
TESSERA_OPERATOR_NAME:
TESSERA_PUBLIC_URL:
TESSERA_TRUSTED_PROXIES:
TESSERA_OIDC_ISSUER:
TESSERA_OIDC_CLIENT_ID:
TESSERA_OIDC_CLIENT_SECRET:
TESSERA_OIDC_REDIRECT_URL:
TESSERA_OIDC_ADMIN_SUBJECTS:
TESSERA_OIDC_ADMIN_GROUPS:
TESSERA_OIDC_GROUPS_CLAIM:
TESSERA_OIDC_CA_FILE:
TESSERA_WORMHOLE_LISTEN:
TESSERA_WORMHOLE_MTLS:
TESSERA_WORMHOLE_CERT:
TESSERA_WORMHOLE_KEY:
TESSERA_WORMHOLE_CLIENT_CA:
TESSERA_EXPORT_CONCURRENCY:
TESSERA_EXPORT_MIN_FREE_BYTES:
TESSERA_OUTPOST_TOKEN_DAYS:
TESSERA_REFRESH_TTL_MINUTES:
TESSERA_REFRESH_MAX_ACTIVE:
TESSERA_OFFSITE_REPOSITORY:
TESSERA_OFFSITE_PASSWORD_FILE:
AWS_ACCESS_KEY_ID:
AWS_SECRET_ACCESS_KEY:
AWS_SESSION_TOKEN:
AWS_REGION:
# Database dumps and exports are staged on the data volume, not in RAM.
TMPDIR: /data
RESTIC_CACHE_DIR: /tmp/restic-cache
RUST_LOG: tessera_hub=info
volumes:
- tessera-data:/data
read_only: true
tmpfs:
- /tmp:size=256m,mode=1777
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
restart: unless-stopped
healthcheck:
test: ["CMD", "/usr/local/bin/tessera-healthcheck"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
volumes:
tessera-data:

View File

@@ -3,6 +3,7 @@ name = "tessera-agent"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[[bin]]
name = "tessera-agent"
@@ -12,6 +13,7 @@ path = "src/main.rs"
tessera-core = { path = "../tessera-core" }
tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true
async-trait.workspace = true
clap.workspace = true
serde.workspace = true
serde_json.workspace = true
@@ -20,3 +22,8 @@ tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace = true
base64 = "0.22"
tempfile.workspace = true
sha2.workspace = true
hex.workspace = true
rustls = { version = "=0.23.46", default-features = false, features = ["ring", "std"] }
rustls-native-certs = "0.8"

View File

@@ -1,57 +1,241 @@
use anyhow::{Context, Result};
use rustls::pki_types::ServerName;
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::time::Duration;
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
let payload = serde_json::to_string(body)?;
request("POST", url, Some(&payload), Some("application/json"), headers)
request(
"POST",
url,
Some((&mut payload.as_bytes(), payload.len() as u64)),
Some("application/json"),
headers,
Duration::from_secs(30),
)
}
pub fn post_file(
url: &str,
file: &mut File,
len: u64,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<String> {
request(
"POST",
url,
Some((file, len)),
Some("application/octet-stream"),
headers,
timeout,
)
}
pub fn get_file(
url: &str,
file: &mut File,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<u64> {
let (mut response, length) = response("GET", url, None, None, headers, timeout)?;
let length = length.context("missing restore payload length")?;
anyhow::ensure!(
length > 0 && length <= 100 * 1024 * 1024 * 1024,
"invalid restore payload length"
);
let read = std::io::copy(&mut response.by_ref().take(length), file)?;
anyhow::ensure!(read == length, "incomplete restore payload");
Ok(length)
}
fn request(
method: &str,
url: &str,
body: Option<&str>,
body: Option<(&mut dyn Read, u64)>,
content_type: Option<&str>,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<String> {
let (host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
let (mut response, length) = response(method, url, body, content_type, headers, timeout)?;
let length = length.unwrap_or(64 * 1024);
anyhow::ensure!(length <= 64 * 1024, "hub JSON response too large");
let mut body = String::new();
let read = response.by_ref().take(length).read_to_string(&mut body)?;
if length < 64 * 1024 {
anyhow::ensure!(read as u64 == length, "incomplete hub response");
}
Ok(body.trim().to_owned())
}
fn response(
method: &str,
url: &str,
body: Option<(&mut dyn Read, u64)>,
content_type: Option<&str>,
headers: &[(&str, &str)],
timeout: Duration,
) -> Result<(BufReader<Socket>, Option<u64>)> {
let (https, host, port, path) = parse_url(url)?;
let mut stream: Socket = if https {
Box::new(connect_tls(&host, port, timeout)?)
} else {
Box::new(connect(&host, port, timeout)?)
};
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
for (k, v) in headers {
anyhow::ensure!(
v.bytes().all(|b| b.is_ascii_graphic() || b == b' '),
"invalid HTTP header value"
);
req.push_str(&format!("{k}: {v}\r\n"));
}
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some((_, len)) = &body {
req.push_str(&format!("Content-Length: {len}\r\n"));
if let Some(ct) = content_type {
req.push_str(&format!("Content-Type: {ct}\r\n"));
}
req.push_str("\r\n");
req.push_str(b);
} else {
req.push_str("\r\n");
}
req.push_str("\r\n");
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0);
Ok(buf[body_start..].trim().to_string())
if let Some((reader, len)) = body {
anyhow::ensure!(
std::io::copy(&mut reader.take(len), &mut stream)? == len,
"incomplete upload"
);
}
stream.flush()?;
let mut response = BufReader::new(stream);
let mut line = String::new();
response.by_ref().take(16 * 1024).read_line(&mut line)?;
let status = line
.split_whitespace()
.nth(1)
.context("missing hub response status")?
.parse::<u16>()?;
anyhow::ensure!((200..300).contains(&status), "hub returned HTTP {status}");
let mut length = None;
let mut header_bytes = 0;
loop {
line.clear();
let read = response.by_ref().take(16 * 1024).read_line(&mut line)?;
header_bytes += read;
anyhow::ensure!(
read != 0 && header_bytes < 16 * 1024,
"invalid hub response headers"
);
if line == "\r\n" {
break;
}
if let Some((name, value)) = line.split_once(':') {
if name.eq_ignore_ascii_case("content-length") {
length = Some(value.trim().parse()?);
}
}
}
Ok((response, if status == 204 { Some(0) } else { length }))
}
fn parse_url(url: &str) -> Result<(String, u16, String)> {
let url = url.strip_prefix("http://").context("only http supported")?;
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
type Socket = Box<dyn ReadWrite>;
trait ReadWrite: Read + Write {}
impl<T: Read + Write> ReadWrite for T {}
fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
anyhow::ensure!(
!url.bytes().any(|b| b.is_ascii_control() || b == b' '),
"invalid hub URL"
);
let (https, rest) = if let Some(rest) = url.strip_prefix("https://") {
(true, rest)
} else if let Some(rest) = url.strip_prefix("http://") {
(false, rest)
} else {
anyhow::bail!("hub url must start with http:// or https://");
};
let (host_port, path) = rest.split_once('/').unwrap_or((rest, ""));
anyhow::ensure!(
!host_port.is_empty() && !host_port.contains(['@', '?', '#']),
"invalid hub authority"
);
let path = if path.is_empty() {
"/".to_string()
} else {
format!("/{path}")
};
let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
(h.to_string(), p.parse()?)
let (host, port) = if let Some((host, port)) = host_port.split_once(':') {
(host.to_string(), port.parse()?)
} else {
(host_port.to_string(), 80)
(host_port.to_string(), if https { 443 } else { 80 })
};
Ok((host, port, path))
Ok((https, host, port, path))
}
fn connect(host: &str, port: u16, timeout: Duration) -> Result<TcpStream> {
for address in (host, port).to_socket_addrs()? {
if let Ok(socket) = TcpStream::connect_timeout(&address, Duration::from_secs(5)) {
socket.set_read_timeout(Some(timeout))?;
socket.set_write_timeout(Some(Duration::from_secs(30)))?;
return Ok(socket);
}
}
anyhow::bail!("could not connect to hub")
}
fn connect_tls(
host: &str,
port: u16,
timeout: Duration,
) -> Result<StreamOwned<ClientConnection, TcpStream>> {
let _ = rustls::crypto::ring::default_provider().install_default();
let mut roots = RootCertStore::empty();
if let Some(ca) = std::env::var_os("TESSERA_WORMHOLE_CA") {
for ca_cert in load_certs(std::path::Path::new(&ca))? {
roots
.add(ca_cert)
.map_err(|error| anyhow::anyhow!("hub CA: {error}"))?;
}
} else {
let native = rustls_native_certs::load_native_certs();
roots.add_parsable_certificates(native.certs);
}
anyhow::ensure!(!roots.is_empty(), "no trusted hub CA certificates");
let builder = ClientConfig::builder().with_root_certificates(roots);
let client = match (
std::env::var_os("TESSERA_WORMHOLE_CLIENT_CERT"),
std::env::var_os("TESSERA_WORMHOLE_CLIENT_KEY"),
) {
(Some(cert), Some(key)) => builder
.with_client_auth_cert(
load_certs(std::path::Path::new(&cert))?,
load_key(std::path::Path::new(&key))?,
)
.map_err(|error| anyhow::anyhow!("client certificate: {error}"))?,
(None, None) => builder.with_no_client_auth(),
_ => anyhow::bail!("configure both Wormhole client certificate and key"),
};
let name = ServerName::try_from(host.to_string()).context("hub hostname")?;
let connection = ClientConnection::new(Arc::new(client), name)?;
let tcp = connect(host, port, timeout)?;
Ok(StreamOwned::new(connection, tcp))
}
fn load_certs(path: &std::path::Path) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
use rustls::pki_types::{pem::PemObject, CertificateDer};
CertificateDer::pem_file_iter(path)
.with_context(|| format!("open {}", path.display()))?
.collect::<Result<Vec<_>, _>>()
.context("parse certificate")
}
fn load_key(path: &std::path::Path) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
use rustls::pki_types::{pem::PemObject, PrivateKeyDer};
PrivateKeyDer::from_pem_file(path).context("parse private key in client key file")
}
#[allow(dead_code)]

View File

@@ -0,0 +1,455 @@
use crate::{http, restore, Cli};
use anyhow::{Context, Result};
use base64::Engine as _;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::File,
io::{self, Seek, SeekFrom},
path::{Path, PathBuf},
process::Stdio,
sync::Arc,
time::Duration,
};
use tessera_core::job::{
CaptureFormat, CaptureLease, CaptureProgress, CaptureReport, ResticCaptureCommit,
CAPTURE_HEARTBEAT_SECONDS,
};
use tessera_core::restore::DatabaseIdentity;
use tessera_providers::{MysqlSource, PostgresSource};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Profile {
source: Option<Source>,
#[serde(default)]
paths: Vec<PathBuf>,
restic_repository: Option<String>,
restic_password_file: Option<PathBuf>,
rest_server_password_file: Option<PathBuf>,
#[serde(default)]
targets: HashMap<Uuid, restore::Target>,
#[serde(default = "default_timeout")]
timeout_seconds: u64,
}
fn default_timeout() -> u64 {
3600
}
#[derive(Deserialize)]
#[serde(tag = "engine", rename_all = "snake_case")]
pub(super) enum Source {
Postgres(PostgresSource),
Mysql(MysqlSource),
}
/// The local backup source, as far as the restore guard cares: which database it is.
#[async_trait::async_trait]
pub(super) trait BackupSource: Sync {
async fn identity(&self) -> Result<DatabaseIdentity>;
}
#[async_trait::async_trait]
impl BackupSource for Source {
async fn identity(&self) -> Result<DatabaseIdentity> {
match self {
Self::Postgres(source) => source.identity().await,
Self::Mysql(source) => source.identity().await,
}
}
}
pub(super) struct Hub {
pub(super) url: String,
pub(super) token: String,
}
pub fn require_secure_hub(url: &str) -> Result<()> {
let local = ["http://127.0.0.1:", "http://localhost:"]
.into_iter()
.any(|prefix| {
url.strip_prefix(prefix)
.is_some_and(|port| port.parse::<u16>().is_ok())
});
anyhow::ensure!(
url.starts_with("https://") || local,
"remote Wormhole connections require an HTTPS hub"
);
Ok(())
}
pub async fn run(cli: &Cli, path: &Path) -> Result<()> {
let profiles: HashMap<Uuid, Profile> =
serde_json::from_reader(File::open(path).context("open capture profiles")?)
.map_err(|_| anyhow::anyhow!("invalid capture profiles"))?;
anyhow::ensure!(!profiles.is_empty(), "capture profile file is empty");
anyhow::ensure!(
profiles.values().all(|profile| profile.timeout_seconds > 0),
"capture timeout must be positive"
);
anyhow::ensure!(
profiles.values().all(|profile| profile.source.is_some()
|| !profile.paths.is_empty()
|| !profile.targets.is_empty()),
"application requires a source or at least one restore target"
);
let url = cli
.hub_url
.as_deref()
.context("TESSERA_HUB_URL")?
.trim_end_matches('/');
require_secure_hub(url)?;
let token = cli
.upload_token
.as_deref()
.context("TESSERA_UPLOAD_TOKEN")?;
anyhow::ensure!(
!token.is_empty() && token.bytes().all(|b| b.is_ascii_graphic()),
"invalid upload token"
);
let hub = Arc::new(Hub {
url: url.to_owned(),
token: token.to_owned(),
});
let mut workers = tokio::task::JoinSet::new();
for (id, profile) in profiles {
let hub = Arc::clone(&hub);
workers.spawn(async move {
loop {
if let Err(error) = async {
let restored = restore::poll(
&hub,
id,
profile.source.as_ref(),
&profile.targets,
profile.timeout_seconds,
Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS),
)
.await?;
if !restored && (profile.source.is_some() || !profile.paths.is_empty()) {
poll(&hub, id, &profile).await?;
}
Ok::<_, anyhow::Error>(())
}
.await
{
tracing::warn!(application_id = %id, %error, "capture polling failed");
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
});
}
workers
.join_next()
.await
.context("capture worker missing")??;
anyhow::bail!("capture worker stopped")
}
async fn poll(hub: &Arc<Hub>, id: Uuid, profile: &Profile) -> Result<()> {
let reply = hub
.post(format!("capture/{id}/claim"), serde_json::Value::Null, None)
.await?;
let Some(lease) = serde_json::from_str::<Option<CaptureLease>>(&reply)? else {
return Ok(());
};
anyhow::ensure!(
lease.profile.application_id == id,
"hub returned a different application"
);
let work = capture(hub, &lease, profile);
tokio::pin!(work);
loop {
tokio::select! {
biased;
result = &mut work => return result,
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => {
hub.report(&lease, CaptureProgress::Heartbeat).await?;
}
}
}
}
async fn capture(hub: &Arc<Hub>, lease: &CaptureLease, profile: &Profile) -> Result<()> {
hub.report(lease, CaptureProgress::Dumping).await?;
if lease.profile.format == CaptureFormat::Filesystem {
if profile.paths.is_empty() {
hub.report(lease, CaptureProgress::DumpFailed).await?;
anyhow::bail!("filesystem profile requires paths");
}
hub.report(lease, CaptureProgress::Uploading).await?;
return commit_backup(hub, lease, profile, None, None).await;
}
let Some(source) = &profile.source else {
hub.report(lease, CaptureProgress::DumpFailed).await?;
anyhow::bail!("capture source is missing");
};
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async {
let stage = tempfile::tempfile().context("create private staging file")?;
let before = probe_identity(source).await;
match (source, lease.profile.format) {
(Source::Postgres(source), CaptureFormat::PostgresCustom) => {
source.dump_to(stage.try_clone()?, "custom").await?
}
(Source::Postgres(source), CaptureFormat::PostgresSql) => {
source.dump_to(stage.try_clone()?, "plain").await?
}
(Source::Mysql(source), CaptureFormat::MysqlSql) => {
source.dump_to(stage.try_clone()?).await?
}
_ => anyhow::bail!("capture profile engine does not match the assignment"),
}
let identity = match before {
Some(identity)
if lease
.profile
.format
.engine()
.is_some_and(|engine| identity.valid(engine))
&& probe_identity(source).await.as_ref() == Some(&identity) =>
{
Some(identity)
}
_ => None,
};
Ok::<_, anyhow::Error>((stage, identity))
})
.await;
let (stage, identity) = match result {
Ok(Ok(stage)) => stage,
_ => {
hub.report(lease, CaptureProgress::DumpFailed).await?;
anyhow::bail!("database dump failed or timed out");
}
};
hub.report(lease, CaptureProgress::Uploading).await?;
if lease.restic {
return commit_backup(hub, lease, profile, Some(stage), identity).await;
}
let identity = identity
.map(|value| serde_json::to_vec(&value))
.transpose()?
.map(|value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value));
if hub
.upload(
format!("capture/{}/payload", lease.job_id),
stage,
Duration::from_secs(profile.timeout_seconds),
"x-tessera-lease-id",
lease.lease_id,
identity,
)
.await
.is_err()
{
hub.report(lease, CaptureProgress::UploadFailed).await?;
anyhow::bail!("backup upload failed");
}
Ok(())
}
async fn commit_backup(
hub: &Arc<Hub>,
lease: &CaptureLease,
profile: &Profile,
stage: Option<File>,
identity: Option<DatabaseIdentity>,
) -> Result<()> {
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async {
let repository = profile
.restic_repository
.as_deref()
.context("configure the profile Restic repository")?;
let mut command = crate::restic_command(repository)?;
if let Some(path) = &profile.restic_password_file {
command
.env_remove("RESTIC_PASSWORD")
.env_remove("RESTIC_PASSWORD_COMMAND")
.env("RESTIC_PASSWORD_FILE", path);
}
if let Some(path) = &profile.rest_server_password_file {
let password = tokio::fs::read_to_string(path)
.await
.context("read Rest Server password")?;
command
.env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string())
.env(
"RESTIC_REST_PASSWORD",
password.trim_end_matches(['\r', '\n']),
);
}
command.args([
"backup",
"--json",
"--quiet",
"--tag",
&format!("tessera-{}", lease.job_id),
]);
let sha256 = if let Some(mut file) = stage {
let (file, hash) = tokio::task::spawn_blocking(move || {
let (_, hash) = digest_file(&mut file)?;
file.seek(SeekFrom::Start(0))?;
Ok::<_, anyhow::Error>((file, hash))
})
.await??;
command
.args(["--stdin", "--stdin-filename", "payload"])
.stdin(Stdio::from(file));
Some(hash)
} else {
command.arg("--").args(&profile.paths);
None
};
let snapshot_id = crate::restic_snapshot(command).await?;
let body = serde_json::to_value(ResticCaptureCommit {
lease_id: lease.lease_id,
snapshot_id,
identity,
sha256,
})?;
for _ in 0..3 {
if hub
.post(
format!("capture/{}/restic", lease.job_id),
body.clone(),
None,
)
.await
.is_ok()
{
return Ok(());
}
}
anyhow::bail!("could not register the Restic snapshot")
})
.await;
match result {
Ok(Ok(())) => Ok(()),
failure => {
hub.report(lease, CaptureProgress::UploadFailed).await?;
failure.context("Restic backup timed out")?
}
}
}
async fn probe_identity(source: &Source) -> Option<DatabaseIdentity> {
tokio::time::timeout(Duration::from_secs(10), source.identity())
.await
.ok()?
.ok()
}
impl Hub {
pub(super) async fn post(
self: &Arc<Self>,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String> {
let hub = Arc::clone(self);
tokio::task::spawn_blocking(move || {
let restore = restore.map(|token| token.to_string());
let mut headers = vec![("x-tessera-upload-token", hub.token.as_str())];
if let Some(token) = &restore {
headers.push(("x-tessera-restore-token", token.as_str()));
}
http::post_json(
&format!("{}/api/v1/wormhole/{path}", hub.url),
&body,
&headers,
)
})
.await?
}
/// Like `post` for a restore report, with the reason for a failure in a header.
pub(super) async fn post_with_reason(
self: &Arc<Self>,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String> {
let hub = Arc::clone(self);
tokio::task::spawn_blocking(move || {
let restore = restore.to_string();
let mut headers = vec![
("x-tessera-upload-token", hub.token.as_str()),
("x-tessera-restore-token", restore.as_str()),
];
if let Some(reason) = reason.as_deref() {
headers.push((tessera_core::restore::FAILURE_REASON_HEADER, reason));
}
http::post_json(
&format!("{}/api/v1/wormhole/{path}", hub.url),
&body,
&headers,
)
})
.await?
}
async fn report(
self: &Arc<Self>,
lease: &CaptureLease,
progress: CaptureProgress,
) -> Result<()> {
let body = CaptureReport {
lease_id: lease.lease_id,
progress,
};
self.post(
format!("capture/{}/report", lease.job_id),
serde_json::to_value(body)?,
None,
)
.await?;
Ok(())
}
pub(super) async fn upload(
self: &Arc<Self>,
path: String,
mut file: File,
timeout: Duration,
lease_header: &'static str,
lease: Uuid,
identity: Option<String>,
) -> Result<()> {
let hub = Arc::clone(self);
let url = format!("{}/api/v1/wormhole/{path}", hub.url);
let lease = lease.to_string();
tokio::task::spawn_blocking(move || {
let (len, digest) = digest_file(&mut file)?;
let mut headers = vec![
("x-tessera-upload-token", hub.token.as_str()),
(lease_header, lease.as_str()),
("x-tessera-sha256", digest.as_str()),
];
if let Some(value) = &identity {
headers.push(("x-tessera-source-identity", value.as_str()));
}
for _ in 0..3 {
file.seek(SeekFrom::Start(0))?;
if http::post_file(&url, &mut file, len, &headers, timeout).is_ok() {
return Ok(());
}
}
anyhow::bail!("backup upload retry limit reached")
})
.await?
}
}
pub(super) fn digest_file(file: &mut File) -> Result<(u64, String)> {
file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
let len = io::copy(file, &mut digest)?;
file.seek(SeekFrom::Start(0))?;
Ok((len, hex::encode(digest.finalize())))
}

View File

@@ -1,9 +1,11 @@
mod http;
mod jobs;
mod restore;
use anyhow::{Context, Result};
use base64::Engine;
use clap::{Parser, Subcommand};
use tessera_core::config::ProviderKind;
use tessera_core::{config::ProviderKind, WormholeCredentials};
use tessera_providers::provider_from_config;
use tracing::info;
@@ -18,6 +20,10 @@ struct Cli {
upload_token: Option<String>,
#[arg(long, env = "TESSERA_ORBIT_ID")]
orbit_id: Option<String>,
#[arg(long, env = "TESSERA_CAPTURE_PROFILES")]
capture_profiles: Option<std::path::PathBuf>,
#[arg(long, env = "TESSERA_WORMHOLE_CREDENTIALS")]
credentials: Option<std::path::PathBuf>,
}
#[derive(Clone, Subcommand)]
@@ -34,34 +40,100 @@ enum AgentCmd {
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let cli = Cli::parse();
let mut cli = Cli::parse();
if !matches!(&cli.command, Some(AgentCmd::Pair { .. })) {
load_credentials(&mut cli)?;
}
match cli.command.clone().unwrap_or(AgentCmd::Run) {
AgentCmd::Run => run_daemon(&cli).await?,
AgentCmd::Run => tokio::select! {
result = run_daemon(&cli) => result?,
result = shutdown_signal() => result?,
},
AgentCmd::Pair { code, name } => pair(&cli, &code, &name)?,
AgentCmd::Beam => beam_once(&cli).await?,
}
Ok(())
}
async fn shutdown_signal() -> Result<()> {
#[cfg(unix)]
{
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
tokio::select! {
result = tokio::signal::ctrl_c() => result?,
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
tokio::signal::ctrl_c().await?;
Ok(())
}
fn pair(cli: &Cli, code: &str, name: &str) -> Result<()> {
let hub = cli
.hub_url
.clone()
.unwrap_or_else(|| "http://127.0.0.1:8787".into());
if let Some(path) = &cli.credentials {
anyhow::ensure!(!path.try_exists()?, "credentials file already exists");
jobs::require_secure_hub(hub.trim_end_matches('/'))?;
}
let body = serde_json::json!({ "code": code, "outpost_name": name });
let raw = http::post_json(
&format!("{hub}/api/v1/wormhole/claim"),
&format!("{}/api/v1/wormhole/claim", hub.trim_end_matches('/')),
&body,
&[],
)?;
let res: serde_json::Value = serde_json::from_str(&raw)?;
println!("TESSERA_UPLOAD_TOKEN={}", res["upload_token"]);
println!("TESSERA_HUB_URL={}", res["hub_url"]);
println!("Outpost {}", res["outpost_id"]);
let mut credentials: WormholeCredentials = serde_json::from_str(&raw)?;
if cli.hub_url.is_some()
&& (hub.starts_with("https://") || !credentials.hub_url.starts_with("https://"))
{
credentials.hub_url = hub;
}
if let Some(path) = &cli.credentials {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| std::path::Path::new("."));
let file =
tempfile::NamedTempFile::new_in(parent).context("create private credentials file")?;
serde_json::to_writer(file.as_file(), &credentials)?;
file.as_file().sync_all()?;
file.persist_noclobber(path)
.context("save pairing credentials (file must not exist)")?;
println!("Saved credentials for outpost {}", credentials.outpost_id);
} else {
println!("TESSERA_UPLOAD_TOKEN={}", credentials.upload_token);
println!("TESSERA_HUB_URL={}", credentials.hub_url);
println!("Outpost {}", credentials.outpost_id);
}
Ok(())
}
fn load_credentials(cli: &mut Cli) -> Result<()> {
let Some(path) = &cli.credentials else {
return Ok(());
};
let file = std::fs::File::open(path).context("open paired credentials")?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
anyhow::ensure!(
file.metadata()?.permissions().mode() & 0o077 == 0,
"paired credentials require owner-only permissions"
);
}
let credentials: WormholeCredentials = serde_json::from_reader(file)
.map_err(|_| anyhow::anyhow!("invalid pairing credentials"))?;
cli.hub_url.get_or_insert(credentials.hub_url);
cli.upload_token.get_or_insert(credentials.upload_token);
Ok(())
}
async fn run_daemon(cli: &Cli) -> Result<()> {
if let Some(path) = &cli.capture_profiles {
return jobs::run(cli, path).await;
}
info!("outpost online — wormhole listening for beam cycles");
loop {
if let Err(e) = beam_once(cli).await {
@@ -81,6 +153,14 @@ async fn beam_once(cli: &Cli) -> Result<()> {
let token = cli.upload_token.clone().context("TESSERA_UPLOAD_TOKEN")?;
let orbit_id = cli.orbit_id.clone().context("TESSERA_ORBIT_ID")?;
if let Some(repository) = std::env::var_os("TESSERA_RESTIC_REPOSITORY") {
let repository = repository
.to_str()
.context("TESSERA_RESTIC_REPOSITORY must be UTF-8")?;
let id = uuid::Uuid::parse_str(&orbit_id).context("invalid TESSERA_ORBIT_ID")?;
return beam_restic(repository, &hub, &token, id).await;
}
let config = serde_json::json!({ "paths": ["./"] });
let provider = provider_from_config(&ProviderKind::Filesystem, &config)?;
let capture = provider.capture().await?;
@@ -109,6 +189,67 @@ async fn beam_once(cli: &Cli) -> Result<()> {
&[("x-tessera-upload-token", &token)],
)?;
info!("beamed {} bytes via wormhole session {session_id}", capture.payload.len());
info!(
"beamed {} bytes via wormhole session {session_id}",
capture.payload.len()
);
Ok(())
}
async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::Uuid) -> Result<()> {
let mut command = restic_command(repository)?;
command.args(["backup", "--json", "--quiet", "--", "."]);
let snapshot = restic_snapshot(command).await?;
let body = serde_json::json!({ "orbit_id": orbit_id, "snapshot_id": snapshot });
let reply = http::post_json(
&format!("{hub}/api/v1/wormhole/restic/commit"),
&body,
&[("x-tessera-upload-token", token)],
)
.with_context(|| format!("register Restic snapshot {snapshot}"))?;
let reply: serde_json::Value = serde_json::from_str(&reply)?;
let registered = reply["snapshot_id"]
.as_str()
.context("hub did not register the Restic snapshot")?;
info!(snapshot, registered, "committed Restic backup");
Ok(())
}
fn restic_command(repository: &str) -> Result<tokio::process::Command> {
let authority = repository
.strip_prefix("rest:https://")
.and_then(|url| url.split('/').next());
anyhow::ensure!(
authority.is_some_and(|host| !host.is_empty() && !host.contains('@')),
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
);
let mut command = tokio::process::Command::new("restic");
command
.env("RESTIC_REPOSITORY", repository)
.env_remove("RESTIC_REPOSITORY_FILE")
.stdin(std::process::Stdio::null())
.kill_on_drop(true);
Ok(command)
}
async fn restic_snapshot(mut command: tokio::process::Command) -> Result<String> {
let output = command
.output()
.await
.context("starting restic (install restic on PATH)")?;
anyhow::ensure!(
output.status.success(),
"restic backup failed ({})",
output.status
);
let summary: serde_json::Value = serde_json::from_str(
std::str::from_utf8(&output.stdout)?
.lines()
.last()
.context("missing restic summary")?,
)?;
Ok(summary["snapshot_id"]
.as_str()
.context("missing restic snapshot ID")?
.to_owned())
}

View File

@@ -0,0 +1,350 @@
use crate::{
http,
jobs::{digest_file, BackupSource, Hub},
};
use anyhow::{ensure, Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use std::{
collections::HashMap,
fs::File,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tessera_core::{
job::CaptureFormat,
restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
};
use tessera_providers::{MysqlRestore, PostgresRestore};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(tag = "engine", rename_all = "snake_case")]
pub(super) enum Target {
Postgres(PostgresRestore),
Mysql(MysqlRestore),
}
/// The local database a restore is applied to. A seam so the destructive sequence in `run` can be driven
/// by fakes in tests; the real implementation is `Target`.
#[async_trait]
pub(super) trait RestoreTarget: Sync {
async fn identity(&self) -> Result<DatabaseIdentity>;
async fn prepare(&self, input: File, lease: &RestoreLease) -> Result<File>;
async fn safety(&self, stage: File) -> Result<()>;
async fn apply(&self, script: File) -> Result<()>;
}
/// What the restore flow needs from the hub. A seam for tests; the real implementation is `Arc<Hub>`.
#[async_trait]
pub(super) trait RestoreHub: Sync {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String>;
async fn send_with_reason(
&self,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String>;
async fn upload_safety(
&self,
lease: &RestoreLease,
stage: File,
timeout: Duration,
) -> Result<()>;
async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result<File>;
}
#[async_trait]
impl RestoreHub for Arc<Hub> {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String> {
self.post(path, body, restore).await
}
async fn send_with_reason(
&self,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String> {
self.post_with_reason(path, body, restore, reason).await
}
async fn upload_safety(
&self,
lease: &RestoreLease,
stage: File,
timeout: Duration,
) -> Result<()> {
self.upload(
format!("restore/{}/safety", lease.job.id),
stage,
timeout,
"x-tessera-restore-token",
lease.token,
None,
)
.await
}
async fn download(&self, lease: &RestoreLease, timeout: Duration) -> Result<File> {
let hub = self.clone();
let id = lease.job.id;
let token = lease.token.to_string();
let digest = lease.artifact.sha256.clone();
tokio::task::spawn_blocking(move || {
let mut file = tempfile::tempfile().context("create private restore staging")?;
let size = http::get_file(
&format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url),
&mut file,
&[
("x-tessera-upload-token", &hub.token),
("x-tessera-restore-token", &token),
],
timeout,
)?;
let (bytes, computed) = digest_file(&mut file)?;
ensure!(
size == bytes && computed == digest,
"restore payload checksum mismatch"
);
Ok(file)
})
.await?
}
}
#[async_trait]
impl RestoreTarget for Target {
async fn identity(&self) -> Result<DatabaseIdentity> {
match self {
Self::Postgres(target) => target.connection.identity().await,
Self::Mysql(target) => target.connection.identity().await,
}
}
async fn prepare(&self, input: File, lease: &RestoreLease) -> Result<File> {
match (self, lease.artifact.format) {
(
Self::Postgres(target),
format @ (CaptureFormat::PostgresCustom | CaptureFormat::PostgresSql),
) => {
target
.prepare(input, format, &lease.job.target.identity)
.await
}
(Self::Mysql(target), CaptureFormat::MysqlSql) => {
target.prepare(input, &lease.job.target.identity).await
}
_ => anyhow::bail!("local restore target engine does not match the assignment"),
}
}
async fn safety(&self, stage: File) -> Result<()> {
match self {
Self::Postgres(target) => target.connection.safety_dump_to(stage).await,
Self::Mysql(target) => target.connection.dump_to(stage).await,
}
}
async fn apply(&self, script: File) -> Result<()> {
match self {
Self::Postgres(target) => target.apply(script).await,
Self::Mysql(target) => target.apply(script).await,
}
}
}
pub(super) async fn poll<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &H,
application: Uuid,
source: Option<&S>,
targets: &HashMap<Uuid, T>,
timeout_seconds: u64,
heartbeat: Duration,
) -> Result<bool> {
for (target_id, target) in targets {
let reply = hub
.send(
format!("restore-targets/{target_id}/claim"),
serde_json::Value::Null,
None,
)
.await?;
let Some(lease) = serde_json::from_str::<Option<RestoreLease>>(&reply)? else {
continue;
};
ensure!(
lease.job.target.id == *target_id && lease.job.target.application_id == application,
"hub returned an unexpected restore target"
);
let permit_taken = AtomicBool::new(false);
let work = run(
hub,
&lease,
target,
source,
Duration::from_secs(timeout_seconds),
&permit_taken,
);
tokio::pin!(work);
loop {
tokio::select! {
biased;
result = &mut work => return result.map(|()| true),
_ = tokio::time::sleep(heartbeat) => {
if let Err(error) = report(hub, &lease, RestoreProgress::Heartbeat).await {
// Once the apply permit is spent, dropping `work` would kill the apply
// half way (its children are `kill_on_drop`) and leave the target
// half-restored with no terminal report. Keep going and let the outcome
// report decide. Before the permit nothing destructive has happened,
// so give up and let the lease expire.
if !permit_taken.load(Ordering::SeqCst) {
return Err(error);
}
tracing::warn!(restore = %lease.job.id, %error, "heartbeat failed during apply; letting the restore finish");
}
}
}
}
}
Ok(false)
}
async fn run<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &H,
lease: &RestoreLease,
target: &T,
source: Option<&S>,
timeout: Duration,
permit_taken: &AtomicBool,
) -> Result<()> {
report(hub, lease, RestoreProgress::Checking).await?;
let downloaded = tokio::time::timeout(timeout, async {
let input = hub.download(lease, timeout).await?;
target.prepare(input, lease).await
})
.await;
let script = match downloaded {
Ok(Ok(script)) => script,
other => {
report_failed(hub, lease, RestoreProgress::InvalidPayload, why(other)).await?;
return Ok(());
}
};
let verified = tokio::time::timeout(timeout, async {
let identity = target.identity().await?;
ensure!(
identity == lease.job.target.identity
&& (lease.artifact.rollback || identity != lease.artifact.identity),
"restore target identity does not match"
);
if let Some(source) = source {
if let Ok(Ok(source_identity)) =
tokio::time::timeout(Duration::from_secs(10), source.identity()).await
{
ensure!(
source_identity != identity,
"target resolves to the local backup source"
);
}
}
Ok::<_, anyhow::Error>(identity)
})
.await;
let identity = match verified {
Ok(Ok(identity)) => identity,
other => {
report_failed(hub, lease, RestoreProgress::WrongTarget, why(other)).await?;
return Ok(());
}
};
report(hub, lease, RestoreProgress::Safety).await?;
let safety = tokio::time::timeout(timeout, async {
let stage = tempfile::tempfile().context("create private safety staging")?;
target.safety(stage.try_clone()?).await?;
ensure!(
target.identity().await? == identity,
"target changed during safety capture"
);
hub.upload_safety(lease, stage, timeout).await?;
Ok::<_, anyhow::Error>(())
})
.await;
if !matches!(safety, Ok(Ok(()))) {
report_failed(hub, lease, RestoreProgress::SafetyFailed, why(safety)).await?;
return Ok(());
}
// The permit is single-use. A lost response leaves the target locked for reconciliation. Mark it
// taken before asking: from here on the hub may consider the apply started.
permit_taken.store(true, Ordering::SeqCst);
hub.send(
format!("restore/{}/apply", lease.job.id),
serde_json::Value::Null,
Some(lease.token),
)
.await?;
match tokio::time::timeout(timeout, target.apply(script)).await {
Ok(Ok(())) => report(hub, lease, RestoreProgress::Applied).await,
other => report_failed(hub, lease, RestoreProgress::ApplyFailed, why(other)).await,
}
}
/// Why a step did not succeed, in words: the error chain, or that it ran out of time.
fn why<T>(result: Result<Result<T>, tokio::time::error::Elapsed>) -> String {
match result {
Ok(Ok(_)) => "unknown".into(),
Ok(Err(error)) => format!("{error:#}"),
Err(_) => "timed out".into(),
}
}
async fn report_failed<H: RestoreHub>(
hub: &H,
lease: &RestoreLease,
progress: RestoreProgress,
reason: String,
) -> Result<()> {
hub.send_with_reason(
format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?,
lease.token,
tessera_core::restore::clean_failure_reason(&reason),
)
.await?;
Ok(())
}
async fn report<H: RestoreHub>(
hub: &H,
lease: &RestoreLease,
progress: RestoreProgress,
) -> Result<()> {
hub.send(
format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?,
Some(lease.token),
)
.await?;
Ok(())
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,863 @@
//! The restore sequence is destructive, so these tests drive `run` and `poll` with in-process fakes and
//! assert what the agent does (and above all never does) at each step. Every fake appends to one shared
//! event log so tests can assert on ordering and absence.
use super::*;
use std::{
collections::VecDeque,
io::{Read, Write},
sync::Mutex,
};
use tessera_core::restore::{RestoreArtifact, RestoreJob, RestoreTarget as JobTarget};
type Log = Arc<Mutex<Vec<String>>>;
fn identity(instance: &str, database: &str) -> DatabaseIdentity {
DatabaseIdentity {
instance: instance.into(),
database: database.into(),
}
}
fn target_identity() -> DatabaseIdentity {
identity("1", "target")
}
fn source_identity() -> DatabaseIdentity {
identity("2", "source")
}
fn lease_for(target: Uuid, application: Uuid, rollback: bool) -> RestoreLease {
RestoreLease {
job: RestoreJob {
id: Uuid::new_v4(),
snapshot_id: Uuid::new_v4(),
target: JobTarget {
id: target,
application_id: application,
outpost_id: Uuid::new_v4(),
name: "target".into(),
engine: tessera_core::restore::Engine::Postgres,
identity: target_identity(),
},
actor: "admin".into(),
status: "running".into(),
phase: "queued".into(),
safety_snapshot_id: None,
created_at: 0,
updated_at: 0,
failure_reason: None,
},
token: Uuid::new_v4(),
artifact: RestoreArtifact {
format: CaptureFormat::PostgresCustom,
// A normal restore comes from another database; a rollback comes from the target itself.
identity: if rollback {
target_identity()
} else {
source_identity()
},
sha256: "00".into(),
rollback,
},
}
}
fn lease() -> RestoreLease {
lease_for(Uuid::new_v4(), Uuid::new_v4(), false)
}
#[derive(Clone, Copy, PartialEq)]
enum Step {
Ok,
Fail,
Hang,
/// Succeeds after this many milliseconds.
Slow(u64),
}
impl Step {
async fn run(self, what: &str) -> Result<()> {
match self {
Step::Ok => Ok(()),
Step::Fail => anyhow::bail!("{what} exploded"),
Step::Hang => std::future::pending().await,
Step::Slow(ms) => {
tokio::time::sleep(Duration::from_millis(ms)).await;
Ok(())
}
}
}
}
type Answer = Result<DatabaseIdentity, &'static str>;
struct FakeTarget {
log: Log,
/// Answers for successive `identity` calls; the last one repeats.
identities: Mutex<VecDeque<Answer>>,
hang_identity: bool,
prepare: Step,
safety: Step,
apply: Step,
}
impl FakeTarget {
fn new(log: &Log) -> Self {
Self {
log: log.clone(),
identities: Mutex::new(VecDeque::from([Ok(target_identity())])),
hang_identity: false,
prepare: Step::Ok,
safety: Step::Ok,
apply: Step::Ok,
}
}
fn identities(self, answers: Vec<Answer>) -> Self {
*self.identities.lock().unwrap() = answers.into();
self
}
}
#[async_trait]
impl RestoreTarget for FakeTarget {
async fn identity(&self) -> Result<DatabaseIdentity> {
self.log.lock().unwrap().push("target.identity".into());
if self.hang_identity {
std::future::pending::<()>().await;
}
let answer = {
let mut answers = self.identities.lock().unwrap();
if answers.len() > 1 {
answers.pop_front().unwrap()
} else {
answers.front().cloned().unwrap()
}
};
answer.map_err(|why| anyhow::anyhow!(why))
}
async fn prepare(&self, mut input: File, _: &RestoreLease) -> Result<File> {
self.log.lock().unwrap().push("target.prepare".into());
self.prepare.run("prepare").await?;
let mut script = tempfile::tempfile()?;
let mut body = Vec::new();
input.read_to_end(&mut body)?;
script.write_all(&body)?;
Ok(script)
}
async fn safety(&self, _: File) -> Result<()> {
self.log.lock().unwrap().push("target.safety".into());
self.safety.run("safety dump").await
}
async fn apply(&self, _: File) -> Result<()> {
self.log.lock().unwrap().push("target.apply".into());
self.apply.run("apply").await
}
}
struct FakeSource(Answer);
#[async_trait]
impl BackupSource for FakeSource {
async fn identity(&self) -> Result<DatabaseIdentity> {
self.0.clone().map_err(|why| anyhow::anyhow!(why))
}
}
struct FakeHub {
log: Log,
/// Queue of claim replies; empty means "nothing to restore".
claims: Mutex<VecDeque<String>>,
download: Step,
upload: Step,
/// A request whose path ends with this fails (the response is "lost").
fail_path: Option<&'static str>,
/// Reports with this progress fail (used to break heartbeats).
fail_progress: Option<&'static str>,
}
impl FakeHub {
fn new(log: &Log) -> Self {
Self {
log: log.clone(),
claims: Mutex::default(),
download: Step::Ok,
upload: Step::Ok,
fail_path: None,
fail_progress: None,
}
}
}
#[async_trait]
impl RestoreHub for FakeHub {
async fn send(
&self,
path: String,
body: serde_json::Value,
restore: Option<Uuid>,
) -> Result<String> {
if path.ends_with("/claim") {
return Ok(self
.claims
.lock()
.unwrap()
.pop_front()
.unwrap_or_else(|| "null".into()));
}
if path.ends_with("/apply") {
assert!(restore.is_some(), "the apply permit needs the lease token");
self.log.lock().unwrap().push("hub.apply-permit".into());
} else {
let progress = body.as_str().unwrap_or("?").to_owned();
self.log.lock().unwrap().push(format!("report:{progress}"));
if self.fail_progress == Some(progress.as_str()) {
anyhow::bail!("hub unreachable");
}
}
if self.fail_path.is_some_and(|suffix| path.ends_with(suffix)) {
anyhow::bail!("response lost");
}
Ok(String::new())
}
async fn send_with_reason(
&self,
_: String,
body: serde_json::Value,
_: Uuid,
reason: Option<String>,
) -> Result<String> {
self.log.lock().unwrap().push(format!(
"failed:{}:{}",
body.as_str().unwrap_or("?"),
reason.unwrap_or_default()
));
Ok(String::new())
}
async fn upload_safety(&self, _: &RestoreLease, _: File, _: Duration) -> Result<()> {
self.log.lock().unwrap().push("hub.safety-upload".into());
self.upload.run("upload").await
}
async fn download(&self, _: &RestoreLease, _: Duration) -> Result<File> {
self.log.lock().unwrap().push("hub.download".into());
self.download.run("download").await?;
Ok(tempfile::tempfile()?)
}
}
const SHORT: Duration = Duration::from_millis(60);
struct Outcome {
result: Result<()>,
log: Vec<String>,
}
impl Outcome {
fn did(&self, event: &str) -> bool {
self.log.iter().any(|entry| entry == event)
}
fn failed(&self, progress: &str) -> Option<&str> {
self.log
.iter()
.find_map(|entry| entry.strip_prefix(&format!("failed:{progress}:")))
}
/// The agent never reached the destructive step.
fn never_applied(&self) -> bool {
!self.did("hub.apply-permit") && !self.did("target.apply")
}
}
async fn drive(
lease: &RestoreLease,
log: &Log,
hub: FakeHub,
target: FakeTarget,
source: Option<FakeSource>,
) -> Outcome {
let result = run(
&hub,
lease,
&target,
source.as_ref(),
SHORT,
&AtomicBool::new(false),
)
.await;
let log = log.lock().unwrap().clone();
Outcome { result, log }
}
fn log() -> Log {
Log::default()
}
#[tokio::test]
async fn full_restore_runs_in_order_and_reports_applied() {
let log = log();
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
None,
)
.await;
out.result.as_ref().unwrap();
let steps: Vec<&str> = out
.log
.iter()
.map(String::as_str)
.filter(|entry| *entry != "target.identity")
.collect();
assert_eq!(
steps,
[
"report:checking",
"hub.download",
"target.prepare",
"report:safety",
"target.safety",
"hub.safety-upload",
"hub.apply-permit",
"target.apply",
"report:applied",
]
);
}
// ---- safety capture: nothing destructive may happen unless the safety copy is stored ----
#[tokio::test]
async fn safety_dump_failure_never_applies() {
let log = log();
let mut target = FakeTarget::new(&log);
target.safety = Step::Fail;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out
.failed("safety_failed")
.unwrap()
.contains("safety dump exploded"));
assert!(!out.did("hub.safety-upload"));
}
#[tokio::test]
async fn safety_upload_failure_never_applies() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.upload = Step::Fail;
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out
.failed("safety_failed")
.unwrap()
.contains("upload exploded"));
}
#[tokio::test]
async fn target_changed_during_safety_capture_never_applies() {
let log = log();
// Verified as the expected target, then a different database answers after the dump.
let target =
FakeTarget::new(&log).identities(vec![Ok(target_identity()), Ok(source_identity())]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out
.failed("safety_failed")
.unwrap()
.contains("target changed during safety capture"));
assert!(
!out.did("hub.safety-upload"),
"a dump of the wrong database must not be stored"
);
}
#[tokio::test]
async fn target_unreachable_after_safety_capture_never_applies() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Ok(target_identity()), Err("gone")]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.never_applied());
assert!(out.failed("safety_failed").is_some());
}
// ---- identity checks ----
#[tokio::test]
async fn identity_mismatch_refuses_before_any_dump() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "other"))]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("wrong_target")
.unwrap()
.contains("identity does not match"));
assert!(out.never_applied());
assert!(
!out.did("target.safety"),
"must refuse before touching the target"
);
assert!(!out.did("report:safety"));
}
#[tokio::test]
async fn identity_probe_error_is_a_wrong_target() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Err("connection refused")]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("wrong_target")
.unwrap()
.contains("connection refused"));
assert!(out.never_applied());
}
#[tokio::test]
async fn restoring_a_backup_onto_its_own_source_database_is_refused() {
let log = log();
let mut lease = lease();
lease.artifact.identity = target_identity(); // artifact was taken from the target itself
let out = drive(
&lease,
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
None,
)
.await;
out.result.as_ref().unwrap();
assert!(out.failed("wrong_target").is_some());
assert!(out.never_applied());
}
#[tokio::test]
async fn rollback_may_restore_onto_the_database_the_copy_came_from() {
let log = log();
let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true);
assert_eq!(lease.artifact.identity, lease.job.target.identity);
let out = drive(
&lease,
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
None,
)
.await;
out.result.as_ref().unwrap();
assert!(out.did("report:applied"));
}
#[tokio::test]
async fn rollback_still_requires_the_target_identity_to_match() {
let log = log();
let lease = lease_for(Uuid::new_v4(), Uuid::new_v4(), true);
let target = FakeTarget::new(&log).identities(vec![Ok(identity("1", "impostor"))]);
let out = drive(&lease, &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out.failed("wrong_target").is_some());
assert!(out.never_applied());
}
#[tokio::test]
async fn target_that_is_the_local_backup_source_is_refused() {
let log = log();
let source = FakeSource(Ok(target_identity()));
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
Some(source),
)
.await;
out.result.as_ref().unwrap();
assert!(out
.failed("wrong_target")
.unwrap()
.contains("target resolves to the local backup source"));
assert!(out.never_applied());
}
#[tokio::test]
async fn a_different_local_source_does_not_block_a_restore() {
let log = log();
let source = FakeSource(Ok(source_identity()));
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
Some(source),
)
.await;
out.result.as_ref().unwrap();
assert!(out.did("report:applied"));
}
/// Documented as designed: the source guard is best effort. If the local source cannot be identified (its
/// probe errors), the restore proceeds on the strength of the target identity checks alone.
#[tokio::test]
async fn unidentifiable_local_source_does_not_block_a_restore() {
let log = log();
let source = FakeSource(Err("source down"));
let out = drive(
&lease(),
&log,
FakeHub::new(&log),
FakeTarget::new(&log),
Some(source),
)
.await;
out.result.as_ref().unwrap();
assert!(out.did("report:applied"));
}
// ---- per-step timeouts map to their own failure state, and never reach apply ----
#[tokio::test]
async fn download_timeout_is_invalid_payload() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.download = Step::Hang;
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("invalid_payload"), Some("timed out"));
assert!(out.never_applied());
assert!(!out.did("target.safety"));
}
#[tokio::test]
async fn prepare_timeout_is_invalid_payload() {
let log = log();
let mut target = FakeTarget::new(&log);
target.prepare = Step::Hang;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("invalid_payload"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn prepare_error_is_invalid_payload_with_its_reason() {
let log = log();
let mut target = FakeTarget::new(&log);
target.prepare = Step::Fail;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("invalid_payload")
.unwrap()
.contains("prepare exploded"));
assert!(out.never_applied());
}
#[tokio::test]
async fn identity_check_timeout_is_wrong_target() {
let log = log();
let mut target = FakeTarget::new(&log);
target.hang_identity = true;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("wrong_target"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn safety_dump_timeout_is_safety_failed() {
let log = log();
let mut target = FakeTarget::new(&log);
target.safety = Step::Hang;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("safety_failed"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn safety_upload_timeout_is_safety_failed() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.upload = Step::Hang;
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("safety_failed"), Some("timed out"));
assert!(out.never_applied());
}
#[tokio::test]
async fn apply_timeout_is_apply_failed_after_the_permit() {
let log = log();
let mut target = FakeTarget::new(&log);
target.apply = Step::Hang;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("apply_failed"), Some("timed out"));
assert!(out.did("hub.apply-permit") && out.did("target.apply"));
assert!(!out.did("report:applied"));
}
#[tokio::test]
async fn apply_error_is_apply_failed_with_its_reason() {
let log = log();
let mut target = FakeTarget::new(&log);
target.apply = Step::Fail;
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert!(out
.failed("apply_failed")
.unwrap()
.contains("apply exploded"));
assert!(!out.did("report:applied"));
}
// ---- the permit ----
/// The permit is single-use and the agent does not retry it. If the response is lost (or the hub refuses),
/// `run` returns the error WITHOUT applying and without reporting anything further: the hub has consumed
/// (or may have consumed) the permit, so the target stays locked until the hub reconciles the lease.
#[tokio::test]
async fn lost_apply_permit_response_does_not_apply_and_leaves_the_lease_for_reconciliation() {
let log = log();
let mut hub = FakeHub::new(&log);
hub.fail_path = Some("/apply");
let out = drive(&lease(), &log, hub, FakeTarget::new(&log), None).await;
assert!(out
.result
.as_ref()
.unwrap_err()
.to_string()
.contains("response lost"));
assert!(out.did("hub.apply-permit"));
assert!(
!out.did("target.apply"),
"no permit response, no destructive step"
);
assert_eq!(out.log.last().map(String::as_str), Some("hub.apply-permit"));
assert!(out
.log
.iter()
.all(|e| !e.starts_with("failed:") && e != "report:applied"));
}
/// Agent dies (or is cancelled) after the permit but before the restore finishes. The hub has seen the
/// permit but never a terminal report, so the lease is left mid-flight for the hub to expire.
#[tokio::test]
async fn crash_between_permit_and_apply_leaves_no_terminal_report() {
let log = log();
let hub = FakeHub::new(&log);
let mut target = FakeTarget::new(&log);
target.apply = Step::Hang;
let lease = lease();
let crashed = tokio::time::timeout(
Duration::from_millis(200),
run(
&hub,
&lease,
&target,
None::<&FakeSource>,
Duration::from_secs(30),
&AtomicBool::new(false),
),
)
.await;
assert!(crashed.is_err(), "the run was dropped mid-apply");
let log = log.lock().unwrap().clone();
assert!(log.contains(&"hub.apply-permit".to_owned()));
assert!(log.contains(&"target.apply".to_owned()));
assert!(log
.iter()
.all(|e| e != "report:applied" && !e.starts_with("failed:")));
}
#[tokio::test]
async fn failure_reasons_are_cleaned_before_they_are_reported() {
let log = log();
let target = FakeTarget::new(&log).identities(vec![Err("line one\nline\ttwo \u{1F4A5}")]);
let out = drive(&lease(), &log, FakeHub::new(&log), target, None).await;
out.result.as_ref().unwrap();
assert_eq!(out.failed("wrong_target"), Some("line one line two ?"));
}
// ---- poll ----
fn poll_fixture(
log: &Log,
lease: &RestoreLease,
target_id: Uuid,
) -> (FakeHub, HashMap<Uuid, FakeTarget>) {
let hub = FakeHub::new(log);
hub.claims
.lock()
.unwrap()
.push_back(serde_json::to_string(lease).unwrap());
let targets = HashMap::from([(target_id, FakeTarget::new(log))]);
(hub, targets)
}
#[tokio::test]
async fn poll_with_nothing_to_claim_does_nothing() {
let log = log();
let hub = FakeHub::new(&log);
let targets = HashMap::from([(Uuid::new_v4(), FakeTarget::new(&log))]);
let did = poll(
&hub,
Uuid::new_v4(),
None::<&FakeSource>,
&targets,
1,
SHORT,
)
.await
.unwrap();
assert!(!did);
assert!(log.lock().unwrap().is_empty());
}
#[tokio::test]
async fn poll_refuses_a_lease_for_another_target_or_application() {
for swap_target in [true, false] {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = if swap_target {
lease_for(Uuid::new_v4(), application, false)
} else {
lease_for(target_id, Uuid::new_v4(), false)
};
let (hub, targets) = poll_fixture(&log, &lease, target_id);
let err = poll(&hub, application, None::<&FakeSource>, &targets, 1, SHORT)
.await
.unwrap_err();
assert!(err.to_string().contains("unexpected restore target"));
assert!(
log.lock().unwrap().is_empty(),
"nothing may run for a mismatched lease"
);
}
}
#[tokio::test]
async fn poll_runs_a_matching_lease() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (hub, targets) = poll_fixture(&log, &lease, target_id);
let did = poll(
&hub,
application,
None::<&FakeSource>,
&targets,
5,
Duration::from_secs(60),
)
.await
.unwrap();
assert!(did);
assert!(log.lock().unwrap().contains(&"report:applied".to_owned()));
}
/// Before the apply permit nothing destructive has happened, so a failed heartbeat gives up on the lease
/// (the hub will expire it) rather than carrying on unobserved.
#[tokio::test]
async fn failed_heartbeat_before_the_permit_abandons_the_restore() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (mut hub, targets) = poll_fixture(&log, &lease, target_id);
hub.fail_progress = Some("heartbeat");
hub.download = Step::Hang;
let err = tokio::time::timeout(
Duration::from_secs(5),
poll(
&hub,
application,
None::<&FakeSource>,
&targets,
30,
Duration::from_millis(50),
),
)
.await
.expect("poll returns once the heartbeat fails")
.unwrap_err();
assert!(err.to_string().contains("hub unreachable"));
let log = log.lock().unwrap().clone();
assert!(log.contains(&"hub.download".to_owned()));
assert!(log.iter().all(|e| e != "hub.apply-permit"
&& e != "target.apply"
&& e != "report:applied"
&& !e.starts_with("failed:")));
}
/// After the permit is spent, dropping the restore would kill the apply half way (its children are
/// `kill_on_drop`). A failed heartbeat is only logged and the apply runs to its terminal report.
#[tokio::test]
async fn failed_heartbeat_after_the_permit_lets_the_apply_finish() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id);
hub.fail_progress = Some("heartbeat");
targets.get_mut(&target_id).unwrap().apply = Step::Slow(300);
let did = tokio::time::timeout(
Duration::from_secs(5),
poll(
&hub,
application,
None::<&FakeSource>,
&targets,
30,
Duration::from_millis(50),
),
)
.await
.expect("poll finishes")
.unwrap();
assert!(did);
let log = log.lock().unwrap().clone();
let beats = log.iter().filter(|e| *e == "report:heartbeat").count();
assert!(beats >= 2, "heartbeats kept being attempted: {beats}");
assert_eq!(log.last().map(String::as_str), Some("report:applied"));
}
/// If the apply itself fails while heartbeats are failing, the failure is still reported.
#[tokio::test]
async fn failed_apply_is_still_reported_when_heartbeats_fail() {
let log = log();
let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4());
let lease = lease_for(target_id, application, false);
let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id);
hub.fail_progress = Some("heartbeat");
targets.get_mut(&target_id).unwrap().apply = Step::Hang;
let err = tokio::time::timeout(
Duration::from_secs(5),
poll(
&hub,
application,
None::<&FakeSource>,
&targets,
1,
Duration::from_millis(50),
),
)
.await
.expect("apply timeout ends the poll")
.unwrap();
assert!(err);
let log = log.lock().unwrap().clone();
assert!(log.iter().any(|e| e.starts_with("failed:apply_failed:")));
}

View File

@@ -3,6 +3,7 @@ name = "tessera-cli"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[[bin]]
name = "tessera"
@@ -14,6 +15,10 @@ tessera-store = { path = "../tessera-store" }
tessera-demo = { path = "../tessera-demo" }
tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true
chrono.workspace = true
tempfile.workspace = true
sha2.workspace = true
hex.workspace = true
clap.workspace = true
serde.workspace = true
serde_json.workspace = true

View File

@@ -1,6 +1,6 @@
use anyhow::{Context, Result};
use std::io::{Read, Write};
use std::net::TcpStream;
use std::net::{IpAddr, TcpStream};
pub fn get(url: &str) -> Result<String> {
request("GET", url, None, None)
@@ -11,10 +11,34 @@ pub fn post_json(url: &str, body: &serde_json::Value) -> Result<String> {
request("POST", url, Some(&payload), Some("application/json"))
}
fn request(method: &str, url: &str, body: Option<&str>, content_type: Option<&str>) -> Result<String> {
pub fn put_json(url: &str, body: &serde_json::Value) -> Result<()> {
let payload = serde_json::to_string(body)?;
request("PUT", url, Some(&payload), Some("application/json"))?;
Ok(())
}
fn request(
method: &str,
url: &str,
body: Option<&str>,
content_type: Option<&str>,
) -> Result<String> {
let (host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
if let Ok(token) = std::env::var("TESSERA_ADMIN_TOKEN") {
let token = token.trim();
if !token.is_empty() {
anyhow::ensure!(
host == "localhost" || host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback()),
"the HTTP CLI requires a loopback hub URL when using an admin token"
);
anyhow::ensure!(
token.bytes().all(|byte| byte.is_ascii_graphic()),
"invalid admin token"
);
req.push_str(&format!("Authorization: Bearer {token}\r\n"));
}
}
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some(ct) = content_type {
@@ -25,11 +49,23 @@ fn request(method: &str, url: &str, body: Option<&str>, content_type: Option<&st
} else {
req.push_str("\r\n");
}
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0);
Ok(buf[body_start..].trim().to_string())
let (headers, body) = buf.split_once("\r\n\r\n").context("invalid hub response")?;
let status = headers
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.context("missing hub response status")?
.parse::<u16>()?;
anyhow::ensure!(
(200..300).contains(&status),
"hub returned HTTP {status}: {}",
body.trim()
);
Ok(body.trim().to_string())
}
fn parse_url(url: &str) -> Result<(String, u16, String)> {

View File

@@ -0,0 +1,787 @@
use anyhow::{ensure, Context, Result};
use chrono::{DateTime, Utc};
use clap::{Args, ValueEnum};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::{self, Read, Seek, SeekFrom},
path::PathBuf,
process::{Command, Stdio},
};
use tessera_core::SnapshotManifest;
use tessera_store::Vault;
use uuid::Uuid;
#[derive(Args, Clone)]
pub struct ImportArgs {
#[arg(long)]
bucket: String,
#[arg(long)]
prefix: String,
#[arg(long)]
endpoint: Option<String>,
#[arg(long)]
orbit_id: Uuid,
#[arg(long)]
application: String,
#[arg(long, value_enum)]
engine: Engine,
/// Consistent SQLite export of the old service's job history.
#[arg(long)]
history: Option<PathBuf>,
/// Reconcile counts, times and sizes without downloading or writing snapshots.
#[arg(long)]
inventory_only: bool,
/// The AWS CLI to run; a field only so tests can substitute a fake one.
#[arg(skip = PathBuf::from("aws"))]
program: PathBuf,
}
#[derive(Clone, Copy, ValueEnum)]
enum Engine {
Postgres,
Mysql,
}
impl Engine {
fn name(self) -> &'static str {
match self {
Self::Postgres => "postgres",
Self::Mysql => "mysql",
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Listing {
#[serde(default)]
contents: Vec<Object>,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all(deserialize = "PascalCase"))]
struct Object {
key: String,
#[serde(rename(deserialize = "ETag"))]
etag: String,
size: u64,
last_modified: DateTime<Utc>,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Downloaded {
#[serde(rename = "ETag")]
etag: String,
content_length: u64,
last_modified: DateTime<Utc>,
}
#[derive(Serialize)]
struct Entry {
snapshot_id: Uuid,
#[serde(flatten)]
object: Object,
status: &'static str,
}
#[derive(Serialize)]
struct Report {
application: String,
bucket: String,
prefix: String,
count: usize,
bytes: u64,
history_snapshot_id: Option<Uuid>,
objects: Vec<Entry>,
}
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
let report = reconcile(vault, args)?;
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
}
fn reconcile(vault: &Vault, args: ImportArgs) -> Result<Report> {
ensure!(
!args.prefix.is_empty() && args.prefix.ends_with('/'),
"provide a per-application prefix ending in '/'"
);
ensure!(
!args.application.trim().is_empty()
&& args.application.len() <= 128
&& !args.application.chars().any(char::is_control),
"invalid application name"
);
if let Some(endpoint) = &args.endpoint {
ensure!(
(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:"))
&& !endpoint.contains(['@', '?', '#', '\r', '\n']),
"use an HTTPS S3 endpoint without embedded credentials"
);
}
let output = aws(&args, "list-objects-v2")
.arg(format!("--prefix={}", args.prefix))
.output()
.context("run AWS CLI S3 inventory")?;
ensure!(
output.status.success(),
"could not list legacy S3 objects ({})",
output.status
);
let listing: Listing =
serde_json::from_slice(&output.stdout).context("parse legacy S3 inventory")?;
let mut objects = Vec::new();
let mut bytes = 0u64;
for object in listing.contents {
if !object.key.starts_with(&args.prefix)
|| !(object.key.ends_with(".sql") || object.key.ends_with(".sql.gz"))
{
continue;
}
ensure!(
object.size > 0 && !object.etag.is_empty() && object.etag != "*",
"invalid legacy archive metadata"
);
bytes = bytes
.checked_add(object.size)
.context("legacy inventory byte count overflow")?;
let key = serde_json::to_vec(&(
"s3-legacy",
&args.endpoint,
&args.bucket,
&object.key,
&object.etag,
object.size,
object.last_modified,
args.orbit_id,
))?;
let snapshot_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, &key);
let status = if args.inventory_only {
"inventoried"
} else if vault.legacy_import_exists(snapshot_id)? {
"already_imported"
} else if import_object(vault, &args, &object, snapshot_id)? {
"imported"
} else {
"already_imported"
};
objects.push(Entry {
snapshot_id,
object,
status,
});
}
let history_snapshot_id = if args.inventory_only {
None
} else {
args.history
.as_ref()
.map(|path| import_history(vault, path))
.transpose()?
};
Ok(Report {
application: args.application,
bucket: args.bucket,
prefix: args.prefix,
count: objects.len(),
bytes,
history_snapshot_id,
objects,
})
}
fn aws(args: &ImportArgs, operation: &str) -> Command {
let mut cmd = Command::new(&args.program);
cmd.args([
"--no-cli-pager",
"--no-cli-auto-prompt",
"--output",
"json",
"s3api",
operation,
])
.arg(format!("--bucket={}", args.bucket))
.stdin(Stdio::null())
.stderr(Stdio::null());
if let Some(endpoint) = &args.endpoint {
cmd.arg(format!("--endpoint-url={endpoint}"));
}
cmd
}
fn import_object(vault: &Vault, args: &ImportArgs, object: &Object, id: Uuid) -> Result<bool> {
let file = tempfile::NamedTempFile::new()?;
let output = aws(args, "get-object")
.arg(format!("--key={}", object.key))
.arg(format!("--if-match={}", object.etag))
.arg(file.path())
.output()
.context("run conditional AWS CLI S3 download")?;
ensure!(
output.status.success(),
"legacy archive download failed ({})",
output.status
);
let received: Downloaded =
serde_json::from_slice(&output.stdout).context("parse downloaded object metadata")?;
ensure!(
received.etag == object.etag
&& received.last_modified == object.last_modified
&& received.content_length == object.size
&& file.as_file().metadata()?.len() == object.size,
"legacy object changed since inventory"
);
let mut file = file.reopen()?;
let format = if object.key.ends_with(".sql.gz") {
let mut signature = [0; 2];
file.read_exact(&mut signature)?;
ensure!(
signature == [0x1f, 0x8b],
"legacy archive is missing a gzip header"
);
file.seek(SeekFrom::Start(0))?;
"sql_gzip"
} else {
"plain"
};
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: args.orbit_id,
orbit_name: args.application.clone(),
provider: args.engine.name().into(),
labels: vec!["legacy-import".into()],
paths: vec![],
restore_hints: serde_json::json!({
"format": format, "legacy": { "bucket": args.bucket, "key": object.key,
"etag": object.etag, "bytes": object.size, "last_modified": object.last_modified }
}),
};
vault.import_legacy_payload(manifest, file, object.last_modified)
}
fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
let mut original = File::open(path).context("open legacy history export")?;
let mut signature = [0; 16];
original.read_exact(&mut signature)?;
ensure!(
&signature == b"SQLite format 3\0",
"legacy history must be a consistent SQLite export"
);
original.seek(SeekFrom::Start(0))?;
let mut staged = tempfile::tempfile()?;
let bytes = io::copy(&mut original, &mut staged)?;
staged.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
io::copy(&mut staged, &mut digest)?;
let checksum = hex::encode(digest.finalize());
let key = format!("legacy-history:{checksum}");
let id = Uuid::new_v5(&Uuid::NAMESPACE_URL, key.as_bytes());
let taken_at: DateTime<Utc> = original.metadata()?.modified()?.into();
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: Uuid::nil(),
orbit_name: "Legacy operator history".into(),
provider: "legacy-history".into(),
labels: vec!["legacy-history".into()],
paths: vec![],
restore_hints: serde_json::json!({"format": "sqlite", "sha256": checksum, "legacy_bytes": bytes}),
};
vault.import_legacy_payload(manifest, staged, taken_at)?;
Ok(id)
}
/// These drive `reconcile` against a stand-in `aws` (a shell script that serves a local directory), so the
/// listing, conditional download, receipts and history paths all run for real; only S3 is faked.
#[cfg(all(test, unix))]
mod tests {
use super::*;
use serde_json::{json, Value};
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
const ETAG: &str = "\"9b2cf535f27731c974343645a3985328\"";
const WHEN: &str = "2026-01-02T03:04:05+00:00";
struct Fixture {
dir: tempfile::TempDir,
vault: Vault,
listing: Vec<Value>,
}
impl Fixture {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let vault = Vault::init(dir.path().join("vault"), "synthetic-passphrase").unwrap();
let fake = dir.path().join("fake");
fs::create_dir_all(fake.join("obj")).unwrap();
fs::create_dir_all(fake.join("meta")).unwrap();
let script = format!(
r#"#!/bin/sh
D='{}'
op="$6"
echo "$op" >> "$D/calls"
case "$op" in
list-objects-v2)
[ -f "$D/list.fail" ] && exit 1
cat "$D/list.json" ;;
get-object)
for a in "$@"; do
last="$a"
case "$a" in --key=*) key="${{a#--key=}}" ;; esac
done
name=$(basename "$key")
[ -f "$D/get.fail.$name" ] && exit 1
cp "$D/obj/$name" "$last"
cat "$D/meta/$name.json" ;;
esac
"#,
fake.display()
);
let program = dir.path().join("aws");
fs::write(&program, script).unwrap();
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
let fixture = Self {
dir,
vault,
listing: vec![],
};
fixture.publish();
fixture
}
fn fake(&self) -> std::path::PathBuf {
self.dir.path().join("fake")
}
fn publish(&self) {
fs::write(
self.fake().join("list.json"),
json!({ "Contents": self.listing }).to_string(),
)
.unwrap();
}
/// Put an object in the listing and on the fake bucket, with matching download metadata.
fn add(&mut self, key: &str, body: &[u8]) {
self.add_listed(key, body, body.len() as u64, ETAG);
let name = key.rsplit('/').next().unwrap();
fs::write(self.fake().join("obj").join(name), body).unwrap();
self.meta(key, ETAG, body.len() as u64, WHEN);
}
/// Only the listing entry, for metadata the object itself would not match.
fn add_listed(&mut self, key: &str, _body: &[u8], size: u64, etag: &str) {
self.listing.push(json!({
"Key": key, "ETag": etag, "Size": size, "LastModified": WHEN
}));
self.publish();
}
fn meta(&self, key: &str, etag: &str, length: u64, modified: &str) {
let name = key.rsplit('/').next().unwrap();
fs::write(
self.fake().join("meta").join(format!("{name}.json")),
json!({"ETag": etag, "ContentLength": length, "LastModified": modified})
.to_string(),
)
.unwrap();
}
fn calls(&self) -> Vec<String> {
fs::read_to_string(self.fake().join("calls"))
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
fn args(&self) -> ImportArgs {
ImportArgs {
bucket: "legacy-bucket".into(),
prefix: "backups/shop/".into(),
endpoint: None,
orbit_id: Uuid::from_u128(7),
application: "shop".into(),
engine: Engine::Postgres,
history: None,
inventory_only: false,
program: self.dir.path().join("aws"),
}
}
fn run(&self, args: ImportArgs) -> Result<Report> {
reconcile(&self.vault, args)
}
fn snapshots(&self) -> usize {
self.vault.list_snapshots().unwrap().len()
}
fn receipts(&self) -> usize {
fs::read_dir(self.vault.root().join("keys/legacy-imports"))
.map(|entries| entries.count())
.unwrap_or(0)
}
}
fn gzip_header(rest: &[u8]) -> Vec<u8> {
[&[0x1f, 0x8b][..], rest].concat()
}
fn statuses(report: &Report) -> Vec<&'static str> {
report.objects.iter().map(|o| o.status).collect()
}
// ---- arguments are validated before anything is listed ----
#[test]
fn bad_arguments_are_refused_before_aws_is_run() {
let fx = Fixture::new();
type Tweak = fn(&mut ImportArgs);
let cases: [(&str, Tweak); 11] = [
("empty prefix", |a| a.prefix = String::new()),
("prefix without a trailing slash", |a| {
a.prefix = "backups/shop".into()
}),
("blank application", |a| a.application = " ".into()),
("long application", |a| a.application = "a".repeat(129)),
("control in application", |a| {
a.application = "sh\nop".into()
}),
("plain http endpoint", |a| {
a.endpoint = Some("http://s3.example.com".into())
}),
("http on another loopback port form", |a| {
a.endpoint = Some("http://localhost:9000".into())
}),
("credentials in the endpoint", |a| {
a.endpoint = Some("https://user:pw@s3.example.com".into())
}),
("query in the endpoint", |a| {
a.endpoint = Some("https://s3.example.com/?x=1".into())
}),
("fragment in the endpoint", |a| {
a.endpoint = Some("https://s3.example.com/#x".into())
}),
("newline in the endpoint", |a| {
a.endpoint = Some("https://s3.example.com/\nx".into())
}),
];
for (what, tweak) in cases {
let mut args = fx.args();
tweak(&mut args);
assert!(fx.run(args).is_err(), "{what} must be refused");
}
assert!(fx.calls().is_empty(), "aws was never run");
let mut ok = fx.args();
ok.endpoint = Some("http://127.0.0.1:9000".into());
assert!(fx.run(ok).is_ok(), "a local test endpoint is allowed");
let mut ok = fx.args();
ok.endpoint = Some("https://s3.example.com".into());
assert!(fx.run(ok).is_ok());
}
// ---- inventory ----
#[test]
fn inventory_counts_only_sql_archives_under_the_prefix_and_writes_nothing() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"select 1;");
fx.add("backups/shop/b.sql.gz", &gzip_header(b"zz"));
fx.add("backups/shop/readme.txt", b"not a dump");
fx.add("backups/shop/nested/c.sql", b"select 3;");
fx.add("backups/shop/d.sql.bak", b"select 4;");
fx.add("backups/other/e.sql", b"another application");
fx.add("backups/shopping/f.sql", b"prefix lookalike");
let mut args = fx.args();
args.inventory_only = true;
let report = fx.run(args).unwrap();
assert_eq!(report.count, 3, "a, b and nested/c");
assert_eq!(report.bytes, 9 + 4 + 9);
assert_eq!(statuses(&report), ["inventoried"; 3]);
assert!(report.history_snapshot_id.is_none());
assert_eq!(fx.snapshots(), 0);
assert_eq!(fx.receipts(), 0);
assert_eq!(fx.calls(), ["list-objects-v2"], "no object was downloaded");
}
#[test]
fn inventory_only_ignores_a_history_export() {
let fx = Fixture::new();
let history = fx.dir.path().join("history.sqlite");
fs::write(&history, b"SQLite format 3\0 rows").unwrap();
let mut args = fx.args();
args.inventory_only = true;
args.history = Some(history);
let report = fx.run(args).unwrap();
assert!(report.history_snapshot_id.is_none());
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn an_empty_or_missing_listing_is_a_clean_zero() {
let fx = Fixture::new();
let report = fx.run(fx.args()).unwrap();
assert_eq!((report.count, report.bytes), (0, 0));
fs::write(fx.fake().join("list.json"), "{}").unwrap();
assert_eq!(fx.run(fx.args()).unwrap().count, 0);
}
#[test]
fn listing_failures_stop_the_run() {
let fx = Fixture::new();
fs::write(fx.fake().join("list.fail"), "").unwrap();
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("could not list"), "{err:#}");
fs::remove_file(fx.fake().join("list.fail")).unwrap();
for broken in [
"",
"not json",
r#"{"Contents":[{"Key":"x"}]}"#,
r#"{"Contents":"x"}"#,
] {
fs::write(fx.fake().join("list.json"), broken).unwrap();
assert!(fx.run(fx.args()).is_err(), "listing {broken:?}");
}
let missing = ImportArgs {
program: fx.dir.path().join("no-such-aws"),
..fx.args()
};
assert!(fx.run(missing).is_err(), "no aws binary is an error");
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn untrustworthy_inventory_metadata_is_refused() {
for (size, etag) in [(0, ETAG), (5, ""), (5, "*")] {
let mut fx = Fixture::new();
fx.add_listed("backups/shop/a.sql", b"", size, etag);
let err = fx.run(fx.args()).err().unwrap();
assert!(
format!("{err:#}").contains("invalid legacy archive metadata"),
"size {size} etag {etag:?}: {err:#}"
);
assert_eq!(fx.snapshots(), 0);
}
}
#[test]
fn an_inventory_whose_sizes_overflow_is_refused() {
let mut fx = Fixture::new();
fx.add_listed("backups/shop/a.sql", b"", u64::MAX, ETAG);
fx.add_listed("backups/shop/b.sql", b"", 2, "\"other\"");
let mut args = fx.args();
args.inventory_only = true;
let err = fx.run(args).err().unwrap();
assert!(format!("{err:#}").contains("overflow"), "{err:#}");
}
// ---- import ----
#[test]
fn importing_stores_each_archive_once_and_a_rerun_changes_nothing() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
fx.add("backups/shop/b.sql.gz", &gzip_header(b"compressed"));
let first = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&first), ["imported", "imported"]);
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
let stored = fx
.vault
.get_snapshot(first.objects[0].snapshot_id)
.unwrap()
.expect("stored under the reported id");
assert_eq!(stored.manifest.orbit_id, Uuid::from_u128(7));
assert_eq!(stored.manifest.orbit_name, "shop");
assert_eq!(stored.manifest.provider, "postgres");
assert_eq!(stored.manifest.labels, ["legacy-import"]);
assert_eq!(stored.manifest.restore_hints["format"], "plain");
assert_eq!(stored.manifest.restore_hints["legacy"]["etag"], ETAG);
let gz = fx
.vault
.get_snapshot(first.objects[1].snapshot_id)
.unwrap()
.unwrap();
assert_eq!(gz.manifest.restore_hints["format"], "sql_gzip");
assert_eq!(
stored.taken_at,
"2026-01-02T03:04:05Z".parse::<DateTime<Utc>>().unwrap(),
"the snapshot keeps the original time, not the import time"
);
let calls_before = fx.calls().len();
let second = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&second), ["already_imported", "already_imported"]);
assert_eq!(
fx.calls().len(),
calls_before + 1,
"the rerun listed but downloaded nothing"
);
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
assert_eq!(
first.objects[0].snapshot_id, second.objects[0].snapshot_id,
"ids are derived, so a rerun finds its own work"
);
}
#[test]
fn the_engine_orbit_and_endpoint_decide_the_mysql_manifest_and_the_snapshot_id() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
let mut mysql = fx.args();
mysql.engine = Engine::Mysql;
let first = fx.run(mysql).unwrap();
let stored = fx
.vault
.get_snapshot(first.objects[0].snapshot_id)
.unwrap()
.unwrap();
assert_eq!(stored.manifest.provider, "mysql");
// another orbit is a different import of the same bytes, not a duplicate
let mut other = fx.args();
other.orbit_id = Uuid::from_u128(8);
let second = fx.run(other).unwrap();
assert_ne!(first.objects[0].snapshot_id, second.objects[0].snapshot_id);
assert_eq!(statuses(&second), ["imported"]);
// so is another endpoint
let mut elsewhere = fx.args();
elsewhere.endpoint = Some("https://s3.example.com".into());
let third = fx.run(elsewhere).unwrap();
assert_ne!(first.objects[0].snapshot_id, third.objects[0].snapshot_id);
assert_eq!(fx.snapshots(), 3);
}
#[test]
fn an_object_that_changed_since_the_inventory_is_not_imported() {
for (what, etag, length, modified) in [
("etag", "\"changed\"", 17, WHEN),
("length", ETAG, 18, WHEN),
("time", ETAG, 17, "2026-01-02T03:04:06+00:00"),
] {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
fx.meta("backups/shop/a.sql", etag, length, modified);
let err = fx.run(fx.args()).err().unwrap();
assert!(
format!("{err:#}").contains("changed since inventory"),
"{what}: {err:#}"
);
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0), "{what}");
}
}
#[test]
fn a_downloaded_file_of_the_wrong_size_is_not_imported() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
// the metadata agrees with the listing but fewer bytes arrived
fs::write(fx.fake().join("obj/a.sql"), b"create").unwrap();
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("changed since inventory"));
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn a_gzip_named_archive_must_start_with_the_gzip_signature() {
let mut fx = Fixture::new();
fx.add("backups/shop/b.sql.gz", b"plainly not gzip");
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("gzip header"), "{err:#}");
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0));
// a one-byte file cannot even hold the signature
let mut tiny = Fixture::new();
tiny.add("backups/shop/t.sql.gz", &[0x1f]);
assert!(tiny.run(tiny.args()).is_err());
assert_eq!(tiny.snapshots(), 0);
}
#[test]
fn a_plain_sql_archive_is_not_inspected_for_a_signature() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", &gzip_header(b"gz bytes in a .sql"));
let report = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&report), ["imported"]);
}
#[test]
fn a_failed_download_stops_the_run_and_a_retry_resumes_where_it_left_off() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
fx.add("backups/shop/b.sql", b"create table b();");
fs::write(fx.fake().join("get.fail.b.sql"), "").unwrap();
let err = fx.run(fx.args()).err().unwrap();
assert!(format!("{err:#}").contains("download failed"), "{err:#}");
assert_eq!((fx.snapshots(), fx.receipts()), (1, 1), "a was kept");
fs::remove_file(fx.fake().join("get.fail.b.sql")).unwrap();
let retry = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&retry), ["already_imported", "imported"]);
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
}
#[test]
fn a_receipt_keeps_an_archive_from_returning_after_its_snapshot_is_forgotten() {
let mut fx = Fixture::new();
fx.add("backups/shop/a.sql", b"create table a();");
let first = fx.run(fx.args()).unwrap();
let id = first.objects[0].snapshot_id;
assert!(fx.vault.legacy_import_exists(id).unwrap());
fx.vault.forget(&[id]).unwrap();
assert_eq!(fx.snapshots(), 0);
let again = fx.run(fx.args()).unwrap();
assert_eq!(statuses(&again), ["already_imported"]);
assert_eq!(fx.snapshots(), 0, "retention's decision is not undone");
}
// ---- the operator-history export ----
#[test]
fn a_history_export_must_be_a_sqlite_file() {
let fx = Fixture::new();
let write = |name: &str, bytes: &[u8]| {
let path = fx.dir.path().join(name);
fs::write(&path, bytes).unwrap();
path
};
for (name, bytes) in [
("empty", &b""[..]),
("short", b"SQLite"),
("text", b"just a text file, long enough to read"),
("near", b"SQLite format 3 not-nul-terminated"),
("wal", b"SQLite format 4\0 later version"),
] {
let mut args = fx.args();
args.history = Some(write(name, bytes));
assert!(fx.run(args).is_err(), "{name} must be refused");
}
let mut missing = fx.args();
missing.history = Some(Path::new("/definitely/not/here.sqlite").into());
assert!(fx.run(missing).is_err());
assert_eq!(fx.snapshots(), 0);
}
#[test]
fn a_history_export_is_stored_once_and_identified_by_its_content() {
let fx = Fixture::new();
let path = fx.dir.path().join("history.sqlite");
fs::write(&path, b"SQLite format 3\0 first export").unwrap();
let mut args = fx.args();
args.history = Some(path.clone());
let first = fx.run(args.clone()).unwrap();
let id = first.history_snapshot_id.expect("history imported");
assert_eq!(fx.snapshots(), 1);
let stored = fx.vault.get_snapshot(id).unwrap().unwrap();
assert_eq!(stored.manifest.provider, "legacy-history");
assert_eq!(stored.manifest.orbit_id, Uuid::nil());
assert_eq!(stored.manifest.restore_hints["format"], "sqlite");
// same bytes: same snapshot, nothing new stored
let second = fx.run(args.clone()).unwrap();
assert_eq!(second.history_snapshot_id, Some(id));
assert_eq!(fx.snapshots(), 1);
// different bytes: a different snapshot
fs::write(&path, b"SQLite format 3\0 second export").unwrap();
let third = fx.run(args).unwrap();
assert_ne!(third.history_snapshot_id, Some(id));
assert_eq!(fx.snapshots(), 2);
}
}

View File

@@ -1,7 +1,9 @@
mod http;
mod legacy_import;
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use clap::{Args, Parser, Subcommand};
use tessera_core::decay::RetentionPolicy;
use tessera_store::Vault;
use uuid::Uuid;
@@ -12,8 +14,9 @@ struct Cli {
command: Commands,
#[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")]
data_dir: String,
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE", default_value = "dev-vault-key")]
vault_pass: String,
/// Required for vault commands. No default; the published example passphrase is rejected for new vaults.
#[arg(long, env = "TESSERA_VAULT_PASSPHRASE")]
vault_pass: Option<String>,
#[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")]
hub_url: String,
}
@@ -32,12 +35,29 @@ enum Commands {
schedule: Option<String>,
#[arg(long)]
dry_run: bool,
#[command(flatten)]
retention: RetentionArgs,
},
/// Change an orbit's retention for future captures.
Retention {
orbit_id: Uuid,
#[arg(long)]
preset: Option<String>,
#[command(flatten)]
counts: RetentionArgs,
},
Snap {
#[arg(long)]
orbit: Option<String>,
},
List,
/// Reconcile and import immutable legacy SQL archives from an S3 prefix.
LegacyImport(legacy_import::ImportArgs),
/// Export the private legacy operator-history SQLite archive.
LegacyHistory {
snapshot_id: Uuid,
output: String,
},
Reconstitute {
snapshot_id: Uuid,
target: String,
@@ -46,6 +66,8 @@ enum Commands {
#[arg(long, default_value = "week-of-dailies")]
preset: String,
},
/// Reclaim unreferenced data from expired Restic snapshots.
Gc,
Wormhole {
#[command(subcommand)]
cmd: WormholeCmd,
@@ -61,6 +83,45 @@ enum Commands {
},
}
#[derive(Args, Clone)]
struct RetentionArgs {
#[arg(long)]
keep_daily: Option<u32>,
#[arg(long)]
keep_weekly: Option<u32>,
#[arg(long)]
keep_monthly: Option<u32>,
#[arg(long)]
keep_yearly: Option<u32>,
}
impl RetentionArgs {
fn policy(self) -> Result<Option<RetentionPolicy>> {
if [
self.keep_daily,
self.keep_weekly,
self.keep_monthly,
self.keep_yearly,
]
.iter()
.all(Option::is_none)
{
return Ok(None);
}
let policy = RetentionPolicy {
keep_daily: self.keep_daily.unwrap_or(0),
keep_weekly: self.keep_weekly.unwrap_or(0),
keep_monthly: self.keep_monthly.unwrap_or(0),
keep_yearly: self.keep_yearly.unwrap_or(0),
};
anyhow::ensure!(
policy.has_tiers(),
"set at least one retention count above zero"
);
Ok(Some(policy))
}
}
#[derive(Subcommand, Clone)]
enum WormholeCmd {
Pair {
@@ -82,14 +143,61 @@ fn main() -> Result<()> {
path,
schedule,
dry_run,
} => cmd_orbit(&cli, name, provider, path, schedule, dry_run)?,
retention,
} => cmd_orbit(
&cli,
name,
provider,
path,
schedule,
dry_run,
retention.policy()?,
)?,
Commands::Retention {
orbit_id,
preset,
counts,
} => {
let retention = counts.policy()?;
anyhow::ensure!(
preset.is_some() != retention.is_some(),
"choose --preset or custom --keep-* counts"
);
http::put_json(
&format!("{}/api/v1/orbits/{orbit_id}/retention", cli.hub_url),
&serde_json::json!({ "decay_preset": preset, "retention": retention }),
)?;
println!("Retention saved for {orbit_id}.");
}
Commands::Snap { orbit } => cmd_snap(&cli, orbit)?,
Commands::List => cmd_list(&cli)?,
Commands::LegacyImport(args) => {
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
legacy_import::run(&vault, args)?;
}
Commands::LegacyHistory {
snapshot_id,
output,
} => {
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
let snapshot = vault
.get_snapshot(snapshot_id)?
.context("legacy history archive not found")?;
anyhow::ensure!(
snapshot.manifest.provider == "legacy-history",
"snapshot is not a legacy history archive"
);
vault.restore_snapshot(snapshot_id, std::path::Path::new(&output))?;
println!("Exported legacy history {snapshot_id}");
}
Commands::Reconstitute {
snapshot_id,
target,
} => cmd_reconstitute(&cli, snapshot_id, target)?,
Commands::Decay { preset } => cmd_decay(&cli, &preset)?,
Commands::Gc => {
Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?.collect_garbage()?
}
Commands::Wormhole { ref cmd } => match cmd {
WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?,
},
@@ -98,14 +206,24 @@ fn main() -> Result<()> {
Ok(())
}
fn require_passphrase(cli: &Cli) -> Result<&str> {
match cli.vault_pass.as_deref() {
Some(pass) if !pass.is_empty() => Ok(pass),
_ => anyhow::bail!(
"Set TESSERA_VAULT_PASSPHRASE or pass --vault-pass. Tessera does not ship a default passphrase."
),
}
}
fn cmd_seed_demo(cli: &Cli, force: bool, reset: bool) -> Result<()> {
let data = std::path::Path::new(&cli.data_dir);
let vault_pass = require_passphrase(cli)?;
if reset {
tessera_demo::clear_demo(data, &cli.vault_pass)?;
tessera_demo::clear_demo(data, vault_pass)?;
println!("Demo seed cleared.");
return Ok(());
}
let report = tessera_demo::apply(data, &cli.vault_pass, force)?;
let report = tessera_demo::apply(data, vault_pass, force)?;
if report.skipped {
println!(
"Demo seed already applied ({} orbits, {} snapshots). Use --force to re-seed.",
@@ -130,7 +248,7 @@ fn cmd_init(cli: &Cli) -> Result<()> {
println!("Vault already initialized.");
return Ok(());
}
Vault::init(&vp, &cli.vault_pass).context("init vault")?;
Vault::init(&vp, require_passphrase(cli)?).context("init vault")?;
println!("Vault initialized at {}", vp.display());
Ok(())
}
@@ -142,7 +260,7 @@ fn cmd_status(cli: &Cli) -> Result<()> {
}
let vp = vault_path(&cli.data_dir);
if vp.join("config").exists() {
let vault = Vault::open(&vp, &cli.vault_pass)?;
let vault = Vault::open(&vp, require_passphrase(cli)?)?;
let n = vault.list_snapshots()?.len();
println!("Vault: online — {n} snapshots");
} else {
@@ -158,10 +276,20 @@ fn cmd_orbit(
path: Option<String>,
schedule: Option<String>,
dry_run: bool,
retention: Option<RetentionPolicy>,
) -> Result<()> {
let config = match provider.as_str() {
"filesystem" => serde_json::json!({ "paths": [path.unwrap_or_else(|| ".".into())] }),
"postgres" => serde_json::json!({ "connection_url": path.context("--path or connection url required")? }),
"postgres" => {
serde_json::json!({ "connection_url": path.context("--path or connection url required")? })
}
"wormhole" => {
anyhow::ensure!(
path.is_none() && schedule.is_none() && !dry_run,
"Wormhole paths and scheduling are set on the outpost"
);
serde_json::json!({})
}
_ => anyhow::bail!("unknown provider"),
};
let body = serde_json::json!({
@@ -170,6 +298,7 @@ fn cmd_orbit(
"provider_config": config,
"schedule": schedule,
"dry_run": dry_run,
"retention": retention,
});
let raw = http::post_json(&format!("{}/api/v1/orbits", cli.hub_url), &body)?;
let orbit: serde_json::Value = serde_json::from_str(&raw)?;
@@ -197,28 +326,33 @@ fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
}
fn cmd_list(cli: &Cli) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
for s in vault.list_snapshots()? {
let stored = s
.stored_bytes
.map(|n| format!(" +{n} bytes stored"))
.unwrap_or_default();
println!(
"{} {} {} bytes orbit={}",
"{} {} {} bytes orbit={}{}",
s.taken_at.to_rfc3339(),
s.id,
s.size_bytes,
s.manifest.orbit_name
s.manifest.orbit_name,
stored,
);
}
Ok(())
}
fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?;
println!("Reconstituted {n} bytes to {target}");
Ok(())
}
fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> {
let mut vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?;
let mut vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
let pruned = vault.prune_with_decay(preset)?;
println!("{} snapshots decayed.", pruned.len());
Ok(())

View File

@@ -3,6 +3,7 @@ name = "tessera-core"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[dependencies]
anyhow.workspace = true

View File

@@ -18,7 +18,7 @@ pub struct HubConfig {
impl Default for HubConfig {
fn default() -> Self {
Self {
listen: "0.0.0.0:8787".into(),
listen: "127.0.0.1:8787".into(),
data_dir: "./data".into(),
admin_password_hash: None,
}

View File

@@ -1,5 +1,6 @@
use chrono::{DateTime, Utc};
use chrono::{DateTime, Datelike, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -42,6 +43,154 @@ pub struct SnapshotRef {
pub taken_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RetentionPolicy {
pub keep_daily: u32,
pub keep_weekly: u32,
pub keep_monthly: u32,
pub keep_yearly: u32,
}
impl RetentionPolicy {
pub fn has_tiers(&self) -> bool {
*self != Self::default()
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum CaptureRetention {
Age {
days: u16,
},
Count {
#[serde(default = "fallback_count")]
keep: u16,
},
}
fn fallback_count() -> u16 {
5
}
impl Default for CaptureRetention {
fn default() -> Self {
Self::Age { days: 14 }
}
}
impl CaptureRetention {
pub fn is_valid(self) -> bool {
match self {
Self::Age { days } => days > 0,
Self::Count { keep } => keep > 0,
}
}
}
pub fn evaluate_capture_retention(
policy: CaptureRetention,
mut snapshots: Vec<SnapshotRef>,
now: DateTime<Utc>,
) -> Vec<Uuid> {
snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id)));
snapshots
.into_iter()
.enumerate()
.skip(1)
.filter_map(|(index, snapshot)| {
let expired = match policy {
CaptureRetention::Age { days } => {
now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days)
}
CaptureRetention::Count { keep } => index >= usize::from(keep),
};
expired.then_some(snapshot.id)
})
.collect()
}
/// A restore safety copy, for its own retention.
#[derive(Debug, Clone)]
pub struct SafetyRef {
pub id: Uuid,
pub taken_at: DateTime<Utc>,
pub target: String,
}
/// Safety copies kept per restore target regardless of age.
pub const SAFETY_KEEP_PER_TARGET: usize = 3;
/// Safety copies younger than this are always kept, however many there are.
pub const SAFETY_KEEP_DAYS: i64 = 7;
/// Which safety copies to forget. Each target keeps its newest few and everything from the last week, so the
/// newest copy of a target is never forgotten here, and a burst of restores cannot erase the way back from
/// the previous one. (A copy that a restore still depends on is protected separately, by the caller.)
pub fn evaluate_safety_retention(snapshots: Vec<SafetyRef>, now: DateTime<Utc>) -> Vec<Uuid> {
let mut targets: std::collections::BTreeMap<String, Vec<SafetyRef>> = Default::default();
for snapshot in snapshots {
targets
.entry(snapshot.target.clone())
.or_default()
.push(snapshot);
}
let mut forget = Vec::new();
for (_, mut copies) in targets {
copies.sort_unstable_by_key(|s| std::cmp::Reverse((s.taken_at, s.id)));
for (index, copy) in copies.into_iter().enumerate() {
let recent = now.signed_duration_since(copy.taken_at).num_days() < SAFETY_KEEP_DAYS;
if index >= SAFETY_KEEP_PER_TARGET && !recent {
forget.push(copy.id);
}
}
}
forget
}
/// Keep the newest snapshot in each of the most recent occupied UTC periods.
pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> {
if !policy.has_tiers() {
return Vec::new();
}
snapshots.sort_unstable_by_key(|s| std::cmp::Reverse((s.taken_at, s.id)));
let mut keep = HashSet::new();
keep_periods(&snapshots, &mut keep, policy.keep_daily, |at| {
at.date_naive()
});
keep_periods(&snapshots, &mut keep, policy.keep_weekly, |at| {
at.iso_week()
});
keep_periods(&snapshots, &mut keep, policy.keep_monthly, |at| {
(at.year(), at.month())
});
keep_periods(&snapshots, &mut keep, policy.keep_yearly, |at| at.year());
snapshots
.into_iter()
.filter_map(|s| (!keep.contains(&s.id)).then_some(s.id))
.collect()
}
fn keep_periods<K: PartialEq>(
snapshots: &[SnapshotRef],
keep: &mut HashSet<Uuid>,
mut count: u32,
period: impl Fn(DateTime<Utc>) -> K,
) {
let mut last = None;
for s in snapshots {
if count == 0 {
break;
}
let key = period(s.taken_at);
if last.as_ref() != Some(&key) {
keep.insert(s.id);
count -= 1;
last = Some(key);
}
}
}
/// Returns snapshot IDs to forget (newest-first input).
pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> {
snapshots.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
@@ -75,7 +224,10 @@ pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec<SnapshotRef>) ->
let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new();
for s in &snapshots {
let key = (s.taken_at.year(), s.taken_at.month());
if let Some(pos) = months.iter().position(|(y, m, _)| *y == key.0 && *m == key.1) {
if let Some(pos) = months
.iter()
.position(|(y, m, _)| *y == key.0 && *m == key.1)
{
if s.taken_at > months[pos].2.taken_at {
months[pos] = (key.0, key.1, s.clone());
}
@@ -96,12 +248,114 @@ pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec<SnapshotRef>) ->
.collect()
}
use chrono::Datelike;
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
use chrono::{Duration, TimeZone, Timelike};
#[test]
fn capture_retention_keeps_one_old_archive_or_the_latest_five() {
let now = Utc::now();
let snapshots: Vec<_> = (0..6)
.map(|i| SnapshotRef {
id: Uuid::new_v4(),
taken_at: now - Duration::days(15 + i),
})
.collect();
assert_eq!(
evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now),
snapshots[1..]
.iter()
.map(|snap| snap.id)
.collect::<Vec<_>>()
);
assert_eq!(
evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now),
[snapshots[5].id]
);
}
#[test]
fn gfs_keeps_the_newest_in_each_period_and_combines_tiers() {
let policy = RetentionPolicy {
keep_daily: 7,
keep_weekly: 2,
keep_monthly: 6,
keep_yearly: 3,
};
let newest = Utc.with_ymd_and_hms(2026, 1, 17, 20, 0, 0).unwrap();
let snapshots: Vec<_> = (0..1460)
.rev()
.flat_map(|day| {
[
newest - Duration::days(day) - Duration::hours(12),
newest - Duration::days(day),
]
.map(|taken_at| SnapshotRef {
id: Uuid::new_v4(),
taken_at,
})
})
.collect();
let expired: std::collections::HashSet<_> = evaluate_gfs(&policy, snapshots.clone())
.into_iter()
.collect();
let kept: Vec<_> = snapshots
.iter()
.filter(|s| !expired.contains(&s.id))
.collect();
let dates: Vec<_> = kept
.iter()
.map(|s| s.taken_at.date_naive().to_string())
.collect();
assert_eq!(
dates,
[
"2024-12-31",
"2025-08-31",
"2025-09-30",
"2025-10-31",
"2025-11-30",
"2025-12-31",
"2026-01-11",
"2026-01-12",
"2026-01-13",
"2026-01-14",
"2026-01-15",
"2026-01-16",
"2026-01-17"
]
);
assert!(kept.iter().all(|s| s.taken_at.hour() == 20));
}
#[test]
fn gfs_weeks_start_monday_and_skip_empty_weeks() {
let sunday = Utc.with_ymd_and_hms(2025, 1, 5, 23, 0, 0).unwrap();
let snapshots: Vec<_> = [-49, -1, 0, 1]
.map(|hours| SnapshotRef {
id: Uuid::new_v4(),
taken_at: sunday + Duration::hours(hours),
})
.into();
let policy = RetentionPolicy {
keep_weekly: 2,
..RetentionPolicy::default()
};
assert_eq!(
evaluate_gfs(&policy, snapshots.clone()),
[snapshots[1].id, snapshots[0].id]
);
let sparse = vec![
snapshots[3].clone(),
SnapshotRef {
id: snapshots[0].id,
taken_at: sunday - Duration::weeks(3),
},
];
assert!(evaluate_gfs(&policy, sparse).is_empty());
assert!(evaluate_gfs(&RetentionPolicy::default(), snapshots).is_empty());
}
#[test]
fn keeps_n_dailies() {
@@ -116,4 +370,469 @@ mod tests {
let forget = evaluate_decay(&policy, snaps);
assert_eq!(forget.len(), 3);
}
fn safety(day: u32, target: &str) -> SafetyRef {
SafetyRef {
id: Uuid::new_v4(),
taken_at: Utc.with_ymd_and_hms(2026, 11, day, 4, 0, 0).unwrap(),
target: target.into(),
}
}
#[test]
fn safety_snapshots_keep_the_newest_few_per_target_and_anything_recent() {
let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap();
let old: Vec<_> = (1..=6).map(|d| safety(d, "staging")).collect(); // all older than a week
let recent = safety(28, "staging");
let mut all = old.clone();
all.push(recent.clone());
let forgotten = evaluate_safety_retention(all, now);
// newest three overall (recent, day 6, day 5) stay; days 1..=4 go
assert_eq!(forgotten.len(), 4);
assert!(!forgotten.contains(&recent.id));
assert!(!forgotten.contains(&old[5].id) && !forgotten.contains(&old[4].id));
assert!(old[..4].iter().all(|s| forgotten.contains(&s.id)));
}
#[test]
fn a_recent_safety_snapshot_is_never_forgotten_even_beyond_the_count() {
let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap();
let burst: Vec<_> = (24..=29).map(|d| safety(d, "staging")).collect(); // six in the last week
assert!(evaluate_safety_retention(burst, now).is_empty());
}
#[test]
fn targets_are_counted_separately_and_each_keeps_at_least_its_newest() {
let now = Utc.with_ymd_and_hms(2027, 6, 1, 0, 0, 0).unwrap(); // everything is very old
let all = vec![safety(1, "staging"), safety(2, "staging"), safety(1, "dev")];
let forgotten = evaluate_safety_retention(all.clone(), now);
assert!(
forgotten.is_empty(),
"three or fewer per target are always kept"
);
let many: Vec<_> = (1..=5)
.map(|d| safety(d, "staging"))
.chain([safety(1, "dev")])
.collect();
let forgotten = evaluate_safety_retention(many.clone(), now);
assert_eq!(forgotten.len(), 2);
assert!(
!forgotten.contains(&many[5].id),
"the only snapshot of another target stays"
);
}
#[test]
fn a_manifest_knows_whether_it_is_a_restore_safety_copy() {
let mut manifest = crate::manifest::SnapshotManifest {
snapshot_id: Uuid::nil(),
orbit_id: Uuid::nil(),
orbit_name: "x".into(),
labels: vec!["postgres".into()],
provider: "postgres".into(),
paths: vec![],
restore_hints: serde_json::json!({"job_id": "j"}),
};
assert!(!manifest.is_restore_safety());
manifest.labels = vec!["restore-safety".into()];
assert!(manifest.is_restore_safety());
manifest.labels = vec![];
manifest.restore_hints = serde_json::json!({"safety_for": "job", "target_id": "t"});
assert!(manifest.is_restore_safety());
assert_eq!(manifest.safety_target().as_deref(), Some("t"));
}
// ---- boundaries ----
fn at(y: i32, mo: u32, d: u32, h: u32, mi: u32, sec: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(y, mo, d, h, mi, sec).unwrap()
}
fn snap(taken_at: DateTime<Utc>) -> SnapshotRef {
SnapshotRef {
id: Uuid::new_v4(),
taken_at,
}
}
#[test]
fn capture_age_boundary_is_a_whole_number_of_days() {
let now = at(2026, 11, 20, 12, 0, 0);
let newest = snap(now);
let exactly = snap(now - Duration::days(14));
let just_under = snap(now - Duration::days(14) + Duration::seconds(1));
let policy = CaptureRetention::Age { days: 14 };
let forgotten = evaluate_capture_retention(
policy,
vec![just_under.clone(), exactly.clone(), newest.clone()],
now,
);
assert_eq!(forgotten, [exactly.id], "14 days old to the second goes");
}
#[test]
fn capture_retention_never_forgets_the_newest_even_when_ancient_or_in_the_future() {
let now = at(2026, 11, 20, 12, 0, 0);
for policy in [
CaptureRetention::Age { days: 1 },
CaptureRetention::Count { keep: 1 },
] {
let only = snap(now - Duration::days(4000));
assert!(evaluate_capture_retention(policy, vec![only], now).is_empty());
// a snapshot stamped in the future (clock skew) has negative age and is never expired
let future = snap(now + Duration::days(3));
let old = snap(now - Duration::days(30));
assert_eq!(
evaluate_capture_retention(policy, vec![old.clone(), future], now),
[old.id]
);
}
assert!(evaluate_capture_retention(CaptureRetention::default(), vec![], now).is_empty());
}
#[test]
fn capture_count_boundaries() {
let now = at(2026, 11, 20, 12, 0, 0);
let snaps: Vec<_> = (0..4).map(|i| snap(now - Duration::hours(i))).collect();
let count = |keep| {
evaluate_capture_retention(CaptureRetention::Count { keep }, snaps.clone(), now).len()
};
assert_eq!(count(1), 3);
assert_eq!(count(3), 1);
assert_eq!(count(4), 0, "keeping exactly as many as exist forgets none");
assert_eq!(count(u16::MAX), 0);
// keep 0 is rejected by validation, but must still not forget the newest if it slips through
assert!(!CaptureRetention::Count { keep: 0 }.is_valid());
assert!(!CaptureRetention::Age { days: 0 }.is_valid());
let forgotten =
evaluate_capture_retention(CaptureRetention::Count { keep: 0 }, snaps.clone(), now);
assert!(!forgotten.contains(&snaps[0].id));
}
#[test]
fn equal_timestamps_are_ordered_by_id_so_the_outcome_is_deterministic() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut twins = vec![snap(now), snap(now), snap(now)];
let keep_one = CaptureRetention::Count { keep: 1 };
let first = evaluate_capture_retention(keep_one, twins.clone(), now);
twins.reverse();
let second = evaluate_capture_retention(keep_one, twins, now);
assert_eq!(set(&first), set(&second));
assert_eq!(first.len(), 2);
}
#[test]
fn safety_age_boundary_is_seven_whole_days() {
let now = at(2026, 11, 30, 12, 0, 0);
let copy = |age: Duration| SafetyRef {
id: Uuid::new_v4(),
taken_at: now - age,
target: "t".into(),
};
// three fresh copies fill the per-target quota, so age alone decides for the next two
let pad: Vec<_> = (1..=3).map(|i| copy(Duration::hours(i))).collect();
let exactly_seven = copy(Duration::days(7));
let just_under = copy(Duration::days(7) - Duration::seconds(1));
let forgotten = evaluate_safety_retention(
pad.into_iter()
.chain([exactly_seven.clone(), just_under.clone()])
.collect(),
now,
);
assert_eq!(
forgotten,
[exactly_seven.id],
"exactly 7 days old is no longer recent; one second less still is"
);
}
#[test]
fn safety_retention_handles_empty_and_a_lone_ancient_copy() {
let now = at(2030, 1, 1, 0, 0, 0);
assert!(evaluate_safety_retention(vec![], now).is_empty());
assert!(evaluate_safety_retention(vec![safety(1, "only")], now).is_empty());
}
#[test]
fn gfs_period_boundaries_are_utc_midnight_iso_weeks_and_calendar_years() {
let daily = RetentionPolicy {
keep_daily: 2,
..Default::default()
};
let last_second = snap(at(2025, 12, 31, 23, 59, 59));
let first_second = snap(at(2026, 1, 1, 0, 0, 0));
let earlier = snap(at(2025, 12, 31, 0, 0, 0));
// 23:59:59 and 00:00:00 straddle a day, so both days count and each keeps its newest
assert_eq!(
evaluate_gfs(
&daily,
vec![earlier.clone(), last_second.clone(), first_second.clone()]
),
[earlier.id]
);
// ISO weeks: Sun 2024-12-29 is week 52; Mon 2024-12-30 and Wed 2025-01-01 are week 1 of 2025
let weekly = RetentionPolicy {
keep_weekly: 2,
..Default::default()
};
let sunday = snap(at(2024, 12, 29, 12, 0, 0));
let monday = snap(at(2024, 12, 30, 0, 0, 0));
let wednesday = snap(at(2025, 1, 1, 12, 0, 0));
assert_eq!(
evaluate_gfs(&weekly, vec![sunday, monday.clone(), wednesday]),
[monday.id]
);
// ISO week 53 of 2020 spans the new year
let a = snap(at(2020, 12, 31, 1, 0, 0));
let b = snap(at(2021, 1, 1, 1, 0, 0));
let one_week = RetentionPolicy {
keep_weekly: 1,
..Default::default()
};
assert_eq!(evaluate_gfs(&one_week, vec![a.clone(), b]), [a.id]);
let yearly = RetentionPolicy {
keep_yearly: 1,
..Default::default()
};
assert_eq!(
evaluate_gfs(&yearly, vec![first_second.clone(), last_second.clone()]),
[last_second.id]
);
// the same month number in another year is a different month
let monthly = RetentionPolicy {
keep_monthly: 2,
..Default::default()
};
let jan25 = snap(at(2025, 1, 15, 0, 0, 0));
let jan26 = snap(at(2026, 1, 15, 0, 0, 0));
let jan26_early = snap(at(2026, 1, 2, 0, 0, 0));
assert_eq!(
evaluate_gfs(&monthly, vec![jan25, jan26, jan26_early.clone()]),
[jan26_early.id]
);
}
#[test]
fn gfs_edge_inputs() {
let all_tiers = RetentionPolicy {
keep_daily: 3,
keep_weekly: 3,
keep_monthly: 3,
keep_yearly: 3,
};
assert!(evaluate_gfs(&all_tiers, vec![]).is_empty());
assert!(evaluate_gfs(&all_tiers, vec![snap(at(2020, 2, 29, 0, 0, 0))]).is_empty());
// all tiers zero means no policy, which keeps everything rather than forgetting everything
let many: Vec<_> = (1..=5).map(|d| snap(at(2026, 1, d, 0, 0, 0))).collect();
assert!(evaluate_gfs(&RetentionPolicy::default(), many.clone()).is_empty());
let huge = RetentionPolicy {
keep_daily: u32::MAX,
keep_weekly: u32::MAX,
keep_monthly: u32::MAX,
keep_yearly: u32::MAX,
};
assert!(evaluate_gfs(&huge, many).is_empty());
}
// ---- properties, over seeded pseudo-random histories (no extra dependency) ----
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
}
fn history(rng: &mut Rng, now: DateTime<Utc>) -> Vec<SnapshotRef> {
let n = rng.below(60);
(0..n)
.map(|_| {
// about three years at second resolution, with some collisions on whole hours
let secs = rng.below(3 * 365 * 86_400) as i64;
let secs = if rng.below(4) == 0 {
secs - secs % 3600
} else {
secs
};
snap(now - Duration::seconds(secs))
})
.collect()
}
fn random_policy(rng: &mut Rng) -> RetentionPolicy {
RetentionPolicy {
keep_daily: rng.below(10) as u32,
keep_weekly: rng.below(10) as u32,
keep_monthly: rng.below(14) as u32,
keep_yearly: rng.below(5) as u32,
}
}
fn survivors(all: &[SnapshotRef], forgotten: &[Uuid]) -> Vec<SnapshotRef> {
all.iter()
.filter(|s| !forgotten.contains(&s.id))
.cloned()
.collect()
}
fn shuffled(rng: &mut Rng, mut v: Vec<SnapshotRef>) -> Vec<SnapshotRef> {
for i in (1..v.len()).rev() {
v.swap(i, rng.below(i as u64 + 1) as usize);
}
v
}
fn set(ids: &[Uuid]) -> HashSet<Uuid> {
ids.iter().copied().collect()
}
fn newest(all: &[SnapshotRef]) -> Option<&SnapshotRef> {
all.iter().max_by_key(|s| (s.taken_at, s.id))
}
#[test]
fn gfs_properties_hold_for_random_histories() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
for _ in 0..400 {
let all = history(&mut rng, now);
let policy = random_policy(&mut rng);
let forgotten = evaluate_gfs(&policy, all.clone());
let ids: Vec<_> = all.iter().map(|s| s.id).collect();
// only names snapshots it was given, each at most once
assert!(set(&forgotten).is_subset(&set(&ids)));
assert_eq!(set(&forgotten).len(), forgotten.len());
// the newest survives whenever any tier is switched on
if policy.has_tiers() {
if let Some(newest) = newest(&all) {
assert!(!forgotten.contains(&newest.id), "{policy:?}");
}
} else {
assert!(forgotten.is_empty());
}
// input order is irrelevant
let again = evaluate_gfs(&policy, shuffled(&mut rng, all.clone()));
assert_eq!(set(&forgotten), set(&again));
// applying the policy to what is left forgets nothing more
let left = survivors(&all, &forgotten);
assert!(evaluate_gfs(&policy, left).is_empty(), "{policy:?}");
// keeping more of any tier never forgets more
let wider = RetentionPolicy {
keep_daily: policy.keep_daily + rng.below(3) as u32,
keep_weekly: policy.keep_weekly + rng.below(3) as u32,
keep_monthly: policy.keep_monthly + rng.below(3) as u32,
keep_yearly: policy.keep_yearly + rng.below(3) as u32,
};
assert!(set(&evaluate_gfs(&wider, all)).is_subset(&set(&forgotten)));
}
}
#[test]
fn capture_retention_properties_hold_for_random_histories() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut rng = Rng(0xD1B5_4A32_D192_ED03);
for _ in 0..400 {
let all = history(&mut rng, now);
let policy = if rng.below(2) == 0 {
CaptureRetention::Age {
days: 1 + rng.below(400) as u16,
}
} else {
CaptureRetention::Count {
keep: 1 + rng.below(20) as u16,
}
};
let forgotten = evaluate_capture_retention(policy, all.clone(), now);
assert_eq!(set(&forgotten).len(), forgotten.len());
if let Some(newest) = newest(&all) {
assert!(!forgotten.contains(&newest.id));
}
let left = survivors(&all, &forgotten);
assert!(evaluate_capture_retention(policy, left, now).is_empty());
let again = evaluate_capture_retention(policy, shuffled(&mut rng, all.clone()), now);
assert_eq!(set(&forgotten), set(&again));
if let CaptureRetention::Count { keep } = policy {
assert_eq!(
all.len() - forgotten.len(),
all.len().min(usize::from(keep))
);
}
}
}
#[test]
fn safety_retention_properties_hold_for_random_histories() {
let now = at(2026, 11, 30, 12, 0, 0);
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
for _ in 0..400 {
let all: Vec<SafetyRef> = (0..rng.below(30))
.map(|_| SafetyRef {
id: Uuid::new_v4(),
taken_at: now - Duration::seconds(rng.below(60 * 86_400) as i64),
target: format!("t{}", rng.below(3)),
})
.collect();
let forgotten = evaluate_safety_retention(all.clone(), now);
assert_eq!(set(&forgotten).len(), forgotten.len());
for copy in all.iter().filter(|c| forgotten.contains(&c.id)) {
// forgotten means old AND outside its target's newest three
assert!(now.signed_duration_since(copy.taken_at).num_days() >= SAFETY_KEEP_DAYS);
let newer = all
.iter()
.filter(|o| {
o.target == copy.target && (o.taken_at, o.id) > (copy.taken_at, copy.id)
})
.count();
assert!(newer >= SAFETY_KEEP_PER_TARGET);
}
for target in ["t0", "t1", "t2"] {
let newest = all
.iter()
.filter(|c| c.target == target)
.max_by_key(|c| (c.taken_at, c.id));
if let Some(newest) = newest {
assert!(!forgotten.contains(&newest.id));
}
}
let left: Vec<_> = all
.iter()
.filter(|c| !forgotten.contains(&c.id))
.cloned()
.collect();
assert!(evaluate_safety_retention(left, now).is_empty());
}
}
#[test]
fn legacy_decay_properties_hold_for_random_histories() {
let now = at(2026, 11, 20, 12, 0, 0);
let mut rng = Rng(0xA076_1D64_78BD_642F);
for _ in 0..400 {
let all = history(&mut rng, now);
let policy = DecayPolicy {
keep_daily: rng.below(10) as usize,
keep_weekly: rng.below(8) as usize,
keep_monthly: rng.below(14) as usize,
};
let forgotten = evaluate_decay(&policy, all.clone());
assert_eq!(set(&forgotten).len(), forgotten.len());
let ids: Vec<_> = all.iter().map(|s| s.id).collect();
assert!(set(&forgotten).is_subset(&set(&ids)));
if policy.keep_daily + policy.keep_weekly + policy.keep_monthly > 0 {
if let Some(newest) = newest(&all) {
assert!(!forgotten.contains(&newest.id));
}
}
let left = survivors(&all, &forgotten);
assert!(evaluate_decay(&policy, left).is_empty());
}
}
}

View File

@@ -21,9 +21,7 @@ impl TesseraError {
"Another orbit is still circling the vault. Try again when it finishes."
}
TesseraError::WrongPassphrase => "That key doesn't unlock this vault.",
TesseraError::ProviderUnreachable(_) => {
"We couldn't reach the source at this outpost."
}
TesseraError::ProviderUnreachable(_) => "We couldn't reach the source at this outpost.",
TesseraError::DiskFull { .. } => {
"The vault is out of space—free room or widen the hold."
}

View File

@@ -0,0 +1,89 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureFormat {
PostgresCustom,
PostgresSql,
MysqlSql,
Filesystem,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CaptureProfile {
pub application_id: Uuid,
pub orbit_id: Uuid,
pub outpost_id: Uuid,
pub format: CaptureFormat,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schedule: Option<CaptureSchedule>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retention: Option<crate::decay::CaptureRetention>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CaptureSchedule {
pub hour: u8,
#[serde(default)]
pub minute: u8,
pub timezone: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CaptureJob {
pub id: Uuid,
pub profile: CaptureProfile,
pub actor: String,
pub status: String,
pub phase: String,
pub created_at: i64,
pub updated_at: i64,
pub snapshot_id: Option<Uuid>,
pub offsite_status: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureEvent {
pub at: i64,
pub phase: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureLease {
pub job_id: Uuid,
pub profile: CaptureProfile,
pub lease_id: Uuid,
#[serde(default)]
pub restic: bool,
}
pub const CAPTURE_LEASE_SECONDS: i64 = 90;
pub const CAPTURE_HEARTBEAT_SECONDS: u64 = 20;
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureProgress {
Heartbeat,
Dumping,
Uploading,
DumpFailed,
UploadFailed,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureReport {
pub lease_id: Uuid,
pub progress: CaptureProgress,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ResticCaptureCommit {
pub lease_id: Uuid,
pub snapshot_id: String,
pub identity: Option<crate::restore::DatabaseIdentity>,
pub sha256: Option<String>,
}

View File

@@ -1,9 +1,12 @@
pub mod config;
pub mod decay;
pub mod errors;
pub mod job;
pub mod manifest;
pub mod orbit;
pub mod reconstitute;
pub mod restore;
pub mod wormhole;
pub use config::*;

View File

@@ -13,6 +13,23 @@ pub struct SnapshotManifest {
pub restore_hints: serde_json::Value,
}
impl SnapshotManifest {
/// A copy of a restore target's database taken before it was overwritten. It belongs to the target, not
/// to the application's backup history: retention must never weigh it against real captures.
pub fn is_restore_safety(&self) -> bool {
self.labels.iter().any(|label| label == "restore-safety")
|| self.restore_hints.get("safety_for").is_some()
}
/// The restore target a safety copy was taken from.
pub fn safety_target(&self) -> Option<String> {
self.restore_hints
.get("target_id")
.and_then(|id| id.as_str())
.map(str::to_string)
}
}
pub fn manifest_hash(manifest: &SnapshotManifest) -> String {
let json = serde_json::to_vec(manifest).expect("manifest serializes");
let digest = Sha256::digest(&json);

View File

@@ -0,0 +1,137 @@
use crate::job::CaptureFormat;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Engine {
Postgres,
Mysql,
}
impl CaptureFormat {
pub fn engine(self) -> Option<Engine> {
match self {
Self::PostgresCustom | Self::PostgresSql => Some(Engine::Postgres),
Self::MysqlSql => Some(Engine::Mysql),
Self::Filesystem => None,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DatabaseIdentity {
pub instance: String,
pub database: String,
}
impl DatabaseIdentity {
pub fn valid(&self, engine: Engine) -> bool {
let instance_valid = match engine {
Engine::Postgres => self
.instance
.parse::<u64>()
.is_ok_and(|id| id.to_string() == self.instance),
Engine::Mysql => {
Uuid::parse_str(&self.instance).is_ok_and(|id| id.to_string() == self.instance)
}
};
instance_valid
&& (1..=255).contains(&self.database.len())
&& !self.database.chars().any(char::is_control)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RestoreTarget {
pub id: Uuid,
pub application_id: Uuid,
pub outpost_id: Uuid,
pub name: String,
pub engine: Engine,
pub identity: DatabaseIdentity,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RestoreRequest {
pub snapshot_id: Uuid,
pub target_id: Uuid,
pub confirmation: String,
}
impl RestoreRequest {
pub fn confirmation(snapshot: Uuid, target: Uuid) -> String {
format!("RESTORE {snapshot} TO {target}")
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RestoreJob {
pub id: Uuid,
pub snapshot_id: Uuid,
pub target: RestoreTarget,
pub actor: String,
pub status: String,
pub phase: String,
pub safety_snapshot_id: Option<Uuid>,
pub created_at: i64,
pub updated_at: i64,
/// Why the job failed, as the agent reported it (cleaned). Only administrators ever see it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure_reason: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RestoreArtifact {
pub format: CaptureFormat,
pub identity: DatabaseIdentity,
pub sha256: String,
/// The artifact is the safety copy a restore took of the very target it is now restored onto (an undo).
/// Its source identity is then the target's own, so the "target is the source" refusal does not apply.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub rollback: bool,
}
#[derive(Deserialize, Serialize)]
pub struct RestoreLease {
pub job: RestoreJob,
pub token: Uuid,
pub artifact: RestoreArtifact,
}
/// Header on a restore report that carries the reason for a failure.
pub const FAILURE_REASON_HEADER: &str = "x-tessera-failure-reason";
const FAILURE_REASON_MAX: usize = 300;
/// Make a failure reason safe to store, log and send in a header: printable ASCII on one line, at most 300
/// bytes. Anything else becomes a space (control characters) or `?` (non-ASCII). Empty input gives `None`.
pub fn clean_failure_reason(text: &str) -> Option<String> {
let mapped: String = text
.chars()
.map(|c| match c {
c if c.is_ascii_graphic() => c,
c if c.is_ascii() => ' ',
_ => '?',
})
.collect();
let line = mapped.split_whitespace().collect::<Vec<_>>().join(" ");
let line: String = line.chars().take(FAILURE_REASON_MAX).collect();
let line = line.trim_end().to_string();
(!line.is_empty()).then_some(line)
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RestoreProgress {
Heartbeat,
Checking,
Safety,
InvalidPayload,
WrongTarget,
SafetyFailed,
Applied,
ApplyFailed,
}

View File

@@ -18,7 +18,15 @@ pub struct PairingCode {
pub hub_outpost_id: Option<Uuid>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize)]
pub struct OutpostSummary {
pub id: Uuid,
pub name: Option<String>,
pub last_seen: Option<String>,
pub pairing_state: String,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct WormholeCredentials {
pub outpost_id: Uuid,
pub upload_token: String,

View File

@@ -3,6 +3,7 @@ name = "tessera-demo"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[dependencies]
tessera-core = { path = "../tessera-core" }

View File

@@ -31,11 +31,33 @@ struct DemoOrbit {
dry_run: bool,
status: &'static str,
snap_count: usize,
interval_hours: i64,
base_size_kb: u32,
}
impl DemoOrbit {
fn snapshot_age(&self, index: usize) -> Duration {
let since_last_success = if self.status == "failed" {
self.interval_hours * 3
} else {
self.interval_hours / 3
};
let jitter = ((index * 13 + self.slug.len() * 7) % 45) as i64;
Duration::hours(since_last_success + index as i64 * self.interval_hours)
+ Duration::minutes(jitter)
}
fn snapshot_size_kb(&self, index: usize) -> u32 {
let variation = 84 + ((index * 7 + self.slug.len() * 3) % 33) as u32;
self.base_size_kb * variation / 100
}
}
fn demo_id(kind: &str, name: &str) -> Uuid {
Uuid::new_v5(&Uuid::NAMESPACE_OID, format!("{DEMO_NS}:{kind}:{name}").as_bytes())
Uuid::new_v5(
&Uuid::NAMESPACE_OID,
format!("{DEMO_NS}:{kind}:{name}").as_bytes(),
)
}
pub fn apply(data_dir: &Path, vault_pass: &str, force: bool) -> Result<SeedReport> {
@@ -98,8 +120,8 @@ pub fn apply(data_dir: &Path, vault_pass: &str, force: bool) -> Result<SeedRepor
for i in 0..o.snap_count {
let snap_id = demo_id("snap", &format!("{}:{}", o.slug, i));
let taken_at = now - Duration::hours((i as i64 + 1) * 9 + (o.slug.len() as i64 % 5));
let payload = synthetic_payload(o.slug, o.base_size_kb + (i as u32) * 17);
let taken_at = now - o.snapshot_age(i);
let payload = synthetic_payload(o.slug, o.snapshot_size_kb(i));
let manifest = SnapshotManifest {
snapshot_id: snap_id,
orbit_id,
@@ -142,10 +164,7 @@ pub fn clear_demo(data_dir: &Path, vault_pass: &str) -> Result<()> {
let id = demo_id("orbit", o.slug).to_string();
conn.execute("DELETE FROM orbits WHERE id = ?1", params![id])?;
}
conn.execute(
"DELETE FROM outposts WHERE id LIKE 'demo-%'",
[],
)?;
conn.execute("DELETE FROM outposts WHERE id LIKE 'demo-%'", [])?;
}
let vault_path = data_dir.join("vault");
if vault_path.join("config").exists() {
@@ -236,134 +255,174 @@ fn demo_orbits() -> Vec<DemoOrbit> {
DemoOrbit {
slug: "prod-api",
provider: "postgres",
config: serde_json::json!({ "connection_url": "postgres://demo/prod" }),
config: serde_json::json!({ "connection_url": "postgres://postgres.demo.invalid/prod" }),
schedule: "0 2 * * *",
decay: "year-of-monthlies",
dry_run: false,
status: "completed",
snap_count: 4,
base_size_kb: 420,
snap_count: 24,
interval_hours: 24,
base_size_kb: 2560,
},
DemoOrbit {
slug: "wiki",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/data/wiki"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/wiki"] }),
schedule: "0 3 * * *",
decay: "week-of-dailies",
dry_run: false,
status: "completed",
snap_count: 3,
base_size_kb: 88,
snap_count: 14,
interval_hours: 24,
base_size_kb: 256,
},
DemoOrbit {
slug: "gitea",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/var/gitea"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/gitea"] }),
schedule: "0 1 * * *",
decay: "month-of-weeklies",
dry_run: false,
status: "running",
snap_count: 3,
base_size_kb: 220,
snap_count: 18,
interval_hours: 24,
base_size_kb: 1024,
},
DemoOrbit {
slug: "monitoring",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/etc/prometheus", "/var/lib/grafana"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/prometheus", "/_tessera_demo/grafana"] }),
schedule: "0 */6 * * *",
decay: "week-of-dailies",
dry_run: false,
status: "completed",
snap_count: 3,
base_size_kb: 64,
snap_count: 28,
interval_hours: 6,
base_size_kb: 96,
},
DemoOrbit {
slug: "staging-db",
provider: "postgres",
config: serde_json::json!({ "connection_url": "postgres://demo/staging" }),
config: serde_json::json!({ "connection_url": "postgres://postgres.demo.invalid/staging" }),
schedule: "0 4 * * 0",
decay: "week-of-dailies",
dry_run: false,
status: "failed",
snap_count: 2,
base_size_kb: 310,
snap_count: 8,
interval_hours: 168,
base_size_kb: 640,
},
DemoOrbit {
slug: "legal-docs",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/vault/legal"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/legal"] }),
schedule: "0 0 * * 1",
decay: "year-of-monthlies",
dry_run: false,
status: "completed",
snap_count: 2,
base_size_kb: 1200,
snap_count: 12,
interval_hours: 168,
base_size_kb: 3072,
},
DemoOrbit {
slug: "matrix-synapse",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/var/matrix"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/matrix"] }),
schedule: "0 2 * * *",
decay: "month-of-weeklies",
dry_run: false,
status: "completed",
snap_count: 3,
base_size_kb: 540,
snap_count: 16,
interval_hours: 24,
base_size_kb: 768,
},
DemoOrbit {
slug: "home-assistant",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/config"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/home-assistant"] }),
schedule: "0 */12 * * *",
decay: "week-of-dailies",
dry_run: false,
status: "completed",
snap_count: 2,
base_size_kb: 45,
snap_count: 21,
interval_hours: 12,
base_size_kb: 64,
},
DemoOrbit {
slug: "deno-api",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/app/deno"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/deno"] }),
schedule: "0 5 * * *",
decay: "week-of-dailies",
dry_run: false,
status: "completed",
snap_count: 3,
base_size_kb: 96,
snap_count: 14,
interval_hours: 24,
base_size_kb: 192,
},
DemoOrbit {
slug: "mail-archive",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/mail/archive"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/mail"] }),
schedule: "0 3 * * 6",
decay: "year-of-monthlies",
dry_run: false,
status: "completed",
snap_count: 2,
base_size_kb: 890,
status: "failed",
snap_count: 12,
interval_hours: 168,
base_size_kb: 1792,
},
DemoOrbit {
slug: "rehearse-nightly",
provider: "filesystem",
config: serde_json::json!({ "paths": ["/tmp/rehearse"] }),
config: serde_json::json!({ "paths": ["/_tessera_demo/rehearse"] }),
schedule: "0 2 * * *",
decay: "week-of-dailies",
dry_run: true,
status: "rehearsed",
snap_count: 0,
interval_hours: 24,
base_size_kb: 0,
},
DemoOrbit {
slug: "observability-pg",
provider: "postgres",
config: serde_json::json!({ "connection_url": "postgres://demo/metrics" }),
config: serde_json::json!({ "connection_url": "postgres://postgres.demo.invalid/metrics" }),
schedule: "0 1 * * *",
decay: "month-of-weeklies",
dry_run: false,
status: "completed",
snap_count: 3,
base_size_kb: 180,
snap_count: 18,
interval_hours: 24,
base_size_kb: 896,
},
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn demo_history_has_volume_and_preserves_capture_cadence() {
let orbits = demo_orbits();
assert_eq!(orbits.iter().filter(|orbit| !orbit.dry_run).count(), 11);
assert!(orbits.iter().map(|orbit| orbit.snap_count).sum::<usize>() >= 180);
for orbit in orbits {
if orbit.dry_run {
assert_eq!(orbit.snap_count, 0);
continue;
}
assert!(orbit.snapshot_age(0) > Duration::zero());
for index in 1..orbit.snap_count {
let gap = orbit.snapshot_age(index) - orbit.snapshot_age(index - 1);
assert!(
(gap - Duration::hours(orbit.interval_hours))
.num_minutes()
.abs()
< 45
);
}
}
}
}

View File

@@ -3,6 +3,7 @@ name = "tessera-hub"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[[bin]]
name = "tessera-hub"
@@ -14,8 +15,10 @@ tessera-store = { path = "../tessera-store" }
tessera-providers = { path = "../tessera-providers" }
tessera-demo = { path = "../tessera-demo" }
anyhow.workspace = true
argon2.workspace = true
axum.workspace = true
chrono.workspace = true
chrono-tz = "0.10"
cron.workspace = true
include_dir = "0.7"
rand.workspace = true
@@ -23,11 +26,32 @@ serde.workspace = true
serde_json.workspace = true
rusqlite.workspace = true
tokio.workspace = true
tokio-util = { version = "0.7", features = ["io"] }
tower-http.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
utoipa.workspace = true
uuid.workspace = true
hex.workspace = true
sha2.workspace = true
base64 = "0.22"
async-compression = { version = "=0.4.36", default-features = false, features = ["tokio", "gzip"] }
futures-core = "0.3"
rustix = { version = "=1.1.6", default-features = false, features = ["fs", "std"] }
governor = { version = "=0.10.4", default-features = false, features = ["std"] }
openidconnect = { version = "=4.1.0", default-features = false, features = ["reqwest", "rustls-tls"] }
tempfile.workspace = true
indexmap = "=2.2.6"
hyper = { version = "=1.12.0", features = ["server", "http1"] }
hyper-util = { version = "=0.1.21", features = ["tokio"] }
rustls = { version = "=0.23.46", default-features = false, features = ["ring", "std"] }
tokio-rustls = "=0.26.2"
tower = { workspace = true }
[dev-dependencies]
rcgen = "=0.13.2"
wiremock = "=0.6.5"
futures-util = "0.3"
rsa = { version = "=0.9.10", features = ["sha2"] }
hmac.workspace = true
tokio.workspace = true

View File

@@ -0,0 +1,751 @@
use axum::http::{HeaderMap, StatusCode};
use std::net::SocketAddr;
#[derive(Clone, Debug, Default)]
pub struct AdminGate {
pub token: Option<String>,
/// Unix time after which the shared admin token is refused. The token is a
/// transition aid for CLI/automation, not a permanent credential.
pub token_expires_at: Option<i64>,
pub local_development: bool,
}
impl AdminGate {
pub fn from_env() -> anyhow::Result<Self> {
let token = std::env::var("TESSERA_ADMIN_TOKEN")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty());
if let Some(token) = &token {
check_token_strength(token)?;
}
let local_development = match std::env::var("TESSERA_LOCAL_DEVELOPMENT").as_deref() {
Ok("1" | "true") => true,
Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false,
_ => anyhow::bail!("TESSERA_LOCAL_DEVELOPMENT must be true, false, 1 or 0"),
};
let token_expires_at = match std::env::var("TESSERA_ADMIN_TOKEN_EXPIRES")
.ok()
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
{
None => None,
Some(value) => Some(parse_end_date(&value)?),
};
Ok(Self {
token,
token_expires_at,
local_development,
})
}
pub fn validate_listener(&self, addr: SocketAddr) -> anyhow::Result<()> {
anyhow::ensure!(!self.local_development || addr.ip().is_loopback(),
"TESSERA_LOCAL_DEVELOPMENT requires a loopback listener; never expose it through a proxy");
Ok(())
}
/// The shared admin token is configured and not past its end date.
pub fn token_active(&self) -> bool {
self.token.is_some() && !self.token_expired(chrono::Utc::now().timestamp())
}
pub fn token_expired(&self, now: i64) -> bool {
self.token_expires_at.is_some_and(|end| now >= end)
}
pub fn log_policy(&self) {
if let Some(end) = self.token_expires_at {
if self.token_expired(chrono::Utc::now().timestamp()) {
tracing::warn!("TESSERA_ADMIN_TOKEN is past its end date ({end}) and is refused; remove it or set a new date");
} else if self.token.is_some() {
tracing::info!("TESSERA_ADMIN_TOKEN is accepted until unix time {end}; plan to replace it with SSO/service access");
}
} else if self.token.is_some() {
tracing::warn!("TESSERA_ADMIN_TOKEN has no end date; set TESSERA_ADMIN_TOKEN_EXPIRES so the shared token cannot stay indefinitely");
}
if self.local_development && self.token.is_none() {
tracing::warn!(
"explicit local development mode: loopback APIs allow anonymous access; do not proxy this listener"
);
} else {
tracing::info!(
"TESSERA_ADMIN_TOKEN is set; backup APIs require that token from every client"
);
}
}
pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> {
let presented = presented_token(headers);
match &self.token {
Some(_) if self.token_expired(chrono::Utc::now().timestamp()) => {
Err(StatusCode::UNAUTHORIZED)
}
Some(expected) => {
if presented.is_some_and(|value| tokens_match(expected, value)) {
Ok(())
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
None if self.local_development
&& peer.ip().is_loopback()
&& !headers.contains_key("forwarded")
&& !headers
.keys()
.any(|key| key.as_str().starts_with("x-forwarded-")) =>
{
Ok(())
}
None => Err(StatusCode::UNAUTHORIZED),
}
}
}
/// Shortest shared admin token the hub will start with.
pub const MIN_ADMIN_TOKEN_LEN: usize = 32;
fn check_token_strength(token: &str) -> anyhow::Result<()> {
anyhow::ensure!(
token.chars().count() >= MIN_ADMIN_TOKEN_LEN,
"TESSERA_ADMIN_TOKEN must be at least {MIN_ADMIN_TOKEN_LEN} characters (for example `openssl rand -hex 32`)"
);
Ok(())
}
/// True when the request carries an admin token (in either header).
pub(crate) fn presents_token(headers: &HeaderMap) -> bool {
presented_token(headers).is_some()
}
fn presented_token(headers: &HeaderMap) -> Option<&str> {
if let Some(value) = headers
.get("x-tessera-admin-token")
.and_then(|value| value.to_str().ok())
{
let value = value.trim();
if !value.is_empty() {
return Some(value);
}
}
let header = headers.get("authorization")?.to_str().ok()?;
let token = header
.strip_prefix("Bearer ")
.or_else(|| header.strip_prefix("bearer "))?
.trim();
if token.is_empty() {
None
} else {
Some(token)
}
}
/// `2026-12-31` (end of that day, UTC) or a full RFC 3339 timestamp.
fn parse_end_date(value: &str) -> anyhow::Result<i64> {
if let Ok(time) = chrono::DateTime::parse_from_rfc3339(value) {
return Ok(time.timestamp());
}
let date = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").map_err(|_| {
anyhow::anyhow!("TESSERA_ADMIN_TOKEN_EXPIRES must be YYYY-MM-DD or an RFC 3339 timestamp")
})?;
Ok(date.and_hms_opt(23, 59, 59).unwrap().and_utc().timestamp())
}
pub(crate) fn tokens_match(expected: &str, presented: &str) -> bool {
let expected = expected.as_bytes();
let presented = presented.as_bytes();
let mut diff = expected.len() ^ presented.len();
for (left, right) in expected.iter().zip(presented.iter()) {
diff |= (*left ^ *right) as usize;
}
diff == 0
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
fn peer(ip: IpAddr) -> SocketAddr {
SocketAddr::new(ip, 9)
}
#[test]
fn short_admin_tokens_are_refused() {
assert!(check_token_strength("short").is_err());
assert!(check_token_strength(&"x".repeat(31)).is_err());
assert!(check_token_strength(&"x".repeat(32)).is_ok());
}
#[test]
fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() {
let gate = AdminGate {
token: None,
local_development: false,
..Default::default()
};
let headers = HeaderMap::new();
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_err());
assert!(gate
.authorize(peer(IpAddr::V6(Ipv6Addr::LOCALHOST)), &headers)
.is_err());
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 4))), &headers)
.is_err());
}
#[test]
fn a_configured_token_is_required_on_loopback() {
let gate = AdminGate {
token: Some("secret-token".into()),
local_development: false,
..Default::default()
};
let mut headers = HeaderMap::new();
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_err());
headers.insert(
"authorization",
HeaderValue::from_static("Bearer secret-token"),
);
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 8))), &headers)
.is_ok());
headers.remove("authorization");
headers.insert(
"x-tessera-admin-token",
HeaderValue::from_static("secret-token"),
);
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_ok());
headers.insert(
"x-tessera-admin-token",
HeaderValue::from_static("secret-tokem"),
);
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_err());
}
#[test]
fn development_is_explicit_loopback_only_and_rejects_forwarded_requests() {
let gate = AdminGate {
token: None,
local_development: true,
..Default::default()
};
for addr in ["127.0.0.1:8787", "[::1]:8787"] {
assert!(gate.validate_listener(addr.parse().unwrap()).is_ok());
assert!(gate
.authorize(addr.parse().unwrap(), &HeaderMap::new())
.is_ok());
}
for addr in ["0.0.0.0:8787", "[::]:8787", "192.0.2.1:8787"] {
assert!(gate.validate_listener(addr.parse().unwrap()).is_err());
assert!(gate
.authorize(addr.parse().unwrap(), &HeaderMap::new())
.is_err());
}
for name in [
"forwarded",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
] {
let mut headers = HeaderMap::new();
headers.insert(name, HeaderValue::from_static("synthetic-proxy"));
assert!(gate
.authorize("127.0.0.1:8787".parse().unwrap(), &headers)
.is_err());
}
}
}
/// Issuer of the break-glass operator row. It is not an `https://` URL, so no
/// OIDC provider can ever produce an identity that maps onto it.
pub const EMERGENCY_ISSUER: &str = "local:emergency";
#[derive(Clone)]
pub struct SessionGate {
config: Option<std::sync::Arc<OperatorConfig>>,
db: crate::db::Db,
/// Fingerprint of the OIDC configuration (issuer, client, admin mapping).
/// OIDC sessions only count while the same configuration is active.
oidc_fp: Option<String>,
}
struct OperatorConfig {
name: String,
password_hash: String,
/// Sessions are bound to this value, so unsetting or rotating the operator
/// hash invalidates every emergency session even though they persist.
fingerprint: String,
}
#[derive(Clone)]
pub struct BrowserSession {
pub id: uuid::Uuid,
pub csrf: String,
pub actor: String,
pub user_id: String,
pub auth_method: String,
/// May use the management API. A signed-in user without a grant is `false`.
pub admin: bool,
pub groups: Vec<String>,
pub expires_at: i64,
}
impl BrowserSession {
pub fn subject(&self) -> crate::auth::Subject {
crate::auth::Subject {
user_id: Some(self.user_id.clone()),
groups: self.groups.clone(),
admin: self.admin,
}
}
/// Audit identity. Never derived from IdP-supplied names: OIDC users are
/// identified by their stable user id, so a username of "operator" cannot
/// be mistaken for the emergency account.
pub fn principal(&self) -> crate::auth::Principal {
match self.auth_method.as_str() {
"oidc" => crate::auth::Principal::Oidc(self.user_id.clone()),
_ => crate::auth::Principal::Emergency(self.actor.clone()),
}
}
}
fn fingerprint(password_hash: &str) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(format!(
"tessera-operator-credential-v1:{password_hash}"
)))
}
fn unix_now() -> i64 {
chrono::Utc::now().timestamp()
}
impl SessionGate {
pub const COOKIE: &str = "__Host-tessera-session";
pub const DURATION: std::time::Duration =
std::time::Duration::from_secs(crate::db::sessions::ABSOLUTE_SECS as u64);
pub fn from_env(db: crate::db::Db, oidc_fp: Option<String>) -> anyhow::Result<Self> {
let config = match std::env::var("TESSERA_OPERATOR_PASSWORD_HASH") {
Ok(password_hash) => {
let name =
std::env::var("TESSERA_OPERATOR_NAME").unwrap_or_else(|_| "operator".into());
anyhow::ensure!(
(1..=64).contains(&name.len())
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)),
"invalid operator name"
);
let parsed = argon2::PasswordHash::new(&password_hash)
.map_err(|_| anyhow::anyhow!("invalid operator Argon2id hash"))?;
anyhow::ensure!(
parsed.algorithm.as_str() == "argon2id",
"operator password requires Argon2id"
);
Some(std::sync::Arc::new(OperatorConfig {
fingerprint: fingerprint(&password_hash),
name,
password_hash,
}))
}
Err(std::env::VarError::NotPresent) => None,
Err(_) => anyhow::bail!("operator password hash must be UTF-8"),
};
Ok(Self {
config,
db,
oidc_fp,
})
}
/// Any browser login method is configured (emergency password and/or OIDC).
pub fn enabled(&self) -> bool {
self.config.is_some() || self.oidc_fp.is_some()
}
/// The emergency password form is available.
pub fn password_enabled(&self) -> bool {
self.config.is_some()
}
pub fn active(&self, headers: &HeaderMap) -> Option<BrowserSession> {
self.active_at(headers, unix_now())
}
pub(crate) fn active_at(&self, headers: &HeaderMap, now: i64) -> Option<BrowserSession> {
let id = cookie_id(headers)?;
let stored = match self.db.lookup_session(&id.to_string(), now) {
Ok(found) => found?,
Err(error) => {
tracing::error!("session lookup failed: {error:#}");
return None;
}
};
// Sessions only count while the credential/configuration that created
// them is still the active one, so unsetting or rotating either revokes them.
let expected = match stored.auth_method.as_str() {
"password" => self
.config
.as_ref()
.map(|config| config.fingerprint.as_str()),
"oidc" => self.oidc_fp.as_deref(),
_ => None,
}?;
if stored.credential_fp.as_deref() != Some(expected) {
return None;
}
Some(BrowserSession {
id,
csrf: crate::db::sessions::csrf_token(&id.to_string()),
actor: stored.display_name,
user_id: stored.user_id,
auth_method: stored.auth_method,
admin: stored.admin,
groups: stored.groups,
expires_at: stored.expires_at,
})
}
pub fn login(&self, headers: &HeaderMap, password: &str) -> Result<BrowserSession, StatusCode> {
use argon2::PasswordVerifier;
let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?;
let hash = argon2::PasswordHash::new(&config.password_hash)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
argon2::Argon2::default()
.verify_password(password.as_bytes(), &hash)
.map_err(|_| StatusCode::UNAUTHORIZED)?;
let internal = |error: anyhow::Error| {
tracing::error!("session create failed: {error:#}");
StatusCode::INTERNAL_SERVER_ERROR
};
// A new ID on every login: a pre-existing cookie never survives (fixation).
if let Some(old) = cookie_id(headers) {
self.remove(old);
}
let now = unix_now();
let user_id = self
.db
.upsert_user(EMERGENCY_ISSUER, &config.name, &config.name, now)
.map_err(internal)?;
let id = uuid::Uuid::new_v4();
let created = self
.db
.create_session(
&id.to_string(),
&user_id,
"password",
Some(&config.fingerprint),
true,
&[],
now,
)
.map_err(internal)?;
if !created {
// Inactive user row: the break-glass account has been disabled.
return Err(StatusCode::UNAUTHORIZED);
}
Ok(BrowserSession {
id,
csrf: crate::db::sessions::csrf_token(&id.to_string()),
actor: config.name.clone(),
user_id,
auth_method: "password".into(),
admin: true,
groups: vec![],
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
})
}
/// Start an OIDC-backed session for a verified identity. The caller has
/// already validated the ID token; `admin` comes from the configured mapping.
pub fn create_oidc(
&self,
user_id: &str,
display_name: &str,
admin: bool,
groups: &[String],
now: i64,
) -> anyhow::Result<BrowserSession> {
let fp = self
.oidc_fp
.as_deref()
.ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?;
let id = uuid::Uuid::new_v4();
anyhow::ensure!(
self.db.create_session(
&id.to_string(),
user_id,
"oidc",
Some(fp),
admin,
groups,
now
)?,
"user is disabled"
);
Ok(BrowserSession {
id,
csrf: crate::db::sessions::csrf_token(&id.to_string()),
actor: display_name.to_string(),
user_id: user_id.to_string(),
auth_method: "oidc".into(),
admin,
groups: groups.to_vec(),
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
})
}
pub fn remove(&self, id: uuid::Uuid) {
if let Err(error) = self.db.revoke_session(&id.to_string()) {
tracing::error!("session revoke failed: {error:#}");
}
}
}
fn cookie_id(headers: &HeaderMap) -> Option<uuid::Uuid> {
headers
.get_all(axum::http::header::COOKIE)
.iter()
.filter_map(|header| header.to_str().ok())
.flat_map(|line| line.split(';'))
.find_map(|pair| {
let (name, id) = pair.trim().split_once('=')?;
(name == SessionGate::COOKIE)
.then(|| uuid::Uuid::parse_str(id).ok())
.flatten()
})
}
pub fn print_operator_hash() -> anyhow::Result<()> {
use argon2::password_hash::{rand_core::OsRng, PasswordHasher, SaltString};
use std::io::BufRead;
let mut password = String::new();
std::io::stdin().lock().read_line(&mut password)?;
let password = password.trim_end_matches(['\n', '\r']);
anyhow::ensure!(
(12..=1024).contains(&password.len()),
"operator password must be 12–1024 bytes"
);
let salt = SaltString::generate(&mut OsRng);
let hash = argon2::Argon2::default()
.hash_password(password.as_bytes(), &salt)
.map_err(|_| anyhow::anyhow!("could not hash operator password"))?;
println!("{hash}");
Ok(())
}
#[cfg(test)]
impl SessionGate {
pub fn fixture(db: crate::db::Db) -> Self {
use argon2::password_hash::{PasswordHasher, SaltString};
let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap();
let password_hash = argon2::Argon2::default()
.hash_password(b"fixture-operator-password", &salt)
.unwrap()
.to_string();
Self::with_hash(db, "fixture-operator", password_hash)
}
pub fn with_hash(db: crate::db::Db, name: &str, password_hash: String) -> Self {
Self {
config: Some(std::sync::Arc::new(OperatorConfig {
name: name.into(),
fingerprint: fingerprint(&password_hash),
password_hash,
})),
db,
oidc_fp: None,
}
}
/// Same database, no operator configured (hash unset after a restart).
pub fn without_operator(db: crate::db::Db) -> Self {
Self {
config: None,
db,
oidc_fp: None,
}
}
pub fn with_oidc(mut self, fingerprint: &str) -> Self {
self.oidc_fp = Some(fingerprint.into());
self
}
pub fn expire(&self) {
self.db.expire_all_sessions();
}
}
#[cfg(test)]
mod session_gate_tests {
use super::*;
use axum::http::HeaderValue;
fn hash(password: &str, salt: &[u8]) -> String {
use argon2::password_hash::{PasswordHasher, SaltString};
argon2::Argon2::default()
.hash_password(password.as_bytes(), &SaltString::encode_b64(salt).unwrap())
.unwrap()
.to_string()
}
fn cookie(session: &BrowserSession) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
axum::http::header::COOKIE,
HeaderValue::from_str(&format!("{}={}", SessionGate::COOKIE, session.id)).unwrap(),
);
headers
}
async fn db() -> (tempfile::TempDir, crate::db::Db) {
let dir = tempfile::tempdir().unwrap();
let db = crate::db::Db::connect(&dir.path().join("t.db"))
.await
.unwrap();
db.migrate().await.unwrap();
(dir, db)
}
#[tokio::test]
async fn a_session_outlives_a_restart_only_with_the_same_operator_credential() {
let (_dir, db) = db().await;
let first = SessionGate::with_hash(
db.clone(),
"ops",
hash("correct-horse-battery", b"salt-number-one"),
);
let session = first
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
// restart with the same credential: still valid
let restarted = SessionGate::with_hash(
db.clone(),
"ops",
hash("correct-horse-battery", b"salt-number-one"),
);
assert!(restarted.active(&cookie(&session)).is_some());
// hash rotated after a suspected compromise: old cookie is dead
let rotated = SessionGate::with_hash(
db.clone(),
"ops",
hash("another-long-password", b"salt-number-two"),
);
assert!(rotated.active(&cookie(&session)).is_none());
// emergency login disabled by unsetting the hash: old cookie is dead
assert!(SessionGate::without_operator(db.clone())
.active(&cookie(&session))
.is_none());
// and it comes back only if the exact credential is configured again
assert!(restarted.active(&cookie(&session)).is_some());
}
#[tokio::test]
async fn login_replaces_a_presented_session_id() {
let (_dir, db) = db().await;
let gate =
SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one"));
let old = gate
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
let new = gate.login(&cookie(&old), "correct-horse-battery").unwrap();
assert_ne!(old.id, new.id);
assert!(gate.active(&cookie(&old)).is_none());
assert!(gate.active(&cookie(&new)).is_some());
assert_eq!(
old.user_id, new.user_id,
"same break-glass user row across logins"
);
}
#[tokio::test]
async fn absolute_expiry_and_user_revoke_apply_to_the_gate() {
let (_dir, db) = db().await;
let gate = SessionGate::with_hash(
db.clone(),
"ops",
hash("correct-horse-battery", b"salt-number-one"),
);
let session = gate
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
let now = unix_now();
assert!(gate.active_at(&cookie(&session), now + 60).is_some());
assert!(gate
.active_at(&cookie(&session), now + crate::db::sessions::ABSOLUTE_SECS)
.is_none());
assert_eq!(db.revoke_user_sessions(&session.user_id).unwrap(), 1);
assert!(gate.active(&cookie(&session)).is_none());
assert!(gate
.login(&HeaderMap::new(), "correct-horse-battery")
.is_ok());
}
#[tokio::test]
async fn the_csrf_token_is_stable_for_a_session_and_not_the_cookie() {
let (_dir, db) = db().await;
let gate =
SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one"));
let session = gate
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
let again = gate.active(&cookie(&session)).unwrap();
assert_eq!(session.csrf, again.csrf);
assert!(!session.csrf.contains(&session.id.to_string()));
}
#[tokio::test]
async fn oidc_sessions_end_when_the_oidc_configuration_changes_or_is_removed() {
let (_dir, db) = db().await;
let user = db
.upsert_user("https://idp.example", "alice", "Alice", unix_now())
.unwrap();
let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a");
let session = gate
.create_oidc(&user, "Alice", true, &[], unix_now())
.unwrap();
assert_eq!(session.principal().fields().0, format!("oidc:{user}"));
assert!(gate.active(&cookie(&session)).is_some());
// admin mapping changed (different fingerprint) or OIDC switched off: dead
assert!(SessionGate::without_operator(db.clone())
.with_oidc("fp-b")
.active(&cookie(&session))
.is_none());
assert!(SessionGate::without_operator(db.clone())
.active(&cookie(&session))
.is_none());
// configuration restored: the same session is valid again
assert!(SessionGate::without_operator(db)
.with_oidc("fp-a")
.active(&cookie(&session))
.is_some());
}
#[tokio::test]
async fn an_oidc_display_name_never_becomes_the_emergency_principal() {
let (_dir, db) = db().await;
let user = db
.upsert_user("https://idp.example", "mallory", "operator", unix_now())
.unwrap();
let session = SessionGate::without_operator(db)
.with_oidc("fp")
.create_oidc(&user, "operator", false, &[], unix_now())
.unwrap();
let (id, kind, method) = session.principal().fields();
assert_eq!((kind, method), ("user", "oidc"));
assert!(id.starts_with("oidc:") && !id.contains("emergency"));
}
}

View File

@@ -0,0 +1,429 @@
//! Administration of access: who holds which permission on which orbit.
//! Administrators only (`access.manage` is never delegated). Every change is
//! audited by id and effective on the very next request of the affected user.
// Refusals are whole responses (`{"reason"}`); they are built once per request, not carried around.
#![allow(clippy::result_large_err)]
use super::routes::{admin_read, admin_write};
use crate::auth::{role, AuditAction, AuditOutcome, AuditResource, Permission, ROLE_NAMES};
use crate::db::access::NewGrant;
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Response},
routing::{get, post, put},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/access/grants", get(list).post(create).put(replace))
.route("/api/v1/access/grants/:id", axum::routing::delete(remove))
.route("/api/v1/access/users", get(users))
.route("/api/v1/access/users/:id", put(set_user))
.route(
"/api/v1/access/users/:id/revoke-sessions",
post(revoke_sessions),
)
}
fn no_store() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn internal(error: impl std::fmt::Display) -> StatusCode {
tracing::error!("access administration failed: {error:#}");
StatusCode::INTERNAL_SERVER_ERROR
}
#[derive(Serialize)]
struct RoleInfo {
name: &'static str,
permissions: Vec<&'static str>,
}
#[derive(Serialize)]
struct GrantList {
grants: Vec<crate::db::access::Grant>,
/// Refresh grants, one per relation: the `refresh.run` permission is never in `grants`.
relation_grants: Vec<crate::db::relations::RelationGrantRow>,
roles: Vec<RoleInfo>,
/// Permissions that can be granted; all others belong to administrators.
grantable: Vec<&'static str>,
/// Permissions only administrators hold, for the screen to show as locked.
admin_only: Vec<&'static str>,
}
fn names(keep: impl Fn(Permission) -> bool) -> Vec<&'static str> {
Permission::ALL
.into_iter()
.filter(|p| keep(*p))
.map(Permission::as_str)
.collect()
}
/// A refusal that says which rule applied (`{"reason": "..."}`), so the screen can say it too.
fn refuse(status: StatusCode, reason: &'static str) -> Response {
(status, Json(serde_json::json!({ "reason": reason }))).into_response()
}
async fn list(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<GrantList>), StatusCode> {
admin_read(&state, peer, &headers)?;
let roles = ROLE_NAMES
.iter()
.map(|name| RoleInfo {
name,
permissions: role(name)
.unwrap_or(&[])
.iter()
.map(|p| p.as_str())
.collect(),
})
.collect();
Ok((
no_store(),
Json(GrantList {
grants: state.db.list_grants().map_err(internal)?,
relation_grants: state.db.list_relation_grants().map_err(internal)?,
roles,
grantable: names(Permission::grantable),
admin_only: names(Permission::admin_only),
}),
))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CreateGrant {
/// `user` (a `users.id`) or `group` (an IdP group name).
principal_type: String,
principal: String,
/// Exactly one of `role`, `permission` and `permissions`.
role: Option<String>,
permission: Option<String>,
permissions: Option<Vec<String>>,
/// Absent = every orbit.
orbit_id: Option<Uuid>,
/// RFC 3339; absent = no expiry.
expires_at: Option<String>,
/// Only for `PUT`: grants of the same person or group and orbit that this request replaces.
#[serde(default)]
replaces: Vec<Uuid>,
}
/// A request that passed every rule: what to write, and for whom.
struct Valid {
permissions: Vec<Permission>,
orbit: Option<String>,
expires_at: Option<i64>,
}
fn validate(state: &HubState, body: &CreateGrant, now: i64) -> Result<Valid, Response> {
let bad = |reason| refuse(StatusCode::BAD_REQUEST, reason);
let unprocessable = |reason| refuse(StatusCode::UNPROCESSABLE_ENTITY, reason);
let mut permissions: Vec<Permission> = match (&body.role, &body.permission, &body.permissions) {
(Some(name), None, None) => role(name).ok_or(bad("unknown_role"))?.to_vec(),
(None, Some(name), None) => vec![Permission::parse(name)
.filter(|p| p.grantable())
.ok_or(bad("unknown_permission"))?],
(None, None, Some(names)) => names
.iter()
.map(|name| {
Permission::parse(name)
.filter(|p| p.grantable())
.ok_or(bad("unknown_permission"))
})
.collect::<Result<_, _>>()?,
_ => return Err(bad("choose_one")),
};
permissions.dedup();
let mut seen = Vec::new();
permissions.retain(|p| {
let new = !seen.contains(p);
seen.push(*p);
new
});
if permissions.is_empty() {
return Err(bad("nothing_selected"));
}
match body.principal_type.as_str() {
"user" => {
Uuid::parse_str(&body.principal).map_err(|_| bad("bad_person"))?;
let user = state
.db
.user_row(&body.principal)
.map_err(|e| internal(e).into_response())?
.ok_or(unprocessable("unknown_user"))?;
if user.is_emergency {
return Err(unprocessable("emergency_operator"));
}
}
"group" => {
if body.principal.is_empty()
|| body.principal.len() > 128
|| body.principal.chars().any(char::is_control)
{
return Err(bad("bad_group"));
}
}
_ => return Err(bad("bad_principal_type")),
}
if let Some(orbit) = body.orbit_id {
if !state
.db
.orbit_exists(&orbit.to_string())
.map_err(|e| internal(e).into_response())?
{
return Err(unprocessable("unknown_orbit"));
}
}
let expires_at = body
.expires_at
.as_deref()
.map(|text| {
chrono::DateTime::parse_from_rfc3339(text)
.map(|t| t.timestamp())
.map_err(|_| bad("bad_end_date"))
})
.transpose()?;
if expires_at.is_some_and(|end| end <= now || end > now + 2 * 366 * 86_400) {
return Err(bad("bad_end_date"));
}
Ok(Valid {
permissions,
orbit: body.orbit_id.map(|id| id.to_string()),
expires_at,
})
}
async fn create(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<CreateGrant>,
) -> Result<(StatusCode, HeaderMap, Json<Vec<crate::db::access::Grant>>), Response> {
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
let now = now();
if !body.replaces.is_empty() {
return Err(refuse(StatusCode::BAD_REQUEST, "replaces_needs_put"));
}
let valid = validate(&state, &body, now)?;
let created_by = actor.id();
let mut created = Vec::new();
for permission in valid.permissions {
let grant = NewGrant {
principal_type: &body.principal_type,
principal: &body.principal,
permission: permission.as_str(),
orbit: valid.orbit.as_deref(),
expires_at: valid.expires_at,
created_by: &created_by,
};
if let Some(grant) = state
.db
.add_grant(&grant, now)
.map_err(|e| internal(e).into_response())?
{
let id = Uuid::parse_str(&grant.id).map_err(|e| internal(e).into_response())?;
state
.db
.audit_event(
&actor.principal,
AuditAction::GrantCreate,
AuditResource::Grant(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(|e| internal(e).into_response())?;
created.push(grant);
}
}
if created.is_empty() {
return Err(refuse(StatusCode::CONFLICT, "already_granted"));
}
Ok((StatusCode::CREATED, no_store(), Json(created)))
}
/// Edit or renew: replace some grants of one person or group and orbit with a new set and end date,
/// all or nothing. Anything that was already granted keeps working through the change.
async fn replace(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<CreateGrant>,
) -> Result<(HeaderMap, Json<Vec<crate::db::access::Grant>>), Response> {
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
let now = now();
let valid = validate(&state, &body, now)?;
let created_by = actor.id();
let new: Vec<NewGrant> = valid
.permissions
.iter()
.map(|permission| NewGrant {
principal_type: &body.principal_type,
principal: &body.principal,
permission: permission.as_str(),
orbit: valid.orbit.as_deref(),
expires_at: valid.expires_at,
created_by: &created_by,
})
.collect();
let replaces: Vec<String> = body.replaces.iter().map(Uuid::to_string).collect();
let outcome = state
.db
.replace_grants(&replaces, &new, now)
.map_err(|e| internal(e).into_response())?;
let crate::db::access::Replace::Done { removed, written } = outcome else {
return Err(refuse(StatusCode::UNPROCESSABLE_ENTITY, "grant_mismatch"));
};
for (id, action) in removed
.iter()
.map(|id| (id, AuditAction::GrantDelete))
.chain(written.iter().map(|g| (&g.id, AuditAction::GrantCreate)))
{
let id = Uuid::parse_str(id).map_err(|e| internal(e).into_response())?;
state
.db
.audit_event(
&actor.principal,
action,
AuditResource::Grant(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(|e| internal(e).into_response())?;
}
Ok((no_store(), Json(written)))
}
async fn remove(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let removed = state.db.delete_grant(&id.to_string()).map_err(internal)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::GrantDelete,
AuditResource::Grant(id),
if removed {
AuditOutcome::Succeeded
} else {
AuditOutcome::Failed
},
actor.request_id,
)
.map_err(internal)?;
if removed {
Ok(StatusCode::NO_CONTENT)
} else {
Err(StatusCode::NOT_FOUND)
}
}
async fn users(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Vec<crate::db::access::UserRow>>), StatusCode> {
admin_read(&state, peer, &headers)?;
Ok((no_store(), Json(state.db.list_users().map_err(internal)?)))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct UserState {
active: bool,
}
/// Look up the target user and refuse the two changes that would lock everyone out.
fn target_user(
state: &HubState,
actor: &super::routes::OperatorActor,
id: Uuid,
) -> Result<crate::db::access::UserRow, Response> {
let user = state
.db
.user_row(&id.to_string())
.map_err(|e| internal(e).into_response())?
.ok_or(StatusCode::NOT_FOUND.into_response())?;
if actor.subject.user_id.as_deref() == Some(user.id.as_str()) {
return Err(refuse(StatusCode::CONFLICT, "cannot_disable_self"));
}
if user.is_emergency {
return Err(refuse(StatusCode::CONFLICT, "cannot_disable_emergency"));
}
Ok(user)
}
async fn set_user(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<UserState>,
) -> Result<StatusCode, Response> {
let actor = admin_write(&state, peer, &headers).map_err(IntoResponse::into_response)?;
let user = target_user(&state, &actor, id)?;
state
.db
.set_user_active(&user.id, body.active)
.map_err(|e| internal(e).into_response())?;
state
.db
.audit_event(
&actor.principal,
AuditAction::UserState,
AuditResource::User(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(|e| internal(e).into_response())?;
Ok(StatusCode::NO_CONTENT)
}
async fn revoke_sessions(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let user = state
.db
.list_users()
.map_err(internal)?
.into_iter()
.find(|u| u.id == id.to_string())
.ok_or(StatusCode::NOT_FOUND)?;
state.db.revoke_user_sessions(&user.id).map_err(internal)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::SessionsRevoke,
AuditResource::User(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,133 @@
//! Keep the route inventory and executable negative HTTP fixtures together.
use super::*;
use axum::{
body::Body,
extract::ConnectInfo,
http::{header, Request, StatusCode},
};
use std::net::SocketAddr;
use tower::ServiceExt;
const CONTRACT: &str = include_str!("../../../../docs/auth-endpoint-contract.md");
#[test]
fn every_registered_path_has_an_authorization_contract() {
for source in [
include_str!("routes.rs"),
include_str!("jobs.rs"),
include_str!("restore.rs"),
include_str!("catalog.rs"),
include_str!("session.rs"),
include_str!("oidc.rs"),
] {
for route in source.split(".route(").skip(1) {
let path = route.split('"').nth(1).expect("route literal");
assert!(
CONTRACT.contains(&format!("| {path} |")),
"missing contract: {path}"
);
}
}
}
#[tokio::test]
async fn human_read_endpoints_reject_anonymous_and_outpost_tokens() {
let dir = tempfile::tempdir().unwrap();
let mut state = crate::state::HubState::bootstrap(
dir.path().to_str().unwrap(),
"synthetic-vault-passphrase",
)
.await
.unwrap();
state.sessions = crate::admin::SessionGate::fixture(state.db.clone());
state.admin.token = Some("synthetic-admin".into());
let outpost = uuid::Uuid::new_v4();
state
.db
.insert_test_credential("synthetic-outpost", &outpost.to_string(), "fixture");
let app = router(state);
// each request comes from its own source so the wrong-token throttle does not mask the 401s
let mut source = 0u32;
for row in CONTRACT.lines().filter(|line| line.starts_with("| /")) {
let fields: Vec<_> = row.split('|').map(str::trim).collect();
if fields[3] != "human" || !fields[2].split(',').any(|method| method == "GET") {
continue;
}
let path = fields[1].replace(":id", "00000000-0000-0000-0000-000000000001");
for token in [None, Some("synthetic-outpost")] {
source += 1;
let mut request =
Request::builder()
.uri(&path)
.extension(ConnectInfo(SocketAddr::from((
[10, 0, (source >> 8) as u8, source as u8],
9000,
))));
if let Some(token) = token {
request = request
.header(header::AUTHORIZATION, format!("Bearer {token}"))
.header("x-tessera-upload-token", token);
}
let response = app
.clone()
.oneshot(request.body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(
response.status(),
StatusCode::UNAUTHORIZED,
"{path} token={token:?}"
);
}
}
}
#[tokio::test]
async fn local_proxy_never_enables_auth_when_credentials_are_absent() {
let dir = tempfile::tempdir().unwrap();
let mut state = crate::state::HubState::bootstrap(
dir.path().to_str().unwrap(),
"synthetic-vault-passphrase",
)
.await
.unwrap();
state.admin = crate::admin::AdminGate {
token: None,
local_development: false,
..Default::default()
};
assert!(!state.sessions.enabled());
let app = router(state);
for forwarded in [false, true] {
let request = |path: &str| {
let mut r = Request::builder()
.uri(path)
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()))
.header(header::HOST, "vault.example.invalid");
if forwarded {
r = r
.header("x-forwarded-for", "127.0.0.1")
.header("x-forwarded-proto", "https");
}
r.body(Body::empty()).unwrap()
};
assert_eq!(
app.clone()
.oneshot(request("/api/v1/orbits"))
.await
.unwrap()
.status(),
StatusCode::UNAUTHORIZED
);
let response = app
.clone()
.oneshot(request("/api/v1/operator/session"))
.await
.unwrap();
let bytes = axum::body::to_bytes(response.into_body(), 1024)
.await
.unwrap();
let status: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(status["authorized"], false);
}
}

View File

@@ -0,0 +1,220 @@
use super::routes::{admin_write, authenticate};
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission};
use crate::exports::{self, Guarded, Refused, EXPORT_PREFIX};
use crate::state::HubState;
use async_compression::tokio::bufread::GzipEncoder;
use axum::body::Bytes;
use axum::{
body::Body,
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, HeaderValue, Method, StatusCode},
response::Response,
routing::get,
Router,
};
use futures_core::Stream;
use std::net::SocketAddr;
use std::pin::Pin;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio_util::io::ReaderStream;
use uuid::Uuid;
/// Frames sent to the client: small and bounded, whatever the size of the snapshot.
const CHUNK: usize = 64 * 1024;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/snapshots/:id", axum::routing::delete(delete))
.route("/api/v1/snapshots/:id/download", get(download))
}
/// Download a snapshot as a file. The order matters: authenticate, find the snapshot, check the
/// permission on its orbit, and only then admit the export, so a caller who may not download can
/// never use up the export slots or disk.
async fn download(
method: Method,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
// Axum would answer HEAD with the GET handler, i.e. run a whole export for nothing.
if method == Method::HEAD {
return Err(StatusCode::METHOD_NOT_ALLOWED);
}
let actor = authenticate(&state, peer, &headers, false)?;
let snapshot = state
.vault
.read()
.await
.get_snapshot(id)
.map_err(internal)?
.filter(|snapshot| snapshot.manifest.provider != "legacy-history")
.ok_or(StatusCode::NOT_FOUND)?;
super::gate::scoped(
&state,
&actor,
Permission::SnapshotDownload,
snapshot.manifest.orbit_id,
)?;
let audit = |action: AuditAction, outcome: AuditOutcome| {
state
.db
.audit_event(
&actor.principal,
action,
AuditResource::Snapshot(id),
outcome,
actor.request_id,
)
.map_err(internal)
};
audit(AuditAction::ExportRequested, AuditOutcome::Allowed)?;
let permit = match state.exports.admit(&state.data_dir, snapshot.size_bytes) {
Ok(permit) => permit,
Err(refused) => {
audit(AuditAction::ExportRequested, AuditOutcome::Failed)?;
return Err(match refused {
Refused::Busy => StatusCode::TOO_MANY_REQUESTS,
Refused::NoSpace => StatusCode::INSUFFICIENT_STORAGE,
});
}
};
let staging = tempfile::Builder::new()
.prefix(EXPORT_PREFIX)
.tempdir_in(&state.data_dir)
.map_err(internal)?;
let path = staging.path().join("download");
state
.export_snapshot(id, path.clone())
.await
.map_err(internal)?;
let mut file = tokio::fs::File::open(&path).await.map_err(internal)?;
let size = file.metadata().await.map_err(internal)?.len();
let mut head = vec![0u8; 512];
let read = file.read(&mut head).await.map_err(internal)?;
head.truncate(read);
file.seek(std::io::SeekFrom::Start(0))
.await
.map_err(internal)?;
let plan = exports::plan(&snapshot.manifest.restore_hints, &head);
// The profile's schedule zone makes the time in the name match the one people see in their schedule.
let application = snapshot
.manifest
.restore_hints
.get("application_id")
.and_then(|v| v.as_str())
.and_then(|v| Uuid::parse_str(v).ok());
let zone = application.and_then(|application| {
state
.db
.capture_profiles()
.ok()?
.into_iter()
.find(|p| p.application_id == application)?
.schedule
.map(|s| s.timezone)
});
let orbit_name = state
.db
.orbit_names()
.ok()
.and_then(|names| names.get(&snapshot.manifest.orbit_id).cloned())
.unwrap_or_else(|| snapshot.manifest.orbit_name.clone());
let file_name = exports::download_name(
&orbit_name,
snapshot.taken_at,
zone.as_deref(),
snapshot
.manifest
.restore_hints
.get("engine")
.and_then(|v| v.as_str()),
id,
plan.extension,
);
audit(AuditAction::ExportReady, AuditOutcome::Succeeded)?;
let reader = tokio::io::BufReader::with_capacity(CHUNK, file);
let stream: Pin<Box<dyn Stream<Item = std::io::Result<Bytes>> + Send>> = if plan.compress {
Box::pin(ReaderStream::with_capacity(GzipEncoder::new(reader), CHUNK))
} else {
Box::pin(ReaderStream::with_capacity(reader, CHUNK))
};
let body = Guarded::new(
stream,
permit,
staging,
state.db.clone(),
actor.principal.clone(),
id,
actor.request_id,
);
let mut response = Response::new(Body::from_stream(body));
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static(plan.content_type),
);
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(&exports::content_disposition(&file_name)).map_err(internal)?,
);
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
// The exact size is only known when the bytes are sent as they are. Never `Content-Encoding`: this
// is the file itself, and a browser must not unpack it.
if !plan.compress {
headers.insert(header::CONTENT_LENGTH, HeaderValue::from(size));
}
Ok(response)
}
async fn delete(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let mut vault = state.vault.clone().write_owned().await;
if state.db.snapshot_in_restore(id).map_err(internal)?
|| state.db.offsite_pending(id).map_err(internal)?
|| state.active_exports().await.contains(&id)
{
return Err(StatusCode::CONFLICT);
}
if vault
.get_snapshot(id)
.map_err(internal)?
.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history")
{
return Err(StatusCode::NOT_FOUND);
}
state
.db
.audit(
"snapshot.delete_requested",
&format!("actor={actor} snapshot={id}"),
)
.await
.map_err(internal)?;
tokio::task::spawn_blocking(move || vault.forget(&[id]))
.await
.map_err(internal)?
.map_err(internal)?;
state
.db
.audit("snapshot.deleted", &format!("actor={actor} snapshot={id}"))
.await
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}
fn internal(_: impl std::fmt::Display) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}

View File

@@ -0,0 +1,856 @@
//! HTTP-level checks for Outpost credentials, limits and the legacy admin token.
use crate::admin::{AdminGate, SessionGate};
use crate::limits::{LimitConfig, Limits};
use crate::state::HubState;
use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Request, Response, StatusCode};
use governor::Quota;
use serde_json::{json, Value};
use std::net::SocketAddr;
use std::num::NonZeroU32;
use std::sync::Arc;
use tower::ServiceExt;
const ADMIN: &str = "synthetic-admin-token";
struct Harness {
app: axum::Router,
state: HubState,
dir: tempfile::TempDir,
}
async fn harness_with(configure: impl FnOnce(&mut HubState)) -> Harness {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some(ADMIN.into());
configure(&mut state);
let app = crate::api::router(state.clone());
Harness { app, state, dir }
}
async fn harness() -> Harness {
harness_with(|_| {}).await
}
fn request(
method: &str,
uri: &str,
peer: &str,
auth: Option<&str>,
body: Option<Value>,
) -> Request<Body> {
let mut builder = Request::builder()
.method(method)
.uri(uri)
.extension(ConnectInfo(
format!("{peer}:4000").parse::<SocketAddr>().unwrap(),
));
if let Some(token) = auth {
builder = builder.header("x-tessera-admin-token", token);
}
match body {
Some(json) => builder
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(json.to_string()))
.unwrap(),
None => builder.body(Body::empty()).unwrap(),
}
}
fn as_outpost(mut request: Request<Body>, token: &str) -> Request<Body> {
request
.headers_mut()
.insert("x-tessera-upload-token", token.parse().unwrap());
request
}
async fn json_of(response: Response<Body>) -> Value {
serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap())
.unwrap_or(Value::Null)
}
impl Harness {
async fn call(&self, request: Request<Body>) -> Response<Body> {
self.app.clone().oneshot(request).await.unwrap()
}
async fn status(&self, request: Request<Body>) -> StatusCode {
self.call(request).await.status()
}
/// The real HTTP pairing path: start (admin) then claim (agent).
async fn pair(&self, name: &str) -> (String, String) {
let start = self
.call(request(
"POST",
"/api/v1/wormhole/pairing",
"127.0.0.1",
Some(ADMIN),
None,
))
.await;
assert_eq!(start.status(), StatusCode::OK);
let code = json_of(start).await["code"].as_str().unwrap().to_string();
let claim = self
.call(request(
"POST",
"/api/v1/wormhole/claim",
"198.51.100.20",
None,
Some(json!({"code": code, "outpost_name": name})),
))
.await;
assert_eq!(claim.status(), StatusCode::OK);
let body = json_of(claim).await;
(
body["outpost_id"].as_str().unwrap().to_string(),
body["upload_token"].as_str().unwrap().to_string(),
)
}
/// An Outpost-authenticated request: 401 only if the token is refused.
async fn outpost_status(&self, token: &str, path: &str) -> StatusCode {
self.status(as_outpost(
request(
"POST",
path,
"198.51.100.20",
None,
Some(json!({"orbit_id": "00000000-0000-0000-0000-000000000001", "total_bytes": 1})),
),
token,
))
.await
}
fn db_file(&self) -> std::path::PathBuf {
self.dir.path().join("tessera.db")
}
fn scalar<T: rusqlite::types::FromSql>(&self, sql: &str) -> T {
rusqlite::Connection::open(self.db_file())
.unwrap()
.query_row(sql, [], |r| r.get(0))
.unwrap()
}
}
const UPLOAD: &str = "/api/v1/wormhole/upload/init";
const LEASED: &str = "/api/v1/wormhole/capture/00000000-0000-0000-0000-000000000001/claim";
#[tokio::test]
async fn pairing_over_http_mints_the_token_at_claim_and_stores_only_digests() {
let h = harness().await;
let (outpost, token) = h.pair("agent-one").await;
assert_eq!(token.len(), 64);
assert_ne!(
h.outpost_status(&token, UPLOAD).await,
StatusCode::UNAUTHORIZED,
"the minted token authenticates"
);
assert_eq!(
h.outpost_status("not-the-token", UPLOAD).await,
StatusCode::UNAUTHORIZED
);
// the code works exactly once
let again = h
.call(request(
"POST",
"/api/v1/wormhole/claim",
"198.51.100.20",
None,
Some(json!({"code": "WHATEVER", "outpost_name": "x"})),
))
.await;
assert_eq!(again.status(), StatusCode::GONE);
// neither the token nor the code is anywhere on disk
let code: String = {
// recover nothing from the DB: ask for a second pairing and look for it afterwards
let start = h
.call(request(
"POST",
"/api/v1/wormhole/pairing",
"127.0.0.1",
Some(ADMIN),
None,
))
.await;
json_of(start).await["code"].as_str().unwrap().to_string()
};
let mut bytes = Vec::new();
for suffix in ["", "-wal", "-journal"] {
let mut name = h.db_file().into_os_string();
name.push(suffix);
bytes.extend(std::fs::read(name).unwrap_or_default());
}
assert!(
bytes.windows(9).any(|w| w == b"agent-one"),
"sanity: the scan really reads the database file"
);
for secret in [token.as_str(), code.as_str()] {
assert!(
!bytes.windows(secret.len()).any(|w| w == secret.as_bytes()),
"clear-text secret on disk"
);
}
let audited: i64 = h.scalar(&format!("SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='succeeded' AND actor_id='{outpost}'"));
assert_eq!(audited, 1);
let leaked: i64 = h.scalar(&format!("SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{token}%'"));
assert_eq!(leaked, 0);
}
#[tokio::test]
async fn revoking_an_outpost_refuses_it_on_its_very_next_request() {
let h = harness().await;
let (outpost, token) = h.pair("agent-one").await;
assert_ne!(
h.outpost_status(&token, UPLOAD).await,
StatusCode::UNAUTHORIZED
);
assert_ne!(
h.outpost_status(&token, LEASED).await,
StatusCode::UNAUTHORIZED,
"lease-bearing endpoint accepts it before"
);
let revoke = |auth| {
request(
"POST",
&format!("/api/v1/wormhole/outposts/{outpost}/revoke"),
"127.0.0.1",
auth,
None,
)
};
assert_eq!(
h.status(revoke(None)).await,
StatusCode::UNAUTHORIZED,
"anonymous cannot revoke"
);
assert_eq!(
h.status(as_outpost(revoke(None), &token)).await,
StatusCode::UNAUTHORIZED,
"an Outpost cannot revoke itself or others"
);
assert_eq!(h.status(revoke(Some(ADMIN))).await, StatusCode::NO_CONTENT);
assert_eq!(
h.outpost_status(&token, UPLOAD).await,
StatusCode::UNAUTHORIZED
);
assert_eq!(
h.outpost_status(&token, LEASED).await,
StatusCode::UNAUTHORIZED,
"the lease-bearing path is refused too"
);
// a revoked Outpost cannot be rotated back to life, an unknown one is 404
let rotate = request(
"POST",
&format!("/api/v1/wormhole/outposts/{outpost}/rotate"),
"127.0.0.1",
Some(ADMIN),
None,
);
assert_eq!(h.status(rotate).await, StatusCode::NOT_FOUND);
let unknown = request(
"POST",
"/api/v1/wormhole/outposts/00000000-0000-0000-0000-00000000dead/revoke",
"127.0.0.1",
Some(ADMIN),
None,
);
assert_eq!(h.status(unknown).await, StatusCode::NOT_FOUND);
let events: Vec<(String, String)> = {
let conn = rusqlite::Connection::open(h.db_file()).unwrap();
let mut stmt = conn.prepare("SELECT action, outcome FROM audit_events WHERE action LIKE 'outpost.credential_%' ORDER BY id").unwrap();
stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap()
.collect::<Result<_, _>>()
.unwrap()
};
assert_eq!(
events,
[
(
"outpost.credential_revoke".to_string(),
"succeeded".to_string()
),
(
"outpost.credential_rotate".to_string(),
"failed".to_string()
),
(
"outpost.credential_revoke".to_string(),
"failed".to_string()
),
]
);
}
#[tokio::test]
async fn rotation_returns_the_new_token_once_and_bounds_the_old_one() {
let h = harness().await;
let (outpost, old) = h.pair("agent-one").await;
let rotate = |query: &str| {
request(
"POST",
&format!("/api/v1/wormhole/outposts/{outpost}/rotate{query}"),
"127.0.0.1",
Some(ADMIN),
None,
)
};
// default grace: both work
let first = h.call(rotate("")).await;
assert_eq!(first.status(), StatusCode::OK);
assert_eq!(first.headers()[header::CACHE_CONTROL], "no-store");
let first = json_of(first).await;
let fresh = first["upload_token"].as_str().unwrap().to_string();
assert!(first["previous_valid_until"].is_string());
assert_ne!(
h.outpost_status(&old, UPLOAD).await,
StatusCode::UNAUTHORIZED
);
assert_ne!(
h.outpost_status(&fresh, UPLOAD).await,
StatusCode::UNAUTHORIZED
);
// grace 0 ends every older token immediately
let second = json_of(h.call(rotate("?grace_minutes=0")).await).await;
assert!(second["previous_valid_until"].is_null());
assert_eq!(
h.outpost_status(&old, UPLOAD).await,
StatusCode::UNAUTHORIZED
);
assert_eq!(
h.outpost_status(&fresh, UPLOAD).await,
StatusCode::UNAUTHORIZED
);
assert_ne!(
h.outpost_status(second["upload_token"].as_str().unwrap(), UPLOAD)
.await,
StatusCode::UNAUTHORIZED
);
assert_eq!(
h.status(rotate("?grace_minutes=5000")).await,
StatusCode::BAD_REQUEST
);
assert_eq!(
h.status(request(
"POST",
&format!("/api/v1/wormhole/outposts/{outpost}/rotate"),
"127.0.0.1",
None,
None
))
.await,
StatusCode::UNAUTHORIZED
);
}
#[tokio::test]
async fn pairing_claims_are_limited_per_source_and_a_spoofed_header_does_not_help() {
let h = harness().await;
let claim = |peer: &str| {
let mut r = request(
"POST",
"/api/v1/wormhole/claim",
peer,
None,
Some(json!({"code": "GUESS", "outpost_name": "x"})),
);
r.headers_mut()
.insert("x-forwarded-for", "198.51.100.77".parse().unwrap());
r
};
let mut codes = Vec::new();
for _ in 0..8 {
codes.push(h.status(claim("203.0.113.5")).await);
}
assert_eq!(
codes.iter().filter(|c| **c == StatusCode::GONE).count(),
5,
"burst of five guesses"
);
assert_eq!(
codes
.iter()
.filter(|c| **c == StatusCode::TOO_MANY_REQUESTS)
.count(),
3
);
assert_eq!(
h.status(claim("203.0.113.6")).await,
StatusCode::GONE,
"another source still has its own budget"
);
let denied: i64 = h.scalar(
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='denied'",
);
assert_eq!(denied, 1, "a flood is audited once, not once per request");
}
fn operator_state(state: &mut HubState) {
state.sessions = SessionGate::fixture(state.db.clone());
}
#[tokio::test]
async fn an_emergency_login_flood_from_one_source_does_not_lock_out_a_legitimate_user() {
let h = harness_with(operator_state).await;
let login = |peer: &str, password: &str| {
request(
"POST",
"/api/v1/operator/login",
peer,
None,
Some(json!({"password": password})),
)
};
let mut attacker = Vec::new();
for _ in 0..20 {
let mut r = login("203.0.113.9", "wrong-guess");
r.headers_mut()
.insert("x-forwarded-for", "192.0.2.1".parse().unwrap());
attacker.push(h.status(r).await);
}
assert_eq!(
attacker
.iter()
.filter(|s| **s == StatusCode::UNAUTHORIZED)
.count(),
5
);
assert_eq!(
attacker
.iter()
.filter(|s| **s == StatusCode::TOO_MANY_REQUESTS)
.count(),
15
);
// the attacker with the right password is still refused while over budget ...
assert_eq!(
h.status(login("203.0.113.9", "fixture-operator-password"))
.await,
StatusCode::TOO_MANY_REQUESTS
);
// ... and a different source signs in fine
assert_eq!(
h.status(login("198.51.100.1", "fixture-operator-password"))
.await,
StatusCode::OK
);
let denied: i64 = h
.scalar("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='denied'");
assert_eq!(denied, 1, "one audit row per source per minute");
let passwords: i64 =
h.scalar("SELECT COUNT(*) FROM audit_events WHERE actor_id||action LIKE '%wrong-guess%'");
assert_eq!(passwords, 0);
}
#[tokio::test]
async fn argon2_work_is_bounded_and_the_permit_is_released_after_each_login() {
// no permits: refused at once rather than queued behind hashing
let none = harness_with(|state| {
operator_state(state);
state.limits = Arc::new(Limits::new(
LimitConfig {
argon2_concurrency: 0,
..LimitConfig::default()
},
vec![],
));
})
.await;
let login = |peer: &str| {
request(
"POST",
"/api/v1/operator/login",
peer,
None,
Some(json!({"password": "fixture-operator-password"})),
)
};
let started = std::time::Instant::now();
assert_eq!(
none.status(login("203.0.113.1")).await,
StatusCode::TOO_MANY_REQUESTS
);
assert!(
started.elapsed() < std::time::Duration::from_millis(500),
"no hashing was started"
);
// one permit, generous budgets: sequential logins all succeed, so the permit is returned
let one = harness_with(|state| {
operator_state(state);
let loose = Quota::per_second(NonZeroU32::new(1000).unwrap());
state.limits = Arc::new(Limits::new(
LimitConfig {
argon2_concurrency: 1,
login_source: loose,
login_account: loose,
..LimitConfig::default()
},
vec![],
));
})
.await;
for _ in 0..4 {
assert_eq!(one.status(login("203.0.113.1")).await, StatusCode::OK);
}
}
#[tokio::test]
async fn the_shared_admin_token_stops_working_after_its_end_date() {
let ok = harness_with(|state| {
state.admin = AdminGate {
token: Some(ADMIN.into()),
token_expires_at: Some(chrono::Utc::now().timestamp() + 3600),
..Default::default()
}
})
.await;
assert_eq!(
ok.status(request(
"GET",
"/api/v1/orbits",
"127.0.0.1",
Some(ADMIN),
None
))
.await,
StatusCode::OK
);
let actor: String = ok.scalar("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='allowed' LIMIT 1");
assert_eq!(
actor, "legacy-admin-token",
"every use is attributed to the legacy token in the audit log"
);
let past = harness_with(|state| {
state.admin = AdminGate {
token: Some(ADMIN.into()),
token_expires_at: Some(chrono::Utc::now().timestamp() - 1),
..Default::default()
}
})
.await;
assert_eq!(
past.status(request(
"GET",
"/api/v1/orbits",
"127.0.0.1",
Some(ADMIN),
None
))
.await,
StatusCode::UNAUTHORIZED
);
// an expired token must not silently fall back to anonymous development access either
let dev = harness_with(|state| {
state.admin = AdminGate {
token: Some(ADMIN.into()),
token_expires_at: Some(1),
local_development: true,
}
})
.await;
assert_eq!(
dev.status(request("GET", "/api/v1/orbits", "127.0.0.1", None, None))
.await,
StatusCode::UNAUTHORIZED
);
assert!(!dev.state.admin.token_active());
}
#[tokio::test]
async fn sso_endpoints_are_rate_limited_per_source() {
let h = harness().await; // OIDC disabled answers 404 before limiting; exercise the limiter directly
let source = h.state.limits.source(
Some("203.0.113.1:1".parse().unwrap()),
&axum::http::HeaderMap::new(),
);
let allowed = (0..60)
.filter(|_| h.state.limits.oidc_login_allowed(source))
.count();
assert_eq!(allowed, 15, "burst, then refused");
let other = h.state.limits.source(
Some("203.0.113.2:1".parse().unwrap()),
&axum::http::HeaderMap::new(),
);
assert!(h.state.limits.oidc_login_allowed(other));
}
// ---- pairing, the ways it must say no ----
const START: &str = "/api/v1/wormhole/pairing";
const CLAIM: &str = "/api/v1/wormhole/claim";
/// A different source address each time, so the per-source claim limit does not interfere.
fn fresh_peer() -> String {
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
format!("192.0.{}.{}", (n >> 8) & 255, n & 255)
}
impl Harness {
async fn start_code(&self) -> String {
let start = self
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
.await;
assert_eq!(start.status(), StatusCode::OK);
json_of(start).await["code"].as_str().unwrap().to_string()
}
async fn claim(&self, _peer: &str, body: Value) -> Response<Body> {
self.call(request("POST", CLAIM, &fresh_peer(), None, Some(body)))
.await
}
fn outposts(&self) -> i64 {
self.scalar("SELECT COUNT(*) FROM outposts")
}
fn credentials(&self) -> i64 {
self.scalar("SELECT COUNT(*) FROM outpost_credentials")
}
}
#[tokio::test]
async fn only_an_admin_can_start_a_pairing() {
let h = harness().await;
for auth in [None, Some("wrong-token"), Some("")] {
let status = h
.status(request("POST", START, "127.0.0.1", auth, None))
.await;
assert!(
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
"{auth:?} must not start a pairing, got {status}"
);
}
// a paired agent's upload token is not an operator credential either
let (_, token) = h.pair("agent").await;
let status = h
.status(as_outpost(
request("POST", START, "198.51.100.20", None, None),
&token,
))
.await;
assert!(
status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN,
"an outpost token must not start a pairing, got {status}"
);
let codes: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes WHERE consumed_at IS NULL");
assert_eq!(codes, 0, "a refused request leaves no code behind");
}
#[tokio::test]
async fn a_started_code_is_twelve_unambiguous_characters_valid_for_about_ten_minutes() {
let h = harness().await;
let start = h
.call(request("POST", START, "127.0.0.1", Some(ADMIN), None))
.await;
let body = json_of(start).await;
let code = body["code"].as_str().unwrap();
assert_eq!(code.len(), 12);
assert!(
code.chars()
.all(|c| "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".contains(c)),
"no 0/O/1/I lookalikes: {code}"
);
let expires = chrono::DateTime::parse_from_rfc3339(body["expires_at"].as_str().unwrap())
.unwrap()
.timestamp();
let in_secs = expires - chrono::Utc::now().timestamp();
assert!((595..=600).contains(&in_secs), "expires in {in_secs}s");
assert_ne!(code, h.start_code().await, "codes are not repeated");
}
#[tokio::test]
async fn a_claim_that_is_refused_creates_no_outpost_and_no_credential() {
let h = harness().await;
let code = h.start_code().await;
let lower = code.to_lowercase();
let spaced = format!(" {code} ");
let truncated = code[..11].to_string();
for wrong in [
lower.as_str(),
spaced.as_str(),
truncated.as_str(),
"",
"AAAAAAAAAAAA",
"'; DROP TABLE pairing_codes;--",
] {
let response = h
.claim("198.51.100.20", json!({"code": wrong, "outpost_name": "x"}))
.await;
assert_eq!(response.status(), StatusCode::GONE, "code {wrong:?}");
}
assert_eq!((h.outposts(), h.credentials()), (0, 0));
let failed: i64 = h.scalar(
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
);
assert_eq!(failed, 6, "every refusal is audited");
let leaked: i64 = h.scalar(&format!(
"SELECT COUNT(*) FROM audit_events WHERE actor_id||action||coalesce(resource_id,'') LIKE '%{code}%'"
));
assert_eq!(leaked, 0, "the code is never written to the audit log");
// the real code still works afterwards: wrong guesses do not burn it
let ok = h
.claim(
"198.51.100.20",
json!({"code": code, "outpost_name": "real"}),
)
.await;
assert_eq!(ok.status(), StatusCode::OK);
}
#[tokio::test]
async fn a_claim_with_a_bad_name_is_refused_before_the_code_is_spent() {
let h = harness().await;
let code = h.start_code().await;
let too_long = "n".repeat(129);
for name in [
"",
" ",
"\t\n",
"tab\there",
"nul\u{0}byte",
too_long.as_str(),
] {
let response = h
.claim("198.51.100.20", json!({"code": code, "outpost_name": name}))
.await;
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "name {name:?}");
}
assert_eq!(h.outposts(), 0);
let longest = "n".repeat(128);
let ok = h
.claim(
"198.51.100.20",
json!({"code": code, "outpost_name": longest}),
)
.await;
assert_eq!(ok.status(), StatusCode::OK, "128 characters is allowed");
assert_eq!(h.outposts(), 1);
}
#[tokio::test]
async fn malformed_claims_are_client_errors_and_never_touch_a_code() {
let h = harness().await;
let code = h.start_code().await;
for body in [
json!({}),
json!({"code": code}),
json!({"outpost_name": "x"}),
json!({"code": 12345, "outpost_name": "x"}),
json!({"code": null, "outpost_name": "x"}),
json!({"code": ["a"], "outpost_name": "x"}),
] {
let status = h.claim("198.51.100.20", body.clone()).await.status();
assert!(
status.is_client_error() && status != StatusCode::GONE,
"{body} gave {status}"
);
}
let good = format!(r#"{{"code":"{code}","outpost_name":"x"}}"#);
let raw = |content_type: Option<&str>, body: &str| {
let mut builder = Request::builder()
.method("POST")
.uri(CLAIM)
.extension(ConnectInfo(
format!("{}:4000", fresh_peer())
.parse::<SocketAddr>()
.unwrap(),
));
if let Some(content_type) = content_type {
builder = builder.header(header::CONTENT_TYPE, content_type);
}
builder.body(Body::from(body.to_string())).unwrap()
};
for request in [
raw(Some("application/json"), "{not json"),
raw(None, &good),
raw(Some("text/plain"), &good),
] {
let status = h.status(request).await;
assert!(status.is_client_error(), "got {status}");
}
assert_eq!((h.outposts(), h.credentials()), (0, 0));
let ok = h
.claim("198.51.100.20", json!({"code": code, "outpost_name": "x"}))
.await;
assert_eq!(
ok.status(),
StatusCode::OK,
"the code survived every bad request"
);
}
#[tokio::test]
async fn an_enormous_code_is_refused_without_trouble() {
let h = harness().await;
let huge = "A".repeat(1 << 20);
let status = h
.claim("198.51.100.20", json!({"code": huge, "outpost_name": "x"}))
.await
.status();
assert!(
status == StatusCode::GONE || status == StatusCode::PAYLOAD_TOO_LARGE,
"got {status}"
);
assert_eq!((h.outposts(), h.credentials()), (0, 0));
}
#[tokio::test]
async fn a_claimed_code_cannot_be_replayed_and_the_replay_is_audited() {
let h = harness().await;
let code = h.start_code().await;
let first = h
.claim(
"198.51.100.20",
json!({"code": code, "outpost_name": "first"}),
)
.await;
assert_eq!(first.status(), StatusCode::OK);
let second = h
.claim(
"198.51.100.21",
json!({"code": code, "outpost_name": "second"}),
)
.await;
assert_eq!(second.status(), StatusCode::GONE);
assert_eq!((h.outposts(), h.credentials()), (1, 1), "no second outpost");
let failed: i64 = h.scalar(
"SELECT COUNT(*) FROM audit_events WHERE action='outpost.pair' AND outcome='failed'",
);
assert_eq!(failed, 1);
}
#[tokio::test]
async fn an_expired_code_is_refused_and_old_ones_are_swept_by_the_next_pairing() {
let h = harness().await;
let now = chrono::Utc::now().timestamp();
h.state
.db
.insert_pairing("old-outpost", "STALECODE234", now - 1)
.unwrap();
h.state
.db
.insert_pairing("ancient-outpost", "ANCIENTCODE2", now - 200_000)
.unwrap();
let response = h
.claim(
"198.51.100.20",
json!({"code": "STALECODE234", "outpost_name": "late"}),
)
.await;
assert_eq!(response.status(), StatusCode::GONE);
assert_eq!((h.outposts(), h.credentials()), (0, 0));
h.start_code().await;
// a code that expired a moment ago lingers (the claim still refuses it); one a day old is deleted
let rows: i64 = h.scalar("SELECT COUNT(*) FROM pairing_codes");
assert_eq!(rows, 2, "the recent stale code and the fresh one remain");
}

View File

@@ -0,0 +1,404 @@
//! Snapshot downloads over HTTP: formats, headers, streaming, cleanup, audit and limits.
use crate::exports::ExportGate;
use crate::state::HubState;
use async_compression::tokio::bufread::{GzipDecoder, GzipEncoder};
use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Method, Request, Response, StatusCode};
use futures_util::StreamExt;
use sha2::{Digest, Sha256};
use std::net::SocketAddr;
use tessera_core::manifest::SnapshotManifest;
use tokio::io::AsyncReadExt;
use tower::ServiceExt;
use uuid::Uuid;
const ADMIN: &str = "synthetic-admin-token";
struct Harness {
app: axum::Router,
state: HubState,
dir: tempfile::TempDir,
}
async fn harness_with(gate: Option<ExportGate>) -> Harness {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
state.admin.token = Some(ADMIN.into());
if let Some(gate) = gate {
state.exports = std::sync::Arc::new(gate);
}
let app = crate::api::router(state.clone());
Harness { app, state, dir }
}
async fn harness() -> Harness {
harness_with(None).await
}
impl Harness {
async fn snapshot(&self, hints: serde_json::Value, payload: &[u8]) -> Uuid {
let id = Uuid::new_v4();
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: Uuid::new_v4(),
orbit_name: "fixture".into(),
labels: vec![],
provider: "postgres".into(),
paths: vec![],
restore_hints: hints,
};
self.state
.vault
.write()
.await
.snapshot(manifest, payload, false)
.unwrap();
id
}
async fn download(&self, id: Uuid, method: Method) -> Response<Body> {
let request = Request::builder()
.method(method)
.uri(format!("/api/v1/snapshots/{id}/download"))
.extension(ConnectInfo("127.0.0.1:4000".parse::<SocketAddr>().unwrap()))
.header("x-tessera-admin-token", ADMIN)
.body(Body::empty())
.unwrap();
self.app.clone().oneshot(request).await.unwrap()
}
fn export_dirs(&self) -> Vec<String> {
std::fs::read_dir(self.dir.path())
.unwrap()
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|name| name.starts_with(crate::exports::EXPORT_PREFIX))
.collect()
}
fn audit(&self, snapshot: Uuid) -> Vec<(String, String)> {
let conn = rusqlite::Connection::open(self.dir.path().join("tessera.db")).unwrap();
let mut stmt = conn
.prepare("SELECT action, outcome FROM audit_events WHERE resource_type='snapshot' AND resource_id=?1 ORDER BY id")
.unwrap();
stmt.query_map([snapshot.to_string()], |r| Ok((r.get(0)?, r.get(1)?)))
.unwrap()
.collect::<Result<_, _>>()
.unwrap()
}
}
async fn gunzip(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
GzipDecoder::new(tokio::io::BufReader::new(bytes))
.read_to_end(&mut out)
.await
.unwrap();
out
}
async fn gzip(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
GzipEncoder::new(tokio::io::BufReader::new(bytes))
.read_to_end(&mut out)
.await
.unwrap();
out
}
fn ustar(extra: &[u8]) -> Vec<u8> {
let mut block = vec![0u8; 512];
block[257..262].copy_from_slice(b"ustar");
block.extend_from_slice(extra);
block
}
#[tokio::test]
async fn each_kind_of_snapshot_downloads_with_the_right_format_and_honest_headers() {
let h = harness().await;
let already_gzip = gzip(b"SELECT 1;\n").await;
let pg_custom = [b"PGDMP\x01\x0e\x00".as_slice(), &[7u8; 300]].concat();
let cases: Vec<(&str, serde_json::Value, Vec<u8>, &str, bool)> = vec![
(
"postgres plain",
serde_json::json!({"engine": "postgres", "format": "plain"}),
b"CREATE TABLE t (x int);\n".repeat(200),
"sql.gz",
true,
),
(
"mysql plain",
serde_json::json!({"engine": "mysql", "format": "plain"}),
b"INSERT INTO t VALUES (1);\n".repeat(200),
"sql.gz",
true,
),
(
"postgres custom",
serde_json::json!({"format": "custom"}),
pg_custom,
"dump",
false,
),
(
"tar by hint",
serde_json::json!({"format": "tar"}),
ustar(b"file contents"),
"tar.gz",
true,
),
(
"tar with no hint (legacy restic)",
serde_json::Value::Null,
ustar(b"file contents"),
"tar.gz",
true,
),
(
"hub filesystem archive",
serde_json::json!({"format": "tessera-fs-v1", "paths": []}),
b"k\0\x02\0\0\0\0\0\0\0ab".to_vec(),
"tessera-fs.gz",
true,
),
(
"sqlite",
serde_json::json!({"format": "sqlite"}),
[b"SQLite format 3\0".as_slice(), &[0u8; 200]].concat(),
"sqlite.gz",
true,
),
(
"sql already gzip",
serde_json::json!({"format": "sql_gzip"}),
already_gzip.clone(),
"sql.gz",
false,
),
(
"labelled plain but gzip",
serde_json::json!({"format": "plain"}),
already_gzip,
"sql.gz",
false,
),
(
"no hints at all",
serde_json::Value::Null,
b"opaque".repeat(100),
"dump.gz",
true,
),
];
for (name, hints, payload, extension, compressed) in cases {
let id = h.snapshot(hints, &payload).await;
let response = h.download(id, Method::GET).await;
assert_eq!(response.status(), StatusCode::OK, "{name}");
let headers = response.headers().clone();
assert!(
headers.get(header::CONTENT_ENCODING).is_none(),
"{name}: the file must not be content-encoded"
);
assert_eq!(headers[header::CACHE_CONTROL], "no-store", "{name}");
assert_eq!(headers[header::X_CONTENT_TYPE_OPTIONS], "nosniff", "{name}");
let disposition = headers[header::CONTENT_DISPOSITION].to_str().unwrap();
let short: String = id.simple().to_string().chars().take(8).collect();
assert!(
disposition.starts_with("attachment; filename=\"")
&& disposition.contains(&format!("_{short}.{extension}\""))
&& disposition.contains("filename*=UTF-8''"),
"{name}: {disposition}"
);
assert!(
!disposition.contains(&id.to_string()),
"{name}: the full id is not the file name any more"
);
let content_type = if extension.ends_with("gz") {
"application/gzip"
} else {
"application/octet-stream"
};
assert_eq!(headers[header::CONTENT_TYPE], content_type, "{name}");
let body = to_bytes(response.into_body(), 1 << 26)
.await
.unwrap()
.to_vec();
if compressed {
assert!(
headers.get(header::CONTENT_LENGTH).is_none(),
"{name}: the compressed size is not known up front"
);
assert_eq!(&body[..2], &[0x1f, 0x8b], "{name}: a real gzip stream");
assert_eq!(
gunzip(&body).await,
payload,
"{name}: decompresses to exactly the original bytes"
);
} else {
assert_eq!(body, payload, "{name}: sent untouched");
assert_eq!(
headers[header::CONTENT_LENGTH],
payload.len().to_string(),
"{name}: exact length"
);
}
}
assert!(
h.export_dirs().is_empty(),
"nothing is left behind after the downloads"
);
}
#[tokio::test]
async fn a_large_snapshot_is_streamed_in_small_frames_and_arrives_intact() {
let h = harness().await;
let line = b"INSERT INTO events VALUES (1, 'a fairly ordinary row of text');\n";
let payload: Vec<u8> = line
.iter()
.copied()
.cycle()
.take(24 * 1024 * 1024)
.collect();
let id = h
.snapshot(serde_json::json!({"format": "plain"}), &payload)
.await;
let response = h.download(id, Method::GET).await;
let mut stream = response.into_body().into_data_stream();
let (mut compressed, mut frames, mut largest) = (Vec::new(), 0, 0);
while let Some(frame) = stream.next().await {
let frame = frame.unwrap();
frames += 1;
largest = largest.max(frame.len());
compressed.extend_from_slice(&frame);
}
assert!(
frames > 5 && largest <= 256 * 1024,
"{frames} frames, largest {largest} bytes"
);
let restored = gunzip(&compressed).await;
assert_eq!(
(restored.len(), Sha256::digest(&restored)),
(payload.len(), Sha256::digest(&payload))
);
assert!(
compressed.len() < payload.len() / 10,
"the stream really is compressed"
);
}
#[tokio::test]
async fn the_audit_trail_and_cleanup_cover_a_finished_and_an_abandoned_download() {
let h = harness().await;
let finished = h
.snapshot(
serde_json::json!({"format": "plain"}),
&b"SELECT 1;\n".repeat(50_000),
)
.await;
let body = to_bytes(h.download(finished, Method::GET).await.into_body(), 1 << 26)
.await
.unwrap();
assert!(!body.is_empty());
let expected = |last: (&str, &str)| {
vec![
("export.requested".to_string(), "allowed".to_string()),
("export.ready".into(), "succeeded".into()),
(last.0.to_string(), last.1.to_string()),
]
};
assert_eq!(
h.audit(finished),
expected(("export.finished", "succeeded"))
);
assert!(h.export_dirs().is_empty());
// The client reads one frame and goes away.
let abandoned = h
.snapshot(
serde_json::json!({"format": "plain"}),
&b"SELECT 2;\n".repeat(2_000_000),
)
.await;
let response = h.download(abandoned, Method::GET).await;
assert_eq!(
h.export_dirs().len(),
1,
"the export exists while the body is alive"
);
let mut stream = response.into_body().into_data_stream();
stream.next().await.unwrap().unwrap();
drop(stream);
assert_eq!(
h.audit(abandoned),
expected(("export.disconnected", "failed"))
);
assert!(
h.export_dirs().is_empty(),
"the export is deleted when the client disconnects"
);
}
#[tokio::test]
async fn only_one_export_runs_when_the_limit_is_one_and_a_refused_request_leaks_nothing() {
let h = harness_with(Some(ExportGate::new(1, 0))).await;
let id = h
.snapshot(
serde_json::json!({"format": "plain"}),
&b"SELECT 1;\n".repeat(10_000),
)
.await;
let first = h.download(id, Method::GET).await;
assert_eq!(first.status(), StatusCode::OK);
let started = std::time::Instant::now();
let second = h.download(id, Method::GET).await;
assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(
started.elapsed() < std::time::Duration::from_secs(1),
"refused at once, not queued"
);
assert_eq!(
h.export_dirs().len(),
1,
"the refused request wrote nothing"
);
drop(first);
let third = h.download(id, Method::GET).await;
assert_eq!(
third.status(),
StatusCode::OK,
"the slot returns when the first download ends"
);
let audited = h.audit(id);
assert!(
audited.contains(&("export.requested".to_string(), "failed".to_string())),
"{audited:?}"
);
}
#[tokio::test]
async fn an_export_that_would_not_fit_on_the_disk_is_refused_before_anything_is_written() {
let h = harness_with(Some(ExportGate::new(2, u64::MAX / 2))).await;
let id = h
.snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n")
.await;
assert_eq!(
h.download(id, Method::GET).await.status(),
StatusCode::INSUFFICIENT_STORAGE
);
assert!(h.export_dirs().is_empty());
}
#[tokio::test]
async fn head_requests_do_not_run_an_export() {
let h = harness().await;
let id = h
.snapshot(serde_json::json!({"format": "plain"}), b"SELECT 1;\n")
.await;
let response = h.download(id, Method::HEAD).await;
assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
assert!(h.export_dirs().is_empty());
assert!(h.audit(id).is_empty(), "no export was requested");
}

View File

@@ -0,0 +1,236 @@
//! The one place that decides what an authenticated caller may do.
//!
//! Order everywhere: authenticate (401 / CSRF 403), resolve the resource, then
//! the gate. A resource the caller cannot see answers 404 (it is not confirmed to
//! exist); one they can see but may not use answers 403. Grants are read from the
//! database on every call, so a revoke is effective on the next request.
use super::routes::OperatorActor;
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Permission};
use crate::state::HubState;
use axum::http::StatusCode;
use std::collections::HashSet;
use uuid::Uuid;
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn audit(
state: &HubState,
actor: &OperatorActor,
resource: AuditResource,
allowed: bool,
) -> Result<(), StatusCode> {
state
.db
.audit_event(
&actor.principal,
AuditAction::Authorization,
resource,
if allowed {
AuditOutcome::Allowed
} else {
AuditOutcome::Denied
},
actor.request_id,
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
fn internal(error: impl std::fmt::Display) -> StatusCode {
tracing::error!("authorization lookup failed: {error}");
StatusCode::INTERNAL_SERVER_ERROR
}
/// Management actions are never delegated: anyone who is not a configured
/// administrator gets 403 without any lookup, so this also reveals nothing about resources.
pub(super) fn admin_only(state: &HubState, actor: &OperatorActor) -> Result<(), StatusCode> {
let allowed = actor.subject.admin;
audit(state, actor, AuditResource::Api, allowed)?;
if allowed {
Ok(())
} else {
Err(StatusCode::FORBIDDEN)
}
}
/// Use `permission` on one orbit. Not visible (no `orbit.read`) is 404, visible
/// but not permitted is 403. A permission that cannot be granted is admin-only.
pub(super) fn scoped(
state: &HubState,
actor: &OperatorActor,
permission: Permission,
orbit: Uuid,
) -> Result<(), StatusCode> {
let resource = AuditResource::Orbit(orbit);
if actor.subject.admin {
return audit(state, actor, resource, true);
}
let held = |permission: Permission| -> Result<bool, StatusCode> {
if permission.grantable() {
{
state
.db
.has_permission(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
permission.as_str(),
&orbit.to_string(),
now(),
)
.map_err(internal)
}
} else {
Ok(false)
}
};
if !held(Permission::OrbitRead)? {
audit(state, actor, resource, false)?;
return Err(StatusCode::NOT_FOUND);
}
let allowed = held(permission)?;
audit(state, actor, resource, allowed)?;
if allowed {
Ok(())
} else {
Err(StatusCode::FORBIDDEN)
}
}
/// Use one relation. Administrators always; anyone else only through a live grant on that very relation
/// (not on its orbit, not on an older version of it). Everything else answers 404, so a relation's
/// existence is not confirmed to someone who cannot use it.
pub(super) fn relation(
state: &HubState,
actor: &OperatorActor,
relation: Uuid,
) -> Result<(), StatusCode> {
let resource = AuditResource::Relation(relation);
if actor.subject.admin {
return audit(state, actor, resource, true);
}
let granted = state
.db
.granted_relations(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
now(),
)
.map_err(internal)?;
let allowed = granted.iter().any(|id| id == &relation.to_string());
audit(state, actor, resource, allowed)?;
if allowed {
Ok(())
} else {
Err(StatusCode::NOT_FOUND)
}
}
/// The relations a caller may use: `None` for an administrator (all), otherwise their granted ids.
/// A caller with none gets 403 rather than an empty list.
pub(super) fn visible_relations(
state: &HubState,
actor: &OperatorActor,
) -> Result<Option<Vec<String>>, StatusCode> {
if actor.subject.admin {
audit(state, actor, AuditResource::Api, true)?;
return Ok(None);
}
let granted = state
.db
.granted_relations(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
now(),
)
.map_err(internal)?;
audit(state, actor, AuditResource::Api, !granted.is_empty())?;
if granted.is_empty() {
Err(StatusCode::FORBIDDEN)
} else {
Ok(Some(granted))
}
}
/// Which orbits a list may show.
pub(super) enum Visible {
All,
Only(HashSet<Uuid>),
}
impl Visible {
pub(super) fn contains(&self, orbit: Uuid) -> bool {
match self {
Self::All => true,
Self::Only(set) => set.contains(&orbit),
}
}
/// SQL-friendly form: `None` = no restriction.
pub(super) fn restriction(&self) -> Option<Vec<String>> {
match self {
Self::All => None,
Self::Only(set) => Some(set.iter().map(Uuid::to_string).collect()),
}
}
}
/// Orbits where the caller holds both `orbit.read` and `permission`. A caller
/// with nothing to see gets 403 rather than an empty list.
pub(super) fn visible(
state: &HubState,
actor: &OperatorActor,
permission: Permission,
) -> Result<Visible, StatusCode> {
if actor.subject.admin {
audit(state, actor, AuditResource::Api, true)?;
return Ok(Visible::All);
}
let fetch = |permission: Permission| {
if !permission.grantable() {
return Ok(Default::default());
}
state
.db
.permitted_orbits(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
permission.as_str(),
now(),
)
.map_err(internal)
};
let read = fetch(Permission::OrbitRead)?;
let wanted = if permission == Permission::OrbitRead {
None
} else {
Some(fetch(permission)?)
};
let parse = |set: &HashSet<String>| -> HashSet<Uuid> {
set.iter()
.filter_map(|id| Uuid::parse_str(id).ok())
.collect()
};
let result = match wanted {
None if read.everywhere => Visible::All,
None => Visible::Only(parse(&read.orbits)),
Some(w) => match (read.everywhere, w.everywhere) {
(true, true) => Visible::All,
(true, false) => Visible::Only(parse(&w.orbits)),
(false, true) => Visible::Only(parse(&read.orbits)),
(false, false) => Visible::Only(
parse(&read.orbits)
.intersection(&parse(&w.orbits))
.copied()
.collect(),
),
},
};
let nothing = matches!(&result, Visible::Only(set) if set.is_empty());
audit(state, actor, AuditResource::Api, !nothing)?;
if nothing {
Err(StatusCode::FORBIDDEN)
} else {
Ok(result)
}
}

View File

@@ -0,0 +1,614 @@
use super::routes::{admin_write, authenticate, upload_token};
use crate::auth::Permission;
use crate::state::HubState;
use axum::{
body::{Body, HttpBody},
extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
http::{header, HeaderMap, StatusCode},
routing::{get, post},
Json, Router,
};
use base64::Engine;
use sha2::{Digest, Sha256};
use std::{net::SocketAddr, pin::Pin, time::Duration};
use tessera_core::job::{
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport,
ResticCaptureCommit,
};
use tessera_core::{restore::DatabaseIdentity, SnapshotManifest};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route(
"/api/v1/capture-profiles",
get(profiles).post(register_profile),
)
.route(
"/api/v1/capture-profiles/:id",
axum::routing::put(update_profile),
)
.route("/api/v1/capture-profiles/:id/jobs", post(enqueue))
.route("/api/v1/capture-jobs", get(history))
.route("/api/v1/capture-jobs/:id", get(job))
.route("/api/v1/capture-jobs/:id/events", get(events))
.route("/api/v1/wormhole/capture/:application/claim", post(claim))
.route("/api/v1/wormhole/capture/:id/report", post(report))
.route("/api/v1/wormhole/capture/:id/payload", post(upload))
.route("/api/v1/wormhole/capture/:id/restic", post(commit_restic))
}
async fn profiles(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
let actor = authenticate(&state, peer, &headers, false)?;
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
let profiles = state.db.capture_profiles().map_err(internal)?;
Ok(Json(
profiles
.into_iter()
.filter(|profile| visible.contains(profile.orbit_id))
.collect(),
))
}
async fn register_profile(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(profile): Json<CaptureProfile>,
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
if profile
.retention
.is_some_and(|retention| !retention.is_valid())
{
return Err(StatusCode::BAD_REQUEST);
}
if let Some(schedule) = &profile.schedule {
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
}
let _vault = state.vault.write().await;
if !state
.db
.register_capture_profile(&profile, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
state
.db
.audit(
"capture.profile_registered",
&format!("actor={actor} application={}", profile.application_id),
)
.await
.map_err(internal)?;
Ok((StatusCode::CREATED, Json(profile)))
}
/// Editable parts of a profile. A field that is absent stays as it is; `null` clears it. Anything else
/// (format, orbit, Outpost) is part of the profile's identity and is refused.
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct ProfileUpdate {
#[serde(default, deserialize_with = "present")]
schedule: Option<Option<tessera_core::job::CaptureSchedule>>,
#[serde(default, deserialize_with = "present")]
retention: Option<Option<tessera_core::decay::CaptureRetention>>,
}
/// Tell `null` from an absent field: `Some(None)` for null, `Some(Some(v))` for a value.
fn present<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de>,
{
<Option<T> as serde::Deserialize>::deserialize(deserializer).map(Some)
}
async fn update_profile(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(update): Json<ProfileUpdate>,
) -> Result<Json<CaptureProfile>, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
if let Some(Some(retention)) = &update.retention {
if !retention.is_valid() {
return Err(StatusCode::BAD_REQUEST);
}
}
if let Some(Some(schedule)) = &update.schedule {
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
}
let mut fields = Vec::new();
if update.schedule.is_some() {
fields.push("schedule");
}
if update.retention.is_some() {
fields.push("retention");
}
let _vault = state.vault.write().await;
let profile = state
.db
.update_capture_profile(
id,
crate::db::ProfileChange {
schedule: update.schedule,
retention: update.retention,
},
now(),
)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
state
.db
.audit(
"capture.profile_updated",
&format!("actor={actor} application={id} fields={}", fields.join(",")),
)
.await
.map_err(internal)?;
Ok(Json(profile))
}
async fn enqueue(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
let actor = authenticate(&state, peer, &headers, true)?;
let orbit = state.db.orbit_of_application(id).map_err(internal)?;
match orbit {
Some(orbit) => super::gate::scoped(&state, &actor, Permission::CaptureRun, orbit)?,
// no such application: administrators learn that, everyone else cannot tell it from "not visible"
None => {
super::gate::admin_only(&state, &actor).map_err(|_| StatusCode::NOT_FOUND)?;
return Err(StatusCode::NOT_FOUND);
}
}
let job = state
.db
.enqueue_capture(id, &actor.id(), now())
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok((StatusCode::ACCEPTED, Json(job)))
}
#[derive(serde::Deserialize)]
struct JobFilter {
application_id: Option<Uuid>,
status: Option<String>,
limit: Option<u16>,
}
async fn history(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Query(filter): Query<JobFilter>,
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
let actor = authenticate(&state, peer, &headers, false)?;
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
if let Some(application) = filter.application_id {
let orbit = state
.db
.orbit_of_application(application)
.map_err(internal)?;
if !orbit.is_some_and(|orbit| visible.contains(orbit)) {
return Err(StatusCode::NOT_FOUND);
}
}
if filter
.status
.as_deref()
.is_some_and(|status| !matches!(status, "queued" | "running" | "completed" | "failed"))
{
return Err(StatusCode::BAD_REQUEST);
}
state
.db
.capture_jobs(
filter.application_id,
filter.status.as_deref(),
filter.limit.unwrap_or(50).clamp(1, 200),
visible.restriction().as_deref(),
)
.map(Json)
.map_err(internal)
}
/// A capture job, if the caller may read its orbit; otherwise 404.
fn job_in_scope(
state: &HubState,
actor: &super::routes::OperatorActor,
id: Uuid,
) -> Result<CaptureJob, StatusCode> {
let job = state.db.capture_job(id).map_err(internal)?;
match job {
Some(job) => {
super::gate::scoped(state, actor, Permission::OrbitRead, job.profile.orbit_id)?;
Ok(job)
}
None => {
super::gate::admin_only(state, actor).map_err(|_| StatusCode::NOT_FOUND)?;
Err(StatusCode::NOT_FOUND)
}
}
}
async fn events(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
let actor = authenticate(&state, peer, &headers, false)?;
let job = job_in_scope(&state, &actor, id)?;
state.db.capture_events(job.id).map(Json).map_err(internal)
}
async fn job(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<CaptureJob>, StatusCode> {
let actor = authenticate(&state, peer, &headers, false)?;
job_in_scope(&state, &actor, id).map(Json)
}
async fn claim(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(application): Path<Uuid>,
) -> Result<Json<Option<CaptureLease>>, StatusCode> {
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let mut lease = state
.db
.claim_capture(outpost, application, now())
.map_err(internal)?;
if let Some(lease) = &mut lease {
lease.restic |= lease.profile.format == CaptureFormat::Filesystem
|| state
.vault
.read()
.await
.outpost_repository_configured(lease.profile.orbit_id)
.map_err(internal)?;
}
Ok(Json(lease))
}
async fn report(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Result<Json<CaptureReport>, JsonRejection>,
) -> Result<StatusCode, StatusCode> {
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
if !state
.db
.report_capture(outpost, id, body, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}
async fn upload(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
.map_err(|_| StatusCode::BAD_REQUEST)?;
let job = state
.db
.capture_upload(outpost, id, lease, now())
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if job.profile.format == CaptureFormat::Filesystem
|| state
.db
.restic_required(job.profile.orbit_id)
.map_err(internal)?
|| state
.vault
.read()
.await
.outpost_repository_configured(job.profile.orbit_id)
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
let identity = headers
.get("x-tessera-source-identity")
.map(|header| {
let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(header.as_bytes())
.map_err(|_| StatusCode::BAD_REQUEST)?;
let identity: DatabaseIdentity =
serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?;
if !job
.profile
.format
.engine()
.is_some_and(|engine| identity.valid(engine))
{
return Err(StatusCode::BAD_REQUEST);
}
Ok(identity)
})
.transpose()?;
let (file, expected) = receive_payload(&state, &headers, body, job.profile.format).await?;
if let Some(snapshot) = job.snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
}
let orbit_id = job.profile.orbit_id;
let manifest = capture_manifest(&state, &job, identity, Some(hex::encode(expected))).await?;
let vault = state.vault.clone().read_owned().await;
let db = state.db.clone();
let offsite_enabled = state.offsite.is_some();
let (snapshot, created) = tokio::task::spawn_blocking(move || {
// SQLite fencing covers metadata publication. Restic work happens before the transaction.
let prepared = if vault.has_published_snapshot(id)? {
None
} else {
Some(vault.prepare_payload(manifest, file, false)?)
};
let mut wrote = false;
let published = db.publish_capture(outpost, id, lease, offsite_enabled, |_| {
if !vault.has_published_snapshot(id)? {
vault.publish_prepared(
prepared
.as_ref()
.ok_or_else(|| anyhow::anyhow!("prepared snapshot missing"))?,
)?;
wrote = true;
}
Ok(())
})?;
// Preserve a prepared copy on an ambiguous commit error for reconciliation.
if !wrote {
if let Some(snap) = prepared.as_ref() {
if let Err(error) = vault.discard_prepared(snap) {
tracing::warn!(%id, %error, "could not discard unpublished capture");
}
}
}
Ok::<_, anyhow::Error>(published)
})
.await
.map_err(internal)?
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if created && state.prune_orbit(orbit_id).await.is_err() {
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
}
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
}
async fn commit_restic(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(commit): Json<ResticCaptureCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let job = state
.db
.capture_upload(outpost, id, commit.lease_id, now())
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if let Some(snapshot) = job.snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
}
let engine = job.profile.format.engine();
if commit
.identity
.as_ref()
.is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine)))
|| (engine.is_some()
&& !commit.sha256.as_ref().is_some_and(|hash| {
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
}))
|| (engine.is_none() && commit.sha256.is_some())
{
return Err(StatusCode::BAD_REQUEST);
}
let orbit_id = job.profile.orbit_id;
let manifest = capture_manifest(&state, &job, commit.identity, commit.sha256).await?;
let vault = state.vault.clone().read_owned().await;
let db = state.db.clone();
let offsite = state.offsite.is_some() && engine.is_some();
let (snapshot, created) = tokio::task::spawn_blocking(move || {
let prepared = vault.prepare_outpost_capture(manifest, outpost, &commit.snapshot_id)?;
db.publish_capture(outpost, id, commit.lease_id, offsite, |_| {
if !vault.has_published_snapshot(id)? {
vault.publish_prepared(&prepared)?;
}
Ok(())
})
})
.await
.map_err(internal)?
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if created && state.prune_orbit(orbit_id).await.is_err() {
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
}
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
}
async fn capture_manifest(
state: &HubState,
job: &CaptureJob,
identity: Option<DatabaseIdentity>,
digest: Option<String>,
) -> Result<SnapshotManifest, StatusCode> {
let id = job.id;
let orbit_id = job.profile.orbit_id;
let orbit = state
.db
.list_orbits()
.await
.map_err(internal)?
.into_iter()
.find(|orbit| orbit.id == orbit_id)
.ok_or(StatusCode::NOT_FOUND)?;
let (engine, format) = match job.profile.format {
CaptureFormat::PostgresCustom => ("postgres", "custom"),
CaptureFormat::PostgresSql => ("postgres", "plain"),
CaptureFormat::MysqlSql => ("mysql", "plain"),
CaptureFormat::Filesystem => ("filesystem", "tar"),
};
Ok(SnapshotManifest {
snapshot_id: id,
orbit_id,
orbit_name: orbit.name,
labels: vec![engine.into()],
provider: engine.into(),
paths: vec![],
restore_hints: serde_json::json!({
"engine": engine, "format": format, "job_id": id, "outpost_id": job.profile.outpost_id,
"application_id": job.profile.application_id, "sha256": digest,
"queued_at": job.created_at, "uploaded_at": now(), "source_identity": identity
}),
})
}
pub(super) async fn receive_payload(
state: &HubState,
headers: &HeaderMap,
mut body: Body,
format: CaptureFormat,
) -> Result<(std::fs::File, [u8; 32]), StatusCode> {
let length = header_value(headers, header::CONTENT_LENGTH.as_str())?
.parse::<u64>()
.map_err(|_| StatusCode::BAD_REQUEST)?;
if length == 0 || length > 100 * 1024 * 1024 * 1024 {
return Err(StatusCode::PAYLOAD_TOO_LARGE);
}
let mut expected = [0u8; 32];
hex::decode_to_slice(header_value(headers, "x-tessera-sha256")?, &mut expected)
.map_err(|_| StatusCode::BAD_REQUEST)?;
let file = tempfile::tempfile_in(&state.data_dir).map_err(internal)?;
let mut file = tokio::fs::File::from_std(file);
let mut digest = Sha256::new();
let mut bytes = 0;
loop {
let next = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx));
let Some(frame) = tokio::time::timeout(Duration::from_secs(30), next)
.await
.map_err(|_| StatusCode::REQUEST_TIMEOUT)?
else {
break;
};
let frame = frame.map_err(|_| StatusCode::BAD_REQUEST)?;
if let Ok(chunk) = frame.into_data() {
bytes += chunk.len() as u64;
if bytes > length {
return Err(StatusCode::BAD_REQUEST);
}
digest.update(&chunk);
file.write_all(&chunk).await.map_err(internal)?;
}
}
if bytes != length || digest.finalize()[..] != expected {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
file.flush().await.map_err(internal)?;
if format == CaptureFormat::PostgresCustom {
let mut signature = [0; 5];
file.seek(std::io::SeekFrom::Start(0))
.await
.map_err(internal)?;
if file.read_exact(&mut signature).await.is_err() || &signature != b"PGDMP" {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
}
Ok((file.into_std().await, expected))
}
pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, StatusCode> {
headers
.get(name)
.and_then(|value| value.to_str().ok())
.ok_or(StatusCode::BAD_REQUEST)
}
pub(super) fn outpost(
state: &HubState,
peer: Option<std::net::SocketAddr>,
headers: &HeaderMap,
) -> Result<Uuid, StatusCode> {
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
let result = authenticate_outpost(state, headers);
match result {
Ok(id) => {
state
.db
.audit_event(
&Principal::Outpost(id),
AuditAction::Authentication,
AuditResource::Outpost(id),
AuditOutcome::Allowed,
Uuid::new_v4(),
)
.map_err(internal)?;
}
Err(_) => {
// One denial row per source per minute; a failed audit write must not
// change the refusal into a 500.
let source = state.limits.source(peer, headers);
if state.limits.audit_denial(source) {
if let Err(error) = state.db.audit_event(
&Principal::Anonymous,
AuditAction::Authentication,
AuditResource::Api,
AuditOutcome::Denied,
Uuid::new_v4(),
) {
tracing::error!(%error, "could not record a denied outpost authentication");
}
}
}
}
result
}
fn authenticate_outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
let token = upload_token(state, headers)?;
let id = state
.db
.upload_token_outpost(token, chrono::Utc::now().timestamp())
.map_err(internal)?
.ok_or(StatusCode::UNAUTHORIZED)?;
let id = Uuid::parse_str(&id).map_err(internal)?;
state.db.touch_outpost(id).map_err(internal)?;
Ok(id)
}
pub(super) fn now() -> i64 {
chrono::Utc::now().timestamp()
}
pub(super) fn internal(_: impl std::fmt::Display) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}

View File

@@ -1,5 +1,28 @@
mod access;
#[cfg(test)]
mod access_tests;
#[cfg(test)]
mod auth_contract;
mod catalog;
#[cfg(test)]
mod credentials_tests;
#[cfg(test)]
mod export_tests;
mod gate;
mod jobs;
mod oidc;
#[cfg(test)]
mod oidc_tests;
mod orbit;
mod refresh;
#[cfg(test)]
mod refresh_tests;
mod relations;
mod restore;
mod routes;
mod session;
pub use orbit::run_orbit_internal;
pub(crate) use relations::identity_facts;
pub(crate) use restore::{artifact, rollback_artifact};
pub use routes::router;

View File

@@ -0,0 +1,232 @@
//! Browser SSO endpoints. Both are public GET navigations: the IdP redirects
//! the browser back here. No tokens are ever sent to the browser, and every
//! redirect target is fixed (`/`), so there is no `next` parameter to abuse.
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::oidc::OidcError;
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, Query, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Redirect, Response},
routing::get,
Router,
};
use serde::Deserialize;
use std::net::SocketAddr;
const CORRELATION: &str = "__Host-tessera-oidc";
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/auth/oidc/login", get(login))
.route("/api/v1/auth/oidc/callback", get(callback))
}
#[derive(Deserialize)]
struct CallbackQuery {
code: Option<String>,
state: Option<String>,
error: Option<String>,
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
/// Correlation cookie: SameSite=Lax so it survives the IdP's cross-site GET
/// redirect, while the session cookie itself stays Strict.
fn correlation_cookie(value: Option<&str>) -> HeaderValue {
let text = format!(
"{CORRELATION}={}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age={}",
value.unwrap_or_default(),
if value.is_some() {
crate::db::oidc_login::TTL_SECS
} else {
0
},
);
HeaderValue::from_str(&text).expect("cookie is ASCII")
}
fn no_store(headers: &mut HeaderMap) {
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
}
fn correlation_from(headers: &HeaderMap) -> Option<String> {
headers
.get_all(header::COOKIE)
.iter()
.filter_map(|h| h.to_str().ok())
.flat_map(|line| line.split(';'))
.find_map(|pair| {
let (name, value) = pair.trim().split_once('=')?;
(name == CORRELATION && !value.is_empty() && value.len() <= 128)
.then(|| value.to_string())
})
}
async fn login(
peer: Option<ConnectInfo<SocketAddr>>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Response {
let Some(oidc) = state.oidc.clone() else {
return StatusCode::NOT_FOUND.into_response();
};
let source = state.limits.source(peer.map(|ConnectInfo(a)| a), &headers);
if !state.limits.oidc_login_allowed(source) {
return StatusCode::TOO_MANY_REQUESTS.into_response();
}
let begun = match oidc.begin().await {
Ok(begun) => begun,
Err(_) => return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await,
};
let browser = uuid::Uuid::new_v4().to_string();
let stored =
state
.db
.begin_oidc_login(&begun.state, &browser, &begun.nonce, &begun.verifier, now());
if !matches!(stored, Ok(true)) {
return failure(&state, "unavailable", StatusCode::SERVICE_UNAVAILABLE).await;
}
let mut response = Redirect::to(&begun.url).into_response();
no_store(response.headers_mut());
response
.headers_mut()
.append(header::SET_COOKIE, correlation_cookie(Some(&browser)));
response
}
async fn callback(
peer: Option<ConnectInfo<SocketAddr>>,
State(state): State<HubState>,
headers: HeaderMap,
Query(query): Query<CallbackQuery>,
) -> Response {
let Some(oidc) = state.oidc.clone() else {
return StatusCode::NOT_FOUND.into_response();
};
let source = state.limits.source(peer.map(|ConnectInfo(a)| a), &headers);
if !state.limits.oidc_callback_allowed(source) {
return StatusCode::TOO_MANY_REQUESTS.into_response();
}
let outcome = complete(&state, &oidc, &headers, query).await;
let mut response = match outcome {
Ok(session) => {
let mut response = Redirect::to("/").into_response();
if let Ok(cookie) = super::session::session_cookie(Some(&session.id.to_string())) {
response.headers_mut().append(header::SET_COOKIE, cookie);
}
response
}
Err(code) => Redirect::to(&format!("/?auth_error={code}")).into_response(),
};
no_store(response.headers_mut());
// The correlation cookie is single-use whatever happened.
response
.headers_mut()
.append(header::SET_COOKIE, correlation_cookie(None));
response
}
/// Returns the new session, or a fixed error code that is safe to show.
async fn complete(
state: &HubState,
oidc: &crate::oidc::OidcProvider,
headers: &HeaderMap,
query: CallbackQuery,
) -> Result<crate::admin::BrowserSession, &'static str> {
let request = uuid::Uuid::new_v4();
let audit = |principal: &Principal, outcome| {
let _ = state.db.audit_event(
principal,
AuditAction::Login,
AuditResource::Session,
outcome,
request,
);
};
let Some(state_param) = query.state.as_deref() else {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("invalid_state");
};
let browser = correlation_from(headers);
let transaction = state
.db
.consume_oidc_login(state_param, browser.as_deref(), now());
let Ok(Some((nonce, verifier))) = transaction else {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("invalid_state");
};
if query.error.is_some() {
// The IdP refused (for example access_denied); nothing from it is echoed.
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("denied");
}
let Some(code) = query
.code
.as_deref()
.filter(|c| !c.is_empty() && c.len() <= 2048)
else {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err("failed");
};
let identity = match oidc.finish(code, &nonce, &verifier).await {
Ok(identity) => identity,
Err(error) => {
audit(&Principal::Anonymous, AuditOutcome::Failed);
return Err(if matches!(error, OidcError::Unavailable) {
"unavailable"
} else {
"failed"
});
}
};
let admin = oidc.config.is_admin(&identity);
// Bounded, so a hostile or huge claim cannot bloat the session row.
let groups: Vec<String> = identity
.groups
.iter()
.filter(|g| !g.is_empty() && g.len() <= 128)
.take(64)
.cloned()
.collect();
let now = now();
let session = state
.db
.upsert_user(
&identity.issuer,
&identity.subject,
&identity.display_name,
now,
)
.and_then(|user_id| {
state
.sessions
.create_oidc(&user_id, &identity.display_name, admin, &groups, now)
});
match session {
Ok(session) => {
audit(&session.principal(), AuditOutcome::Succeeded);
Ok(session)
}
Err(error) => {
tracing::warn!("OIDC session not created: {error:#}");
audit(&Principal::Anonymous, AuditOutcome::Failed);
Err("disabled")
}
}
}
async fn failure(state: &HubState, code: &'static str, status: StatusCode) -> Response {
let _ = state.db.audit_event(
&Principal::Anonymous,
AuditAction::Login,
AuditResource::Session,
AuditOutcome::Failed,
uuid::Uuid::new_v4(),
);
let mut response = (status, code).into_response();
no_store(response.headers_mut());
response
}

View File

@@ -0,0 +1,804 @@
//! End-to-end OIDC login against a mock IdP. Tokens are hand-built and signed
//! with throwaway RSA keys generated in this process, so every negative case
//! (wrong nonce, issuer, audience, signature, `alg: none`, HS256, rotation) is
//! a real failure of verification, not of the fixture.
use crate::admin::SessionGate;
use crate::oidc::{OidcConfig, OidcProvider};
use crate::state::HubState;
use axum::body::{to_bytes, Body};
use axum::extract::ConnectInfo;
use axum::http::{header, Request, Response, StatusCode};
use base64::Engine;
use hmac::{Hmac, Mac};
use rsa::pkcs1v15::SigningKey;
use rsa::signature::{SignatureEncoding, Signer};
use rsa::traits::PublicKeyParts;
use rsa::RsaPrivateKey;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::net::SocketAddr;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use tower::ServiceExt;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, Request as MockRequest, Respond, ResponseTemplate};
const CLIENT_ID: &str = "tessera";
const CLIENT_SECRET: &str = "synthetic-client-secret";
const REDIRECT: &str = "https://hub.example/api/v1/auth/oidc/callback";
fn b64(bytes: impl AsRef<[u8]>) -> String {
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
}
/// Index 0 = the IdP's key, 1 = its rotated key, 2 = an attacker's key.
fn keys() -> &'static [RsaPrivateKey; 3] {
static KEYS: OnceLock<[RsaPrivateKey; 3]> = OnceLock::new();
KEYS.get_or_init(|| {
let mut rng = rand::rngs::OsRng;
[0, 1, 2].map(|_| RsaPrivateKey::new(&mut rng, 2048).unwrap())
})
}
#[derive(Clone)]
struct Scenario {
nonce: String,
challenge: String,
sub: Option<String>,
name: Option<String>,
email: Option<String>,
iss: Option<String>,
aud: Value,
azp: Option<String>,
exp_in: i64,
alg: &'static str,
signer: usize,
kid: &'static str,
groups: Option<Value>,
token_status: u16,
}
impl Default for Scenario {
fn default() -> Self {
Self {
nonce: String::new(),
challenge: String::new(),
sub: Some("admin-sub".into()),
name: Some("Ada Admin".into()),
email: None,
iss: None,
aud: json!(CLIENT_ID),
azp: None,
exp_in: 3600,
alg: "RS256",
signer: 0,
kid: "k1",
groups: None,
token_status: 200,
}
}
}
struct Idp {
server: MockServer,
scenario: Arc<Mutex<Scenario>>,
jwks: Arc<Mutex<Vec<(&'static str, usize)>>>,
}
struct TokenEndpoint {
scenario: Arc<Mutex<Scenario>>,
issuer: String,
}
fn sign(alg: &str, kid: &str, signer: usize, claims: &Value) -> String {
let header = json!({"alg": alg, "typ": "JWT", "kid": kid});
let signing_input = format!("{}.{}", b64(header.to_string()), b64(claims.to_string()));
let signature = match alg {
"RS256" => b64(SigningKey::<Sha256>::new(keys()[signer].clone())
.sign(signing_input.as_bytes())
.to_bytes()),
"HS256" => {
let mut mac = Hmac::<Sha256>::new_from_slice(CLIENT_SECRET.as_bytes()).unwrap();
mac.update(signing_input.as_bytes());
b64(mac.finalize().into_bytes())
}
_ => String::new(), // alg "none"
};
format!("{signing_input}.{signature}")
}
impl Respond for TokenEndpoint {
fn respond(&self, request: &MockRequest) -> ResponseTemplate {
let scenario = self.scenario.lock().unwrap().clone();
if scenario.token_status != 200 {
return ResponseTemplate::new(scenario.token_status);
}
let form: std::collections::HashMap<String, String> =
openidconnect::url::form_urlencoded::parse(&request.body)
.into_owned()
.collect();
// Real PKCE check: S256(code_verifier) must equal the challenge sent at /authorize.
let verifier = form.get("code_verifier").cloned().unwrap_or_default();
if b64(Sha256::digest(verifier.as_bytes())) != scenario.challenge
|| form.get("code").map(String::as_str) != Some("good-code")
{
return ResponseTemplate::new(400).set_body_json(json!({"error": "invalid_grant"}));
}
let now = chrono::Utc::now().timestamp();
let mut claims = json!({
"iss": scenario.iss.clone().unwrap_or_else(|| self.issuer.clone()),
"aud": scenario.aud,
"exp": now + scenario.exp_in,
"iat": now,
"nonce": scenario.nonce,
});
let object = claims.as_object_mut().unwrap();
if let Some(sub) = &scenario.sub {
object.insert("sub".into(), json!(sub));
}
if let Some(name) = &scenario.name {
object.insert("preferred_username".into(), json!(name));
}
if let Some(email) = &scenario.email {
object.insert("email".into(), json!(email));
}
if let Some(azp) = &scenario.azp {
object.insert("azp".into(), json!(azp));
}
if let Some(groups) = &scenario.groups {
object.insert("groups".into(), groups.clone());
}
ResponseTemplate::new(200).set_body_json(json!({
"access_token": "synthetic-access-token-never-shown",
"token_type": "Bearer",
"expires_in": 3600,
"id_token": sign(scenario.alg, scenario.kid, scenario.signer, &claims),
}))
}
}
impl Idp {
async fn start() -> Self {
// Generate the RSA keys up front: inside a mock handler, a slow debug-build
// keygen would eat the hub's HTTP timeout.
tokio::task::spawn_blocking(|| {
keys();
})
.await
.unwrap();
let server = MockServer::start().await;
let scenario = Arc::new(Mutex::new(Scenario::default()));
let jwks = Arc::new(Mutex::new(vec![("k1", 0usize)]));
let issuer = server.uri();
Mock::given(method("GET"))
.and(path("/.well-known/openid-configuration"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": issuer,
"authorization_endpoint": format!("{issuer}/authorize"),
"token_endpoint": format!("{issuer}/token"),
"jwks_uri": format!("{issuer}/jwks"),
"response_types_supported": ["code"],
"subject_types_supported": ["public"],
"id_token_signing_alg_values_supported": ["RS256"],
})))
.mount(&server)
.await;
let served = jwks.clone();
Mock::given(method("GET"))
.and(path("/jwks"))
.respond_with(move |_: &MockRequest| {
let keys_json: Vec<Value> = served
.lock()
.unwrap()
.iter()
.map(|(kid, index)| {
let public = keys()[*index].to_public_key();
json!({"kty":"RSA","use":"sig","alg":"RS256","kid":kid,
"n": b64(public.n().to_bytes_be()), "e": b64(public.e().to_bytes_be())})
})
.collect();
ResponseTemplate::new(200).set_body_json(json!({"keys": keys_json}))
})
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/token"))
.respond_with(TokenEndpoint {
scenario: scenario.clone(),
issuer,
})
.mount(&server)
.await;
Self {
server,
scenario,
jwks,
}
}
fn issuer(&self) -> String {
self.server.uri()
}
async fn hits(&self, route: &str) -> usize {
self.server
.received_requests()
.await
.unwrap()
.iter()
.filter(|r| r.url.path() == route)
.count()
}
}
struct Harness {
app: axum::Router,
state: HubState,
idp: Idp,
_dir: tempfile::TempDir,
}
fn config(idp: &Idp) -> OidcConfig {
let mut config = OidcConfig::new(&idp.issuer(), CLIENT_ID, CLIENT_SECRET, REDIRECT);
config.admin_subjects.insert("admin-sub".into());
config.admin_groups.insert("tessera-admins".into());
config
}
async fn harness_with(min_refresh: Duration) -> Harness {
let idp = Idp::start().await;
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
let config = config(&idp);
state.sessions =
SessionGate::without_operator(state.db.clone()).with_oidc(&config.fingerprint());
state.oidc = Some(Arc::new(
OidcProvider::new(config)
.unwrap()
.with_min_refresh(min_refresh),
));
let app = crate::api::router(state.clone());
Harness {
app,
state,
idp,
_dir: dir,
}
}
async fn harness() -> Harness {
harness_with(Duration::from_secs(60)).await
}
fn get(uri: &str, cookies: &[String]) -> Request<Body> {
let mut request = Request::builder()
.uri(uri)
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
if !cookies.is_empty() {
request = request.header(header::COOKIE, cookies.join("; "));
}
request.body(Body::empty()).unwrap()
}
fn set_cookies(response: &Response<Body>) -> Vec<String> {
response
.headers()
.get_all(header::SET_COOKIE)
.iter()
.map(|v| v.to_str().unwrap().to_string())
.collect()
}
fn cookie_pair(set_cookie: &str) -> String {
set_cookie.split(';').next().unwrap().to_string()
}
fn location(response: &Response<Body>) -> String {
response.headers()[header::LOCATION]
.to_str()
.unwrap()
.to_string()
}
struct Started {
state: String,
correlation: String,
}
impl Harness {
async fn call(&self, request: Request<Body>) -> Response<Body> {
self.app.clone().oneshot(request).await.unwrap()
}
/// Visit /login, check the authorization request, and arm the IdP with the
/// nonce and PKCE challenge the hub generated.
async fn start(&self) -> Started {
let response = self.call(get("/api/v1/auth/oidc/login", &[])).await;
assert!(
response.status().is_redirection(),
"login redirects, got {}",
response.status()
);
let target = openidconnect::url::Url::parse(&location(&response)).unwrap();
assert!(target
.as_str()
.starts_with(&format!("{}/authorize", self.idp.issuer())));
let q: std::collections::HashMap<String, String> =
target.query_pairs().into_owned().collect();
assert_eq!(q["response_type"], "code");
assert_eq!(q["client_id"], CLIENT_ID);
assert_eq!(q["redirect_uri"], REDIRECT);
assert_eq!(q["code_challenge_method"], "S256");
assert!(q["scope"].split(' ').any(|s| s == "openid"));
assert!(!q.contains_key("next") && !q.contains_key("client_secret"));
let cookies = set_cookies(&response);
assert_eq!(cookies.len(), 1);
for flag in ["HttpOnly", "Secure", "SameSite=Lax", "Path=/"] {
assert!(cookies[0].contains(flag), "{flag} in {}", cookies[0]);
}
assert!(cookies[0].starts_with("__Host-tessera-oidc="));
{
let mut scenario = self.idp.scenario.lock().unwrap();
scenario.nonce = q["nonce"].clone();
scenario.challenge = q["code_challenge"].clone();
}
Started {
state: q["state"].clone(),
correlation: cookie_pair(&cookies[0]),
}
}
async fn callback(&self, started: &Started, query: &str) -> Response<Body> {
self.call(get(
&format!("/api/v1/auth/oidc/callback?{query}"),
std::slice::from_ref(&started.correlation),
))
.await
}
/// Full successful-or-not login with the current scenario.
async fn login(&self) -> (Response<Body>, Started) {
let started = self.start().await;
let response = self
.callback(&started, &format!("code=good-code&state={}", started.state))
.await;
(response, started)
}
fn mutate(&self, change: impl FnOnce(&mut Scenario)) {
change(&mut self.idp.scenario.lock().unwrap());
}
fn count(&self, table: &str) -> i64 {
rusqlite::Connection::open(self.state.data_dir.join("tessera.db"))
.unwrap()
.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0))
.unwrap()
}
fn query<T: rusqlite::types::FromSql>(&self, sql: &str) -> T {
rusqlite::Connection::open(self.state.data_dir.join("tessera.db"))
.unwrap()
.query_row(sql, [], |r| r.get(0))
.unwrap()
}
}
fn session_cookie(response: &Response<Body>) -> String {
let cookies = set_cookies(response);
let session = cookies
.iter()
.find(|c| c.starts_with("__Host-tessera-session=") && !c.contains("Max-Age=0"))
.expect("session cookie");
for flag in ["HttpOnly", "Secure", "SameSite=Strict"] {
assert!(session.contains(flag));
}
cookie_pair(session)
}
async fn json_body(response: Response<Body>) -> Value {
serde_json::from_slice(&to_bytes(response.into_body(), 1 << 20).await.unwrap()).unwrap()
}
#[tokio::test]
async fn an_admin_subject_signs_in_and_gets_a_session_but_never_a_token() {
let h = harness().await;
let (response, started) = h.login().await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&response), "/", "fixed redirect target");
let cookies = set_cookies(&response);
assert_eq!(
cookies.len(),
2,
"session cookie plus cleared correlation cookie: {cookies:?}"
);
assert!(cookies
.iter()
.any(|c| c.starts_with("__Host-tessera-oidc=;") && c.contains("Max-Age=0")));
let session = session_cookie(&response);
let headers_text = format!("{:?}", response.headers());
assert!(!headers_text.contains("synthetic-access-token") && !headers_text.contains("eyJ"));
assert!(to_bytes(response.into_body(), 4096)
.await
.unwrap()
.is_empty());
let me = h
.call(get("/api/v1/me", std::slice::from_ref(&session)))
.await;
assert_eq!(me.status(), StatusCode::OK);
let me = json_body(me).await;
assert_eq!(me["kind"], "user");
assert_eq!(me["auth_method"], "oidc");
assert!(me["id"].as_str().unwrap().starts_with("oidc:"));
assert_eq!(me["display_name"], "Ada Admin");
assert_eq!(me["capabilities"][0], "admin");
assert_eq!(
h.call(get("/api/v1/orbits", std::slice::from_ref(&session)))
.await
.status(),
StatusCode::OK
);
// Identity is (issuer, subject); the transaction was consumed; the audit actor is the stable user id.
let issuer: String = h.query("SELECT issuer FROM users");
assert_eq!(issuer, h.idp.issuer());
assert_eq!(h.count("oidc_login"), 0);
let actor: String = h.query(
"SELECT actor_id FROM audit_events WHERE action='auth.login' AND outcome='succeeded'",
);
assert_eq!(actor, me["id"]);
// PKCE verified by the IdP and the code is not reusable by replaying the callback.
let replay = h
.callback(&started, &format!("code=good-code&state={}", started.state))
.await;
assert_eq!(location(&replay), "/?auth_error=invalid_state");
assert!(set_cookies(&replay)
.iter()
.all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")));
assert_eq!(h.count("sessions"), 1);
}
#[tokio::test]
async fn a_signed_in_user_without_a_grant_gets_identity_but_no_api_access() {
let h = harness().await;
// Display name "operator" must not be mistaken for the emergency account.
h.mutate(|s| {
s.sub = Some("plain-user".into());
s.name = Some("operator".into());
});
let (response, _) = h.login().await;
assert_eq!(location(&response), "/");
let session = session_cookie(&response);
let me = json_body(
h.call(get("/api/v1/me", std::slice::from_ref(&session)))
.await,
)
.await;
assert_eq!(me["capabilities"].as_array().unwrap().len(), 0);
assert!(me["id"].as_str().unwrap().starts_with("oidc:"), "{me}");
let status = json_body(
h.call(get(
"/api/v1/operator/session",
std::slice::from_ref(&session),
))
.await,
)
.await;
assert_eq!(status["authorized"], false);
assert_eq!(status["actor"], "operator");
assert!(status["csrf"].is_string(), "can still sign out");
assert_eq!(
h.call(get("/api/v1/orbits", std::slice::from_ref(&session)))
.await
.status(),
StatusCode::FORBIDDEN
);
let denied_actor: String = h.query("SELECT actor_id FROM audit_events WHERE action='authorization.check' AND outcome='denied' ORDER BY id DESC LIMIT 1");
assert!(
denied_actor.starts_with("oidc:"),
"audited as the OIDC user, not emergency:operator: {denied_actor}"
);
let logout = Request::builder()
.method("DELETE")
.uri("/api/v1/operator/session")
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()))
.header(header::COOKIE, session.clone())
.header("x-tessera-csrf", status["csrf"].as_str().unwrap())
.body(Body::empty())
.unwrap();
assert_eq!(h.call(logout).await.status(), StatusCode::NO_CONTENT);
assert_eq!(
h.call(get("/api/v1/me", &[session])).await.status(),
StatusCode::UNAUTHORIZED
);
}
#[tokio::test]
async fn admin_comes_from_a_verified_group_claim_and_a_bad_claim_grants_nothing() {
let h = harness().await;
for (groups, expect_admin) in [
(Some(json!(["dev", "tessera-admins"])), true),
(Some(json!("tessera-admins")), true),
(Some(json!(["dev"])), false),
(Some(json!({"tessera-admins": true})), false),
(Some(json!([["tessera-admins"]])), false),
(None, false),
] {
h.mutate(|s| {
s.sub = Some("group-user".into());
s.groups = groups.clone();
});
let (response, _) = h.login().await;
let session = session_cookie(&response);
let expected = if expect_admin {
StatusCode::OK
} else {
StatusCode::FORBIDDEN
};
assert_eq!(
h.call(get("/api/v1/orbits", &[session])).await.status(),
expected,
"{groups:?}"
);
}
}
#[tokio::test]
async fn the_same_email_under_a_different_subject_is_a_different_user() {
let h = harness().await;
for sub in ["sub-a", "sub-b", "sub-a"] {
h.mutate(|s| {
s.sub = Some(sub.into());
s.email = Some("same@example.com".into());
});
let (response, _) = h.login().await;
assert_eq!(location(&response), "/");
}
assert_eq!(
h.count("users"),
2,
"two subjects, no linking by email; the repeat logs in as the first"
);
}
#[tokio::test]
async fn invalid_tokens_never_create_a_session_or_a_user() {
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
let h = harness().await;
type Case = (&'static str, Box<dyn Fn(&mut Scenario)>);
let cases: Vec<Case> = vec![
(
"wrong nonce",
Box::new(|s| s.nonce = "not-the-nonce".into()),
),
(
"wrong issuer",
Box::new(|s| s.iss = Some("https://evil.example".into())),
),
(
"wrong audience",
Box::new(|s| s.aud = json!("someone-else")),
),
(
"extra audience without azp",
Box::new(|s| s.aud = json!([CLIENT_ID, "other"])),
),
(
"azp is another client",
Box::new(|s| {
s.aud = json!([CLIENT_ID, "other"]);
s.azp = Some("other".into());
}),
),
("expired", Box::new(|s| s.exp_in = -3600)),
("signed by an attacker key", Box::new(|s| s.signer = 2)),
("alg none", Box::new(|s| s.alg = "none")),
(
"HS256 with the client secret",
Box::new(|s| s.alg = "HS256"),
),
("no subject", Box::new(|s| s.sub = None)),
("empty subject", Box::new(|s| s.sub = Some(String::new()))),
];
for (name, change) in cases {
h.mutate(|s| *s = Scenario::default());
let started = h.start().await;
h.mutate(|s| change(s));
let response = h
.callback(&started, &format!("code=good-code&state={}", started.state))
.await;
let target = location(&response);
assert!(target == "/?auth_error=failed", "{name}: {target}");
assert!(
set_cookies(&response)
.iter()
.all(|c| !c.starts_with("__Host-tessera-session=") || c.contains("Max-Age=0")),
"{name}"
);
assert_eq!(h.count("sessions"), 0, "{name}");
assert_eq!(h.count("users"), 0, "{name}");
}
}
#[tokio::test]
async fn login_transactions_cannot_be_replayed_borrowed_or_forged() {
let h = harness().await;
// Another browser (no / wrong correlation cookie) holding the right state.
let started = h.start().await;
let no_cookie = h
.call(get(
&format!(
"/api/v1/auth/oidc/callback?code=good-code&state={}",
started.state
),
&[],
))
.await;
assert_eq!(location(&no_cookie), "/?auth_error=invalid_state");
let again = h
.callback(&started, &format!("code=good-code&state={}", started.state))
.await;
assert_eq!(
location(&again),
"/?auth_error=invalid_state",
"a failed attempt burns the transaction"
);
let started = h.start().await;
let wrong = Started {
state: started.state.clone(),
correlation: "__Host-tessera-oidc=forged".into(),
};
assert_eq!(
location(
&h.callback(&wrong, &format!("code=good-code&state={}", started.state))
.await
),
"/?auth_error=invalid_state"
);
// Unknown, missing and mismatched state.
let started = h.start().await;
assert_eq!(
location(&h.callback(&started, "code=good-code&state=made-up").await),
"/?auth_error=invalid_state"
);
assert_eq!(
location(&h.callback(&started, "code=good-code").await),
"/?auth_error=invalid_state"
);
// Expired transaction.
let started = h.start().await;
rusqlite::Connection::open(h.state.data_dir.join("tessera.db"))
.unwrap()
.execute("UPDATE oidc_login SET expires_at = 1", [])
.unwrap();
assert_eq!(
location(
&h.callback(&started, &format!("code=good-code&state={}", started.state))
.await
),
"/?auth_error=invalid_state"
);
// The IdP reporting an error: shown as a fixed code, nothing echoed, transaction consumed.
let started = h.start().await;
let denied = h
.callback(
&started,
&format!(
"error=access_denied&error_description=secret-detail&state={}",
started.state
),
)
.await;
assert_eq!(location(&denied), "/?auth_error=denied");
assert!(!format!("{:?}", denied.headers()).contains("secret-detail"));
assert_eq!(h.count("oidc_login"), 0);
assert_eq!(h.count("sessions"), 0);
// A wrong code is rejected by the IdP.
let started = h.start().await;
assert_eq!(
location(
&h.callback(&started, &format!("code=bad-code&state={}", started.state))
.await
),
"/?auth_error=failed"
);
assert_eq!(h.count("sessions"), 0);
let failed: i64 = h.query("SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='failed' AND actor_id='anonymous'");
assert!(failed >= 6);
}
#[tokio::test]
async fn rotated_signing_keys_are_picked_up_but_refreshes_are_rate_limited() {
let h = harness_with(Duration::from_millis(1)).await;
let (first, _) = h.login().await;
assert_eq!(location(&first), "/");
assert_eq!(h.idp.hits("/jwks").await, 1);
// The IdP rotates: new key and kid, old key withdrawn. The cached key set is stale.
*h.idp.jwks.lock().unwrap() = vec![("k2", 1)];
h.mutate(|s| {
s.signer = 1;
s.kid = "k2";
});
tokio::time::sleep(Duration::from_millis(5)).await;
let (after, _) = h.login().await;
assert_eq!(
location(&after),
"/",
"refreshed once and verified with the new key"
);
assert_eq!(h.idp.hits("/jwks").await, 2);
// With the default 60s gap, a flood of bad signatures cannot hammer the IdP.
let limited = harness().await;
for _ in 0..4 {
limited.mutate(|s| *s = Scenario::default());
let started = limited.start().await;
limited.mutate(|s| s.signer = 2);
let r = limited
.callback(&started, &format!("code=good-code&state={}", started.state))
.await;
assert_eq!(location(&r), "/?auth_error=failed");
}
assert!(limited.idp.hits("/.well-known/openid-configuration").await <= 2);
}
#[tokio::test]
async fn an_idp_outage_degrades_to_fixed_errors_and_never_a_session() {
// Cold start with the IdP down: no redirect, no transaction stored.
let cold = harness().await;
cold.idp.server.reset().await;
let down = cold.call(get("/api/v1/auth/oidc/login", &[])).await;
assert_eq!(down.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(cold.count("oidc_login"), 0);
// Warm cache, then the token endpoint dies mid-login.
let h = harness().await;
let (ok, _) = h.login().await;
assert_eq!(location(&ok), "/");
h.mutate(|s| s.token_status = 500);
let started = h.start().await; // metadata is cached, so /login still works
let response = h
.callback(&started, &format!("code=good-code&state={}", started.state))
.await;
assert!(response.status().is_redirection());
assert!(location(&response).starts_with("/?auth_error="));
h.idp.server.reset().await;
let started = h.start().await;
let response = h
.callback(&started, &format!("code=good-code&state={}", started.state))
.await;
assert!(
location(&response).starts_with("/?auth_error="),
"{}",
location(&response)
);
}
#[tokio::test]
async fn oidc_endpoints_are_absent_when_oidc_is_not_configured() {
let dir = tempfile::tempdir().unwrap();
let state = HubState::bootstrap(dir.path().to_str().unwrap(), "synthetic-vault-passphrase")
.await
.unwrap();
let app = crate::api::router(state);
for uri in [
"/api/v1/auth/oidc/login",
"/api/v1/auth/oidc/callback?code=x&state=y",
] {
assert_eq!(
app.clone().oneshot(get(uri, &[])).await.unwrap().status(),
StatusCode::NOT_FOUND
);
}
}

View File

@@ -1,54 +1,138 @@
use crate::db::OrbitRow;
use crate::state::HubState;
use anyhow::{Context, Result};
use tessera_core::config::ProviderKind;
use tessera_core::manifest::SnapshotManifest;
use tessera_providers::provider_from_config;
use tessera_providers::{FilesystemConfig, MysqlSource, PostgresProvider, PostgresSource};
use uuid::Uuid;
pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<()> {
let orbits = state.db.list_orbits().await?;
let orbit = orbits
.into_iter()
.find(|o| o.id == orbit_id)
.context("orbit not found")?;
run_orbit_row(state, orbit).await
#[derive(serde::Deserialize)]
#[serde(tag = "engine", rename_all = "snake_case")]
pub(super) enum DatabaseSource {
Postgres(PostgresSource),
Mysql(MysqlSource),
}
pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> {
impl DatabaseSource {
pub(super) fn valid_endpoint(&self) -> bool {
let (host, port, database, user, password_file) = match self {
Self::Postgres(source) if source.bastion.is_none() => (
&source.host,
source.port,
&source.database,
&source.user,
&source.password_file,
),
Self::Mysql(MysqlSource::Direct {
host,
port,
database,
user,
password_file,
..
}) => (host, *port, database, user, password_file),
_ => return false,
};
port != 0
&& password_file.is_absolute()
&& [host, database, user]
.iter()
.all(|value| !value.trim().is_empty() && !value.chars().any(char::is_control))
}
}
pub async fn run_orbit_internal(state: HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
anyhow::ensure!(
orbit.provider != "wormhole",
"Wormhole backups are started by the outpost agent"
);
let orbit_id = orbit.id;
anyhow::ensure!(
state.active_orbits.lock().await.insert(orbit_id),
"orbit already running"
);
// Keep capture and its status update together if the requesting client disconnects.
tokio::spawn(async move {
let result = run_orbit_row(&state, orbit).await;
if result.is_err() {
if let Err(error) = state.db.set_orbit_status(orbit_id, "failed").await {
tracing::error!(%orbit_id, %error, "could not record failed capture");
}
}
state.active_orbits.lock().await.remove(&orbit_id);
result
})
.await?
}
async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
state.db.set_orbit_status(orbit.id, "running").await?;
let provider_kind = match orbit.provider.as_str() {
"filesystem" => ProviderKind::Filesystem,
"postgres" => ProviderKind::Postgres,
_ => ProviderKind::Command,
};
let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?;
let provider = provider_from_config(&provider_kind, &config)?;
let capture = provider.capture().await.context("capture")?;
let manifest = SnapshotManifest {
let mut manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: orbit.id,
orbit_name: orbit.name.clone(),
labels: capture.labels,
labels: vec![orbit.provider.clone()],
provider: orbit.provider.clone(),
paths: vec![],
restore_hints: capture.restore_hints,
restore_hints: serde_json::Value::Null,
};
let mut vault = state.vault.write().await;
let snap = vault
.snapshot(manifest, &capture.payload, orbit.dry_run)
.context("vault snapshot")?;
if !orbit.dry_run {
let _pruned = vault.prune_with_decay(&orbit.decay_preset)?;
let (payload, max_file_bytes) = match orbit.provider.as_str() {
"filesystem" => {
let config: FilesystemConfig = serde_json::from_value(config)?;
manifest.paths = config.paths;
(None, config.max_file_bytes)
}
"database" => {
let source = serde_json::from_value::<DatabaseSource>(config)?;
let file = tempfile::tempfile()?;
let (engine, format) = match source {
DatabaseSource::Postgres(source) => {
source.dump_to(file.try_clone()?, "plain").await?;
("postgres", "plain")
}
DatabaseSource::Mysql(source) => {
source.dump_to(file.try_clone()?).await?;
("mysql", "plain")
}
};
manifest.provider = engine.into();
manifest.restore_hints = serde_json::json!({"engine": engine, "format": format});
(Some(file), None)
}
"postgres" => {
let provider = PostgresProvider::from_config(&config)?;
let file = tempfile::tempfile()?;
manifest.restore_hints = provider.dump_to(file.try_clone()?).await?;
(Some(file), None)
}
"wormhole" => anyhow::bail!("Wormhole backups are started by the outpost agent"),
"command" => {
anyhow::bail!("command provider is outside this release; use filesystem or postgres")
}
other => anyhow::bail!("unknown provider '{other}'"),
};
let vault = state.vault.clone().read_owned().await;
let snap = tokio::task::spawn_blocking(move || {
match payload {
Some(file) => vault.snapshot_payload(manifest, file, orbit.dry_run),
None => vault.snapshot_files(manifest, max_file_bytes, orbit.dry_run),
}
.context("vault snapshot")
})
.await??;
let snap_id = snap.id;
let retained_snapshot = if orbit.dry_run {
None
} else {
let pruned = state.prune_orbit(orbit.id).await?;
state
.db
.audit("decay.pruned", &format!("orbit={}", orbit.name))
.await?;
}
(!pruned.contains(&snap_id)).then_some(snap_id)
};
let status = if orbit.dry_run {
"rehearsed"
@@ -64,8 +148,8 @@ pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> {
} else {
"orbit.completed"
},
&format!("snapshot={}", snap.id),
&format!("snapshot={snap_id}"),
)
.await?;
Ok(())
Ok(retained_snapshot)
}

View File

@@ -0,0 +1,526 @@
//! Starting, watching and cancelling a refresh of a staging database.
//!
//! The caller names a relation they hold a grant on and confirms what they saw (source, target and
//! version). They never choose the snapshot or the target: the run captures its own fresh dump and
//! restores exactly that onto the relation's target.
use super::routes::{authenticate, OperatorActor};
use crate::auth::{AuditAction, AuditOutcome, AuditResource};
use crate::db::refresh::{CancelError, Progress, RefreshRun, StartError};
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Response},
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/refresh-runs", get(list).post(start))
.route("/api/v1/refresh-runs/:id", get(show).delete(cancel))
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn no_store() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers
}
fn internal(error: impl std::fmt::Display) -> StatusCode {
tracing::error!("refresh: {error:#}");
StatusCode::INTERNAL_SERVER_ERROR
}
fn reason(status: StatusCode, reason: &str) -> Response {
(
status,
no_store(),
Json(serde_json::json!({ "reason": reason })),
)
.into_response()
}
/// A run as its viewer may see it. Only administrators see who started it and the snapshot id.
#[derive(Serialize)]
struct RunView {
id: String,
relation_id: String,
source_name: String,
target_name: String,
status: String,
blocked_reason: Option<String>,
capture_status: Option<String>,
capture_phase: Option<String>,
snapshot_taken_at: Option<i64>,
restore_status: Option<String>,
restore_phase: Option<String>,
created_at: i64,
updated_at: i64,
expires_at: i64,
#[serde(skip_serializing_if = "Option::is_none")]
requested_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
snapshot_id: Option<String>,
/// This run put a target back from the safety copy of an earlier restore.
undo: bool,
/// For an undo, the run whose restore it puts back; the Activity log shows the undo under it.
#[serde(skip_serializing_if = "Option::is_none")]
undo_of: Option<String>,
/// The restore job this run queued, which is how the Activity log ties a restore to its run.
#[serde(skip_serializing_if = "Option::is_none")]
restore_job_id: Option<String>,
/// This restore can be put back right now: it is the newest of its target and its safety copy is in the vault.
/// Never says where the copy is.
undo_available: bool,
/// Why it can or cannot be put back, for a restore that took a safety copy: `available`, `superseded` (something
/// was restored onto the target after it) or `expired` (retention has forgotten the copy).
#[serde(skip_serializing_if = "Option::is_none")]
undo_state: Option<&'static str>,
/// While it can be undone: when the safety copy is first at risk of being forgotten. Retention keeps a copy a
/// week, and longer while it is one of the target's newest few.
#[serde(skip_serializing_if = "Option::is_none")]
undo_kept_until: Option<i64>,
}
/// What `undo_views` found out about one run.
#[derive(Clone, Copy)]
struct Undo {
state: &'static str,
kept_until: Option<i64>,
}
/// For every run in the list that took a safety copy, whether it can be put back. The database answers for all of
/// them in one go; the vault is only asked whether a copy still exists (a file lookup), and read only for the one
/// restore per target that could still be undone.
async fn undo_views(
state: &HubState,
runs: &[RefreshRun],
) -> Result<std::collections::HashMap<String, Undo>, StatusCode> {
let infos = state.db.undo_infos(runs).map_err(internal)?;
let mut views = std::collections::HashMap::new();
if infos.is_empty() {
return Ok(views);
}
let vault = state.vault.read().await;
for run in runs {
let Some(info) = infos.get(&run.id) else {
continue;
};
// Safety copies are forgotten by retention: the restore stays in the log, but there is nothing to go back to.
if !vault
.has_published_snapshot(info.safety)
.map_err(internal)?
{
views.insert(
run.id.clone(),
Undo {
state: "expired",
kept_until: None,
},
);
} else if !info.latest {
views.insert(
run.id.clone(),
Undo {
state: "superseded",
kept_until: None,
},
);
} else if let Some(taken) = fitting_snapshot(state, &vault, &run.relation_id, info.safety)?
{
let kept = taken + tessera_core::decay::SAFETY_KEEP_DAYS * 86_400;
views.insert(
run.id.clone(),
Undo {
state: "available",
kept_until: Some(kept),
},
);
}
}
Ok(views)
}
async fn view_one(state: &HubState, run: &RefreshRun, admin: bool) -> Result<RunView, StatusCode> {
let undo = undo_views(state, std::slice::from_ref(run)).await?;
view(state, run, admin, undo.get(&run.id))
}
fn view(
state: &HubState,
run: &RefreshRun,
admin: bool,
undo: Option<&Undo>,
) -> Result<RunView, StatusCode> {
let Progress {
capture_status,
capture_phase,
snapshot_taken_at,
restore_status,
restore_phase,
source_name,
target_name,
} = state.db.refresh_progress(run).map_err(internal)?;
Ok(RunView {
id: run.id.clone(),
relation_id: run.relation_id.clone(),
source_name,
target_name,
status: run.status.clone(),
blocked_reason: run.blocked_reason.clone(),
capture_status,
capture_phase,
snapshot_taken_at,
restore_status,
restore_phase,
created_at: run.created_at,
updated_at: run.updated_at,
expires_at: run.expires_at,
requested_by: admin.then(|| run.requester.clone()),
snapshot_id: admin.then(|| run.snapshot_id.clone()).flatten(),
undo: run.is_undo(),
undo_of: state.db.undo_parent(run).map_err(internal)?,
restore_job_id: run.restore_job_id.clone(),
undo_available: undo.is_some_and(|undo| undo.state == "available"),
undo_state: undo.map(|undo| undo.state),
undo_kept_until: undo.and_then(|undo| undo.kept_until),
})
}
fn owns(actor: &OperatorActor, run: &RefreshRun) -> bool {
actor.subject.user_id.is_some() && actor.subject.user_id == run.requester_user_id
}
/// May this caller look at this run: an administrator, whoever started it, or someone holding a
/// grant on its relation. Anyone else gets 404.
fn can_see(state: &HubState, actor: &OperatorActor, run: &RefreshRun) -> Result<bool, StatusCode> {
if actor.subject.admin || owns(actor, run) {
return Ok(true);
}
let granted = state
.db
.granted_relations(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
now(),
)
.map_err(internal)?;
Ok(granted.iter().any(|id| id == &run.relation_id))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Start {
relation_id: Uuid,
/// `REFRESH <source> TO <target> v<version>`: exactly what the person was shown.
confirmation: String,
/// Chosen by the client so a double click or a retry starts one run, not two.
idempotency_key: String,
/// Restore this existing snapshot instead of capturing a new one. It must be a restorable capture of the
/// relation's own source.
#[serde(default)]
snapshot_id: Option<Uuid>,
/// Put the target back as it was before this earlier restore: restore that restore's safety copy onto the same
/// target. The run must be a completed restore of this relation and the newest one of its target.
#[serde(default)]
undo_of: Option<Uuid>,
}
fn valid_key(key: &str) -> bool {
(1..=128).contains(&key.len())
&& key
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b))
}
/// Is this snapshot one that a relation may restore: a database capture of the relation's own source orbit,
/// never a safety copy of some target, with what a restore needs (format, checksum, source identity)? When it is,
/// when it was taken (seconds since the epoch).
fn fitting_snapshot(
state: &HubState,
vault: &tessera_store::Vault,
relation: &str,
snapshot: Uuid,
) -> Result<Option<i64>, StatusCode> {
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
return Ok(None);
};
let Some(stored) = vault.get_snapshot(snapshot).map_err(internal)? else {
return Ok(None);
};
let manifest = &stored.manifest;
let target = match state.db.relation_target(relation).map_err(internal)? {
Some(id) => Uuid::parse_str(&id)
.ok()
.and_then(|id| state.db.restore_target(id).ok().flatten()),
None => None,
};
let fits = manifest.orbit_id.to_string() == source
&& if manifest.is_restore_safety() {
// a safety copy only ever goes back onto the target it was taken from
target
.as_ref()
.is_some_and(|target| crate::api::rollback_artifact(manifest, target).is_some())
} else {
crate::api::artifact(manifest).is_some()
};
Ok(fits.then(|| stored.taken_at.timestamp()))
}
async fn snapshot_fits(
state: &HubState,
relation: &str,
snapshot: Uuid,
) -> Result<bool, StatusCode> {
let vault = state.vault.read().await;
Ok(fitting_snapshot(state, &vault, relation, snapshot)?.is_some())
}
async fn start(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<Start>,
) -> Result<Response, StatusCode> {
let actor = authenticate(&state, peer, &headers, true)?;
if !valid_key(&body.idempotency_key) {
return Err(StatusCode::BAD_REQUEST);
}
super::gate::relation(&state, &actor, body.relation_id)?;
let relation = body.relation_id.to_string();
// What to restore: a snapshot the person picked, the safety copy that undoes an earlier restore, or (neither)
// a fresh capture.
let mut chosen: Option<(Uuid, Option<String>)> = None;
if let Some(of) = body.undo_of {
if body.snapshot_id.is_some() {
return Err(StatusCode::BAD_REQUEST);
}
let candidate = state
.db
.undo_candidate(&of.to_string(), &relation)
.map_err(internal)?;
let Ok(safety) = candidate else {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
};
// the copy may have been removed since
if !snapshot_fits(&state, &relation, safety).await? {
return Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"));
}
chosen = Some((safety, Some(of.to_string())));
} else if let Some(snapshot) = body.snapshot_id {
if !snapshot_fits(&state, &relation, snapshot).await? {
return Ok(reason(
StatusCode::UNPROCESSABLE_ENTITY,
"snapshot_unusable",
));
}
chosen = Some((snapshot, None));
}
// What authorised this run, recorded so it can be checked again before anything is overwritten.
let authorized_by = if actor.subject.admin {
"admin".to_string()
} else {
match state
.db
.granting_relation_grant(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
&relation,
now(),
)
.map_err(internal)?
{
Some(grant) => format!("grant:{grant}"),
None => return Err(StatusCode::NOT_FOUND),
}
};
let started = state
.db
.create_refresh_run(
&relation,
&body.confirmation,
&actor.id(),
actor.subject.user_id.as_deref(),
&authorized_by,
&body.idempotency_key,
chosen
.as_ref()
.map(|(snapshot, of)| (*snapshot, of.as_deref())),
state.refresh.ttl_secs,
state.refresh.max_active,
now(),
)
.map_err(internal)?;
match started {
Ok((run, created)) => {
if created {
crate::refresh::audit_run(
&state,
&run.id,
if run.is_undo() { "undo" } else { "capturing" },
);
}
let status = if created {
StatusCode::ACCEPTED
} else {
StatusCode::OK
};
Ok((
status,
no_store(),
Json(view_one(&state, &run, actor.subject.admin).await?),
)
.into_response())
}
Err(StartError::NothingToUndo) => {
Ok(reason(StatusCode::UNPROCESSABLE_ENTITY, "nothing_to_undo"))
}
Err(StartError::UnknownRelation) => Err(StatusCode::NOT_FOUND),
Err(StartError::Unusable(why)) => Ok((
StatusCode::CONFLICT,
no_store(),
Json(serde_json::json!({"reason": "relation_unusable", "detail": why})),
)
.into_response()),
Err(StartError::StaleConfirmation) => {
Ok(reason(StatusCode::CONFLICT, "stale_confirmation"))
}
Err(StartError::SourceUnavailable) => {
Ok(reason(StatusCode::CONFLICT, "source_unavailable"))
}
Err(StartError::KeyReused) => Ok(reason(StatusCode::CONFLICT, "key_reused")),
Err(StartError::TooManyRuns) => Ok(reason(StatusCode::TOO_MANY_REQUESTS, "too_many_runs")),
Err(StartError::TargetBusy(id)) => {
// Only someone who may see that run is told which one it is.
let visible = match state.db.refresh_run(&id).map_err(internal)? {
Some(run) => can_see(&state, &actor, &run)?,
None => false,
};
let mut payload = serde_json::json!({"reason": "run_active"});
if visible {
payload["run_id"] = serde_json::json!(id);
}
Ok((StatusCode::CONFLICT, no_store(), Json(payload)).into_response())
}
}
}
async fn list(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Vec<RunView>>), StatusCode> {
let actor = authenticate(&state, peer, &headers, false)?;
let granted = super::gate::visible_relations(&state, &actor)?;
let runs = match (&granted, actor.subject.admin) {
(None, _) => state.db.refresh_runs(None, None, 50),
(Some(relations), _) => {
state
.db
.refresh_runs(actor.subject.user_id.as_deref(), Some(relations), 50)
}
}
.map_err(internal)?;
let undo = undo_views(&state, &runs).await?;
let mut views = Vec::with_capacity(runs.len());
for run in &runs {
views.push(view(&state, run, actor.subject.admin, undo.get(&run.id))?);
}
Ok((no_store(), Json(views)))
}
async fn show(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<(HeaderMap, Json<RunView>), StatusCode> {
let actor = authenticate(&state, peer, &headers, false)?;
let run = state
.db
.refresh_run(&id.to_string())
.map_err(internal)?
.filter(|run| can_see(&state, &actor, run).unwrap_or(false));
let allowed = run.is_some();
state
.db
.audit_event(
&actor.principal,
AuditAction::Authorization,
AuditResource::RefreshRun(id),
if allowed {
AuditOutcome::Allowed
} else {
AuditOutcome::Denied
},
actor.request_id,
)
.map_err(internal)?;
let run = run.ok_or(StatusCode::NOT_FOUND)?;
Ok((
no_store(),
Json(view_one(&state, &run, actor.subject.admin).await?),
))
}
async fn cancel(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
let actor = authenticate(&state, peer, &headers, true)?;
let run = state.db.refresh_run(&id.to_string()).map_err(internal)?;
let (visible, allowed) = match &run {
Some(run) => (
can_see(&state, &actor, run)?,
actor.subject.admin || owns(&actor, run),
),
None => (false, false),
};
state
.db
.audit_event(
&actor.principal,
AuditAction::Authorization,
AuditResource::RefreshRun(id),
if allowed {
AuditOutcome::Allowed
} else {
AuditOutcome::Denied
},
actor.request_id,
)
.map_err(internal)?;
if !visible {
return Err(StatusCode::NOT_FOUND);
}
if !allowed {
// Someone who may see the run but did not start it and is not an administrator.
return Err(StatusCode::FORBIDDEN);
}
match state
.db
.cancel_refresh_run(&id.to_string(), now())
.map_err(internal)?
{
Ok(run) => {
crate::refresh::audit_run(&state, &run.id, "cancelled");
Ok((
no_store(),
Json(view_one(&state, &run, actor.subject.admin).await?),
)
.into_response())
}
Err(CancelError::Unknown) => Err(StatusCode::NOT_FOUND),
Err(CancelError::TooLate) => Ok(reason(StatusCode::CONFLICT, "too_late")),
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,631 @@
//! Environments, relations and who may use them.
//!
//! Administrators configure everything here. The one endpoint a refresher sees is
//! `GET /api/v1/refresh-relations`, which lists only the relations they hold a grant on and
//! never shows where the database is (no identity, host, Outpost or application id).
use super::routes::{admin_read, admin_write, authenticate};
use crate::auth::{AuditAction, AuditOutcome, AuditResource};
use crate::db::relations::{Reject, ENVIRONMENTS};
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Response},
routing::{get, put},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use tessera_core::restore::{DatabaseIdentity, Engine};
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/orbits/:id/environment", put(set_orbit_environment))
.route(
"/api/v1/restore-targets/:id/environment",
put(set_target_environment),
)
.route("/api/v1/relations", get(list).post(create))
.route("/api/v1/relations/:id", put(retarget).delete(deactivate))
.route(
"/api/v1/relations/:id/access",
get(list_access).post(grant_access),
)
.route(
"/api/v1/relations/:id/access/:grant",
axum::routing::delete(revoke_access),
)
.route("/api/v1/refresh-relations", get(mine))
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
fn no_store() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers
}
fn internal(error: impl std::fmt::Display) -> StatusCode {
tracing::error!("relations: {error:#}");
StatusCode::INTERNAL_SERVER_ERROR
}
/// A refused request names the rule that refused it, so an administrator can fix the setup.
fn refused(reject: Reject) -> Response {
let status = match reject {
Reject::UnknownSource | Reject::UnknownTarget => StatusCode::NOT_FOUND,
Reject::Duplicate => StatusCode::CONFLICT,
_ => StatusCode::UNPROCESSABLE_ENTITY,
};
(status, Json(serde_json::json!({ "reason": reject.code() }))).into_response()
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetEnvironment {
environment: String,
}
fn valid_environment(value: &str) -> bool {
ENVIRONMENTS.contains(&value)
}
async fn set_orbit_environment(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<SetEnvironment>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
if !valid_environment(&body.environment) {
return Err(StatusCode::BAD_REQUEST);
}
if !state
.db
.set_orbit_environment(id, &body.environment, now())
.map_err(internal)?
{
return Err(StatusCode::NOT_FOUND);
}
state
.db
.audit_event(
&actor.principal,
AuditAction::EnvironmentSet,
AuditResource::Orbit(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}
#[derive(Serialize)]
struct EnvironmentChange {
/// Relations that stopped working because of this change.
ended_relations: Vec<String>,
}
async fn set_target_environment(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<SetEnvironment>,
) -> Result<Json<EnvironmentChange>, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
if !valid_environment(&body.environment) {
return Err(StatusCode::BAD_REQUEST);
}
let ended = state
.db
.set_target_environment(id, &body.environment, now())
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::EnvironmentSet,
AuditResource::RestoreTarget(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(internal)?;
for relation in &ended {
if let Ok(relation) = Uuid::parse_str(relation) {
state
.db
.audit_event(
&actor.principal,
AuditAction::RelationDeactivate,
AuditResource::Relation(relation),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(internal)?;
}
}
Ok(Json(EnvironmentChange {
ended_relations: ended,
}))
}
#[derive(Serialize)]
struct OrbitSetup {
id: String,
name: String,
environment: Option<String>,
application_id: Option<String>,
engine: Option<&'static str>,
/// Can this orbit be the source of a relation, and if not, why not.
ready: bool,
reason: Option<&'static str>,
}
#[derive(Serialize)]
struct TargetSetup {
id: String,
name: String,
engine: &'static str,
identity: DatabaseIdentity,
application_id: String,
environment: Option<String>,
outpost_active: bool,
}
#[derive(Serialize)]
struct Overview {
relations: Vec<crate::db::relations::RelationView>,
orbits: Vec<OrbitSetup>,
targets: Vec<TargetSetup>,
}
fn engine_name(engine: Engine) -> &'static str {
match engine {
Engine::Postgres => "postgres",
Engine::Mysql => "mysql",
}
}
async fn list(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Overview>), StatusCode> {
admin_read(&state, peer, &headers)?;
let (orbit_env, target_env) = state.db.environments().map_err(internal)?;
let profiles: std::collections::HashMap<_, _> = state
.db
.capture_profiles()
.map_err(internal)?
.into_iter()
.map(|p| (p.orbit_id, p))
.collect();
let orbits = state
.db
.list_orbits()
.await
.map_err(internal)?
.into_iter()
.map(|orbit| {
let profile = profiles.get(&orbit.id);
let engine = profile.and_then(|p| p.format.engine());
let environment = orbit_env.get(&orbit.id.to_string()).cloned();
let reason = if profile.is_none() {
Some("not_managed")
} else if engine.is_none() {
Some("not_restore_ready")
} else if environment.is_none() {
Some("environment_unset")
} else {
None
};
OrbitSetup {
id: orbit.id.to_string(),
name: orbit.name,
environment,
application_id: profile.map(|p| p.application_id.to_string()),
engine: engine.map(engine_name),
ready: reason.is_none(),
reason,
}
})
.collect();
let targets = state
.db
.all_restore_targets(now())
.map_err(internal)?
.into_iter()
.map(|(target, outpost_active)| TargetSetup {
environment: target_env.get(&target.id.to_string()).cloned(),
id: target.id.to_string(),
name: target.name,
engine: engine_name(target.engine),
identity: target.identity,
application_id: target.application_id.to_string(),
outpost_active,
})
.collect();
let relations = state
.db
.relation_views(false, None, now())
.map_err(internal)?;
Ok((
no_store(),
Json(Overview {
relations,
orbits,
targets,
}),
))
}
/// What the snapshots say about a target: does its identity match a database that is captured as a
/// production (or unlabelled) source, and has the source itself been seen at all?
pub(crate) async fn identity_facts(
state: &HubState,
source: Uuid,
target: &DatabaseIdentity,
) -> Result<(bool, bool), StatusCode> {
let (orbit_env, _) = state.db.environments().map_err(internal)?;
let vault = state.vault.read().await;
let snapshots = vault.list_snapshots().map_err(internal)?;
let (mut clash, mut verified) = (false, false);
for snapshot in snapshots {
let Some(identity) = snapshot
.manifest
.restore_hints
.get("source_identity")
.cloned()
else {
continue;
};
let Ok(identity) = serde_json::from_value::<DatabaseIdentity>(identity) else {
continue;
};
let from = snapshot.manifest.orbit_id;
if from == source {
verified = true;
}
if &identity == target {
// A staging or development orbit that backs up the target itself is fine; anything else is
// a database captured as production (or never classified) under a staging label.
let own_backup = from != source
&& matches!(
orbit_env.get(&from.to_string()).map(String::as_str),
Some("staging" | "development")
);
if !own_backup {
clash = true;
}
}
}
Ok((clash, verified))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NewRelation {
source_orbit_id: Uuid,
target_id: Uuid,
}
async fn create(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<NewRelation>,
) -> Result<Response, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let Some(target) = state.db.restore_target(body.target_id).map_err(internal)? else {
return Ok(refused(Reject::UnknownTarget));
};
let (clash, verified) = identity_facts(&state, body.source_orbit_id, &target.identity).await?;
match state
.db
.create_relation(
body.source_orbit_id,
body.target_id,
None,
clash,
verified,
&actor.id(),
now(),
)
.map_err(internal)?
{
Ok(relation) => {
let id = Uuid::parse_str(&relation.id).map_err(internal)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::RelationCreate,
AuditResource::Relation(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(internal)?;
Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response())
}
Err(reject) => Ok(refused(reject)),
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Retarget {
target_id: Uuid,
}
async fn retarget(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<Retarget>,
) -> Result<Response, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let old = state
.db
.relation(&id.to_string())
.map_err(internal)?
.filter(|r| r.active)
.ok_or(StatusCode::NOT_FOUND)?;
let source = Uuid::parse_str(&old.source_orbit_id).map_err(internal)?;
let Some(target) = state.db.restore_target(body.target_id).map_err(internal)? else {
return Ok(refused(Reject::UnknownTarget));
};
let (clash, verified) = identity_facts(&state, source, &target.identity).await?;
match state
.db
.create_relation(
source,
body.target_id,
Some(&old.id),
clash,
verified,
&actor.id(),
now(),
)
.map_err(internal)?
{
Ok(relation) => {
let new_id = Uuid::parse_str(&relation.id).map_err(internal)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::RelationRetarget,
AuditResource::Relation(new_id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(internal)?;
Ok((StatusCode::CREATED, no_store(), Json(relation)).into_response())
}
Err(reject) => Ok(refused(reject)),
}
}
async fn deactivate(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let done = state
.db
.deactivate_relation(&id.to_string(), "deactivated_by_admin", now())
.map_err(internal)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::RelationDeactivate,
AuditResource::Relation(id),
if done {
AuditOutcome::Succeeded
} else {
AuditOutcome::Failed
},
actor.request_id,
)
.map_err(internal)?;
if done {
Ok(StatusCode::NO_CONTENT)
} else {
Err(StatusCode::NOT_FOUND)
}
}
async fn list_access(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<(HeaderMap, Json<Vec<crate::db::relations::RelationGrant>>), StatusCode> {
admin_read(&state, peer, &headers)?;
state
.db
.relation(&id.to_string())
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok((
no_store(),
Json(
state
.db
.relation_grants(&id.to_string())
.map_err(internal)?,
),
))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct NewAccess {
principal_type: String,
principal: String,
expires_at: Option<String>,
}
async fn grant_access(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<NewAccess>,
) -> Result<
(
StatusCode,
HeaderMap,
Json<crate::db::relations::RelationGrant>,
),
StatusCode,
> {
let actor = admin_write(&state, peer, &headers)?;
let now = now();
match body.principal_type.as_str() {
"user" => {
Uuid::parse_str(&body.principal).map_err(|_| StatusCode::BAD_REQUEST)?;
// The emergency operator is an administrator and never holds grants.
match state.db.user_row(&body.principal).map_err(internal)? {
Some(user) if !user.is_emergency => {}
_ => return Err(StatusCode::UNPROCESSABLE_ENTITY),
}
}
"group" => {
if body.principal.is_empty()
|| body.principal.len() > 128
|| body.principal.chars().any(char::is_control)
{
return Err(StatusCode::BAD_REQUEST);
}
}
_ => return Err(StatusCode::BAD_REQUEST),
}
let expires_at = body
.expires_at
.as_deref()
.map(|text| {
chrono::DateTime::parse_from_rfc3339(text)
.map(|t| t.timestamp())
.map_err(|_| StatusCode::BAD_REQUEST)
})
.transpose()?;
if expires_at.is_some_and(|end| end <= now || end > now + 2 * 366 * 86_400) {
return Err(StatusCode::BAD_REQUEST);
}
state
.db
.relation(&id.to_string())
.map_err(internal)?
.filter(|r| r.active)
.ok_or(StatusCode::NOT_FOUND)?;
let grant = state
.db
.add_relation_grant(
&body.principal_type,
&body.principal,
&id.to_string(),
expires_at,
&actor.id(),
now,
)
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::RelationGrantCreate,
AuditResource::Relation(id),
AuditOutcome::Succeeded,
actor.request_id,
)
.map_err(internal)?;
Ok((StatusCode::CREATED, no_store(), Json(grant)))
}
async fn revoke_access(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path((id, grant)): Path<(Uuid, Uuid)>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let removed = state
.db
.delete_relation_grant(&id.to_string(), &grant.to_string())
.map_err(internal)?;
state
.db
.audit_event(
&actor.principal,
AuditAction::RelationGrantDelete,
AuditResource::Relation(id),
if removed {
AuditOutcome::Succeeded
} else {
AuditOutcome::Failed
},
actor.request_id,
)
.map_err(internal)?;
if removed {
Ok(StatusCode::NO_CONTENT)
} else {
Err(StatusCode::NOT_FOUND)
}
}
/// A relation as a refresher sees it: names and environments, never where the database is.
#[derive(Serialize)]
struct MyRelation {
id: String,
version: i64,
/// The orbit this relation restores from, so a screen can offer it on that orbit's snapshots.
source_orbit_id: String,
source_name: String,
source_environment: Option<String>,
target_name: String,
target_environment: Option<String>,
usable: bool,
unusable_reason: Option<&'static str>,
}
async fn mine(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Vec<MyRelation>>), StatusCode> {
let actor = authenticate(&state, peer, &headers, false)?;
let granted = super::gate::visible_relations(&state, &actor)?;
let views = state
.db
.relation_views(true, granted.as_deref(), now())
.map_err(internal)?;
let list = views
.into_iter()
.map(|view| MyRelation {
id: view.relation.id,
version: view.relation.version,
source_orbit_id: view.relation.source_orbit_id,
source_name: view.source_name,
source_environment: view.source_environment,
target_name: view.target_name,
target_environment: view.target_environment,
usable: view.usable,
unusable_reason: view.unusable_reason,
})
.collect();
Ok((no_store(), Json(list)))
}

View File

@@ -0,0 +1,562 @@
use super::{
jobs::{header_value, internal, now, outpost, receive_payload},
routes::{admin_read, admin_write},
};
use crate::state::HubState;
use axum::{
body::Body,
extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use serde::Deserialize;
use std::net::SocketAddr;
use tessera_core::{
job::CaptureFormat,
restore::{
Engine, RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreRequest,
RestoreTarget,
},
SnapshotManifest,
};
use tokio_util::io::ReaderStream;
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/restore-targets", post(register))
.route("/api/v1/restore-targets/:id", axum::routing::put(rename))
.route("/api/v1/capture-profiles/:id/restore-targets", get(targets))
.route(
"/api/v1/snapshots/:id/restore-targets",
get(snapshot_targets),
)
.route("/api/v1/restore-jobs", post(enqueue).get(recent))
.route("/api/v1/snapshots/:id/restore-jobs", get(history))
.route("/api/v1/restore-jobs/:id", get(job).delete(cancel))
.route("/api/v1/restore-jobs/:id/reconcile", post(reconcile))
.route("/api/v1/wormhole/restore-targets/:id/claim", post(claim))
.route("/api/v1/wormhole/restore/:id/payload", get(payload))
.route("/api/v1/wormhole/restore/:id/report", post(report))
.route("/api/v1/wormhole/restore/:id/safety", post(safety))
.route("/api/v1/wormhole/restore/:id/apply", post(apply))
}
async fn register(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(target): Json<RestoreTarget>,
) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
if target.name.trim().is_empty()
|| target.name.len() > 128
|| target.name.chars().any(char::is_control)
|| !target.identity.valid(target.engine)
{
return Err(StatusCode::BAD_REQUEST);
}
let profiles = state.db.capture_profiles().map_err(internal)?;
if !profiles.iter().any(|profile| {
profile.application_id == target.application_id
&& profile.format.engine() == Some(target.engine)
}) {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
if !state
.db
.register_restore_target(&target)
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
state
.db
.audit(
"restore.target_registered",
&format!("actor={actor} target={}", target.id),
)
.await
.map_err(internal)?;
Ok((StatusCode::CREATED, Json(target)))
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Rename {
name: String,
}
/// Same rules as at registration: not blank, at most 128 characters, no control characters.
fn valid_target_name(name: &str) -> bool {
!name.trim().is_empty() && name.len() <= 128 && !name.chars().any(char::is_control)
}
async fn rename(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<Rename>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let name = body.name.trim();
if !valid_target_name(name) {
return Err(StatusCode::BAD_REQUEST);
}
if !state.db.rename_restore_target(id, name).map_err(internal)? {
return Err(StatusCode::NOT_FOUND);
}
state
.db
.audit(
"restore_target.renamed",
&format!("actor={actor} target={id}"),
)
.await
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}
async fn targets(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(application): Path<Uuid>,
) -> Result<Json<Vec<RestoreTarget>>, StatusCode> {
admin_read(&state, peer, &headers)?;
state
.db
.restore_targets(application)
.map(Json)
.map_err(internal)
}
#[derive(serde::Serialize)]
struct SnapshotTarget {
#[serde(flatten)]
target: RestoreTarget,
ineligible_reason: Option<&'static str>,
}
async fn snapshot_targets(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
admin_read(&state, peer, &headers)?;
let vault = state.vault.read().await;
let snap = vault
.get_snapshot(snapshot)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
let (application, artifact) =
artifact(&snap.manifest).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
let targets = state
.db
.restore_targets_with_activity(application)
.map_err(internal)?;
let responses = targets
.into_iter()
.map(|(target, active)| {
let ineligible_reason = if active {
crate::db::restore_target_mismatch(&target, &artifact)
} else {
Some("Outpost is no longer paired")
};
SnapshotTarget {
target,
ineligible_reason,
}
})
.collect();
Ok(Json(responses))
}
async fn enqueue(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(request): Json<RestoreRequest>,
) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id)
{
return Err(StatusCode::BAD_REQUEST);
}
// The catalogue lock serializes creation of the durable pin with deletion.
let vault = state.vault.read().await;
let snap = vault
.get_snapshot(request.snapshot_id)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
let (application, artifact) =
artifact(&snap.manifest).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
let job = state
.db
.enqueue_restore(
request.snapshot_id,
application,
request.target_id,
&actor.id(),
&artifact,
now(),
)
.map_err(internal)?
.ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
Ok((StatusCode::ACCEPTED, Json(job)))
}
pub(crate) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArtifact)> {
let hints = &manifest.restore_hints;
let application = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
let format = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
("postgres", "custom") => CaptureFormat::PostgresCustom,
("postgres", "plain") => CaptureFormat::PostgresSql,
("mysql", "plain") => CaptureFormat::MysqlSql,
_ => return None,
};
let sha256 = hints.get("sha256")?.as_str()?.to_owned();
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let identity: tessera_core::restore::DatabaseIdentity =
serde_json::from_value(hints.get("source_identity")?.clone()).ok()?;
if !format.engine().is_some_and(|engine| identity.valid(engine)) {
return None;
}
Some((
application,
RestoreArtifact {
format,
identity,
sha256,
rollback: false,
},
))
}
/// The artifact for putting a target back from the safety copy a restore took of it, or `None` when the
/// snapshot is not such a copy, was taken from some other target, or lacks what a restore needs. The copy is a
/// dump of the target itself, so its source identity is the target's own.
pub(crate) fn rollback_artifact(
manifest: &SnapshotManifest,
target: &tessera_core::restore::RestoreTarget,
) -> Option<RestoreArtifact> {
if !manifest.is_restore_safety() || manifest.safety_target()? != target.id.to_string() {
return None;
}
let format = match (
manifest.provider.as_str(),
manifest.restore_hints.get("format")?.as_str()?,
) {
("postgres", "custom") => CaptureFormat::PostgresCustom,
("postgres", "plain") => CaptureFormat::PostgresSql,
("mysql", "plain") => CaptureFormat::MysqlSql,
_ => return None,
};
let sha256 = manifest.restore_hints.get("sha256")?.as_str()?.to_owned();
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
(format.engine() == Some(target.engine)).then(|| RestoreArtifact {
format,
identity: target.identity.clone(),
sha256,
rollback: true,
})
}
async fn job(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<RestoreJob>, StatusCode> {
admin_read(&state, peer, &headers)?;
state
.db
.restore_job(id, now())
.map_err(internal)?
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
}
async fn history(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
admin_read(&state, peer, &headers)?;
state
.db
.restore_history(snapshot, now())
.map(Json)
.map_err(internal)
}
#[derive(Deserialize)]
struct Recent {
limit: Option<u32>,
}
/// The newest restore jobs across all snapshots. The activity log reads this instead of asking snapshot by snapshot.
async fn recent(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Query(query): Query<Recent>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
admin_read(&state, peer, &headers)?;
state
.db
.restore_recent(query.limit.unwrap_or(50).clamp(1, 200), now())
.map(Json)
.map_err(internal)
}
async fn cancel(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
if !state
.db
.cancel_restore(id, &actor.id(), now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
struct Reconcile {
confirmation: String,
}
async fn reconcile(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<Reconcile>,
) -> Result<StatusCode, (StatusCode, Json<serde_json::Value>)> {
let plain = |status: StatusCode| (status, Json(serde_json::Value::Null));
let actor = admin_write(&state, peer, &headers).map_err(plain)?;
if body.confirmation != format!("RECONCILE {id}") {
return Err(plain(StatusCode::BAD_REQUEST));
}
if !state
.db
.reconcile_restore(id, &actor.id(), now())
.map_err(|error| plain(internal(error)))?
{
return Err((
StatusCode::CONFLICT,
Json(serde_json::json!({
"error": "only a restore job in recovery_required can be reconciled"
})),
));
}
Ok(StatusCode::NO_CONTENT)
}
async fn claim(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(target): Path<Uuid>,
) -> Result<Json<Option<RestoreLease>>, StatusCode> {
let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
state
.db
.claim_restore(outpost, target, now())
.map(Json)
.map_err(internal)
}
fn auth(
state: &HubState,
peer: Option<ConnectInfo<SocketAddr>>,
headers: &HeaderMap,
) -> Result<(Uuid, Uuid), StatusCode> {
let outpost = outpost(state, peer.map(|ConnectInfo(addr)| addr), headers)?;
let token =
header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?;
Ok((
outpost,
Uuid::parse_str(token).map_err(|_| StatusCode::UNAUTHORIZED)?,
))
}
async fn payload(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
let (outpost, token) = auth(&state, peer, &headers)?;
let (job, artifact, _) = state
.db
.restore_access(outpost, id, token, now())
.map_err(internal)?
.filter(|(job, _, _)| job.phase == "checking")
.ok_or(StatusCode::FORBIDDEN)?;
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
let path = staging.path().join("restore");
let size = state
.export_snapshot(job.snapshot_id, path.clone())
.await
.map_err(internal)?;
if state
.db
.restore_access(outpost, id, token, now())
.map_err(internal)?
.is_none_or(|(job, _, _)| job.phase != "checking")
{
return Err(StatusCode::FORBIDDEN);
}
let file = tokio::fs::File::open(path).await.map_err(internal)?;
Ok((
[
(header::CONTENT_TYPE, "application/octet-stream".to_owned()),
(header::CONTENT_LENGTH, size.to_string()),
(header::CACHE_CONTROL, "no-store".to_owned()),
(
axum::http::HeaderName::from_static("x-tessera-sha256"),
artifact.sha256,
),
],
Body::from_stream(ReaderStream::new(file)),
)
.into_response())
}
async fn report(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Result<Json<RestoreProgress>, JsonRejection>,
) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, peer, &headers)?;
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
// Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not
// with what ends up in the database and the log.
let reason = headers
.get(tessera_core::restore::FAILURE_REASON_HEADER)
.and_then(|value| value.to_str().ok())
.and_then(tessera_core::restore::clean_failure_reason);
if !state
.db
.report_restore(outpost, id, token, progress, reason.as_deref(), now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
if let Some(reason) = &reason {
tracing::warn!(job = %id, ?progress, %reason, "restore step failed");
}
Ok(StatusCode::NO_CONTENT)
}
async fn safety(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> {
let (outpost, token) = auth(&state, peer, &headers)?;
let (job, _, safety_id) = state
.db
.restore_access(outpost, id, token, now())
.map_err(internal)?
.filter(|(job, _, _)| matches!(job.phase.as_str(), "safety" | "ready"))
.ok_or(StatusCode::FORBIDDEN)?;
let (format, provider, format_name) = match job.target.engine {
Engine::Postgres => (CaptureFormat::PostgresCustom, "postgres", "custom"),
Engine::Mysql => (CaptureFormat::MysqlSql, "mysql", "plain"),
};
let (file, expected) = receive_payload(&state, &headers, body, format).await?;
if let Some(snapshot) = job.safety_snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
}
let vault = state.vault.clone().read_owned().await;
let db = state.db.clone();
let saved = tokio::task::spawn_blocking(move || {
let input = vault
.get_snapshot(job.snapshot_id)?
.ok_or_else(|| anyhow::anyhow!("pinned snapshot missing"))?;
let manifest = SnapshotManifest {
snapshot_id: safety_id,
orbit_id: input.manifest.orbit_id,
orbit_name: input.manifest.orbit_name,
provider: provider.into(),
labels: vec!["restore-safety".into()],
paths: vec![],
restore_hints: serde_json::json!({
"format": format_name, "safety_for": id, "target_id": job.target.id,
"sha256": hex::encode(expected),
}),
};
let prepared = if vault.has_published_snapshot(safety_id)? {
None
} else {
let prepared = vault.prepare_payload(manifest, file, false)?;
if let Err(error) = vault.verify_prepared_payload(&prepared, &expected) {
let _ = vault.discard_prepared(&prepared);
return Err(error);
}
Some(prepared)
};
let mut wrote = false;
let result = db.record_safety(outpost, id, token, now(), |expected_id| {
anyhow::ensure!(expected_id == safety_id, "stale safety snapshot");
if !vault.has_published_snapshot(safety_id)? {
vault.publish_prepared(
prepared
.as_ref()
.ok_or_else(|| anyhow::anyhow!("safety snapshot missing"))?,
)?;
wrote = true;
}
Ok(())
})?;
if !wrote {
if let Some(prepared) = &prepared {
let _ = vault.discard_prepared(prepared);
}
}
Ok::<_, anyhow::Error>(result)
})
.await
.map_err(internal)?
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
Ok(Json(serde_json::json!({ "snapshot_id": saved })))
}
async fn apply(
State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, peer, &headers)?;
if !state
.db
.authorize_apply(outpost, id, token, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,573 @@
use crate::admin::{tokens_match, SessionGate};
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
#[derive(Serialize)]
struct Status {
login_enabled: bool,
oidc_enabled: bool,
authorized: bool,
admin: bool,
actor: Option<String>,
csrf: Option<String>,
expires_at: Option<i64>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Login {
password: String,
}
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/operator/session", get(status).delete(logout))
.route("/api/v1/operator/login", post(login))
.route("/api/v1/me", get(me))
.route(
"/api/v1/me/preferences",
get(preferences).put(set_preferences),
)
}
async fn status(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> (HeaderMap, Json<Status>) {
let browser = state.sessions.active(&headers);
// The app opens for an administrator or for anyone holding a live grant that lets them read an orbit.
let reads_something = browser.as_ref().is_some_and(|session| {
let now = chrono::Utc::now().timestamp();
!session.admin
&& (state
.db
.permitted_orbits(Some(&session.user_id), &session.groups, "orbit.read", now)
.is_ok_and(|p| p.everywhere || !p.orbits.is_empty())
// someone who may only refresh a staging database still gets in, to that one screen
|| state.db.granted_relations(Some(&session.user_id), &session.groups, now).is_ok_and(|r| !r.is_empty()))
});
let authorized = browser.as_ref().is_some_and(|session| session.admin)
|| reads_something
|| (browser.is_none()
&& !state.sessions.enabled()
&& state.admin.token.is_none()
&& state.admin.authorize(peer, &headers).is_ok());
(
no_store(),
Json(Status {
login_enabled: state.sessions.password_enabled(),
oidc_enabled: state.oidc.is_some(),
authorized,
admin: browser.as_ref().map_or(authorized, |session| session.admin),
actor: browser.as_ref().map(|session| session.actor.clone()),
expires_at: browser.as_ref().map(|session| session.expires_at),
csrf: browser.map(|session| session.csrf.to_string()),
}),
)
}
#[derive(Serialize)]
struct MyGrant {
permission: String,
/// `None` = every orbit.
orbit_id: Option<String>,
}
#[derive(Serialize)]
struct Me {
id: String,
kind: &'static str,
auth_method: &'static str,
display_name: String,
admin: bool,
capabilities: Vec<String>,
grants: Vec<MyGrant>,
/// Ids of the relations this person may refresh through (everything, for an administrator).
refresh_relations: Vec<String>,
}
/// The caller's own identity and what it may use: `admin`, its live grants, and the relations it may refresh through.
async fn me(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Me>), StatusCode> {
// Identity only, no gate: a signed-in user without any grant still gets this (empty grants).
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
let (id, kind, auth_method) = actor.principal.fields();
let grants: Vec<MyGrant> = if actor.subject.admin {
vec![]
} else {
state
.db
.grants_of(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
chrono::Utc::now().timestamp(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.into_iter()
.map(|(permission, orbit_id)| MyGrant {
permission,
orbit_id,
})
.collect()
};
let mut capabilities: Vec<String> = if actor.subject.admin {
vec!["admin".into()]
} else {
let mut names: Vec<String> = grants.iter().map(|g| g.permission.clone()).collect();
names.dedup();
names
};
capabilities.sort();
let refresh_relations = if actor.subject.admin {
vec![]
} else {
state
.db
.granted_relations(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
chrono::Utc::now().timestamp(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
};
Ok((
no_store(),
Json(Me {
id,
kind,
auth_method,
display_name: actor.name.clone(),
admin: actor.subject.admin,
capabilities,
grants,
refresh_relations,
}),
))
}
/// Display choices an account keeps across browsers. Every key has a closed set of values.
const LOOKS: [&str; 2] = ["window", "radar"];
#[derive(Serialize)]
struct Preferences {
look: Option<String>,
}
/// The caller's own preferences. A caller without an account (the legacy token, local
/// development) simply has none.
async fn preferences(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Preferences>), StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
let stored = match actor.subject.user_id.as_deref() {
Some(user) => state
.db
.preferences(user)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
None => Default::default(),
};
let look = stored
.get("look")
.filter(|value| LOOKS.contains(&value.as_str()))
.cloned();
Ok((no_store(), Json(Preferences { look })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetPreferences {
look: Option<String>,
}
async fn set_preferences(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<SetPreferences>,
) -> Result<StatusCode, StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, true)?;
let user = actor
.subject
.user_id
.as_deref()
.ok_or(StatusCode::NOT_FOUND)?;
if let Some(look) = body.look {
if !LOOKS.contains(&look.as_str()) {
return Err(StatusCode::BAD_REQUEST);
}
state
.db
.set_preference(user, "look", &look, chrono::Utc::now().timestamp())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
Ok(StatusCode::NO_CONTENT)
}
async fn login(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(input): Json<Login>,
) -> Result<(HeaderMap, Json<Status>), StatusCode> {
// Cheap checks first: per-source budget, then the account ceiling, then a
// bounded number of concurrent Argon2 verifications. A flood is refused
// before it can cost CPU or memory, and it only spends its own source's budget.
let source = state.limits.source(Some(peer), &headers);
if !state.limits.login_allowed(source) {
if state.limits.audit_denial(source) {
let _ = state.db.audit_event(
&Principal::Anonymous,
AuditAction::Login,
AuditResource::Session,
AuditOutcome::Denied,
uuid::Uuid::new_v4(),
);
}
return Err(StatusCode::TOO_MANY_REQUESTS);
}
if input.password.is_empty() || input.password.len() > 1024 {
return Err(StatusCode::UNAUTHORIZED);
}
let permit = state
.limits
.argon2
.clone()
.try_acquire_owned()
.map_err(|_| StatusCode::TOO_MANY_REQUESTS)?;
let gate = state.sessions.clone();
let attempt = tokio::task::spawn_blocking(move || {
let _permit = permit; // released when hashing is done, not when the handler returns
gate.login(&headers, &input.password)
})
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let (principal, outcome) = match &attempt {
Ok(session) => (
Principal::Emergency(session.actor.clone()),
AuditOutcome::Succeeded,
),
Err(_) => (Principal::Anonymous, AuditOutcome::Failed),
};
state
.db
.audit_event(
&principal,
AuditAction::Login,
AuditResource::Session,
outcome,
uuid::Uuid::new_v4(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let session = attempt?;
state
.db
.audit("operator.login", &session.actor)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store();
headers.insert(
header::SET_COOKIE,
session_cookie(Some(&session.id.to_string()))?,
);
Ok((
headers,
Json(Status {
login_enabled: true,
oidc_enabled: state.oidc.is_some(),
authorized: true,
admin: true,
actor: Some(session.actor),
expires_at: Some(session.expires_at),
csrf: Some(session.csrf.to_string()),
}),
))
}
async fn logout(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(StatusCode, HeaderMap), StatusCode> {
let session = state
.sessions
.active(&headers)
.ok_or(StatusCode::UNAUTHORIZED)?;
require_csrf(&headers, &session.csrf.to_string())?;
state.sessions.remove(session.id);
state
.db
.audit_event(
&session.principal(),
AuditAction::Logout,
AuditResource::Session,
AuditOutcome::Succeeded,
uuid::Uuid::new_v4(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
state
.db
.audit("operator.logout", &session.actor)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store();
headers.insert(header::SET_COOKIE, session_cookie(None)?);
Ok((StatusCode::NO_CONTENT, headers))
}
pub(super) fn require_csrf(headers: &HeaderMap, expected: &str) -> Result<(), StatusCode> {
if headers
.get("x-tessera-csrf")
.and_then(|value| value.to_str().ok())
.is_some_and(|value| tokens_match(expected, value))
{
Ok(())
} else {
Err(StatusCode::FORBIDDEN)
}
}
fn no_store() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers
}
pub(super) fn session_cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
let value = format!(
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
SessionGate::COOKIE,
id.unwrap_or_default(),
if id.is_some() {
SessionGate::DURATION.as_secs()
} else {
0
},
);
HeaderValue::from_str(&value).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::{to_bytes, Body};
use axum::http::Request;
use tower::ServiceExt;
#[tokio::test]
async fn operator_session_requires_csrf_and_expires_without_disabling_cli() {
let dir = tempfile::tempdir().unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await
.unwrap();
state.sessions = SessionGate::fixture(state.db.clone());
state.admin.token = Some("fixture-api-token".into());
let app = crate::api::router(state.clone());
let request = |method: &str, uri: &str, body: &'static str| {
Request::builder()
.method(method)
.uri(uri)
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body))
.unwrap()
};
let anonymous = app
.clone()
.oneshot(request("GET", "/api/v1/orbits", ""))
.await
.unwrap();
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
let denied = app
.clone()
.oneshot(request(
"POST",
"/api/v1/operator/login",
r#"{"password":"wrong"}"#,
))
.await
.unwrap();
assert_eq!(denied.status(), StatusCode::UNAUTHORIZED);
let login = app
.clone()
.oneshot(request(
"POST",
"/api/v1/operator/login",
r#"{"password":"fixture-operator-password"}"#,
))
.await
.unwrap();
assert_eq!(login.status(), StatusCode::OK);
let set_cookie = login.headers()[header::SET_COOKIE].to_str().unwrap();
assert!(set_cookie.contains("HttpOnly; Secure; SameSite=Strict"));
let cookie = HeaderValue::from_str(set_cookie.split(';').next().unwrap()).unwrap();
let bytes = to_bytes(login.into_body(), 1024).await.unwrap();
let status: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(status["actor"], "fixture-operator");
let csrf = HeaderValue::from_str(status["csrf"].as_str().unwrap()).unwrap();
let mut action = request("POST", "/api/v1/wormhole/pairing", "");
action.headers_mut().insert(header::COOKIE, cookie.clone());
let denied = app.clone().oneshot(action).await.unwrap();
assert_eq!(denied.status(), StatusCode::FORBIDDEN);
let mut action = request("POST", "/api/v1/wormhole/pairing", "");
action.headers_mut().insert(header::COOKIE, cookie.clone());
action.headers_mut().insert("x-tessera-csrf", csrf.clone());
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::OK
);
let mut action = request("DELETE", "/api/v1/operator/session", "");
action.headers_mut().insert(header::COOKIE, cookie.clone());
action.headers_mut().insert("x-tessera-csrf", csrf);
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::NO_CONTENT
);
let mut action = request("GET", "/api/v1/orbits", "");
action.headers_mut().insert(header::COOKIE, cookie);
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
let login = app
.clone()
.oneshot(request(
"POST",
"/api/v1/operator/login",
r#"{"password":"fixture-operator-password"}"#,
))
.await
.unwrap();
let cookie = HeaderValue::from_str(
login.headers()[header::SET_COOKIE]
.to_str()
.unwrap()
.split(';')
.next()
.unwrap(),
)
.unwrap();
state.sessions.expire();
let mut action = request("GET", "/api/v1/orbits", "");
action.headers_mut().insert(header::COOKIE, cookie);
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
let mut cli = request("GET", "/api/v1/orbits", "");
cli.headers_mut().insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer fixture-api-token"),
);
assert_eq!(app.oneshot(cli).await.unwrap().status(), StatusCode::OK);
let connection = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
let audited: i64 = connection.query_row(
"SELECT COUNT(*) FROM audit_log WHERE event IN ('operator.login','operator.logout') AND detail = 'fixture-operator'",
[], |row| row.get(0),
).unwrap();
assert_eq!(audited, 3);
let actor_count: i64 = connection.query_row(
"SELECT COUNT(*) FROM audit_events WHERE action IN ('auth.login','auth.logout')
AND actor_id='emergency:fixture-operator' AND actor_kind='user' AND auth_method='password'",
[], |row| row.get(0),
).unwrap();
assert_eq!(actor_count, 3);
let failed_count: i64 = connection.query_row(
"SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='failed' AND actor_id='anonymous'",
[], |row| row.get(0),
).unwrap();
assert_eq!(failed_count, 1);
let values: String = connection.query_row(
"SELECT group_concat(actor_id || action || coalesce(resource_id,'') || auth_method) FROM audit_events",
[], |row| row.get(0),
).unwrap();
for secret in [
"fixture-operator-password",
"fixture-api-token",
"Bearer",
"wrong",
] {
assert!(!values.contains(secret));
}
}
#[tokio::test]
async fn me_reports_the_caller_and_rejects_anonymous() {
let dir = tempfile::tempdir().unwrap();
let mut state =
HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.await
.unwrap();
state.sessions = SessionGate::fixture(state.db.clone());
let app = crate::api::router(state);
let peer = || ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap());
let anonymous = app
.clone()
.oneshot(
Request::builder()
.uri("/api/v1/me")
.extension(peer())
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
let login = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/v1/operator/login")
.extension(peer())
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"password":"fixture-operator-password"}"#))
.unwrap(),
)
.await
.unwrap();
let cookie = HeaderValue::from_str(
login.headers()[header::SET_COOKIE]
.to_str()
.unwrap()
.split(';')
.next()
.unwrap(),
)
.unwrap();
let me = app
.oneshot(
Request::builder()
.uri("/api/v1/me")
.extension(peer())
.header(header::COOKIE, cookie)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(me.status(), StatusCode::OK);
assert_eq!(me.headers()[header::CACHE_CONTROL], "no-store");
let body: serde_json::Value =
serde_json::from_slice(&to_bytes(me.into_body(), 4096).await.unwrap()).unwrap();
assert_eq!(body["id"], "emergency:fixture-operator");
assert_eq!(body["kind"], "user");
assert_eq!(body["auth_method"], "password");
assert_eq!(body["capabilities"][0], "admin");
assert!(!body.to_string().contains("csrf"));
}
}

View File

@@ -0,0 +1,234 @@
//! Server-derived identities and payload-free audit records.
use uuid::Uuid;
#[derive(Clone, Debug)]
pub enum Principal {
Emergency(String),
/// OIDC user, by stable `users.id` (never by a name supplied by the IdP).
Oidc(String),
Service(&'static str),
Outpost(Uuid),
Anonymous,
LocalDevelopment,
}
impl Principal {
pub fn fields(&self) -> (String, &'static str, &'static str) {
match self {
Self::Emergency(name) => (format!("emergency:{name}"), "user", "password"),
Self::Oidc(id) => (format!("oidc:{id}"), "user", "oidc"),
Self::Service(id) => (id.to_string(), "service", "api_token"),
Self::Outpost(id) => (id.to_string(), "outpost", "outpost_token"),
Self::Anonymous => ("anonymous".into(), "anonymous", "none"),
Self::LocalDevelopment => ("local-development".into(), "service", "development"),
}
}
}
pub enum AuditAction {
Authentication,
Authorization,
Login,
Logout,
OutpostBind,
OutpostPair,
CredentialRotate,
CredentialRevoke,
GrantCreate,
GrantDelete,
UserState,
SessionsRevoke,
ExportRequested,
ExportReady,
ExportFinished,
ExportDisconnected,
EnvironmentSet,
RelationCreate,
RelationRetarget,
RelationDeactivate,
RelationGrantCreate,
RelationGrantDelete,
/// One of the refresh run's states or steps; the name is the audit action (`refresh.completed`, ...).
RefreshEvent(&'static str),
}
impl AuditAction {
pub fn as_str(&self) -> &'static str {
match self {
Self::Authentication => "authentication.check",
Self::Authorization => "authorization.check",
Self::Login => "auth.login",
Self::Logout => "auth.logout",
Self::OutpostBind => "orbit.outpost_bind",
Self::OutpostPair => "outpost.pair",
Self::CredentialRotate => "outpost.credential_rotate",
Self::CredentialRevoke => "outpost.credential_revoke",
Self::GrantCreate => "access.grant_create",
Self::GrantDelete => "access.grant_delete",
Self::UserState => "access.user_state",
Self::SessionsRevoke => "access.sessions_revoke",
Self::ExportRequested => "export.requested",
Self::ExportReady => "export.ready",
Self::ExportFinished => "export.finished",
Self::ExportDisconnected => "export.disconnected",
Self::EnvironmentSet => "environment.set",
Self::RelationCreate => "relation.create",
Self::RelationRetarget => "relation.retarget",
Self::RelationDeactivate => "relation.deactivate",
Self::RelationGrantCreate => "relation.grant_create",
Self::RelationGrantDelete => "relation.grant_delete",
Self::RefreshEvent(name) => name,
}
}
}
pub enum AuditOutcome {
Allowed,
Denied,
Succeeded,
Failed,
}
impl AuditOutcome {
pub fn as_str(&self) -> &'static str {
match self {
Self::Allowed => "allowed",
Self::Denied => "denied",
Self::Succeeded => "succeeded",
Self::Failed => "failed",
}
}
}
pub enum AuditResource {
Api,
Session,
Orbit(Uuid),
Outpost(Uuid),
UploadSession(Uuid),
Grant(Uuid),
User(Uuid),
Snapshot(Uuid),
Relation(Uuid),
RestoreTarget(Uuid),
RefreshRun(Uuid),
}
impl AuditResource {
pub fn fields(&self) -> (&'static str, Option<String>) {
match self {
Self::Api => ("api", None),
Self::Session => ("session", None),
Self::Orbit(id) => ("orbit", Some(id.to_string())),
Self::Outpost(id) => ("outpost", Some(id.to_string())),
Self::UploadSession(id) => ("upload_session", Some(id.to_string())),
Self::Grant(id) => ("grant", Some(id.to_string())),
Self::User(id) => ("user", Some(id.to_string())),
Self::Snapshot(id) => ("snapshot", Some(id.to_string())),
Self::Relation(id) => ("relation", Some(id.to_string())),
Self::RestoreTarget(id) => ("restore_target", Some(id.to_string())),
Self::RefreshRun(id) => ("refresh_run", Some(id.to_string())),
}
}
}
/// What a signed-in user may do. Only the first four can be granted to a
/// non-administrator; everything else belongs to the configured administrators
/// (SSO admin mapping, the emergency operator, the legacy admin token). Names are
/// matched exactly, never by prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Permission {
OrbitRead,
SnapshotRead,
CaptureRun,
SnapshotDownload,
OrbitManage,
OutpostManage,
RetentionManage,
SnapshotDelete,
RecoveryManage,
AccessManage,
/// Configuring environments and relations. Administrators only.
RelationManage,
/// Refreshing a staging target. Never held through `access_grants`: it is granted per relation, in `relation_grants`.
RefreshRun,
}
impl Permission {
pub fn as_str(self) -> &'static str {
match self {
Self::OrbitRead => "orbit.read",
Self::SnapshotRead => "snapshot.read",
Self::CaptureRun => "capture.run",
Self::SnapshotDownload => "snapshot.download",
Self::OrbitManage => "orbit.manage",
Self::OutpostManage => "outpost.manage",
Self::RetentionManage => "retention.manage",
Self::SnapshotDelete => "snapshot.delete",
Self::RecoveryManage => "recovery.manage",
Self::AccessManage => "access.manage",
Self::RelationManage => "relation.manage",
Self::RefreshRun => "refresh.run",
}
}
/// Every permission, in the order the administration screens list them.
pub const ALL: [Permission; 12] = [
Self::OrbitRead,
Self::SnapshotRead,
Self::CaptureRun,
Self::SnapshotDownload,
Self::OrbitManage,
Self::OutpostManage,
Self::RetentionManage,
Self::SnapshotDelete,
Self::RecoveryManage,
Self::AccessManage,
Self::RelationManage,
Self::RefreshRun,
];
pub fn parse(text: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|permission| permission.as_str() == text)
}
/// Held only by administrators (neither grantable nor the per-relation refresh).
pub fn admin_only(self) -> bool {
!self.grantable() && self != Self::RefreshRun
}
/// May be given to a non-administrator through a grant.
pub fn grantable(self) -> bool {
matches!(
self,
Self::OrbitRead | Self::SnapshotRead | Self::CaptureRun | Self::SnapshotDownload
)
}
}
/// Named bundles that expand into individual grants. Every bundle includes
/// `orbit.read`: without it a resource is invisible and answers 404.
pub fn role(name: &str) -> Option<&'static [Permission]> {
use Permission::*;
match name {
"viewer" => Some(&[OrbitRead, SnapshotRead]),
"capturer" => Some(&[OrbitRead, SnapshotRead, CaptureRun]),
"downloader" => Some(&[OrbitRead, SnapshotRead, SnapshotDownload]),
_ => None,
}
}
pub const ROLE_NAMES: [&str; 3] = ["viewer", "capturer", "downloader"];
/// Who is asking, as far as authorization is concerned.
#[derive(Clone, Debug)]
pub struct Subject {
/// `users.id` for signed-in users; `None` for the legacy token and local development.
pub user_id: Option<String>,
/// Groups verified at sign-in. Changes at the IdP apply at the next sign-in.
pub groups: Vec<String>,
/// Configured administrator: holds every permission everywhere.
pub admin: bool,
}

View File

@@ -1,7 +1,20 @@
pub(crate) mod access;
mod audit;
pub(crate) mod credentials;
mod jobs;
pub use jobs::ProfileChange;
pub(crate) mod oidc_login;
pub(crate) mod refresh;
pub(crate) mod relations;
mod restore;
pub mod sessions;
pub(crate) use restore::restore_target_mismatch;
use anyhow::Result;
use rusqlite::{params, Connection};
use rusqlite::{params, Connection, OptionalExtension};
use std::path::Path;
use std::sync::{Arc, Mutex};
use tessera_core::{decay::RetentionPolicy, OutpostSummary};
use uuid::Uuid;
#[derive(Clone)]
@@ -9,7 +22,7 @@ pub struct Db {
conn: Arc<Mutex<Connection>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[derive(Clone)]
pub struct OrbitRow {
pub id: Uuid,
pub name: String,
@@ -17,6 +30,7 @@ pub struct OrbitRow {
pub provider_config: String,
pub schedule: Option<String>,
pub decay_preset: String,
pub retention: Option<RetentionPolicy>,
pub dry_run: bool,
pub last_status: String,
}
@@ -66,14 +80,46 @@ impl Db {
total INTEGER,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS upload_ranges (
session_id TEXT NOT NULL,
start_off INTEGER NOT NULL,
end_off INTEGER NOT NULL
);
"#,
)?;
ensure_column(
&conn,
"upload_sessions",
"sealed",
"INTEGER NOT NULL DEFAULT 0",
)?;
ensure_column(&conn, "orbits", "retention", "TEXT")?;
ensure_column(
&conn,
"orbits",
"outpost_id",
"TEXT REFERENCES outposts(id)",
)?;
credentials::migrate(&conn)?;
jobs::migrate(&conn)?;
restore::migrate(&conn)?;
audit::migrate(&conn)?;
sessions::migrate(&conn)?;
oidc_login::migrate(&conn)?;
access::migrate(&conn)?;
relations::migrate(&conn)?;
refresh::migrate(&conn)?;
Ok(())
}
pub async fn list_orbits(&self) -> Result<Vec<OrbitRow>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status FROM orbits ORDER BY name")?;
let mut stmt = conn.prepare("SELECT o.id, o.name, o.provider, o.provider_config, o.schedule, o.decay_preset, o.dry_run,
CASE WHEN p.application_id IS NULL THEN o.last_status ELSE COALESCE((
SELECT j.status FROM capture_jobs j WHERE j.application_id = p.application_id
ORDER BY j.created_at DESC, j.rowid DESC LIMIT 1
), 'idle') END, o.retention
FROM orbits o LEFT JOIN capture_profiles p ON p.orbit_id = o.id ORDER BY o.name")?;
let rows = stmt.query_map([], |r| {
Ok(OrbitRow {
id: Uuid::parse_str(&r.get::<_, String>(0)?).unwrap_or_else(|_| Uuid::new_v4()),
@@ -82,21 +128,73 @@ impl Db {
provider_config: r.get(3)?,
schedule: r.get(4)?,
decay_preset: r.get(5)?,
retention: r
.get::<_, Option<String>>(8)?
.map(|json| {
serde_json::from_str(&json).map_err(|error| {
rusqlite::Error::FromSqlConversionFailure(
8,
rusqlite::types::Type::Text,
Box::new(error),
)
})
})
.transpose()?,
dry_run: r.get::<_, i64>(6)? != 0,
last_status: r.get(7)?,
})
})?;
Ok(rows.filter_map(|r| r.ok()).collect())
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
/// Current names of all orbits, by id. Snapshots keep the name they were written under; what people see
/// is the name the orbit has now.
pub fn orbit_names(&self) -> Result<std::collections::HashMap<Uuid, String>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name FROM orbits")?;
let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
Ok(rows
.filter_map(Result::ok)
.filter_map(|(id, name)| Some((Uuid::parse_str(&id).ok()?, name)))
.collect())
}
/// Change an orbit's name. `None` for an unknown orbit, `Some(false)` when another orbit has the name
/// (compared without regard to case), `Some(true)` when renamed.
pub fn rename_orbit(&self, id: Uuid, name: &str) -> Result<Option<bool>> {
let conn = self.conn.lock().unwrap();
let exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE id = ?1)",
params![id.to_string()],
|r| r.get(0),
)?;
if !exists {
return Ok(None);
}
let taken: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE lower(name) = lower(?2) AND id <> ?1)",
params![id.to_string(), name],
|r| r.get(0),
)?;
if taken {
return Ok(Some(false));
}
conn.execute(
"UPDATE orbits SET name = ?2 WHERE id = ?1",
params![id.to_string(), name],
)?;
Ok(Some(true))
}
pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
r#"INSERT INTO orbits (id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
r#"INSERT INTO orbits (id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status, retention)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
ON CONFLICT(id) DO UPDATE SET
name=excluded.name, provider=excluded.provider, provider_config=excluded.provider_config,
schedule=excluded.schedule, decay_preset=excluded.decay_preset, dry_run=excluded.dry_run"#,
schedule=excluded.schedule, decay_preset=excluded.decay_preset, dry_run=excluded.dry_run,
retention=excluded.retention"#,
params![
row.id.to_string(),
row.name,
@@ -106,11 +204,44 @@ impl Db {
row.decay_preset,
row.dry_run as i64,
row.last_status,
row.retention.as_ref().map(serde_json::to_string).transpose()?,
],
)?;
Ok(())
}
pub fn set_orbit_retention(
&self,
id: Uuid,
preset: &str,
policy: Option<&RetentionPolicy>,
) -> Result<bool> {
let json = policy.map(serde_json::to_string).transpose()?;
let changed = self.conn.lock().unwrap().execute(
"UPDATE orbits SET decay_preset = ?1, retention = ?2 WHERE id = ?3",
params![preset, json, id.to_string()],
)?;
Ok(changed > 0)
}
pub fn orbit_retention(&self, id: Uuid) -> Result<(String, Option<RetentionPolicy>)> {
let row: Option<(String, Option<String>)> = self
.conn
.lock()
.unwrap()
.query_row(
"SELECT decay_preset, retention FROM orbits WHERE id = ?1",
[id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let (preset, json) = row.unwrap_or_else(|| ("week-of-dailies".into(), None));
Ok((
preset,
json.as_deref().map(serde_json::from_str).transpose()?,
))
}
pub async fn set_orbit_status(&self, id: Uuid, status: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
@@ -133,13 +264,233 @@ impl Db {
&self,
id: &str,
orbit_id: &str,
outpost_id: Uuid,
total: Option<i64>,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
let inserted = conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, outpost_id, offset, total, sealed, created_at)
SELECT ?1, id, ?3, 0, ?4, 0, datetime('now') FROM orbits
WHERE id = ?2 AND outpost_id = ?3 AND provider = 'wormhole' AND dry_run = 0",
params![id, orbit_id, outpost_id.to_string(), total],
)?;
anyhow::ensure!(
inserted == 1,
"Outpost assignment changed during upload initialization"
);
Ok(())
}
pub fn bind_legacy_outpost(&self, orbit: Uuid, outpost: Uuid) -> Result<bool> {
let conn = self.conn.lock().unwrap();
Ok(conn.execute(
"UPDATE orbits SET outpost_id=?2 WHERE id=?1 AND provider='wormhole' AND dry_run=0
AND NOT EXISTS (SELECT 1 FROM capture_profiles WHERE orbit_id=?1)
AND EXISTS (SELECT 1 FROM outposts WHERE id=?2 AND pairing_state='active')",
params![orbit.to_string(), outpost.to_string()],
)? == 1)
}
pub fn legacy_upload_owned_by(&self, orbit: Uuid, outpost: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1 AND outpost_id=?2
AND provider='wormhole' AND dry_run=0)",
params![orbit.to_string(), outpost.to_string()],
|row| row.get(0),
)?)
}
pub fn list_outposts(&self) -> Result<Vec<OutpostSummary>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn
.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?;
let rows = stmt.query_map([], |row| {
let id = Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| {
rusqlite::Error::FromSqlConversionFailure(
0,
rusqlite::types::Type::Text,
Box::new(err),
)
})?;
Ok(OutpostSummary {
id,
name: row.get(1)?,
last_seen: row.get(2)?,
pairing_state: row.get(3)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn touch_outpost(&self, id: Uuid) -> Result<()> {
let now = chrono::Utc::now();
let recent = (now - chrono::Duration::seconds(30)).to_rfc3339();
self.conn.lock().unwrap().execute(
"UPDATE outposts SET last_seen = ?2 WHERE id = ?1 AND (last_seen IS NULL OR last_seen < ?3)",
params![id.to_string(), now.to_rfc3339(), recent],
)?;
Ok(())
}
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT orbit_id, total, sealed, outpost_id FROM upload_sessions WHERE id = ?1",
)?;
let mut rows = stmt.query(params![id])?;
let Some(row) = rows.next()? else {
return Ok(None);
};
let orbit_id: String = row.get(0)?;
let total: Option<i64> = row.get(1)?;
let sealed: i64 = row.get(2)?;
Ok(Some(UploadSession {
orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?,
total: total.unwrap_or(0).max(0) as u64,
sealed: sealed != 0,
outpost_id: row.get(3)?,
}))
}
/// Records a received range. Returns whether this call won the right to seal.
pub fn record_range(&self, session_id: &str, start: u64, end: u64, total: u64) -> Result<bool> {
let conn = self.conn.lock().unwrap();
conn.execute_batch("BEGIN IMMEDIATE")?;
let outcome = (|| -> Result<bool> {
let sealed: i64 = conn.query_row(
"SELECT sealed FROM upload_sessions WHERE id = ?1",
params![session_id],
|row| row.get(0),
)?;
if sealed != 0 {
return Ok(false);
}
conn.execute(
"INSERT INTO upload_ranges (session_id, start_off, end_off) VALUES (?1, ?2, ?3)",
params![session_id, start as i64, end as i64],
)?;
let mut stmt =
conn.prepare("SELECT start_off, end_off FROM upload_ranges WHERE session_id = ?1")?;
let ranges = stmt
.query_map(params![session_id], |row| {
Ok(crate::upload::ByteRange {
start: row.get::<_, i64>(0)? as u64,
end: row.get::<_, i64>(1)? as u64,
})
})?
.collect::<Result<Vec<_>, _>>()?;
let covered = crate::upload::contiguous_from_zero(&ranges);
conn.execute(
"UPDATE upload_sessions SET offset = ?2 WHERE id = ?1",
params![session_id, covered as i64],
)?;
if covered >= total {
conn.execute(
"UPDATE upload_sessions SET sealed = 1 WHERE id = ?1 AND sealed = 0",
params![session_id],
)?;
return Ok(true);
}
Ok(false)
})();
match outcome {
Ok(value) => {
conn.execute_batch("COMMIT")?;
Ok(value)
}
Err(error) => {
let _ = conn.execute_batch("ROLLBACK");
Err(error)
}
}
}
pub fn mark_upload_unsealed(&self, session_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, offset, total, created_at) VALUES (?1, ?2, 0, ?3, datetime('now'))",
params![id, orbit_id, total],
"UPDATE upload_sessions SET sealed = 0 WHERE id = ?1",
params![session_id],
)?;
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct UploadSession {
pub orbit_id: Uuid,
pub outpost_id: Option<String>,
pub total: u64,
pub sealed: bool,
}
fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Result<()> {
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
let names = stmt.query_map([], |row| row.get::<_, String>(1))?;
for name in names {
if name? == column {
return Ok(());
}
}
conn.execute(
&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"),
[],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn existing_orbit_can_switch_between_preset_and_custom_retention() {
let conn = Connection::open_in_memory().unwrap();
let id = Uuid::new_v4();
conn.execute_batch(
"CREATE TABLE orbits (
id TEXT PRIMARY KEY, name TEXT, provider TEXT, provider_config TEXT,
schedule TEXT, decay_preset TEXT, dry_run INTEGER, last_status TEXT
)",
)
.unwrap();
conn.execute(
"INSERT INTO orbits VALUES (?1, 'archive', 'filesystem', '{}', NULL,
'month-of-weeklies', 0, 'completed')",
[id.to_string()],
)
.unwrap();
let db = Db {
conn: Arc::new(Mutex::new(conn)),
};
db.migrate().await.unwrap();
assert_eq!(
db.orbit_retention(id).unwrap(),
("month-of-weeklies".into(), None)
);
let policy = RetentionPolicy {
keep_daily: 7,
keep_weekly: 2,
keep_monthly: 6,
keep_yearly: 3,
};
assert!(db
.set_orbit_retention(id, "week-of-dailies", Some(&policy))
.unwrap());
let orbit = db.list_orbits().await.unwrap().remove(0);
assert_eq!(orbit.retention, Some(policy));
assert_eq!(orbit.last_status, "completed");
assert_eq!(db.orbit_retention(id).unwrap().1, Some(policy));
assert!(db
.set_orbit_retention(id, "year-of-monthlies", None)
.unwrap());
assert_eq!(
db.orbit_retention(id).unwrap(),
("year-of-monthlies".into(), None)
);
assert!(!db
.set_orbit_retention(Uuid::new_v4(), "year-of-monthlies", None)
.unwrap());
}
}

View File

@@ -0,0 +1,539 @@
//! Grants: which permission a user (or an IdP group) holds, globally or on one orbit.
//!
//! Grants are read live on every request, never cached, so a revoke or an expiry
//! is effective on the very next request. Anything stored that does not parse as a
//! known permission or scope is ignored by the gate.
use super::*;
use std::collections::HashSet;
#[derive(Clone, Debug, serde::Serialize)]
pub struct Grant {
pub id: String,
pub principal_type: String,
pub principal: String,
pub permission: String,
pub scope_type: String,
pub scope_id: Option<String>,
pub expires_at: Option<i64>,
pub created_by: String,
pub created_at: i64,
}
pub struct NewGrant<'a> {
pub principal_type: &'a str,
pub principal: &'a str,
pub permission: &'a str,
pub orbit: Option<&'a str>,
pub expires_at: Option<i64>,
pub created_by: &'a str,
}
/// Outcome of [`Db::replace_grants`].
pub enum Replace {
Done {
removed: Vec<String>,
written: Vec<Grant>,
},
/// A grant to replace belongs to someone or somewhere else than the new set.
Mismatch,
}
/// Orbits a subject may use for one permission.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Permitted {
pub everywhere: bool,
pub orbits: HashSet<String>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct UserRow {
pub id: String,
pub issuer: String,
pub display_name: String,
pub active: bool,
pub created_at: i64,
pub last_login_at: Option<i64>,
pub is_emergency: bool,
/// Administrator at the last sign-in (the SSO admin mapping; the emergency operator always is).
pub admin: bool,
/// Groups the identity provider reported at the last sign-in.
pub groups: Vec<String>,
}
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS access_grants (
id TEXT PRIMARY KEY,
principal_type TEXT NOT NULL CHECK(principal_type IN ('user','group')),
principal TEXT NOT NULL,
permission TEXT NOT NULL,
scope_type TEXT NOT NULL CHECK(scope_type IN ('global','orbit')),
scope_id TEXT NOT NULL DEFAULT '',
expires_at INTEGER,
created_by TEXT NOT NULL,
created_at INTEGER NOT NULL,
UNIQUE(principal_type, principal, permission, scope_type, scope_id)
);
CREATE INDEX IF NOT EXISTS access_grants_principal ON access_grants(principal_type, principal);
CREATE TABLE IF NOT EXISTS user_preferences (
user_id TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY(user_id, key)
);",
)?;
Ok(())
}
const LIVE: &str = "(expires_at IS NULL OR expires_at > ?2)
AND ((principal_type='user' AND principal=?3) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?4))))";
fn groups_json(groups: &[String]) -> String {
serde_json::to_string(groups).unwrap_or_else(|_| "[]".into())
}
impl Db {
/// Insert one grant; `None` when an identical grant already exists.
pub fn add_grant(&self, grant: &NewGrant<'_>, now: i64) -> Result<Option<Grant>> {
let conn = self.conn.lock().unwrap();
let id = Uuid::new_v4().to_string();
let (scope_type, scope_id) = match grant.orbit {
Some(orbit) => ("orbit", orbit),
None => ("global", ""),
};
let inserted = conn.execute(
"INSERT OR IGNORE INTO access_grants(id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
params![id, grant.principal_type, grant.principal, grant.permission, scope_type, scope_id, grant.expires_at, grant.created_by, now],
)?;
Ok((inserted == 1).then(|| Grant {
id,
principal_type: grant.principal_type.into(),
principal: grant.principal.into(),
permission: grant.permission.into(),
scope_type: scope_type.into(),
scope_id: grant.orbit.map(str::to_string),
expires_at: grant.expires_at,
created_by: grant.created_by.into(),
created_at: now,
}))
}
/// Edit or renew a set of grants in one transaction: remove `replaces` (each must belong to the same
/// principal and scope), then write `grants`, updating the end date of any that already exist.
/// Returns the removed ids and the written grants. `Err(None)`-style conflicts are reported as `Replace::Mismatch`.
pub fn replace_grants(
&self,
replaces: &[String],
grants: &[NewGrant<'_>],
now: i64,
) -> Result<Replace> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let mut removed = Vec::new();
for id in replaces {
let row: Option<(String, String, String, String)> = tx
.query_row(
"SELECT principal_type,principal,scope_type,scope_id FROM access_grants WHERE id=?1",
params![id],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)
.optional()?;
let Some((kind, who, scope_type, scope_id)) = row else {
continue;
};
let same = grants.iter().all(|g| {
g.principal_type == kind
&& g.principal == who
&& match g.orbit {
Some(orbit) => scope_type == "orbit" && scope_id == orbit,
None => scope_type == "global",
}
});
if !same {
return Ok(Replace::Mismatch);
}
tx.execute("DELETE FROM access_grants WHERE id=?1", params![id])?;
removed.push(id.clone());
}
let mut written = Vec::new();
for grant in grants {
let (scope_type, scope_id) = match grant.orbit {
Some(orbit) => ("orbit", orbit),
None => ("global", ""),
};
tx.execute(
"INSERT INTO access_grants(id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)
ON CONFLICT(principal_type,principal,permission,scope_type,scope_id) DO UPDATE SET expires_at=excluded.expires_at",
params![Uuid::new_v4().to_string(), grant.principal_type, grant.principal, grant.permission, scope_type, scope_id, grant.expires_at, grant.created_by, now],
)?;
let id: String = tx.query_row(
"SELECT id FROM access_grants WHERE principal_type=?1 AND principal=?2 AND permission=?3 AND scope_type=?4 AND scope_id=?5",
params![grant.principal_type, grant.principal, grant.permission, scope_type, scope_id],
|r| r.get(0),
)?;
written.push(Grant {
id,
principal_type: grant.principal_type.into(),
principal: grant.principal.into(),
permission: grant.permission.into(),
scope_type: scope_type.into(),
scope_id: grant.orbit.map(str::to_string),
expires_at: grant.expires_at,
created_by: grant.created_by.into(),
created_at: now,
});
}
tx.commit()?;
Ok(Replace::Done { removed, written })
}
pub fn delete_grant(&self, id: &str) -> Result<bool> {
Ok(self
.conn
.lock()
.unwrap()
.execute("DELETE FROM access_grants WHERE id=?1", params![id])?
== 1)
}
pub fn list_grants(&self) -> Result<Vec<Grant>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id,principal_type,principal,permission,scope_type,scope_id,expires_at,created_by,created_at
FROM access_grants ORDER BY principal_type, principal, scope_type, scope_id, permission",
)?;
let rows = stmt.query_map([], |r| {
let scope_type: String = r.get(4)?;
let scope_id: String = r.get(5)?;
Ok(Grant {
id: r.get(0)?,
principal_type: r.get(1)?,
principal: r.get(2)?,
permission: r.get(3)?,
scope_id: (scope_type == "orbit").then_some(scope_id),
scope_type,
expires_at: r.get(6)?,
created_by: r.get(7)?,
created_at: r.get(8)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// Does the subject hold `permission` on `orbit` (a global grant counts)?
pub fn has_permission(
&self,
user: Option<&str>,
groups: &[String],
permission: &str,
orbit: &str,
now: i64,
) -> Result<bool> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
&format!(
"SELECT EXISTS(SELECT 1 FROM access_grants WHERE permission=?1 AND {LIVE}
AND (scope_type='global' OR (scope_type='orbit' AND scope_id=?5)))"
),
params![permission, now, user, groups_json(groups), orbit],
|r| r.get(0),
)?)
}
pub fn permitted_orbits(
&self,
user: Option<&str>,
groups: &[String],
permission: &str,
now: i64,
) -> Result<Permitted> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&format!(
"SELECT scope_type, scope_id FROM access_grants WHERE permission=?1 AND {LIVE}"
))?;
let rows = stmt.query_map(params![permission, now, user, groups_json(groups)], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
})?;
let mut out = Permitted::default();
for row in rows {
let (scope, id) = row?;
if scope == "global" {
out.everywhere = true;
} else {
out.orbits.insert(id);
}
}
Ok(out)
}
/// Live grants of one subject, for `/me`.
pub fn grants_of(
&self,
user: Option<&str>,
groups: &[String],
now: i64,
) -> Result<Vec<(String, Option<String>)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT permission, scope_type, scope_id FROM access_grants WHERE (expires_at IS NULL OR expires_at > ?1)
AND ((principal_type='user' AND principal=?2) OR (principal_type='group' AND principal IN (SELECT value FROM json_each(?3))))
ORDER BY permission, scope_id")?;
let rows = stmt.query_map(params![now, user, groups_json(groups)], |r| {
let scope_type: String = r.get(1)?;
let scope_id: String = r.get(2)?;
Ok((
r.get::<_, String>(0)?,
(scope_type == "orbit").then_some(scope_id),
))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn list_users(&self) -> Result<Vec<UserRow>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id,issuer,display_name,active,created_at,last_login_at,last_groups,last_admin FROM users ORDER BY display_name, id")?;
let rows = stmt.query_map([], |r| {
let issuer: String = r.get(1)?;
let is_emergency = issuer == crate::admin::EMERGENCY_ISSUER;
Ok(UserRow {
id: r.get(0)?,
is_emergency,
issuer,
display_name: r.get(2)?,
active: r.get::<_, i64>(3)? == 1,
created_at: r.get(4)?,
last_login_at: r.get(5)?,
groups: serde_json::from_str(&r.get::<_, String>(6)?).unwrap_or_default(),
admin: is_emergency || r.get::<_, i64>(7)? == 1,
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// One user, or `None`.
pub fn user_row(&self, id: &str) -> Result<Option<UserRow>> {
Ok(self.list_users()?.into_iter().find(|u| u.id == id))
}
/// Enable or disable a user. Disabling also ends every session at once.
pub fn set_user_active(&self, id: &str, active: bool) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let changed = tx.execute(
"UPDATE users SET active=?2, generation=generation+1 WHERE id=?1",
params![id, active],
)? == 1;
if changed && !active {
tx.execute("DELETE FROM sessions WHERE user_id=?1", params![id])?;
}
tx.commit()?;
Ok(changed)
}
/// Per-account display preferences (for example the Window/Radar view).
pub fn preferences(&self, user: &str) -> Result<std::collections::BTreeMap<String, String>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT key, value FROM user_preferences WHERE user_id=?1")?;
let rows = stmt.query_map(params![user], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn set_preference(&self, user: &str, key: &str, value: &str, now: i64) -> Result<()> {
self.conn.lock().unwrap().execute(
"INSERT INTO user_preferences(user_id,key,value,updated_at) VALUES (?1,?2,?3,?4)
ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
params![user, key, value, now],
)?;
Ok(())
}
pub fn orbit_exists(&self, id: &str) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1)",
params![id],
|r| r.get(0),
)?)
}
/// The orbit an application (capture profile) belongs to.
pub fn orbit_of_application(&self, application: Uuid) -> Result<Option<Uuid>> {
let conn = self.conn.lock().unwrap();
let orbit: Option<String> = conn
.query_row(
"SELECT orbit_id FROM capture_profiles WHERE application_id=?1",
params![application.to_string()],
|r| r.get(0),
)
.optional()?;
Ok(orbit.and_then(|id| Uuid::parse_str(&id).ok()))
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn db() -> (tempfile::TempDir, Db) {
let dir = tempfile::tempdir().unwrap();
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
db.migrate().await.unwrap();
(dir, db)
}
fn grant<'a>(
kind: &'a str,
who: &'a str,
permission: &'a str,
orbit: Option<&'a str>,
expires: Option<i64>,
) -> NewGrant<'a> {
NewGrant {
principal_type: kind,
principal: who,
permission,
orbit,
expires_at: expires,
created_by: "test",
}
}
#[tokio::test]
async fn a_grant_applies_to_its_user_scope_and_permission_only() {
let (_d, db) = db().await;
db.add_grant(
&grant("user", "u1", "orbit.read", Some("orbit-a"), None),
10,
)
.unwrap()
.unwrap();
let has = |user: &str, perm: &str, orbit: &str| {
db.has_permission(Some(user), &[], perm, orbit, 20).unwrap()
};
assert!(has("u1", "orbit.read", "orbit-a"));
assert!(!has("u1", "orbit.read", "orbit-b"), "other orbit");
assert!(!has("u1", "snapshot.read", "orbit-a"), "other permission");
assert!(!has("u2", "orbit.read", "orbit-a"), "other user");
assert!(
!has("u1", "orbit.", "orbit-a") && !has("u1", "orbit", "orbit-a"),
"never by prefix"
);
assert!(
!db.has_permission(None, &[], "orbit.read", "orbit-a", 20)
.unwrap(),
"no user, no groups"
);
}
#[tokio::test]
async fn a_global_grant_covers_every_orbit_and_a_group_grant_covers_its_members() {
let (_d, db) = db().await;
db.add_grant(&grant("group", "qa", "capture.run", None, None), 10)
.unwrap()
.unwrap();
let qa = vec!["qa".to_string()];
assert!(db
.has_permission(Some("anyone"), &qa, "capture.run", "any-orbit", 11)
.unwrap());
assert!(!db
.has_permission(
Some("anyone"),
&["devs".to_string()],
"capture.run",
"any-orbit",
11
)
.unwrap());
assert!(
!db.has_permission(Some("anyone"), &[], "capture.run", "any-orbit", 11)
.unwrap(),
"claim missing = no groups"
);
let p = db
.permitted_orbits(Some("anyone"), &qa, "capture.run", 11)
.unwrap();
assert!(p.everywhere && p.orbits.is_empty());
}
#[tokio::test]
async fn expired_and_deleted_grants_stop_applying_on_the_next_check() {
let (_d, db) = db().await;
let timed = db
.add_grant(&grant("user", "u1", "orbit.read", Some("o"), Some(100)), 10)
.unwrap()
.unwrap();
assert!(db
.has_permission(Some("u1"), &[], "orbit.read", "o", 99)
.unwrap());
assert!(
!db.has_permission(Some("u1"), &[], "orbit.read", "o", 100)
.unwrap(),
"expiry is exclusive"
);
let forever = db
.add_grant(&grant("user", "u1", "snapshot.read", Some("o"), None), 10)
.unwrap()
.unwrap();
assert!(db
.has_permission(Some("u1"), &[], "snapshot.read", "o", 1_000_000)
.unwrap());
assert!(db.delete_grant(&forever.id).unwrap());
assert!(
!db.has_permission(Some("u1"), &[], "snapshot.read", "o", 11)
.unwrap(),
"revoked at once"
);
assert!(!db.delete_grant(&forever.id).unwrap());
let _ = timed;
}
#[tokio::test]
async fn duplicates_are_ignored_and_the_list_filters_by_permission() {
let (_d, db) = db().await;
assert!(db
.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 1)
.unwrap()
.is_some());
assert!(db
.add_grant(&grant("user", "u1", "orbit.read", Some("a"), None), 2)
.unwrap()
.is_none());
db.add_grant(&grant("user", "u1", "orbit.read", Some("b"), None), 1)
.unwrap();
db.add_grant(&grant("user", "u1", "capture.run", Some("c"), None), 1)
.unwrap();
let p = db
.permitted_orbits(Some("u1"), &[], "orbit.read", 5)
.unwrap();
assert!(!p.everywhere);
assert_eq!(
p.orbits,
["a".to_string(), "b".to_string()].into_iter().collect()
);
assert_eq!(db.list_grants().unwrap().len(), 3);
assert_eq!(db.grants_of(Some("u1"), &[], 5).unwrap().len(), 3);
}
#[tokio::test]
async fn disabling_a_user_ends_their_sessions_and_blocks_new_ones() {
let (_d, db) = db().await;
let user = db
.upsert_user("https://idp.example", "sub", "Sam", 1)
.unwrap();
db.create_session("s1", &user, "oidc", None, false, &[], 1)
.unwrap();
assert!(db.set_user_active(&user, false).unwrap());
assert!(db.lookup_session("s1", 2).unwrap().is_none());
assert!(!db
.create_session("s2", &user, "oidc", None, false, &[], 2)
.unwrap());
assert!(db.set_user_active(&user, true).unwrap());
assert!(db
.create_session("s3", &user, "oidc", None, false, &[], 3)
.unwrap());
assert!(!db.set_user_active("missing", false).unwrap());
}
}

View File

@@ -0,0 +1,169 @@
use super::*;
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch("CREATE TABLE IF NOT EXISTS audit_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
at INTEGER NOT NULL,
request_id TEXT NOT NULL,
actor_id TEXT NOT NULL,
actor_kind TEXT NOT NULL CHECK(actor_kind IN ('user','service','outpost','anonymous')),
auth_method TEXT NOT NULL,
action TEXT NOT NULL,
resource_type TEXT NOT NULL,
resource_id TEXT,
outcome TEXT NOT NULL CHECK(outcome IN ('allowed','denied','succeeded','failed'))
);
CREATE INDEX IF NOT EXISTS audit_events_actor_at ON audit_events(actor_id,at);
CREATE INDEX IF NOT EXISTS audit_events_resource_at ON audit_events(resource_type,resource_id,at);")?;
Ok(())
}
impl Db {
/// Test helper: the free-form audit log as (event, detail).
#[cfg(test)]
pub fn audit_log_events(&self) -> Vec<(String, String)> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn
.prepare("SELECT event, detail FROM audit_log ORDER BY rowid")
.unwrap();
stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.filter_map(Result::ok)
.collect()
}
pub fn audit_event(
&self,
actor: &Principal,
action: AuditAction,
resource: AuditResource,
outcome: AuditOutcome,
request_id: Uuid,
) -> Result<()> {
let (id, kind, method) = actor.fields();
let (resource_type, resource_id) = resource.fields();
self.conn.lock().unwrap().execute(
"INSERT INTO audit_events(at,request_id,actor_id,actor_kind,auth_method,action,resource_type,resource_id,outcome)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
params![chrono::Utc::now().timestamp(), request_id.to_string(), id, kind, method,
action.as_str(), resource_type, resource_id, outcome.as_str()],
)?;
Ok(())
}
/// Deletes structured audit events recorded before `cutoff` (unix seconds);
/// returns how many rows went.
pub fn prune_audit_events(&self, cutoff: i64) -> Result<usize> {
Ok(self
.conn
.lock()
.unwrap()
.execute("DELETE FROM audit_events WHERE at < ?1", params![cutoff])?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn pruning_removes_only_events_older_than_the_cutoff() {
let dir = tempfile::tempdir().unwrap();
let db = Db::connect(&dir.path().join("fixture.db")).await.unwrap();
db.migrate().await.unwrap();
for _ in 0..3 {
db.audit_event(
&Principal::Anonymous,
AuditAction::Authentication,
AuditResource::Api,
AuditOutcome::Denied,
Uuid::new_v4(),
)
.unwrap();
}
let now = chrono::Utc::now().timestamp();
db.conn
.lock()
.unwrap()
.execute(
"UPDATE audit_events SET at = ?1 WHERE id <= 2",
params![now - 100 * 86_400],
)
.unwrap();
assert_eq!(db.prune_audit_events(now - 90 * 86_400).unwrap(), 2);
let left: i64 = db
.conn
.lock()
.unwrap()
.query_row("SELECT count(*) FROM audit_events", [], |r| r.get(0))
.unwrap();
assert_eq!(left, 1);
}
#[tokio::test]
async fn structured_audit_survives_reopen_and_preserves_legacy_events() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("fixture.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
db.audit("legacy.fixture", "legacy audit remains")
.await
.unwrap();
let request = Uuid::new_v4();
let orbit = Uuid::new_v4();
db.audit_event(
&Principal::Emergency("devops-alice".into()),
AuditAction::OutpostBind,
AuditResource::Orbit(orbit),
AuditOutcome::Succeeded,
request,
)
.unwrap();
db.audit_event(
&Principal::Outpost(Uuid::new_v4()),
AuditAction::Authorization,
AuditResource::Outpost(Uuid::new_v4()),
AuditOutcome::Denied,
Uuid::new_v4(),
)
.unwrap();
drop(db);
let reopened = Db::connect(&path).await.unwrap();
reopened.migrate().await.unwrap();
let conn = reopened.conn.lock().unwrap();
let row: (String,String,String,String,String) = conn.query_row(
"SELECT actor_id,actor_kind,action,resource_id,request_id FROM audit_events WHERE outcome='succeeded'",
[], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?))).unwrap();
assert_eq!(
row,
(
"emergency:devops-alice".into(),
"user".into(),
"orbit.outpost_bind".into(),
orbit.to_string(),
request.to_string()
)
);
assert_eq!(
conn.query_row(
"SELECT count(*) FROM audit_log WHERE event='legacy.fixture'",
[],
|r| r.get::<_, i64>(0)
)
.unwrap(),
1
);
// The typed event accepts neither a password nor arbitrary client detail/payload.
let columns: Vec<String> = conn
.prepare("PRAGMA table_info(audit_events)")
.unwrap()
.query_map([], |r| r.get(1))
.unwrap()
.collect::<rusqlite::Result<_>>()
.unwrap();
assert!(!columns
.iter()
.any(|name| ["detail", "payload", "token", "password"].contains(&name.as_str())));
}
}

View File

@@ -0,0 +1,575 @@
//! Outpost pairing codes and upload credentials.
//!
//! Neither the pairing code nor the upload token is stored in clear: only a
//! SHA-256 digest of each. The token is generated at claim time and handed to
//! the agent exactly once. Both are high-entropy random values, so a plain
//! digest lookup is appropriate (there is nothing to brute-force offline).
use super::*;
use rand::RngCore;
use sha2::{Digest, Sha256};
pub const DEFAULT_LIFETIME_DAYS: i64 = 365;
/// Lifetime of a newly issued or migrated credential (`TESSERA_OUTPOST_TOKEN_DAYS`).
pub fn lifetime_secs() -> i64 {
std::env::var("TESSERA_OUTPOST_TOKEN_DAYS")
.ok()
.and_then(|v| v.trim().parse::<i64>().ok())
.filter(|days| (1..=3650).contains(days))
.unwrap_or(DEFAULT_LIFETIME_DAYS)
* 86_400
}
pub fn digest(kind: &str, secret: &str) -> String {
hex::encode(Sha256::digest(format!("tessera-{kind}-v1:{secret}")))
}
/// 256 random bits from the OS CSPRNG, hex encoded.
pub fn new_token() -> String {
let mut bytes = [0u8; 32];
rand::rngs::OsRng.fill_bytes(&mut bytes);
hex::encode(bytes)
}
#[derive(Debug)]
pub struct Issued {
pub token: String,
pub outpost_id: String,
pub expires_at: i64,
/// Set for a rotation: until when the previous credential still works.
pub previous_valid_until: Option<i64>,
}
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS pairing_codes (
code_digest TEXT PRIMARY KEY,
outpost_id TEXT NOT NULL,
expires_at INTEGER NOT NULL,
consumed_at INTEGER
);
CREATE TABLE IF NOT EXISTS outpost_credentials (
id TEXT PRIMARY KEY,
outpost_id TEXT NOT NULL,
token_digest TEXT NOT NULL UNIQUE,
state TEXT NOT NULL CHECK(state IN ('active','revoked')),
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
revoked_at INTEGER,
source TEXT NOT NULL DEFAULT 'pairing'
);
CREATE INDEX IF NOT EXISTS outpost_credentials_outpost ON outpost_credentials(outpost_id, state);",
)?;
let legacy: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='wormhole_tokens')",
[],
|row| row.get(0),
)?;
if legacy {
migrate_legacy(conn)?;
}
Ok(())
}
/// One-time move of `wormhole_tokens` (clear-text token and code) into digests.
///
/// * Active tokens keep working: they get a fresh lifetime from now. The old
/// `expires_at` was the *pairing code's* expiry and says nothing about the token.
/// * Unclaimed codes keep their own expiry; their pre-minted token is discarded.
/// * `secure_delete` is on for this connection while the clear text is dropped,
/// so freed pages are zeroed instead of left in the file. Old backups and
/// copies of the database still contain the tokens: rotate them.
fn migrate_legacy(conn: &Connection) -> Result<()> {
let now = chrono::Utc::now().timestamp();
let lifetime = lifetime_secs();
conn.execute_batch("PRAGMA secure_delete = ON;")?;
let result = (|| -> Result<()> {
conn.execute_batch("BEGIN IMMEDIATE")?;
let moved = (|| -> Result<(usize, usize)> {
let mut active = 0;
let mut codes = 0;
let rows: Vec<(String, String, String, String, Option<String>, String)> = {
let mut stmt = conn.prepare("SELECT token, outpost_id, code, state, outpost_name, expires_at FROM wormhole_tokens")?;
let mapped = stmt.query_map([], |r| {
Ok((
r.get(0)?,
r.get(1)?,
r.get(2)?,
r.get(3)?,
r.get(4)?,
r.get(5)?,
))
})?;
mapped.collect::<rusqlite::Result<_>>()?
};
for (token, outpost, code, state, name, expires) in rows {
if state == "active" {
conn.execute(
"INSERT OR IGNORE INTO outposts(id, name, pairing_state) VALUES (?1, ?2, 'active')",
params![outpost, name],
)?;
conn.execute(
"INSERT OR IGNORE INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'migrated')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, now + lifetime],
)?;
active += 1;
} else if state == "code_shown" {
let expires_at = chrono::DateTime::parse_from_rfc3339(&expires)
.map(|t| t.timestamp())
.unwrap_or(0);
conn.execute(
"INSERT OR IGNORE INTO pairing_codes(code_digest,outpost_id,expires_at) VALUES (?1,?2,?3)",
params![digest("pairing-code", &code), outpost, expires_at],
)?;
codes += 1;
}
}
conn.execute_batch("DROP TABLE wormhole_tokens")?;
Ok((active, codes))
})();
match moved {
Ok((active, codes)) => {
conn.execute_batch("COMMIT")?;
tracing::warn!(
"migrated {active} Outpost token(s) and {codes} pairing code(s) to digests; \
copies of the old database still hold the clear-text tokens, so rotate them"
);
Ok(())
}
Err(error) => {
let _ = conn.execute_batch("ROLLBACK");
Err(error)
}
}
})();
conn.execute_batch("PRAGMA secure_delete = OFF;")?;
result
}
impl Db {
pub fn insert_pairing(&self, outpost_id: &str, code: &str, expires_at: i64) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"DELETE FROM pairing_codes WHERE expires_at <= ?1 OR consumed_at IS NOT NULL",
params![expires_at - 86_400],
)?;
conn.execute(
"INSERT INTO pairing_codes(code_digest, outpost_id, expires_at) VALUES (?1, ?2, ?3)",
params![digest("pairing-code", code), outpost_id, expires_at],
)?;
Ok(())
}
/// Consume a pairing code and mint the upload token. The single UPDATE …
/// RETURNING is what makes a code usable once; the `Db` mutex additionally
/// serialises callers. The token exists in clear only in the return value.
pub fn claim_pairing(
&self,
code: &str,
outpost_name: &str,
now: i64,
) -> Result<Option<Issued>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let outpost: Option<String> = tx
.query_row(
"UPDATE pairing_codes SET consumed_at = ?2
WHERE code_digest = ?1 AND consumed_at IS NULL AND expires_at > ?2
RETURNING outpost_id",
params![digest("pairing-code", code), now],
|row| row.get(0),
)
.optional()?;
let Some(outpost) = outpost else {
return Ok(None);
};
let token = new_token();
let expires_at = now + lifetime_secs();
tx.execute(
"INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active')
ON CONFLICT(id) DO UPDATE SET name = excluded.name, last_seen = excluded.last_seen, pairing_state = 'active'",
params![outpost, outpost_name, chrono::Utc::now().to_rfc3339()],
)?;
tx.execute(
"INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'pairing')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, expires_at],
)?;
tx.commit()?;
Ok(Some(Issued {
token,
outpost_id: outpost,
expires_at,
previous_valid_until: None,
}))
}
/// The Outpost a presented token belongs to, if it is active and unexpired.
pub fn upload_token_outpost(&self, token: &str, now: i64) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(conn
.query_row(
"SELECT outpost_id FROM outpost_credentials
WHERE token_digest = ?1 AND state = 'active' AND expires_at > ?2",
params![digest("outpost-token", token), now],
|row| row.get(0),
)
.optional()?)
}
/// Issue a new credential for a paired Outpost. Older active credentials keep
/// working for `grace_secs` (0 = they stop immediately), so an operator has a
/// bounded window to put the new token on the agent. Returns `None` for an
/// unknown or revoked Outpost: it must be paired again.
pub fn rotate_credential(
&self,
outpost: &str,
grace_secs: i64,
now: i64,
) -> Result<Option<Issued>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let paired: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM outposts WHERE id = ?1 AND pairing_state = 'active')",
params![outpost],
|row| row.get(0),
)?;
if !paired {
return Ok(None);
}
let until = now + grace_secs.max(0);
tx.execute(
"UPDATE outpost_credentials SET expires_at = MIN(expires_at, ?3)
WHERE outpost_id = ?1 AND state = 'active' AND expires_at > ?2",
params![outpost, now, until],
)?;
let token = new_token();
let expires_at = now + lifetime_secs();
tx.execute(
"INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'rotation')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", &token), now, expires_at],
)?;
tx.commit()?;
Ok(Some(Issued {
token,
outpost_id: outpost.to_string(),
expires_at,
previous_valid_until: (grace_secs > 0).then_some(until),
}))
}
/// Revoke every credential of an Outpost, effective on its next request.
/// Returns false when the Outpost is unknown.
pub fn revoke_outpost(&self, outpost: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"UPDATE outpost_credentials SET state='revoked', revoked_at=?2 WHERE outpost_id=?1 AND state='active'",
params![outpost, now],
)?;
let known = tx.execute(
"UPDATE outposts SET pairing_state='revoked' WHERE id=?1",
params![outpost],
)? == 1;
// Anything that overwrites through, or reads from, this Outpost must stop working with it.
tx.execute(
"UPDATE orbit_relations SET active=0, deactivated_at=?2, deactivated_reason='outpost_revoked'
WHERE active=1 AND (target_id IN (SELECT id FROM restore_targets WHERE outpost_id=?1)
OR source_application_id IN (SELECT application_id FROM capture_profiles WHERE outpost_id=?1))",
params![outpost, now],
)?;
tx.commit()?;
Ok(known)
}
/// Test fixture: a paired Outpost whose token is a chosen string.
#[cfg(test)]
pub fn insert_test_credential(&self, token: &str, outpost: &str, name: &str) {
let conn = self.conn.lock().unwrap();
let now = chrono::Utc::now().timestamp();
conn.execute(
"INSERT INTO outposts(id, name, last_seen, pairing_state) VALUES (?1, ?2, ?3, 'active')
ON CONFLICT(id) DO UPDATE SET pairing_state='active'",
params![outpost, name, chrono::Utc::now().to_rfc3339()],
)
.unwrap();
conn.execute(
"INSERT INTO outpost_credentials(id,outpost_id,token_digest,state,created_at,expires_at,source)
VALUES (?1,?2,?3,'active',?4,?5,'pairing')",
params![Uuid::new_v4().to_string(), outpost, digest("outpost-token", token), now, now + lifetime_secs()],
)
.unwrap();
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn db() -> (tempfile::TempDir, Db, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("t.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
(dir, db, path)
}
/// Every byte SQLite may have left on disk for this database.
fn disk_bytes(path: &std::path::Path) -> Vec<u8> {
let mut all = Vec::new();
for suffix in ["", "-wal", "-journal", "-shm"] {
let mut name = path.as_os_str().to_owned();
name.push(suffix);
if let Ok(bytes) = std::fs::read(std::path::PathBuf::from(name)) {
all.extend(bytes);
}
}
all
}
fn contains(haystack: &[u8], needle: &str) -> bool {
haystack
.windows(needle.len())
.any(|w| w == needle.as_bytes())
}
#[tokio::test]
async fn the_code_and_token_are_never_stored_in_clear() {
let (_dir, db, path) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "ABCDEFGH2345", 10_000).unwrap();
let issued = db
.claim_pairing("ABCDEFGH2345", "agent", 100)
.unwrap()
.unwrap();
assert_eq!(issued.token.len(), 64);
assert_eq!(
db.upload_token_outpost(&issued.token, 101)
.unwrap()
.as_deref(),
Some(outpost.as_str())
);
drop(db);
let bytes = disk_bytes(&path);
assert!(
contains(&bytes, "agent"),
"sanity: the scan really reads the database file"
);
assert!(
!contains(&bytes, &issued.token),
"token in the database file"
);
assert!(
!contains(&bytes, "ABCDEFGH2345"),
"pairing code in the database file"
);
}
#[tokio::test]
async fn a_code_works_once_and_only_before_it_expires() {
let (_dir, db, _) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "CODE-ONE", 1_000).unwrap();
assert!(db.claim_pairing("WRONG", "a", 10).unwrap().is_none());
assert!(db.claim_pairing("CODE-ONE", "a", 10).unwrap().is_some());
assert!(
db.claim_pairing("CODE-ONE", "a", 11).unwrap().is_none(),
"replay"
);
db.insert_pairing(&outpost, "CODE-TWO", 1_000).unwrap();
assert!(
db.claim_pairing("CODE-TWO", "a", 1_000).unwrap().is_none(),
"expired at its deadline"
);
}
#[tokio::test]
async fn concurrent_claims_of_one_code_yield_exactly_one_token() {
// The Db mutex serialises these, so this shows the statement is atomic
// (one consumer per code), not that SQLite arbitrates a race.
let (_dir, db, _) = db().await;
db.insert_pairing(&Uuid::new_v4().to_string(), "RACE-CODE", 1_000_000)
.unwrap();
let handles: Vec<_> = (0..8)
.map(|_| {
let db = db.clone();
std::thread::spawn(move || db.claim_pairing("RACE-CODE", "a", 5).unwrap().is_some())
})
.collect();
let winners = handles
.into_iter()
.map(|h| h.join().unwrap())
.filter(|won| *won)
.count();
assert_eq!(winners, 1);
}
#[tokio::test]
async fn revoked_and_expired_tokens_are_rejected_on_the_next_lookup() {
let (_dir, db, _) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "C", 1_000).unwrap();
let issued = db.claim_pairing("C", "agent", 10).unwrap().unwrap();
assert!(db
.upload_token_outpost(&issued.token, issued.expires_at - 1)
.unwrap()
.is_some());
assert!(
db.upload_token_outpost(&issued.token, issued.expires_at)
.unwrap()
.is_none(),
"expiry"
);
assert!(db
.upload_token_outpost(&issued.token, 20)
.unwrap()
.is_some());
assert!(db.revoke_outpost(&outpost, 21).unwrap());
assert!(
db.upload_token_outpost(&issued.token, 22)
.unwrap()
.is_none(),
"revoked"
);
assert!(
db.rotate_credential(&outpost, 60, 23).unwrap().is_none(),
"a revoked Outpost must be paired again"
);
assert!(!db.revoke_outpost(&Uuid::new_v4().to_string(), 1).unwrap());
}
#[tokio::test]
async fn rotation_has_an_explicit_grace_window() {
let (_dir, db, _) = db().await;
let outpost = Uuid::new_v4().to_string();
db.insert_pairing(&outpost, "C", 1_000).unwrap();
let first = db.claim_pairing("C", "agent", 10).unwrap().unwrap();
let second = db.rotate_credential(&outpost, 300, 100).unwrap().unwrap();
assert_eq!(second.previous_valid_until, Some(400));
assert_ne!(first.token, second.token);
assert!(
db.upload_token_outpost(&first.token, 399)
.unwrap()
.is_some(),
"old token inside the grace window"
);
assert!(
db.upload_token_outpost(&first.token, 400)
.unwrap()
.is_none(),
"and not after it"
);
assert!(db
.upload_token_outpost(&second.token, 400)
.unwrap()
.is_some());
// grace 0 cuts the old token at once
let third = db.rotate_credential(&outpost, 0, 500).unwrap().unwrap();
assert_eq!(third.previous_valid_until, None);
assert!(db
.upload_token_outpost(&second.token, 500)
.unwrap()
.is_none());
assert!(db
.upload_token_outpost(&third.token, 500)
.unwrap()
.is_some());
// an unknown outpost cannot be rotated into existence
assert!(db
.rotate_credential(&Uuid::new_v4().to_string(), 0, 1)
.unwrap()
.is_none());
}
/// A pre-M4 database: clear-text tokens and codes in `wormhole_tokens`.
fn legacy_database(path: &std::path::Path) {
let conn = Connection::open(path).unwrap();
conn.execute_batch(
"CREATE TABLE outposts (id TEXT PRIMARY KEY, name TEXT, last_seen TEXT, pairing_state TEXT NOT NULL DEFAULT 'unpaired');
CREATE TABLE wormhole_tokens (token TEXT PRIMARY KEY, outpost_id TEXT NOT NULL, code TEXT NOT NULL, state TEXT NOT NULL, expires_at TEXT NOT NULL, outpost_name TEXT);",
)
.unwrap();
// paired long ago: the *code* expiry is in the past and must not become the token expiry
conn.execute("INSERT INTO wormhole_tokens VALUES ('LEGACY-ACTIVE-TOKEN-0001','11111111-1111-1111-1111-111111111111','LEGACYCODE1','active','2020-01-01T00:00:00+00:00','old-agent')", []).unwrap();
let future = (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339();
conn.execute("INSERT INTO wormhole_tokens VALUES ('PREMINTED-TOKEN-0002','22222222-2222-2222-2222-222222222222','LEGACYCODE2','code_shown',?1,NULL)", params![future]).unwrap();
conn.execute("INSERT INTO wormhole_tokens VALUES ('PREMINTED-TOKEN-0003','33333333-3333-3333-3333-333333333333','LEGACYCODE3','code_shown','2020-01-01T00:00:00+00:00',NULL)", []).unwrap();
}
#[tokio::test]
async fn legacy_clear_text_tokens_are_migrated_in_place_and_scrubbed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("legacy.db");
legacy_database(&path);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let now = chrono::Utc::now().timestamp();
// the paired agent keeps working with its existing token
assert_eq!(
db.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now)
.unwrap()
.as_deref(),
Some("11111111-1111-1111-1111-111111111111")
);
assert!(db
.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now + lifetime_secs() + 10)
.unwrap()
.is_none());
// an unclaimed code can still be claimed once, but its pre-minted token is gone
let claimed = db
.claim_pairing("LEGACYCODE2", "new-agent", now)
.unwrap()
.unwrap();
assert_ne!(claimed.token, "PREMINTED-TOKEN-0002");
assert!(db
.upload_token_outpost("PREMINTED-TOKEN-0002", now)
.unwrap()
.is_none());
assert!(
db.claim_pairing("LEGACYCODE3", "late-agent", now)
.unwrap()
.is_none(),
"expired code stays expired"
);
// the old table and every clear-text copy are gone, including freed pages
let exists: bool = db
.conn
.lock()
.unwrap()
.query_row(
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name='wormhole_tokens')",
[],
|r| r.get(0),
)
.unwrap();
assert!(!exists);
let state: String = db.conn.lock().unwrap()
.query_row("SELECT pairing_state FROM outposts WHERE id='11111111-1111-1111-1111-111111111111'", [], |r| r.get(0)).unwrap();
assert_eq!(state, "active");
drop(db);
let bytes = disk_bytes(&path);
assert!(
contains(&bytes, "old-agent") || contains(&bytes, "new-agent"),
"sanity: the scan really reads the database file"
);
for secret in [
"LEGACY-ACTIVE-TOKEN-0001",
"PREMINTED-TOKEN-0002",
"PREMINTED-TOKEN-0003",
"LEGACYCODE1",
"LEGACYCODE2",
"LEGACYCODE3",
] {
assert!(!contains(&bytes, secret), "{secret} still on disk");
}
// migrating again changes nothing
let again = Db::connect(&path).await.unwrap();
again.migrate().await.unwrap();
assert!(again
.upload_token_outpost("LEGACY-ACTIVE-TOKEN-0001", now)
.unwrap()
.is_some());
}
}

View File

@@ -0,0 +1,889 @@
use super::*;
use rusqlite::{types::Type, Row, TransactionBehavior};
use tessera_core::job::{
CaptureEvent, CaptureJob, CaptureLease, CaptureProfile, CaptureProgress, CaptureReport,
CAPTURE_LEASE_SECONDS,
};
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS capture_profiles (
application_id TEXT PRIMARY KEY,
orbit_id TEXT NOT NULL UNIQUE,
outpost_id TEXT NOT NULL,
profile TEXT NOT NULL,
registered_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS capture_jobs (
id TEXT PRIMARY KEY,
application_id TEXT NOT NULL,
actor TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
phase TEXT NOT NULL DEFAULT 'queued',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
lease_id TEXT,
lease_until INTEGER,
snapshot_id TEXT,
schedule_slot INTEGER,
offsite_status TEXT,
offsite_attempt_at INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS capture_jobs_queue
ON capture_jobs(application_id, status, created_at);
CREATE INDEX IF NOT EXISTS capture_jobs_history
ON capture_jobs(application_id, created_at);
CREATE TABLE IF NOT EXISTS capture_events (
id INTEGER PRIMARY KEY, job_id TEXT NOT NULL, at INTEGER NOT NULL, phase TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS capture_events_job ON capture_events(job_id, id);
CREATE TRIGGER IF NOT EXISTS capture_events_queued AFTER INSERT ON capture_jobs
BEGIN
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
END;
CREATE TRIGGER IF NOT EXISTS capture_events_progress AFTER UPDATE OF phase ON capture_jobs
WHEN OLD.phase <> NEW.phase OR OLD.lease_id IS NOT NEW.lease_id
BEGIN
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
DELETE FROM capture_events WHERE job_id = NEW.id AND id < COALESCE((
SELECT id FROM capture_events WHERE job_id = NEW.id ORDER BY id DESC LIMIT 1 OFFSET 63
), 0);
END;",
)?;
ensure_column(
conn,
"capture_profiles",
"registered_at",
"INTEGER NOT NULL DEFAULT 0",
)?;
ensure_column(conn, "capture_jobs", "schedule_slot", "INTEGER")?;
ensure_column(conn, "capture_jobs", "offsite_status", "TEXT")?;
ensure_column(
conn,
"capture_jobs",
"offsite_attempt_at",
"INTEGER NOT NULL DEFAULT 0",
)?;
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS capture_jobs_slot ON capture_jobs(application_id, schedule_slot)",
[],
)?;
Ok(())
}
const JOB_VIEW: &str = "SELECT j.id, p.profile, j.actor, j.status, j.phase, j.created_at,
j.updated_at, j.snapshot_id, j.offsite_status FROM capture_jobs j JOIN capture_profiles p USING(application_id)";
pub(super) fn invalid_column(
index: usize,
error: impl std::error::Error + Send + Sync + 'static,
) -> rusqlite::Error {
rusqlite::Error::FromSqlConversionFailure(index, Type::Text, Box::new(error))
}
fn parse_profile(row: &Row<'_>, index: usize) -> rusqlite::Result<CaptureProfile> {
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn read_job(row: &Row<'_>) -> rusqlite::Result<CaptureJob> {
Ok(CaptureJob {
id: Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))?,
profile: parse_profile(row, 1)?,
actor: row.get(2)?,
status: row.get(3)?,
phase: row.get(4)?,
created_at: row.get(5)?,
updated_at: row.get(6)?,
snapshot_id: row
.get::<_, Option<String>>(7)?
.map(|value| Uuid::parse_str(&value))
.transpose()
.map_err(|err| invalid_column(7, err))?,
offsite_status: row.get(8)?,
})
}
/// What an operator may change on a capture profile: `None` = leave as is, `Some(None)` = clear.
#[derive(Default)]
pub struct ProfileChange {
pub schedule: Option<Option<tessera_core::job::CaptureSchedule>>,
pub retention: Option<Option<tessera_core::decay::CaptureRetention>>,
}
impl Db {
pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"INSERT INTO capture_profiles (application_id, orbit_id, outpost_id, profile, registered_at)
SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (
SELECT 1 FROM orbits WHERE id = ?2 AND provider = 'wormhole' AND dry_run = 0
AND COALESCE(json_extract(provider_config, '$.source'), ?6) = ?6
)
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?5)
ON CONFLICT DO NOTHING",
params![profile.application_id.to_string(), profile.orbit_id.to_string(),
profile.outpost_id.to_string(), serde_json::to_string(profile)?, now,
if profile.format.engine().is_some() { "database" } else { "filesystem" }],
)?;
Ok(changed == 1)
}
/// Change the parts of a profile an operator may edit. Absent = unchanged, `Some(None)` = cleared.
///
/// A changed schedule moves the schedule cursor up to `now` (the cursor is the later of the newest
/// scheduled job and `registered_at`), so a slot that is already past under the new schedule is never
/// replayed: the first job comes from the next slot. Returns `None` when there is no such profile.
pub fn update_capture_profile(
&self,
application: Uuid,
change: ProfileChange,
now: i64,
) -> Result<Option<CaptureProfile>> {
let conn = self.conn.lock().unwrap();
let current: Option<CaptureProfile> = conn
.query_row(
"SELECT profile FROM capture_profiles WHERE application_id = ?1",
params![application.to_string()],
|row| parse_profile(row, 0),
)
.optional()?;
let Some(mut profile) = current else {
return Ok(None);
};
let schedule_changed = change.schedule.as_ref().is_some_and(|new| {
serde_json::to_string(new).ok() != serde_json::to_string(&profile.schedule).ok()
});
if let Some(schedule) = change.schedule {
profile.schedule = schedule;
}
if let Some(retention) = change.retention {
profile.retention = retention;
}
conn.execute(
"UPDATE capture_profiles SET profile = ?2,
registered_at = CASE WHEN ?4 THEN max(registered_at, ?3) ELSE registered_at END
WHERE application_id = ?1",
params![
application.to_string(),
serde_json::to_string(&profile)?,
now,
schedule_changed
],
)?;
Ok(Some(profile))
}
pub fn capture_profiles(&self) -> Result<Vec<CaptureProfile>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT profile FROM capture_profiles ORDER BY application_id")?;
let rows = stmt.query_map([], |row| parse_profile(row, 0))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT p.profile, max(COALESCE(MAX(j.schedule_slot), 0), p.registered_at)
FROM capture_profiles p LEFT JOIN capture_jobs j USING(application_id)
GROUP BY p.application_id",
)?;
let rows = stmt.query_map([], |row| Ok((parse_profile(row, 0)?, row.get(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn enqueue_scheduled_capture(&self, application: Uuid, slot: i64, now: i64) -> Result<()> {
self.conn.lock().unwrap().execute(
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at, schedule_slot)
SELECT ?1, application_id, 'scheduler', ?4, ?4, ?3 FROM capture_profiles p
WHERE application_id = ?2
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = p.outpost_id AND state = 'active' AND expires_at > ?4)
ON CONFLICT(application_id, schedule_slot) DO NOTHING",
params![Uuid::new_v4().to_string(), application.to_string(), slot, now],
)?;
Ok(())
}
pub fn enqueue_capture(
&self,
application_id: Uuid,
actor: &str,
now: i64,
) -> Result<Option<CaptureJob>> {
let conn = self.conn.lock().unwrap();
match insert_capture_job(&conn, application_id, actor, now)? {
Some(id) => capture_job(&conn, id),
None => Ok(None),
}
}
pub fn capture_jobs(
&self,
application: Option<Uuid>,
status: Option<&str>,
limit: u16,
orbits: Option<&[String]>,
) -> Result<Vec<CaptureJob>> {
let conn = self.conn.lock().unwrap();
// The orbit restriction is part of the query, before LIMIT, so a restricted
// caller still gets a full page of their own jobs.
let mut stmt = conn.prepare(&format!(
"{JOB_VIEW} WHERE (?1 IS NULL OR j.application_id = ?1) AND (?2 IS NULL OR j.status = ?2)
AND (?4 IS NULL OR j.application_id IN (
SELECT application_id FROM capture_profiles WHERE orbit_id IN (SELECT value FROM json_each(?4))))
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
))?;
let restriction = orbits.map(serde_json::to_string).transpose()?;
let rows = stmt.query_map(
params![
application.map(|id| id.to_string()),
status,
limit,
restriction
],
read_job,
)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn capture_events(&self, job: Uuid) -> Result<Vec<CaptureEvent>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT at, phase FROM capture_events WHERE job_id = ?1 ORDER BY id")?;
let rows = stmt.query_map([job.to_string()], |row| {
Ok(CaptureEvent {
at: row.get(0)?,
phase: row.get(1)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn capture_job(&self, id: Uuid) -> Result<Option<CaptureJob>> {
capture_job(&self.conn.lock().unwrap(), id)
}
pub fn capture_profile_for_orbit(&self, orbit: Uuid) -> Result<Option<CaptureProfile>> {
Ok(self
.conn
.lock()
.unwrap()
.query_row(
"SELECT profile FROM capture_profiles WHERE orbit_id = ?1",
[orbit.to_string()],
|row| parse_profile(row, 0),
)
.optional()?)
}
pub fn managed_orbit(&self, orbit_id: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM capture_profiles WHERE orbit_id = ?1)",
[orbit_id.to_string()],
|row| row.get(0),
)?)
}
pub fn pending_offsite(&self) -> Result<Vec<Uuid>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id FROM capture_jobs WHERE offsite_status IN ('pending', 'failed')
ORDER BY offsite_attempt_at, rowid LIMIT 10",
)?;
let rows = stmt.query_map([], |row| {
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn set_offsite_result(&self, job: Uuid, success: bool) -> Result<()> {
self.conn.lock().unwrap().execute(
"UPDATE capture_jobs SET offsite_status = ?2, offsite_attempt_at = ?3 WHERE id = ?1",
params![
job.to_string(),
if success { "copied" } else { "failed" },
chrono::Utc::now().timestamp()
],
)?;
Ok(())
}
pub fn offsite_pending(&self, id: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM capture_jobs WHERE snapshot_id = ?1 AND offsite_status IN ('pending', 'failed'))",
[id.to_string()], |row| row.get(0),
)?)
}
pub fn restic_required(&self, orbit: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT json_extract(provider_config, '$.source') IS NOT NULL FROM orbits WHERE id = ?1",
[orbit.to_string()], |row| row.get(0),
).optional()?.unwrap_or(false))
}
pub fn capture_upload(
&self,
outpost: Uuid,
id: Uuid,
lease: Uuid,
now: i64,
) -> Result<Option<CaptureJob>> {
capture_upload(&self.conn.lock().unwrap(), outpost, id, lease, now)
}
pub fn publish_capture(
&self,
outpost: Uuid,
id: Uuid,
lease: Uuid,
offsite_enabled: bool,
publish: impl FnOnce(&CaptureJob) -> Result<()>,
) -> Result<Option<(Uuid, bool)>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let now = chrono::Utc::now().timestamp();
let Some(job) = capture_upload(&tx, outpost, id, lease, now)? else {
return Ok(None);
};
if let Some(snapshot_id) = job.snapshot_id {
return Ok(Some((snapshot_id, false)));
}
publish(&job)?;
tx.execute(
"UPDATE capture_jobs SET status = 'completed', phase = 'completed', snapshot_id = ?1, updated_at = ?2, offsite_status = ?3
WHERE id = ?1",
params![id.to_string(), now, offsite_enabled.then_some("pending")],
)?;
tx.execute(
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.completed', ?1)",
[format!("actor={} job={id} snapshot={id}", job.actor)],
)?;
tx.commit()?;
Ok(Some((id, true)))
}
pub fn incomplete_publications(&self) -> Result<Vec<Uuid>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT id FROM capture_jobs WHERE status IN ('running', 'failed')")?;
let rows = stmt.query_map([], |row| {
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn reconcile_capture(
&self,
snapshot: Uuid,
orbit: Uuid,
offsite_enabled: bool,
) -> Result<()> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let changed = tx.execute(
"UPDATE capture_jobs SET status = 'completed', phase = 'completed',
snapshot_id = id, updated_at = ?3, offsite_status = ?4
WHERE id = ?1 AND status <> 'completed' AND application_id IN (
SELECT application_id FROM capture_profiles WHERE orbit_id = ?2
)",
params![
snapshot.to_string(),
orbit.to_string(),
chrono::Utc::now().timestamp(),
offsite_enabled.then_some("pending")
],
)?;
if changed == 1 {
tx.execute(
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.reconciled', ?1)",
[format!("snapshot={snapshot}")],
)?;
}
tx.commit()?;
Ok(())
}
pub fn claim_capture(
&self,
outpost: Uuid,
application: Uuid,
now: i64,
) -> Result<Option<CaptureLease>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let candidate = tx.query_row(
"SELECT j.id, p.profile, json_extract(o.provider_config, '$.source') IS NOT NULL
FROM capture_jobs j JOIN capture_profiles p USING(application_id) JOIN orbits o ON o.id = p.orbit_id
WHERE p.outpost_id = ?1 AND p.application_id = ?2
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
AND NOT EXISTS (SELECT 1 FROM capture_jobs active WHERE active.application_id = j.application_id
AND active.status = 'running' AND active.lease_until > ?3)
AND NOT EXISTS (SELECT 1 FROM restore_jobs r JOIN restore_targets t ON t.id = r.target_id
WHERE t.application_id = j.application_id AND
(r.status IN ('applying','recovery_required') OR (r.status = 'running' AND r.lease_until > ?3)))
ORDER BY j.created_at, j.rowid LIMIT 1",
params![outpost.to_string(), application.to_string(), now],
|row| Ok((row.get::<_, String>(0)?, parse_profile(row, 1)?, row.get::<_, bool>(2)?)),
).optional()?;
let Some((id, profile, restic)) = candidate else {
return Ok(None);
};
let job_id = Uuid::parse_str(&id)?;
let lease_id = Uuid::new_v4();
tx.execute(
"UPDATE capture_jobs SET status = 'running', phase = 'claimed',
lease_id = ?2, lease_until = ?3, updated_at = ?4 WHERE id = ?1",
params![id, lease_id.to_string(), now + CAPTURE_LEASE_SECONDS, now],
)?;
tx.commit()?;
Ok(Some(CaptureLease {
job_id,
profile,
lease_id,
restic,
}))
}
pub fn report_capture(
&self,
outpost: Uuid,
job: Uuid,
report: CaptureReport,
now: i64,
) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let (phase, prior, status) = match report.progress {
CaptureProgress::Heartbeat => (None, None, "running"),
CaptureProgress::Dumping => (Some("dumping"), Some("claimed"), "running"),
CaptureProgress::Uploading => (Some("uploading"), Some("dumping"), "running"),
CaptureProgress::DumpFailed => (Some("dump_failed"), Some("dumping"), "failed"),
CaptureProgress::UploadFailed => (Some("upload_failed"), Some("uploading"), "failed"),
};
let changed = conn.execute(
"UPDATE capture_jobs SET status = ?6, phase = COALESCE(?5, phase), updated_at = ?4, lease_until = ?7
WHERE id = ?1 AND lease_id = ?2 AND status = 'running' AND lease_until > ?4
AND (?8 IS NULL OR phase = ?8 OR phase = ?5)
AND application_id IN (SELECT application_id FROM capture_profiles WHERE outpost_id = ?3)",
params![job.to_string(), report.lease_id.to_string(), outpost.to_string(), now,
phase, status, now + CAPTURE_LEASE_SECONDS, prior],
)?;
Ok(changed == 1)
}
}
/// Queue a capture for a managed application whose Outpost is usable. Returns the job id, or
/// `None` when there is no such profile or its Outpost has no usable credential. Takes a plain
/// connection so a refresh run can queue the capture in the same transaction as the run itself.
pub(super) fn insert_capture_job(
conn: &Connection,
application_id: Uuid,
actor: &str,
now: i64,
) -> Result<Option<Uuid>> {
let id = Uuid::new_v4();
let changed = conn.execute(
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at)
SELECT ?1, application_id, ?3, ?4, ?4 FROM capture_profiles p
WHERE application_id = ?2
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = p.outpost_id AND state = 'active' AND expires_at > ?4)",
params![id.to_string(), application_id.to_string(), actor, now],
)?;
Ok((changed == 1).then_some(id))
}
fn capture_upload(
conn: &Connection,
outpost: Uuid,
id: Uuid,
lease: Uuid,
now: i64,
) -> Result<Option<CaptureJob>> {
Ok(conn.query_row(
&format!("{JOB_VIEW} WHERE j.id = ?1 AND p.outpost_id = ?2 AND j.lease_id = ?3
AND (j.status = 'completed' OR (j.status = 'running' AND j.phase = 'uploading' AND j.lease_until > ?4))"),
params![id.to_string(), outpost.to_string(), lease.to_string(), now],
read_job,
).optional()?)
}
fn capture_job(conn: &Connection, id: Uuid) -> Result<Option<CaptureJob>> {
Ok(conn
.query_row(
&format!("{JOB_VIEW} WHERE j.id = ?1"),
[id.to_string()],
read_job,
)
.optional()?)
}
#[cfg(test)]
mod tests {
use super::*;
use tessera_core::job::CaptureFormat;
async fn profile(db: &Db, outpost_id: Uuid) -> CaptureProfile {
let orbit_id = Uuid::new_v4();
db.upsert_orbit(&OrbitRow {
id: orbit_id,
name: "fixture".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
CaptureProfile {
application_id: Uuid::new_v4(),
orbit_id,
outpost_id,
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
}
}
#[tokio::test]
async fn queue_survives_restart_and_fences_competing_agents() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("old.db");
Connection::open(&path).unwrap().execute_batch(
"CREATE TABLE orbits (id TEXT PRIMARY KEY, name TEXT, provider TEXT, provider_config TEXT,
schedule TEXT, decay_preset TEXT, dry_run INTEGER, last_status TEXT);
INSERT INTO orbits VALUES ('20200000-0000-0000-0000-000000000000', 'old', 'postgres',
'{\"connection_url\":\"synthetic-secret\"}', NULL, 'week-of-dailies', 0, 'idle');"
).unwrap();
let outpost = Uuid::new_v4();
let other = Uuid::new_v4();
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let a = profile(&db, outpost).await;
let b = profile(&db, outpost).await;
let app = a.application_id;
assert!(!db.register_capture_profile(&a, 100).unwrap());
assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none());
for (id, token) in [(outpost, "token-a"), (other, "token-b")] {
db.insert_test_credential(token, &id.to_string(), "agent");
}
assert!(db.register_capture_profile(&a, 100).unwrap());
assert!(db.register_capture_profile(&b, 100).unwrap());
let queued = db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
db.enqueue_capture(b.application_id, "fixture", 100)
.unwrap()
.unwrap();
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
assert!(
db.list_orbits()
.await
.unwrap()
.iter()
.any(|orbit| orbit.name == "old"
&& orbit.provider_config.contains("synthetic-secret"))
);
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "queued");
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().actor, "fixture");
assert!(db.claim_capture(other, app, 100).unwrap().is_none());
let second = Db::connect(&path).await.unwrap();
let race = std::thread::scope(|scope| {
let first = scope.spawn(|| db.claim_capture(outpost, app, 100).unwrap());
let second = scope.spawn(|| second.claim_capture(outpost, app, 100).unwrap());
[first.join().unwrap(), second.join().unwrap()]
});
assert_eq!(race.iter().flatten().count(), 1);
let lease = race.into_iter().flatten().next().unwrap();
assert_eq!(lease.job_id, queued.id);
assert!(db
.claim_capture(outpost, b.application_id, 101)
.unwrap()
.is_some());
let report = |lease_id, progress| CaptureReport { lease_id, progress };
assert!(!db
.report_capture(
other,
queued.id,
report(lease.lease_id, CaptureProgress::Dumping),
101
)
.unwrap());
assert!(db
.report_capture(
outpost,
queued.id,
report(lease.lease_id, CaptureProgress::Dumping),
101
)
.unwrap());
drop(db);
let db = Db::connect(&path).await.unwrap();
let retry = db.claim_capture(outpost, app, 191).unwrap().unwrap();
assert_eq!(retry.job_id, queued.id);
assert_ne!(retry.lease_id, lease.lease_id);
assert!(!db
.report_capture(
outpost,
queued.id,
report(lease.lease_id, CaptureProgress::Heartbeat),
192
)
.unwrap());
assert!(db
.report_capture(
outpost,
queued.id,
report(retry.lease_id, CaptureProgress::Dumping),
192
)
.unwrap());
assert!(db
.report_capture(
outpost,
queued.id,
report(retry.lease_id, CaptureProgress::DumpFailed),
193
)
.unwrap());
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "failed");
assert!(db.claim_capture(outpost, app, 194).unwrap().is_some());
}
#[tokio::test]
async fn managed_orbit_uses_latest_job_even_after_a_success() {
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_test_credential("token", &outpost.to_string(), "agent");
let profile = profile(&db, outpost).await;
let app = profile.application_id;
let now = chrono::Utc::now().timestamp();
assert!(db.register_capture_profile(&profile, now).unwrap());
for (progress, expected) in [
(CaptureProgress::Uploading, "completed"),
(CaptureProgress::DumpFailed, "failed"),
] {
let job = db.enqueue_capture(app, "fixture", now).unwrap().unwrap();
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "queued");
let lease = db.claim_capture(outpost, app, now).unwrap().unwrap();
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running");
for progress in [CaptureProgress::Dumping, progress] {
assert!(db
.report_capture(
outpost,
job.id,
CaptureReport {
lease_id: lease.lease_id,
progress,
},
now
)
.unwrap());
}
if expected == "completed" {
assert!(db
.publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(()))
.unwrap()
.is_some());
}
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, expected);
}
}
#[tokio::test]
async fn daily_slots_are_caught_up_once_and_offline_jobs_are_visible() {
use chrono::{TimeZone, Utc};
use tessera_core::job::CaptureSchedule;
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("jobs.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_test_credential("test", &outpost.to_string(), "agent");
let mut a = profile(&db, outpost).await;
let mut b = profile(&db, outpost).await;
a.schedule = Some(CaptureSchedule {
hour: 2,
minute: 0,
timezone: "Asia/Jakarta".into(),
});
b.schedule = a.schedule.clone();
let registered = Utc.with_ymd_and_hms(2026, 11, 7, 18, 0, 0).unwrap();
for p in [&a, &b] {
assert!(db
.register_capture_profile(p, registered.timestamp())
.unwrap());
}
let tick = crate::scheduler::tick_capture_schedules;
tick(&db, registered).unwrap();
assert!(db.capture_jobs(None, None, 100, None).unwrap().is_empty());
let now = Utc.with_ymd_and_hms(2026, 11, 8, 19, 5, 0).unwrap();
tick(&db, now).unwrap();
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
tick(&db, now).unwrap();
let all = db.capture_jobs(None, Some("queued"), 100, None).unwrap();
assert_eq!(all.len(), 4);
let history = db
.capture_jobs(Some(a.application_id), Some("queued"), 100, None)
.unwrap();
assert_eq!(history.len(), 2);
assert!(history.iter().all(|job| job.actor == "scheduler"));
let first = db
.claim_capture(outpost, a.application_id, now.timestamp())
.unwrap()
.unwrap();
for (progress, offset) in [
(CaptureProgress::Dumping, 1),
(CaptureProgress::Heartbeat, 2),
(CaptureProgress::DumpFailed, 3),
] {
assert!(db
.report_capture(
outpost,
first.job_id,
CaptureReport {
lease_id: first.lease_id,
progress
},
now.timestamp() + offset
)
.unwrap());
}
let failed = db
.capture_jobs(Some(a.application_id), Some("failed"), 100, None)
.unwrap();
assert_eq!(failed.len(), 1);
let events = db.capture_events(first.job_id).unwrap();
assert_eq!(
events
.iter()
.map(|event| event.phase.as_str())
.collect::<Vec<_>>(),
["queued", "claimed", "dumping", "dump_failed"]
);
}
#[tokio::test]
async fn a_profile_changes_only_its_schedule_and_retention() {
use tessera_core::job::CaptureSchedule;
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_test_credential("token", &outpost.to_string(), "agent");
let profile = profile(&db, outpost).await;
assert!(db.register_capture_profile(&profile, 100).unwrap());
let schedule = CaptureSchedule {
hour: 3,
minute: 15,
timezone: "Asia/Jakarta".into(),
};
let changed = db
.update_capture_profile(
profile.application_id,
ProfileChange {
schedule: Some(Some(schedule.clone())),
retention: None,
},
200,
)
.unwrap()
.expect("the profile exists");
assert_eq!(
changed.schedule.as_ref().map(|s| (s.hour, s.minute)),
Some((3, 15))
);
assert_eq!(
(changed.orbit_id, changed.outpost_id),
(profile.orbit_id, profile.outpost_id)
);
assert_eq!(
db.capture_profiles().unwrap()[0]
.schedule
.as_ref()
.map(|s| s.hour),
Some(3)
);
// absent means unchanged, null means cleared
let cleared = db
.update_capture_profile(
profile.application_id,
ProfileChange {
schedule: Some(None),
retention: None,
},
300,
)
.unwrap()
.unwrap();
assert!(cleared.schedule.is_none());
assert!(db
.update_capture_profile(Uuid::new_v4(), ProfileChange::default(), 300)
.unwrap()
.is_none());
}
/// Moving a schedule must never run slots that already passed under the new one: the first job comes
/// from the next slot after the change.
#[tokio::test]
async fn changing_a_schedule_does_not_replay_slots_that_are_already_past() {
use chrono::{TimeZone, Utc};
use tessera_core::job::CaptureSchedule;
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_test_credential("token", &outpost.to_string(), "agent");
let mut profile = profile(&db, outpost).await;
profile.schedule = Some(CaptureSchedule {
hour: 2,
minute: 30,
timezone: "Asia/Jakarta".into(),
});
let registered = Utc.with_ymd_and_hms(2026, 11, 1, 0, 0, 0).unwrap();
assert!(db
.register_capture_profile(&profile, registered.timestamp())
.unwrap());
let tick = crate::scheduler::tick_capture_schedules;
// days of ordinary running: the last slot is 2026-11-14 02:30 WIB
tick(&db, Utc.with_ymd_and_hms(2026, 11, 14, 20, 0, 0).unwrap()).unwrap();
let before = db.capture_jobs(None, None, 1000, None).unwrap().len();
// at 10:00 WIB (03:00 UTC) on the 15th the operator moves the schedule to 03:00 WIB, whose slot
// for the 15th is already in the past
let change_time = Utc.with_ymd_and_hms(2026, 11, 15, 3, 0, 0).unwrap();
let moved = CaptureSchedule {
hour: 3,
minute: 0,
timezone: "Asia/Jakarta".into(),
};
db.update_capture_profile(
profile.application_id,
ProfileChange {
schedule: Some(Some(moved)),
retention: None,
},
change_time.timestamp(),
)
.unwrap()
.unwrap();
tick(&db, change_time).unwrap();
assert_eq!(
db.capture_jobs(None, None, 1000, None).unwrap().len(),
before,
"no replay of a past slot"
);
// the next 03:00 WIB (20:00 UTC on the 15th) fires once
tick(&db, Utc.with_ymd_and_hms(2026, 11, 15, 20, 0, 0).unwrap()).unwrap();
assert_eq!(
db.capture_jobs(None, None, 1000, None).unwrap().len(),
before + 1
);
}
}

View File

@@ -0,0 +1,150 @@
//! One-time OIDC login transactions (state, nonce, PKCE verifier) bound to the
//! browser that started them.
use super::*;
use crate::db::sessions::session_digest;
pub const TTL_SECS: i64 = 600;
/// `/login` is a public GET that inserts a row; bound the table.
const MAX_PENDING: i64 = 500;
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS oidc_login (
state_digest TEXT PRIMARY KEY,
browser_digest TEXT NOT NULL,
nonce TEXT NOT NULL,
pkce_verifier TEXT NOT NULL,
expires_at INTEGER NOT NULL
);",
)?;
Ok(())
}
impl Db {
/// Store a transaction. Returns false when too many are pending.
pub fn begin_oidc_login(
&self,
state: &str,
browser: &str,
nonce: &str,
verifier: &str,
now: i64,
) -> Result<bool> {
let conn = self.conn.lock().unwrap();
conn.execute(
"DELETE FROM oidc_login WHERE expires_at <= ?1",
params![now],
)?;
let pending: i64 = conn.query_row("SELECT COUNT(*) FROM oidc_login", [], |r| r.get(0))?;
if pending >= MAX_PENDING {
return Ok(false);
}
conn.execute(
"INSERT INTO oidc_login(state_digest,browser_digest,nonce,pkce_verifier,expires_at) VALUES (?1,?2,?3,?4,?5)",
params![session_digest(state), session_digest(browser), nonce, verifier, now + TTL_SECS],
)?;
Ok(true)
}
/// Atomically consume the transaction for `state`. Any attempt burns it,
/// including one from a browser that does not hold the correlation cookie,
/// so a leaked `state` cannot be retried. Returns `(nonce, verifier)` only
/// for the right browser, before expiry, exactly once.
pub fn consume_oidc_login(
&self,
state: &str,
browser: Option<&str>,
now: i64,
) -> Result<Option<(String, String)>> {
let conn = self.conn.lock().unwrap();
let row: Option<(String, String, String, i64)> = conn
.query_row(
"DELETE FROM oidc_login WHERE state_digest=?1 RETURNING browser_digest,nonce,pkce_verifier,expires_at",
params![session_digest(state)],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)
.optional()?;
Ok(row.and_then(|(bound, nonce, verifier, expires)| {
(browser.is_some_and(|b| session_digest(b) == bound) && expires > now)
.then_some((nonce, verifier))
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn db() -> (tempfile::TempDir, Db) {
let dir = tempfile::tempdir().unwrap();
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
db.migrate().await.unwrap();
(dir, db)
}
#[tokio::test]
async fn a_transaction_is_single_use_and_bound_to_its_browser() {
let (_dir, db) = db().await;
assert!(db.begin_oidc_login("s1", "b1", "n", "v", 100).unwrap());
assert_eq!(
db.consume_oidc_login("s1", Some("b1"), 101).unwrap(),
Some(("n".into(), "v".into()))
);
assert_eq!(
db.consume_oidc_login("s1", Some("b1"), 102).unwrap(),
None,
"replay"
);
db.begin_oidc_login("s2", "b2", "n", "v", 100).unwrap();
assert_eq!(
db.consume_oidc_login("s2", Some("other"), 101).unwrap(),
None,
"wrong browser"
);
assert_eq!(
db.consume_oidc_login("s2", Some("b2"), 102).unwrap(),
None,
"burned by the failed attempt"
);
db.begin_oidc_login("s3", "b3", "n", "v", 100).unwrap();
assert_eq!(
db.consume_oidc_login("s3", None, 101).unwrap(),
None,
"no cookie"
);
db.begin_oidc_login("s4", "b4", "n", "v", 100).unwrap();
assert_eq!(
db.consume_oidc_login("s4", Some("b4"), 100 + TTL_SECS)
.unwrap(),
None,
"expired"
);
}
#[tokio::test]
async fn only_digests_of_state_and_browser_are_keys_and_pending_rows_are_capped() {
let (_dir, db) = db().await;
db.begin_oidc_login("raw-state", "raw-browser", "n", "v", 1)
.unwrap();
let (state, browser): (String, String) = db
.conn
.lock()
.unwrap()
.query_row(
"SELECT state_digest,browser_digest FROM oidc_login",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert!(!state.contains("raw-state") && !browser.contains("raw-browser"));
for i in 0..MAX_PENDING {
let _ = db.begin_oidc_login(&format!("s{i}"), "b", "n", "v", 1);
}
assert!(!db
.begin_oidc_login("one-too-many", "b", "n", "v", 1)
.unwrap());
assert!(db
.begin_oidc_login("after-expiry", "b", "n", "v", 1 + TTL_SECS)
.unwrap());
}
}

View File

@@ -0,0 +1,819 @@
//! Durable refresh runs: capture a fresh dump of a source, then restore exactly that snapshot onto
//! the target of a relation.
//!
//! Every step is one transaction and can be repeated safely after a crash:
//! * the run and its capture job are created together, so there is never a run without a capture or the reverse;
//! * the restore job is queued and linked in one transaction guarded by `restore_job_id IS NULL`;
//! * a run follows its own capture job (`capture_job_id`), never "the latest snapshot", and that id is a
//! retention pin for as long as the run is active;
//! * everything that can change is checked again right before anything destructive: this module's
//! [`invalid_reason`] is also called from `authorize_apply`, in the same transaction that flips the
//! restore job to `applying`.
use super::*;
use crate::db::relations::{read_relation, unusable, Relation, RELATION_COLUMNS};
use rusqlite::{Transaction, TransactionBehavior};
use tessera_core::restore::RestoreArtifact;
/// While a run is in one of these states its target is locked and its snapshot is pinned.
pub const ACTIVE: [&str; 3] = ["capturing", "restoring", "recovery_required"];
#[derive(Clone, Debug, serde::Serialize)]
pub struct RefreshRun {
pub id: String,
pub relation_id: String,
pub relation_version: i64,
pub source_orbit_id: String,
pub source_application_id: String,
pub target_id: String,
pub requester: String,
pub requester_user_id: Option<String>,
/// `admin`, or `grant:<relation_grants.id>`. Group membership can only be verified as of the request.
pub authorized_by: String,
pub status: String,
pub blocked_reason: Option<String>,
pub capture_job_id: String,
pub snapshot_id: Option<String>,
pub restore_job_id: Option<String>,
pub created_at: i64,
pub updated_at: i64,
pub expires_at: i64,
}
const COLUMNS: &str = "id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id,authorized_by,status,blocked_reason,capture_job_id,snapshot_id,restore_job_id,created_at,updated_at,expires_at";
fn read_run(r: &rusqlite::Row<'_>) -> rusqlite::Result<RefreshRun> {
Ok(RefreshRun {
id: r.get(0)?,
relation_id: r.get(1)?,
relation_version: r.get(2)?,
source_orbit_id: r.get(3)?,
source_application_id: r.get(4)?,
target_id: r.get(5)?,
requester: r.get(6)?,
requester_user_id: r.get(7)?,
authorized_by: r.get(8)?,
status: r.get(9)?,
blocked_reason: r.get(10)?,
capture_job_id: r.get(11)?,
snapshot_id: r.get(12)?,
restore_job_id: r.get(13)?,
created_at: r.get(14)?,
updated_at: r.get(15)?,
expires_at: r.get(16)?,
})
}
#[derive(Debug, PartialEq, Eq)]
pub enum StartError {
/// No such active relation.
UnknownRelation,
/// The relation exists but cannot be used right now (target relabelled, Outpost gone, ...).
Unusable(&'static str),
/// The caller confirmed a different source, target or version than the relation has now.
StaleConfirmation,
/// The source's Outpost cannot take a capture job.
SourceUnavailable,
/// This target already has a run in progress; the id is returned so the caller can be shown it if allowed.
TargetBusy(String),
/// The same idempotency key was used for a different relation.
KeyReused,
/// Too many refreshes are running at once.
TooManyRuns,
/// The restore to undo is not one that can be undone (any more).
NothingToUndo,
}
/// What the confirmation must say: it names exactly what the person saw, including the version.
/// `capture_job_id` of a run that restores a snapshot somebody picked instead of capturing a new one.
const EXISTING: &str = "existing:";
/// Same, for a run that puts a target back from the safety copy of an earlier restore.
const UNDO: &str = "undo:";
/// Does this run take its snapshot from the request instead of from a capture of its own?
fn picked_snapshot(run: &RefreshRun) -> bool {
run.capture_job_id.starts_with(EXISTING) || run.capture_job_id.starts_with(UNDO)
}
impl RefreshRun {
/// This run put a target back from a safety copy.
pub fn is_undo(&self) -> bool {
self.capture_job_id.starts_with(UNDO)
}
}
/// The safety copy a restore took before it overwrote its target, and whether it is still the newest restore there.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UndoInfo {
pub safety: Uuid,
/// Nothing was restored onto the target after it. Undoing an older restore would also undo what came later.
pub latest: bool,
}
/// Does this run have a safety copy that puts its target back? A restore that finished, one an administrator
/// has since reconciled, and one whose apply failed (the agent says it stopped, so nothing is still writing) all
/// do: in the last case, rolling back is the recovery. An apply whose agent went silent may still be running, so
/// it waits for an administrator to reconcile it.
fn undo_info(conn: &Connection, run: &RefreshRun) -> Result<Option<UndoInfo>> {
if !matches!(
run.status.as_str(),
"completed" | "reconciled" | "recovery_required"
) {
return Ok(None);
}
let Some(job) = &run.restore_job_id else {
return Ok(None);
};
let row: Option<(String, String, Option<String>)> = conn
.query_row(
"SELECT status, phase, safety_id FROM restore_jobs WHERE id = ?1",
params![job],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let Some((status, phase, Some(safety))) = row else {
return Ok(None);
};
let sound = match status.as_str() {
"completed" | "reconciled" => true,
"recovery_required" => phase == "apply_failed",
_ => false,
};
if !sound {
return Ok(None);
}
// Jobs are numbered in the order they were queued.
let later: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE target_id = ?1
AND rowid > (SELECT rowid FROM restore_jobs WHERE id = ?2)
AND status IN ('queued','running','applying','completed','reconciled','recovery_required'))",
params![run.target_id, job],
|r| r.get(0),
)?;
Ok(Some(UndoInfo {
safety: Uuid::parse_str(&safety)?,
latest: !later,
}))
}
fn undo_check(
conn: &Connection,
run: &str,
relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
let Some(run) = get(conn, run)?.filter(|r| r.relation_id == relation) else {
return Ok(Err(UndoRefusal::NothingToUndo));
};
Ok(match undo_info(conn, &run)? {
None => Err(UndoRefusal::NothingToUndo),
Some(info) if !info.latest => Err(UndoRefusal::NotTheLatest),
Some(info) => Ok(info.safety),
})
}
/// Why a restore cannot be undone.
#[derive(Debug, PartialEq, Eq)]
pub enum UndoRefusal {
/// No such run, not of this relation, not a restore that can be put back, or it took no safety copy.
NothingToUndo,
/// Something else was restored onto the target after it. Undoing an older restore would also undo that.
NotTheLatest,
}
impl Db {
/// The safety copy that undoes `run`, if the run is a restore of this relation that can be put back and the
/// newest restore of its target. Whether the copy still exists in the vault is for the caller to check.
pub fn undo_candidate(
&self,
run: &str,
relation: &str,
) -> Result<std::result::Result<Uuid, UndoRefusal>> {
undo_check(&self.conn.lock().unwrap(), run, relation)
}
/// What can be done about each run's restore, for a whole list under one lock: only runs that took a safety
/// copy appear. See `UndoInfo`.
pub fn undo_infos(
&self,
runs: &[RefreshRun],
) -> Result<std::collections::HashMap<String, UndoInfo>> {
let conn = self.conn.lock().unwrap();
let mut infos = std::collections::HashMap::new();
for run in runs {
if let Some(info) = undo_info(&conn, run)? {
infos.insert(run.id.clone(), info);
}
}
Ok(infos)
}
/// The restore this undo puts back: the run whose restore took the safety copy that `run` restores.
pub fn undo_parent(&self, run: &RefreshRun) -> Result<Option<String>> {
let Some(safety) = run.snapshot_id.as_deref().filter(|_| run.is_undo()) else {
return Ok(None);
};
let conn = self.conn.lock().unwrap();
Ok(conn
.query_row(
"SELECT r.id FROM refresh_runs r JOIN restore_jobs j ON j.id = r.restore_job_id
WHERE j.safety_id = ?1 AND r.target_id = ?2 AND r.id <> ?3",
params![safety, run.target_id, run.id],
|r| r.get(0),
)
.optional()?)
}
pub fn relation_target(&self, relation: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(relation_of(&conn, relation)?.map(|r| r.target_id))
}
pub fn relation_source_orbit(&self, relation: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(relation_of(&conn, relation)?.map(|r| r.source_orbit_id))
}
}
pub fn confirmation_text(source: &str, target: &str, version: i64) -> String {
format!("REFRESH {source} TO {target} v{version}")
}
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS refresh_runs (
id TEXT PRIMARY KEY,
relation_id TEXT NOT NULL,
relation_version INTEGER NOT NULL,
source_orbit_id TEXT NOT NULL,
source_application_id TEXT NOT NULL,
target_id TEXT NOT NULL,
requester TEXT NOT NULL,
requester_user_id TEXT,
authorized_by TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('capturing','restoring','recovery_required','completed','capture_failed',
'restore_failed','blocked','cancelled','expired','reconciled')),
blocked_reason TEXT,
capture_job_id TEXT NOT NULL UNIQUE,
snapshot_id TEXT,
restore_job_id TEXT UNIQUE,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
UNIQUE(requester, idempotency_key)
);
CREATE UNIQUE INDEX IF NOT EXISTS refresh_runs_one_active_per_target ON refresh_runs(target_id)
WHERE status IN ('capturing','restoring','recovery_required');
CREATE INDEX IF NOT EXISTS refresh_runs_recent ON refresh_runs(created_at);",
)?;
Ok(())
}
fn get(conn: &Connection, id: &str) -> Result<Option<RefreshRun>> {
Ok(conn
.query_row(
&format!("SELECT {COLUMNS} FROM refresh_runs WHERE id=?1"),
params![id],
read_run,
)
.optional()?)
}
/// The run that owns a restore job, if the job was queued by a refresh. Admin restores have none.
pub(super) fn run_for_restore(conn: &Connection, restore_job: &str) -> Result<Option<RefreshRun>> {
Ok(conn
.query_row(
&format!("SELECT {COLUMNS} FROM refresh_runs WHERE restore_job_id=?1"),
params![restore_job],
read_run,
)
.optional()?)
}
fn relation_of(conn: &Connection, id: &str) -> Result<Option<Relation>> {
Ok(conn
.query_row(
&format!("SELECT {RELATION_COLUMNS} FROM orbit_relations WHERE id=?1"),
params![id],
read_relation,
)
.optional()?)
}
fn names(conn: &Connection, relation: &Relation) -> rusqlite::Result<(String, String)> {
let source: String = conn
.query_row(
"SELECT name FROM orbits WHERE id=?1",
params![relation.source_orbit_id],
|r| r.get(0),
)
.optional()?
.unwrap_or_default();
let target_profile: Option<String> = conn
.query_row(
"SELECT profile FROM restore_targets WHERE id=?1",
params![relation.target_id],
|r| r.get(0),
)
.optional()?;
let target = target_profile
.and_then(|p| serde_json::from_str::<serde_json::Value>(&p).ok())
.and_then(|p| p["name"].as_str().map(str::to_string))
.unwrap_or_default();
Ok((source, target))
}
/// Why this run must not go on, if anything has changed since it was started. Nothing here is cached:
/// the relation, the requester and the grant that authorised the run are read again each time.
pub(super) fn invalid_reason(
conn: &Connection,
run: &RefreshRun,
now: i64,
) -> Result<Option<&'static str>> {
let Some(relation) = relation_of(conn, &run.relation_id)? else {
return Ok(Some("relation_ended"));
};
if !relation.active {
return Ok(Some("relation_ended"));
}
if unusable(conn, &relation, now)?.is_some() {
return Ok(Some("relation_unusable"));
}
if let Some(user) = &run.requester_user_id {
let active: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM users WHERE id=?1 AND active=1)",
params![user],
|r| r.get(0),
)?;
if !active {
return Ok(Some("user_disabled"));
}
}
if let Some(grant) = run.authorized_by.strip_prefix("grant:") {
let alive: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM relation_grants WHERE id=?1 AND relation_id=?2 AND (expires_at IS NULL OR expires_at > ?3))",
params![grant, run.relation_id, now],
|r| r.get(0),
)?;
if !alive {
return Ok(Some("access_revoked"));
}
}
if now >= run.expires_at {
return Ok(Some("expired"));
}
Ok(None)
}
fn finish(
conn: &Connection,
run: &str,
status: &str,
reason: Option<&str>,
now: i64,
) -> Result<()> {
conn.execute(
"UPDATE refresh_runs SET status=?2, blocked_reason=?3, updated_at=?4 WHERE id=?1 AND status IN ('capturing','restoring','recovery_required')",
params![run, status, reason, now],
)?;
Ok(())
}
/// Stop a run that is no longer allowed to continue. A restore that has not started applying is cancelled;
/// one that has is left to finish (a half-applied restore must be finished or reconciled, not abandoned).
pub(super) fn block(conn: &Connection, run: &RefreshRun, reason: &str, now: i64) -> Result<()> {
if let Some(job) = &run.restore_job_id {
conn.execute(
"UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status IN ('queued','running')",
params![job, now],
)?;
}
finish(
conn,
&run.id,
if reason == "expired" {
"expired"
} else {
"blocked"
},
Some(reason),
now,
)
}
fn restore_status(conn: &Connection, job: &str) -> Result<Option<String>> {
Ok(conn
.query_row(
"SELECT status FROM restore_jobs WHERE id=?1",
params![job],
|r| r.get(0),
)
.optional()?)
}
impl Db {
/// Start a run. Returns the run and whether it was newly created (`false` = the same idempotency key
/// from the same requester, so the existing run is returned and nothing else happens).
#[allow(clippy::too_many_arguments)]
pub fn create_refresh_run(
&self,
relation_id: &str,
confirmation: &str,
requester: &str,
requester_user_id: Option<&str>,
authorized_by: &str,
idempotency_key: &str,
// a snapshot to restore instead of capturing one, and the run it undoes when it is the safety copy of one
snapshot: Option<(Uuid, Option<&str>)>,
ttl_secs: i64,
max_active: i64,
now: i64,
) -> Result<std::result::Result<(RefreshRun, bool), StartError>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let result = (|| -> Result<std::result::Result<(RefreshRun, bool), StartError>> {
let existing: Option<RefreshRun> = tx
.query_row(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE requester=?1 AND idempotency_key=?2"), params![requester, idempotency_key], read_run)
.optional()?;
if let Some(run) = existing {
return Ok(if run.relation_id == relation_id {
Ok((run, false))
} else {
Err(StartError::KeyReused)
});
}
let Some(relation) = relation_of(&tx, relation_id)?.filter(|r| r.active) else {
return Ok(Err(StartError::UnknownRelation));
};
if let Some(reason) = unusable(&tx, &relation, now)? {
return Ok(Err(StartError::Unusable(reason)));
}
let (source, target) = names(&tx, &relation)?;
if confirmation != confirmation_text(&source, &target, relation.version) {
return Ok(Err(StartError::StaleConfirmation));
}
let undoing = snapshot.and_then(|(_, of)| of);
// The run being undone does not count as busy: if its apply failed, undoing it is how it is recovered.
let busy: Option<String> = tx
.query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required') AND id IS NOT ?2", params![relation.target_id, undoing], |r| r.get(0))
.optional()?;
if let Some(id) = busy {
return Ok(Err(StartError::TargetBusy(id)));
}
let running: i64 = tx.query_row("SELECT COUNT(*) FROM refresh_runs WHERE status IN ('capturing','restoring','recovery_required')", [], |r| r.get(0))?;
if running >= max_active {
return Ok(Err(StartError::TooManyRuns));
}
if let Some((safety, Some(of))) = snapshot {
// Checked again inside this transaction: what was true when the request was read may not be now.
if !matches!(undo_check(&tx, of, relation_id)?, Ok(found) if found == safety) {
return Ok(Err(StartError::NothingToUndo));
}
if let Some(parent) = get(&tx, of)?.filter(|r| r.status == "recovery_required") {
// The failed apply no longer fences the target: this undo takes over from it, and puts back what
// the restore replaced. What it leaves behind is kept as this undo's own safety copy.
if let Some(job) = &parent.restore_job_id {
tx.execute(
"UPDATE restore_jobs SET status='reconciled', phase='rolled_back', updated_at=?2
WHERE id=?1 AND status='recovery_required' AND phase='apply_failed'",
params![job, now],
)?;
}
finish(&tx, &parent.id, "reconciled", None, now)?;
tx.execute(
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), 'restore.rolled_back', ?1)",
params![format!("run={} by={requester}", parent.id)],
)?;
}
}
let id = Uuid::new_v4().to_string();
// A run either takes a fresh backup first, or restores a snapshot the person picked: then it has
// no capture job, only a placeholder, and the snapshot is recorded from the start.
let capture = match snapshot {
Some((_, Some(_))) => format!("{UNDO}{id}"),
Some((_, None)) => format!("{EXISTING}{id}"),
None => {
let application = Uuid::parse_str(&relation.source_application_id)?;
let Some(capture) =
super::jobs::insert_capture_job(&tx, application, requester, now)?
else {
return Ok(Err(StartError::SourceUnavailable));
};
capture.to_string()
}
};
tx.execute(
"INSERT INTO refresh_runs(id,relation_id,relation_version,source_orbit_id,source_application_id,target_id,requester,requester_user_id,
authorized_by,idempotency_key,status,capture_job_id,snapshot_id,created_at,updated_at,expires_at)
VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'capturing',?11,?12,?13,?13,?14)",
params![id, relation.id, relation.version, relation.source_orbit_id, relation.source_application_id, relation.target_id,
requester, requester_user_id, authorized_by, idempotency_key, capture, snapshot.map(|(s, _)| s.to_string()), now, now + ttl_secs],
)?;
Ok(Ok((get(&tx, &id)?.expect("just inserted"), true)))
})()?;
if result.is_ok() {
tx.commit()?;
}
Ok(result)
}
pub fn refresh_run(&self, id: &str) -> Result<Option<RefreshRun>> {
get(&self.conn.lock().unwrap(), id)
}
/// Runs still in progress, oldest first.
pub fn active_refresh_runs(&self) -> Result<Vec<RefreshRun>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&format!("SELECT {COLUMNS} FROM refresh_runs WHERE status IN ('capturing','restoring','recovery_required') ORDER BY created_at"))?;
let rows = stmt
.query_map([], read_run)?
.collect::<rusqlite::Result<_>>()?;
Ok(rows)
}
/// Recent runs (all of them, or only those of one requester / a set of relations), newest first.
pub fn refresh_runs(
&self,
requester_user: Option<&str>,
relations: Option<&[String]>,
limit: i64,
) -> Result<Vec<RefreshRun>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(&format!(
"SELECT {COLUMNS} FROM refresh_runs WHERE (?1 IS NULL AND ?2 IS NULL) OR requester_user_id = ?1
OR relation_id IN (SELECT value FROM json_each(?2)) ORDER BY created_at DESC, rowid DESC LIMIT ?3"
))?;
let relations_json = relations.map(serde_json::to_string).transpose()?;
let rows = stmt
.query_map(params![requester_user, relations_json, limit], read_run)?
.collect::<rusqlite::Result<_>>()?;
Ok(rows)
}
/// Everything the status screens need about a run, with the capture and restore job state it follows.
pub fn refresh_progress(&self, run: &RefreshRun) -> Result<Progress> {
let conn = self.conn.lock().unwrap();
let capture: Option<(String, String, i64)> = conn
.query_row(
"SELECT status, phase, updated_at FROM capture_jobs WHERE id=?1",
params![run.capture_job_id],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.optional()?;
let restore: Option<(String, String)> = match &run.restore_job_id {
Some(job) => conn
.query_row(
"SELECT status, phase FROM restore_jobs WHERE id=?1",
params![job],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?,
None => None,
};
let relation = relation_of(&conn, &run.relation_id)?;
let (source_name, target_name) = match &relation {
Some(r) => names(&conn, r)?,
None => Default::default(),
};
Ok(Progress {
capture_status: capture.as_ref().map(|c| c.0.clone()),
capture_phase: capture.as_ref().map(|c| c.1.clone()),
snapshot_taken_at: capture.filter(|c| c.0 == "completed").map(|c| c.2),
restore_status: restore.as_ref().map(|r| r.0.clone()),
restore_phase: restore.map(|r| r.1),
source_name,
target_name,
})
}
/// Advance one run by looking at what its jobs and its authorisation say now. Idempotent.
pub fn sync_refresh_run(&self, id: &str, now: i64) -> Result<Sync> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let outcome = sync_in(&tx, id, now)?;
tx.commit()?;
Ok(outcome)
}
/// Queue the restore of the run's own snapshot. Everything is checked again inside the transaction, the
/// restore job is linked only if the run does not have one yet, and a second call changes nothing.
pub fn enqueue_refresh_restore(
&self,
id: &str,
artifact: &RestoreArtifact,
identity_clash: bool,
now: i64,
) -> Result<Linked> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let outcome = (|| -> Result<Linked> {
let Some(run) = get(&tx, id)? else {
return Ok(Linked::NotReady);
};
if run.status != "capturing" || run.restore_job_id.is_some() {
return Ok(Linked::NotReady);
}
let snapshot = if picked_snapshot(&run) {
let Some(snapshot) = run.snapshot_id.clone() else {
return Ok(Linked::NotReady);
};
snapshot
} else {
let capture: Option<(String, Option<String>)> = tx
.query_row(
"SELECT status, snapshot_id FROM capture_jobs WHERE id=?1",
params![run.capture_job_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
let Some((_, Some(snapshot))) = capture.filter(|c| c.0 == "completed") else {
return Ok(Linked::NotReady);
};
snapshot
};
if let Some(reason) = invalid_reason(&tx, &run, now)? {
block(&tx, &run, reason, now)?;
return Ok(Linked::Blocked(reason));
}
if identity_clash {
block(&tx, &run, "target_matches_a_production_source", now)?;
return Ok(Linked::Blocked("target_matches_a_production_source"));
}
let snapshot = Uuid::parse_str(&snapshot)?;
let job = super::restore::enqueue_restore_in(
&tx,
snapshot,
Uuid::parse_str(&run.source_application_id)?,
Uuid::parse_str(&run.target_id)?,
&run.requester,
artifact,
now,
)?;
let Some(job) = job else {
block(&tx, &run, "target_rejected", now)?;
return Ok(Linked::Blocked("target_rejected"));
};
let changed = tx.execute(
"UPDATE refresh_runs SET status='restoring', snapshot_id=?2, restore_job_id=?3, updated_at=?4
WHERE id=?1 AND status='capturing' AND restore_job_id IS NULL",
params![run.id, snapshot.to_string(), job.id.to_string(), now],
)?;
if changed != 1 {
return Ok(Linked::NotReady);
}
Ok(Linked::Queued(job.id.to_string()))
})()?;
tx.commit()?;
Ok(outcome)
}
/// Stop a run for a reason found outside the database (for example its snapshot cannot be restored).
pub fn block_refresh_run(&self, id: &str, reason: &str, now: i64) -> Result<()> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
if let Some(run) = get(&tx, id)? {
block(&tx, &run, reason, now)?;
}
tx.commit()?;
Ok(())
}
/// Cancel a run before anything has been applied. `Err` carries why it could not be.
pub fn cancel_refresh_run(
&self,
id: &str,
now: i64,
) -> Result<std::result::Result<RefreshRun, CancelError>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let result = (|| -> Result<std::result::Result<RefreshRun, CancelError>> {
let Some(run) = get(&tx, id)? else {
return Ok(Err(CancelError::Unknown));
};
if !ACTIVE.contains(&run.status.as_str()) || run.status == "recovery_required" {
return Ok(Err(CancelError::TooLate));
}
if let Some(job) = &run.restore_job_id {
match restore_status(&tx, job)?.as_deref() {
Some("applying") | Some("recovery_required") | Some("completed") => {
return Ok(Err(CancelError::TooLate))
}
_ => {}
}
}
if let Some(job) = &run.restore_job_id {
tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status IN ('queued','running')", params![job, now])?;
}
finish(&tx, &run.id, "cancelled", None, now)?;
Ok(Ok(get(&tx, id)?.expect("exists")))
})()?;
tx.commit()?;
Ok(result)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum CancelError {
Unknown,
TooLate,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Linked {
Queued(String),
Blocked(&'static str),
/// Nothing to do: not at that step yet, or it was already done.
NotReady,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Sync {
Unchanged,
/// The run moved to this status.
Moved(String),
/// The capture finished; the caller must now read the snapshot and call `enqueue_refresh_restore`.
NeedRestore(String),
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct Progress {
pub capture_status: Option<String>,
pub capture_phase: Option<String>,
pub snapshot_taken_at: Option<i64>,
pub restore_status: Option<String>,
pub restore_phase: Option<String>,
pub source_name: String,
pub target_name: String,
}
fn sync_in(tx: &Transaction<'_>, id: &str, now: i64) -> Result<Sync> {
let Some(run) = get(tx, id)? else {
return Ok(Sync::Unchanged);
};
if !ACTIVE.contains(&run.status.as_str()) {
return Ok(Sync::Unchanged);
}
let restore = match &run.restore_job_id {
Some(job) => restore_status(tx, job)?,
None => None,
};
// Until the restore starts applying, any change in what authorised the run stops it.
let past_the_point_of_no_return = matches!(
restore.as_deref(),
Some("applying" | "recovery_required" | "completed" | "failed" | "reconciled")
);
if !past_the_point_of_no_return {
if let Some(reason) = invalid_reason(tx, &run, now)? {
block(tx, &run, reason, now)?;
return Ok(Sync::Moved(
if reason == "expired" {
"expired"
} else {
"blocked"
}
.into(),
));
}
}
let move_to = |status: &str| -> Result<Sync> {
finish(tx, &run.id, status, None, now)?;
Ok(Sync::Moved(status.into()))
};
match run.status.as_str() {
"capturing" if picked_snapshot(&run) => {
// Nothing to capture: the snapshot was chosen when the run was started.
match (&run.snapshot_id, &run.restore_job_id) {
(Some(snapshot), None) => Ok(Sync::NeedRestore(snapshot.clone())),
_ => Ok(Sync::Unchanged),
}
}
"capturing" => {
let capture: Option<(String, Option<String>)> = tx
.query_row(
"SELECT status, snapshot_id FROM capture_jobs WHERE id=?1",
params![run.capture_job_id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
match capture {
Some((status, _)) if status == "failed" => move_to("capture_failed"),
Some((status, Some(snapshot)))
if status == "completed" && run.restore_job_id.is_none() =>
{
Ok(Sync::NeedRestore(snapshot))
}
None => move_to("capture_failed"),
_ => Ok(Sync::Unchanged),
}
}
"restoring" | "recovery_required" => match restore.as_deref() {
Some("completed") => move_to("completed"),
Some("failed") => move_to("restore_failed"),
Some("cancelled") => move_to("cancelled"),
Some("reconciled") => move_to("reconciled"),
Some("recovery_required") if run.status == "restoring" => move_to("recovery_required"),
None => move_to("restore_failed"),
_ => Ok(Sync::Unchanged),
},
_ => Ok(Sync::Unchanged),
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,676 @@
use super::{jobs::invalid_column, *};
use rusqlite::{Row, Transaction, TransactionBehavior};
use tessera_core::{
job::CAPTURE_LEASE_SECONDS,
restore::{RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreTarget},
};
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS restore_targets (
id TEXT PRIMARY KEY,
application_id TEXT NOT NULL,
outpost_id TEXT NOT NULL,
identity TEXT NOT NULL UNIQUE,
profile TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS restore_jobs (
id TEXT PRIMARY KEY,
snapshot_id TEXT NOT NULL,
target_id TEXT NOT NULL,
actor TEXT NOT NULL,
artifact TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
phase TEXT NOT NULL DEFAULT 'queued',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
lease_token TEXT,
lease_until INTEGER,
attempt_safety_id TEXT,
safety_id TEXT,
failure_reason TEXT
);
CREATE INDEX IF NOT EXISTS restore_jobs_target ON restore_jobs(target_id, status);
CREATE INDEX IF NOT EXISTS restore_jobs_snapshot ON restore_jobs(snapshot_id, safety_id, status);",
)?;
// databases created before failure reasons existed
ensure_column(conn, "restore_jobs", "failure_reason", "TEXT")?;
Ok(())
}
const VIEW: &str =
"SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at,
j.updated_at, j.artifact, j.attempt_safety_id, j.failure_reason
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
Uuid::parse_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn json<T: serde::de::DeserializeOwned>(row: &Row<'_>, index: usize) -> rusqlite::Result<T> {
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
Ok(RestoreJob {
id: uuid(row, 0)?,
snapshot_id: uuid(row, 1)?,
target: json(row, 2)?,
actor: row.get(3)?,
status: row.get(4)?,
phase: row.get(5)?,
safety_snapshot_id: row
.get::<_, Option<String>>(6)?
.map(|id| Uuid::parse_str(&id))
.transpose()
.map_err(|err| invalid_column(6, err))?,
created_at: row.get(7)?,
updated_at: row.get(8)?,
failure_reason: row.get(11)?,
})
}
pub(crate) fn restore_target_mismatch(
target: &RestoreTarget,
artifact: &RestoreArtifact,
) -> Option<&'static str> {
if Some(target.engine) != artifact.format.engine() {
Some("Database engine differs from the snapshot")
} else if target.identity == artifact.identity && !artifact.rollback {
Some("Target is the source database")
} else {
None
}
}
impl Db {
pub fn register_restore_target(&self, target: &RestoreTarget) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?6)
ON CONFLICT DO NOTHING",
params![
target.id.to_string(),
target.application_id.to_string(),
target.outpost_id.to_string(),
serde_json::to_string(&(target.engine, &target.identity))?,
serde_json::to_string(target)?,
chrono::Utc::now().timestamp(),
],
)?;
Ok(changed == 1)
}
/// Change the display name of a restore target. Its id, identity and Outpost are not touched, so
/// relations and jobs that refer to it stay valid. Returns false for an unknown target.
pub fn rename_restore_target(&self, id: Uuid, name: &str) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"UPDATE restore_targets SET profile = json_set(profile, '$.name', ?2) WHERE id = ?1",
params![id.to_string(), name],
)?;
Ok(changed == 1)
}
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
Ok(self
.restore_targets_with_activity(application)?
.into_iter()
.map(|(target, _)| target)
.collect())
}
pub fn restore_targets_with_activity(
&self,
application: Uuid,
) -> Result<Vec<(RestoreTarget, bool)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT t.profile, EXISTS (SELECT 1 FROM outpost_credentials
WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?2)
FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id",
)?;
let rows = stmt.query_map(
params![application.to_string(), chrono::Utc::now().timestamp()],
|row| Ok((json(row, 0)?, row.get(1)?)),
)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn enqueue_restore(
&self,
snapshot: Uuid,
application: Uuid,
target: Uuid,
actor: &str,
artifact: &RestoreArtifact,
now: i64,
) -> Result<Option<RestoreJob>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let job = enqueue_restore_in(&tx, snapshot, application, target, actor, artifact, now)?;
tx.commit()?;
Ok(job)
}
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
Ok(conn
.query_row(
&format!("{VIEW} WHERE j.id = ?1"),
[id.to_string()],
read_job,
)
.optional()?)
}
pub fn restore_history(&self, snapshot: Uuid, now: i64) -> Result<Vec<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
let mut stmt = conn.prepare(&format!(
"{VIEW} WHERE j.snapshot_id = ?1 ORDER BY j.rowid DESC LIMIT 25"
))?;
let rows = stmt.query_map([snapshot.to_string()], read_job)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The newest restore jobs across every snapshot, newest first, for the activity log.
pub fn restore_recent(&self, limit: u32, now: i64) -> Result<Vec<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
let mut stmt = conn.prepare(&format!("{VIEW} ORDER BY j.rowid DESC LIMIT ?1"))?;
let rows = stmt.query_map([limit], read_job)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn snapshot_in_restore(&self, id: Uuid) -> Result<bool> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1)
AND status IN ('queued','running','applying','recovery_required'))
-- a refresh run pins its own snapshot from the moment it starts: the snapshot id is its capture job id
OR EXISTS(SELECT 1 FROM refresh_runs WHERE capture_job_id = ?1
AND status IN ('capturing','restoring','recovery_required'))",
[id.to_string()], |row| row.get(0),
)?)
}
pub fn claim_restore(
&self,
outpost: Uuid,
target: Uuid,
now: i64,
) -> Result<Option<RestoreLease>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
expire_destructive(&tx, now)?;
let selected = tx.query_row(
&format!("{VIEW} WHERE t.id = ?1 AND t.outpost_id = ?2
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
AND NOT EXISTS (
SELECT 1 FROM restore_jobs active JOIN restore_targets owner ON owner.id = active.target_id
WHERE owner.application_id = t.application_id
AND (active.status IN ('applying','recovery_required')
OR (active.status = 'running' AND active.lease_until > ?3))
)
AND NOT EXISTS (
SELECT 1 FROM capture_jobs c WHERE c.application_id = t.application_id
AND c.status = 'running' AND c.lease_until > ?3
)
ORDER BY j.created_at, j.rowid LIMIT 1"),
params![target.to_string(), outpost.to_string(), now],
|row| Ok((read_job(row)?, json(row, 9)?)),
).optional()?;
let Some((mut job, artifact)) = selected else {
tx.commit()?;
return Ok(None);
};
let token = Uuid::new_v4();
tx.execute(
"UPDATE restore_jobs SET status = 'running', phase = 'claimed', lease_token = ?2, lease_until = ?3,
attempt_safety_id = ?4, safety_id = NULL, updated_at = ?5 WHERE id = ?1",
params![job.id.to_string(), token.to_string(), now + CAPTURE_LEASE_SECONDS,
Uuid::new_v4().to_string(), now],
)?;
job.status = "running".into();
job.phase = "claimed".into();
job.safety_snapshot_id = None;
job.updated_at = now;
tx.commit()?;
Ok(Some(RestoreLease {
job,
token,
artifact,
}))
}
pub fn restore_access(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
restore_access(&self.conn.lock().unwrap(), outpost, id, token, now)
}
pub fn record_safety(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
publish: impl FnOnce(Uuid) -> Result<()>,
) -> Result<Option<Uuid>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, expected)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(None);
};
if job.status != "running" {
return Ok(None);
}
if let Some(safety) = job.safety_snapshot_id {
return Ok(Some(safety));
}
if job.phase != "safety" {
return Ok(None);
}
publish(expected)?;
tx.execute("UPDATE restore_jobs SET phase = 'ready', safety_id = ?2, updated_at = ?3 WHERE id = ?1",
params![id.to_string(), expected.to_string(), now])?;
audit(
&tx,
"restore.safety_committed",
&format!("job={id} snapshot={expected}"),
)?;
tx.commit()?;
Ok(Some(expected))
}
pub fn authorize_apply(&self, outpost: Uuid, id: Uuid, token: Uuid, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(false);
};
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
return Ok(false);
}
// A refresh is only allowed to overwrite its target while what authorised it still holds. The check
// and the flip to `applying` are one transaction, and the agent applies nothing without this answer.
// Restores an administrator queued directly have no run and behave exactly as before.
if let Some(run) = super::refresh::run_for_restore(&tx, &id.to_string())? {
if let Some(reason) = super::refresh::invalid_reason(&tx, &run, now)? {
super::refresh::block(&tx, &run, reason, now)?;
tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status='running'", params![id.to_string(), now])?;
audit(
&tx,
"restore.apply_refused",
&format!("job={id} run={} reason={reason}", run.id),
)?;
tx.commit()?;
return Ok(false);
}
}
tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1",
params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
audit(
&tx,
"restore.apply_authorized",
&format!("job={id} target={}", job.target.id),
)?;
tx.commit()?;
Ok(true)
}
pub fn report_restore(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
progress: RestoreProgress,
reason: Option<&str>,
now: i64,
) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(false);
};
let (status, phase) = match progress {
RestoreProgress::Heartbeat => (job.status.as_str(), job.phase.as_str()),
RestoreProgress::Checking if job.phase == "claimed" => ("running", "checking"),
RestoreProgress::Safety if job.phase == "checking" => ("running", "safety"),
RestoreProgress::InvalidPayload if job.phase == "checking" => {
("failed", "invalid_payload")
}
RestoreProgress::WrongTarget if job.phase == "checking" => ("failed", "wrong_target"),
RestoreProgress::SafetyFailed if matches!(job.phase.as_str(), "safety" | "ready") => {
("failed", "safety_failed")
}
RestoreProgress::Applied if job.status == "applying" => ("completed", "completed"),
RestoreProgress::ApplyFailed if job.status == "applying" => {
("recovery_required", "apply_failed")
}
_ => return Ok(false),
};
tx.execute("UPDATE restore_jobs SET status = ?2, phase = ?3, updated_at = ?4, lease_until = ?5 WHERE id = ?1",
params![id.to_string(), status, phase, now, now + CAPTURE_LEASE_SECONDS])?;
if !matches!(progress, RestoreProgress::Heartbeat) {
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
}
let failed = matches!(
progress,
RestoreProgress::InvalidPayload
| RestoreProgress::WrongTarget
| RestoreProgress::SafetyFailed
| RestoreProgress::ApplyFailed
);
if let (true, Some(reason)) = (failed, reason) {
tx.execute(
"UPDATE restore_jobs SET failure_reason = ?2 WHERE id = ?1",
params![id.to_string(), reason],
)?;
audit(
&tx,
"restore.failed",
&format!("job={id} phase={phase} reason={reason}"),
)?;
}
tx.commit()?;
Ok(true)
}
pub fn reconcile_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
expire_destructive(&tx, now)?;
let changed = tx.execute(
"UPDATE restore_jobs SET status = 'reconciled', phase = 'reconciled', updated_at = ?2
WHERE id = ?1 AND status = 'recovery_required'",
params![id.to_string(), now],
)?;
if changed == 1 {
audit(
&tx,
"restore.reconciled",
&format!("actor={actor} job={id}"),
)?;
}
tx.commit()?;
Ok(changed == 1)
}
pub fn cancel_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let changed = tx.execute(
"UPDATE restore_jobs SET status = 'cancelled', phase = 'cancelled', updated_at = ?2
WHERE id = ?1 AND status IN ('queued','running')",
params![id.to_string(), now],
)?;
if changed == 1 {
audit(&tx, "restore.cancelled", &format!("actor={actor} job={id}"))?;
}
tx.commit()?;
Ok(changed == 1)
}
}
/// Queue a restore inside a transaction the caller owns, so a refresh run can link it atomically.
pub(super) fn enqueue_restore_in(
tx: &Transaction<'_>,
snapshot: Uuid,
application: Uuid,
target: Uuid,
actor: &str,
artifact: &RestoreArtifact,
now: i64,
) -> Result<Option<RestoreJob>> {
let registered: Option<RestoreTarget> = tx.query_row(
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?3)",
params![target.to_string(), application.to_string(), now],
|row| json(row, 0),
).optional()?;
let Some(registered) = registered else {
return Ok(None);
};
if restore_target_mismatch(&registered, artifact).is_some() {
return Ok(None);
}
let id = Uuid::new_v4();
tx.execute(
"INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)",
params![id.to_string(), snapshot.to_string(), target.to_string(), actor,
serde_json::to_string(artifact)?, now],
)?;
audit(
tx,
"restore.queued",
&format!("actor={actor} job={id} snapshot={snapshot} target={target}"),
)?;
let job = tx.query_row(
&format!("{VIEW} WHERE j.id = ?1"),
[id.to_string()],
read_job,
)?;
Ok(Some(job))
}
fn restore_access(
conn: &Connection,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
Ok(conn
.query_row(
&format!(
"{VIEW} WHERE j.id = ?1 AND t.outpost_id = ?2 AND j.lease_token = ?3
AND j.lease_until > ?4 AND j.status IN ('running', 'applying')"
),
params![id.to_string(), outpost.to_string(), token.to_string(), now],
|row| Ok((read_job(row)?, json(row, 9)?, uuid(row, 10)?)),
)
.optional()?)
}
fn expire_destructive(conn: &Connection, now: i64) -> Result<()> {
conn.execute(
"UPDATE restore_jobs SET status = 'recovery_required', phase = 'lease_lost', updated_at = ?1
WHERE status = 'applying' AND lease_until <= ?1",
[now],
)?;
Ok(())
}
fn audit(tx: &Transaction<'_>, event: &str, detail: &str) -> Result<()> {
tx.execute(
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), ?1, ?2)",
params![event, detail],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tessera_core::{
job::{CaptureFormat, CaptureProfile},
restore::{DatabaseIdentity, Engine},
};
#[tokio::test]
async fn expired_apply_survives_restart_and_fences_the_target_until_reconciled() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("restore.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_test_credential("synthetic-token", &outpost.to_string(), "agent");
let orbit = Uuid::new_v4();
db.upsert_orbit(&OrbitRow {
id: orbit,
name: "fixture".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
let app = Uuid::new_v4();
assert!(db
.register_capture_profile(
&CaptureProfile {
application_id: app,
orbit_id: orbit,
outpost_id: outpost,
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
},
100
)
.unwrap());
let target = Uuid::new_v4();
assert!(db
.register_restore_target(&RestoreTarget {
id: target,
application_id: app,
outpost_id: outpost,
name: "target".into(),
engine: Engine::Postgres,
identity: DatabaseIdentity {
instance: "123".into(),
database: "target".into()
},
})
.unwrap());
let snapshot = Uuid::new_v4();
let artifact = RestoreArtifact {
format: CaptureFormat::PostgresCustom,
sha256: "0".repeat(64),
rollback: false,
identity: DatabaseIdentity {
instance: "123".into(),
database: "source".into(),
},
};
let registered = db
.restore_targets_with_activity(app)
.unwrap()
.pop()
.unwrap();
assert!(registered.1);
let same_source = RestoreArtifact {
identity: registered.0.identity.clone(),
..artifact.clone()
};
assert_eq!(
restore_target_mismatch(&registered.0, &same_source),
Some("Target is the source database")
);
assert!(db
.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100)
.unwrap()
.is_none());
let job = db
.enqueue_restore(snapshot, app, target, "fixture", &artifact, 100)
.unwrap()
.unwrap();
let next_snapshot = Uuid::new_v4();
let next = db
.enqueue_restore(next_snapshot, app, target, "fixture", &artifact, 101)
.unwrap()
.unwrap();
let lease = db.claim_restore(outpost, target, 102).unwrap().unwrap();
assert_eq!(lease.job.id, job.id);
assert!(db.claim_restore(outpost, target, 103).unwrap().is_none());
assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 104)
.unwrap());
assert!(db
.report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Checking,
None,
104
)
.unwrap());
assert!(db
.report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Safety,
None,
105
)
.unwrap());
assert!(db
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
"synthetic write failure"
))
.is_err());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 107)
.unwrap());
let safety = db
.record_safety(outpost, job.id, lease.token, 108, |_| Ok(()))
.unwrap()
.unwrap();
assert!(db
.authorize_apply(outpost, job.id, lease.token, 109)
.unwrap());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 110)
.unwrap());
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let late = 109 + CAPTURE_LEASE_SECONDS;
assert!(db.claim_restore(outpost, target, late).unwrap().is_none());
assert!(db
.restore_access(outpost, job.id, lease.token, late)
.unwrap()
.is_none());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, late)
.unwrap());
let interrupted = db.restore_job(job.id, late).unwrap().unwrap();
assert_eq!(interrupted.status, "recovery_required");
let recent = db.restore_recent(10, late).unwrap();
assert_eq!(
recent.iter().map(|item| item.id).collect::<Vec<_>>(),
vec![next.id, job.id]
);
assert_eq!(db.restore_recent(1, late).unwrap().len(), 1);
assert_eq!(interrupted.safety_snapshot_id, Some(safety));
assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(db.snapshot_in_restore(safety).unwrap());
assert!(db.reconcile_restore(job.id, "fixture", late + 1).unwrap());
assert!(!db.snapshot_in_restore(snapshot).unwrap());
assert!(!db.snapshot_in_restore(safety).unwrap());
let retry = db
.claim_restore(outpost, target, late + 2)
.unwrap()
.unwrap();
assert_eq!(retry.job.id, next.id);
assert_ne!(retry.token, lease.token);
}
}

View File

@@ -0,0 +1,387 @@
//! Persistent users and browser sessions.
//!
//! Only a digest of the session ID is stored. Revocation is explicit (rows are
//! deleted in a transaction and the user's generation is bumped) because SQLite
//! foreign keys are not enabled on this connection.
use super::*;
use sha2::{Digest, Sha256};
pub const IDLE_SECS: i64 = 30 * 60;
pub const ABSOLUTE_SECS: i64 = 8 * 3600;
/// `last_seen` is only rewritten when it is this stale, to avoid a write per request.
const TOUCH_AFTER_SECS: i64 = 60;
/// Digest used as the primary key; the raw session ID never reaches the database.
pub fn session_digest(id: &str) -> String {
hex::encode(Sha256::digest(format!("tessera-session-v1:{id}")))
}
/// CSRF token derived from the session ID with a different domain prefix, so it
/// can be shown to the page without being usable as the stored digest.
pub fn csrf_token(id: &str) -> String {
hex::encode(Sha256::digest(format!("tessera-csrf-v1:{id}")))
}
pub struct StoredSession {
pub user_id: String,
pub display_name: String,
pub auth_method: String,
pub credential_fp: Option<String>,
pub admin: bool,
/// Groups verified at sign-in (JSON in the table).
pub groups: Vec<String>,
pub expires_at: i64,
}
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
issuer TEXT NOT NULL,
subject TEXT NOT NULL,
display_name TEXT NOT NULL,
active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)),
generation INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
last_login_at INTEGER,
UNIQUE(issuer, subject)
);
CREATE TABLE IF NOT EXISTS sessions (
token_digest TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
generation INTEGER NOT NULL,
auth_method TEXT NOT NULL,
credential_fp TEXT,
auth_time INTEGER NOT NULL,
created_at INTEGER NOT NULL,
last_seen INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_user ON sessions(user_id);
CREATE INDEX IF NOT EXISTS sessions_expiry ON sessions(expires_at);",
)?;
// Added after the first M2 build; default 0 keeps old rows without admin rights.
super::ensure_column(conn, "sessions", "admin", "INTEGER NOT NULL DEFAULT 0")?;
super::ensure_column(conn, "sessions", "groups", "TEXT NOT NULL DEFAULT '[]'")?;
// What the identity provider said at the user's last sign-in, kept after the session ends so the
// access screens can still say who is an administrator and which groups a person comes through.
super::ensure_column(conn, "users", "last_groups", "TEXT NOT NULL DEFAULT '[]'")?;
super::ensure_column(conn, "users", "last_admin", "INTEGER NOT NULL DEFAULT 0")?;
Ok(())
}
impl Db {
/// Find or create the user for a stable `(issuer, subject)` identity.
pub fn upsert_user(
&self,
issuer: &str,
subject: &str,
display_name: &str,
now: i64,
) -> Result<String> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO users(id,issuer,subject,display_name,created_at,last_login_at)
VALUES (?1,?2,?3,?4,?5,?5)
ON CONFLICT(issuer,subject) DO UPDATE SET display_name=excluded.display_name, last_login_at=excluded.last_login_at",
params![Uuid::new_v4().to_string(), issuer, subject, display_name, now],
)?;
Ok(conn.query_row(
"SELECT id FROM users WHERE issuer=?1 AND subject=?2",
params![issuer, subject],
|row| row.get(0),
)?)
}
/// Create a session for an active user. Returns false when the user is
/// missing or inactive. Expired rows are purged opportunistically.
#[allow(clippy::too_many_arguments)]
pub fn create_session(
&self,
id: &str,
user_id: &str,
auth_method: &str,
credential_fp: Option<&str>,
admin: bool,
groups: &[String],
now: i64,
) -> Result<bool> {
let conn = self.conn.lock().unwrap();
conn.execute(
"DELETE FROM sessions WHERE expires_at <= ?1 OR last_seen + ?2 <= ?1",
params![now, IDLE_SECS],
)?;
let inserted = conn.execute(
"INSERT INTO sessions(token_digest,user_id,generation,auth_method,credential_fp,auth_time,created_at,last_seen,expires_at,admin,groups)
SELECT ?1, id, generation, ?3, ?4, ?5, ?5, ?5, ?6, ?7, ?8 FROM users WHERE id=?2 AND active=1",
params![session_digest(id), user_id, auth_method, credential_fp, now, now + ABSOLUTE_SECS, admin, serde_json::to_string(groups)?],
)?;
if inserted == 1 {
conn.execute(
"UPDATE users SET last_groups=?2, last_admin=?3 WHERE id=?1",
params![user_id, serde_json::to_string(groups)?, admin],
)?;
}
Ok(inserted == 1)
}
/// Validate a session in one statement (user active, generation current,
/// absolute and idle deadlines), then slide the idle window. The touch is an
/// UPDATE only, so a stale write can never recreate a revoked row.
pub fn lookup_session(&self, id: &str, now: i64) -> Result<Option<StoredSession>> {
let digest = session_digest(id);
let conn = self.conn.lock().unwrap();
let found: Option<(StoredSession, i64)> = conn
.query_row(
"SELECT s.user_id,u.display_name,s.auth_method,s.credential_fp,s.expires_at,s.last_seen,s.admin,s.groups
FROM sessions s JOIN users u ON u.id=s.user_id
WHERE s.token_digest=?1 AND u.active=1 AND s.generation=u.generation
AND s.expires_at>?2 AND s.last_seen+?3>?2",
params![digest, now, IDLE_SECS],
|row| {
Ok((
StoredSession {
user_id: row.get(0)?,
display_name: row.get(1)?,
auth_method: row.get(2)?,
credential_fp: row.get(3)?,
expires_at: row.get(4)?,
admin: row.get(6)?,
groups: serde_json::from_str(&row.get::<_, String>(7)?).unwrap_or_default(),
},
row.get(5)?,
))
},
)
.optional()?;
let Some((session, last_seen)) = found else {
return Ok(None);
};
if now - last_seen >= TOUCH_AFTER_SECS {
conn.execute(
"UPDATE sessions SET last_seen=?2 WHERE token_digest=?1",
params![digest, now],
)?;
}
Ok(Some(session))
}
pub fn revoke_session(&self, id: &str) -> Result<()> {
self.conn.lock().unwrap().execute(
"DELETE FROM sessions WHERE token_digest=?1",
params![session_digest(id)],
)?;
Ok(())
}
/// Invalidate every session of a user, including any created concurrently
/// from the previous generation. Returns the number of rows removed.
pub fn revoke_user_sessions(&self, user_id: &str) -> Result<usize> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
tx.execute(
"UPDATE users SET generation=generation+1 WHERE id=?1",
params![user_id],
)?;
let removed = tx.execute("DELETE FROM sessions WHERE user_id=?1", params![user_id])?;
tx.commit()?;
Ok(removed)
}
#[cfg(test)]
pub fn expire_all_sessions(&self) {
self.conn
.lock()
.unwrap()
.execute("UPDATE sessions SET expires_at=0", [])
.unwrap();
}
#[cfg(test)]
pub fn session_rows(&self) -> i64 {
self.conn
.lock()
.unwrap()
.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))
.unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
async fn db() -> (tempfile::TempDir, Db) {
let dir = tempfile::tempdir().unwrap();
let db = Db::connect(&dir.path().join("t.db")).await.unwrap();
db.migrate().await.unwrap();
(dir, db)
}
#[tokio::test]
async fn idle_and_absolute_deadlines_use_the_supplied_clock() {
let (_dir, db) = db().await;
let user = db
.upsert_user("local:emergency", "ops", "ops", 1000)
.unwrap();
assert!(db
.create_session("a", &user, "password", Some("fp"), true, &[], 1000)
.unwrap());
assert!(db
.lookup_session("a", 1000 + IDLE_SECS - 1)
.unwrap()
.is_some());
// sliding: the touch above moved last_seen, so a request just inside the
// new idle window is still fine, one beyond it is not
assert!(db
.lookup_session("a", 1000 + 2 * IDLE_SECS - 2)
.unwrap()
.is_some());
assert!(db
.lookup_session("a", 1000 + 3 * IDLE_SECS)
.unwrap()
.is_none());
assert!(db
.create_session("b", &user, "password", None, true, &[], 5000)
.unwrap());
let mut now = 5000;
while now + IDLE_SECS - 10 < 5000 + ABSOLUTE_SECS {
now += IDLE_SECS - 10;
assert!(
db.lookup_session("b", now).unwrap().is_some(),
"active at {now}"
);
}
// keeps being used, yet the absolute deadline still ends it
assert!(db
.lookup_session("b", 5000 + ABSOLUTE_SECS)
.unwrap()
.is_none());
}
#[tokio::test]
async fn only_a_digest_is_stored_and_csrf_is_not_the_key() {
let (_dir, db) = db().await;
let user = db.upsert_user("local:emergency", "ops", "ops", 1).unwrap();
db.create_session("raw-session-id", &user, "password", None, true, &[], 1)
.unwrap();
let conn = db.conn.lock().unwrap();
let key: String = conn
.query_row("SELECT token_digest FROM sessions", [], |r| r.get(0))
.unwrap();
assert_ne!(key, "raw-session-id");
assert_eq!(key, session_digest("raw-session-id"));
assert_ne!(key, csrf_token("raw-session-id"));
let stored: String = conn
.query_row("SELECT group_concat(token_digest||user_id||auth_method||coalesce(credential_fp,'')) FROM sessions", [], |r| r.get(0))
.unwrap();
assert!(!stored.contains("raw-session-id"));
}
#[tokio::test]
async fn revoked_sessions_cannot_be_resurrected_by_a_late_touch() {
let (_dir, db) = db().await;
let user = db
.upsert_user("local:emergency", "ops", "ops", 1000)
.unwrap();
db.create_session("a", &user, "password", None, true, &[], 1000)
.unwrap();
db.revoke_session("a").unwrap();
assert!(db
.lookup_session("a", 1000 + 2 * TOUCH_AFTER_SECS)
.unwrap()
.is_none());
assert_eq!(db.session_rows(), 0);
}
#[tokio::test]
async fn per_user_revoke_ends_all_sessions_and_allows_a_new_login() {
let (_dir, db) = db().await;
let one = db
.upsert_user("https://idp.example", "alice", "Alice", 10)
.unwrap();
let two = db
.upsert_user("https://idp.example", "bob", "Bob", 10)
.unwrap();
for id in ["a1", "a2"] {
db.create_session(id, &one, "oidc", None, true, &[], 10)
.unwrap();
}
db.create_session("b1", &two, "oidc", None, true, &[], 10)
.unwrap();
assert_eq!(db.revoke_user_sessions(&one).unwrap(), 2);
assert!(db.lookup_session("a1", 11).unwrap().is_none());
assert!(db.lookup_session("a2", 11).unwrap().is_none());
assert!(db.lookup_session("b1", 11).unwrap().is_some());
assert!(db
.create_session("a3", &one, "oidc", None, true, &[], 12)
.unwrap());
assert!(db.lookup_session("a3", 13).unwrap().is_some());
}
#[tokio::test]
async fn inactive_users_have_no_valid_or_new_sessions() {
let (_dir, db) = db().await;
let user = db
.upsert_user("https://idp.example", "carol", "Carol", 10)
.unwrap();
db.create_session("c1", &user, "oidc", None, true, &[], 10)
.unwrap();
db.conn
.lock()
.unwrap()
.execute("UPDATE users SET active=0 WHERE id=?1", params![user])
.unwrap();
assert!(db.lookup_session("c1", 11).unwrap().is_none());
assert!(!db
.create_session("c2", &user, "oidc", None, true, &[], 11)
.unwrap());
assert!(!db
.create_session("c3", "no-such-user", "oidc", None, true, &[], 11)
.unwrap());
}
#[tokio::test]
async fn issuer_and_subject_identify_the_user_not_the_display_name() {
let (_dir, db) = db().await;
let first = db
.upsert_user("https://idp.example", "sub-1", "Sam", 1)
.unwrap();
let again = db
.upsert_user("https://idp.example", "sub-1", "Samuel", 2)
.unwrap();
let other_subject = db
.upsert_user("https://idp.example", "sub-2", "Sam", 3)
.unwrap();
let other_issuer = db
.upsert_user("https://other.example", "sub-1", "Sam", 4)
.unwrap();
assert_eq!(first, again);
assert_ne!(first, other_subject);
assert_ne!(first, other_issuer);
}
#[tokio::test]
async fn sessions_survive_reopening_the_database_but_expired_ones_do_not() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("t.db");
{
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let user = db
.upsert_user("local:emergency", "ops", "ops", 1000)
.unwrap();
db.create_session("live", &user, "password", Some("fp"), true, &[], 1000)
.unwrap();
db.create_session("old", &user, "password", Some("fp"), true, &[], 1000)
.unwrap();
}
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
assert!(db.lookup_session("live", 1000 + 60).unwrap().is_some());
assert!(db
.lookup_session("old", 1000 + ABSOLUTE_SECS + 1)
.unwrap()
.is_none());
}
}

View File

@@ -0,0 +1,678 @@
//! Snapshot downloads: what the file is, how it is compressed, and the limits around producing it.
//!
//! The export is first written to a private directory by the vault, then streamed to the client,
//! compressed on the fly when it is not already a compressed format. The decision uses both the
//! manifest hints and the first bytes of the real file; the bytes win, because hints are written by
//! many producers and one of them (a legacy Restic commit) writes none.
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::db::Db;
use axum::body::Bytes;
use futures_core::Stream;
use std::io;
use std::pin::Pin;
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
use std::task::{Context, Poll};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use uuid::Uuid;
pub const EXPORT_PREFIX: &str = "tessera-export-";
const DEFAULT_CONCURRENCY: usize = 2;
const DEFAULT_MARGIN: u64 = 512 * 1024 * 1024;
/// Reduce free text to `[a-z0-9_-]`: anything else becomes `_`, runs collapse, and the ends are trimmed.
fn slug(text: &str, limit: usize) -> String {
let mut out = String::new();
for c in text.chars() {
let c = if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c.to_ascii_lowercase()
} else {
'_'
};
if c == '_' && out.ends_with('_') {
continue;
}
out.push(c);
}
let out = out.trim_matches(['_', '-']);
out.chars()
.take(limit)
.collect::<String>()
.trim_matches(['_', '-'])
.to_string()
}
/// A readable file name for a download: `<application>_<time>_<engine>_<id8>.<extension>`.
///
/// The application is the orbit name reduced to `[a-z0-9_-]`; the time is when the backup was taken in the
/// profile's schedule zone (UTC with `Z` when there is none); the first eight characters of the snapshot id
/// keep two backups from the same minute apart. Nothing from the orbit name can reach the header unfiltered.
pub fn download_name(
orbit: &str,
taken_at: chrono::DateTime<chrono::Utc>,
zone: Option<&str>,
engine: Option<&str>,
id: Uuid,
extension: &str,
) -> String {
let when = match zone.and_then(|zone| zone.parse::<chrono_tz::Tz>().ok()) {
Some(tz) => taken_at
.with_timezone(&tz)
.format("%Y-%m-%dT%H%M%z")
.to_string(),
None => taken_at.format("%Y-%m-%dT%H%MZ").to_string(),
};
let application = match slug(orbit, 48) {
name if name.is_empty() => "snapshot".to_string(),
name => name,
};
let mut name = format!("{application}_{when}");
if let Some(engine) = engine
.map(|engine| slug(engine, 16))
.filter(|engine| !engine.is_empty())
{
name.push('_');
name.push_str(&engine);
}
let short: String = id.simple().to_string().chars().take(8).collect();
format!("{name}_{short}.{extension}")
}
/// `Content-Disposition` with both the plain `filename` and the RFC 5987 `filename*` forms.
pub fn content_disposition(name: &str) -> String {
let plain: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || "-._+".contains(c) {
c
} else {
'_'
}
})
.collect();
let mut encoded = String::new();
for byte in name.bytes() {
if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) {
encoded.push(byte as char);
} else {
encoded.push_str(&format!("%{byte:02X}"));
}
}
format!("attachment; filename=\"{plain}\"; filename*=UTF-8''{encoded}")
}
/// How a snapshot is delivered.
#[derive(Debug, PartialEq, Eq)]
pub struct Plan {
/// File extension of the download, without the dot.
pub extension: &'static str,
/// Compress with gzip while streaming. Formats that are already compressed pass through unchanged.
pub compress: bool,
pub content_type: &'static str,
}
fn plan_of(extension: &'static str, compress: bool) -> Plan {
let gz = extension.ends_with("gz");
Plan {
extension,
compress,
content_type: if gz || compress {
"application/gzip"
} else {
"application/octet-stream"
},
}
}
/// Decide the delivery from the manifest `restore_hints` and the first bytes of the exported file.
pub fn plan(hints: &serde_json::Value, head: &[u8]) -> Plan {
let format = hints.get("format").and_then(|f| f.as_str()).unwrap_or("");
let starts = |magic: &[u8]| head.starts_with(magic);
// Already compressed or a self-compressing dump: send the bytes untouched.
if starts(&[0x1f, 0x8b]) {
let ext = match format {
"tar" => "tar.gz",
"plain" | "sql_gzip" => "sql.gz",
_ => "gz",
};
return plan_of(ext, false);
}
if starts(b"PGDMP") {
return plan_of("dump", false); // pg_dump -Fc compresses its own data
}
if starts(&[0x28, 0xb5, 0x2f, 0xfd]) {
return plan_of("zst", false);
}
if starts(&[0xfd, b'7', b'z', b'X', b'Z', 0x00]) {
return plan_of("xz", false);
}
if starts(b"BZh") {
return plan_of("bz2", false);
}
if starts(b"PK\x03\x04") {
return plan_of("zip", false);
}
// Compressible content.
if starts(b"SQLite format 3\0") || format == "sqlite" {
return plan_of("sqlite.gz", true);
}
if head.len() > 262 && &head[257..262] == b"ustar" || format == "tar" {
return plan_of("tar.gz", true);
}
match format {
"plain" | "sql" => plan_of("sql.gz", true),
"tessera-fs-v1" => plan_of("tessera-fs.gz", true),
_ => plan_of("dump.gz", true),
}
}
/// Limits on how many exports run at once and how much disk one may need.
pub struct ExportGate {
permits: Arc<Semaphore>,
/// Free space that must remain after the export has been written.
min_free: u64,
/// Bytes promised to exports that are admitted and not finished yet. Free space alone cannot say
/// that, because an export that has only just started has barely written anything.
reserved: Arc<AtomicU64>,
}
/// The most one export may reserve: 64 of them (the concurrency ceiling) still fit in a `u64`.
const MAX_RESERVATION: u64 = 1 << 57;
/// An admitted export: its place among the running ones and the disk it was promised. Both are given
/// back when this is dropped.
pub struct Admission {
_permit: OwnedSemaphorePermit,
reserved: Arc<AtomicU64>,
size: u64,
}
impl Drop for Admission {
fn drop(&mut self) {
self.reserved.fetch_sub(self.size, Ordering::SeqCst);
}
}
pub enum Refused {
/// Too many exports are already running.
Busy,
/// Not enough free disk for this snapshot.
NoSpace,
}
impl ExportGate {
pub fn new(concurrency: usize, min_free: u64) -> Self {
Self {
permits: Arc::new(Semaphore::new(concurrency)),
min_free,
reserved: Arc::default(),
}
}
pub fn from_env() -> Self {
let number = |name: &str| {
std::env::var(name)
.ok()
.and_then(|v| v.trim().parse::<u64>().ok())
};
Self::new(
number("TESSERA_EXPORT_CONCURRENCY")
.map_or(DEFAULT_CONCURRENCY, |n| n.clamp(1, 64) as usize),
number("TESSERA_EXPORT_MIN_FREE_BYTES").unwrap_or(DEFAULT_MARGIN),
)
}
/// Admit one export of about `size` bytes into `dir`. The slot and the bytes are held for as long as the
/// response body, so exports admitted together cannot each count on the same free space.
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<Admission, Refused> {
let permit = self
.permits
.clone()
.try_acquire_owned()
.map_err(|_| Refused::Busy)?;
// No disk is that large, and the cap keeps the running total from overflowing.
let size = size.min(MAX_RESERVATION);
// Reserve first, then check: concurrent callers can only over-refuse, never over-admit.
let earlier = self.reserved.fetch_add(size, Ordering::SeqCst);
let admission = Admission {
_permit: permit,
reserved: self.reserved.clone(),
size,
};
match free_bytes(dir) {
// `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies.
// Bytes already written by running exports are no longer free and are counted again in `earlier`; being
// that cautious is deliberate.
Some(free) if free < earlier.saturating_add(size).saturating_add(self.min_free) => {
Err(Refused::NoSpace)
}
_ => Ok(admission),
}
}
}
#[cfg(unix)]
fn free_bytes(dir: &std::path::Path) -> Option<u64> {
let stat = rustix::fs::statvfs(dir).ok()?;
Some(stat.f_bavail.saturating_mul(stat.f_frsize))
}
#[cfg(not(unix))]
fn free_bytes(_dir: &std::path::Path) -> Option<u64> {
None
}
/// Remove export directories a crash left behind. Only directories with our own prefix, only directly
/// inside `data_dir`; run before the listener starts. Older `.tmp*` leftovers are deliberately not touched.
pub fn sweep_stale(data_dir: &std::path::Path) -> usize {
let Ok(entries) = std::fs::read_dir(data_dir) else {
return 0;
};
let mut removed = 0;
for entry in entries.flatten() {
let name = entry.file_name();
let is_ours = name.to_str().is_some_and(|n| n.starts_with(EXPORT_PREFIX));
let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
if is_ours && is_dir && std::fs::remove_dir_all(entry.path()).is_ok() {
removed += 1;
}
}
removed
}
/// Owns everything an in-flight download needs and reports how it ended. Dropping it (the stream ended,
/// the client went away, or the response was discarded) releases the permit and deletes the export.
pub struct Guarded<S> {
inner: Pin<Box<S>>,
_permit: Admission,
_dir: tempfile::TempDir,
db: Db,
principal: Principal,
snapshot: Uuid,
request: Uuid,
completed: bool,
failed: bool,
}
impl<S> Guarded<S> {
pub fn new(
inner: S,
permit: Admission,
dir: tempfile::TempDir,
db: Db,
principal: Principal,
snapshot: Uuid,
request: Uuid,
) -> Self {
Self {
inner: Box::pin(inner),
_permit: permit,
_dir: dir,
db,
principal,
snapshot,
request,
completed: false,
failed: false,
}
}
}
impl<S: Stream<Item = io::Result<Bytes>>> Stream for Guarded<S> {
type Item = io::Result<Bytes>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let polled = self.inner.as_mut().poll_next(cx);
match &polled {
Poll::Ready(None) => self.completed = true,
Poll::Ready(Some(Err(_))) => self.failed = true,
_ => {}
}
polled
}
}
impl<S> Drop for Guarded<S> {
fn drop(&mut self) {
// "Finished" means the body was handed to the connection, not that a file reached a disk.
let (action, outcome) = if self.completed && !self.failed {
(AuditAction::ExportFinished, AuditOutcome::Succeeded)
} else {
(AuditAction::ExportDisconnected, AuditOutcome::Failed)
};
if let Err(error) = self.db.audit_event(
&self.principal,
action,
AuditResource::Snapshot(self.snapshot),
outcome,
self.request,
) {
tracing::error!("could not audit the end of an export: {error:#}");
}
}
}
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
fn taken() -> chrono::DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 11, 14, 19, 30, 5).unwrap()
}
fn id() -> Uuid {
Uuid::parse_str("a1b2c3d4-0000-4000-8000-000000000000").unwrap()
}
#[test]
fn a_download_is_named_after_the_application_the_time_and_the_engine() {
let name = download_name(
"app",
taken(),
Some("Europe/Berlin"),
Some("postgres"),
id(),
"dump",
);
assert_eq!(name, "app_2026-11-14T2030+0100_postgres_a1b2c3d4.dump");
let name = download_name("ledger", taken(), None, Some("mysql"), id(), "sql.gz");
assert_eq!(name, "ledger_2026-11-14T1930Z_mysql_a1b2c3d4.sql.gz");
// no engine (a folder snapshot): the part is left out
assert_eq!(
download_name("docs", taken(), None, None, id(), "tar.gz"),
"docs_2026-11-14T1930Z_a1b2c3d4.tar.gz"
);
}
#[test]
fn an_unknown_time_zone_falls_back_to_utc() {
let name = download_name(
"app",
taken(),
Some("Mars/Olympus"),
Some("postgres"),
id(),
"dump",
);
assert!(name.contains("_2026-11-14T1930Z_"), "{name}");
}
#[test]
fn two_snapshots_in_the_same_minute_get_different_names() {
let other = Uuid::parse_str("ffffffff-0000-4000-8000-000000000000").unwrap();
let a = download_name("app", taken(), None, Some("postgres"), id(), "dump");
let b = download_name("app", taken(), None, Some("postgres"), other, "dump");
assert_ne!(a, b);
}
#[test]
fn hostile_orbit_names_cannot_escape_the_file_name_or_the_header() {
for orbit in [
"../../etc/passwd",
"a\"b\r\nSet-Cookie: x=1",
"name; filename=evil.exe",
"Ünïcode データ",
"\u{202e}gnp.exe",
" ",
"",
&"x".repeat(500),
] {
let name = download_name(orbit, taken(), None, Some("postgres"), id(), "dump");
assert!(
name.bytes().all(|b| b.is_ascii_lowercase()
|| b.is_ascii_digit()
|| b"_-.+TZ".contains(&b)),
"{name:?}"
);
assert!(!name.contains(".."), "{name:?}");
assert!(name.len() <= 100, "{name:?}");
let header = content_disposition(&name);
let value = axum::http::HeaderValue::from_str(&header).expect("a valid header value");
// the only `=` signs are the two the header itself writes: nothing from the name adds a parameter
assert_eq!(header.matches("filename=").count(), 1, "{header}");
assert_eq!(header.matches("filename*=").count(), 1, "{header}");
assert_eq!(header.matches(';').count(), 2, "{header}");
assert_eq!(value.to_str().unwrap(), header);
assert!(!header.contains(['\r', '\n']));
}
let name = download_name("", taken(), None, None, id(), "dump");
assert!(name.starts_with("snapshot_"), "{name}");
}
#[test]
fn the_header_carries_both_filename_forms() {
let header = content_disposition("app_2026-11-14T2030+0100_postgres_a1b2c3d4.dump");
assert_eq!(
header,
"attachment; filename=\"app_2026-11-14T2030+0100_postgres_a1b2c3d4.dump\"; \
filename*=UTF-8''app_2026-11-14T2030%2B0100_postgres_a1b2c3d4.dump"
);
}
use super::*;
use serde_json::json;
fn ustar() -> Vec<u8> {
let mut block = vec![0u8; 512];
block[257..262].copy_from_slice(b"ustar");
block
}
#[test]
fn every_producer_of_a_snapshot_gets_the_right_delivery() {
let gz = [0x1f, 0x8b, 8, 0];
let cases: Vec<(&str, serde_json::Value, Vec<u8>, &str, bool)> = vec![
(
"hub database orbit, postgres plain SQL",
json!({"engine": "postgres", "format": "plain"}),
b"-- PostgreSQL dump\n".to_vec(),
"sql.gz",
true,
),
(
"hub database orbit, mysql plain SQL",
json!({"engine": "mysql", "format": "plain"}),
b"-- MySQL dump\n".to_vec(),
"sql.gz",
true,
),
(
"agent capture, postgres custom",
json!({"engine": "postgres", "format": "custom", "sha256": "x"}),
b"PGDMP\x01\x0e\x00".to_vec(),
"dump",
false,
),
(
"hub postgres provider, custom",
json!({"format": "custom", "restore_command_hint": "pg_restore"}),
b"PGDMP\x01".to_vec(),
"dump",
false,
),
(
"restic filesystem, tar by hint",
json!({"format": "tar"}),
ustar(),
"tar.gz",
true,
),
(
"restic filesystem snapshot with no hint but a tar payload",
serde_json::Value::Null,
ustar(),
"tar.gz",
true,
),
(
"hub filesystem orbit archive",
json!({"paths": [], "format": "tessera-fs-v1"}),
b"a/b\0\x03\0\0\0\0\0\0\0xyz".to_vec(),
"tessera-fs.gz",
true,
),
(
"sqlite database",
json!({"format": "sqlite"}),
b"SQLite format 3\0....".to_vec(),
"sqlite.gz",
true,
),
(
"SQL that is already gzip",
json!({"format": "sql_gzip"}),
gz.to_vec(),
"sql.gz",
false,
),
(
"hint says plain SQL but the file is gzip: no double compression",
json!({"format": "plain"}),
gz.to_vec(),
"sql.gz",
false,
),
(
"a tar that is already gzip",
json!({"format": "tar"}),
gz.to_vec(),
"tar.gz",
false,
),
(
"zstd payload",
serde_json::Value::Null,
vec![0x28, 0xb5, 0x2f, 0xfd, 0],
"zst",
false,
),
(
"legacy wormhole commit with no hints",
serde_json::Value::Null,
b"opaque payload".to_vec(),
"dump.gz",
true,
),
(
"demo seed",
json!({"demo": true}),
b"demo".to_vec(),
"dump.gz",
true,
),
];
for (name, hints, head, extension, compress) in cases {
let got = plan(&hints, &head);
assert_eq!(
(got.extension, got.compress),
(extension, compress),
"{name}"
);
let ct = if extension.ends_with("gz") {
"application/gzip"
} else {
"application/octet-stream"
};
assert_eq!(got.content_type, ct, "{name}");
}
}
#[test]
fn sweeping_removes_only_our_own_export_directories() {
let dir = tempfile::tempdir().unwrap();
let make = |name: &str| std::fs::create_dir(dir.path().join(name)).unwrap();
make("tessera-export-aaaa");
make("tessera-export-bbbb");
make("vault");
make(".tmpXYZ");
std::fs::write(
dir.path().join("tessera-export-file"),
b"a file, not a directory",
)
.unwrap();
std::fs::create_dir_all(dir.path().join("vault/tessera-export-nested")).unwrap();
assert_eq!(sweep_stale(dir.path()), 2);
for kept in [
"vault",
".tmpXYZ",
"tessera-export-file",
"vault/tessera-export-nested",
] {
assert!(dir.path().join(kept).exists(), "{kept} must survive");
}
assert!(!dir.path().join("tessera-export-aaaa").exists());
}
#[test]
fn admission_is_bounded_by_concurrency_and_by_free_disk() {
let dir = tempfile::tempdir().unwrap();
let gate = ExportGate::new(1, 0);
let held = gate
.admit(dir.path(), 1)
.ok()
.expect("first export is admitted");
assert!(
matches!(gate.admit(dir.path(), 1), Err(Refused::Busy)),
"second export is refused at once"
);
drop(held);
assert!(
gate.admit(dir.path(), 1).is_ok(),
"the permit comes back when the first ends"
);
let greedy = ExportGate::new(4, u64::MAX / 2);
assert!(matches!(
greedy.admit(dir.path(), 10),
Err(Refused::NoSpace)
));
assert!(
matches!(
ExportGate::new(4, 0).admit(dir.path(), u64::MAX),
Err(Refused::NoSpace)
),
"a snapshot bigger than the disk"
);
}
#[test]
fn concurrent_exports_cannot_each_count_on_the_same_free_space() {
let dir = tempfile::tempdir().unwrap();
let free = free_bytes(dir.path()).expect("statvfs works on the temp dir");
// each export needs a bit over a third of what is free, so two fit on paper but not together
// (the disk may move under us a little, which is why the margin is generous)
let size = free / 3 + free / 20;
let gate = ExportGate::new(8, 0);
let first = gate.admit(dir.path(), size).ok().expect("one fits");
let second = gate.admit(dir.path(), size).ok().expect("two fit");
assert!(
matches!(gate.admit(dir.path(), size), Err(Refused::NoSpace)),
"the third would need more than the disk has once the first two are counted"
);
drop(first);
assert!(
gate.admit(dir.path(), size).is_ok(),
"a finished export gives its bytes back"
);
drop(second);
}
#[test]
fn a_refused_export_leaves_nothing_reserved() {
let dir = tempfile::tempdir().unwrap();
let gate = ExportGate::new(2, 0);
for _ in 0..3 {
assert!(matches!(
gate.admit(dir.path(), u64::MAX),
Err(Refused::NoSpace)
));
}
assert_eq!(gate.reserved.load(Ordering::SeqCst), 0);
let busy = ExportGate::new(1, 0);
let held = busy.admit(dir.path(), 5).ok().unwrap();
assert!(matches!(busy.admit(dir.path(), 7), Err(Refused::Busy)));
assert_eq!(busy.reserved.load(Ordering::SeqCst), 5);
drop(held);
assert_eq!(busy.reserved.load(Ordering::SeqCst), 0);
}
}

View File

@@ -0,0 +1,278 @@
//! Request limiting for the unauthenticated and expensive endpoints.
//!
//! Limits are per *source*, so one noisy client cannot use up the budget of
//! the others. The source is the TCP peer. `X-Forwarded-For` is honoured only
//! when the peer is a configured trusted proxy (`TESSERA_TRUSTED_PROXIES`),
//! walking the header right to left past trusted hops. IPv6 sources are keyed by
//! their /64. State is in memory and per hub process: it resets on restart and
//! is not shared between replicas.
use axum::http::HeaderMap;
use governor::{
clock::DefaultClock, state::keyed::DefaultKeyedStateStore, state::InMemoryState,
state::NotKeyed, Quota, RateLimiter,
};
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::num::NonZeroU32;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::Semaphore;
type Keyed = RateLimiter<IpAddr, DefaultKeyedStateStore<IpAddr>, DefaultClock>;
type Direct = RateLimiter<NotKeyed, InMemoryState, DefaultClock>;
pub struct LimitConfig {
pub login_source: Quota,
/// Ceiling for the single emergency account across all sources. Deliberately
/// looser than the per-source quota: a tight account lock would let anyone
/// lock the break-glass operator out.
pub login_account: Quota,
pub claim_source: Quota,
pub claim_global: Quota,
pub oidc_login_source: Quota,
pub oidc_callback_source: Quota,
pub argon2_concurrency: usize,
}
fn per_minute(rate: u32, burst: u32) -> Quota {
Quota::per_minute(NonZeroU32::new(rate).unwrap()).allow_burst(NonZeroU32::new(burst).unwrap())
}
impl Default for LimitConfig {
fn default() -> Self {
Self {
login_source: per_minute(10, 5),
login_account: per_minute(60, 30),
claim_source: per_minute(10, 5),
claim_global: per_minute(120, 60),
oidc_login_source: per_minute(30, 15),
oidc_callback_source: per_minute(60, 30),
argon2_concurrency: 2,
}
}
}
pub struct Limits {
login_source: Keyed,
login_account: Direct,
claim_source: Keyed,
claim_global: Direct,
oidc_login_source: Keyed,
oidc_callback_source: Keyed,
audit_denial: Keyed,
admin_token_failure: Keyed,
pub argon2: Arc<Semaphore>,
trusted_proxies: Vec<IpAddr>,
calls: AtomicU64,
}
impl Limits {
pub fn new(config: LimitConfig, trusted_proxies: Vec<IpAddr>) -> Self {
Self {
login_source: RateLimiter::keyed(config.login_source),
login_account: RateLimiter::direct(config.login_account),
claim_source: RateLimiter::keyed(config.claim_source),
claim_global: RateLimiter::direct(config.claim_global),
oidc_login_source: RateLimiter::keyed(config.oidc_login_source),
oidc_callback_source: RateLimiter::keyed(config.oidc_callback_source),
// one audit row per source per minute, so a flood cannot fill the audit table
audit_denial: RateLimiter::keyed(per_minute(1, 1)),
admin_token_failure: RateLimiter::keyed(per_minute(10, 5)),
argon2: Arc::new(Semaphore::new(config.argon2_concurrency)),
trusted_proxies,
calls: AtomicU64::new(0),
}
}
pub fn from_env() -> anyhow::Result<Self> {
let mut proxies = Vec::new();
if let Ok(list) = std::env::var("TESSERA_TRUSTED_PROXIES") {
for item in list.split(',').map(str::trim).filter(|s| !s.is_empty()) {
proxies.push(
item.parse::<IpAddr>().map_err(|_| {
anyhow::anyhow!("TESSERA_TRUSTED_PROXIES: invalid IP {item}")
})?,
);
}
}
Ok(Self::new(LimitConfig::default(), proxies))
}
/// The rate-limit key for a request. `None` peer (should not happen) maps to
/// one strict shared bucket instead of bypassing limits.
pub fn source(&self, peer: Option<SocketAddr>, headers: &HeaderMap) -> IpAddr {
let Some(peer) = peer else {
return IpAddr::V6(Ipv6Addr::UNSPECIFIED);
};
let mut client = peer.ip();
if self.trusted_proxies.contains(&client) {
let forwarded: Vec<&str> = headers
.get_all("x-forwarded-for")
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|line| line.split(','))
.map(str::trim)
.collect();
for hop in forwarded.iter().rev() {
match hop.parse::<IpAddr>() {
Ok(ip) if self.trusted_proxies.contains(&ip) => continue,
Ok(ip) => {
client = ip;
break;
}
Err(_) => break, // malformed: stay on the proxy's own address
}
}
}
normalize(client)
}
fn maintain(&self) {
if self.calls.fetch_add(1, Ordering::Relaxed) % 512 == 511 {
self.login_source.retain_recent();
self.claim_source.retain_recent();
self.oidc_login_source.retain_recent();
self.oidc_callback_source.retain_recent();
self.audit_denial.retain_recent();
self.admin_token_failure.retain_recent();
}
}
pub fn login_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.login_source.check_key(&source).is_ok() && self.login_account.check().is_ok()
}
pub fn claim_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.claim_source.check_key(&source).is_ok() && self.claim_global.check().is_ok()
}
pub fn oidc_login_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.oidc_login_source.check_key(&source).is_ok()
}
pub fn oidc_callback_allowed(&self, source: IpAddr) -> bool {
self.maintain();
self.oidc_callback_source.check_key(&source).is_ok()
}
/// Counts one wrong admin token from `source`; false once that source has used up its budget.
pub fn admin_token_failure(&self, source: IpAddr) -> bool {
self.maintain();
self.admin_token_failure.check_key(&source).is_ok()
}
/// True at most once a minute per source: use it to decide whether a denial is audited.
pub fn audit_denial(&self, source: IpAddr) -> bool {
self.audit_denial.check_key(&source).is_ok()
}
}
/// IPv4-mapped IPv6 becomes IPv4; other IPv6 addresses collapse to their /64.
fn normalize(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V4(_) => ip,
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => IpAddr::V4(v4),
None => {
let mut octets = v6.octets();
octets[8..].fill(0);
IpAddr::V6(Ipv6Addr::from(octets))
}
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
fn peer(ip: &str) -> Option<SocketAddr> {
Some(SocketAddr::new(ip.parse().unwrap(), 4000))
}
fn headers(xff: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert("x-forwarded-for", HeaderValue::from_str(xff).unwrap());
h
}
fn limits(proxies: &[&str]) -> Limits {
Limits::new(
LimitConfig::default(),
proxies.iter().map(|p| p.parse().unwrap()).collect(),
)
}
#[test]
fn one_source_cannot_use_up_another_sources_login_budget() {
let l = limits(&[]);
let a = l.source(peer("203.0.113.1"), &HeaderMap::new());
let b = l.source(peer("203.0.113.2"), &HeaderMap::new());
let mut allowed = 0;
for _ in 0..50 {
allowed += l.login_allowed(a) as u32;
}
assert_eq!(allowed, 5, "burst of 5, then refused");
assert!(l.login_allowed(b), "an unrelated source is unaffected");
}
#[test]
fn forwarded_for_is_ignored_unless_the_peer_is_a_trusted_proxy() {
let l = limits(&["10.0.0.1"]);
let spoof = headers("198.51.100.9");
assert_eq!(
l.source(peer("203.0.113.7"), &spoof),
"203.0.113.7".parse::<IpAddr>().unwrap(),
"untrusted peer cannot choose its key"
);
assert_eq!(
l.source(peer("10.0.0.1"), &spoof),
"198.51.100.9".parse::<IpAddr>().unwrap()
);
// client-supplied prefix is ignored: walk right to left, skipping trusted hops
let chain = headers("1.1.1.1, 198.51.100.9, 10.0.0.1");
assert_eq!(
l.source(peer("10.0.0.1"), &chain),
"198.51.100.9".parse::<IpAddr>().unwrap()
);
// junk or missing header falls back to the proxy itself
assert_eq!(
l.source(peer("10.0.0.1"), &headers("not-an-ip")),
"10.0.0.1".parse::<IpAddr>().unwrap()
);
assert_eq!(
l.source(peer("10.0.0.1"), &HeaderMap::new()),
"10.0.0.1".parse::<IpAddr>().unwrap()
);
}
#[test]
fn ipv6_sources_share_a_budget_per_64_and_mapped_v4_is_v4() {
let l = limits(&[]);
let a = l.source(peer("2001:db8:1:2::1"), &HeaderMap::new());
let b = l.source(peer("2001:db8:1:2:ffff::9"), &HeaderMap::new());
let c = l.source(peer("2001:db8:1:3::1"), &HeaderMap::new());
assert_eq!(a, b);
assert_ne!(a, c);
assert_eq!(
l.source(peer("::ffff:192.0.2.5"), &HeaderMap::new()),
"192.0.2.5".parse::<IpAddr>().unwrap()
);
assert_eq!(
l.source(None, &HeaderMap::new()),
IpAddr::V6(Ipv6Addr::UNSPECIFIED)
);
}
#[test]
fn denials_are_audited_at_most_once_a_minute_per_source() {
let l = limits(&[]);
let a: IpAddr = "203.0.113.1".parse().unwrap();
assert!(l.audit_denial(a));
assert!(!l.audit_denial(a));
assert!(l.audit_denial("203.0.113.2".parse().unwrap()));
}
}

View File

@@ -1,7 +1,15 @@
mod admin;
mod api;
mod auth;
mod db;
mod exports;
mod limits;
mod mtls;
mod oidc;
mod refresh;
mod scheduler;
mod state;
mod upload;
use anyhow::Result;
use state::HubState;
@@ -10,15 +18,45 @@ use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> Result<()> {
if std::env::args().nth(1).as_deref() == Some("--hash-operator-password") {
return admin::print_operator_hash();
}
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env().add_directive("tessera_hub=info".parse()?))
.init();
let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into());
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "0.0.0.0:8787".into());
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE").unwrap_or_else(|_| "dev-vault-key".into());
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "127.0.0.1:8787".into());
let addr: SocketAddr = listen.parse()?;
let admin = admin::AdminGate::from_env()?;
admin.validate_listener(addr)?;
let audit_retention = scheduler::audit_retention_from_env()?;
let wormhole = mtls::from_env()?;
if let Some(config) = &wormhole {
admin.validate_listener(config.listen)?;
}
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE")
.ok()
.filter(|value| !value.is_empty())
.ok_or_else(|| {
anyhow::anyhow!(
"TESSERA_VAULT_PASSPHRASE is required and must be non-empty. Tessera does not ship a default passphrase."
)
})?;
if vault_pass == "dev-vault-key" {
tracing::warn!(
"TESSERA_VAULT_PASSPHRASE is the old published example. New vaults refuse it; set a private passphrase."
);
}
let state = HubState::bootstrap(&data_dir, &vault_pass).await?;
let mut state = HubState::bootstrap(&data_dir, &vault_pass).await?;
// Exports a crash left half-written; nothing is serving yet, so nothing can be using them.
let swept = exports::sweep_stale(std::path::Path::new(&data_dir));
if swept > 0 {
tracing::info!("removed {swept} unfinished snapshot export(s) from a previous run");
}
anyhow::ensure!(state.sessions.enabled() || state.admin.token_active() || state.admin.local_development,
"configure a named emergency operator and/or TESSERA_ADMIN_TOKEN; anonymous local access requires explicit TESSERA_LOCAL_DEVELOPMENT=true");
if std::env::var("TESSERA_SEED_DEMO")
.map(|v| v == "1" || v == "true")
@@ -26,8 +64,9 @@ async fn main() -> Result<()> {
{
match tessera_demo::apply(std::path::Path::new(&data_dir), &vault_pass, false) {
Ok(r) if !r.skipped => {
tracing::info!(
"demo seed: {} orbits, {} snapshots",
tracing::warn!(
"TESSERA_SEED_DEMO wrote demo backup history into {}: {} orbits, {} snapshots",
data_dir,
r.orbits,
r.snapshots
);
@@ -40,12 +79,40 @@ async fn main() -> Result<()> {
}
}
state.configure_offsite()?;
state.reconcile_capture_catalog().await?;
state.start_offsite_worker();
scheduler::start_audit_retention(state.db.clone(), audit_retention);
scheduler::start_orbit_scheduler(state.clone()).await?;
refresh::start(state.clone());
if state.sessions.enabled() {
tracing::info!("operator sessions enabled; CLI access uses a separate admin token");
} else {
state.admin.log_policy();
}
if let Some(wormhole) = wormhole {
state.wormhole_mtls = true;
state.accept_plain_upload = false;
let mut tls_state = state.clone();
tls_state.accept_plain_upload = true;
let listen_addr = wormhole.listen;
let tls_app = api::router(tls_state);
tokio::spawn(async move {
if let Err(error) = mtls::serve(wormhole, tls_app).await {
tracing::error!("wormhole mTLS stopped: {error:#}");
}
});
tracing::info!("plain HTTP uploads are closed; wormhole clients use {listen_addr}");
}
let app = api::router(state);
let addr: SocketAddr = listen.parse()?;
tracing::info!("Tessera hub listening on {addr}");
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.await?;
Ok(())
}

View File

@@ -0,0 +1,263 @@
use anyhow::{Context, Result};
use axum::body::Body;
use axum::extract::Request;
use axum::response::Response;
use axum::Router;
use hyper::body::Incoming;
use hyper_util::rt::TokioIo;
use hyper_util::service::TowerToHyperService;
use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier;
use rustls::RootCertStore;
use rustls::ServerConfig;
use std::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context as TaskContext, Poll};
use tokio::net::TcpListener;
use tokio_rustls::TlsAcceptor;
use tower::{Service, ServiceExt};
pub struct WormholeMtls {
pub listen: SocketAddr,
cert: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
client_ca: RootCertStore,
}
pub fn from_env() -> Result<Option<WormholeMtls>> {
let raw = std::env::var("TESSERA_WORMHOLE_MTLS").unwrap_or_default();
let enabled = raw == "1" || raw.eq_ignore_ascii_case("true");
if !enabled {
return Ok(None);
}
let cert = std::env::var("TESSERA_WORMHOLE_CERT")
.context("TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled")?;
let key = std::env::var("TESSERA_WORMHOLE_KEY")
.context("TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled")?;
let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA")
.context("TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled")?;
let listen = std::env::var("TESSERA_WORMHOLE_LISTEN")
.unwrap_or_else(|_| "127.0.0.1:8788".into())
.parse()
.context("TESSERA_WORMHOLE_LISTEN")?;
install_provider();
Ok(Some(WormholeMtls {
listen,
cert: load_certs(Path::new(&cert))?,
key: load_key(Path::new(&key))?,
client_ca: load_ca(Path::new(&ca))?,
}))
}
pub fn install_provider() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
install_provider();
let verifier = WebPkiClientVerifier::builder(Arc::new(mtls.client_ca))
.build()
.map_err(|error| anyhow::anyhow!("wormhole client CA: {error}"))?;
let server = ServerConfig::builder()
.with_client_cert_verifier(verifier)
.with_single_cert(mtls.cert, mtls.key)
.map_err(|error| anyhow::anyhow!("wormhole certificate: {error}"))?;
let acceptor = TlsAcceptor::from(Arc::new(server));
let listener = TcpListener::bind(mtls.listen)
.await
.with_context(|| format!("bind wormhole mTLS {}", mtls.listen))?;
tracing::info!(
"wormhole mTLS listening on {}; a client certificate is required",
mtls.listen
);
loop {
let (tcp, peer) = match listener.accept().await {
Ok(accepted) => accepted,
Err(error) => {
// Out of file descriptors, an aborted handshake and the like pass; stopping the
// listener would end every Outpost's connection until a restart.
tracing::warn!(%error, "wormhole mTLS accept failed; continuing");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
continue;
}
};
let acceptor = acceptor.clone();
let app = app.clone();
tokio::spawn(async move {
let Ok(tls) = acceptor.accept(tcp).await else {
return;
};
let io = TokioIo::new(tls);
let service = TowerToHyperService::new(HyperApp(app, peer));
let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service)
.await;
});
}
}
#[derive(Clone)]
struct HyperApp(Router, SocketAddr);
impl Service<Request<Incoming>> for HyperApp {
type Response = Response;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;
fn poll_ready(&mut self, _cx: &mut TaskContext<'_>) -> Poll<Result<(), Infallible>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request<Incoming>) -> Self::Future {
let app = self.0.clone();
let mut request = request.map(Body::new);
// The TLS listener has no `into_make_service_with_connect_info`; supply the peer here
// so handlers that rate limit by source see the real address.
request
.extensions_mut()
.insert(axum::extract::ConnectInfo(self.1));
Box::pin(async move {
Ok(app
.oneshot(request)
.await
.unwrap_or_else(|error| match error {}))
})
}
}
pub fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
CertificateDer::pem_file_iter(path)
.with_context(|| format!("open {}", path.display()))?
.collect::<Result<Vec<_>, _>>()
.context("parse certificate")
}
pub fn load_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
PrivateKeyDer::from_pem_file(path).context("parse private key (none found in file?)")
}
pub fn load_ca(path: &Path) -> Result<RootCertStore> {
let mut roots = RootCertStore::empty();
for cert in load_certs(path)? {
roots
.add(cert)
.map_err(|error| anyhow::anyhow!("client CA: {error}"))?;
}
if roots.is_empty() {
anyhow::bail!("client CA file contained no certificates");
}
Ok(roots)
}
#[cfg(test)]
mod tests {
use super::*;
use rcgen::{
BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, KeyPair,
};
/// Agents reach pairing and upload routes over mTLS. Those handlers rate limit
/// by source, which needs the peer address; this proves it is supplied on that
/// listener (without it every agent request would fail in the extractor).
#[tokio::test]
async fn agent_requests_over_mtls_carry_their_peer_address() {
let ca_key = KeyPair::generate().unwrap();
let mut ca_params = CertificateParams::new(vec![]).unwrap();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
ca_params
.distinguished_name
.push(DnType::CommonName, "tessera-test-ca");
let ca = ca_params.self_signed(&ca_key).unwrap();
let server_key = KeyPair::generate().unwrap();
let server = CertificateParams::new(vec!["localhost".into()])
.unwrap()
.signed_by(&server_key, &ca, &ca_key)
.unwrap();
let client_key = KeyPair::generate().unwrap();
let mut client_params = CertificateParams::new(vec!["agent".into()]).unwrap();
client_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
let client = client_params.signed_by(&client_key, &ca, &ca_key).unwrap();
let dir = tempfile::tempdir().unwrap();
let write = |name: &str, pem: String| {
let path = dir.path().join(name);
std::fs::write(&path, pem).unwrap();
path
};
let port = {
let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
probe.local_addr().unwrap().port()
};
let mtls = WormholeMtls {
listen: SocketAddr::from(([127, 0, 0, 1], port)),
cert: load_certs(&write("server.pem", server.pem())).unwrap(),
key: load_key(&write("server.key", server_key.serialize_pem())).unwrap(),
client_ca: load_ca(&write("ca.pem", ca.pem())).unwrap(),
};
let mut state = crate::state::HubState::bootstrap(
dir.path().join("hub").to_str().unwrap(),
"synthetic-vault-passphrase",
)
.await
.unwrap();
state.admin.token = Some("synthetic-admin".into());
tokio::spawn(mtls_serve(mtls, crate::api::router(state)));
let identity = openidconnect::reqwest::Identity::from_pem(
format!("{}{}", client.pem(), client_key.serialize_pem()).as_bytes(),
)
.unwrap();
let trusted = openidconnect::reqwest::Certificate::from_pem(ca.pem().as_bytes()).unwrap();
let with_cert = openidconnect::reqwest::Client::builder()
.add_root_certificate(trusted.clone())
.identity(identity)
.build()
.unwrap();
// `pairing` requires `ConnectInfo<SocketAddr>` (no fallback), so a 200 proves the peer is supplied.
let url = format!("https://localhost:{port}/api/v1/wormhole/pairing");
let body = serde_json::json!({});
let mut answer = None;
for _ in 0..50 {
match with_cert
.post(&url)
.header("x-tessera-admin-token", "synthetic-admin")
.header("content-type", "application/json")
.body(body.to_string())
.send()
.await
{
Ok(response) => {
answer = Some(response.status().as_u16());
break;
}
Err(_) => tokio::time::sleep(std::time::Duration::from_millis(100)).await,
}
}
assert_eq!(
answer,
Some(200),
"a handler that requires ConnectInfo ran, so the peer address was supplied"
);
// without a client certificate the TLS handshake itself is refused
let anonymous = openidconnect::reqwest::Client::builder()
.add_root_certificate(trusted)
.build()
.unwrap();
assert!(anonymous
.post(&url)
.header("x-tessera-admin-token", "synthetic-admin")
.header("content-type", "application/json")
.body(body.to_string())
.send()
.await
.is_err());
}
async fn mtls_serve(mtls: WormholeMtls, app: Router) {
let _ = serve(mtls, app).await;
}
}

View File

@@ -0,0 +1,574 @@
//! OpenID Connect relying party: authorization code flow with PKCE.
//!
//! Protocol work (discovery, token exchange, ID-token signature, issuer,
//! audience, expiry and nonce checks) is done by the `openidconnect` crate.
//! This module owns configuration, key/metadata refresh policy and the mapping
//! from verified claims to a Tessera identity. Tokens never leave this module:
//! the caller only receives an [`Identity`].
use anyhow::{bail, Context, Result};
use openidconnect::core::{CoreAuthenticationFlow, CoreClient, CoreProviderMetadata};
use openidconnect::reqwest;
use openidconnect::{
AccessTokenHash, AuthorizationCode, ClientId, ClientSecret, CsrfToken, EndpointMaybeSet,
EndpointNotSet, EndpointSet, IssuerUrl, Nonce, OAuth2TokenResponse, PkceCodeChallenge,
PkceCodeVerifier, RedirectUrl, Scope, TokenResponse,
};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock};
pub const CALLBACK_PATH: &str = "/api/v1/auth/oidc/callback";
/// How long discovery metadata and signing keys are trusted without a refresh.
const METADATA_TTL: Duration = Duration::from_secs(600);
/// Minimum gap between refresh attempts, so unknown `kid`s cannot hammer the IdP.
const REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(60);
type Client = CoreClient<
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointMaybeSet,
EndpointMaybeSet,
>;
#[derive(Clone)]
pub struct OidcConfig {
pub issuer: String,
pub client_id: String,
client_secret: String,
pub redirect_url: String,
pub admin_subjects: BTreeSet<String>,
pub admin_groups: BTreeSet<String>,
pub groups_claim: String,
pub ca_file: Option<PathBuf>,
}
impl OidcConfig {
/// Read `TESSERA_OIDC_*`. `Ok(None)` when no issuer is configured.
/// A plain-http issuer is only accepted for a loopback host while
/// `TESSERA_LOCAL_DEVELOPMENT` is on.
pub fn from_env(local_development: bool) -> Result<Option<Self>> {
let var = |name: &str| {
std::env::var(name)
.ok()
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
};
let Some(issuer) = var("TESSERA_OIDC_ISSUER") else {
return Ok(None);
};
let need = |name: &str| {
var(name).with_context(|| format!("{name} is required when TESSERA_OIDC_ISSUER is set"))
};
let list = |name: &str| -> BTreeSet<String> {
var(name)
.map(|v| {
v.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
})
.unwrap_or_default()
};
let config = Self {
issuer,
client_id: need("TESSERA_OIDC_CLIENT_ID")?,
client_secret: need("TESSERA_OIDC_CLIENT_SECRET")?,
redirect_url: need("TESSERA_OIDC_REDIRECT_URL")?,
admin_subjects: list("TESSERA_OIDC_ADMIN_SUBJECTS"),
admin_groups: list("TESSERA_OIDC_ADMIN_GROUPS"),
groups_claim: var("TESSERA_OIDC_GROUPS_CLAIM").unwrap_or_else(|| "groups".into()),
ca_file: var("TESSERA_OIDC_CA_FILE").map(PathBuf::from),
};
config.validate(local_development)?;
Ok(Some(config))
}
pub fn validate(&self, allow_loopback_http: bool) -> Result<()> {
check_url("TESSERA_OIDC_ISSUER", &self.issuer, allow_loopback_http)?;
check_url(
"TESSERA_OIDC_REDIRECT_URL",
&self.redirect_url,
allow_loopback_http,
)?;
let redirect = url_parts(&self.redirect_url)?;
if redirect.path() != CALLBACK_PATH
|| redirect.query().is_some()
|| redirect.fragment().is_some()
{
bail!("TESSERA_OIDC_REDIRECT_URL must end with exactly {CALLBACK_PATH}");
}
if self.admin_subjects.is_empty() && self.admin_groups.is_empty() {
bail!("OIDC needs TESSERA_OIDC_ADMIN_SUBJECTS or TESSERA_OIDC_ADMIN_GROUPS; otherwise nobody could administer the hub");
}
Ok(())
}
/// Test constructor; the secret stays private to this module.
#[cfg(test)]
pub fn new(issuer: &str, client_id: &str, client_secret: &str, redirect_url: &str) -> Self {
Self {
issuer: issuer.into(),
client_id: client_id.into(),
client_secret: client_secret.into(),
redirect_url: redirect_url.into(),
admin_subjects: BTreeSet::new(),
admin_groups: BTreeSet::new(),
groups_claim: "groups".into(),
ca_file: None,
}
}
/// Identifies this configuration for session binding. It covers who may
/// administer, so removing an admin and restarting demotes their session.
/// The client secret is deliberately excluded: rotating it needs no logout.
pub fn fingerprint(&self) -> String {
let mut hash = Sha256::new();
hash.update(b"tessera-oidc-v1");
for part in [self.issuer.as_str(), &self.client_id, &self.groups_claim] {
hash.update([0]);
hash.update(part.as_bytes());
}
for set in [&self.admin_subjects, &self.admin_groups] {
hash.update([1]);
for item in set.iter() {
hash.update([0]);
hash.update(item.as_bytes());
}
}
hex::encode(hash.finalize())
}
/// Admin comes only from configuration matched against verified claims.
/// A missing or malformed group claim never grants anything.
pub fn is_admin(&self, identity: &Identity) -> bool {
self.admin_subjects.contains(&identity.subject)
|| identity
.groups
.iter()
.any(|group| self.admin_groups.contains(group))
}
}
fn url_parts(value: &str) -> Result<openidconnect::url::Url> {
openidconnect::url::Url::parse(value).with_context(|| format!("invalid URL {value}"))
}
fn check_url(name: &str, value: &str, allow_loopback_http: bool) -> Result<()> {
let url = url_parts(value).with_context(|| name.to_string())?;
match url.scheme() {
"https" => Ok(()),
"http" if allow_loopback_http
&& matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]")) => Ok(()),
_ => bail!("{name} must be an https:// URL (plain http is only accepted for loopback with TESSERA_LOCAL_DEVELOPMENT)"),
}
}
/// A verified identity. Display name is an attribute only, never an identifier.
#[derive(Debug, Clone)]
pub struct Identity {
pub issuer: String,
pub subject: String,
pub display_name: String,
pub groups: Vec<String>,
}
#[derive(Debug)]
pub enum OidcError {
/// IdP could not be reached and nothing usable is cached.
Unavailable,
/// The IdP response failed a protocol check.
Rejected,
}
struct Cached {
client: Arc<Client>,
fetched_at: Instant,
}
pub struct OidcProvider {
pub config: OidcConfig,
http: reqwest::Client,
cache: RwLock<Option<Cached>>,
/// Serialises refreshes; never held while the cache lock is held.
refresh: Mutex<Option<Instant>>,
min_refresh: Duration,
}
pub struct Begin {
pub url: String,
pub state: String,
pub nonce: String,
pub verifier: String,
}
impl OidcProvider {
pub fn new(config: OidcConfig) -> Result<Self> {
let mut builder = reqwest::Client::builder()
// Following redirects would turn discovery/JWKS fetches into an SSRF primitive.
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(15));
if let Some(path) = &config.ca_file {
let pem = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
builder = builder.add_root_certificate(
reqwest::Certificate::from_pem(&pem).context("TESSERA_OIDC_CA_FILE")?,
);
}
Ok(Self {
http: builder.build().context("build OIDC HTTP client")?,
config,
cache: RwLock::new(None),
refresh: Mutex::new(None),
min_refresh: REFRESH_MIN_INTERVAL,
})
}
#[cfg(test)]
pub fn with_min_refresh(mut self, gap: Duration) -> Self {
self.min_refresh = gap;
self
}
async fn discover(&self) -> Result<Client> {
let metadata = CoreProviderMetadata::discover_async(
IssuerUrl::new(self.config.issuer.clone())?,
&self.http,
)
.await?;
Ok(CoreClient::from_provider_metadata(
metadata,
ClientId::new(self.config.client_id.clone()),
Some(ClientSecret::new(self.config.client_secret.clone())),
)
.set_redirect_uri(RedirectUrl::new(self.config.redirect_url.clone())?))
}
/// Cached client, refreshed when stale. On refresh failure a previously
/// fetched client keeps working (IdP outage), a missing one is `Unavailable`.
/// `force` re-fetches keys for an unknown `kid` but is rate limited.
async fn client(&self, force: bool) -> Result<Arc<Client>, OidcError> {
let current = {
let guard = self.cache.read().await;
guard.as_ref().map(|c| (c.client.clone(), c.fetched_at))
};
let fresh = |at: Instant| at.elapsed() < METADATA_TTL;
if let Some((client, at)) = &current {
if fresh(*at) && !force {
return Ok(client.clone());
}
}
let mut last_attempt = self.refresh.lock().await;
// Someone else may have refreshed while we waited for the lock.
let cached = self
.cache
.read()
.await
.as_ref()
.map(|c| (c.client.clone(), c.fetched_at));
if let Some((client, at)) = &cached {
if fresh(*at) && !force {
return Ok(client.clone());
}
}
// Without any cached client, retry sooner so recovery after an outage is quick.
let gap = if cached.is_some() {
self.min_refresh
} else {
self.min_refresh.min(Duration::from_secs(5))
};
if last_attempt.is_some_and(|t| t.elapsed() < gap) {
return cached.map(|(c, _)| c).ok_or(OidcError::Unavailable);
}
*last_attempt = Some(Instant::now());
match self.discover().await {
Ok(client) => {
let client = Arc::new(client);
*self.cache.write().await = Some(Cached {
client: client.clone(),
fetched_at: Instant::now(),
});
Ok(client)
}
Err(error) => {
tracing::warn!("OIDC discovery failed: {error:#}");
current.map(|(c, _)| c).ok_or(OidcError::Unavailable)
}
}
}
/// Build the authorization redirect. The caller stores `state`, `nonce` and
/// `verifier` as a one-time login transaction bound to the browser.
pub async fn begin(&self) -> Result<Begin, OidcError> {
let client = self.client(false).await?;
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
let (url, state, nonce) = client
.authorize_url(
CoreAuthenticationFlow::AuthorizationCode,
CsrfToken::new_random,
Nonce::new_random,
)
.add_scope(Scope::new("profile".into()))
.set_pkce_challenge(challenge)
.url();
Ok(Begin {
url: url.to_string(),
state: state.secret().clone(),
nonce: nonce.secret().clone(),
verifier: verifier.secret().clone(),
})
}
/// Exchange the code and verify the ID token. Details go to the log; the
/// caller only sees `Unavailable` or `Rejected`.
pub async fn finish(
&self,
code: &str,
nonce: &str,
verifier: &str,
) -> Result<Identity, OidcError> {
let client = self.client(false).await?;
let response = client
.exchange_code(AuthorizationCode::new(code.to_string()))
.map_err(|_| OidcError::Unavailable)?
.set_pkce_verifier(PkceCodeVerifier::new(verifier.to_string()))
.request_async(&self.http)
.await
.map_err(|error| {
tracing::warn!("OIDC token exchange failed: {error}");
match error {
openidconnect::RequestTokenError::Request(_) => OidcError::Unavailable,
_ => OidcError::Rejected,
}
})?;
let id_token = response.id_token().ok_or_else(|| {
tracing::warn!("OIDC token response has no ID token");
OidcError::Rejected
})?;
let nonce = Nonce::new(nonce.to_string());
let mut client = client;
for attempt in 0..2 {
match verify(
&client,
id_token,
response.access_token(),
&nonce,
&self.config.groups_claim,
) {
Ok(identity) => return Ok(identity),
// Keys may have rotated since the last fetch: refresh once and retry.
Err(Verify::Signature) if attempt == 0 => client = self.client(true).await?,
Err(_) => break,
}
}
Err(OidcError::Rejected)
}
}
enum Verify {
Signature,
Other,
}
/// All checks on one ID token: signature, issuer, audience, expiry and nonce
/// (library), access-token hash, then mapping to an owned [`Identity`].
fn verify(
client: &Client,
id_token: &openidconnect::core::CoreIdToken,
access_token: &openidconnect::AccessToken,
nonce: &Nonce,
groups_claim: &str,
) -> Result<Identity, Verify> {
let verifier = client.id_token_verifier();
let claims = id_token.claims(&verifier, nonce).map_err(|error| {
tracing::warn!("OIDC ID token rejected: {error}");
if matches!(
error,
openidconnect::ClaimsVerificationError::SignatureVerification(_)
) {
Verify::Signature
} else {
Verify::Other
}
})?;
if let Some(expected) = claims.access_token_hash() {
let actual = id_token
.signing_alg()
.ok()
.and_then(|alg| id_token.signing_key(&verifier).ok().map(|key| (alg, key)))
.and_then(|(alg, key)| AccessTokenHash::from_token(access_token, alg, key).ok());
if actual.as_ref() != Some(expected) {
tracing::warn!("OIDC access token hash mismatch");
return Err(Verify::Other);
}
}
let subject = claims.subject().as_str().to_string();
if subject.is_empty() || subject.len() > 255 {
tracing::warn!("OIDC ID token has an unusable subject");
return Err(Verify::Other);
}
let display_name = claims
.preferred_username()
.map(|n| n.as_str().to_string())
.or_else(|| {
claims
.name()
.and_then(|n| n.get(None))
.map(|n| n.as_str().to_string())
})
.unwrap_or_else(|| subject.clone())
.chars()
.take(128)
.collect();
// The signature was verified by `claims()` above, so reading one more
// claim from the same token is safe. Missing or malformed means no groups.
let groups = groups_from_token(&id_token.to_string(), groups_claim);
Ok(Identity {
issuer: claims.issuer().as_str().to_string(),
subject,
display_name,
groups,
})
}
fn groups_from_token(jwt: &str, claim: &str) -> Vec<String> {
use base64::Engine;
let Some(payload) = jwt.split('.').nth(1) else {
return vec![];
};
let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload) else {
return vec![];
};
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
return vec![];
};
match value.get(claim) {
Some(serde_json::Value::String(one)) => vec![one.clone()],
Some(serde_json::Value::Array(items)) => items
.iter()
.filter_map(|item| item.as_str().map(str::to_string))
.collect(),
_ => vec![],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn config() -> OidcConfig {
let mut config = OidcConfig::new(
"https://idp.example/realm",
"tessera",
"secret",
"https://hub.example/api/v1/auth/oidc/callback",
);
config.admin_subjects.insert("admin-sub".into());
config
}
#[test]
fn http_issuers_are_rejected_unless_loopback_in_local_development() {
let mut c = config();
assert!(c.validate(false).is_ok());
c.issuer = "http://idp.example".into();
assert!(c.validate(false).is_err());
assert!(
c.validate(true).is_err(),
"non-loopback http stays rejected"
);
c.issuer = "http://localhost:8080/realms/t".into();
assert!(c.validate(false).is_err());
assert!(
c.validate(true).is_ok(),
"loopback http issuer in local development"
);
c.redirect_url = "http://hub.example/api/v1/auth/oidc/callback".into();
assert!(
c.validate(true).is_err(),
"non-loopback http redirect stays rejected"
);
c.redirect_url = "http://localhost:8787/api/v1/auth/oidc/callback".into();
assert!(c.validate(true).is_ok());
assert!(c.validate(false).is_err());
}
#[test]
fn redirect_url_must_be_the_exact_callback_and_an_admin_mapping_is_required() {
let mut c = config();
c.redirect_url = "https://hub.example/other".into();
assert!(c.validate(false).is_err());
c.redirect_url = "https://hub.example/api/v1/auth/oidc/callback?x=1".into();
assert!(c.validate(false).is_err());
let mut c = config();
c.admin_subjects.clear();
assert!(c.validate(false).is_err(), "no way to administer");
c.admin_groups.insert("tessera-admins".into());
assert!(c.validate(false).is_ok());
}
#[test]
fn admin_mapping_uses_subject_or_verified_group_only() {
let mut c = config();
c.admin_groups.insert("tessera-admins".into());
let id = |sub: &str, groups: &[&str]| Identity {
issuer: "i".into(),
subject: sub.into(),
display_name: "operator".into(),
groups: groups.iter().map(|g| g.to_string()).collect(),
};
assert!(c.is_admin(&id("admin-sub", &[])));
assert!(c.is_admin(&id("someone", &["tessera-admins"])));
assert!(!c.is_admin(&id("someone", &["other"])));
assert!(
!c.is_admin(&id("someone", &[])),
"missing groups claim grants nothing"
);
assert!(
!c.is_admin(&id("operator", &[])),
"display name is not an identifier"
);
}
#[test]
fn fingerprint_changes_with_the_admin_mapping_but_not_the_client_secret() {
let base = config();
let mut rotated = config();
rotated.client_secret = "new-secret".into();
assert_eq!(base.fingerprint(), rotated.fingerprint());
let mut demoted = config();
demoted.admin_subjects.clear();
demoted.admin_subjects.insert("someone-else".into());
assert_ne!(base.fingerprint(), demoted.fingerprint());
let mut renamed = config();
renamed.groups_claim = "roles".into();
assert_ne!(base.fingerprint(), renamed.fingerprint());
}
#[test]
fn groups_accept_a_string_or_array_and_ignore_anything_else() {
use base64::Engine;
let jwt = |json: &str| {
format!(
"h.{}.s",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json)
)
};
assert_eq!(
groups_from_token(&jwt(r#"{"groups":["a","b"]}"#), "groups"),
["a", "b"]
);
assert_eq!(
groups_from_token(&jwt(r#"{"groups":"solo"}"#), "groups"),
["solo"]
);
assert!(groups_from_token(&jwt(r#"{"groups":{"a":1}}"#), "groups").is_empty());
assert!(groups_from_token(&jwt(r#"{"groups":[1,null]}"#), "groups").is_empty());
assert!(groups_from_token(&jwt(r#"{"other":["a"]}"#), "groups").is_empty());
assert!(groups_from_token("not-a-jwt", "groups").is_empty());
}
}

View File

@@ -0,0 +1,175 @@
//! The refresh driver: moves durable refresh runs forward.
//!
//! The runs and every transition live in SQLite (`db/refresh.rs`); this loop only looks at them. It
//! holds no state, so a restart simply carries on. The one step that needs the vault (reading the
//! snapshot a run's capture produced) happens outside any database lock, and the store re-checks
//! everything inside its transaction before it queues the restore.
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::db::refresh::{Linked, RefreshRun, Sync};
use crate::state::HubState;
use std::time::Duration;
use uuid::Uuid;
pub const DEFAULT_TTL_MINUTES: i64 = 120;
pub const DEFAULT_MAX_ACTIVE: i64 = 4;
pub struct RefreshConfig {
/// How long a run may take before it starts applying. After that it expires. Once applying, it is never cut off.
pub ttl_secs: i64,
/// Refreshes running at once, to bound the load on production sources.
pub max_active: i64,
}
impl RefreshConfig {
pub fn from_env() -> Self {
let number = |name: &str| {
std::env::var(name)
.ok()
.and_then(|v| v.trim().parse::<i64>().ok())
};
Self {
ttl_secs: number("TESSERA_REFRESH_TTL_MINUTES")
.filter(|m| (1..=1440).contains(m))
.unwrap_or(DEFAULT_TTL_MINUTES)
* 60,
max_active: number("TESSERA_REFRESH_MAX_ACTIVE")
.filter(|m| (1..=64).contains(m))
.unwrap_or(DEFAULT_MAX_ACTIVE),
}
}
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
/// The audit action and outcome that go with a run reaching a state.
pub fn audit_name(status: &str) -> (&'static str, AuditOutcome) {
match status {
"capturing" => ("refresh.started", AuditOutcome::Succeeded),
"undo" => ("refresh.undo_started", AuditOutcome::Succeeded),
"restoring" => ("refresh.restore_queued", AuditOutcome::Succeeded),
"completed" => ("refresh.completed", AuditOutcome::Succeeded),
"reconciled" => ("refresh.reconciled", AuditOutcome::Succeeded),
"cancelled" => ("refresh.cancelled", AuditOutcome::Succeeded),
"capture_failed" => ("refresh.capture_failed", AuditOutcome::Failed),
"restore_failed" => ("refresh.restore_failed", AuditOutcome::Failed),
"recovery_required" => ("refresh.recovery_required", AuditOutcome::Failed),
"blocked" => ("refresh.blocked", AuditOutcome::Denied),
"expired" => ("refresh.expired", AuditOutcome::Denied),
_ => ("refresh.changed", AuditOutcome::Succeeded),
}
}
pub fn audit_run(state: &HubState, run: &str, status: &str) {
let (action, outcome) = audit_name(status);
if let Ok(id) = Uuid::parse_str(run) {
if let Err(error) = state.db.audit_event(
&Principal::Service("refresh"),
AuditAction::RefreshEvent(action),
AuditResource::RefreshRun(id),
outcome,
Uuid::new_v4(),
) {
tracing::error!("could not audit refresh run {run}: {error:#}");
}
}
}
/// One pass over every active run. Returns how many changed.
pub async fn tick(state: &HubState) -> anyhow::Result<usize> {
let mut changed = 0;
for run in state.db.active_refresh_runs()? {
match state.db.sync_refresh_run(&run.id, now())? {
Sync::Unchanged => {}
Sync::Moved(status) => {
changed += 1;
audit_run(state, &run.id, &status);
}
Sync::NeedRestore(snapshot) => {
if queue_restore(state, &run, &snapshot).await? {
changed += 1;
}
}
}
}
Ok(changed)
}
/// Read the run's own snapshot and queue its restore. Idempotent: a second call finds the job already linked.
async fn queue_restore(state: &HubState, run: &RefreshRun, snapshot: &str) -> anyhow::Result<bool> {
let snapshot_id = Uuid::parse_str(snapshot)?;
let manifest = state
.vault
.read()
.await
.get_snapshot(snapshot_id)?
.map(|s| s.manifest);
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
// A safety copy is restorable only onto the target it was taken from (an undo); anything else must be a
// capture with its source identity.
let artifact = manifest.as_ref().and_then(|manifest| {
if manifest.is_restore_safety() {
target
.as_ref()
.and_then(|target| crate::api::rollback_artifact(manifest, target))
} else {
crate::api::artifact(manifest).map(|(_, artifact)| artifact)
}
});
let Some(artifact) = artifact else {
// The snapshot is missing or lacks what a restore needs (format, checksum, source identity).
state
.db
.block_refresh_run(&run.id, "snapshot_not_restorable", now())?;
audit_run(state, &run.id, "blocked");
return Ok(true);
};
// The driver looks again: a run that was told to restore a snapshot only restores one of its own source.
let belongs = manifest
.as_ref()
.is_some_and(|manifest| manifest.orbit_id.to_string() == run.source_orbit_id);
if !belongs {
state
.db
.block_refresh_run(&run.id, "snapshot_not_restorable", now())?;
audit_run(state, &run.id, "blocked");
return Ok(true);
}
let clash = match target {
Some(target) => {
let source = Uuid::parse_str(&run.source_orbit_id)?;
crate::api::identity_facts(state, source, &target.identity)
.await
.map_err(|status| anyhow::anyhow!("identity check failed: {status}"))?
.0
}
None => true,
};
match state
.db
.enqueue_refresh_restore(&run.id, &artifact, clash, now())?
{
Linked::Queued(_) => {
audit_run(state, &run.id, "restoring");
Ok(true)
}
Linked::Blocked(_) => {
audit_run(state, &run.id, "blocked");
Ok(true)
}
Linked::NotReady => Ok(false),
}
}
/// Start the background loop. Cheap when nothing is running.
pub fn start(state: HubState) {
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(3)).await;
if let Err(error) = tick(&state).await {
tracing::warn!("refresh driver: {error:#}");
}
}
});
}

View File

@@ -1,46 +1,185 @@
use crate::state::HubState;
use anyhow::Result;
use anyhow::{Context, Result};
use chrono::{DateTime, NaiveTime, TimeZone, Utc};
use chrono_tz::Tz;
use cron::Schedule;
use std::str::FromStr;
use tessera_core::job::CaptureSchedule;
use tokio::time::{sleep, Duration};
use tracing::{error, info};
pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
let db = state.db.clone();
tokio::spawn(async move {
loop {
if let Err(e) = tick_schedules(state.clone()).await {
if let Err(e) = tick_capture_schedules(&db, Utc::now()) {
error!("capture scheduler tick: {e}");
}
sleep(Duration::from_secs(30)).await;
}
});
tokio::spawn(async move {
let mut previous = Utc::now();
loop {
let now = Utc::now();
if let Err(e) = tick_schedules(state.clone(), previous, now).await {
error!("scheduler tick: {e}");
}
previous = now;
sleep(Duration::from_secs(30)).await;
}
});
Ok(())
}
async fn tick_schedules(state: HubState) -> Result<()> {
const DEFAULT_AUDIT_RETENTION_DAYS: i64 = 90;
/// `TESSERA_AUDIT_RETENTION_DAYS`: how long structured audit events are kept.
/// Unset means 90 days; `0` keeps them forever.
pub fn audit_retention_from_env() -> Result<Option<i64>> {
parse_audit_retention(
std::env::var("TESSERA_AUDIT_RETENTION_DAYS")
.ok()
.as_deref(),
)
}
fn parse_audit_retention(value: Option<&str>) -> Result<Option<i64>> {
let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else {
return Ok(Some(DEFAULT_AUDIT_RETENTION_DAYS));
};
let days: i64 = value
.parse()
.ok()
.filter(|days| (0..=36_500).contains(days))
.context(
"TESSERA_AUDIT_RETENTION_DAYS must be a whole number of days (0 keeps everything)",
)?;
Ok((days > 0).then_some(days))
}
/// Prunes audit events once now and then every hour.
pub fn start_audit_retention(db: crate::db::Db, retention_days: Option<i64>) {
let Some(days) = retention_days else {
info!("audit retention disabled: audit events are kept forever");
return;
};
tokio::spawn(async move {
loop {
let cutoff = Utc::now().timestamp() - days * 86_400;
match db.prune_audit_events(cutoff) {
Ok(0) => {}
Ok(n) => info!("pruned {n} audit event(s) older than {days} days"),
Err(e) => error!("audit retention: {e}"),
}
sleep(Duration::from_secs(3600)).await;
}
});
}
pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> {
if expression.split_whitespace().count() == 5 {
Schedule::from_str(&format!("0 {expression}"))
} else {
Schedule::from_str(expression)
}
}
async fn tick_schedules(
state: HubState,
previous: DateTime<Utc>,
now: DateTime<Utc>,
) -> Result<()> {
let orbits = state.db.list_orbits().await?;
let now = chrono::Utc::now();
for orbit in orbits {
let Some(cron_expr) = orbit.schedule.as_ref() else {
if orbit.provider == "wormhole" {
continue;
}
let Some(cron_expr) = orbit
.schedule
.as_deref()
.filter(|expr| !expr.trim().is_empty())
else {
continue;
};
let schedule = match Schedule::from_str(cron_expr) {
let schedule = match orbit_schedule(cron_expr) {
Ok(s) => s,
Err(e) => {
error!("bad cron on orbit {}: {e}", orbit.name);
continue;
}
};
let upcoming = schedule.upcoming(chrono::Utc).take(1).collect::<Vec<_>>();
if let Some(next) = upcoming.first() {
let delta = (*next - now).num_seconds().abs();
if delta < 35 {
info!("scheduler firing orbit {}", orbit.name);
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit.id).await {
error!("orbit {} failed: {e}", orbit.name);
}
if schedule
.after(&previous)
.next()
.is_some_and(|slot| slot <= now)
{
info!("scheduler firing orbit {}", orbit.name);
let orbit_id = orbit.id;
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit).await {
error!("orbit {orbit_id} failed: {e}");
}
}
}
Ok(())
}
pub fn capture_schedule(schedule: &CaptureSchedule) -> Option<(NaiveTime, Tz)> {
let time = NaiveTime::from_hms_opt(u32::from(schedule.hour), u32::from(schedule.minute), 0)?;
Some((time, schedule.timezone.parse().ok()?))
}
pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime<Utc>) -> Result<()> {
for (profile, cursor) in db.capture_schedule_cursors()? {
let Some(schedule) = &profile.schedule else {
continue;
};
let (time, tz) = capture_schedule(schedule).context("invalid stored capture schedule")?;
let start = DateTime::from_timestamp(cursor, 0).context("invalid schedule cursor")?;
let end = now.with_timezone(&tz).date_naive();
let mut date = start.with_timezone(&tz).date_naive();
for _ in 0..32 {
if date > end {
break;
}
if let Some(slot) = tz.from_local_datetime(&date.and_time(time)).earliest() {
if slot.timestamp() > cursor && slot <= now {
db.enqueue_scheduled_capture(
profile.application_id,
slot.timestamp(),
now.timestamp(),
)?;
}
}
date = date.succ_opt().context("schedule date overflow")?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn audit_retention_defaults_to_ninety_days_and_zero_disables_it() {
assert_eq!(parse_audit_retention(None).unwrap(), Some(90));
assert_eq!(parse_audit_retention(Some(" ")).unwrap(), Some(90));
assert_eq!(parse_audit_retention(Some("30")).unwrap(), Some(30));
assert_eq!(parse_audit_retention(Some("0")).unwrap(), None);
assert!(parse_audit_retention(Some("-1")).is_err());
assert!(parse_audit_retention(Some("soon")).is_err());
}
#[test]
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();
let slot = Utc.with_ymd_and_hms(2026, 11, 10, 2, 0, 0).unwrap();
for expression in ["0 2 * * *", "0 0 2 * * *"] {
let schedule = orbit_schedule(expression).unwrap();
assert_eq!(schedule.after(&before).next(), Some(slot));
assert!(schedule.after(&slot).next().unwrap() > slot);
}
assert!(orbit_schedule("60 2 * * *").is_err());
}
}

View File

@@ -1,31 +1,54 @@
use crate::admin::{AdminGate, SessionGate};
use crate::db::Db;
use anyhow::Result;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use tessera_core::reconstitute::ReconstituteSession;
use tessera_core::wormhole::PairingState;
use tessera_store::Vault;
use tokio::sync::RwLock;
use tessera_core::decay::{
evaluate_capture_retention, evaluate_gfs, evaluate_safety_retention, CaptureRetention,
RetentionPolicy, SafetyRef, SnapshotRef,
};
use tessera_core::job::CaptureProfile;
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState};
use tessera_store::{Offsite, Vault};
use tokio::sync::{Mutex, RwLock};
use uuid::Uuid;
pub(crate) enum ManagedRetention {
Orbit(RetentionPolicy),
Profile(CaptureRetention),
Default(CaptureRetention),
}
impl ManagedRetention {
pub(crate) fn resolve(profile: &CaptureProfile, orbit: Option<RetentionPolicy>) -> Self {
match (profile.retention, orbit) {
(Some(policy), _) => Self::Profile(policy),
(None, Some(policy)) => Self::Orbit(policy),
(None, None) => Self::Default(CaptureRetention::default()),
}
}
}
#[derive(Clone)]
pub struct HubState {
pub db: Db,
pub data_dir: PathBuf,
pub vault_passphrase: String,
pub offsite: Option<Arc<Offsite>>,
pub vault: Arc<RwLock<Vault>>,
pub pairing_codes: Arc<RwLock<Vec<PairingEntry>>>,
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
}
#[derive(Clone)]
pub struct PairingEntry {
pub code: String,
pub expires_at: chrono::DateTime<chrono::Utc>,
pub state: PairingState,
pub outpost_id: Uuid,
pub upload_token: String,
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
pub admin: AdminGate,
pub sessions: SessionGate,
pub oidc: Option<std::sync::Arc<crate::oidc::OidcProvider>>,
pub limits: Arc<crate::limits::Limits>,
pub exports: Arc<crate::exports::ExportGate>,
pub refresh: Arc<crate::refresh::RefreshConfig>,
pub wormhole_mtls: bool,
/// Token uploads are accepted on this listener. Plain HTTP turns this off
/// when wormhole mTLS is required, so those routes are not a bypass.
pub accept_plain_upload: bool,
}
impl HubState {
@@ -43,18 +66,231 @@ impl HubState {
Vault::init(&vault_path, vault_pass)?
};
let admin = AdminGate::from_env()?;
let oidc_config = crate::oidc::OidcConfig::from_env(admin.local_development)?;
Ok(Self {
db,
db: db.clone(),
data_dir,
vault_passphrase: vault_pass.to_string(),
offsite: None,
vault: Arc::new(RwLock::new(vault)),
pairing_codes: Arc::new(RwLock::new(Vec::new())),
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
active_orbits: Arc::new(Mutex::new(HashSet::new())),
admin,
sessions: SessionGate::from_env(
db.clone(),
oidc_config.as_ref().map(|c| c.fingerprint()),
)?,
limits: Arc::new(crate::limits::Limits::from_env()?),
exports: Arc::new(crate::exports::ExportGate::from_env()),
refresh: Arc::new(crate::refresh::RefreshConfig::from_env()),
oidc: oidc_config
.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new))
.transpose()?,
wormhole_mtls: false,
accept_plain_upload: true,
})
}
pub async fn upload_token_valid(&self, token: &str) -> bool {
let codes = self.pairing_codes.read().await;
codes.iter().any(|c| c.upload_token == token && c.state == PairingState::Active)
pub fn configure_offsite(&mut self) -> Result<()> {
let Some(repository) = std::env::var_os("TESSERA_OFFSITE_REPOSITORY") else {
return Ok(());
};
let repository = repository
.to_str()
.ok_or_else(|| anyhow::anyhow!("off-site repository must be UTF-8"))?;
let password = std::env::var_os("TESSERA_OFFSITE_PASSWORD_FILE").ok_or_else(|| {
anyhow::anyhow!("TESSERA_OFFSITE_PASSWORD_FILE is required for off-site copies")
})?;
self.offsite = Some(Arc::new(Offsite::new(
repository,
std::path::Path::new(&password),
)?));
Ok(())
}
pub async fn reconcile_capture_catalog(&self) -> Result<()> {
let vault = self.vault.clone().read_owned().await;
let db = self.db.clone();
let offsite_enabled = self.offsite.is_some();
tokio::task::spawn_blocking(move || {
for id in db.incomplete_publications()? {
let Some(snap) = vault.get_snapshot(id)? else {
continue;
};
if snap
.manifest
.restore_hints
.get("job_id")
.and_then(|id| id.as_str())
.and_then(|id| Uuid::parse_str(id).ok())
== Some(snap.id)
{
let offsite = offsite_enabled && snap.manifest.restore_hints["format"] != "tar";
db.reconcile_capture(snap.id, snap.manifest.orbit_id, offsite)?;
}
}
Ok(())
})
.await?
}
pub fn start_offsite_worker(&self) {
let Some(offsite) = self.offsite.clone() else {
return;
};
let state = self.clone();
tokio::spawn(async move {
loop {
match state.db.pending_offsite() {
Ok(jobs) => {
for id in jobs {
let offsite = offsite.clone();
let prepared = state.vault.read().await.prepare_offsite_copy(id);
let result = match prepared {
Ok(copy) => offsite.copy_capture(copy).await,
Err(error) => Err(error),
};
let success = result.is_ok();
if let Err(error) = &result {
tracing::warn!(%id, error = %format!("{error:#}"), "off-site capture copy failed");
}
if state.db.set_offsite_result(id, success).is_err() {
tracing::warn!(%id, "could not save off-site copy status");
}
}
}
Err(_) => tracing::warn!("could not read off-site copy queue"),
}
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
});
}
pub async fn export_snapshot(&self, snapshot: Uuid, dest: PathBuf) -> Result<u64> {
let vault = self.vault.clone().read_owned().await;
let local_dest = dest.clone();
let (local, published) = tokio::task::spawn_blocking(move || {
(
vault.restore_snapshot(snapshot, &local_dest),
vault.has_published_snapshot(snapshot),
)
})
.await?;
if local.is_err() && published? {
if let Some(offsite) = &self.offsite {
return offsite.restore(snapshot, &dest).await;
}
}
local
}
pub async fn active_exports(&self) -> HashSet<Uuid> {
self.reconstitute_sessions
.read()
.await
.values()
.filter_map(|session| {
matches!(
session.state,
ReconstituteState::Countdown
| ReconstituteState::Confirming
| ReconstituteState::Restoring
)
.then_some(session.snapshot_id)
})
.collect()
}
pub async fn prune_orbit(&self, orbit_id: Uuid) -> Result<Vec<Uuid>> {
let mut vault = self.vault.clone().write_owned().await;
let (preset, retention) = self.db.orbit_retention(orbit_id)?;
let profile = self.db.capture_profile_for_orbit(orbit_id)?;
let active_exports = self.active_exports().await;
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
let Some(profile) = profile else {
return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref());
};
let (safety, captures): (Vec<_>, Vec<_>) = vault
.list_snapshots()?
.into_iter()
.filter(|snapshot| snapshot.manifest.orbit_id == orbit_id)
.partition(|snapshot| snapshot.manifest.is_restore_safety());
let snapshots = captures
.into_iter()
.map(|snapshot| SnapshotRef {
id: snapshot.id,
taken_at: snapshot.taken_at,
})
.collect();
// Safety copies of restore targets have their own retention: they never count as a backup of
// the application, so they can neither displace a capture nor be displaced by one.
let safety: Vec<_> = safety
.into_iter()
.map(|snapshot| SafetyRef {
id: snapshot.id,
taken_at: snapshot.taken_at,
target: snapshot.manifest.safety_target().unwrap_or_default(),
})
.collect();
let expired = match ManagedRetention::resolve(&profile, retention) {
ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots),
ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => {
evaluate_capture_retention(policy, snapshots, chrono::Utc::now())
}
};
let mut deletable = Vec::new();
let expired = expired
.into_iter()
.chain(evaluate_safety_retention(safety, chrono::Utc::now()));
for id in expired {
if !active_exports.contains(&id)
&& !db.offsite_pending(id)?
&& !db.snapshot_in_restore(id)?
{
deletable.push(id);
}
}
vault.forget(&deletable)?;
Ok(deletable)
})
.await?
}
}
#[cfg(test)]
mod tests {
use super::*;
use tessera_core::job::CaptureFormat;
#[test]
fn managed_retention_prefers_profile_then_orbit_then_default() {
let mut profile = CaptureProfile {
application_id: Uuid::nil(),
orbit_id: Uuid::nil(),
outpost_id: Uuid::nil(),
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
};
let orbit = RetentionPolicy {
keep_daily: 3,
keep_weekly: 0,
keep_monthly: 0,
keep_yearly: 0,
};
assert!(matches!(
ManagedRetention::resolve(&profile, None),
ManagedRetention::Default(CaptureRetention::Age { days: 14 })
));
assert!(matches!(
ManagedRetention::resolve(&profile, Some(orbit)),
ManagedRetention::Orbit(policy) if policy == orbit
));
profile.retention = Some(CaptureRetention::Count { keep: 5 });
assert!(matches!(
ManagedRetention::resolve(&profile, Some(orbit)),
ManagedRetention::Profile(CaptureRetention::Count { keep: 5 })
));
}
}

View File

@@ -0,0 +1,76 @@
use std::fs::File;
use std::io::{self, Seek, SeekFrom, Write};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ByteRange {
pub start: u64,
pub end: u64,
}
/// Bytes covered from offset 0 with no gap. Overlaps are merged.
pub fn contiguous_from_zero(ranges: &[ByteRange]) -> u64 {
let mut ordered: Vec<ByteRange> = ranges
.iter()
.copied()
.filter(|range| range.end > range.start)
.collect();
ordered.sort_by_key(|range| (range.start, range.end));
let mut covered = 0u64;
for range in ordered {
if range.start > covered {
break;
}
covered = covered.max(range.end);
}
covered
}
pub fn write_at(file: &mut File, offset: u64, data: &[u8], total: u64) -> io::Result<ByteRange> {
let end = offset
.checked_add(data.len() as u64)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows"))?;
if end > total {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"chunk exceeds the declared upload size",
));
}
file.seek(SeekFrom::Start(offset))?;
file.write_all(data)?;
Ok(ByteRange { start: offset, end })
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
#[test]
fn out_of_order_chunks_cover_the_object() {
assert_eq!(contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]), 0);
assert_eq!(
contiguous_from_zero(&[
ByteRange { start: 4, end: 8 },
ByteRange { start: 0, end: 4 },
]),
8
);
assert_eq!(
contiguous_from_zero(&[
ByteRange { start: 0, end: 3 },
ByteRange { start: 2, end: 5 },
]),
5
);
}
#[test]
fn writes_honor_offset() {
let mut file = NamedTempFile::new().unwrap();
write_at(file.as_file_mut(), 3, b"def", 6).unwrap();
write_at(file.as_file_mut(), 0, b"abc", 6).unwrap();
assert!(write_at(file.as_file_mut(), 4, b"xyz", 6).is_err());
let bytes = std::fs::read(file.path()).unwrap();
assert_eq!(&bytes[..6], b"abcdef");
}
}

View File

@@ -3,6 +3,7 @@ name = "tessera-providers"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[dependencies]
tessera-core = { path = "../tessera-core" }
@@ -12,4 +13,7 @@ serde.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["process", "fs"] }
tracing.workspace = true
tempfile.workspace = true
regex = "1"
uuid.workspace = true
walkdir.workspace = true

View File

@@ -1,8 +1,16 @@
mod filesystem;
mod mysql;
mod mysql_restore;
mod postgres;
mod postgres_restore;
mod ssh;
pub use filesystem::*;
pub use mysql::MysqlSource;
pub use mysql_restore::MysqlRestore;
pub use postgres::*;
pub use postgres_restore::{PostgresReset, PostgresRestore};
pub use ssh::SshEndpoint;
use anyhow::Result;
use async_trait::async_trait;
@@ -22,10 +30,15 @@ pub struct CaptureResult {
pub restore_hints: Value,
}
pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result<Box<dyn BackupProvider>> {
pub fn provider_from_config(
kind: &ProviderKind,
config: &Value,
) -> Result<Box<dyn BackupProvider>> {
match kind {
ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)),
ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)),
ProviderKind::Command => anyhow::bail!("command provider not implemented in v1"),
ProviderKind::Command => {
anyhow::bail!("command provider is outside this release; use filesystem or postgres")
}
}
}

View File

@@ -0,0 +1,238 @@
use crate::SshEndpoint;
use anyhow::{Context, Result};
use serde::Deserialize;
use std::{fs, io::Write, path::PathBuf, process::Stdio};
use tessera_core::restore::DatabaseIdentity;
use tokio::process::Command;
#[derive(Deserialize)]
#[serde(tag = "transport", rename_all = "snake_case", deny_unknown_fields)]
pub enum MysqlSource {
Direct {
host: String,
#[serde(default = "default_port")]
port: u16,
database: String,
user: String,
password_file: PathBuf,
#[serde(default)]
tls: MysqlTls,
},
Ssh {
bastion: SshEndpoint,
database: String,
defaults_file: String,
},
}
fn default_port() -> u16 {
3306
}
#[derive(Default, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum MysqlTls {
#[default]
VerifyIdentity,
VerifyIdentityWithCa {
ca_file: PathBuf,
},
Required,
Disabled,
}
const FLAGS: &[&str] = &[
"--single-transaction",
"--skip-dump-date",
"--skip-lock-tables",
"--no-tablespaces",
"--set-gtid-purged=OFF",
"--default-character-set=utf8mb4",
"--routines",
"--events",
"--triggers",
];
impl MysqlSource {
pub async fn dump_to(&self, file: fs::File) -> Result<()> {
self.run(
"mysqldump",
FLAGS,
Stdio::null(),
Stdio::from(file.try_clone()?),
)
.await?;
anyhow::ensure!(
file.metadata()?.len() > 0,
"MySQL dump produced an empty file"
);
Ok(())
}
pub fn database(&self) -> &str {
match self {
Self::Direct { database, .. } | Self::Ssh { database, .. } => database,
}
}
pub async fn identity(&self) -> Result<DatabaseIdentity> {
let output = self
.run(
"mysql",
&[
"--batch",
"--raw",
"--skip-column-names",
"--default-character-set=utf8mb4",
"--execute",
"SELECT JSON_OBJECT('instance', LOWER(@@server_uuid), 'database', DATABASE())",
],
Stdio::null(),
Stdio::piped(),
)
.await?;
serde_json::from_slice(&output.stdout).context("invalid MySQL identity")
}
pub(crate) async fn run(
&self,
program: &str,
args: &[&str],
stdin: Stdio,
stdout: Stdio,
) -> Result<std::process::Output> {
let config;
let mut cmd = match self {
Self::Direct {
host,
port,
database,
user,
password_file,
tls,
} => {
validate_database(database)?;
anyhow::ensure!(
!host.is_empty() && *port != 0 && !user.is_empty(),
"invalid MySQL endpoint"
);
let password =
fs::read_to_string(password_file).context("read MySQL password file")?;
let mut defaults =
tempfile::NamedTempFile::new().context("create private MySQL options file")?;
writeln!(
defaults,
"[client]\npassword={}",
option_value(password.trim_end_matches(['\r', '\n']))?
)?;
let mut cmd = Command::new(program);
cmd.arg(format!("--defaults-file={}", defaults.path().display()))
.arg("--protocol=TCP")
.arg("--host")
.arg(host)
.arg("--port")
.arg(port.to_string())
.arg("--user")
.arg(user);
let mode = match tls {
MysqlTls::VerifyIdentity => "VERIFY_IDENTITY",
MysqlTls::VerifyIdentityWithCa { ca_file } => {
cmd.arg("--ssl-ca").arg(ca_file);
"VERIFY_IDENTITY"
}
MysqlTls::Required => "REQUIRED",
MysqlTls::Disabled => "DISABLED",
};
cmd.arg(format!("--ssl-mode={mode}"))
.args(args)
.args(["--", database]);
config = Some(defaults);
cmd
}
Self::Ssh {
bastion,
database,
defaults_file,
} => {
validate_database(database)?;
anyhow::ensure!(
defaults_file.starts_with('/') && !defaults_file.contains(['\0', '\r', '\n']),
"invalid remote options path"
);
let mut cmd = bastion.command()?;
let options = shell_arg(&format!("--defaults-file={defaults_file}"));
let database = shell_arg(database);
let args = args
.iter()
.map(|arg| shell_arg(arg))
.collect::<Vec<_>>()
.join(" ");
let command = format!("env -u MYSQL_PWD MYSQL_TEST_LOGIN_FILE=/dev/null {program} {options} {args} -- {database}");
cmd.args(["--", &bastion.host, &command]);
config = None;
cmd
}
};
let output = cmd
.env_remove("MYSQL_PWD")
.env("MYSQL_TEST_LOGIN_FILE", "/dev/null")
.stdin(stdin)
.stderr(Stdio::null())
.stdout(stdout)
.kill_on_drop(true)
.spawn()
.context("start MySQL client")?
.wait_with_output()
.await
.context("wait for MySQL client")?;
drop(config);
anyhow::ensure!(
output.status.success(),
"{program} failed ({})",
output.status
);
Ok(output)
}
}
fn validate_database(database: &str) -> Result<()> {
anyhow::ensure!(
!database.is_empty() && !database.contains(['\0', '\r', '\n']),
"invalid MySQL database name"
);
Ok(())
}
fn option_value(value: &str) -> Result<String> {
anyhow::ensure!(
!value.is_empty() && !value.contains(['\0', '\r', '\n']),
"invalid MySQL password"
);
Ok(format!(
"\"{}\"",
value.replace('\\', "\\\\").replace('"', "\\\"")
))
}
fn shell_arg(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn remote_database_and_options_are_literal_shell_arguments() {
let value = "space 'quote' $(exit 23)";
let script = format!("printf '%s' {}", shell_arg(value));
let result = std::process::Command::new("sh")
.args(["-c", &script])
.output()
.unwrap();
assert!(result.status.success());
assert_eq!(result.stdout, value.as_bytes());
assert!(option_value("secret\n[client]").is_err());
assert_eq!(option_value("a\\b\"#c").unwrap(), "\"a\\\\b\\\"#c\"");
}
}

View File

@@ -0,0 +1,94 @@
use crate::MysqlSource;
use anyhow::{ensure, Result};
use serde::Deserialize;
use std::{
fs::File,
io::{BufRead, BufReader, Seek, SeekFrom, Write},
process::Stdio,
};
use tessera_core::restore::{DatabaseIdentity, Engine};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MysqlRestore {
pub connection: MysqlSource,
#[serde(default)]
pub recreate_database: bool,
#[serde(default)]
pub use_target_definer: bool,
}
impl MysqlRestore {
pub async fn prepare(&self, mut dump: File, expected: &DatabaseIdentity) -> Result<File> {
ensure!(
expected.valid(Engine::Mysql) && expected.database == self.connection.database(),
"MySQL target identity does not match the local profile"
);
ensure!(
!matches!(
expected.database.to_ascii_lowercase().as_str(),
"mysql" | "information_schema" | "performance_schema" | "sys"
),
"system database restore is forbidden"
);
dump.seek(SeekFrom::Start(0))?;
let mut script = tempfile::tempfile()?;
let database = mysql_hex(&expected.database);
let instance = mysql_hex(&expected.instance);
// PREPARE fails before any DDL if this connection resolves to the wrong target.
writeln!(script, "SET @tessera_guard = IF(BINARY LOWER(@@server_uuid) = {instance} AND BINARY DATABASE() = {database}, 'DO 0', 'TESSERA_RESTORE_TARGET_MISMATCH');")?;
writeln!(script, "PREPARE tessera_guard FROM @tessera_guard;\nEXECUTE tessera_guard;\nDEALLOCATE PREPARE tessera_guard;")?;
if self.recreate_database {
let name = format!("`{}`", expected.database.replace('`', "``"));
writeln!(
script,
"DROP DATABASE {name};\nCREATE DATABASE {name} CHARACTER SET utf8mb4;\nUSE {name};"
)?;
}
let use_target_definer = self.use_target_definer;
tokio::task::spawn_blocking(move || {
if use_target_definer {
let definer = regex::bytes::Regex::new(
r"^(CREATE |/\*![0-9]{5} )DEFINER=`(?:[^`]|``)*`@`(?:[^`]|``)*`",
)?;
let mut reader = BufReader::new(dump);
let mut line = Vec::new();
while reader.read_until(b'\n', &mut line)? > 0 {
script.write_all(&definer.replace(&line, &b"${1}DEFINER=CURRENT_USER"[..]))?;
line.clear();
}
} else {
std::io::copy(&mut dump, &mut script)?;
}
script.seek(SeekFrom::Start(0))?;
Ok(script)
})
.await?
}
pub async fn apply(&self, script: File) -> Result<()> {
self.connection
.run(
"mysql",
&[
"--binary-mode",
"--skip-reconnect",
"--skip-force",
"--default-character-set=utf8mb4",
],
Stdio::from(script),
Stdio::null(),
)
.await?;
Ok(())
}
}
fn mysql_hex(value: &str) -> String {
use std::fmt::Write;
let mut literal = String::from("0x");
for byte in value.bytes() {
write!(literal, "{byte:02x}").expect("writing to String cannot fail");
}
literal
}

View File

@@ -1,10 +1,13 @@
use super::{BackupProvider, CaptureResult};
use super::{ssh::loopback_listener, BackupProvider, CaptureResult, SshEndpoint};
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::Stdio;
use tessera_core::config::ProviderKind;
use tessera_core::{config::ProviderKind, restore::DatabaseIdentity};
use tokio::process::Command;
#[derive(Debug, Clone, Deserialize)]
@@ -22,11 +25,347 @@ pub struct PostgresProvider {
config: PostgresConfig,
}
struct PgTarget {
host: String,
port: String,
user: String,
password: String,
dbname: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PostgresSource {
pub host: String,
#[serde(default = "default_port")]
pub port: u16,
pub database: String,
pub user: String,
pub password_file: PathBuf,
#[serde(default)]
pub tls: PostgresTls,
pub bastion: Option<SshEndpoint>,
}
fn default_port() -> u16 {
5432
}
#[derive(Default, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum PostgresTls {
#[default]
VerifyFull,
VerifyFullWithCa {
ca_file: PathBuf,
},
Require,
Disable,
}
impl PostgresSource {
pub async fn dump_to(&self, file: fs::File, format: &str) -> Result<()> {
self.dump_archive(file, format, false).await
}
pub async fn safety_dump_to(&self, file: fs::File) -> Result<()> {
self.dump_archive(file, "custom", true).await
}
async fn dump_archive(
&self,
file: fs::File,
format: &str,
preserve_permissions: bool,
) -> Result<()> {
let mut args = dump_args(format)?;
if !preserve_permissions {
args.extend(["--no-owner".into(), "--no-acl".into()]);
}
self.run(
"pg_dump",
&args,
None,
Stdio::null(),
Stdio::from(file.try_clone()?),
)
.await?;
anyhow::ensure!(file.metadata()?.len() > 0, "pg_dump produced an empty file");
Ok(())
}
pub async fn identity(&self) -> Result<DatabaseIdentity> {
let args = ["-X", "-w", "-At", "-v", "ON_ERROR_STOP=1", "-c",
"SELECT json_build_object('instance', system_identifier::text, 'database', pg_catalog.current_database()) FROM pg_catalog.pg_control_system()"];
let args = args.map(String::from);
let output = self
.run("psql", &args, None, Stdio::null(), Stdio::piped())
.await?;
serde_json::from_slice(&output.stdout).context("invalid PostgreSQL identity")
}
pub(crate) async fn run(
&self,
program: &str,
args: &[String],
database: Option<&str>,
stdin: Stdio,
stdout: Stdio,
) -> Result<std::process::Output> {
let password =
fs::read_to_string(&self.password_file).context("read PostgreSQL password file")?;
let mut target = PgTarget {
host: self.host.clone(),
port: self.port.to_string(),
dbname: database.unwrap_or(&self.database).to_owned(),
user: self.user.clone(),
password: password.trim_end_matches(['\r', '\n']).to_owned(),
};
anyhow::ensure!(
!target.host.contains(',') && self.port != 0,
"invalid PostgreSQL endpoint"
);
let spec = PgProcess {
program,
args,
stdin,
stdout,
};
if let Some(bastion) = &self.bastion {
let listener = loopback_listener().await?;
target.port = listener.local_addr()?.port().to_string();
let forwarding = bastion.forward(listener, &self.host, self.port);
tokio::select! {
result = run_pg(&target, spec, Some((&self.tls, true))) => result,
result = forwarding => { result?; anyhow::bail!("SSH forwarding stopped"); }
}
} else {
run_pg(&target, spec, Some((&self.tls, false))).await
}
}
}
impl PostgresProvider {
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
let config: PostgresConfig = serde_json::from_value(config.clone())?;
parse_postgres_url(&config.connection_url)?;
dump_args(&config.format)?;
Ok(Self { config })
}
pub async fn dump_to(&self, file: fs::File) -> Result<serde_json::Value> {
self.dump(Stdio::from(file.try_clone()?)).await?;
anyhow::ensure!(file.metadata()?.len() > 0, "pg_dump produced an empty file");
Ok(self.restore_hints())
}
async fn dump(&self, stdout: Stdio) -> Result<std::process::Output> {
let target = parse_postgres_url(&self.config.connection_url)?;
let args = dump_args(&self.config.format)?;
run_pg(
&target,
PgProcess {
program: "pg_dump",
args: &args,
stdin: Stdio::null(),
stdout,
},
None,
)
.await
}
fn restore_hints(&self) -> serde_json::Value {
let command = if self.config.format == "plain" {
"psql -d \"$DATABASE_URL\" -f dump.file"
} else {
"pg_restore -d \"$DATABASE_URL\" dump.file"
};
json!({ "format": self.config.format, "restore_command_hint": command })
}
}
fn percent_decode(input: &str) -> Result<String> {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' && index + 2 < bytes.len() {
let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).ok();
if let Some(hex) = hex {
if let Ok(value) = u8::from_str_radix(hex, 16) {
out.push(value);
index += 3;
continue;
}
}
}
out.push(bytes[index]);
index += 1;
}
String::from_utf8(out).context("connection url is not utf-8")
}
fn parse_postgres_url(url: &str) -> Result<PgTarget> {
let rest = url
.strip_prefix("postgres://")
.or_else(|| url.strip_prefix("postgresql://"))
.context("postgres connection_url must start with postgres:// or postgresql://")?;
let (userinfo, hostpart) = rest
.split_once('@')
.context("connection url is missing userinfo")?;
let (user, password) = userinfo
.split_once(':')
.context("connection url is missing a password")?;
let (hostport, dbpath) = hostpart
.split_once('/')
.context("connection url is missing a database")?;
let dbname = dbpath.split('?').next().unwrap_or(dbpath);
let (host, port) = if let Some(host) = hostport.strip_prefix('[') {
let (host, port) = host
.split_once("]:")
.context("ipv6 connection url is missing a port")?;
(host.to_string(), port.to_string())
} else if let Some((host, port)) = hostport.split_once(':') {
(host.to_string(), port.to_string())
} else {
(hostport.to_string(), "5432".into())
};
if host.is_empty() || dbname.is_empty() {
anyhow::bail!("connection url is missing a host or database");
}
Ok(PgTarget {
host,
port,
user: percent_decode(user)?,
password: percent_decode(password)?,
dbname: percent_decode(dbname)?,
})
}
fn escape_pgpass(value: &str) -> String {
value.replace('\\', "\\\\").replace(':', "\\:")
}
struct PgProcess<'a> {
program: &'a str,
args: &'a [String],
stdin: Stdio,
stdout: Stdio,
}
async fn run_pg(
target: &PgTarget,
process: PgProcess<'_>,
tls: Option<(&PostgresTls, bool)>,
) -> Result<std::process::Output> {
let pgpass = write_pgpass(target, tls.is_some())?;
let mut cmd = Command::new(process.program);
if let Some((tls, forwarded)) = tls {
// Local profiles explicitly control the libpq endpoint and TLS policy.
for (name, _) in std::env::vars_os() {
if name.to_string_lossy().starts_with("PG") {
cmd.env_remove(name);
}
}
if forwarded {
cmd.env("PGHOSTADDR", "127.0.0.1");
}
let mode = match tls {
PostgresTls::VerifyFull => "verify-full",
PostgresTls::VerifyFullWithCa { ca_file } => {
cmd.env("PGSSLROOTCERT", ca_file);
"verify-full"
}
PostgresTls::Require => "require",
PostgresTls::Disable => "disable",
};
cmd.env("PGSSLMODE", mode).env("PGGSSENCMODE", "disable");
}
let output = cmd
.args(process.args)
.env("PGPASSFILE", pgpass.path())
.env("PGHOST", &target.host)
.env("PGPORT", &target.port)
.env("PGUSER", &target.user)
.env("PGDATABASE", &target.dbname)
.env_remove("PGPASSWORD")
.stdin(process.stdin)
.stdout(process.stdout)
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.context("starting PostgreSQL client")?
.wait_with_output()
.await
.context("waiting for PostgreSQL client")?;
anyhow::ensure!(
output.status.success(),
"{} failed ({}){}",
process.program,
output.status,
client_reason(&output.stderr)
);
Ok(output)
}
/// The reason a PostgreSQL client gave for failing, reduced to what is safe to report: only the primary
/// `ERROR:`/`FATAL:` lines. `DETAIL`, `CONTEXT`, `LINE`, `STATEMENT` and `HINT` are left out because they
/// quote rows and statements, and the location prefix (`psql:-:1234:`) is not needed. At most two lines.
pub(crate) fn client_reason(stderr: &[u8]) -> String {
let text = String::from_utf8_lossy(stderr);
let lines: Vec<String> = text
.lines()
.filter_map(|line| {
let line = line.trim();
let line = match line.find(": ").filter(|_| line.starts_with("psql:")) {
Some(_) => line.splitn(4, ':').nth(3).unwrap_or(line).trim(),
None => line,
};
let primary = ["ERROR:", "FATAL:", "pg_dump: error:", "pg_restore: error:"]
.iter()
.any(|prefix| line.starts_with(prefix));
primary.then(|| line.to_string())
})
.take(2)
.collect();
if lines.is_empty() {
String::new()
} else {
format!(": {}", lines.join(" | "))
}
}
fn write_pgpass(target: &PgTarget, any_database: bool) -> Result<tempfile::NamedTempFile> {
let fields = [
&target.host,
&target.port,
&target.dbname,
&target.user,
&target.password,
];
anyhow::ensure!(
fields
.iter()
.all(|field| !field.is_empty() && !field.contains(['\n', '\r', '\0'])),
"invalid PostgreSQL connection field"
);
let mut file = tempfile::NamedTempFile::new().context("create pgpass file")?;
let mut fields = fields.map(|value| escape_pgpass(value));
if any_database {
fields[2] = "*".into();
}
let line = fields.join(":");
writeln!(file, "{line}")?;
Ok(file)
}
fn dump_args(format: &str) -> Result<Vec<String>> {
match format {
"custom" => Ok(vec!["-Fc".into(), "-w".into()]),
"plain" => Ok(vec!["-w".into()]),
other => anyhow::bail!("unknown pg format: {other}"),
}
}
#[async_trait]
@@ -36,28 +375,54 @@ impl BackupProvider for PostgresProvider {
}
async fn capture(&self) -> Result<CaptureResult> {
let mut cmd = Command::new("pg_dump");
cmd.arg(&self.config.connection_url);
match self.config.format.as_str() {
"custom" => {
cmd.arg("-Fc");
}
"plain" => {}
other => anyhow::bail!("unknown pg format: {other}"),
}
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let output = cmd.output().await.context("pg_dump failed to start")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("pg_dump failed: {stderr}");
}
let output = self.dump(Stdio::piped()).await?;
Ok(CaptureResult {
payload: output.stdout,
labels: vec!["postgres".into()],
restore_hints: json!({
"format": self.config.format,
"restore_command_hint": "pg_restore -d $DATABASE_URL dump.file"
}),
restore_hints: self.restore_hints(),
})
}
}
#[cfg(test)]
mod tests {
#[test]
fn a_client_failure_names_its_error_without_quoting_data() {
let stderr =
b"psql:-:42: ERROR: duplicate key value violates unique constraint \"users_pkey\"\n\
DETAIL: Key (email)=(alice@example.test) already exists.\n\
CONTEXT: COPY users, line 7: \"7\\talice@example.test\"\n\
psql:-:99: ERROR: schema \"drizzle\" already exists\n";
let reason = client_reason(stderr);
assert_eq!(
reason,
": ERROR: duplicate key value violates unique constraint \"users_pkey\" | ERROR: schema \"drizzle\" already exists"
);
assert!(!reason.contains("alice") && !reason.contains("COPY"));
assert_eq!(client_reason(b""), "");
assert_eq!(client_reason(b"just noise\n"), "");
}
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn pg_dump_keeps_the_url_out_of_argv() {
let target =
parse_postgres_url("postgres://migrator:s%3Acret@example.invalid:5433/billing")
.unwrap();
assert_eq!(target.password, "s:cret");
let args = dump_args("custom").unwrap();
let pgpass = write_pgpass(&target, false).unwrap();
let rendered = fs::read_to_string(pgpass.path()).unwrap();
assert!(rendered.contains("s\\:cret"));
assert!(!args
.iter()
.any(|arg| arg.contains("s:cret") || arg.contains("postgres://")));
let mode = fs::metadata(pgpass.path()).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let joined = args.join(" ");
assert!(!joined.contains(&target.password));
assert!(!joined.contains(&target.user));
}
}

View File

@@ -0,0 +1,897 @@
use crate::PostgresSource;
use anyhow::{ensure, Context, Result};
use serde::Deserialize;
use std::{
fs::{self, File},
io::{self, BufRead, BufReader, Read, Seek, SeekFrom, Write},
path::PathBuf,
process::Stdio,
};
use tessera_core::{
job::CaptureFormat,
restore::{DatabaseIdentity, Engine},
};
use tokio::process::Command;
#[derive(Deserialize)]
#[serde(tag = "reset", rename_all = "snake_case", deny_unknown_fields)]
pub enum PostgresReset {
Schema {
#[serde(default = "public")]
schema: String,
},
/// Empty every non-system schema of the database (not only `public`), in the same transaction as the
/// restore. For databases that keep tables in several schemas, so that a dump's `CREATE SCHEMA` for
/// one of them does not collide with the copy already there. Roles, extensions' own catalog entries,
/// publications and other objects that live outside schemas are left alone.
UserSchemas,
RecreateDatabase,
}
fn public() -> String {
"public".into()
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PostgresRestore {
pub connection: PostgresSource,
pub mode: PostgresReset,
pub post_restore_sql: Option<PathBuf>,
#[serde(default)]
pub omit_transaction_timeout: bool,
#[serde(default)]
pub omit_pg_stat_statements: bool,
}
impl PostgresRestore {
pub async fn prepare(
&self,
mut dump: File,
format: CaptureFormat,
expected: &DatabaseIdentity,
) -> Result<File> {
ensure!(
expected.valid(Engine::Postgres) && expected.database == self.connection.database,
"PostgreSQL target identity does not match the local profile"
);
ensure!(
!matches!(
expected.database.as_str(),
"postgres" | "template0" | "template1"
),
"system database restore is forbidden"
);
let help = Command::new("psql")
.arg("--help=commands")
.kill_on_drop(true)
.output()
.await?;
ensure!(
help.status.success()
&& help
.stdout
.windows(b"\\restrict".len())
.any(|word| word == b"\\restrict"),
"PostgreSQL restore requires a psql client with restricted mode"
);
dump.seek(SeekFrom::Start(0))?;
let mut data = match format {
CaptureFormat::PostgresCustom => {
convert(
dump,
"pg_restore",
&["--no-owner", "--no-privileges", "--file=-"],
)
.await?
}
CaptureFormat::PostgresSql => {
let mut signature = [0; 2];
dump.read_exact(&mut signature)?;
dump.seek(SeekFrom::Start(0))?;
if signature == [0x1f, 0x8b] {
convert(dump, "gzip", &["-dc"]).await?
} else {
dump
}
}
_ => anyhow::bail!("invalid PostgreSQL dump format"),
};
data.seek(SeekFrom::Start(0))?;
let mut script = tempfile::tempfile()?;
writeln!(script, "SET standard_conforming_strings = on;")?;
let instance = literal(&expected.instance);
let database = literal(&expected.database);
match &self.mode {
PostgresReset::Schema { schema } => {
ensure!(
!schema.is_empty()
&& schema.len() <= 63
&& !schema.chars().any(char::is_control)
&& schema != "information_schema"
&& !schema.starts_with("pg_"),
"invalid target schema"
);
writeln!(script, "BEGIN;")?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(
script,
"DROP SCHEMA IF EXISTS {} CASCADE;",
identifier(schema)
)?;
if schema == "public" {
writeln!(script, "CREATE SCHEMA public;")?;
}
}
PostgresReset::UserSchemas => {
writeln!(script, "BEGIN;")?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(
script,
"DO $tessera$\nDECLARE s text;\nBEGIN\n FOR s IN SELECT nspname FROM pg_catalog.pg_namespace\n WHERE nspname !~ '^pg_' AND nspname <> 'information_schema'\n LOOP\n EXECUTE pg_catalog.format('DROP SCHEMA %I CASCADE', s);\n END LOOP;\nEND\n$tessera$;"
)?;
writeln!(script, "CREATE SCHEMA public;")?;
}
PostgresReset::RecreateDatabase => {
ensure!(
expected
.database
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'),
"recreate mode requires an alphanumeric database identifier"
);
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datname = {database}))::int) FROM pg_catalog.pg_control_system();")?;
let name = identifier(&expected.database);
writeln!(
script,
"DROP DATABASE {name};\nCREATE DATABASE {name};\n\\connect {}",
expected.database
)?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(script, "BEGIN;")?;
}
}
// The dump's own CREATE EXTENSION for pg_stat_statements is left out on request, but the reset has
// already dropped the extension the target had. Put it back where it was so its views and functions
// survive; a target that never had it still does not get it.
let preserved = if self.omit_pg_stat_statements {
self.extension_schema("pg_stat_statements").await?
} else {
None
};
let key = uuid::Uuid::new_v4().simple();
writeln!(script, "\\restrict {key}")?;
let skip_timeout = self.omit_transaction_timeout;
let skip_extension = self.omit_pg_stat_statements;
let create_public = match &self.mode {
PostgresReset::Schema { schema } => schema == "public",
PostgresReset::UserSchemas => true,
PostgresReset::RecreateDatabase => false,
};
let post_sql = self.post_restore_sql.clone();
tokio::task::spawn_blocking(move || {
append_dump(
data,
&mut script,
skip_timeout,
skip_extension,
create_public,
)?;
if let Some(schema) = preserved {
script.write_all(keep_extension_sql("pg_stat_statements", &schema).as_bytes())?;
}
if let Some(path) = post_sql {
io::copy(
&mut fs::File::open(path).context("read local post-restore SQL")?,
&mut script,
)?;
}
writeln!(script, "\nCOMMIT;\n\\unrestrict {key}")?;
script.seek(SeekFrom::Start(0))?;
Ok(script)
})
.await?
}
/// The schema an extension is installed in on the target right now, if it is installed.
async fn extension_schema(&self, name: &str) -> Result<Option<String>> {
let query = format!(
"SELECT n.nspname FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = {}",
literal(name)
);
let args = ["-X", "-w", "-q", "-At", "-c"]
.map(String::from)
.into_iter()
.chain([query])
.collect::<Vec<_>>();
let output = self
.connection
.run("psql", &args, None, Stdio::null(), Stdio::piped())
.await?;
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok((!text.is_empty()).then_some(text))
}
pub async fn apply(&self, script: File) -> Result<()> {
let database = match self.mode {
PostgresReset::RecreateDatabase => Some("postgres"),
PostgresReset::Schema { .. } | PostgresReset::UserSchemas => None,
};
// VERBOSITY=terse keeps psql from quoting statements and row data in its errors
let args = [
"-X",
"-w",
"-q",
"-v",
"ON_ERROR_STOP=1",
"-v",
"VERBOSITY=terse",
"-f",
"-",
]
.map(String::from);
self.connection
.run("psql", &args, database, Stdio::from(script), Stdio::null())
.await?;
Ok(())
}
}
/// Statements that bring an extension back in the schema it had, for the end of a restore script.
fn keep_extension_sql(extension: &str, schema: &str) -> String {
let schema = identifier(schema);
format!("CREATE SCHEMA IF NOT EXISTS {schema};\nCREATE EXTENSION IF NOT EXISTS {extension} WITH SCHEMA {schema};\n")
}
fn literal(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
fn identifier(value: &str) -> String {
format!("\"{}\"", value.replace('"', "\"\""))
}
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
let file = tempfile::tempfile()?;
// Read the archive header without moving the offset that the child process will start from.
let header = read_header(&input);
let output = Command::new(executable)
.args(args)
.stdin(Stdio::from(input))
.stdout(Stdio::from(file.try_clone()?))
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.context("prepare PostgreSQL restore script")?
.wait_with_output()
.await
.context("prepare PostgreSQL restore script")?;
if !output.status.success() {
if executable == "pg_restore" {
let local = local_client_version("pg_restore").await;
anyhow::bail!(
"{}",
explain_restore_failure(header.as_ref(), local.as_deref(), &output.stderr)
);
}
anyhow::bail!("{executable} rejected the restore archive");
}
ensure!(
file.metadata()?.len() > 0,
"empty PostgreSQL restore script"
);
Ok(file)
}
/// What pg_dump wrote at the top of a custom-format archive.
#[derive(Debug)]
pub(crate) struct ArchiveHeader {
/// Archive format version, e.g. (1, 16, 0) for pg_dump 17.
pub format: (u8, u8, u8),
/// Version of the pg_dump that made it, e.g. `17.2`.
pub dumped_by: Option<String>,
}
fn read_header(file: &File) -> Option<ArchiveHeader> {
let mut head = vec![0u8; 512];
#[cfg(unix)]
let read = {
use std::os::unix::fs::FileExt;
file.read_at(&mut head, 0).ok()?
};
#[cfg(not(unix))]
let read = {
let _ = file;
0
};
head.truncate(read);
parse_archive_header(&head)
}
/// Parse the start of a custom-format archive. Anything unexpected gives `None`: the header only enriches an
/// error message, so it must never be a reason to fail by itself.
pub(crate) fn parse_archive_header(bytes: &[u8]) -> Option<ArchiveHeader> {
let rest = bytes.strip_prefix(b"PGDMP")?;
let (&major, rest) = rest.split_first()?;
let (&minor, rest) = rest.split_first()?;
let (&revision, rest) = rest.split_first()?;
if major != 1 || minor < 10 || rest.len() < 3 {
return None; // before 1.10 there is no pg_dump version string
}
let (int_size, rest) = (usize::from(rest[0]), &rest[2..]); // integer size, then offset size
if !(1..=8).contains(&int_size) {
return None;
}
let mut cursor = Cursor {
bytes: rest,
int_size,
};
cursor.byte()?; // archive format
if (major, minor) >= (1, 15) {
cursor.byte()?; // compression algorithm
} else {
cursor.int()?; // compression level
}
for _ in 0..7 {
cursor.int()?; // creation time
}
cursor.text()?; // database name
cursor.text()?; // server version
let dumped_by = cursor.text()?;
let version = dumped_by.split(' ').next()?.to_string();
let valid = !version.is_empty()
&& version
.split('.')
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()));
Some(ArchiveHeader {
format: (major, minor, revision),
dumped_by: valid.then_some(version),
})
}
struct Cursor<'a> {
bytes: &'a [u8],
int_size: usize,
}
impl Cursor<'_> {
fn byte(&mut self) -> Option<u8> {
let (&byte, rest) = self.bytes.split_first()?;
self.bytes = rest;
Some(byte)
}
/// pg_dump's integer: a sign byte, then the magnitude, least significant byte first.
fn int(&mut self) -> Option<i64> {
let sign = self.byte()?;
let mut value = 0i64;
for index in 0..self.int_size {
value |= i64::from(self.byte()?) << (8 * index);
}
Some(if sign == 0 { value } else { -value })
}
fn text(&mut self) -> Option<String> {
let length = usize::try_from(self.int()?)
.ok()
.filter(|length| *length <= 256)?;
let (text, rest) = self.bytes.split_at_checked(length)?;
self.bytes = rest;
Some(String::from_utf8_lossy(text).into_owned())
}
}
async fn local_client_version(program: &str) -> Option<String> {
let output = Command::new(program)
.arg("--version")
.kill_on_drop(true)
.output()
.await
.ok()?;
let text = String::from_utf8_lossy(&output.stdout);
// "pg_restore (PostgreSQL) 16.15 (Ubuntu ...)"
text.split_whitespace()
.find(|word| word.chars().next().is_some_and(|c| c.is_ascii_digit()))
.map(str::to_string)
}
fn major_of(version: &str) -> Option<u32> {
version.split('.').next()?.parse().ok()
}
/// A reason that says what to do when the archive was made by a newer pg_dump than the local pg_restore
/// understands, and otherwise passes on what pg_restore itself said.
pub(crate) fn explain_restore_failure(
header: Option<&ArchiveHeader>,
local: Option<&str>,
stderr: &[u8],
) -> String {
let said = crate::postgres::client_reason(stderr);
let newer = header
.and_then(|header| header.dumped_by.as_deref())
.zip(local)
.filter(|(dumped, local)| major_of(dumped) > major_of(local));
match (newer, header) {
(Some((dumped, local)), Some(header)) => format!(
"pg_restore {local} cannot read this archive (made by pg_dump {dumped}, archive format {}.{}): install a PostgreSQL client >= {} on the restore host{said}",
header.format.0,
header.format.1,
major_of(dumped).unwrap_or_default(),
),
_ if !said.is_empty() => format!("pg_restore rejected the restore archive{said}"),
_ => "pg_restore rejected the restore archive".to_string(),
}
}
fn append_dump(
data: File,
script: &mut File,
skip_timeout: bool,
skip_extension: bool,
create_public: bool,
) -> Result<()> {
let mut input = BufReader::new(data);
let mut header = true;
let mut extension_statement = false;
let mut copy_data = false;
let mut line = Vec::new();
while input.read_until(b'\n', &mut line)? > 0 {
let text = line.strip_suffix(b"\n").unwrap_or(&line);
if copy_data {
script.write_all(&line)?;
copy_data = text != b"\\.";
line.clear();
continue;
}
if text.starts_with(b"-- Name: ") {
extension_statement = skip_extension
&& (text.starts_with(b"-- Name: pg_stat_statements; Type: EXTENSION;")
|| text.starts_with(b"-- Name: EXTENSION pg_stat_statements; Type: COMMENT;"));
header = false;
}
// Tessera installs its own restricted-mode key. Archive-generated keys are redundant.
let own_restriction = [b"\\restrict ".as_slice(), b"\\unrestrict ".as_slice()]
.iter()
.any(|prefix| {
text.strip_prefix(*prefix)
.is_some_and(|key| !key.is_empty() && key.iter().all(u8::is_ascii_alphanumeric))
});
let extension = extension_statement
&& (text
.starts_with(b"CREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA ")
|| text.starts_with(b"COMMENT ON EXTENSION pg_stat_statements IS "));
if !text.is_empty() && !text.starts_with(b"--") {
extension_statement = false;
}
if !(own_restriction
|| extension
|| header && skip_timeout && text == b"SET transaction_timeout = 0;")
{
if create_public && text == b"CREATE SCHEMA public;" {
writeln!(script, "CREATE SCHEMA IF NOT EXISTS public;")?;
} else {
script.write_all(&line)?;
}
}
copy_data = text.starts_with(b"COPY ") && text.ends_with(b" FROM stdin;");
line.clear();
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
fn restore(mode: &str) -> PostgresRestore {
serde_json::from_value(serde_json::json!({
"connection": {"host": "127.0.0.1", "port": 5432, "database": "app", "user": "u",
"password_file": "/nonexistent", "tls": {"mode": "disable"}},
"mode": serde_json::from_str::<serde_json::Value>(mode).unwrap(),
}))
.unwrap()
}
async fn script(restore: &PostgresRestore) -> String {
let mut dump = tempfile::tempfile().unwrap();
writeln!(
dump,
"CREATE SCHEMA drizzle;\nCREATE SCHEMA public;\nCREATE TABLE drizzle.t (id int);"
)
.unwrap();
let identity = DatabaseIdentity {
instance: "7300000000000000001".into(),
database: "app".into(),
};
let mut file = restore
.prepare(dump, CaptureFormat::PostgresSql, &identity)
.await
.unwrap();
let mut text = String::new();
file.read_to_string(&mut text).unwrap();
text
}
/// A custom-format archive header the way pg_dump writes it: magic, version, sizes, format, compression,
/// the creation time (seven integers), then database name, server version and pg_dump version.
fn archive_header(major: u8, minor: u8, dumped_by: &str) -> Vec<u8> {
fn int(out: &mut Vec<u8>, value: u32) {
out.push(0); // sign
out.extend(value.to_le_bytes());
}
fn text(out: &mut Vec<u8>, value: &str) {
int(out, value.len() as u32);
out.extend(value.as_bytes());
}
let mut out = b"PGDMP".to_vec();
out.extend([major, minor, 0, 4, 8, 1]);
if (major, minor) >= (1, 15) {
out.push(1); // compression algorithm, one byte since 1.15
} else {
int(&mut out, 0); // compression level as an integer before that
}
for _ in 0..7 {
int(&mut out, 1); // creation time
}
text(&mut out, "app");
text(&mut out, "17.2");
text(&mut out, dumped_by);
out
}
#[test]
fn the_archive_header_names_the_pg_dump_that_made_it() {
for (major, minor, by) in [
(1, 14, "14.20"),
(1, 16, "17.2"),
(1, 15, "16.15 (Ubuntu 16.15-1)"),
] {
let header = parse_archive_header(&archive_header(major, minor, by)).expect("a header");
assert_eq!((header.format.0, header.format.1), (major, minor));
assert_eq!(
header.dumped_by.as_deref(),
Some(by.split(' ').next().unwrap())
);
}
assert!(parse_archive_header(b"-- plain sql").is_none());
assert!(parse_archive_header(b"PGDMP").is_none(), "truncated");
assert!(parse_archive_header(&archive_header(1, 16, "17.2")[..20]).is_none());
}
#[test]
fn a_too_old_pg_restore_says_which_client_to_install() {
let header = parse_archive_header(&archive_header(1, 16, "17.2"));
let reason = explain_restore_failure(
header.as_ref(),
Some("16.15"),
b"pg_restore: error: unsupported version (1.16) in file header\n",
);
assert!(
reason.contains("pg_restore 16.15")
&& reason.contains("pg_dump 17.2")
&& reason.contains(">= 17"),
"{reason}"
);
assert!(
reason.contains("unsupported version (1.16)"),
"the client's own words stay: {reason}"
);
// an unreadable header or an equal version falls back to what pg_restore said
let reason = explain_restore_failure(
None,
Some("16.15"),
b"pg_restore: error: could not read from input file: end of file\n",
);
assert!(
reason.contains("could not read from input file") && !reason.contains("install"),
"{reason}"
);
let same = parse_archive_header(&archive_header(1, 15, "16.9"));
assert!(!explain_restore_failure(same.as_ref(), Some("16.15"), b"").contains("install"));
assert_eq!(
explain_restore_failure(None, None, b""),
"pg_restore rejected the restore archive"
);
}
#[test]
fn an_extension_the_target_had_is_recreated_where_it_lived() {
assert_eq!(
keep_extension_sql("pg_stat_statements", "public"),
"CREATE SCHEMA IF NOT EXISTS \"public\";\nCREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA \"public\";\n"
);
// a schema name cannot break out of its quotes
assert!(keep_extension_sql("pg_stat_statements", "a\"b; DROP").contains("\"a\"\"b; DROP\""));
}
fn psql_with_restricted_mode() -> bool {
std::process::Command::new("psql")
.arg("--help=commands")
.output()
.is_ok_and(|out| String::from_utf8_lossy(&out.stdout).contains("\\restrict"))
}
#[tokio::test]
async fn user_schemas_mode_empties_every_non_system_schema_inside_the_transaction() {
if !psql_with_restricted_mode() {
return;
}
let text = script(&restore(r#"{"reset": "user_schemas"}"#)).await;
let begin = text.find("BEGIN;").unwrap();
let identity_check = text.find("pg_control_system()").unwrap();
let drop_all = text
.find("DROP SCHEMA %I CASCADE")
.expect("drops schemas by name");
let dump = text.find("CREATE SCHEMA drizzle;").unwrap();
assert!(
begin < identity_check && identity_check < drop_all && drop_all < dump,
"{text}"
);
// system schemas are never touched
assert!(
text.contains("nspname !~ '^pg_'") && text.contains("nspname <> 'information_schema'")
);
// public is created once by us; the dump's own CREATE becomes harmless
assert_eq!(text.matches("CREATE SCHEMA public;").count(), 1, "{text}");
assert!(text.contains("CREATE SCHEMA IF NOT EXISTS public;"));
assert!(text.trim_end().contains("COMMIT;"));
}
#[tokio::test]
async fn schema_mode_still_only_drops_the_one_schema() {
if !psql_with_restricted_mode() {
return;
}
let text = script(&restore(r#"{"reset": "schema", "schema": "public"}"#)).await;
assert!(text.contains("DROP SCHEMA IF EXISTS \"public\" CASCADE;"));
assert!(!text.contains("DROP SCHEMA %I"));
}
async fn prepared(restore: &PostgresRestore, dump: &[u8], identity: &DatabaseIdentity) -> File {
let mut file = tempfile::tempfile().unwrap();
file.write_all(dump).unwrap();
restore
.prepare(file, CaptureFormat::PostgresSql, identity)
.await
.unwrap()
}
fn sh(port: &str, db: &str, sql: &str) -> String {
let out = std::process::Command::new("psql")
.args([
"-X",
"-q",
"-At",
"-h",
"127.0.0.1",
"-p",
port,
"-U",
"postgres",
"-d",
db,
"-c",
sql,
])
.env("PGPASSWORD", "pw")
.output()
.unwrap();
assert!(
out.status.success(),
"{sql}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// Needs a throwaway PostgreSQL server (user `postgres`, password `pw`) whose port is in
/// `TESSERA_TEST_PG_PORT`. Run with `--ignored`.
#[tokio::test]
#[ignore]
async fn multi_schema_databases_restore_with_user_schemas_and_fail_readably_without() {
let port = std::env::var("TESSERA_TEST_PG_PORT").expect("TESSERA_TEST_PG_PORT");
let dir = tempfile::tempdir().unwrap();
let password = dir.path().join("pw");
fs::write(&password, "pw\n").unwrap();
for db in ["src_db", "dst_db"] {
sh(&port, "postgres", &format!("DROP DATABASE IF EXISTS {db}"));
sh(&port, "postgres", &format!("CREATE DATABASE {db}"));
}
// the source: public plus a second schema, like an app that keeps its migrations in `drizzle`
sh(&port, "src_db", "CREATE SCHEMA drizzle; CREATE TABLE drizzle.migrations (id int, hash text); INSERT INTO drizzle.migrations VALUES (1, 'a'), (2, 'b'); CREATE TABLE public.users (id int, email text); INSERT INTO public.users VALUES (1, 'alice@example.test')");
// the target: already has `drizzle`, a dev-only table in it, and a stale public table
sh(&port, "dst_db", "CREATE SCHEMA drizzle; CREATE TABLE drizzle.roles (id int); CREATE SCHEMA extra; CREATE TABLE extra.t (id int); CREATE TABLE public.stale (id int)");
let dump = std::process::Command::new("pg_dump")
.args([
"-h",
"127.0.0.1",
"-p",
&port,
"-U",
"postgres",
"-d",
"src_db",
"--no-owner",
"--no-acl",
"-Fp",
])
.env("PGPASSWORD", "pw")
.output()
.unwrap();
assert!(dump.status.success());
let sid = sh(
&port,
"dst_db",
"SELECT system_identifier FROM pg_control_system()",
);
let identity = DatabaseIdentity {
instance: sid,
database: "dst_db".into(),
};
let target = |mode: serde_json::Value| -> PostgresRestore {
serde_json::from_value(serde_json::json!({
"connection": {"host": "127.0.0.1", "port": port.parse::<u16>().unwrap(), "database": "dst_db", "user": "postgres",
"password_file": password, "tls": {"mode": "disable"}},
"mode": mode,
}))
.unwrap()
};
// 1. `schema` mode on a multi-schema database: fails, says why, and changes nothing
let one = target(serde_json::json!({"reset": "schema"}));
let error = one
.apply(prepared(&one, &dump.stdout, &identity).await)
.await
.unwrap_err()
.to_string();
assert!(
error.contains("ERROR:") && error.contains("already exists"),
"{error}"
);
assert!(
!error.contains("alice"),
"no row data in the reason: {error}"
);
assert_eq!(
sh(&port, "dst_db", "SELECT count(*) FROM drizzle.roles"),
"0"
);
assert_eq!(
sh(
&port,
"dst_db",
"SELECT count(*) FROM information_schema.tables WHERE table_name = 'stale'"
),
"1"
);
// 2. `user_schemas` mode: the database becomes the source, nothing of the old target survives
let all = target(serde_json::json!({"reset": "user_schemas"}));
all.apply(prepared(&all, &dump.stdout, &identity).await)
.await
.unwrap();
assert_eq!(
sh(&port, "dst_db", "SELECT count(*) FROM drizzle.migrations"),
"2"
);
assert_eq!(
sh(&port, "dst_db", "SELECT email FROM public.users"),
"alice@example.test"
);
let names = sh(&port, "dst_db", "SELECT string_agg(table_schema || '.' || table_name, ',' ORDER BY 1) FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog','information_schema')");
assert_eq!(names, "drizzle.migrations,public.users");
assert_eq!(
sh(
&port,
"dst_db",
"SELECT count(*) FROM pg_namespace WHERE nspname = 'extra'"
),
"0"
);
// 3. a real custom-format archive: its header names the pg_dump that wrote it
let custom = std::process::Command::new("pg_dump")
.args([
"-h",
"127.0.0.1",
"-p",
&port,
"-U",
"postgres",
"-d",
"src_db",
"-Fc",
])
.env("PGPASSWORD", "pw")
.output()
.unwrap();
let header = parse_archive_header(&custom.stdout).expect("a real archive header parses");
let dumped_by = header.dumped_by.expect("with the pg_dump version");
let server_major = sh(&port, "src_db", "SHOW server_version_num")
.parse::<u32>()
.unwrap()
/ 10000;
assert!(
dumped_by.starts_with(&format!("{server_major}.")),
"{dumped_by}"
);
// 4. pg_stat_statements: kept where the target had it, never added where it had none
for db in ["ext_src", "ext_dst", "ext_none"] {
sh(&port, "postgres", &format!("DROP DATABASE IF EXISTS {db}"));
sh(&port, "postgres", &format!("CREATE DATABASE {db}"));
}
sh(
&port,
"ext_src",
"CREATE EXTENSION pg_stat_statements; CREATE TABLE public.t (id int)",
);
sh(
&port,
"ext_dst",
"CREATE EXTENSION pg_stat_statements; CREATE TABLE public.old (id int)",
);
let ext_dump = std::process::Command::new("pg_dump")
.args([
"-h",
"127.0.0.1",
"-p",
&port,
"-U",
"postgres",
"-d",
"ext_src",
"--no-owner",
"--no-acl",
"-Fp",
])
.env("PGPASSWORD", "pw")
.output()
.unwrap();
for (db, expected) in [("ext_dst", "1"), ("ext_none", "0")] {
let identity = DatabaseIdentity {
instance: sh(
&port,
db,
"SELECT system_identifier FROM pg_control_system()",
),
database: db.into(),
};
let restore: PostgresRestore = serde_json::from_value(serde_json::json!({
"connection": {"host": "127.0.0.1", "port": port.parse::<u16>().unwrap(), "database": db, "user": "postgres",
"password_file": password, "tls": {"mode": "disable"}},
"mode": {"reset": "user_schemas"},
"omit_pg_stat_statements": true,
}))
.unwrap();
restore
.apply(prepared(&restore, &ext_dump.stdout, &identity).await)
.await
.unwrap();
assert_eq!(
sh(
&port,
db,
"SELECT count(*) FROM pg_extension WHERE extname = 'pg_stat_statements'"
),
expected,
"{db}"
);
assert_eq!(
sh(&port, db, "SELECT count(*) FROM public.t"),
"0",
"{db}: the dump's table arrived"
);
}
// the extension's own view works again after the restore (it was not left half-dropped)
// its objects are back too, not just the catalog entry (the view itself needs the server to preload it)
assert_eq!(
sh(
&port,
"ext_dst",
"SELECT count(*) FROM pg_proc WHERE proname = 'pg_stat_statements_reset'"
),
"1"
);
}
}

View File

@@ -0,0 +1,148 @@
use anyhow::{Context, Result};
use serde::Deserialize;
use std::{net::Ipv4Addr, path::PathBuf, process::Stdio};
use tokio::{
io,
net::{TcpListener, TcpStream},
process::Command,
};
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SshEndpoint {
pub host: String,
#[serde(default = "default_port")]
pub port: u16,
pub user: String,
pub identity_file: PathBuf,
pub known_hosts_file: PathBuf,
}
fn default_port() -> u16 {
22
}
fn valid_host(host: &str) -> bool {
!host.is_empty()
&& host
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b".-_:".contains(&b))
}
impl SshEndpoint {
pub(crate) fn command(&self) -> Result<Command> {
anyhow::ensure!(
valid_host(&self.host) && self.port != 0,
"invalid SSH endpoint"
);
anyhow::ensure!(
!self.user.is_empty()
&& self
.user
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)),
"invalid SSH user"
);
anyhow::ensure!(
self.known_hosts_file.is_absolute() && self.identity_file.is_absolute(),
"SSH files require absolute paths"
);
// OpenSSH treats these options as config values and expands tokens in paths.
anyhow::ensure!(
self.known_hosts_file
.to_str()
.is_some_and(|s| !s.contains(['"', '\\', '\n', '\r', '%', '$'])),
"invalid SSH known_hosts path"
);
let mut cmd = Command::new("ssh");
cmd.args([
"-F",
"/dev/null",
"-T",
"-o",
"BatchMode=yes",
"-o",
"IdentitiesOnly=yes",
"-o",
"IdentityAgent=none",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"GlobalKnownHostsFile=/dev/null",
"-o",
"UpdateHostKeys=no",
"-o",
"ConnectTimeout=10",
"-o",
"ServerAliveInterval=10",
"-o",
"ServerAliveCountMax=2",
"-o",
"ForwardAgent=no",
"-o",
"PasswordAuthentication=no",
])
.arg("-o")
.arg(format!(
"UserKnownHostsFile=\"{}\"",
self.known_hosts_file.display()
))
.arg("-i")
.arg(&self.identity_file)
.arg("-p")
.arg(self.port.to_string())
.arg("-l")
.arg(&self.user)
.stderr(Stdio::null())
.kill_on_drop(true);
Ok(cmd)
}
pub(crate) async fn forward(&self, listener: TcpListener, host: &str, port: u16) -> Result<()> {
anyhow::ensure!(valid_host(host), "invalid forwarded host");
let destination = if host.contains(':') {
format!("[{host}]:{port}")
} else {
format!("{host}:{port}")
};
let mut connections = tokio::task::JoinSet::new();
loop {
tokio::select! {
socket = listener.accept(), if connections.len() < 4 => {
let (socket, _) = socket?;
let endpoint = self.clone();
let destination = destination.clone();
connections.spawn(async move { endpoint.forward_connection(socket, &destination).await });
}
completed = connections.join_next(), if !connections.is_empty() => {
// Closing one client connection must not interrupt its replacement.
if let Err(error) = completed.context("missing SSH forwarding task")?? {
tracing::debug!(%error, "SSH forwarding connection closed");
}
}
}
}
}
async fn forward_connection(&self, socket: TcpStream, destination: &str) -> Result<()> {
let mut child = self
.command()?
.args(["-W", destination, "--", &self.host])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.context("start SSH forward")?;
let (mut reader, mut writer) = socket.into_split();
let mut stdin = child.stdin.take().context("SSH stdin missing")?;
let mut stdout = child.stdout.take().context("SSH stdout missing")?;
let send = async move { io::copy(&mut reader, &mut stdin).await };
let receive = async move { io::copy(&mut stdout, &mut writer).await };
tokio::try_join!(send, receive).context("forward database connection")?;
anyhow::ensure!(child.wait().await?.success(), "SSH forwarding failed");
Ok(())
}
}
pub(crate) async fn loopback_listener() -> Result<TcpListener> {
Ok(TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?)
}

View File

@@ -3,12 +3,13 @@ name = "tessera-store"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[dependencies]
tessera-core = { path = "../tessera-core" }
anyhow.workspace = true
aes-gcm.workspace = true
pbkdf2.workspace = true
argon2.workspace = true
hmac.workspace = true
sha2.workspace = true
chrono.workspace = true
@@ -20,5 +21,5 @@ tempfile.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["fs", "io-util"] }
tracing.workspace = true
uuid.workspace = true
uuid = { workspace = true, features = ["v5"] }
walkdir.workspace = true

View File

@@ -1,10 +1,11 @@
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::Aes256Gcm;
use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit};
use anyhow::{anyhow, Result};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use argon2::{Algorithm, Argon2, Params, Version};
use hmac::{Hmac, Mac};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::fs;
use std::path::Path;
@@ -17,25 +18,37 @@ pub struct VaultKey {
}
impl VaultKey {
/// Opens an existing key or creates one. A salt with no `kdf.json` stays
/// PBKDF2 so vaults created before Argon2id still open. A missing salt is a
/// new vault and uses Argon2id.
pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result<Self> {
let salt = if salt_path.exists() {
fs::read(salt_path)?
} else {
let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(salt_path, &salt)?;
salt.to_vec()
};
if passphrase.is_empty() {
anyhow::bail!("vault passphrase is required");
}
let marker = salt_path.with_file_name("kdf.json");
if marker.exists() {
let spec: KdfSpec = serde_json::from_slice(&fs::read(&marker)?)?;
let salt = fs::read(salt_path)?;
restrict_secret_file(salt_path)?;
return derive_marked(passphrase, &salt, &spec);
}
if salt_path.exists() {
restrict_secret_file(salt_path)?;
let salt = fs::read(salt_path)?;
return cipher_from_key(&pbkdf2_key(passphrase, &salt));
}
let mut key = [0u8; 32];
pbkdf2::<Hmac<Sha256>>(passphrase.as_bytes(), &salt, 100_000, &mut key);
let cipher =
Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(Self { cipher })
let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt);
if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(salt_path, salt)?;
restrict_secret_file(salt_path)?;
let spec = KdfSpec::argon2id();
fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?;
restrict_secret_file(&marker)?;
derive_marked(passphrase, &salt, &spec)
}
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
@@ -63,6 +76,100 @@ impl VaultKey {
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
struct KdfSpec {
kdf: String,
#[serde(default = "default_m_kib")]
m_kib: u32,
#[serde(default = "default_t")]
t: u32,
#[serde(default = "default_p")]
p: u32,
}
fn default_m_kib() -> u32 {
19_456
}
fn default_t() -> u32 {
2
}
fn default_p() -> u32 {
1
}
impl KdfSpec {
fn argon2id() -> Self {
Self {
kdf: "argon2id".into(),
m_kib: default_m_kib(),
t: default_t(),
p: default_p(),
}
}
}
fn pbkdf2_key(passphrase: &str, salt: &[u8]) -> [u8; 32] {
pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, 100_000)
}
fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] {
// RFC 8018 PBKDF2-HMAC-SHA256, one block (dkLen = 32). This is the historical
// vault KDF, so existing salt files still open.
type HmacSha256 = Hmac<Sha256>;
let mut block = {
let mut mac =
<HmacSha256 as Mac>::new_from_slice(password).expect("hmac accepts any key length");
mac.update(salt);
mac.update(&1u32.to_be_bytes());
mac.finalize().into_bytes()
};
let mut derived = block;
for _ in 1..iterations {
let mut mac =
<HmacSha256 as Mac>::new_from_slice(password).expect("hmac accepts any key length");
mac.update(&block);
block = mac.finalize().into_bytes();
for (slot, byte) in derived.iter_mut().zip(block.iter()) {
*slot ^= *byte;
}
}
derived.into()
}
fn derive_marked(passphrase: &str, salt: &[u8], spec: &KdfSpec) -> Result<VaultKey> {
let key = match spec.kdf.as_str() {
"argon2id" => {
let params = Params::new(spec.m_kib, spec.t, spec.p, Some(32))
.map_err(|e| anyhow!("argon2 params: {e}"))?;
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let mut key = [0u8; 32];
argon
.hash_password_into(passphrase.as_bytes(), salt, &mut key)
.map_err(|e| anyhow!("argon2id: {e}"))?;
key
}
"pbkdf2" => pbkdf2_key(passphrase, salt),
other => anyhow::bail!("unknown vault kdf: {other}"),
};
cipher_from_key(&key)
}
fn cipher_from_key(key: &[u8; 32]) -> Result<VaultKey> {
let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow!("cipher key: {e}"))?;
Ok(VaultKey { cipher })
}
fn restrict_secret_file(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
pub fn content_id(data: &[u8]) -> String {
use sha2::Digest;
hex::encode(Sha256::digest(data))
@@ -76,6 +183,9 @@ pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf {
#[cfg(test)]
mod tests {
use super::*;
use aes_gcm::aead::generic_array::GenericArray;
use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit};
use tempfile::tempdir;
#[test]
@@ -87,4 +197,63 @@ mod tests {
let plain = key.decrypt(&enc).unwrap();
assert_eq!(plain, b"stardust");
}
#[test]
fn rejects_empty_passphrase() {
let dir = tempdir().unwrap();
let err = VaultKey::derive_from_passphrase("", &dir.path().join("salt"));
assert!(err.is_err());
}
#[cfg(unix)]
#[test]
fn salt_file_is_owner_only() {
use std::os::unix::fs::PermissionsExt;
let dir = tempdir().unwrap();
let salt = dir.path().join("salt");
VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let mode = fs::metadata(&salt).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
#[test]
fn new_vault_uses_argon2id() {
let dir = tempdir().unwrap();
let salt = dir.path().join("tessera.salt");
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
let marker: serde_json::Value =
serde_json::from_slice(&fs::read(dir.path().join("kdf.json")).unwrap()).unwrap();
assert_eq!(marker["kdf"], "argon2id");
let enc = key.encrypt(b"stardust").unwrap();
let raw_salt = fs::read(&salt).unwrap();
let legacy = pbkdf2_key("test-vault", &raw_salt);
let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap();
let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]);
assert!(legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).is_err());
assert_eq!(key.decrypt(&enc).unwrap(), b"stardust");
}
#[test]
fn pbkdf2_matches_the_rfc_vector() {
let key = super::pbkdf2_hmac_sha256(b"password", b"salt", 4096);
assert_eq!(
hex::encode(key),
"c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a"
);
}
#[test]
fn existing_pbkdf2_salt_still_opens() {
let dir = tempdir().unwrap();
let salt = dir.path().join("tessera.salt");
fs::write(&salt, b"0123456789abcdef").unwrap();
let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap();
assert!(!dir.path().join("kdf.json").exists());
let enc = key.encrypt(b"legacy").unwrap();
let legacy = pbkdf2_key("test-vault", b"0123456789abcdef");
let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap();
let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]);
let plain = legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).unwrap();
assert_eq!(plain, b"legacy");
}
}

View File

@@ -1,17 +1,16 @@
//! Restic-compatible path layout vault engine.
//! Encrypted snapshot metadata and Restic-backed storage for new captures.
//!
//! Layout under vault root:
//! - `config` — repository version marker (restic-compatible sentinel)
//! - `data/` — content-addressed encrypted packs (`{prefix}/{id}`)
//! - `snapshots/` — JSON snapshot metadata
//! - `index/` — chunk index shards
//! - `keys/` — key material (local key file)
//!
//! Full `rustic_core` integration is deferred until toolchain meets its MSRV;
//! emergency verify may use external `rustic`/`restic` where formats align.
//! - `restic/` and `outposts/` — Restic repositories
//! - `snapshots/` — Tessera snapshot metadata
//! - `keys/` — vault key derivation and outpost configuration
//! - `config`, `data/`, `index/` — legacy Tessera storage
mod crypto;
mod index;
mod offsite;
mod restic;
mod vault;
pub use offsite::{Offsite, OffsiteCopy};
pub use vault::*;

View File

@@ -0,0 +1,375 @@
use crate::restic;
use anyhow::{ensure, Context, Result};
use std::{
fs,
io::Write,
path::{Path, PathBuf},
process::{Output, Stdio},
time::Duration,
};
use tokio::process::Command;
use uuid::Uuid;
/// Wall-clock limits per restic call. A WAN object store answers in under a second most of the time and
/// in well over ten seconds some of the time, so these are sized for the slow case.
#[derive(Clone, Copy)]
struct Limits {
probe: u64,
list: u64,
init: u64,
copy: u64,
}
const LIMITS: Limits = Limits {
probe: 120,
list: 120,
init: 90,
copy: 3600,
};
/// A listing that times out is retried this many times before the copy is called failed.
const VERIFY_ATTEMPTS: usize = 3;
pub struct Offsite {
repo: restic::Repository,
limits: Limits,
}
pub struct OffsiteCopy {
pub(crate) snapshot: Uuid,
pub(crate) source: restic::Repository,
pub(crate) restic_id: String,
}
impl Offsite {
pub fn new(repository: &str, password_file: &Path) -> Result<Self> {
let location = repository
.strip_prefix("s3:https://")
.or_else(|| {
repository
.strip_prefix("s3:http://")
.filter(|rest| rest.starts_with("127.0.0.1:"))
})
.context("off-site repository requires an S3 HTTPS endpoint")?;
let parts: Vec<_> = location.splitn(3, '/').collect();
ensure!(
parts.len() == 3
&& parts.iter().all(|part| !part.is_empty())
&& !repository.contains(['@', '?', '#', '\n', '\r']),
"use a dedicated S3 bucket prefix without embedded credentials"
);
let password =
fs::read_to_string(password_file).context("read off-site Restic password")?;
let password = password.trim_end_matches(['\r', '\n']);
ensure!(!password.is_empty(), "off-site Restic password is empty");
Ok(Self {
repo: restic::Repository {
path: PathBuf::from(repository),
password: password.into(),
},
limits: LIMITS,
})
}
fn command(&self) -> Command {
let mut command = Command::from(self.repo.command());
command
.args(["-o", "s3.retries=3", "--stuck-request-timeout=60s"])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
command
}
async fn copy_from(&self, source: &restic::Repository, id: &str) -> Result<()> {
restic::validate_id(id)?;
let mut password = tempfile::NamedTempFile::new()?;
writeln!(password, "{}", source.password)?;
let probe = run(
self.command().args(["snapshots", "--json"]),
self.limits.probe,
)
.await?;
if probe.status.code() == Some(10) {
safe(
run(self.command().arg("init"), self.limits.init).await?,
"init",
)?;
} else {
safe(probe, "probe")?;
}
safe(
run(
self.command()
.env_remove("RESTIC_FROM_PASSWORD")
.env_remove("RESTIC_FROM_PASSWORD_COMMAND")
.env_remove("RESTIC_FROM_REPOSITORY_FILE")
.env_remove("RESTIC_FROM_KEY_HINT")
.arg("copy")
.arg("--from-repo")
.arg(&source.path)
.arg("--from-password-file")
.arg(password.path())
.arg(id),
self.limits.copy,
)
.await?,
"copy",
)?;
Ok(())
}
/// The restic id of the copy tagged for this snapshot, `None` when there is none (or no repository yet).
async fn tagged_snapshot(&self, snapshot: Uuid) -> Result<Option<String>> {
#[derive(serde::Deserialize)]
struct Copy {
id: String,
}
let output = run(
self.command().args([
"snapshots",
"--json",
"--tag",
&restic::tessera_tag(snapshot),
]),
self.limits.list,
)
.await?;
// Exit code 10: the repository does not exist yet, so nothing has been copied.
if output.status.code() == Some(10) {
return Ok(None);
}
let output = safe(output, "list")?;
let mut snapshots: Vec<Copy> = serde_json::from_slice(&output.stdout)?;
Ok(snapshots.pop().map(|copy| copy.id))
}
/// `tagged_snapshot` with retries: a slow listing must not turn a finished copy into a failed one.
async fn tagged_snapshot_retrying(&self, snapshot: Uuid) -> Result<Option<String>> {
retry(VERIFY_ATTEMPTS, &[2, 5], || self.tagged_snapshot(snapshot)).await
}
pub async fn restore(&self, snapshot: Uuid, dest: &Path) -> Result<u64> {
let id = self
.tagged_snapshot(snapshot)
.await?
.context("snapshot not found in off-site repository")?;
restic::validate_id(&id)?;
let parent = dest
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
let file = tempfile::NamedTempFile::new_in(parent)?;
safe(
run(
self.command()
.args(["dump", &id, restic::PAYLOAD])
.stdout(Stdio::from(file.reopen()?)),
3600,
)
.await?,
"dump",
)?;
let size = file.as_file().metadata()?.len();
file.as_file().sync_all()?;
file.persist_noclobber(dest)?;
Ok(size)
}
pub async fn copy_capture(&self, copy: OffsiteCopy) -> Result<()> {
// A copy is complete once its tagged snapshot exists (restic writes the snapshot last), so an earlier
// attempt that finished but could not be confirmed is simply accepted instead of copied again.
if self
.tagged_snapshot_retrying(copy.snapshot)
.await?
.is_some()
{
return Ok(());
}
self.copy_from(&copy.source, &copy.restic_id).await?;
ensure!(
self.tagged_snapshot_retrying(copy.snapshot)
.await?
.is_some(),
"off-site snapshot tag not found after copy"
);
Ok(())
}
}
async fn run(command: &mut Command, seconds: u64) -> Result<Output> {
let result = tokio::time::timeout(
Duration::from_secs(seconds),
command.spawn()?.wait_with_output(),
)
.await
.with_context(|| format!("off-site Restic operation timed out after {seconds}s"))??;
Ok(result)
}
fn safe(output: Output, step: &str) -> Result<Output> {
ensure!(
output.status.success(),
"off-site Restic {step} failed ({}){}",
output.status,
stderr_tail(&output.stderr)
);
Ok(output)
}
/// The end of restic's error output, on one line, so a failure says why. Restic never prints the
/// repository password or S3 keys (they travel in the environment).
fn stderr_tail(stderr: &[u8]) -> String {
let text = String::from_utf8_lossy(stderr);
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
if text.is_empty() {
return String::new();
}
let start = text
.char_indices()
.rev()
.nth(299)
.map_or(0, |(index, _)| index);
format!(": {}", &text[start..])
}
async fn retry<T, F, Fut>(attempts: usize, delays: &[u64], mut attempt: F) -> Result<T>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
let mut tries = 0;
loop {
match attempt().await {
Ok(value) => return Ok(value),
Err(error) => {
tries += 1;
if tries >= attempts {
return Err(error);
}
let wait = delays
.get(tries - 1)
.or(delays.last())
.copied()
.unwrap_or(0);
tokio::time::sleep(Duration::from_secs(wait)).await;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[tokio::test]
async fn a_slow_listing_is_retried_until_it_answers() {
let calls = AtomicUsize::new(0);
let value = retry(3, &[0], || async {
if calls.fetch_add(1, Ordering::SeqCst) < 2 {
anyhow::bail!("timed out")
}
Ok(7)
})
.await
.unwrap();
assert_eq!((value, calls.load(Ordering::SeqCst)), (7, 3));
}
#[tokio::test]
async fn retries_stop_and_report_the_last_error() {
let calls = AtomicUsize::new(0);
let error = retry::<(), _, _>(3, &[0], || async {
calls.fetch_add(1, Ordering::SeqCst);
anyhow::bail!("still down")
})
.await
.unwrap_err();
assert_eq!(
(error.to_string(), calls.load(Ordering::SeqCst)),
("still down".into(), 3)
);
}
#[test]
fn a_failure_names_its_reason_without_dumping_the_output() {
let long = "x".repeat(2000);
let tail = stderr_tail(format!("line one\n {long} end").as_bytes());
assert!(tail.starts_with(": ") && tail.ends_with(" end") && tail.len() <= 304);
assert_eq!(stderr_tail(b""), "");
}
fn restic_available() -> bool {
std::process::Command::new("restic")
.arg("version")
.output()
.is_ok_and(|out| out.status.success())
}
/// Real restic, local directories standing in for the object store: an absent destination repository is
/// created and filled, and an already-copied snapshot is accepted without touching the source again.
#[tokio::test]
async fn a_finished_copy_is_confirmed_and_not_copied_twice() {
if !restic_available() {
return;
}
let dir = tempfile::tempdir().unwrap();
let source = restic::Repository {
path: dir.path().join("source"),
password: "source-pass".into(),
};
fs::create_dir(&source.path).unwrap();
let init = source.command().arg("init").output().unwrap();
assert!(init.status.success());
let data = dir.path().join("payload");
fs::write(&data, b"synthetic dump").unwrap();
let snapshot = Uuid::new_v4();
let backup = source
.command()
.args(["backup", "--tag", &restic::tessera_tag(snapshot)])
.arg(&data)
.output()
.unwrap();
assert!(backup.status.success());
let listing = source
.command()
.args(["snapshots", "--json"])
.output()
.unwrap();
let id = serde_json::from_slice::<Vec<serde_json::Value>>(&listing.stdout).unwrap()[0]
["id"]
.as_str()
.unwrap()
.to_string();
let offsite = Offsite {
repo: restic::Repository {
path: dir.path().join("offsite"),
password: "offsite-pass".into(),
},
limits: LIMITS,
};
let copy = |source: &restic::Repository| OffsiteCopy {
snapshot,
source: restic::Repository {
path: source.path.clone(),
password: source.password.clone(),
},
restic_id: id.clone(),
};
offsite.copy_capture(copy(&source)).await.unwrap();
assert!(offsite.tagged_snapshot(snapshot).await.unwrap().is_some());
fs::remove_dir_all(&source.path).unwrap();
offsite
.copy_capture(copy(&source))
.await
.expect("an existing tagged copy needs no source");
let other = Uuid::new_v4();
let mut missing = copy(&source);
missing.snapshot = other;
let error = offsite.copy_capture(missing).await.unwrap_err();
assert!(format!("{error:#}").contains("copy failed"), "{error:#}");
}
}

View File

@@ -0,0 +1,196 @@
use anyhow::{ensure, Context, Result};
use serde::Deserialize;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
pub(crate) const PREFIX: &str = "restic:";
pub(crate) const OUTPOST_PREFIX: &str = "restic-outpost:";
pub(crate) const PAYLOAD: &str = "/payload";
pub(crate) fn tessera_tag(snapshot: uuid::Uuid) -> String {
format!("tessera-{snapshot}")
}
#[derive(Clone)]
pub(crate) struct Repository {
pub path: PathBuf,
pub password: String,
}
#[derive(Deserialize)]
pub(crate) struct Summary {
pub snapshot_id: Option<String>,
pub total_bytes_processed: u64,
pub data_added_packed: u64,
pub data_blobs: u64,
}
#[derive(Deserialize)]
struct Snapshot {
id: String,
summary: Option<Summary>,
#[serde(default)]
tags: Vec<String>,
#[serde(default)]
paths: Vec<String>,
}
impl Repository {
pub fn command(&self) -> Command {
self.command_at(&self.path)
}
fn command_at(&self, path: &Path) -> Command {
let mut cmd = Command::new("restic");
cmd.arg("--repo")
.arg(path)
.arg("--no-cache")
.env("RESTIC_PASSWORD", &self.password)
.env_remove("RESTIC_PASSWORD_FILE")
.env_remove("RESTIC_PASSWORD_COMMAND")
.env_remove("RESTIC_REPOSITORY_FILE")
.env_remove("RESTIC_KEY_HINT")
.env_remove("RESTIC_CACERT")
.env_remove("RESTIC_TLS_CLIENT_CERT")
.stdin(Stdio::null());
cmd
}
pub fn init(&self) -> Result<()> {
if self.path.join("config").try_exists()? {
return Ok(());
}
let temp = tempfile::tempdir_in(self.path.parent().context("repository parent")?)?;
checked(
self.command_at(temp.path())
.arg("init")
.output()
.context("starting restic init")?,
"init",
)?;
match fs::rename(temp.path(), &self.path) {
Ok(()) => Ok(()),
Err(_) if self.path.join("config").try_exists()? => Ok(()),
Err(err) => Err(err).context("publishing the restic repository"),
}
}
pub fn backup(&self, mut cmd: Command) -> Result<Summary> {
let output = cmd
.output()
.context("starting restic backup (install restic on PATH)")?;
let summary = std::str::from_utf8(&output.stdout)?
.lines()
.last()
.and_then(|line| serde_json::from_str::<Summary>(line).ok());
if !output.status.success() {
// Restic can commit an incomplete snapshot on exit 3. Tessera never publishes it.
if let Some(id) = summary.as_ref().and_then(|s| s.snapshot_id.as_deref()) {
if let Err(error) = self.forget(&[id.to_owned()]) {
tracing::warn!(%error, "could not remove incomplete restic snapshot");
}
}
}
checked(output, "backup")?;
summary.context("restic did not report a backup summary")
}
pub fn dump(&self, id: &str, path: &str, file: File) -> Result<()> {
validate_id(id)?;
let output = self
.command()
.args(["dump", id, path])
.stdout(file)
.output()?;
checked(output, "dump")?;
Ok(())
}
pub fn forget(&self, ids: &[String]) -> Result<()> {
if ids.is_empty() {
return Ok(());
}
for id in ids {
validate_id(id)?;
}
checked(self.command().arg("forget").args(ids).output()?, "forget")?;
Ok(())
}
pub fn snapshot_summary(
&self,
id: &str,
tag: Option<&str>,
expected_path: Option<&str>,
) -> Result<Summary> {
validate_id(id)?;
let output = checked(
self.command().args(["snapshots", "--json", id]).output()?,
"snapshots",
)?;
let snapshots: Vec<Snapshot> = serde_json::from_slice(&output.stdout)?;
snapshots
.into_iter()
.find(|snap| {
snap.id == id
&& tag.is_none_or(|tag| snap.tags.iter().any(|value| value == tag))
&& expected_path.is_none_or(|path| snap.paths == [path])
})
.and_then(|snap| snap.summary)
.context("outpost snapshot or backup summary is missing")
}
pub fn prune(&self, expired: &[String]) -> Result<()> {
if !self.path.exists() {
ensure!(expired.is_empty(), "restic repository is missing");
return Ok(());
}
let output = checked(
self.command().args(["snapshots", "--json"]).output()?,
"snapshots",
)?;
let snapshots: Vec<Snapshot> = serde_json::from_slice(&output.stdout)?;
let ids = snapshots
.into_iter()
.map(|snap| snap.id)
.collect::<std::collections::HashSet<_>>();
let existing: Vec<_> = expired
.iter()
.filter(|id| ids.contains(*id))
.cloned()
.collect();
self.forget(&existing)?;
checked(self.command().arg("prune").output()?, "prune")?;
Ok(())
}
}
pub(crate) fn validate_id(id: &str) -> Result<()> {
ensure!(
id.len() == 64 && id.bytes().all(|b| b.is_ascii_hexdigit()),
"invalid restic snapshot ID"
);
Ok(())
}
fn checked(output: Output, action: &str) -> Result<Output> {
ensure!(
output.status.success(),
"restic {action} failed ({}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
);
Ok(output)
}
pub(crate) fn literal_pattern(path: &Path) -> Result<String> {
let mut pattern = String::new();
for c in path.to_str().context("vault path must be UTF-8")?.chars() {
if matches!(c, '\\' | '[' | ']' | '*' | '?') {
pattern.push('\\');
}
pattern.push(c);
}
Ok(pattern)
}

View File

@@ -1,15 +1,21 @@
use crate::crypto::{content_id, pack_path, VaultKey};
use crate::index::ChunkIndex;
use crate::restic::{self, Repository};
use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs;
use std::fs::{self, File};
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use tessera_core::decay::{evaluate_decay, DecayPolicy, SnapshotRef};
use std::process::{Command, Stdio};
use tessera_core::decay::{
evaluate_decay, evaluate_gfs, DecayPolicy, RetentionPolicy, SnapshotRef,
};
use tessera_core::manifest::SnapshotManifest;
use uuid::Uuid;
const RESTIC_CONFIG: &str = "{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n";
const RESTIC_CONFIG: &str =
"{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredSnapshot {
@@ -18,21 +24,45 @@ pub struct StoredSnapshot {
pub manifest: SnapshotManifest,
pub size_bytes: u64,
pub tree_root: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stored_bytes: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub new_data_chunks: Option<u64>,
}
pub struct Vault {
root: PathBuf,
key: VaultKey,
index: ChunkIndex,
restic: Repository,
}
#[derive(Deserialize)]
struct OutpostRepository {
outpost_id: Uuid,
password: String,
}
/// Shortest passphrase accepted for a new vault. Existing vaults keep opening with a warning.
pub const MIN_PASSPHRASE_CHARS: usize = 16;
impl Vault {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
if passphrase == "dev-vault-key" {
anyhow::bail!(
"refusing to initialize a vault with the published dev passphrase; choose a private passphrase"
);
}
anyhow::ensure!(
passphrase.chars().count() >= MIN_PASSPHRASE_CHARS,
"the vault passphrase must be at least {MIN_PASSPHRASE_CHARS} characters"
);
let root = root.as_ref().to_path_buf();
fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?;
fs::create_dir_all(root.join("index"))?;
fs::create_dir_all(root.join("keys"))?;
restrict_dir(&root.join("keys"))?;
let config_path = root.join("config");
if !config_path.exists() {
@@ -43,6 +73,7 @@ impl Vault {
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = ChunkIndex::default();
let v = Self {
restic: Self::repository(&root, passphrase)?,
root,
key,
index,
@@ -56,16 +87,377 @@ impl Vault {
if !root.join("config").exists() {
anyhow::bail!("vault not initialized");
}
restrict_dir(&root.join("keys"))?;
// Not refused: that would lock existing deployments out of their own backups.
if passphrase == "dev-vault-key" {
tracing::warn!(
"this vault uses the published dev passphrase; rotate it to a private one"
);
} else if passphrase.chars().count() < MIN_PASSPHRASE_CHARS {
tracing::warn!(
"the vault passphrase is shorter than {MIN_PASSPHRASE_CHARS} characters; a new vault would refuse it"
);
}
let salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?;
Ok(Self {
restic: Self::repository(&root, passphrase)?,
root,
key,
index,
})
}
fn repository(root: &Path, password: &str) -> Result<Repository> {
Ok(Repository {
path: root.canonicalize()?.join("restic"),
password: password.into(),
})
}
fn outpost_config_path(&self, orbit_id: Uuid) -> PathBuf {
self.root
.join("keys")
.join(format!("outpost-{orbit_id}.json"))
}
pub fn outpost_repository_configured(&self, orbit_id: Uuid) -> Result<bool> {
Ok(self.outpost_config_path(orbit_id).try_exists()?)
}
fn outpost_config(&self, orbit_id: Uuid) -> Result<OutpostRepository> {
Ok(serde_json::from_slice(
&fs::read(self.outpost_config_path(orbit_id))
.context("outpost repository is not configured")?,
)?)
}
fn outpost_repository(&self, orbit_id: Uuid, config: OutpostRepository) -> Repository {
Repository {
path: self
.restic
.path
.with_file_name("outposts")
.join(orbit_id.to_string()),
password: config.password,
}
}
pub fn register_outpost_snapshot(
&mut self,
mut manifest: SnapshotManifest,
outpost_id: Uuid,
restic_id: &str,
) -> Result<Option<(Uuid, bool)>> {
restic::validate_id(restic_id)?;
if !self.outpost_repository_configured(manifest.orbit_id)? {
return Ok(None);
}
let config = self.outpost_config(manifest.orbit_id)?;
if config.outpost_id != outpost_id {
return Ok(None);
}
let id = Uuid::new_v5(&manifest.orbit_id, restic_id.as_bytes());
let dir = self.root.join("snapshots");
if dir.join(format!("{id}.json.enc")).try_exists()?
|| dir.join(format!("{id}.expired")).try_exists()?
{
return Ok(Some((id, false)));
}
let repo = self.outpost_repository(manifest.orbit_id, config);
let summary = repo.snapshot_summary(restic_id, None, None)?;
manifest.snapshot_id = id;
manifest.restore_hints = serde_json::json!({ "format": "tar" });
self.write_snapshot(
&StoredSnapshot {
id,
taken_at: Utc::now(),
manifest,
size_bytes: summary.total_bytes_processed,
tree_root: format!("{}{restic_id}", restic::OUTPOST_PREFIX),
stored_bytes: Some(summary.data_added_packed),
new_data_chunks: Some(summary.data_blobs),
},
false,
)?;
Ok(Some((id, true)))
}
pub fn prepare_outpost_capture(
&self,
manifest: SnapshotManifest,
outpost_id: Uuid,
restic_id: &str,
) -> Result<StoredSnapshot> {
let config = self.outpost_config(manifest.orbit_id)?;
anyhow::ensure!(
config.outpost_id == outpost_id,
"repository belongs to another outpost"
);
let repo = self.outpost_repository(manifest.orbit_id, config);
let id = manifest.snapshot_id;
let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD);
let summary =
repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?;
Ok(StoredSnapshot {
id,
taken_at: Utc::now(),
manifest,
size_bytes: summary.total_bytes_processed,
tree_root: format!("{}{restic_id}", restic::OUTPOST_PREFIX),
stored_bytes: Some(summary.data_added_packed),
new_data_chunks: Some(summary.data_blobs),
})
}
pub fn snapshot_files(
&self,
mut manifest: SnapshotManifest,
max_file_bytes: Option<u64>,
dry_run: bool,
) -> Result<StoredSnapshot> {
let vault = self.root.canonicalize()?;
anyhow::ensure!(!manifest.paths.is_empty(), "no filesystem paths to back up");
let paths = manifest
.paths
.iter()
.map(|name| {
let path = Path::new(name);
let canonical = path
.canonicalize()
.with_context(|| format!("backup source {name}"))?;
anyhow::ensure!(
!canonical.starts_with(&vault),
"backup source is inside the Tessera vault"
);
if let Some(max) = max_file_bytes {
let metadata = fs::metadata(path)?;
anyhow::ensure!(
!metadata.is_file() || metadata.len() <= max,
"file exceeds max_file_bytes: {name}"
);
}
// Preserve a final symlink, while resolving aliases in its parent for vault exclusion.
let path = if fs::symlink_metadata(path)?.is_symlink() {
path.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."))
.canonicalize()?
.join(path.file_name().context("symlink name")?)
} else {
canonical
};
Ok(path)
})
.collect::<Result<Vec<_>>>()?;
manifest.restore_hints = serde_json::json!({ "format": "tar" });
let exclude = restic::literal_pattern(&vault)?;
self.restic_snapshot(manifest, dry_run, |cmd| {
cmd.args(["--exclude", &exclude]);
if let Some(max) = max_file_bytes {
cmd.arg("--exclude-larger-than").arg(max.to_string());
}
cmd.arg("--").args(paths);
})
}
pub fn snapshot_payload(
&self,
manifest: SnapshotManifest,
payload: File,
dry_run: bool,
) -> Result<StoredSnapshot> {
let snap = self.prepare_payload(manifest, payload, dry_run)?;
if !dry_run {
self.publish_prepared(&snap)?;
}
Ok(snap)
}
pub fn prepare_payload(
&self,
manifest: SnapshotManifest,
mut payload: File,
dry_run: bool,
) -> Result<StoredSnapshot> {
if payload.metadata()?.len() == 0 {
// Restic rejects empty stdin. A relative filename keeps the same restore path.
let temp = tempfile::tempdir()?;
File::create(temp.path().join("payload"))?;
return self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
cmd.current_dir(temp.path())
.args(["--force", "--", "payload"]);
});
}
payload.seek(SeekFrom::Start(0))?;
self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
cmd.args(["--stdin", "--stdin-filename", restic::PAYLOAD])
.stdin(Stdio::from(payload));
})
}
fn restic_snapshot(
&self,
manifest: SnapshotManifest,
dry_run: bool,
source: impl FnOnce(&mut Command),
) -> Result<StoredSnapshot> {
let snap = self.prepare_restic_snapshot(manifest, dry_run, source)?;
if !dry_run {
self.publish_prepared(&snap)?;
}
Ok(snap)
}
fn prepare_restic_snapshot(
&self,
manifest: SnapshotManifest,
dry_run: bool,
source: impl FnOnce(&mut Command),
) -> Result<StoredSnapshot> {
let taken_at = Utc::now();
let temp;
let rehearsal;
let repo = if dry_run && !self.restic.path.join("config").try_exists()? {
temp = tempfile::tempdir()?;
rehearsal = Repository {
path: temp.path().join("repo"),
password: self.restic.password.clone(),
};
&rehearsal
} else {
&self.restic
};
repo.init()
.context("opening the deduplicated vault (restic must be on PATH)")?;
let mut cmd = repo.command();
cmd.args([
"backup",
"--json",
"--quiet",
"--tag",
&restic::tessera_tag(manifest.snapshot_id),
]);
if dry_run {
cmd.arg("--dry-run");
}
source(&mut cmd);
let summary = repo.backup(cmd)?;
let tree_root = if dry_run {
"dry-run".into()
} else {
let id = summary
.snapshot_id
.as_deref()
.context("restic did not commit a snapshot")?;
restic::validate_id(id)?;
format!("{}{id}", restic::PREFIX)
};
let snap = StoredSnapshot {
id: manifest.snapshot_id,
taken_at,
manifest,
size_bytes: summary.total_bytes_processed,
tree_root,
stored_bytes: Some(summary.data_added_packed),
new_data_chunks: Some(summary.data_blobs),
};
Ok(snap)
}
pub fn import_legacy_payload(
&self,
manifest: SnapshotManifest,
payload: File,
taken_at: chrono::DateTime<Utc>,
) -> Result<bool> {
let id = manifest.snapshot_id;
let receipts = self.root.join("keys/legacy-imports");
fs::create_dir_all(&receipts)?;
restrict_dir(&receipts)?;
let receipt = receipts.join(id.to_string());
if receipt.try_exists()? {
return Ok(false);
}
let snapshots = self.root.join("snapshots");
let already_imported = || -> Result<bool> {
Ok(self.has_published_snapshot(id)?
|| snapshots.join(format!("{id}.expired")).try_exists()?)
};
let imported = if already_imported()? {
false
} else {
let mut prepared = self.prepare_payload(manifest, payload, false)?;
prepared.taken_at = taken_at;
match self.publish_prepared(&prepared) {
Ok(()) => true,
Err(_) if already_imported()? => {
self.discard_prepared(&prepared)?;
false
}
Err(error) => return Err(error),
}
};
let marker = tempfile::NamedTempFile::new_in(&receipts)?;
marker.as_file().sync_all()?;
match marker.persist_noclobber(&receipt) {
Ok(_) => sync_directory(&receipts)?,
Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => (),
Err(error) => return Err(error.into()),
}
Ok(imported)
}
pub fn legacy_import_exists(&self, id: Uuid) -> Result<bool> {
Ok(self
.root
.join("keys/legacy-imports")
.join(id.to_string())
.try_exists()?)
}
pub fn verify_prepared_payload(
&self,
snap: &StoredSnapshot,
expected: &[u8; 32],
) -> Result<()> {
use sha2::{Digest, Sha256};
let id = snap
.tree_root
.strip_prefix(restic::PREFIX)
.context("prepared payload is missing")?;
let mut file = tempfile::tempfile()?;
self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?;
file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
std::io::copy(&mut file, &mut digest)?;
anyhow::ensure!(
digest.finalize()[..] == expected[..],
"stored payload checksum mismatch"
);
Ok(())
}
pub fn publish_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
self.write_snapshot(snap, false)
}
pub fn discard_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
self.restic.forget(&[id.to_owned()])?;
}
Ok(())
}
pub fn has_published_snapshot(&self, id: Uuid) -> Result<bool> {
Ok(self
.root
.join("snapshots")
.join(format!("{id}.json.enc"))
.try_exists()?)
}
fn index_path(&self) -> PathBuf {
self.root.join("index/tessera-main.json")
}
@@ -136,6 +528,8 @@ impl Vault {
manifest,
size_bytes: payload.len() as u64,
tree_root: "dry-run".into(),
stored_bytes: None,
new_data_chunks: None,
});
}
@@ -148,16 +542,47 @@ impl Vault {
manifest,
size_bytes: payload.len() as u64,
tree_root: chunk_id,
stored_bytes: None,
new_data_chunks: None,
};
let path = self
.root
.join("snapshots")
.join(format!("{}.json", snap.id));
fs::write(&path, serde_json::to_string_pretty(&snap)?)?;
self.write_snapshot(&snap, true)?;
Ok(snap)
}
fn write_snapshot(&self, snap: &StoredSnapshot, overwrite: bool) -> Result<()> {
let plain = serde_json::to_vec(&snap)?;
let enc = self.key.encrypt(&plain)?;
let dir = self.root.join("snapshots");
let path = dir.join(format!("{}.json.enc", snap.id));
let mut temp = tempfile::NamedTempFile::new_in(&dir)?;
temp.write_all(&enc)?;
temp.as_file().sync_all()?;
if overwrite {
temp.persist(path)?;
} else {
temp.persist_noclobber(path)?;
}
sync_directory(&dir)
}
fn read_snapshot_file(&self, path: &Path) -> Result<StoredSnapshot> {
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if name.ends_with(".json.enc") || name.ends_with(".expired") {
let plain = self.key.decrypt(&fs::read(path)?)?;
Ok(serde_json::from_slice(&plain)?)
} else if name.ends_with(".json") {
let snap: StoredSnapshot = serde_json::from_str(&fs::read_to_string(path)?)?;
anyhow::ensure!(
!snap.tree_root.starts_with(restic::PREFIX)
&& !snap.tree_root.starts_with(restic::OUTPOST_PREFIX),
"restic snapshot metadata must be encrypted"
);
Ok(snap)
} else {
anyhow::bail!("not a snapshot file");
}
}
pub fn list_snapshots(&self) -> Result<Vec<StoredSnapshot>> {
let dir = self.root.join("snapshots");
if !dir.exists() {
@@ -166,52 +591,215 @@ impl Vault {
let mut out = Vec::new();
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
let name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
if !(name.ends_with(".json") || name.ends_with(".json.enc")) {
continue;
}
let data = fs::read_to_string(&path)?;
let snap: StoredSnapshot = serde_json::from_str(&data)?;
out.push(snap);
out.push(self.read_snapshot_file(&path)?);
}
out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at));
Ok(out)
}
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let path = self.root.join("snapshots").join(format!("{id}.json"));
let data = fs::read_to_string(&path).context("snapshot metadata")?;
let snap: StoredSnapshot = serde_json::from_str(&data)?;
let bytes = self.read_chunk(&snap.tree_root)?;
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)?;
pub fn prepare_offsite_copy(&self, id: Uuid) -> Result<crate::OffsiteCopy> {
let snapshot =
self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?;
anyhow::ensure!(
snapshot.manifest.restore_hints.get("job_id").is_some(),
"snapshot is not a capture job"
);
let (source, restic_id) =
if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit = snapshot.manifest.orbit_id;
(
self.outpost_repository(orbit, self.outpost_config(orbit)?),
id,
)
} else {
(
self.restic.clone(),
snapshot
.tree_root
.strip_prefix(restic::PREFIX)
.context("capture Restic snapshot missing")?,
)
};
Ok(crate::OffsiteCopy {
snapshot: id,
source,
restic_id: restic_id.to_owned(),
})
}
pub fn get_snapshot(&self, id: Uuid) -> Result<Option<StoredSnapshot>> {
for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.try_exists()? {
return self.read_snapshot_file(&path).map(Some);
}
}
fs::write(dest, &bytes)?;
Ok(bytes.len() as u64)
Ok(None)
}
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let snap = self
.get_snapshot(id)?
.context("snapshot metadata not found")?;
let parent = dest
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
let mut temp = tempfile::NamedTempFile::new_in(parent)?;
if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit_id = snap.manifest.orbit_id;
let path = if snap.manifest.restore_hints["format"] == "tar" {
"/"
} else {
restic::PAYLOAD
};
self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?)
.dump(id, path, temp.reopen()?)?;
} else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
let path = if snap.manifest.provider == "filesystem" {
"/"
} else {
restic::PAYLOAD
};
self.restic.dump(id, path, temp.reopen()?)?;
} else {
temp.write_all(&self.read_chunk(&snap.tree_root)?)?;
}
let len = temp.as_file().metadata()?.len();
temp.as_file().sync_all()?;
// never replace a file that is already there
temp.persist_noclobber(dest)?;
Ok(len)
}
pub fn forget(&mut self, ids: &[Uuid]) -> Result<usize> {
let mut removed = 0;
for id in ids {
let path = self.root.join("snapshots").join(format!("{id}.json"));
if path.exists() {
fs::remove_file(&path)?;
let mut gone = false;
for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.exists() {
let snap = self.read_snapshot_file(&path)?;
if snap.tree_root.starts_with(restic::PREFIX)
|| snap.tree_root.starts_with(restic::OUTPOST_PREFIX)
{
fs::rename(&path, path.with_file_name(format!("{id}.expired")))?;
} else {
fs::remove_file(&path)?;
}
gone = true;
}
}
if gone {
removed += 1;
}
}
Ok(removed)
}
pub fn collect_garbage(&mut self) -> Result<()> {
let dir = self.root.join("snapshots");
let mut expired = std::collections::HashMap::<Option<Uuid>, Vec<(String, PathBuf)>>::new();
for entry in fs::read_dir(&dir)? {
let path = entry?.path();
if path.extension().is_some_and(|ext| ext == "expired") {
let snap = self.read_snapshot_file(&path)?;
let (orbit, id) =
if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
(Some(snap.manifest.orbit_id), id)
} else {
(
None,
snap.tree_root
.strip_prefix(restic::PREFIX)
.context("invalid expired snapshot")?,
)
};
restic::validate_id(id)?;
expired
.entry(orbit)
.or_default()
.push((id.to_owned(), path));
}
}
// The expiry must survive a crash before its backing snapshot can be removed.
sync_directory(&dir)?;
expired.entry(None).or_default();
for (orbit, snapshots) in expired {
let outpost;
let repo = if let Some(orbit_id) = orbit {
outpost = self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?);
&outpost
} else {
&self.restic
};
repo.prune(
&snapshots
.iter()
.map(|(id, _)| id.clone())
.collect::<Vec<_>>(),
)?;
for (_, path) in snapshots {
match fs::remove_file(path) {
Ok(()) => (),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
Err(error) => return Err(error.into()),
}
}
}
Ok(())
}
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let policy = DecayPolicy::from_preset(preset);
let snaps = self.list_snapshots()?;
let refs: Vec<SnapshotRef> = snaps
.iter()
self.prune_snapshots(
preset,
None,
snaps.into_iter().filter(|snapshot| {
snapshot.manifest.provider != "legacy-history"
&& snapshot.manifest.restore_hints.get("job_id").is_none()
&& !snapshot.manifest.is_restore_safety()
}),
)
}
pub fn prune_orbit_with_decay(
&mut self,
orbit_id: Uuid,
preset: &str,
retention: Option<&RetentionPolicy>,
) -> Result<Vec<Uuid>> {
let snaps = self.list_snapshots()?;
self.prune_snapshots(
preset,
retention,
snaps
.into_iter()
.filter(|s| s.manifest.orbit_id == orbit_id && !s.manifest.is_restore_safety()),
)
}
fn prune_snapshots(
&mut self,
preset: &str,
retention: Option<&RetentionPolicy>,
snapshots: impl Iterator<Item = StoredSnapshot>,
) -> Result<Vec<Uuid>> {
let refs = snapshots
.map(|s| SnapshotRef {
id: s.id,
taken_at: s.taken_at,
})
.collect();
let to_forget = evaluate_decay(&policy, refs);
let to_forget = match retention {
Some(policy) => evaluate_gfs(policy, refs),
None => evaluate_decay(&DecayPolicy::from_preset(preset), refs),
};
self.forget(&to_forget)?;
Ok(to_forget)
}
@@ -221,16 +809,98 @@ impl Vault {
}
}
fn sync_directory(path: &Path) -> Result<()> {
#[cfg(unix)]
File::open(path)?.sync_all()?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
fn restrict_dir(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if path.exists() {
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
}
}
#[cfg(not(unix))]
let _ = path;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
use tessera_core::manifest::SnapshotManifest;
#[test]
#[ignore = "requires restic on PATH"]
fn changed_files_reuse_chunks_and_restore_after_prune() {
use rand::{RngCore, SeedableRng};
let dir = tempdir().unwrap();
let source = dir.path().join("source");
fs::create_dir(&source).unwrap();
let mut bytes = vec![0; 24 * 1024 * 1024];
rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes);
let file = source.join("large.bin");
fs::write(&file, &bytes).unwrap();
let mut vault = Vault::init(dir.path().join("vault"), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
orbit_name: "files".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![source.to_str().unwrap().into()],
restore_hints: serde_json::json!({}),
};
let first = vault.snapshot_files(manifest.clone(), None, false).unwrap();
let mut manifest = manifest;
manifest.snapshot_id = Uuid::new_v4();
let identical = vault.snapshot_files(manifest.clone(), None, false).unwrap();
assert_eq!(identical.new_data_chunks, Some(0));
bytes.splice(100..100, [1; 1024]);
fs::write(&file, &bytes).unwrap();
fs::write(source.join("added.txt"), b"new file").unwrap();
manifest.snapshot_id = Uuid::new_v4();
let changed = vault.snapshot_files(manifest.clone(), None, false).unwrap();
assert!(changed.stored_bytes.unwrap() < first.stored_bytes.unwrap() / 2);
vault.forget(&[first.id, identical.id]).unwrap();
vault.collect_garbage().unwrap();
assert_eq!(vault.list_snapshots().unwrap().len(), 1);
let output = dir.path().join("restore.tar");
vault.restore_snapshot(changed.id, &output).unwrap();
let extracted = dir.path().join("extracted");
fs::create_dir(&extracted).unwrap();
assert!(std::process::Command::new("tar")
.arg("-xf")
.arg(output)
.arg("-C")
.arg(&extracted)
.status()
.unwrap()
.success());
let restored = extracted.join(source.canonicalize().unwrap().strip_prefix("/").unwrap());
assert_eq!(fs::read(restored.join("large.bin")).unwrap(), bytes);
assert_eq!(fs::read(restored.join("added.txt")).unwrap(), b"new file");
manifest
.paths
.push(dir.path().join("missing").to_string_lossy().into());
manifest.snapshot_id = Uuid::new_v4();
assert!(vault.snapshot_files(manifest, None, false).is_err());
assert_eq!(vault.list_snapshots().unwrap().len(), 1);
}
#[test]
fn init_snap_list_restore() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap();
let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
@@ -240,9 +910,7 @@ mod tests {
paths: vec![],
restore_hints: serde_json::json!({}),
};
let snap = vault
.snapshot(manifest, b"payload bytes", false)
.unwrap();
let snap = vault.snapshot(manifest, b"payload bytes", false).unwrap();
let list = vault.list_snapshots().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].id, snap.id);
@@ -255,7 +923,7 @@ mod tests {
#[test]
fn dry_run_writes_nothing() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret").unwrap();
let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
@@ -268,4 +936,119 @@ mod tests {
vault.snapshot(manifest, b"x", true).unwrap();
assert!(vault.list_snapshots().unwrap().is_empty());
}
#[test]
fn orbit_decay_keeps_other_orbits_recoverable() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let orbit_id = Uuid::new_v4();
let other_id = Uuid::new_v4();
let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap();
for (index, id) in [orbit_id, orbit_id, other_id].into_iter().enumerate() {
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: id,
orbit_name: "same name".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
};
vault
.snapshot_at(
manifest,
b"x",
false,
now - chrono::Duration::seconds(index as i64),
)
.unwrap();
}
let pruned = vault
.prune_orbit_with_decay(orbit_id, "month-of-weeklies", None)
.unwrap();
assert_eq!(pruned.len(), 1);
assert!(vault
.list_snapshots()
.unwrap()
.iter()
.any(|s| s.manifest.orbit_id == other_id));
}
#[test]
fn new_snapshots_are_encrypted_and_legacy_json_still_reads() {
let dir = tempdir().unwrap();
let mut vault = Vault::init(dir.path(), "secret-test-passphrase").unwrap();
let legacy_id = Uuid::new_v4();
let legacy = StoredSnapshot {
id: legacy_id,
taken_at: DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
manifest: SnapshotManifest {
snapshot_id: legacy_id,
orbit_id: Uuid::new_v4(),
orbit_name: "legacy".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
},
size_bytes: 4,
tree_root: "missing".into(),
stored_bytes: None,
new_data_chunks: None,
};
fs::write(
dir.path()
.join("snapshots")
.join(format!("{legacy_id}.json")),
serde_json::to_string(&legacy).unwrap(),
)
.unwrap();
let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(),
orbit_name: "new".into(),
labels: vec![],
provider: "filesystem".into(),
paths: vec![],
restore_hints: serde_json::json!({}),
};
let snap = vault.snapshot(manifest, b"cipher", false).unwrap();
assert!(dir
.path()
.join("snapshots")
.join(format!("{}.json.enc", snap.id))
.exists());
assert!(!dir
.path()
.join("snapshots")
.join(format!("{}.json", snap.id))
.exists());
let names: Vec<_> = vault
.list_snapshots()
.unwrap()
.into_iter()
.map(|s| s.manifest.orbit_name)
.collect();
assert!(names.contains(&"legacy".to_string()));
assert!(names.contains(&"new".to_string()));
let out = dir.path().join("restored.bin");
assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6);
}
#[test]
fn new_vaults_need_a_long_passphrase_but_existing_short_ones_still_open() {
let dir = tempfile::tempdir().unwrap();
assert!(Vault::init(dir.path(), "fifteen-chars-x").is_err());
assert!(Vault::init(dir.path(), "sixteen-chars-xx").is_ok());
// a vault made before the rule: same data, shorter passphrase never got in, so reopen with the long one
assert!(Vault::open(dir.path(), "sixteen-chars-xx").is_ok());
}
#[test]
fn init_rejects_published_dev_passphrase() {
let dir = tempdir().unwrap();
assert!(Vault::init(dir.path(), "dev-vault-key").is_err());
assert!(Vault::init(dir.path(), "").is_err());
}
}

32
deny.toml Normal file
View File

@@ -0,0 +1,32 @@
# Supply-chain gate. Run: cargo deny check
[graph]
all-features = false
[advisories]
version = 2
# Unmaintained warnings are tracked, not ignored silently; see the auth design notes.
unmaintained = "workspace"
ignore = [
{ id = "RUSTSEC-2023-0071", reason = "Marvin attack concerns RSA private-key operations. Tessera only verifies ID-token signatures with public keys (openidconnect core/crypto.rs); runtime code never calls an RSA private-key operation; only test fixtures sign tokens with throwaway keys. No patched rsa 0.9 exists. Revisit when openidconnect moves to rsa >= 0.10." },
]
[licenses]
version = 2
allow = [
"MIT", "MIT-0", "Apache-2.0", "Apache-2.0 WITH LLVM-exception", "ISC",
"BSD-2-Clause", "BSD-3-Clause", "Unicode-3.0", "Zlib", "CC0-1.0",
"BSL-1.0", "Unlicense",
"CDLA-Permissive-2.0", # webpki-roots: Mozilla CA data
"AGPL-3.0-or-later", # Tessera's own crates
]
confidence-threshold = 0.9
[bans]
multiple-versions = "warn"
wildcards = "deny"
allow-wildcard-paths = true
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]

432
docs/DATABASE-CAPTURE.md Normal file
View File

@@ -0,0 +1,432 @@
# Managed database backups
A capture profile maps one application and Wormhole orbit to a paired outpost. The hub stores the assignment, format, schedule, and retention policy. The agent reads connection settings and password references from its local profile file. Each application has one active capture lease. An agent can serve several applications in parallel.
## Pair an agent
Build the hub, CLI and agent with `cargo build --workspace`. Put Restic on the hub and the database client for the source server version on the agent. SSH profiles also use OpenSSH on the agent. MySQL remote capture runs the server-compatible `mysqldump` on the SSH host.
Generate a pairing code in **Outposts** or call `POST /api/v1/wormhole/pairing` with operator credentials. On the agent, create the credential file once.
```sh
tessera-agent --hub-url https://backup.example.org --credentials /etc/tessera/wormhole.json pair CODE --name database-outpost
tessera-agent --credentials /etc/tessera/wormhole.json --capture-profiles /etc/tessera/capture.json run
```
Always pass `--credentials`: only then is the upload token written to the file and kept out of the terminal. Without it, `pair` prints `TESSERA_UPLOAD_TOKEN=…` to stdout, where shell history, logs and CI output can capture it. The file must not exist yet, and its directory must be writable by the account that runs `pair` (for a service account, use its home directory rather than a root-owned `/etc` path, or create the file as root and `chown` it to the service account with mode 0600 before `run`).
The credentials file is owner-only and contains the hub URL, outpost UUID and upload token. Keep it outside the repository. TLS uses the system trust store. Set `TESSERA_WORMHOLE_CA` for a private CA and configure both `TESSERA_WORMHOLE_CLIENT_CERT` and `TESSERA_WORMHOLE_CLIENT_KEY` for a hub that requires mTLS. Plain HTTP capture is available on loopback for local testing.
## Register an application
In **Orbits**, choose **Database** or **Filesystem / Folder**, then **Via Outpost**. Save the orbit and register its Outpost backup profile. Pick the paired Outpost, application UUID, and optional daily UTC schedule. Database profiles also need an engine.
For **Via Hub**, give the hub a readable folder path or a reachable PostgreSQL/MySQL endpoint and an absolute password-file path. Mount these files into the container when applicable. TLS verifies the server identity by default. Provide a CA file for a private CA. The hub needs a matching database client on its PATH. The bundled hub image includes `pg_dump` and `mysqldump`. Use a compatible client for the source server version.
For CLI setup, create an orbit using `tessera orbit billing --provider wormhole` and save its returned UUID. Use the UUID of the paired outpost shown in **Outposts**. Choose a stable application UUID and submit the following object to `POST /api/v1/capture-profiles` using the hub's admin API token or authenticated operator session.
```json
{
"application_id": "e1656c14-0d87-4572-a548-b66cc283e61f",
"orbit_id": "393e5c00-65b8-4084-a521-099732948a6c",
"outpost_id": "c7072265-89ab-493a-8dbe-948c1e9aa24c",
"format": "postgres_custom",
"schedule": { "hour": 2, "timezone": "Asia/Jakarta" }
}
```
To change a profile's schedule or retention later, send `PUT /api/v1/capture-profiles/{application_id}` with an administrator credential and only the fields to change: an absent field stays, `null` clears it. The format, orbit and Outpost are part of the profile's identity and are refused. Validation matches registration. Changing the schedule moves the schedule cursor to the time of the change, so a slot that has already passed under the new schedule is not run late: the first job comes from the next slot. The change is audited as `capture.profile_updated`.
Downloads are named `<orbit>_<time>_<engine>_<id8>.<ext>`, for example `lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump`. The orbit name is reduced to `[a-z0-9_-]`, the time is when the backup was taken in the profile's schedule zone (UTC with `Z` when there is no schedule), and the first eight characters of the snapshot id keep backups from the same minute apart. The header carries both `filename` and the RFC 5987 `filename*`.
The safety copy that a restore takes of its target (label `restore-safety`) is not a backup of the application, so retention never counts it against captures: it can neither push a production capture out nor be pushed out by one. Safety copies have their own rule, per restore target: the newest three are kept, plus any younger than seven days, and a copy that a restore still depends on is never forgotten.
A schedule is optional. Scheduled jobs catch up from the time the profile was registered and stay queued while the outpost is offline. Retention defaults to 14 days and keeps the newest archive. Use `"retention": {"mode": "count"}` for five archives or set its `keep` value explicitly. An orbit's custom GFS policy applies when the profile has no explicit retention override. The offline CLI decay command only processes legacy snapshots.
Set the same application UUID in the agent's local JSON file. Each entry has a `source` and an optional `timeout_seconds` (default 3600). The password file contains one line and should be readable only by the service account.
```json
{
"e1656c14-0d87-4572-a548-b66cc283e61f": {
"source": {
"engine": "postgres",
"host": "billing.internal",
"database": "billing",
"user": "backup",
"password_file": "/etc/tessera/billing.password",
"tls": { "mode": "verify_full_with_ca", "ca_file": "/etc/tessera/database-ca.pem" }
}
}
}
```
| Case | Format | Agent source |
| --- | --- | --- |
| Direct PostgreSQL | `postgres_custom` or `postgres_sql` | Example above. Port defaults to 5432. TLS defaults to `verify_full`. |
| PostgreSQL through SSH | `postgres_custom` or `postgres_sql` | Add a `bastion` object. Keep the PostgreSQL hostname that the server certificate covers. |
| Direct MySQL | `mysql_sql` | Use `"engine": "mysql", "transport": "direct"`, host, database, user, password file and MySQL TLS policy. Port defaults to 3306. TLS modes include `verify_identity_with_ca` with a CA file and `required`. |
| MySQL through SSH | `mysql_sql` | Use `"engine": "mysql", "transport": "ssh"`, `bastion`, `database` and `defaults_file`. The latter is an absolute path to a private MySQL client options file on the SSH host. |
The `bastion` object has `host`, `user`, `identity_file`, `known_hosts_file` and an optional `port` (default 22). Use an absolute path for each file. Record the authorized SSH server host key in the pinned known-hosts file. The SSH login needs forwarding permission for PostgreSQL or permission to run the MySQL client and read its options file for remote MySQL.
## Run and inspect a backup
Open **Orbits → Outpost backup jobs**, select an application, and queue a backup. In the API, use `POST /api/v1/capture-profiles/{application-id}/jobs`. Poll `GET /api/v1/capture-jobs/{job-id}` for status and its `/events` endpoint for phase history. The list endpoint supports `application_id`, `status`, and `limit` filters. Successful captures expose their engine, format, and job ID in the snapshot catalog.
New Outpost orbits require the current agent and an incremental Restic repository. Follow the Rest Server and repository setup in [the README](../README.md#incremental-wormhole-transfers-for-filesystem-archives) for each orbit. Use the same repository password in the hub's orbit key and the agent's password file. Add these fields to the application's agent profile:
```json
{
"restic_repository": "rest:https://backup.example.org/<orbit-id>/",
"restic_password_file": "/etc/tessera/keys/repository-password",
"rest_server_password_file": "/etc/tessera/keys/rest-server-password"
}
```
The Rest Server login is the orbit ID when `rest_server_password_file` is set. For a private Rest Server CA, configure `RESTIC_CACERT` on the agent. A filesystem profile uses `"paths": ["/path/to/folder"]` in place of `source` and `"format": "filesystem"` on the hub.
The agent sends new Restic chunks and snapshot metadata. The hub registers the snapshot after checking the lease and repository. One capture job produces one catalog ID across retries. A logical database backup needs room on the executor for one private temporary dump per concurrent capture. A database can run with its normal logging settings. The dump is read in full at the source, and Restic performs deduplication before transfer to the repository.
Existing database orbits keep the legacy full-upload path until their Restic repository is configured. That path validates length and SHA-256 at ingest, stages on both sides, and has a 100 GiB upload limit.
Use the snapshot detail to download or remove an archive. Database snapshots can also be exported to a file on the hub. Use **Database recovery options** to apply a verified database archive to a registered target.
## Operator sign-in
Authentication is required by default, including requests from loopback and a
local reverse proxy. Before upgrading, configure the emergency operator hash/name
and/or the separate API admin token. Startup refuses a hub without credentials.
An existing install with neither configured must bootstrap credentials locally
before restarting; there is no first-user auto-admin or public registration.
Use a named individual emergency operator, not a shared daily SSO account.
For synthetic local development only, `TESSERA_LOCAL_DEVELOPMENT=true` explicitly
enables anonymous loopback access when no operator/token is configured. Both
listeners must bind loopback; wildcard and non-loopback binds are rejected.
Forwarded requests are rejected in this mode, but that is not a proxy trust
boundary: never reverse-proxy a development listener. Compose keeps the mode off
and needs operator/API credentials even with a localhost published port.
In the container, run the hash mode through the image: `printf '%s\n' "$pw" | docker run --rm -i --entrypoint tessera-hub <image> --hash-operator-password`. Generate an Argon2id hash and set `TESSERA_OPERATOR_PASSWORD_HASH` to the result. The hub reads the password from stdin in hash mode. For example, from an interactive Bash shell:
```bash
read -rs -p 'Operator password: ' tessera_operator_password; printf '\n'
export TESSERA_OPERATOR_PASSWORD_HASH="$(printf '%s\n' "$tessera_operator_password" | tessera-hub --hash-operator-password)"
unset tessera_operator_password
```
Set `TESSERA_OPERATOR_NAME` for the audited identity, or use the default `operator`. Serve the browser over HTTPS outside loopback. Sessions expire after eight hours. They survive a hub restart as long as the operator credential is unchanged; rotating or removing `TESSERA_OPERATOR_PASSWORD_HASH` invalidates them. Browser mutations require the session's CSRF token. API and CLI callers use the separate `TESSERA_ADMIN_TOKEN`. Use the bundled HTTP CLI on the hub's loopback listener when sending the token.
Legacy full-upload agents now need an explicit orbit assignment. With operator
CSRF or an admin API token, call `PUT /api/v1/orbits/{orbit-id}/outpost` with
`{"outpost_id":"<paired-outpost-uuid>"}`. Only active paired Outposts and legacy
Wormhole orbits are accepted; managed capture assignment remains on its profile.
Existing unassigned orbits and upload sessions without an owner fail closed.
Review the mapping, bind the orbit, then restart the upload to obtain a new owned
session. No owner is inferred from a name or an old token. This does not delete
old snapshots or partial uploads; operators can remove abandoned partial files
after stopping the old agent. Rebinding invalidates in-flight uploads from the
previous Outpost.
## Optional S3 copy
Configure `TESSERA_OFFSITE_REPOSITORY=s3:https://s3.example.org/tessera-backups/managed` with a dedicated prefix and point `TESSERA_OFFSITE_PASSWORD_FILE` to the independent Restic password. Supply AWS credentials via the hub service environment or the provider's credential chain. In Docker, mount the password file at the container path using a read-only mount.
The hub retries failed copies and reports their state on the capture job. Local retention and deletion protect pending copies. Off-site archives remain available independently after local catalog removal. To recover without the hub or its primary repository, use the off-site Restic password and S3 credentials with these commands:
```sh
restic -r "$TESSERA_OFFSITE_REPOSITORY" --password-file "$TESSERA_OFFSITE_PASSWORD_FILE" snapshots --tag "tessera-<snapshot-uuid>"
restic -r "$TESSERA_OFFSITE_REPOSITORY" --password-file "$TESSERA_OFFSITE_PASSWORD_FILE" dump <restic-id-from-first-command> /payload > recovered.dump
```
## Register a restore target
Configure target credentials on the assigned agent. A target can use a different outpost from its source. PostgreSQL identifies a logical database by cluster system identifier and database name. MySQL uses the server UUID and database name. PostgreSQL source and target roles need read access to `pg_catalog.pg_control_system()` to verify identity. A capture with an unavailable source identity remains available for export.
From a restorable snapshot, open **Database recovery options** and select **Register restore target**. For API setup, call `POST /api/v1/restore-targets` with `id`, `application_id`, `outpost_id`, `name`, `engine` and `identity`. The identity has `instance` and `database`. Query the values on the target.
- PostgreSQL uses `SELECT system_identifier, current_database() FROM pg_catalog.pg_control_system()`.
- MySQL uses `SELECT LOWER(@@server_uuid), DATABASE()`.
On the target agent, add a `targets` map under the application UUID, keyed by the registered target UUID. A target-only outpost can omit the application's `source`. An example PostgreSQL entry follows.
```json
{
"engine": "postgres",
"connection": {
"host": "staging-db.internal",
"database": "billing_staging",
"user": "restore",
"password_file": "/etc/tessera/staging.password",
"tls": { "mode": "verify_full_with_ca", "ca_file": "/etc/tessera/database-ca.pem" }
},
"mode": { "reset": "schema", "schema": "public" }
}
```
Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. An orbit can be renamed with `PUT /api/v1/orbits/{id}` and `{"name": "..."}` (administrators only, 1 to 128 characters, no control characters, unique without regard to case, audited as `orbit.renamed`). Only the name changes. Snapshots keep the name they were written under inside their (immutable) metadata, so the snapshot list and the download file name look the orbit up by id and show its current name; a snapshot of an orbit that no longer exists keeps its original name.
A restore target can be renamed later with `PUT /api/v1/restore-targets/{id}` and `{"name": "..."}` (administrators only, 1 to 128 characters, no control characters, audited as `restore_target.renamed`). Only the display name changes: the id, the identity, the Outpost, relations and earlier jobs stay as they are. Since several applications can each have a target called `dev`, the Relations console shows the application next to every target and in its pickers, and the Refresh screen shows the application on each card. Registering a target suggests `<application> · <database>` until a name is typed.
Use `{"reset":"user_schemas"}` for a database whose tables live in several schemas: it drops every non-system schema (everything except `pg_*` and `information_schema`) and recreates `public`, in the same transaction as the restore, so a dump's `CREATE SCHEMA` for a schema that already exists on the target cannot collide. Schema mode only drops the one named schema, so a dump that also creates another schema that the target already has fails and rolls back; the target is left unchanged. Objects that live outside schemas (roles, publications, subscriptions) are not touched, and the connected role must own, or be allowed to drop, every schema it empties. Supply a local `post_restore_sql` file for target-specific SQL. PostgreSQL can read custom archives and plain or gzip-compressed SQL. The agent requires a psql client with restricted mode for restore. `omit_transaction_timeout` and `omit_pg_stat_statements` enable specific compatibility rules.
A custom-format archive must be readable by the `pg_restore` on the restore host. pg_restore refuses archives made by a newer pg_dump, so install a client at least as new as the one that captured. The check happens while the archive is being prepared, before the safety backup and before anything is touched, and the failure names both versions, for example `pg_restore 16.15 cannot read this archive (made by pg_dump 17.2, archive format 1.16): install a PostgreSQL client >= 17 on the restore host`. With `omit_pg_stat_statements`, the dump's own `pg_stat_statements` statements are skipped, but an extension the target already had is recreated in the schema it lived in (a target without it does not get it).
When a restore step fails, the agent reports why and the hub keeps it as `failure_reason` on the restore job (visible to administrators through `GET /api/v1/restore-jobs/{id}`, written to the hub log and the audit log as `restore.failed`). It is the client's own primary error line (`ERROR:`/`FATAL:`), cleaned to one line of printable ASCII of at most 300 characters. `DETAIL`, `CONTEXT` and statement text are dropped because they quote data, and the psql run uses `VERBOSITY=terse`. People who only hold a refresh grant never see it: their run shows the status, not the database's words. Message text can still name an object or value in a few cases (for example an invalid input value), so treat the field as administrator-only.
A MySQL target uses `"engine":"mysql"` and the same `connection` fields as a direct or SSH MySQL source. `recreate_database` drops and recreates the registered database before applying SQL. `use_target_definer` rewrites supported dump DEFINER clauses to the connected MySQL user.
Open the snapshot and choose its recovery options, then pick the target in **Restore**. **Activity** lists recent restore jobs across all snapshots (`GET /api/v1/restore-jobs?limit=`, newest first, at most 200) and flags any that need reconciliation. The required confirmation includes both UUIDs. The hub verifies the safety archive before issuing the single-use apply permit. If the job reports `recovery_required`, stop any old apply process and verify its database session has ended. Recover the target with the linked safety archive, verify data and permissions, then confirm reconciliation to release the lock. Session-authenticated file exports use a filename in the hub's private `exports` directory.
## Import legacy archives
Run the CLI against the staging vault. Use an AWS CLI profile with `s3:ListBucket` scoped to the legacy prefix and `s3:GetObject` on the objects in that prefix.
```sh
tessera legacy-import --bucket legacy-bucket --prefix billing/ --orbit-id ORBIT_UUID --application billing --engine postgres --inventory-only
```
Repeat without `--inventory-only` to import. The JSON report includes the source key, ETag, size, last-modified timestamp, and Tessera snapshot ID. Conditional reads reject changed objects between listing and download. A persistent receipt prevents reimport after local retention and GC. [AWS S3 CLI inventory](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects-v2.html), [AWS S3 conditional download](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html).
Add `--history /path/to/consistent-history.sqlite` to archive a consistent SQLite export of the old job history. Save the reported history ID and retrieve it with `tessera legacy-history HISTORY_UUID history.sqlite` on the vault host. Inspect the retrieved copy read-only. Legacy SQL archives retain their original bytes and can be applied to a temporary database with the matching engine client.
## OIDC sign-in (single issuer)
Set `TESSERA_OIDC_ISSUER` to enable browser SSO (authorization code + PKCE S256,
Tessera is a confidential client). When it is set, these are also required:
| Variable | Meaning |
| --- | --- |
| `TESSERA_OIDC_CLIENT_ID`, `TESSERA_OIDC_CLIENT_SECRET` | Client registered at the IdP. The secret is only read from the environment and never logged. |
| `TESSERA_OIDC_REDIRECT_URL` | Public, static callback, exactly `https://<hub>/api/v1/auth/oidc/callback`. It is never derived from `Host` or `X-Forwarded-*`. |
| `TESSERA_OIDC_ADMIN_SUBJECTS` | Comma-separated `sub` values that may administer the hub. |
| `TESSERA_OIDC_ADMIN_GROUPS` | Comma-separated group names that may administer the hub. |
| `TESSERA_OIDC_GROUPS_CLAIM` | ID-token claim that carries groups (default `groups`; string or array of strings). |
| `TESSERA_OIDC_CA_FILE` | Optional PEM bundle for an IdP behind a private CA. |
At least one admin subject or group is mandatory, otherwise startup fails: with
no mapping nobody could administer the hub. Issuer and redirect URL must be
`https://`; plain http is accepted only for a loopback host together with
`TESSERA_LOCAL_DEVELOPMENT=true`.
Behaviour to know about:
- Users are identified by `(issuer, subject)`, never by email or display name.
There is no auto-link by email and no first-user-becomes-admin.
- A user who signs in but matches no admin mapping gets a "No access yet" page and
`403` on every management API. They can still call `GET /api/v1/me` and sign out.
- Group membership is read at sign-in. A change at the IdP applies at the next
sign-in, at most 8 hours later (absolute session limit); there is no back-channel
logout or SCIM yet.
- Changing the issuer, client ID, admin subjects/groups or groups claim ends every
existing OIDC session. Rotating the client secret does not.
- Sign-out ends the Tessera session only. The IdP session stays, so the next
"Sign in with SSO" may not ask for a password. RP-initiated logout is not implemented.
- ID tokens must be signed with RS256 (the library default). An IdP that signs
with another algorithm is rejected until that is made configurable.
- The emergency operator password keeps working beside SSO and is shown under
"Emergency operator sign-in" when SSO is on.
- No IdP token is stored or sent to the browser; the browser only receives the
Tessera session cookie.
## Outpost credentials, rotation and request limits
**Storage.** The hub keeps only SHA-256 digests of pairing codes and Outpost upload
tokens. A pairing code is shown once (10 minute lifetime, single use). The upload
token does not exist until the agent claims the code; it is returned once and never
stored or logged. Tokens are 256-bit random values. They expire after
`TESSERA_OUTPOST_TOKEN_DAYS` days (default 365).
**Upgrading an existing hub.** On first start the old clear-text `wormhole_tokens`
table is moved to digests and dropped, with `secure_delete` on so freed pages are
zeroed. Paired agents keep working with their current token and get a fresh
lifetime from the migration (the old `expires_at` was the pairing code's expiry).
Copies and backups of the old database still contain the clear-text tokens:
**rotate every Outpost token after upgrading** and treat old backups as sensitive.
Do not downgrade to a binary that predates this change; it would not understand the
new tables. Back up `tessera.db` first and rehearse on a copy.
**Rotate** (admin only). `POST /api/v1/wormhole/outposts/{id}/rotate?grace_minutes=60`
returns the new `upload_token` once. The previous token keeps working for the grace
period (default 60, maximum 1440, `0` cuts it at once) so you can put the new value
in the agent's `TESSERA_UPLOAD_TOKEN` and restart it. There is no agent
self-rotation yet: the operator delivers the new token.
**Revoke** (admin only). `POST /api/v1/wormhole/outposts/{id}/revoke` refuses every
token of that Outpost on its next request; it must be paired again. Both actions are
audited (`outpost.credential_rotate`, `outpost.credential_revoke`).
**Limits.** Unauthenticated and expensive endpoints are limited per source with
`governor`: emergency login (5 burst, 10/min per source, plus a looser 60/min account
ceiling), pairing claim (5 burst, 10/min per source, 120/min overall), SSO start and
callback. At most 2 Argon2 verifications run at once; further attempts get `429`
immediately. A denial is written to the audit log at most once a minute per source.
- The source is the TCP peer address. `X-Forwarded-For` is only used when the peer
is listed in `TESSERA_TRUSTED_PROXIES` (comma-separated IPs), read right to left
past trusted hops. Behind a reverse proxy **set this**, otherwise every user
shares the proxy's budget. IPv6 sources are keyed by /64.
- The account ceiling is deliberately looser than the per-source limit. With one
break-glass account, a tight account lock would let anyone lock the operator out.
- Limiter state is in memory: it resets when the hub restarts and is not shared
between hub processes.
**Shared admin token.** `TESSERA_ADMIN_TOKEN` is a transition aid. It must be at least
32 characters; generate one with `openssl rand -base64 32`. Set
`TESSERA_ADMIN_TOKEN_EXPIRES` (`YYYY-MM-DD`, end of that day UTC, or an RFC 3339
timestamp) and the hub refuses the token after that time. Without it the hub logs a
warning at start. Every use is audited as the `legacy-admin-token` service principal.
## Who may do what (access grants)
Administrators are the people named by the SSO admin mapping (`TESSERA_OIDC_ADMIN_SUBJECTS` /
`TESSERA_OIDC_ADMIN_GROUPS`), the emergency operator and the shared admin token. They can
do everything. Everyone else gets **nothing** until an administrator grants it in the
Access console (or through `/api/v1/access/*`). A grant names a person (a user who has signed
in) or an identity-provider group, a permission, an orbit (or all orbits) and optionally an end date.
Permissions that can be granted: `orbit.read`, `snapshot.read`, `capture.run`,
`snapshot.download`. They are separate: running a backup does not allow downloading it, and
the reverse. The roles `viewer`, `capturer` and `downloader` are shortcuts that expand into
these permissions, each including `orbit.read`. Everything else (creating or changing orbits,
profiles, Outposts, retention, deleting snapshots, restores, and access itself) stays with
administrators and cannot be delegated.
- An orbit a user has no `orbit.read` on is invisible: by id it answers `404`, in lists it is
left out. A visible orbit without the needed permission answers `403`. A user with no grant at
all gets `403` on lists and sees "No access yet" in the app.
- Grants are read on every request. Removing a grant, an expiry, disabling a user or
"Sign out everywhere" take effect on that user's next request. A change to a user's groups at
the identity provider applies at their next sign-in (at most 8 hours later), because groups
are taken from the sign-in token.
- A group grant applies to people whose token carries that group; a missing groups claim grants nothing.
- Jobs and audit entries record the stable user id (`oidc:<id>`), never the name the IdP reports.
- Until the self-service refresh arrives, restore targets and restore history are shown to
administrators only, because they describe the destination database.
- The administrator who disables a user cannot disable themselves or the emergency operator.
- Display choices (currently the Window/Radar view) are stored per account (`/api/v1/me/preferences`), so they follow
a person to another browser. Accounts without a user row (the shared admin token, local development) keep the
choice in the browser only.
## Downloading a snapshot
`GET /api/v1/snapshots/{id}/download` (needs `snapshot.download` on the orbit) returns the snapshot as a file.
The format follows what the snapshot really contains, judged from its first bytes and its manifest:
| Snapshot | Downloaded as |
| --- | --- |
| PostgreSQL or MySQL plain SQL | `.sql.gz` (gzip, compressed while streaming) |
| Filesystem backup (tar) | `.tar.gz` |
| SQLite | `.sqlite.gz` |
| Hub filesystem archive | `.tessera-fs.gz` |
| PostgreSQL custom dump (`pg_dump -Fc`) | `.dump`, unchanged: it already compresses its own data |
| Anything already gzip, zstd, xz, bzip2 or zip | unchanged, never compressed twice |
| Unknown content | `.dump.gz` |
The response is the file itself: there is no `Content-Encoding`, so a browser saves the `.gz` as it is; unpack
it with `gunzip`. `Content-Length` is only sent when the bytes are passed through unchanged. `HEAD` answers `405`.
The vault first writes the export to a private `tessera-export-*` directory inside the data directory, then streams it
in small frames (the hub does not hold the archive in memory while compressing). A chunk-stored snapshot is still read
from the vault in one piece when it is exported, so a very large snapshot of that kind needs that much memory once.
The directory is deleted when the download ends, when the client disconnects, and at the next start if the hub crashed.
Limits: `TESSERA_EXPORT_CONCURRENCY` exports at once (default 2; more get `429` at once) and
`TESSERA_EXPORT_MIN_FREE_BYTES` of free disk that must remain after the export (default 512 MiB; otherwise `507`).
The snapshot's recorded size is added to that margin; if a producer did not record one, only the margin applies.
The audit log records `export.requested`, `export.ready` and then `export.finished` or `export.disconnected` for each
download. "Finished" means the body was handed to the connection, not that a file reached the person's disk.
## Refresh relations (staging from production)
A *relation* says that one source orbit may overwrite one restore target (a staging or development database),
in that direction only. Administrators set it up in the Relations console (or `/api/v1/relations`). Nothing is assumed:
1. Give each **source orbit** and each **restore target** an environment: `production`, `staging` or `development`.
An orbit or target that is not labelled is never used. A target labelled `production` is refused.
2. A source must be a managed Outpost database backup (a capture profile with a restorable PostgreSQL or MySQL format).
Filesystem backups are not databases and cannot be a source.
3. A target is registered for one application, so it can only be connected to that application's orbit, with the same engine.
4. Connect them. The hub refuses a target whose database identity matches a database captured as production (or never
classified) in any snapshot, which catches a production database labelled staging. A staging or development orbit that
backs up the target itself does not count. If the source has no snapshot yet, the relation is created as *not yet
compared* and the refresh checks again before it applies anything. Each refusal names the rule that stopped it.
Relations are versioned. Pointing one at another target creates a new relation (new id, next version) and ends the old one.
Who may start a refresh is granted **per relation id** (`refresh.run`, to a person or an identity-provider group, with an
optional end date), so a new version starts with nobody allowed. These grants are separate from orbit access and never
include `orbit.read`, `snapshot.download` or `capture.run`. A person holding only a relation grant sees its name and
environments and never where the database is (no identity, host, Outpost or application id).
A relation stops being usable at once when its target is relabelled `production`, when either Outpost on its path is
revoked, or (when read) when an Outpost credential has expired. Existing administrator restores (`POST /restore-jobs`)
are unchanged.
### Starting a refresh
`POST /api/v1/refresh-runs` with `relation_id`, an `idempotency_key` and a `confirmation` that says exactly what the person
was shown: `REFRESH <source> TO <target> v<version>`. The caller never picks the snapshot or the target. The hub then:
1. creates the run and queues a **new capture** of the source in one transaction (a failed capture never falls back to an
older snapshot, and the run follows its own capture job, not "the latest snapshot");
2. when that capture has been published, queues the restore of **that snapshot** onto the relation's target, using the
existing restore path (lease, fencing, checksum and identity checks, safety backup of the target before anything is
overwritten);
3. follows the restore job to its end.
A run can also restore a snapshot somebody picked instead of capturing a new one: add `snapshot_id` to the request. The
snapshot must be a restorable database capture of the relation's own source orbit (never a safety copy, never another
orbit's); otherwise the answer is `422 snapshot_unusable` and nothing is started. Such a run has no capture step, but
everything else is the same: one run per target at a time, idempotency, cancelling until the target is overwritten, and
the authorisation checks right before overwriting. The same snapshot can be restored to several targets, and again later.
A restore can be undone: `undo_of` (the id of that run) restores the safety copy the restore took of its target
back onto the same target, through the same checks, countdown, progress and a new safety copy, so the undo can itself be
undone. A restore that completed, one an administrator reconciled, and one whose apply failed (the agent reported it) can
be undone; for the last, undoing is the recovery: the failed apply stops fencing the target in the same transaction
that starts the undo (job phase `rolled_back`, audited as `restore.rolled_back`). An apply whose agent went silent
(`lease_lost`) may still be writing, so it waits for an administrator to reconcile it first. The request is refused with
`422 nothing_to_undo` when the run is none of these for this relation, when something was restored onto the target after
it (only the newest restore of a target can be undone), or when the safety copy has been removed. A safety copy is only ever accepted as a source for the target it was taken from, whether it arrives through
`undo_of` or `snapshot_id`; the check is made by the hub, and again by the agent (its restore artifact carries
`rollback`). Run views say `undo`, `undo_of` (the restore an undo puts back), `restore_job_id` and `undo_available`, never where
the copy is. A restore that took a safety copy also says `undo_state`: `available` (with `undo_kept_until`, when retention
may first forget the copy: a week after it was taken, and later while it is one of the target's newest few),
`superseded` (something was restored after it) or `expired` (retention has forgotten the copy; this wins over
`superseded`). The Activity log shows `expired` as "Safety backup expired" in place of a link, and lists an undo
under the restore it reverses. Run lists work out all of this with one database pass and a file lookup per copy, and
read the vault only for the newest restore of each target. The run is audited as
`refresh.undo_started`. Undoing needs the same permission as restoring.
In the web UI there is no separate Refresh screen. Restoring lives in the Vault: pick an orbit, capture it if you want the
latest data (or click a snapshot that is already there), and in the snapshot detail press **Restore**. The button is
disabled with "No restore point" when no relation has been set up for the orbit. The modal offers the restore points
(Development and/or Staging) that the person may use, shows what will be overwritten, and after **Begin restore** counts
ten seconds in the browser, during which **Abort** sends nothing. Then it follows four steps (Checking, Safety copy,
Applying, Completed) from the run, and Abort still works until Applying starts. A finished restore offers **Undo this restore** (**Roll back** when it was interrupted), and the modal offers
**Undo last restore** for the chosen restore point while that is still possible. Safety copies are not listed with the
backups. A person needs to see the orbit's snapshots (for example the viewer role on the orbit) and a relation grant;
administrators can also restore to any other registered target from the same modal.
States: `capturing`, `restoring`, then `completed`, or `capture_failed`, `restore_failed`, `blocked` (with a reason),
`expired`, `cancelled`, `recovery_required` (the restore was interrupted after it started overwriting: an administrator
must reconcile it), `reconciled`. A target has at most one run in progress; a second request answers `409 run_active`
(the run id is only included for people who may see that run) and the same idempotency key from the same person returns
the same run. `TESSERA_REFRESH_MAX_ACTIVE` (default 4) bounds how many run at once; `TESSERA_REFRESH_TTL_MINUTES`
(default 120) is how long a run may take before it starts overwriting, after which it expires.
**Authorisation is checked again before anything is overwritten.** The run records what authorised it: an administrator,
or the grant on the relation. When the agent asks for permission to apply, the hub checks, in the same transaction that
allows it, that the relation is still active and usable (not relabelled production, Outposts still paired), that the
person is still an active user, that their grant still exists and has not expired, that the deadline has not passed, and
that the target is still not the source database. If any of that no longer holds, the restore is cancelled, the run is
`blocked`, and the agent is told `409`, so it overwrites nothing. A group grant can only be verified as of the request: the
hub checks that the grant still exists, not that the person is still in the group. Once overwriting has started it is
finished (or reconciled), not abandoned, whatever happens to the access.
A run pins its snapshot from the moment it starts, so retention and manual deletion leave it alone until the run ends.
The person who started a run, an administrator and anyone holding a grant on its relation can watch it
(`GET /api/v1/refresh-runs`, `/{id}`); only the person who started it or an administrator can cancel it, and only before
the restore starts overwriting. Others see names, states and times, never the database identity, the snapshot id or who
started it. Audit entries (`refresh.started`, `refresh.restore_queued`, `refresh.completed`, `refresh.blocked`, ...)
name the run and, for the start, the person.

View File

@@ -64,7 +64,7 @@ Tessera is a self-hosted backup vault. This document is the contract for metapho
**Invariants**
- Only one active capture per orbit per vault at a time (hub enforces lock).
- Decay runs only after a **successful** non-dry-run seal.
- Automatic decay runs only after a **successful** non-dry-run seal and applies to the captured orbit.
- Dry-run (“rehearse”) never writes snapshot metadata to the vault store.
---
@@ -112,7 +112,7 @@ Tessera is a self-hosted backup vault. This document is the contract for metapho
│ issue device token + id │
│───────────────────────────────►│
│ │
│ mTLS or Bearer on upload API │
│ Bearer upload token on upload API │
│◄───────────────────────────────│
```
@@ -139,12 +139,13 @@ Tone: short sentences, metaphor in headings, facts in telemetry panels.
## Security baseline
1. **Vault key:** Argon2id-derived key from passphrase; key file `keys/tessera.key` (mode 0600). Never logged.
2. **Hub auth (v1):** Local admin password → HTTP-only session cookie; hook point for OIDC later.
3. **Agents:** No vault master key. Hub issues **scoped upload tokens** per outpost/orbit after pairing.
4. **Wormhole:** v1 token-based HTTPS upload; mTLS optional when `TESSERA_WORMHOLE_MTLS=1` and certs present.
5. **Control plane:** SQLite (`data/tessera.db`) holds metadata only—no backup payloads.
6. **Audit:** Pairing, reconstitute start/complete, decay prune logged to `audit_log` table.
1. **Vault key:** New vaults use Argon2id (19 MiB, time cost 2, parallelism 1). The salt is `keys/tessera.salt` (mode 0600) and the parameters are `keys/kdf.json`. A salt with no `kdf.json` stays PBKDF2-HMAC-SHA256, 100,000 iterations, so vaults created before Argon2id still open. The derived key is not stored. Never log the passphrase. New vaults refuse a well-known development passphrase. New snapshot metadata is AES-GCM ciphertext in `{id}.json.enc`. Existing plaintext `{id}.json` files still list and restore. Chunk index JSON stays plaintext.
2. **Hub auth:** Browser access uses server-side sessions: OIDC sign-in (authorization code with PKCE) and an emergency operator account. Every route passes one central gate: authenticate, resolve the resource, then check the caller's grants. Management actions are administrator-only; non-admins can only hold `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download` and per-relation `refresh.run`. Outpost tokens and pairing codes are stored as digests. Requests are rate limited. The per-route matrix is in `docs/auth-endpoint-contract.md`. Behind a reverse proxy, set `TESSERA_TRUSTED_PROXIES` to the proxies you operate. The default listen address is `127.0.0.1:8787`.
3. **Agents:** No vault master key. After pairing, the hub issues an upload token stored in SQLite. The token survives a hub restart. Claim is an atomic update of a pairing code that has not expired.
4. **Wormhole:** A Restic agent sends missing chunks to its own authenticated, append-only REST repository and registers the finished snapshot using its paired token. The hub checks that the token belongs to the outpost assigned to that orbit. Legacy uploads require `total_bytes`. Chunks are written at `offset` into a mode `0600` `.part` file. When the ranges cover the payload, the hub stores it in Restic, applies decay, and deletes the `.part`. A later chunk on a sealed session is 409. `TESSERA_WORMHOLE_MTLS=1` (or `true`) starts a separate rustls listener that requires a client certificate. It needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is running, the plain HTTP upload and commit routes return 403. An `https://` agent needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`.
5. **Providers:** Filesystem and Postgres are in this release. The command provider is rejected with `command provider is outside this release; use filesystem or postgres`. Postgres parses `postgres://` or `postgresql://`, writes the password to a mode `0600` pgpass file, and passes `PGPASSFILE`, `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE`. The URL and password are not process arguments.
6. **Control plane:** SQLite (`data/tessera.db`) holds metadata, pairing codes, upload tokens, and upload ranges — no backup payloads.
7. **Audit:** Pairing, wormhole seal, reconstitute start/complete, and decay prune are logged to `audit_log`.
---

View File

@@ -1,32 +1,103 @@
# Tessera canvas — galaxy vault (Space Engine mode)
# Tessera orbital vault
Diegetic **cockpit HUD** over a persistent **galaxy viewport**. The vault is a **black hole** at center; each **orbit** is a **star** on an elliptical path; **snapshots** are **moons** around that star (when locked).
The persistent viewport maps backup jobs and recovery points. The black hole represents the vault. Stars represent orbits, and moons represent the latest snapshots of the selected orbit.
## Viewport modes
## Viewport and consoles
| Mode | Behavior |
|------|----------|
| **Flowing** (default) | Stars orbit the singularity; accretion disk spins; moons hidden; targets not clickable |
| **Locked** | Click **black hole** once — bodies ease into spaced slots and **stop**; star opens orbit console; moon opens snapshot tile |
- **Flowing** animates the projected orbits and the black hole's accretion disk. Pause or resume from the map toolbar. The map coasts to a visual stop, then reveals labels and moons in **Locked** mode, starting with the selected orbit. Resuming reverses that reveal. Selecting an orbit also locks the map. Reduced motion locks it immediately.
- Select a star or use the orbit register. The register prioritizes failed and active jobs and supports the up/down arrow keys. The inspector includes the capture action and full snapshot history.
- The first three recovery points of the selected orbit appear as moons when the map has room. Select a moon or history entry to review the snapshot and start a restore. Escape closes the console. Restore countdown and polling continue if the console closes.
- Hub connectivity is separate from backup health. Capture targets the named orbit. A running backup is a light circling its star; when it succeeds the light leaves for the black hole, and when it fails it is lost. See Orbit activity below. Rehearsals show text feedback and a ghost light.
- The map shows up to 55 overview orbits and reserves one slot for inspecting an orbit beyond that limit. The register provides access to every orbit. On narrow screens the map, register, and inspector stack vertically.
- **Big Screen** is a holographic visor. The map fills the viewport, and every piece of the workspace has a counterpart there and springs to it with `useScreenTransition` rather than popping. There are no panels or plates, only light: thin mint lines and glowing text, a vignette and faint scan over the scene, four corner brackets and a glass edge. Top left, the brand and the map's mode (Flowing, or Locked with the orbit). Top right, the four telemetry readings with their lamps. Bottom left, the legend. Bottom centre, the systems as text, the active one held in a glowing frame (it can still be dragged), and an ember label for Activity while something needs you. Bottom right, the Window | Radar words with a sliding underline, the motion and exit keys, then search and sign out as outlined circles, with the hub's state above them. The register, the inspector, the canopy frame and the sill captions fade out; every orbit is labelled on the map, each on a dark glass chip so the radar's grid cannot swallow it (up to 60, each placed clear of the others; the workspace map shows 12), and the picked orbit's label stands off its star on an elbowed leader line, with its status beneath. Use **Exit big screen** or Escape to return to the workspace. Below 900 px the legend is hidden and the controls sit above the systems; below 520 px the brand and telemetry are hidden too and the view switch shows icons.
- Drag the active navbar item sideways and release to open the destination. The regular navbar is a tray of switches with a sliding pill. Big Screen uses the same text tabs with a glowing frame in place of the pill.
- The navbar stays available above the side panel so you can switch directly between consoles. In the regular workspace it becomes a floating text dock in the same top position. Big Screen keeps its tabs at the bottom.
- Use **Search**, **⌘K**, or **Ctrl+K** from the vault, a console, or Big Screen. An empty field shows navigation shortcuts. Type to find destinations, orbits by name, ID, or provider, and snapshots by orbit name, ID, or displayed capture date. Search uses the summaries already loaded by the vault. Use the arrow keys and Enter, or select a result with a pointer. Escape closes search and returns focus to its button. Search is a spotlight panel over a dimmed, lightly blurred deck: a large input, grouped results with a kind label on the right (the active row adds an Enter mark), a footer of key hints and the result count, and a "No signal" message when nothing matches.
Click the **black hole** again to resume flow. HUD line under telemetry: green “flowing” / amber “locked”.
## Consoles
## HUD rail
- Orbits, Outposts, Activity and Snapshot open as console screens, and Restore opens from a snapshot: a centered panel under the navbar with an engraved label, a title and an Esc key, sized per console (`panelWidths` in `App.tsx`). They fade and rise with the shared spring, and the map behind is inert while one is open.
- Orbits is two columns. The left holds the outpost job history and one card per orbit (a failed orbit gets an ember edge; Capture is the single amber key). The right is the permanent New orbit form: Folder | Database and Via hub | Via outpost are `Segmented` switches, fields are recessed, and Cancel resets the form. Below 860 px the form stacks under the list.
- Outposts is a gate. With no code it shows a dark eye inside violet rings and one key, Open a wormhole. With a code it shows the code in large mono, a burn bar and a ticking time left (the bar counts down from the time the code was first seen, since the hub sends only the expiry), the agent command with a Copy key, and Generate fresh code. Outpost health is a roster with a lamp, last activity and an Online or Silent label; an outpost is online if it was seen in the last two minutes.
- Selects are themed (`ui/Select.tsx`, a drop-in for `<select>` that reads `<option>` children). The trigger is a recessed field with a chevron set in from the edge. The list is drawn in a portal so a console's scroll never clips it, flips above when there is no room below, and shows the active row with an amber edge and the chosen row with a check. Arrow keys, Home, End, type-ahead, Enter and Space work with focus kept on the trigger, and Escape closes only the list. A hidden input carries the value into forms, so `required` still validates.
- Activity is one log of backups and restores, and it only leads somewhere; it never acts. A row opens its snapshot (restores start there) or, for a backup that is running or failed and has no snapshot yet, its orbit. Rows are grouped Needs you (a restore in `recovery_required`, or a hub orbit whose last backup failed), Running now (with a five-tick position) and then days. A backup that stored a snapshot is one row. A restore whose snapshot retention has removed is shown without a link. Filter by text or by Backups and Restores. The Activity tab lamp turns ember while anything needs you. Data comes from the snapshot list, `GET /api/v1/capture-jobs`, which covers outpost orbits, `GET /api/v1/restore-jobs`, and the last status of hub orbits, which have no job list, so a failed one has no time. File exports are not logged: the hub keeps those sessions in memory and cannot list them, so a running export is followed from the Restore screen, which the footer reopens while one is active. The model is in `web/src/lib/activity.ts`.
- The Restore screen is two columns. The left chooses and confirms: the recovery point as a card, the snapshot select, and a Restore to database | Export file on hub switch (shown for managed database snapshots). Database mode picks a registered target, shows an amber warning that the target is replaced, and asks for the typed confirmation before Queue database restore is enabled. The right follows the work. For a database it is the newest restore job as a five-step progress list (Queued, Verifying, Safety backup, Applying restore, Complete); a failed step becomes an ember diamond with the hub's reason, and recovery acknowledgement appears there when the job needs it. Older jobs are listed compactly. For a file export it is the countdown ring, which keeps counting from the hub's session, with Abort on the left. Below 860 px the right column stacks under the left.
- The snapshot sheet opens from a moon, a history row or search. Its label says where the point sits (Recovery point · 1 of 4). A hero shows a small orbit with up to four moons and the chosen one lit; Captured, Payload (with the change against the previous snapshot of the same orbit) and Recovery sit in one plate; the id has a Copy key. Database recovery options (or Export file on hub) is the primary key, Download is secondary, and Delete is deliberately quiet and asks for confirmation in an ember panel.
- Buttons are bevelled keys (`Button`, `.console-control`): raised with a top highlight, pressed with an inset shadow. Amber marks the one primary action, ember marks a destructive one.
Unchanged — ◎ ⟳ ◉ ◇ ↩ consoles; **Esc** dismisses.
## Data and rendering
## Data
- The map preserves each orbit's assigned slot across polling updates. Layout and snapshot grouping live in `web/src/lib/galaxyLayout.ts`.
- Snapshot summaries carry `orbit_id`. When connected to an older hub, the UI groups by name only if the name is unique.
- Successful capture preserves HTTP 204 and supplies `X-Tessera-Snapshot-Id` when it retained a new snapshot. Automatic decay applies to that orbit's history.
- The orbits, markers, moons and selection are SVG on one animation clock. The black hole and the sky behind it are a single WebGL2 shader in `web/src/lib/blackhole/`. The clock pauses when the tab is hidden. Labels are laid out in screen coordinates.
- Stars: `GET /api/v1/orbits` (status → star color)
- Moons: `GET /api/v1/snapshots` grouped by `orbit_name`, max 6 per star
## Black hole renderer
## Demo
- Each pixel is a light ray traced through Schwarzschild spacetime (`geodesic.ts`, mirrored in the GLSL in `shaders.ts`). Rays that fall in are black, rays that cross the disk plane pick up Doppler-beamed disk light, and rays that escape sample the sky. The shadow, the arch of the far side of the disk, the second image and the Einstein ring all come from that, not from artwork. Far from the hole the integrator is skipped for the weak-field deflection. The thin ring hugging the shadow is real: it is light that skimmed the photon sphere. It stays on by default, and `rimCut` can fade it out.
- The proportions follow reference imagery of a thin disk seen from a low angle: the disk reaches about 26 M, roughly five times the shadow's radius, the camera sits 8° above the disk plane, the disk is optically thick near the hole and thins toward its rim, and its brightness falls steeply outward. In the app the shadow is 34 scene units across its radius, so the disk ends just past the first orbit ring. The disk plane is not the orbit plane: the orbits keep their own 0.68 tilt.
- The orbit overlay has two looks that follow the radar wave. In the realistic look each orbit is a star: a bright core, a glow tinted by status (mint when healthy, amber while working, ember red when failed) and four diffraction spikes, which the sky's own stars never have, so a marker cannot be mistaken for scenery. The orbit tracks recede to a faint trace; hovering a marker reveals its shell, and the selected orbit keeps its bright dashed ring. While the map flows, each marker trails a tapered comet tail back along its orbit, which lengthens with speed. Stars shimmer: each scales and brightens slightly out of phase with the others, and working and failed stars move the most. The shimmer rides the scene loop that is already running, so a stopped map is perfectly still, and it is off under reduced motion. Hovering a star enlarges it with the shared spring. Status is still carried by shape as well as colour: failed keeps its diamond and busy keeps its dashed ring. In the radar look the markers are plain instrument dots and the tracks are drawn at full strength. Each marker and track ring takes the look at its own distance from the hole, so they change as the wave front passes. The renderer exposes this as `signal.lookAt` and calls `signal.onLook` while the wave runs.
- The disk's texture is filtered by how many pixels each feature covers: noise octaves too fine to resolve collapse to their mean and melt into a smooth glow, so thin lines cannot alias into moire. Light bent a long way round the hole is squeezed onto fewer pixels, so it is filtered harder. The gas shears with differential rotation, and the whole pattern flows faster near the hole.
- **Camera.** Drag the map to turn the view: dragging sideways walks the camera round the hole (`yaw`), dragging down raises it above the orbit plane and dragging up lowers it (`lift`, from nearly edge-on to steeply from above). Click the black hole to spring back to the default view by the short way round. The whole scene turns together: the shader's camera takes an azimuth and an elevation (`uAzimuth`, `uElevation`), and the orbit overlay is projected through the same view in `galaxyLayout.ts` (`orbitPose`, `trailAngle` and `project` take a `View`; the default view is the map's old one). Rings open into circles or flatten into lines, stars and rockets move along them, a star behind the hole's shadow is hidden by it, and the disk's bright side and the lensed sky change as they would. A press that starts on a marker or a moon still selects it. While the camera moves, markers, rings and rockets are placed straight onto the SVG and labels and moons are hidden; they are laid out again once it rests. A camera at rest costs nothing: the black hole is redrawn only while the view differs from the last draw, at the tier's rate (15 fps on the still tier). On touch screens a sideways drag turns the map and a vertical one still scrolls the page; Big Screen takes both. The camera has no keyboard control yet; the register and the search reach every orbit without it.
- The sky must never rival the orbit markers drawn over it. Point sources in the bake (stars and distant galaxies) are small, few, and capped in brightness (`POINT_CAP`), and every marker has a soft dark backing disc and a dark outline, so it stays readable over any haze. Treat both as a contract: a sky change that adds bright features near the orbits breaks clickability.
- The sky is baked once into a cubemap at load and sampled per pixel. It is a procedural galaxy with a bulge, dust lanes, nebulae, distant galaxies and stars.
- The canvas sits under the whole scene panel and follows `.galaxy-frame` through its bounding rectangle, so the hole stays centred on the orbits while the frame springs between the workspace and Big Screen. Drawing happens in Motion's post-render step so it never lags the frame's transform.
- The galaxy loop publishes its disk clock and the capture absorption to the renderer through a shared signal, so Flowing, coasting and capture spin-up drive the disk. A locked map renders once and sleeps.
- Quality adapts to the device. A few synchronised frames are timed at startup and after a resize, and the tier steps down until the median fits the frame budget: `high`, `medium`, `low`, `minimal`, then `still`, which freezes ambient motion. Ambient drawing is capped at 30 fps or lower. Tiers and the governor live in `quality.ts`.
- Without WebGL2, or after a lost context, the scene falls back to the SVG core and backdrop.
- The map is a cockpit canopy: chamfered corners with a bezel line and corner screws (`.canopy-frame`, drawn over the map and ignoring pointer events), clipped by `.vault-scene`'s `clip-path`. Big Screen drops the frame. The bezel stays neutral in both looks.
- The deck around the canopy follows the same vocabulary: the navbar is a tray of switches with a lamp per tab (the thumb still springs and drags), the overview is a slim telemetry rail, consoles carry an engraved label and a corner screw, and status lamps glow and stay distinct by shape. The canopy's sill holds the legend, the view switch and the motion and big-screen controls; below 760 px, and in Big Screen, the controls move up to the map toolbar.
- Icon-only keys (Pause or Resume motion, Big screen, Sign out, Search) share one size, `--key`, and one gap, `--key-gap`, and keep their names in `aria-label` and the tooltip. Read-outs that sit beside keys (Hub online, the Big Screen status and telemetry) are recessed plates of the same height. Telemetry readings carry a lamp: ice for orbits, mint for failed at zero, ember diamond for failed above zero, a pale diamond for snapshots, violet for payload.
- **Window | Radar** is a two-position view switch on the canopy sill (`ViewSwitch` in `VaultScene.tsx`, a `radiogroup`; arrow keys move between positions). Its thumb rides the shared spring and tints amber for the window and mint for radar. It switches between the realistic and radar looks. The choice is remembered per browser. Without WebGL2 the button is hidden. The radar sweep runs on its own clock rather than the scene's, so it keeps turning on a locked map. Reduced motion switches looks at once and holds the sweep still and evenly lit, and the still quality tier does the same. A page that loads with the radar look applies it at once, with no wave. While the sweep runs the map redraws at the tier's frame-rate cap, so radar costs more battery than a locked realistic map, which draws nothing.
- The radar look draws range rings every 6 M, a bearing scale at 30 M just outside the disk, a crosshair and a rotating sweep head whose phosphor fades behind it. The lensed grid only shows outside about 20 M, so it never crowds the disk. The disk is drawn as contour bands equal in log brightness, and the long dim outer disk stays faint so the inner contours carry the weight.
- A realistic and a stylized radar look share the same trace. The radar look arrives as a wave spreading outward from the hole: each pixel picks its look from its distance to a spring-driven front, with a thin leading edge (mint going to radar, amber coming back). `look.ts` holds the spring and queues a request made mid-wave rather than reversing it.
`TESSERA_DATA_DIR=... tessera seed-demo --force` for 12+ stars.
## Build
## Orbit activity
```bash
cd web && npm run build
cargo build --release -p tessera-hub
What a backup is doing is shown by how a light moves, not by a drawing of a rocket. The light is a small glowing triangle that points where it is going, with a trail that follows the path it actually flew. The code is in `web/src/lib/orbitActivity.ts` (what happened), `rocket.ts` (the physics) and `trail.ts`, drawn by `RocketSprites.tsx`.
- **Where the events come from.** The scene compares each orbit's status between polls. A click shows its own verdict until a poll that began after it has landed, so one backup is never animated twice and never flips through a stale status. A page that loads, or an orbit that appears, only sets a baseline: running orbits start circling and finished ones stay settled, so opening the page never replays history. A backup that finished between two polls still gets its outcome.
- **Queued.** The light waits docked on its star with a dim engine.
- **Running.** It circles its star, climbing and spinning up the longer it runs.
- **Success.** When the status turns completed, the light waits for a launch window, the point on its circle where its own motion already carries it round the black hole and a little inward, then departs with the velocity it has. It follows the pseudo-Newtonian pull of the black hole, `mu / (r - r_s)^2`, after a short burn that trims its angular momentum to just under the capture limit. The path curves with the orbits instead of running straight in, the speed rises all the way, and near the shadow the light reddens, dims and stretches as gravitational redshift and tidal forces would, so it is gone by the shadow's edge. The disk spins up as it feeds, then the new snapshot flashes once its confirmed entry is listed.
- **Failure.** If the hub can tell the cause (`dump_failed`, `upload_failed`), a failure before departure explodes in place; a failure while carrying the payload launches, loses power and falls back to its star. Otherwise it explodes. The star keeps its busy look until that moment and then turns red.
- **Rehearsal.** A faint dashed light circles, then lands back on its star without leaving. The result is amber, since nothing was stored.
- **Limits.** At most ten lights are drawn at once; further working orbits keep their busy ring. Reduced motion draws no lights, and every outcome shows at once.
- **Verification.** `capture-galaxy.mjs` checks the lights by `data-orbit`. The physics has unit tests that hold the properties that matter for every shell and launch phase: it always arrives, it curves, and it never slows on the way in.
## Animation guideline
- Use the installed Framer Motion API from `motion/react`. Declarative `motion` components inherit the physics spring from `MotionConfig` in `web/src/main.tsx`. Use `uiSpring` for direct controls, `gentleSpring` for reveal and layout travel, and `ambientSpring` for scene effects. The tokens in `web/src/lib/motion.ts` define stiffness, damping, mass, and rest thresholds.
- Keep the element, its React key, and its MotionValues stable while a target can change. Update the scalar `animate` target, call `animate(value, nextTarget, uiSpring)` on the same MotionValue, or call `.set(nextTarget)` on a `useSpring` value. Motion automatically replaces the active animation and inherits the live value and velocity. Leave `from`, `velocity`, and fixed timing options unset for these retargets. For colors and other compound styles, spring a numeric mix amount or progress value and derive the visual property from it.
- Keep `AnimatePresence` mounted and use a stable child key so a reopening element can reverse its exit. Make an exiting overlay inert and release its hit area immediately. Track direct manipulation one-to-one and seed the spring with release velocity when handing control over from an external gesture.
- Keep CSS state changes immediate. Use Motion springs for visual transitions, including hover and loading feedback. Reserve repeating springs for ambient indicators and give them a static state under reduced motion. For continuous simulation, keep the path on its existing clock and spring its speed or progress. A new event can start a distinct path at its own origin.
- Prefer a small physical simulation to keyframes when something travels. A rocket's position and velocity are integrated, and each state only changes which forces act on it and never resets its velocity, so every transition is continuous and any one can be interrupted by another. Drive the parameters that shape it (spin, radius, engine thrust, opacity) with springs from `motion.ts`. If the snapshot list is still refreshing, let the arrival finish and hold the flash until its confirmed snapshot arrives.
- Measure the destination frame on a mode change or resize. Spring the map's center and size from its current visual rectangle, and recompute the collision layout once the frame settles.
- Honor live changes to `prefers-reduced-motion`. The app applies declarative targets immediately. Imperative effects must stop and jump to the appropriate static state themselves. Verify reversals before settling, the final target, and reduced motion in a browser.
## Local verification
Build the web UI before building the hub, which embeds the generated assets.
```sh
cd web
npm ci
npm run typecheck
npm test
npm run build
cd ..
cargo test --workspace --locked
cargo build --locked -p tessera-hub
```
To preview a populated scene, start the hub with `TESSERA_SEED_DEMO=1` and a fresh temporary `TESSERA_DATA_DIR`. Open the vault and select an orbit with snapshots to review the locked layout.
The optional `web/scripts/capture-galaxy.mjs` helper uses a local Playwright and Chromium installation. It saves Flowing and Locked screenshots in the system temporary directory by default. To exercise 55 orbits and simulated successful and failed captures against a running web build, use the browser fixture. It measures median and p95 frame intervals with Chromium CPU throttling and checks reversal, capture feedback, resizing, and reduced motion.
```sh
TESSERA_GALAXY_FIXTURE=1 CPU_THROTTLE=4 FRAME_P95_MAX_MS=33.4 \
TESSERA_URL=http://127.0.0.1:5173 node web/scripts/capture-galaxy.mjs
```
Set `VIEWPORT_WIDTH=3840 VIEWPORT_HEIGHT=2160` for a 4K viewport. Set `VERIFY_ANIMATION=0` to record a fixture baseline on older builds. If Playwright or Chromium is installed outside the web workspace, point `PLAYWRIGHT_MODULE` and `CHROMIUM_PATH` at those installations.

View File

@@ -0,0 +1,103 @@
# HTTP authorization contract
This is the authorization contract for every HTTP route the hub registers. The
`access_tests` suite generates its authorization matrix from the table below, and
the `auth_contract` tests fail if a registered route has no row, so the table and
the code cannot drift apart silently.
Order of checks, everywhere: authenticate, then resolve the resource, then apply
the gate. Grants are read from the database on every request, so a revoke takes
effect on the next request. The permissions that can be granted to a non-admin are
`orbit.read`, `snapshot.read`, `capture.run` and `snapshot.download`; every other
permission belongs only to a configured administrator, and anyone else gets 403
without any resource lookup. A resource outside the caller's scope answers 404, a
visible resource without the needed permission answers 403, and a list for which
the caller holds no access at all answers 403.
A human is an active user session or a service token with a grant; an Outpost
token is rejected on human routes. Cookie-authenticated mutations require a CSRF
token. An anonymous caller or a wrong token gets 401. Request parsing errors may
answer 400, 415 or 422 before the gate, but never expose data. An Outpost is an
active token with an owner assignment and, where it applies, a lease or fence; it
is not an admin or browser token. Job status and data are visible only within the
owner's scope, or to an administrator.
Loopback callers get no special treatment: when no credentials are configured and
local development mode is not explicitly enabled, requests are rejected, including
requests that arrive with forwarded-for headers claiming to be local.
| Route | Methods | Principal | Permission | Scope | Data allowed out |
| --- | --- | --- | --- | --- | --- |
| /health | GET | public | — | — | static liveness |
| /api-doc/openapi.json | GET | human | session.self | any signed-in caller | requires sign-in or the admin token; public only when TESSERA_PUBLIC_OPENAPI=true |
| /api/v1/operator/session | GET | public | — | current session | status, actor and CSRF token of the caller's own session; no-store |
| /api/v1/operator/session | DELETE | human | session.self | current session | nothing; CSRF required |
| /api/v1/me | GET | human | session.self | current principal | id, kind, auth method, display name, capabilities; no-store |
| /api/v1/auth/oidc/login | GET | public | — | OIDC configured | redirect to the IdP; sets one-time Lax correlation cookie; 404 when OIDC is off |
| /api/v1/auth/oidc/callback | GET | public | — | login transaction + correlation cookie | redirect to `/`; session cookie only on success, fixed error code otherwise; no tokens |
| /api/v1/access/grants | GET | human | access.manage | admin | list of grants, refresh grants per relation, roles, and which permissions are grantable and which are admin-only; no-store |
| /api/v1/access/grants | POST,PUT | human | access.manage | admin | POST: a new grant (role, permission, or list of permissions; global or per-orbit scope; expiry); PUT: atomically replace or extend the set of grants for the same person or group and orbit; the reason for a refusal is returned in `{"reason"}`; audited per id |
| /api/v1/access/grants/:id | DELETE | human | access.manage | admin | nothing; effective on the next request; audited |
| /api/v1/access/users | GET | human | access.manage | admin | list of users (no credentials); no-store |
| /api/v1/access/users/:id | PUT | human | access.manage | admin | nothing; deactivating a user also ends all of their sessions; not allowed on yourself or the emergency account |
| /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | nothing; all of the user's sessions end |
| /api/v1/me/preferences | GET,PUT | human | session.self | current account | the caller's own display choice (look: window or radar); no-store; CSRF on PUT; for tokens and dev sessions without an account GET is empty and PUT answers 404 |
| /api/v1/orbits/:id | PUT | human | orbit.manage | admin | name only (1-128 characters, no control characters, unique ignoring case); id, provider, schedule and retention are unchanged; existing snapshots show the current name; audited as `orbit.renamed` |
| /api/v1/orbits/:id/environment | PUT | human | orbit.manage | admin | nothing; labels the source (production, staging or development); audited |
| /api/v1/restore-targets/:id | PUT | human | relation.manage | admin | name only (1-128 characters, no control characters); id, identity, Outpost, relations and past jobs are unchanged; audited as `restore_target.renamed` |
| /api/v1/restore-targets/:id/environment | PUT | human | relation.manage | admin | active relations to a target labelled production end immediately; audited |
| /api/v1/relations | GET,POST | human | relation.manage | admin | list of relations, orbits and targets for the wizard (with identity); POST creates a relation or names the rule that refused it |
| /api/v1/relations/:id | PUT,DELETE | human | relation.manage | admin | PUT creates a new version (new id, grants do not carry over); DELETE deactivates; audited |
| /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | `refresh.run` grants per relation (user or group, expiry); audited |
| /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | effective on the next request; audited |
| /api/v1/refresh-relations | GET | human | refresh.run | granted relations | name and environment only; no identity, host, Outpost or application id; 403 without a grant |
| /api/v1/refresh-runs | GET,POST | human | refresh.run | granted relations | POST: relation_id + confirmation `REFRESH <source> TO <target> v<version>` + idempotency key; optional `undo_of` (id of the target's latest restore run that finished, was reconciled, or failed during apply): restore the target from that run's safety copy (422 `nothing_to_undo`; a safety copy is only accepted for its own target); optional `snapshot_id`: restore an existing snapshot of the relation's source orbit (not a safety copy, not another orbit's; 422 `snapshot_unusable`), otherwise the run takes a fresh capture; the caller does not choose the target; 404 for anyone without a grant; GET: the caller's own runs or those of granted relations (admin: all), without snapshot id or requester for non-admins |
| /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, requester, or holder of a grant on its relation | GET answers 404 for anyone else; DELETE only by the requester or an admin (other grant holders get 403) and only before apply, afterwards 409 |
| /api/v1/operator/login | POST | public | — | emergency account | opaque cookie and CSRF token; rate limited, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | filtered, safe metadata |
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | nothing; pins are checked |
| /api/v1/snapshots/:id/download | GET | human | snapshot.download | snapshot→orbit | raw archive: gzip or an already compressed format (`.sql.gz`, `.tar.gz`, `.sqlite.gz`, `.dump`), no Content-Encoding, no-store, nosniff; HEAD answers 405; export slots and disk are limited |
| /api/v1/orbits | GET | human | orbit.read | orbit | metadata without provider_config |
| /api/v1/orbits | POST | human | orbit.manage | admin | safe metadata |
| /api/v1/orbits/:id/retention | PUT | human | retention.manage | orbit | nothing |
| /api/v1/orbits/:id/run | POST | human | capture.run | orbit | safe job and status |
| /api/v1/orbits/:id/outpost | PUT | human | outpost.manage | orbit | explicit legacy assignment; managed orbits go through a capture profile |
| /api/v1/reconstitute | POST | human | recovery.manage | snapshot→orbit | administrative restore session, not self-service |
| /api/v1/reconstitute/:id | GET,DELETE | human | recovery.manage | restore session→snapshot→orbit | safe status; cancel before apply |
| /api/v1/wormhole/outposts | GET | human | outpost.manage | admin | names and status; no tokens |
| /api/v1/wormhole/pairing | POST | human | outpost.manage | admin | short-lived code |
| /api/v1/wormhole/claim | POST | public | pairing.consume | one-time code | new token returned once to the claimant; limited per source and globally; the code is stored only as a digest |
| /api/v1/wormhole/outposts/:id/rotate | POST | human | outpost.manage | paired Outpost | new token returned once (no-store); the old token stays valid for a grace period; audited |
| /api/v1/wormhole/outposts/:id/revoke | POST | human | outpost.manage | Outpost | nothing; every credential is rejected from the next request; audited |
| /api/v1/wormhole/upload/init | POST | outpost | upload.assigned | orbit owner | upload session id owned by the caller |
| /api/v1/wormhole/upload/chunk | POST | outpost | upload.assigned | session owner + orbit owner | nothing |
| /api/v1/wormhole/restic/commit | POST | outpost | upload.assigned | orbit owner + repository owner | snapshot id of the owner |
| /api/v1/capture-profiles | GET | human | orbit.read | profile→orbit | filtered profiles; no DSN |
| /api/v1/capture-profiles | POST | human | orbit.manage | orbit | safe profile |
| /api/v1/capture-profiles/:id | PUT | human | orbit.manage | admin | schedule and retention only (absent = unchanged, null = remove); same validation as POST; the schedule cursor moves to the time of the change; audited |
| /api/v1/capture-profiles/:id/jobs | POST | human | capture.run | profile→orbit | safe job |
| /api/v1/capture-jobs | GET | human | orbit.read | job→orbit | filtered history |
| /api/v1/capture-jobs/:id | GET | human | orbit.read | job→orbit | safe status |
| /api/v1/capture-jobs/:id/events | GET | human | orbit.read | job→orbit | phases and timestamps, no database logs |
| /api/v1/wormhole/capture/:application/claim | POST | outpost | capture.assigned | profile owner | lease owned by the caller |
| /api/v1/wormhole/capture/:id/report | POST | outpost | capture.assigned | job owner + lease | nothing |
| /api/v1/wormhole/capture/:id/payload | POST | outpost | capture.assigned | job owner + lease | nothing |
| /api/v1/wormhole/capture/:id/restic | POST | outpost | capture.assigned | job owner + lease + repository | commit of the owner |
| /api/v1/restore-targets | POST | human | orbit.manage | target→orbit | identity verified by an admin; no credentials |
| /api/v1/capture-profiles/:id/restore-targets | GET | human | recovery.manage | admin | target identity (instance, database) for admins only; no credentials |
| /api/v1/snapshots/:id/restore-targets | GET | human | recovery.manage | admin | target identity for admins only; no credentials |
| /api/v1/restore-jobs | GET,POST | human | recovery.manage | admin | administrative restore and the recent list; self-service refresh goes through relations (`refresh.run`) instead |
| /api/v1/snapshots/:id/restore-jobs | GET | human | recovery.manage | admin | restore history with target and actor; admin only |
| /api/v1/restore-jobs/:id | GET,DELETE | human | recovery.manage | job→snapshot + target | safe status; cancel before apply |
| /api/v1/restore-jobs/:id/reconcile | POST | human | recovery.manage | job→target | administrative recovery status |
| /api/v1/wormhole/restore-targets/:id/claim | POST | outpost | restore.assigned | target owner | lease + artifact metadata |
| /api/v1/wormhole/restore/:id/payload | GET | outpost | restore.assigned | job owner + lease/fence | raw payload, agent only |
| /api/v1/wormhole/restore/:id/report | POST | outpost | restore.assigned | job owner + lease/fence | nothing |
| /api/v1/wormhole/restore/:id/safety | POST | outpost | restore.assigned | job owner + lease/fence | safety snapshot of the owner |
| /api/v1/wormhole/restore/:id/apply | POST | outpost | restore.assigned | job owner + lease/fence | permission to apply, after revalidation |
The SPA and its assets are public and contain only the static UI, not vault data.
GET routes also answer HEAD, as Axum does, behind the same gate. Internal refresh
actions never grant free-standing `capture.run` or `snapshot.download`. Legacy
recovery stays an administrator path and is not a shortcut around self-service
refresh.

View File

@@ -1,2 +1,2 @@
[toolchain]
channel = "1.88.0"
channel = "1.89.0"

93
scripts/export-public.sh Executable file
View File

@@ -0,0 +1,93 @@
#!/usr/bin/env bash
# Build a clean, single-commit tree of the current HEAD for a fresh public repository. Nothing is pushed.
#
# Usage: TESSERA_PRIVATE_TERMS=/path/to/terms.txt scripts/export-public.sh /path/to/empty-dir
# scripts/export-public.sh --allow-unchecked /path/to/empty-dir
#
# TESSERA_PRIVATE_TERMS names a file, kept outside the repository, with one term per line (host names,
# customer names, internal systems, personal names). The export is refused when any term occurs in the exported
# tree. The variable must be set and the file must exist and contain at least one term; otherwise the script fails.
# Pass --allow-unchecked only if you knowingly want to skip that check.
#
# Independently of the terms file, a given terms file also enables two pattern checks on the export: personal
# e-mail addresses (anything that is not a documentation/placeholder address) and organisation-specific hosts.
set -euo pipefail
allow_unchecked=0
out=""
for arg in "$@"; do
case "$arg" in
--allow-unchecked) allow_unchecked=1 ;;
-*) echo "unknown option: $arg" >&2; exit 2 ;;
*) [ -z "$out" ] || { echo "only one target directory" >&2; exit 2; }; out="$arg" ;;
esac
done
[ -n "$out" ] || { echo "usage: $0 [--allow-unchecked] <empty-target-dir>" >&2; exit 2; }
terms="${TESSERA_PRIVATE_TERMS:-}"
if [ "$allow_unchecked" -eq 0 ]; then
if [ -z "$terms" ]; then
echo "refusing to export: TESSERA_PRIVATE_TERMS is not set (or pass --allow-unchecked to skip the private-terms check)" >&2
exit 1
fi
if [ ! -f "$terms" ]; then
echo "refusing to export: TESSERA_PRIVATE_TERMS=$terms is not a file" >&2
exit 1
fi
if ! grep -q '[^[:space:]]' "$terms"; then
echo "refusing to export: $terms contains no terms" >&2
exit 1
fi
fi
mkdir -p "$out"
[ -z "$(ls -A "$out" 2>/dev/null)" ] || { echo "target must be empty" >&2; exit 1; }
root="$(git rev-parse --show-toplevel)"
git -C "$root" diff --quiet HEAD || { echo "commit or stash first" >&2; exit 1; }
git -C "$root" archive HEAD | tar -x -C "$out"
# Local tooling and agent state never belongs in a public tree, even if an old commit tracked it.
for path in .serena .claude .cursor .idea .vscode graft floorplan .ignore web/AGENTS.md AGENTS.md CLAUDE.md \
web/blackhole-proto.html tasks; do
rm -rf "${out:?}/$path"
done
if [ -n "$terms" ] && [ -f "$terms" ] && grep -q '[^[:space:]]' "$terms"; then
fail=0
# 1. literal private terms (case-insensitive)
if hits="$(grep -rIl -i -F -f "$terms" "$out" --exclude-dir=node_modules)"; [ -n "$hits" ]; then
echo "private terms found in:" >&2
echo "$hits" >&2
fail=1
fi
# 2. personal e-mail addresses: any address that is not a documentation or no-reply placeholder
email='[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}'
placeholder='@(example\.(com|org|net|invalid)|[A-Za-z0-9.-]*\.(example|invalid|test|localhost)|users\.noreply\.github\.com|noreply\.[A-Za-z0-9.-]+)$|:(noreply|no-reply)@'
if hits="$(grep -rIoE "$email" "$out" --exclude-dir=node_modules --exclude=Cargo.lock --exclude=package-lock.json \
| grep -vE "$placeholder" || true)"; [ -n "$hits" ]; then
echo "possible personal e-mail addresses (review, then remove or allow-list):" >&2
echo "$hits" | sort -u >&2
fail=1
fi
# 3. organisation-specific hosts (any host label containing the org name after an @ or in a URL)
org="sen""kensha" # split so that this script does not match itself
if hits="$(grep -rIiEl "@[A-Za-z0-9.-]*$org|https?://[A-Za-z0-9.-]*$org" "$out" --exclude-dir=node_modules || true)"; [ -n "$hits" ]; then
echo "organisation-specific hosts found in:" >&2
echo "$hits" >&2
fail=1
fi
[ "$fail" -eq 0 ] || exit 1
else
echo "warning: --allow-unchecked given, so no check for private terms or personal e-mail addresses was made" >&2
fi
cat <<EOF
clean tree at $out; review it, then create the public history with a neutral author, for example:
cd "$out"
git init
git add -A
git -c user.name="<PUBLIC NAME>" -c user.email="<PUBLIC EMAIL OR noreply ADDRESS>" commit -m "Initial release"
Do not run a bare 'git commit' there: it would use your global git identity.
EOF

1
tests/auth-compat/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target/

3402
tests/auth-compat/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
[package]
name = "tessera-auth-compat"
version = "0.0.0"
edition = "2021"
rust-version = "1.88"
publish = false
license = "AGPL-3.0-or-later"
# Isolated spike: no auth dependency enters the application until A00 passes.
[workspace]
resolver = "2"
[dependencies]
async-trait = "0.1"
axum = "=0.7.9"
tower = { version = "0.5", features = ["util"] }
tokio = { version = "=1.40.0", features = ["full"] }
rusqlite = { version = "=0.31.0", features = ["bundled"] }
sha2 = "=0.10.8"
serde_json = "1"
time = "=0.3.47"
tower-sessions = { version = "=0.15.0", default-features = false }
openidconnect = { version = "=4.1.0", default-features = false, features = ["reqwest", "rustls-tls"] }
governor = { version = "=0.10.4", default-features = false, features = ["std"] }
async-compression = { version = "=0.4.36", default-features = false, features = ["tokio", "gzip"] }
casbin = { version = "=2.10.1", default-features = false, features = ["runtime-tokio"] }
rusqlite_migration = "=1.2.0"

116
tests/auth-compat/README.md Normal file
View File

@@ -0,0 +1,116 @@
# A00 compatibility spike
Evidence date: 11 November 2026. **Compatibility demonstrated; A00 acceptance
still open. This crate is not runtime authentication and does not prove OIDC
token validation, end-to-end revocation, or the self-service stories.**
Run from the repository root:
```sh
rtk proxy env CARGO_TARGET_DIR=target/auth-compat cargo test --locked --manifest-path tests/auth-compat/Cargo.toml
rtk cargo tree --manifest-path tests/auth-compat/Cargo.toml -i libsqlite3-sys
rtk cargo audit --file tests/auth-compat/Cargo.lock
```
The separate workspace/lockfile prevents experimental libraries entering the hub.
Keep this executable evidence until production implementations replace its tests.
No SQLx, second SQLite pool, external policy service, or workflow engine is used.
## Tested candidates
| Crate | Exact version | Features | Declared MSRV | License |
| --- | --- | --- | --- | --- |
| openidconnect | 4.1.0 | reqwest,rustls-tls; defaults off | 1.88 | MIT |
| reqwest | 0.12.28 (resolved) | OIDC feature closure | 1.64 | MIT OR Apache-2.0 |
| tower-sessions | 0.15.0 | defaults off | unspecified | MIT |
| governor | 0.10.4 | std; defaults off | unspecified | MIT |
| async-compression | 0.4.36 | tokio,gzip; defaults off | unspecified | MIT OR Apache-2.0 |
| casbin | 2.10.1 | runtime-tokio; defaults off | unspecified | Apache-2.0 |
| rusqlite_migration | 1.2.0 | defaults only | 1.70 | Apache-2.0 |
| time | 0.3.47 | defaults | 1.88 | MIT OR Apache-2.0 |
| rustls | 0.23.46 (resolved) | reqwest feature closure | 1.71 | Apache-2.0 OR ISC OR MIT |
All six tests pass with local `rustc 1.88.0` on aarch64-apple-darwin, Axum 0.7.9,
Tower 0.5.3, Tokio 1.40.0, rusqlite 0.31.0. No Linux image build was run.
Unspecified MSRV is not assumed: the locked dependency graph was compiled.
Declared licenses were inspected through `cargo info` and target-filtered
`cargo metadata`; cargo-deny has **not** been run, so this is not license clearance.
Tower 0.5 works with current session middleware using Axum 0.7's
`Extension<Session>`. Disable tower-sessions' Axum extractor feature. tower-cookies
still brings axum-core 0.5.6 alongside Axum's 0.4.5, but the actual router/layer
test passes: their extractor traits are not mixed. Do not upgrade Axum solely
to obtain the session extractor. Only one libsqlite3-sys (0.28.0) resolves, including
the migration helper. An Axum major upgrade and an ORM have not been justified.
## Checks and limits
- SQLite SessionStore: collision regeneration, digest-only key and data-only JSON
(never serialize Record containing the bearer ID), rotation invalidates old ID,
auth deadline survives rotation, idle/absolute expiry, stale save after delete
cannot recreate a revoked row. UPDATE-only save is essential. This spike uses
an in-memory SQLite connection, not durable hub sessions or a fake-clock suite.
- Production A07 must additionally bind sessions to active users and an
authoritative revocation generation/deadline: concurrent rotation/create can
otherwise create a new record after a bulk revoke. The spike does not prove
that stronger property. Do not copy it unchanged into runtime.
- Same 14-row exact actor/resource/action matrix for Casbin and SQLite grants:
no grant, reverse/unrelated relation, QA capture/download separation,
developer scope, service, Outpost, admin, anonymous and unknown action. Both
pass; removal denies on the next evaluation. Expiry/group/user-active/domain
safety guards still belong in A11 tests.
- Prefer typed permission + direct SQL grants for the fixed permission set.
Casbin still requires SQL persistence, reload/invalidation, list filtering and
domain guards, while the exact-scope query already implements this evaluator.
The prototype does not justify a new policy source/cache. Casbin is rejected
for runtime; this old comparison candidate also resolves unmaintained
smartstring. It is not a recommendation to ship casbin 2.10.1.
- governor keyed quota rejects source A's second request without consuming B's
quota. Semaphore admission and trusted-source extraction are A08 work.
- gzip magic, decompression and exact synthetic SQL bytes pass. Not an export
quota, memory, disconnect or disk-full benchmark (A21).
- OIDC HTTP client builds with redirects disabled and S256 PKCE. Discovery,
claims, signed fixtures, JWKS rotation/outage, nonce/state replay and IdP
browser verification remain A09/A25 work, not covered by this smoke test.
- rusqlite_migration can use the same Connection and advance user_version.
Production already has idempotent migrations; retain those until a numbered
baseline migration is designed in A24. No helper enters runtime yet.
## Audit evidence and release blockers
`cargo-audit 0.21.2` could not parse current RustSec CVSS 4 records. A temporary
0.22.0 installation (MSRV 1.85) under `/tmp/tessera-auth-tools` successfully
audited both lockfiles. No advisory ignore or weakened validation was added.
Initial baseline audit: **10 vulnerabilities**, plus two unmaintained warnings
and two Tokio unsound warnings. Initial spike: **12 vulnerabilities**. Updating
only the spike's resolved rustls/webpki to 0.23.46/0.103.16 and pinning time 0.3.47
removed its TLS/time findings; six tests still pass. Final spike still reports:
- [RUSTSEC-2026-0459](https://rustsec.org/advisories/RUSTSEC-2026-0459.html):
bundled SQLite via libsqlite3-sys 0.28.0; patched binding >=0.39.0.
- [RUSTSEC-2023-0071](https://rustsec.org/advisories/RUSTSEC-2023-0071.html):
RSA 0.9.10, patched >=0.10.0. openidconnect 4.1.0 still depends on 0.9.
Tessera's intended RP uses public-key verification, not RSA private-key
decryption/signing; document reachability before any narrowly scoped exception.
Do not silently suppress it or write a replacement verifier.
- Tokio 1.40.0 unsound warnings: RUSTSEC-2025-0023 and RUSTSEC-2026-0386;
a common patched branch is 1.51.6 (MSRV 1.71).
Workspace runtime TLS is **still** rustls 0.23.23/webpki 0.102.8 with its baseline
findings: RUSTSEC-2026-0346, -0285, -0348, -0349; webpki -0104, -0098, -0099,
-0049, -0382. The runtime manifest/lockfile was deliberately not changed by this
isolated experiment. Existing unmaintained warnings concern proc-macro-error and
rustls-pemfile. Release approval requires triage/remediation, not merely compilation.
Further A00 work: prove a patched SQLite baseline, test required upgrades across
workspace and old DBs, resolve/triage RSA and Tokio, run cargo-deny, and re-audit.
rusqlite 0.41.1 declares Rust 1.89, while libsqlite3-sys 0.39.0 declares 1.88;
do not assume the current compiler or migration helper supports the upgrade.
Record a separate compiler/binding migration slice if needed. No runtime auth
library has been selected as release-ready until these checks pass.
Primary API references were fetched through Context7:
`/ramosbugs/openidconnect-rs`, `/maxcountryman/tower-sessions`, `/apache/casbin-rs`.
Published package manifests/metadata and RustSec were checked directly; versions
were not selected solely from a `latest` documentation URL.

View File

@@ -0,0 +1,363 @@
//! Executable A00 experiments, not production authentication.
#[cfg(test)]
mod tests {
use async_trait::async_trait;
use rusqlite::{params, Connection, OptionalExtension};
use sha2::{Digest, Sha256};
use std::sync::{Arc, Mutex};
use time::{Duration, OffsetDateTime};
use tower_sessions::{
session::{Id, Record},
session_store, Session, SessionStore,
};
#[derive(Clone, Debug)]
struct Store(Arc<Mutex<Connection>>);
fn digest(id: &Id) -> Vec<u8> {
Sha256::digest(id.to_string().as_bytes()).to_vec()
}
impl Store {
fn new() -> Self {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE sessions (
digest BLOB PRIMARY KEY, data TEXT NOT NULL,
idle INTEGER NOT NULL, absolute INTEGER NOT NULL
)",
)
.unwrap();
Self(Arc::new(Mutex::new(conn)))
}
}
fn backend(e: rusqlite::Error) -> session_store::Error {
session_store::Error::Backend(e.to_string())
}
#[async_trait]
impl SessionStore for Store {
async fn create(&self, record: &mut Record) -> session_store::Result<()> {
let conn = self.0.lock().unwrap();
let absolute = record
.data
.entry("auth_deadline".into())
.or_insert_with(|| {
serde_json::json!(
(OffsetDateTime::now_utc() + Duration::hours(8)).unix_timestamp()
)
})
.as_i64()
.expect("server-owned auth deadline");
loop {
// Serialize only data: Record contains the raw bearer ID.
let inserted = conn.execute(
"INSERT INTO sessions VALUES (?1, ?2, ?3, ?4) ON CONFLICT(digest) DO NOTHING",
params![digest(&record.id), serde_json::to_string(&record.data).unwrap(),
record.expiry_date.unix_timestamp(),
absolute],
).map_err(backend)?;
if inserted == 1 {
return Ok(());
}
record.id = Id::default();
}
}
async fn save(&self, record: &Record) -> session_store::Result<()> {
// UPDATE only: a stale in-flight request must never resurrect a revoked row.
let changed = self
.0
.lock()
.unwrap()
.execute(
"UPDATE sessions SET data = ?2, idle = MIN(?3, absolute)
WHERE digest = ?1 AND idle > ?4 AND absolute > ?4",
params![
digest(&record.id),
serde_json::to_string(&record.data).unwrap(),
record.expiry_date.unix_timestamp(),
OffsetDateTime::now_utc().unix_timestamp()
],
)
.map_err(backend)?;
if changed == 0 {
return Err(session_store::Error::Backend("revoked or expired".into()));
}
Ok(())
}
async fn load(&self, id: &Id) -> session_store::Result<Option<Record>> {
let row: Option<(String, i64)> = self
.0
.lock()
.unwrap()
.query_row(
"SELECT data, MIN(idle, absolute) FROM sessions
WHERE digest = ?1 AND idle > ?2 AND absolute > ?2",
params![digest(id), OffsetDateTime::now_utc().unix_timestamp()],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.map_err(backend)?;
Ok(row.map(|(data, expiry)| Record {
id: *id,
data: serde_json::from_str(&data).unwrap(),
expiry_date: OffsetDateTime::from_unix_timestamp(expiry).unwrap(),
}))
}
async fn delete(&self, id: &Id) -> session_store::Result<()> {
self.0
.lock()
.unwrap()
.execute("DELETE FROM sessions WHERE digest = ?1", [digest(id)])
.map_err(backend)?;
Ok(())
}
}
fn record() -> Record {
Record {
id: Id::default(),
data: Default::default(),
expiry_date: OffsetDateTime::now_utc() + Duration::minutes(30),
}
}
#[tokio::test]
async fn session_collision_digest_rotation_expiry_and_revoke() {
let store = Store::new();
let mut first = record();
let deadline = (OffsetDateTime::now_utc() + Duration::minutes(5)).unix_timestamp();
first
.data
.insert("auth_deadline".into(), serde_json::json!(deadline));
store.create(&mut first).await.unwrap();
let mut collision = first.clone();
store.create(&mut collision).await.unwrap();
assert_ne!(first.id, collision.id);
let raw: String = store
.0
.lock()
.unwrap()
.query_row(
"SELECT group_concat(hex(digest) || data) FROM sessions",
[],
|r| r.get(0),
)
.unwrap();
assert!(!raw.contains(&first.id.to_string()));
let session = Session::new(Some(first.id), Arc::new(store.clone()), None);
session.insert("actor", "qa").await.unwrap();
session.cycle_id().await.unwrap();
session.save().await.unwrap();
assert_ne!(session.id().unwrap(), first.id);
assert!(store.load(&first.id).await.unwrap().is_none());
assert_eq!(session.get::<String>("actor").await.unwrap().unwrap(), "qa");
let rotated_deadline: i64 = store
.0
.lock()
.unwrap()
.query_row(
"SELECT absolute FROM sessions WHERE digest=?1",
[digest(&session.id().unwrap())],
|r| r.get(0),
)
.unwrap();
assert_eq!(
rotated_deadline, deadline,
"rotation must not extend absolute auth lifetime"
);
let stale = store.load(&session.id().unwrap()).await.unwrap().unwrap();
store.delete(&stale.id).await.unwrap();
assert!(store.save(&stale).await.is_err());
assert!(store.load(&stale.id).await.unwrap().is_none());
for column in ["idle", "absolute"] {
let mut r = record();
store.create(&mut r).await.unwrap();
store
.0
.lock()
.unwrap()
.execute(
&format!("UPDATE sessions SET {column} = 0 WHERE digest = ?1"),
[digest(&r.id)],
)
.unwrap();
assert!(store.load(&r.id).await.unwrap().is_none());
assert!(store.save(&r).await.is_err());
}
}
#[tokio::test]
async fn axum_07_accepts_current_session_layer_without_axum_extractor_feature() {
use axum::{
body::{to_bytes, Body},
http::Request,
routing::get,
Extension, Router,
};
use tower::ServiceExt;
use tower_sessions::SessionManagerLayer;
let app = Router::new()
.route(
"/",
get(|Extension(session): Extension<Session>| async move {
session.insert("actor", "qa").await.unwrap();
"ok"
}),
)
.layer(SessionManagerLayer::new(Store::new()));
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), 200);
assert!(response.headers().contains_key("set-cookie"));
assert_eq!(
to_bytes(response.into_body(), 32).await.unwrap().as_ref(),
b"ok"
);
}
#[tokio::test]
async fn gzip_content_and_keyed_limiter() {
use async_compression::tokio::bufread::{GzipDecoder, GzipEncoder};
use tokio::io::{AsyncReadExt, BufReader};
let original = b"CREATE TABLE synthetic (id INTEGER);\n";
let mut gzip = Vec::new();
GzipEncoder::new(&original[..])
.read_to_end(&mut gzip)
.await
.unwrap();
assert_eq!(&gzip[..2], &[0x1f, 0x8b]);
let mut decoded = Vec::new();
GzipDecoder::new(BufReader::new(&gzip[..]))
.read_to_end(&mut decoded)
.await
.unwrap();
assert_eq!(decoded, original);
let limiter = governor::RateLimiter::keyed(governor::Quota::per_minute(
std::num::NonZeroU32::new(1).unwrap(),
));
assert!(limiter.check_key(&"source-a").is_ok());
assert!(limiter.check_key(&"source-a").is_err());
assert!(limiter.check_key(&"source-b").is_ok());
}
#[test]
fn oidc_client_disables_redirects_and_uses_s256() {
use openidconnect::{reqwest, PkceCodeChallenge};
let _client = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
assert_eq!(challenge.method().as_str(), "S256");
assert!(verifier.secret().len() >= 43);
}
#[test]
fn migration_shares_sqlite_binding() {
use rusqlite_migration::{Migrations, M};
let mut conn = Connection::open_in_memory().unwrap();
Migrations::new(vec![M::up("CREATE TABLE fixture (id INTEGER PRIMARY KEY)")])
.to_latest(&mut conn)
.unwrap();
assert_eq!(
conn.query_row("PRAGMA user_version", [], |r| r.get::<_, i64>(0))
.unwrap(),
1
);
}
#[tokio::test]
async fn casbin_and_sql_grants_have_the_same_deny_and_revoke_matrix() {
use casbin::prelude::*;
let model = DefaultModel::from_str(
"[request_definition]\nr = sub, obj, act\n[policy_definition]\np = sub, obj, act\n\
[policy_effect]\ne = some(where (p.eft == allow))\n\
[matchers]\nm = r.sub == p.sub && r.obj == p.obj && r.act == p.act",
)
.await
.unwrap();
let mut enforcer = Enforcer::new(model, MemoryAdapter::default())
.await
.unwrap();
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE grants (actor TEXT, resource TEXT, action TEXT,
PRIMARY KEY(actor, resource, action))",
)
.unwrap();
let grants = [
("qa", "prod->stage", "refresh.run"),
("developer", "prod", "snapshot.download"),
("service", "stage", "capture.run"),
("admin", "prod", "orbit.manage"),
];
for (actor, resource, action) in grants {
enforcer
.add_policy(vec![actor.into(), resource.into(), action.into()])
.await
.unwrap();
conn.execute(
"INSERT INTO grants VALUES (?1, ?2, ?3)",
params![actor, resource, action],
)
.unwrap();
}
let matrix = [
("qa", "prod->stage", "refresh.run", true),
("qa", "stage->prod", "refresh.run", false),
("qa", "prod->dev", "refresh.run", false),
("qa", "prod", "capture.run", false),
("qa", "prod", "snapshot.download", false),
("developer", "prod", "snapshot.download", true),
("developer", "stage", "snapshot.download", false),
("developer", "prod", "capture.run", false),
("service", "stage", "capture.run", true),
("service", "prod", "capture.run", false),
("outpost", "prod", "orbit.manage", false),
("admin", "prod", "orbit.manage", true),
("anonymous", "prod", "orbit.manage", false),
("admin", "prod", "unknown", false),
];
for (actor, resource, action, expected) in matrix {
let sql: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM grants WHERE actor=?1 AND resource=?2 AND action=?3)",
params![actor, resource, action], |r| r.get(0)).unwrap();
assert_eq!(sql, expected, "SQL {actor}/{resource}/{action}");
assert_eq!(
enforcer.enforce((actor, resource, action)).unwrap(),
expected,
"Casbin {actor}/{resource}/{action}"
);
}
enforcer
.remove_policy(vec![
"qa".into(),
"prod->stage".into(),
"refresh.run".into(),
])
.await
.unwrap();
conn.execute("DELETE FROM grants WHERE actor='qa'", [])
.unwrap();
assert!(!enforcer
.enforce(("qa", "prod->stage", "refresh.run"))
.unwrap());
assert!(!conn
.query_row(
"SELECT EXISTS(SELECT 1 FROM grants WHERE actor='qa')",
[],
|r| r.get::<_, bool>(0)
)
.unwrap());
}
}

39
tests/fixtures/README.md vendored Normal file
View File

@@ -0,0 +1,39 @@
# Backup fixtures
Use a clean development host with Restic, PostgreSQL client/server tools, MySQL client tools, OpenSSL, OpenSSH, Docker, AWS CLI, Node.js and Python 3.9+. The SSH fixture uses a temporary loopback `sshd` and generated keys. Some Linux hosts require the distro's SSH privilege separation directory to exist before a non-root fixture can start.
```sh
rtk proxy npm --prefix web run build
rtk cargo build --workspace
rtk cargo test --workspace
rtk cargo test -p tessera-store -- --ignored
rtk proxy python3 tests/fixtures/restic-orbits.py
rtk proxy python3 tests/fixtures/capture-postgres.py
rtk proxy python3 tests/fixtures/capture-mysql.py
rtk proxy python3 tests/fixtures/restore-postgres.py
rtk proxy python3 tests/fixtures/offsite.py
rtk proxy python3 tests/fixtures/browser.py
rtk proxy python3 tests/fixtures/legacy-import.py
rtk proxy python3 tests/fixtures/matrix.py
```
- Restic orbits requires `rest-server` and `htpasswd` on PATH. It checks the four source/access combinations with a TLS Rest Server, re-runs after small changes, and verifies filesystem and PostgreSQL restores. Add `--mysql` to include MySQL capture and restore through both access modes.
- PostgreSQL covers direct TLS, verified PostgreSQL TLS through a pinned bastion, a mismatched hostname, a wrong host key, partial upload, a competing outpost, retry after a dropped reply, and a real restore to a second database.
- MySQL starts `mysql:9.2` by default. Use the matching `mysqldump` on PATH. Set `TESSERA_FIXTURE_MYSQL_IMAGE` to test a different server with a compatible client. The fixture covers direct and SSH capture, host-key failure, an engine error, and restore of data with a view, routine, and event.
- S3 starts `motoserver/moto:5.1.12` on loopback. It checks failed copy, retry, and export with the primary Restic repository offline.
- The browser test uses Playwright from Node's resolution path or `TESSERA_PLAYWRIGHT_MODULE` and its bundled Chromium or `TESSERA_FIXTURE_CHROME`. The fixture submits backup and restore jobs as an operator, exercises a capture-only profile, and verifies recovery status, the safety ID, and filesystem export. A fixture outpost handles the scoped job protocol.
- PostgreSQL restore verifies target identity, scoped payload access, checksum rejection, safety pinning, schema and recreate modes, a PostgreSQL 17 dump restored to PostgreSQL 14, restricted psql commands, and restart after reset. The fixture uses the PostgreSQL 14 host tools and the postgres:17 container for the newer source.
- The legacy import fixture reads compressed SQL archives from S3, restores synthetic samples, and verifies history access and idempotency after local GC.
- The matrix pairs three outposts, runs ten application profiles against isolated databases, exercises a scheduler tick for 02.00 WIB, and checks manual capture, scheduled capture, registered restore targets, and S3 copies. Its JSON output records durations, freshness, size and restore results.
## Fixture mapping
| Case | Fixture | Placement to validate |
| --- | --- | --- |
| Direct PostgreSQL | TLS to a loopback server, mismatched hostname case | Run the agent where it can reach the database with the same TLS policy. |
| PostgreSQL behind a bastion | TLS through a loopback SSH bastion, wrong host key case | Run near the database if there is direct access. Otherwise use a pinned SSH forward to the database and validate the PostgreSQL server hostname. |
| MySQL behind SSH | Pinned SSH login, wrong host key and engine-error cases | Use the matched MySQL client on the SSH host and a private client options file. |
| Capture-only application | Profile without a restore target | Backups work; a restore request is refused until a target is registered. |
Verify deployed client and server versions, routes and privileges on the real hosts before relying on a placement.

115
tests/fixtures/browser.mjs vendored Normal file
View File

@@ -0,0 +1,115 @@
import assert from "node:assert/strict";
import { createRequire } from "node:module";
const { chromium } = createRequire(import.meta.url)(process.env.TESSERA_PLAYWRIGHT_MODULE || "playwright");
const [baseURL, password, captureOnly, filesystemSnapshot] = process.argv.slice(2);
const browser = await chromium.launch({
executablePath: process.env.TESSERA_FIXTURE_CHROME || undefined,
});
try {
const context = await browser.newContext({ baseURL, viewport: { width: 1100, height: 820 } });
const page = await context.newPage();
const errors = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.goto("/");
await page.getByRole("heading", { name: "Operator sign-in" }).waitFor();
const orbitsStatus = () => page.evaluate(async () => (await fetch("/api/v1/orbits")).status);
assert.equal(await orbitsStatus(), 401);
await page.getByLabel("Operator password").fill(password);
await page.getByRole("button", { name: "Sign in", exact: true }).click();
await page.getByRole("heading", { name: "Orbital vault" }).waitFor();
assert.equal(await orbitsStatus(), 200);
const pairingWithoutCsrf = await page.evaluate(async () =>
(await fetch("/api/v1/wormhole/pairing", { method: "POST" })).status);
assert.equal(pairingWithoutCsrf, 403);
await page.getByRole("button", { name: "Restore", exact: true }).click();
await page.getByRole("heading", { name: "Restore snapshot" }).waitFor();
await page.getByRole("combobox", { name: "Snapshot", exact: true }).selectOption(captureOnly);
await page.getByText("This application has no registered restore targets.").waitFor();
assert.equal(await page.getByRole("button", { name: "Queue database restore" }).count(), 0);
await page.getByRole("button", { name: "Close", exact: true }).click();
await page.getByRole("button", { name: "Orbits", exact: true }).click();
await page.getByRole("heading", { name: "Outpost backup jobs" }).waitFor();
await page.getByRole("button", { name: "Add an orbit" }).click();
await page.getByLabel("Backup source").selectOption("database");
await page.getByLabel("Database engine").selectOption("mysql");
assert.equal(await page.getByLabel("Database host").count(), 1);
await page.getByLabel(/^Access/).selectOption("outpost");
assert.equal(await page.getByLabel("Database host").count(), 0);
await page.getByLabel("Backup source").selectOption("filesystem");
await page.getByLabel("Name", { exact: true }).fill("Browser Outpost folder");
const savedOrbit = page.waitForResponse((response) =>
response.url().endsWith("/api/v1/orbits") && response.request().method() === "POST");
await page.getByRole("button", { name: "Save orbit" }).click();
const saved = await savedOrbit;
assert.equal(saved.ok(), true);
const orbit = await saved.json();
assert.equal(orbit.source, "filesystem");
assert.equal(orbit.access, "outpost");
const profile = page.getByRole("heading", { name: "Register Outpost backup profile" }).locator("..");
assert.equal(await profile.getByLabel("Database engine").count(), 0);
const outpost = profile.getByLabel("Assigned Outpost");
await outpost.getByRole("option", { name: /Browser fixture outpost/ }).waitFor({ state: "attached" });
await outpost.selectOption(await outpost.getByRole("option", { name: /Browser fixture outpost/ }).getAttribute("value"));
const registeredProfile = page.waitForResponse((response) =>
response.url().endsWith("/api/v1/capture-profiles") && response.request().method() === "POST");
await profile.getByRole("button", { name: "Register profile" }).click();
const registered = await registeredProfile;
assert.equal(registered.ok(), true);
assert.equal((await registered.json()).format, "filesystem");
await page.getByRole("combobox", { name: "Application", exact: true })
.selectOption({ label: "Browser fixture database" });
await page.getByRole("combobox", { name: "Job status" }).selectOption("failed");
await page.getByRole("button", { name: /Source preparation failed or timed out/ }).click();
await page.getByText("Preparing source", { exact: true }).waitFor();
await page.getByRole("combobox", { name: "Job status" }).selectOption("running");
await page.getByText("No jobs match these filters.").waitFor();
await page.getByRole("button", { name: "Back up selected application" }).click();
await page.getByText("Backup queued.").waitFor();
await page.getByRole("button", { name: "Open snapshot" }).click();
await page.getByRole("heading", { name: "Snapshot detail" }).waitFor();
const received = page.waitForEvent("download");
await page.getByRole("link", { name: "Download snapshot" }).click();
const download = await received;
const stream = await download.createReadStream();
const chunks = [];
for await (const chunk of stream) chunks.push(chunk);
assert.match(Buffer.concat(chunks).toString(), /INSERT INTO browser_fixture VALUES \(42\)/);
await page.getByRole("button", { name: "Recovery options" }).click();
const targetField = page.getByRole("combobox", { name: "Registered target" });
const targetOption = targetField.getByRole("option", { name: /^Browser staging target/ });
await targetOption.waitFor({ state: "attached" });
await targetField.selectOption(await targetOption.getAttribute("value"));
const restoreCode = await page.getByText(/^RESTORE [a-f0-9-]+ TO [a-f0-9-]+$/).textContent();
assert.equal(await page.getByRole("button", { name: "Queue database restore" }).isDisabled(), true);
await page.getByLabel("Restore confirmation").fill(restoreCode);
await page.getByRole("button", { name: "Queue database restore" }).click();
await page.getByText("Apply failed. Recovery required.", { exact: true }).waitFor();
await page.getByRole("link", { name: /^Safety backup [a-f0-9-]+$/ }).waitFor();
const recoveryCode = await page.getByText(/^RECONCILE [a-f0-9-]+$/).textContent();
await page.getByLabel("Reconciliation confirmation").fill(recoveryCode);
await page.getByRole("button", { name: "Mark target recovered" }).click();
await page.getByText("Recovery verified by operator", { exact: true }).waitFor();
await page.getByRole("combobox", { name: "Snapshot", exact: true }).selectOption(filesystemSnapshot);
await page.getByLabel("Export filename on hub").fill("filesystem.tar");
await page.getByRole("button", { name: "Begin file export" }).click();
await page.getByText("File export complete.", { exact: true }).waitFor();
await page.getByRole("button", { name: "Close", exact: true }).click();
await page.getByRole("button", { name: "Orbits", exact: true }).click();
await page.getByRole("button", { name: /Browser fixture database Backup completed/ }).click();
await page.getByRole("button", { name: "Open snapshot" }).click();
await page.getByRole("button", { name: "Delete snapshot" }).click();
await page.getByRole("button", { name: "Confirm deletion" }).click();
await page.getByRole("heading", { name: "Snapshot detail" }).waitFor({ state: "hidden" });
await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole("button", { name: "Sign out" }).click();
await page.getByRole("heading", { name: "Operator sign-in" }).waitFor();
assert.equal(await orbitsStatus(), 401);
assert.deepEqual(errors, []);
console.log("Browser sign-in, backup, download, database restore/reconciliation, filesystem export, and deletion verified");
} finally {
await browser.close();
}

Some files were not shown because too many files have changed in this diff Show More