Compare commits

...

77 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
167 changed files with 36187 additions and 2625 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"]

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

8
.gitignore vendored
View File

@@ -9,5 +9,11 @@ web/dist/
*.part *.part
.DS_Store .DS_Store
# graft's local graph cache — regenerable, not committed (run `graft build`). # Local tooling and editor/agent state: never part of the repository.
/.serena/
/.claude/
/.ignore
/graft/ /graft/
/floorplan/
/web/AGENTS.md
/web/blackhole-proto.html

View File

@@ -1,5 +0,0 @@
# graft's cards are gitignored but should stay greppable: ripgrep reads
# .ignore before .gitignore, so this re-admits the tree to search only.
!graft/
graft/.cache/
graft/.graph/

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.

1891
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -14,7 +14,7 @@ members = [
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
authors = ["Senkensha"] authors = ["The Tessera contributors"]
[workspace.dependencies] [workspace.dependencies]
anyhow = "1.0" anyhow = "1.0"
@@ -29,9 +29,9 @@ rand = "0.8"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
sha2 = "=0.10.8" sha2 = "=0.10.8"
rusqlite = { version = "=0.31.0", features = ["bundled"] } rusqlite = { version = "=0.41.1", features = ["bundled"] }
thiserror = "1.0" thiserror = "1.0"
tokio = { version = "=1.40.0", features = ["full"] } tokio = { version = "1.51.6", features = ["full"] }
tokio-cron-scheduler = "0.13" tokio-cron-scheduler = "0.13"
tower = "0.5" tower = "0.5"
tower-http = { version = "0.6", features = ["fs", "trace", "cors"] } tower-http = { version = "0.6", features = ["fs", "trace", "cors"] }

View File

@@ -1,28 +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 WORKDIR /build
COPY web/package.json web/package-lock.json* ./ COPY web/package.json web/package-lock.json* ./
RUN npm ci RUN npm ci
COPY web/ ./ COPY web/ ./
RUN npm run build RUN npm run build
FROM rust:1.88-bookworm AS rust FROM rust:1.89-bookworm@sha256:948f9b08a66e7fe01b03a98ef1c7568292e07ec2e4fe90d88c07bb14563c84ff AS rust
WORKDIR /build WORKDIR /build
COPY Cargo.toml Cargo.lock* ./ COPY Cargo.toml Cargo.lock* ./
COPY crates ./crates COPY crates ./crates
COPY --from=web /build/dist ./web/dist 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 restic/restic:0.19.1 AS restic FROM restic/restic:0.19.1@sha256:136600b6ff6843d61d355f7f71f460a166429f35de6fd11b568fece3c9a4d510 AS restic
FROM mysql:8.4 AS mysql-client FROM mysql:8.4@sha256:a81d043930e51745522bd5c430961cf8286f0a23f0a9a2a6e0108f7ea71b0902 AS mysql-client
FROM debian:bookworm-slim FROM debian:bookworm-slim@sha256:734a72b3d6142a71993b4bc580ca01d8ca687f77a2c422d96a961d3376b179bc
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client libstdc++6 && rm -rf /var/lib/apt/lists/* # Bookworm ships pg_dump 15, which refuses to dump a newer server. Install a
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/ # 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=restic /usr/bin/restic /usr/local/bin/restic
COPY --from=mysql-client /usr/bin/mysqldump /usr/local/bin/mysqldump COPY --from=mysql-client /usr/bin/mysqldump /usr/local/bin/mysqldump
RUN restic version && mysqldump --version 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_LISTEN=0.0.0.0:8787
ENV TESSERA_DATA_DIR=/data ENV TESSERA_DATA_DIR=/data
EXPOSE 8787 EXPOSE 8787
VOLUME ["/data"] VOLUME ["/data"]
USER tessera
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["/usr/local/bin/tessera-healthcheck"]
ENTRYPOINT ["tessera-hub"] ENTRYPOINT ["tessera-hub"]

View File

@@ -16,9 +16,14 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera-hub ./target/release/tessera-hub
``` ```
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`. 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. 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.
With neither operator sessions nor an admin token configured, the admin API is available on loopback only. Set `TESSERA_ADMIN_TOKEN` for API/CLI access and pass it as `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. To sign in from the dashboard, configure the separate [operator password hash](docs/DATABASE-CAPTURE.md#operator-sign-in). 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 ### Docker Compose
@@ -27,12 +32,30 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
docker compose up --build docker compose up --build
``` ```
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. The image includes `pg_dump` via `postgresql-client`. 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 ### CLI
```bash ```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' export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera init ./target/release/tessera init
./target/release/tessera orbit nightly --path ./docs ./target/release/tessera orbit nightly --path ./docs
@@ -69,6 +92,8 @@ The API accepts `{"retention":{"keep_daily":7,"keep_weekly":2,"keep_monthly":6,"
The same repository setup is used by new [Outpost backup profiles](docs/DATABASE-CAPTURE.md). 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. 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. 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.
@@ -79,6 +104,14 @@ The agent reads files to detect changes, sends missing chunks and metadata throu
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. 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 ## Architecture
See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tessera-store`, `tessera-providers`, `tessera-hub`, `tessera-agent`, `tessera-cli`. See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tessera-store`, `tessera-providers`, `tessera-hub`, `tessera-agent`, `tessera-cli`.
@@ -88,9 +121,11 @@ See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tesser
- 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. - 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. - 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. - 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 release image includes `pg_dump`; a native hub needs it on `PATH`. - 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`. - 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 is not implemented. The canvas does not attach `TESSERA_ADMIN_TOKEN`. - 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 ## 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

@@ -5,21 +5,58 @@ services:
- "127.0.0.1:8787:8787" - "127.0.0.1:8787:8787"
environment: environment:
TESSERA_LISTEN: "0.0.0.0:8787" TESSERA_LISTEN: "0.0.0.0:8787"
TESSERA_LOCAL_DEVELOPMENT: "false"
TESSERA_DATA_DIR: /data TESSERA_DATA_DIR: /data
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE} TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE}
TESSERA_ADMIN_TOKEN: TESSERA_ADMIN_TOKEN:
TESSERA_ADMIN_TOKEN_EXPIRES:
TESSERA_OPERATOR_PASSWORD_HASH: TESSERA_OPERATOR_PASSWORD_HASH:
TESSERA_OPERATOR_NAME: 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_REPOSITORY:
TESSERA_OFFSITE_PASSWORD_FILE: TESSERA_OFFSITE_PASSWORD_FILE:
AWS_ACCESS_KEY_ID: AWS_ACCESS_KEY_ID:
AWS_SECRET_ACCESS_KEY: AWS_SECRET_ACCESS_KEY:
AWS_SESSION_TOKEN: AWS_SESSION_TOKEN:
AWS_REGION: 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 RUST_LOG: tessera_hub=info
volumes: volumes:
- tessera-data:/data - tessera-data:/data
read_only: true
tmpfs:
- /tmp:size=256m,mode=1777
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
restart: unless-stopped restart: unless-stopped
healthcheck:
test: ["CMD", "/usr/local/bin/tessera-healthcheck"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s
volumes: volumes:
tessera-data: tessera-data:

View File

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

View File

@@ -226,19 +226,16 @@ fn connect_tls(
} }
fn load_certs(path: &std::path::Path) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> { fn load_certs(path: &std::path::Path) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>> {
let mut reader = use rustls::pki_types::{pem::PemObject, CertificateDer};
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?); CertificateDer::pem_file_iter(path)
rustls_pemfile::certs(&mut reader) .with_context(|| format!("open {}", path.display()))?
.collect::<Result<Vec<_>, _>>() .collect::<Result<Vec<_>, _>>()
.context("parse certificate") .context("parse certificate")
} }
fn load_key(path: &std::path::Path) -> Result<rustls::pki_types::PrivateKeyDer<'static>> { fn load_key(path: &std::path::Path) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
let mut reader = use rustls::pki_types::{pem::PemObject, PrivateKeyDer};
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?); PrivateKeyDer::from_pem_file(path).context("parse private key in client key file")
rustls_pemfile::private_key(&mut reader)
.context("parse private key")?
.context("no private key in client key file")
} }
#[allow(dead_code)] #[allow(dead_code)]

View File

@@ -13,7 +13,8 @@ use std::{
time::Duration, time::Duration,
}; };
use tessera_core::job::{ use tessera_core::job::{
CaptureFormat, CaptureLease, CaptureProgress, CaptureReport, ResticCaptureCommit, CAPTURE_HEARTBEAT_SECONDS, CaptureFormat, CaptureLease, CaptureProgress, CaptureReport, ResticCaptureCommit,
CAPTURE_HEARTBEAT_SECONDS,
}; };
use tessera_core::restore::DatabaseIdentity; use tessera_core::restore::DatabaseIdentity;
use tessera_providers::{MysqlSource, PostgresSource}; use tessera_providers::{MysqlSource, PostgresSource};
@@ -45,8 +46,15 @@ pub(super) enum Source {
Mysql(MysqlSource), Mysql(MysqlSource),
} }
impl Source { /// The local backup source, as far as the restore guard cares: which database it is.
pub(super) async fn identity(&self) -> Result<DatabaseIdentity> { #[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 { match self {
Self::Postgres(source) => source.identity().await, Self::Postgres(source) => source.identity().await,
Self::Mysql(source) => source.identity().await, Self::Mysql(source) => source.identity().await,
@@ -83,9 +91,9 @@ pub async fn run(cli: &Cli, path: &Path) -> Result<()> {
"capture timeout must be positive" "capture timeout must be positive"
); );
anyhow::ensure!( anyhow::ensure!(
profiles profiles.values().all(|profile| profile.source.is_some()
.values() || !profile.paths.is_empty()
.all(|profile| profile.source.is_some() || !profile.paths.is_empty() || !profile.targets.is_empty()), || !profile.targets.is_empty()),
"application requires a source or at least one restore target" "application requires a source or at least one restore target"
); );
let url = cli let url = cli
@@ -118,6 +126,7 @@ pub async fn run(cli: &Cli, path: &Path) -> Result<()> {
profile.source.as_ref(), profile.source.as_ref(),
&profile.targets, &profile.targets,
profile.timeout_seconds, profile.timeout_seconds,
Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS),
) )
.await?; .await?;
if !restored && (profile.source.is_some() || !profile.paths.is_empty()) { if !restored && (profile.source.is_some() || !profile.paths.is_empty()) {
@@ -195,7 +204,11 @@ async fn capture(hub: &Arc<Hub>, lease: &CaptureLease, profile: &Profile) -> Res
} }
let identity = match before { let identity = match before {
Some(identity) Some(identity)
if lease.profile.format.engine().is_some_and(|engine| identity.valid(engine)) if lease
.profile
.format
.engine()
.is_some_and(|engine| identity.valid(engine))
&& probe_identity(source).await.as_ref() == Some(&identity) => && probe_identity(source).await.as_ref() == Some(&identity) =>
{ {
Some(identity) Some(identity)
@@ -248,39 +261,73 @@ async fn commit_backup(
identity: Option<DatabaseIdentity>, identity: Option<DatabaseIdentity>,
) -> Result<()> { ) -> Result<()> {
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async { 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 repository = profile
.restic_repository
.as_deref()
.context("configure the profile Restic repository")?;
let mut command = crate::restic_command(repository)?; let mut command = crate::restic_command(repository)?;
if let Some(path) = &profile.restic_password_file { if let Some(path) = &profile.restic_password_file {
command.env_remove("RESTIC_PASSWORD").env_remove("RESTIC_PASSWORD_COMMAND") command
.env_remove("RESTIC_PASSWORD")
.env_remove("RESTIC_PASSWORD_COMMAND")
.env("RESTIC_PASSWORD_FILE", path); .env("RESTIC_PASSWORD_FILE", path);
} }
if let Some(path) = &profile.rest_server_password_file { if let Some(path) = &profile.rest_server_password_file {
let password = tokio::fs::read_to_string(path).await.context("read Rest Server password")?; let password = tokio::fs::read_to_string(path)
command.env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string()) .await
.env("RESTIC_REST_PASSWORD", password.trim_end_matches(['\r', '\n'])); .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)]); command.args([
"backup",
"--json",
"--quiet",
"--tag",
&format!("tessera-{}", lease.job_id),
]);
let sha256 = if let Some(mut file) = stage { let sha256 = if let Some(mut file) = stage {
let (file, hash) = tokio::task::spawn_blocking(move || { let (file, hash) = tokio::task::spawn_blocking(move || {
let (_, hash) = digest_file(&mut file)?; let (_, hash) = digest_file(&mut file)?;
file.seek(SeekFrom::Start(0))?; file.seek(SeekFrom::Start(0))?;
Ok::<_, anyhow::Error>((file, hash)) Ok::<_, anyhow::Error>((file, hash))
}).await??; })
command.args(["--stdin", "--stdin-filename", "payload"]).stdin(Stdio::from(file)); .await??;
command
.args(["--stdin", "--stdin-filename", "payload"])
.stdin(Stdio::from(file));
Some(hash) Some(hash)
} else { } else {
command.arg("--").args(&profile.paths); command.arg("--").args(&profile.paths);
None None
}; };
let snapshot_id = crate::restic_snapshot(command).await?; let snapshot_id = crate::restic_snapshot(command).await?;
let body = serde_json::to_value(ResticCaptureCommit { lease_id: lease.lease_id, snapshot_id, identity, sha256 })?; let body = serde_json::to_value(ResticCaptureCommit {
lease_id: lease.lease_id,
snapshot_id,
identity,
sha256,
})?;
for _ in 0..3 { for _ in 0..3 {
if hub.post(format!("capture/{}/restic", lease.job_id), body.clone(), None).await.is_ok() { if hub
.post(
format!("capture/{}/restic", lease.job_id),
body.clone(),
None,
)
.await
.is_ok()
{
return Ok(()); return Ok(());
} }
} }
anyhow::bail!("could not register the Restic snapshot") anyhow::bail!("could not register the Restic snapshot")
}).await; })
.await;
match result { match result {
Ok(Ok(())) => Ok(()), Ok(Ok(())) => Ok(()),
failure => { failure => {
@@ -320,6 +367,33 @@ impl Hub {
.await? .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( async fn report(
self: &Arc<Self>, self: &Arc<Self>,
lease: &CaptureLease, lease: &CaptureLease,

View File

@@ -211,15 +211,10 @@ async fn beam_restic(repository: &str, hub: &str, token: &str, orbit_id: uuid::U
let registered = reply["snapshot_id"] let registered = reply["snapshot_id"]
.as_str() .as_str()
.context("hub did not register the Restic snapshot")?; .context("hub did not register the Restic snapshot")?;
info!( info!(snapshot, registered, "committed Restic backup");
snapshot,
registered,
"committed Restic backup"
);
Ok(()) Ok(())
} }
fn restic_command(repository: &str) -> Result<tokio::process::Command> { fn restic_command(repository: &str) -> Result<tokio::process::Command> {
let authority = repository let authority = repository
.strip_prefix("rest:https://") .strip_prefix("rest:https://")
@@ -229,7 +224,8 @@ fn restic_command(repository: &str) -> Result<tokio::process::Command> {
"TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials" "TESSERA_RESTIC_REPOSITORY must be a rest:https:// URL without embedded credentials"
); );
let mut command = tokio::process::Command::new("restic"); let mut command = tokio::process::Command::new("restic");
command.env("RESTIC_REPOSITORY", repository) command
.env("RESTIC_REPOSITORY", repository)
.env_remove("RESTIC_REPOSITORY_FILE") .env_remove("RESTIC_REPOSITORY_FILE")
.stdin(std::process::Stdio::null()) .stdin(std::process::Stdio::null())
.kill_on_drop(true); .kill_on_drop(true);
@@ -237,13 +233,23 @@ fn restic_command(repository: &str) -> Result<tokio::process::Command> {
} }
async fn restic_snapshot(mut command: tokio::process::Command) -> Result<String> { async fn restic_snapshot(mut command: tokio::process::Command) -> Result<String> {
let output = command.output().await.context("starting restic (install restic on PATH)")?; let output = command
anyhow::ensure!(output.status.success(), "restic backup failed ({})", output.status); .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( let summary: serde_json::Value = serde_json::from_str(
std::str::from_utf8(&output.stdout)? std::str::from_utf8(&output.stdout)?
.lines() .lines()
.last() .last()
.context("missing restic summary")?, .context("missing restic summary")?,
)?; )?;
Ok(summary["snapshot_id"].as_str().context("missing restic snapshot ID")?.to_owned()) Ok(summary["snapshot_id"]
.as_str()
.context("missing restic snapshot ID")?
.to_owned())
} }

View File

@@ -1,12 +1,21 @@
use crate::{ use crate::{
http, http,
jobs::{digest_file, Hub, Source}, jobs::{digest_file, BackupSource, Hub},
}; };
use anyhow::{ensure, Context, Result}; use anyhow::{ensure, Context, Result};
use async_trait::async_trait;
use serde::Deserialize; use serde::Deserialize;
use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; use std::{
collections::HashMap,
fs::File,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
time::Duration,
};
use tessera_core::{ use tessera_core::{
job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS}, job::CaptureFormat,
restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
}; };
use tessera_providers::{MysqlRestore, PostgresRestore}; use tessera_providers::{MysqlRestore, PostgresRestore};
@@ -19,7 +28,108 @@ pub(super) enum Target {
Mysql(MysqlRestore), Mysql(MysqlRestore),
} }
impl Target { /// 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> { async fn identity(&self) -> Result<DatabaseIdentity> {
match self { match self {
Self::Postgres(target) => target.connection.identity().await, Self::Postgres(target) => target.connection.identity().await,
@@ -59,16 +169,17 @@ impl Target {
} }
} }
pub(super) async fn poll( pub(super) async fn poll<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &Arc<Hub>, hub: &H,
application: Uuid, application: Uuid,
source: Option<&Source>, source: Option<&S>,
targets: &HashMap<Uuid, Target>, targets: &HashMap<Uuid, T>,
timeout_seconds: u64, timeout_seconds: u64,
heartbeat: Duration,
) -> Result<bool> { ) -> Result<bool> {
for (target_id, target) in targets { for (target_id, target) in targets {
let reply = hub let reply = hub
.post( .send(
format!("restore-targets/{target_id}/claim"), format!("restore-targets/{target_id}/claim"),
serde_json::Value::Null, serde_json::Value::Null,
None, None,
@@ -81,20 +192,32 @@ pub(super) async fn poll(
lease.job.target.id == *target_id && lease.job.target.application_id == application, lease.job.target.id == *target_id && lease.job.target.application_id == application,
"hub returned an unexpected restore target" "hub returned an unexpected restore target"
); );
let permit_taken = AtomicBool::new(false);
let work = run( let work = run(
hub, hub,
&lease, &lease,
target, target,
source, source,
Duration::from_secs(timeout_seconds), Duration::from_secs(timeout_seconds),
&permit_taken,
); );
tokio::pin!(work); tokio::pin!(work);
loop { loop {
tokio::select! { tokio::select! {
biased; biased;
result = &mut work => return result.map(|()| true), result = &mut work => return result.map(|()| true),
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => { _ = tokio::time::sleep(heartbeat) => {
report(hub, &lease, RestoreProgress::Heartbeat).await?; 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");
}
} }
} }
} }
@@ -102,23 +225,24 @@ pub(super) async fn poll(
Ok(false) Ok(false)
} }
async fn run( async fn run<H: RestoreHub, T: RestoreTarget, S: BackupSource>(
hub: &Arc<Hub>, hub: &H,
lease: &RestoreLease, lease: &RestoreLease,
target: &Target, target: &T,
source: Option<&Source>, source: Option<&S>,
timeout: Duration, timeout: Duration,
permit_taken: &AtomicBool,
) -> Result<()> { ) -> Result<()> {
report(hub, lease, RestoreProgress::Checking).await?; report(hub, lease, RestoreProgress::Checking).await?;
let downloaded = tokio::time::timeout(timeout, async { let downloaded = tokio::time::timeout(timeout, async {
let input = download(hub, lease, timeout).await?; let input = hub.download(lease, timeout).await?;
target.prepare(input, lease).await target.prepare(input, lease).await
}) })
.await; .await;
let script = match downloaded { let script = match downloaded {
Ok(Ok(script)) => script, Ok(Ok(script)) => script,
_ => { other => {
report(hub, lease, RestoreProgress::InvalidPayload).await?; report_failed(hub, lease, RestoreProgress::InvalidPayload, why(other)).await?;
return Ok(()); return Ok(());
} }
}; };
@@ -126,7 +250,8 @@ async fn run(
let verified = tokio::time::timeout(timeout, async { let verified = tokio::time::timeout(timeout, async {
let identity = target.identity().await?; let identity = target.identity().await?;
ensure!( ensure!(
identity == lease.job.target.identity && identity != lease.artifact.identity, identity == lease.job.target.identity
&& (lease.artifact.rollback || identity != lease.artifact.identity),
"restore target identity does not match" "restore target identity does not match"
); );
if let Some(source) = source { if let Some(source) = source {
@@ -144,8 +269,8 @@ async fn run(
.await; .await;
let identity = match verified { let identity = match verified {
Ok(Ok(identity)) => identity, Ok(Ok(identity)) => identity,
_ => { other => {
report(hub, lease, RestoreProgress::WrongTarget).await?; report_failed(hub, lease, RestoreProgress::WrongTarget, why(other)).await?;
return Ok(()); return Ok(());
} }
}; };
@@ -158,48 +283,61 @@ async fn run(
target.identity().await? == identity, target.identity().await? == identity,
"target changed during safety capture" "target changed during safety capture"
); );
hub.upload( hub.upload_safety(lease, stage, timeout).await?;
format!("restore/{}/safety", lease.job.id),
stage,
timeout,
"x-tessera-restore-token",
lease.token,
None,
)
.await?;
Ok::<_, anyhow::Error>(()) Ok::<_, anyhow::Error>(())
}) })
.await; .await;
if !matches!(safety, Ok(Ok(()))) { if !matches!(safety, Ok(Ok(()))) {
report(hub, lease, RestoreProgress::SafetyFailed).await?; report_failed(hub, lease, RestoreProgress::SafetyFailed, why(safety)).await?;
return Ok(()); return Ok(());
} }
// The permit is single-use. A lost response leaves the target locked for reconciliation. // The permit is single-use. A lost response leaves the target locked for reconciliation. Mark it
hub.post( // 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), format!("restore/{}/apply", lease.job.id),
serde_json::Value::Null, serde_json::Value::Null,
Some(lease.token), Some(lease.token),
) )
.await?; .await?;
let applied = matches!( match tokio::time::timeout(timeout, target.apply(script)).await {
tokio::time::timeout(timeout, target.apply(script)).await, Ok(Ok(())) => report(hub, lease, RestoreProgress::Applied).await,
Ok(Ok(())) other => report_failed(hub, lease, RestoreProgress::ApplyFailed, why(other)).await,
); }
report(
hub,
lease,
if applied {
RestoreProgress::Applied
} else {
RestoreProgress::ApplyFailed
},
)
.await
} }
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> { /// Why a step did not succeed, in words: the error chain, or that it ran out of time.
hub.post( 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), format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?, serde_json::to_value(progress)?,
Some(lease.token), Some(lease.token),
@@ -208,28 +346,5 @@ async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress)
Ok(()) Ok(())
} }
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> { #[cfg(test)]
let hub = hub.clone(); mod tests;
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?
}

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 version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
publish = false
[[bin]] [[bin]]
name = "tessera" name = "tessera"

View File

@@ -33,6 +33,9 @@ pub struct ImportArgs {
/// Reconcile counts, times and sizes without downloading or writing snapshots. /// Reconcile counts, times and sizes without downloading or writing snapshots.
#[arg(long)] #[arg(long)]
inventory_only: bool, 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)] #[derive(Clone, Copy, ValueEnum)]
@@ -96,6 +99,12 @@ struct Report {
} }
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> { 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!( ensure!(
!args.prefix.is_empty() && args.prefix.ends_with('/'), !args.prefix.is_empty() && args.prefix.ends_with('/'),
"provide a per-application prefix ending in '/'" "provide a per-application prefix ending in '/'"
@@ -173,7 +182,7 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
.map(|path| import_history(vault, path)) .map(|path| import_history(vault, path))
.transpose()? .transpose()?
}; };
let report = Report { Ok(Report {
application: args.application, application: args.application,
bucket: args.bucket, bucket: args.bucket,
prefix: args.prefix, prefix: args.prefix,
@@ -181,13 +190,11 @@ pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
bytes, bytes,
history_snapshot_id, history_snapshot_id,
objects, objects,
}; })
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
} }
fn aws(args: &ImportArgs, operation: &str) -> Command { fn aws(args: &ImportArgs, operation: &str) -> Command {
let mut cmd = Command::new("aws"); let mut cmd = Command::new(&args.program);
cmd.args([ cmd.args([
"--no-cli-pager", "--no-cli-pager",
"--no-cli-auto-prompt", "--no-cli-auto-prompt",
@@ -285,3 +292,496 @@ fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
vault.import_legacy_payload(manifest, staged, taken_at)?; vault.import_legacy_payload(manifest, staged, taken_at)?;
Ok(id) 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

@@ -196,7 +196,7 @@ fn main() -> Result<()> {
} => cmd_reconstitute(&cli, snapshot_id, target)?, } => cmd_reconstitute(&cli, snapshot_id, target)?,
Commands::Decay { preset } => cmd_decay(&cli, &preset)?, Commands::Decay { preset } => cmd_decay(&cli, &preset)?,
Commands::Gc => { Commands::Gc => {
Vault::open(&vault_path(&cli.data_dir), require_passphrase(&cli)?)?.collect_garbage()? Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?.collect_garbage()?
} }
Commands::Wormhole { ref cmd } => match cmd { Commands::Wormhole { ref cmd } => match cmd {
WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?, WormholeCmd::Pair { code, name } => wormhole_pair(&cli, code, name)?,
@@ -326,7 +326,7 @@ fn cmd_snap(cli: &Cli, orbit_name: Option<String>) -> Result<()> {
} }
fn cmd_list(cli: &Cli) -> Result<()> { fn cmd_list(cli: &Cli) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
for s in vault.list_snapshots()? { for s in vault.list_snapshots()? {
let stored = s let stored = s
.stored_bytes .stored_bytes
@@ -345,14 +345,14 @@ fn cmd_list(cli: &Cli) -> Result<()> {
} }
fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> { fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> {
let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?; let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?;
println!("Reconstituted {n} bytes to {target}"); println!("Reconstituted {n} bytes to {target}");
Ok(()) Ok(())
} }
fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> { fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> {
let mut vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; let mut vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(cli)?)?;
let pruned = vault.prune_with_decay(preset)?; let pruned = vault.prune_with_decay(preset)?;
println!("{} snapshots decayed.", pruned.len()); println!("{} snapshots decayed.", pruned.len());
Ok(()) Ok(())

View File

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

View File

@@ -61,8 +61,13 @@ impl RetentionPolicy {
#[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)] #[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum CaptureRetention { pub enum CaptureRetention {
Age { days: u16 }, Age {
Count { #[serde(default = "fallback_count")] keep: u16 }, days: u16,
},
Count {
#[serde(default = "fallback_count")]
keep: u16,
},
} }
fn fallback_count() -> u16 { fn fallback_count() -> u16 {
@@ -90,13 +95,57 @@ pub fn evaluate_capture_retention(
now: DateTime<Utc>, now: DateTime<Utc>,
) -> Vec<Uuid> { ) -> Vec<Uuid> {
snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id))); snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id)));
snapshots.into_iter().enumerate().skip(1).filter_map(|(index, snapshot)| { snapshots
let expired = match policy { .into_iter()
CaptureRetention::Age { days } => now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days), .enumerate()
CaptureRetention::Count { keep } => index >= usize::from(keep), .skip(1)
}; .filter_map(|(index, snapshot)| {
expired.then_some(snapshot.id) let expired = match policy {
}).collect() 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. /// Keep the newest snapshot in each of the most recent occupied UTC periods.
@@ -175,7 +224,10 @@ pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec<SnapshotRef>) ->
let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new(); let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new();
for s in &snapshots { for s in &snapshots {
let key = (s.taken_at.year(), s.taken_at.month()); 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 { if s.taken_at > months[pos].2.taken_at {
months[pos] = (key.0, key.1, s.clone()); months[pos] = (key.0, key.1, s.clone());
} }
@@ -204,14 +256,23 @@ mod tests {
#[test] #[test]
fn capture_retention_keeps_one_old_archive_or_the_latest_five() { fn capture_retention_keeps_one_old_archive_or_the_latest_five() {
let now = Utc::now(); let now = Utc::now();
let snapshots: Vec<_> = (0..6).map(|i| SnapshotRef { let snapshots: Vec<_> = (0..6)
id: Uuid::new_v4(), .map(|i| SnapshotRef {
taken_at: now - Duration::days(15 + i), id: Uuid::new_v4(),
}).collect(); taken_at: now - Duration::days(15 + i),
assert_eq!(evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now), })
snapshots[1..].iter().map(|snap| snap.id).collect::<Vec<_>>()); .collect();
assert_eq!(evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now), assert_eq!(
[snapshots[5].id]); 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] #[test]
@@ -309,4 +370,469 @@ mod tests {
let forget = evaluate_decay(&policy, snaps); let forget = evaluate_decay(&policy, snaps);
assert_eq!(forget.len(), 3); 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." "Another orbit is still circling the vault. Try again when it finishes."
} }
TesseraError::WrongPassphrase => "That key doesn't unlock this vault.", TesseraError::WrongPassphrase => "That key doesn't unlock this vault.",
TesseraError::ProviderUnreachable(_) => { TesseraError::ProviderUnreachable(_) => "We couldn't reach the source at this outpost.",
"We couldn't reach the source at this outpost."
}
TesseraError::DiskFull { .. } => { TesseraError::DiskFull { .. } => {
"The vault is out of space—free room or widen the hold." "The vault is out of space—free room or widen the hold."
} }

View File

@@ -13,6 +13,23 @@ pub struct SnapshotManifest {
pub restore_hints: serde_json::Value, 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 { pub fn manifest_hash(manifest: &SnapshotManifest) -> String {
let json = serde_json::to_vec(manifest).expect("manifest serializes"); let json = serde_json::to_vec(manifest).expect("manifest serializes");
let digest = Sha256::digest(&json); let digest = Sha256::digest(&json);

View File

@@ -79,6 +79,9 @@ pub struct RestoreJob {
pub safety_snapshot_id: Option<Uuid>, pub safety_snapshot_id: Option<Uuid>,
pub created_at: i64, pub created_at: i64,
pub updated_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)] #[derive(Clone, Debug, Deserialize, Serialize)]
@@ -86,6 +89,10 @@ pub struct RestoreArtifact {
pub format: CaptureFormat, pub format: CaptureFormat,
pub identity: DatabaseIdentity, pub identity: DatabaseIdentity,
pub sha256: String, 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)] #[derive(Deserialize, Serialize)]
@@ -95,6 +102,27 @@ pub struct RestoreLease {
pub artifact: RestoreArtifact, 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)] #[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum RestoreProgress { pub enum RestoreProgress {

View File

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

View File

@@ -54,7 +54,10 @@ impl DemoOrbit {
} }
fn demo_id(kind: &str, name: &str) -> Uuid { 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> { pub fn apply(data_dir: &Path, vault_pass: &str, force: bool) -> Result<SeedReport> {
@@ -161,10 +164,7 @@ pub fn clear_demo(data_dir: &Path, vault_pass: &str) -> Result<()> {
let id = demo_id("orbit", o.slug).to_string(); let id = demo_id("orbit", o.slug).to_string();
conn.execute("DELETE FROM orbits WHERE id = ?1", params![id])?; conn.execute("DELETE FROM orbits WHERE id = ?1", params![id])?;
} }
conn.execute( conn.execute("DELETE FROM outposts WHERE id LIKE 'demo-%'", [])?;
"DELETE FROM outposts WHERE id LIKE 'demo-%'",
[],
)?;
} }
let vault_path = data_dir.join("vault"); let vault_path = data_dir.join("vault");
if vault_path.join("config").exists() { if vault_path.join("config").exists() {
@@ -416,7 +416,12 @@ mod tests {
assert!(orbit.snapshot_age(0) > Duration::zero()); assert!(orbit.snapshot_age(0) > Duration::zero());
for index in 1..orbit.snap_count { for index in 1..orbit.snap_count {
let gap = orbit.snapshot_age(index) - orbit.snapshot_age(index - 1); let gap = orbit.snapshot_age(index) - orbit.snapshot_age(index - 1);
assert!((gap - Duration::hours(orbit.interval_hours)).num_minutes().abs() < 45); assert!(
(gap - Duration::hours(orbit.interval_hours))
.num_minutes()
.abs()
< 45
);
} }
} }
} }

View File

@@ -3,6 +3,7 @@ name = "tessera-hub"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
publish = false
[[bin]] [[bin]]
name = "tessera-hub" name = "tessera-hub"
@@ -34,15 +35,23 @@ uuid.workspace = true
hex.workspace = true hex.workspace = true
sha2.workspace = true sha2.workspace = true
base64 = "0.22" 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 tempfile.workspace = true
indexmap = "=2.2.6" indexmap = "=2.2.6"
hyper = { version = "=1.12.0", features = ["server", "http1"] } hyper = { version = "=1.12.0", features = ["server", "http1"] }
hyper-util = { version = "=0.1.21", features = ["tokio"] } hyper-util = { version = "=0.1.21", features = ["tokio"] }
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] } rustls = { version = "=0.23.46", default-features = false, features = ["ring", "std"] }
rustls-pemfile = "=2.2.0"
tokio-rustls = "=0.26.2" tokio-rustls = "=0.26.2"
tower = { workspace = true } tower = { workspace = true }
[dev-dependencies] [dev-dependencies]
rcgen = "=0.13.2" 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 tokio.workspace = true

View File

@@ -1,24 +1,72 @@
use axum::http::{HeaderMap, StatusCode}; use axum::http::{HeaderMap, StatusCode};
use std::net::SocketAddr; use std::net::SocketAddr;
#[derive(Clone, Debug)] #[derive(Clone, Debug, Default)]
pub struct AdminGate { pub struct AdminGate {
pub token: Option<String>, 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 { impl AdminGate {
pub fn from_env() -> Self { pub fn from_env() -> anyhow::Result<Self> {
let token = std::env::var("TESSERA_ADMIN_TOKEN") let token = std::env::var("TESSERA_ADMIN_TOKEN")
.ok() .ok()
.map(|value| value.trim().to_string()) .map(|value| value.trim().to_string())
.filter(|value| !value.is_empty()); .filter(|value| !value.is_empty());
Self { token } 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) { pub fn log_policy(&self) {
if self.token.is_none() { 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!( tracing::warn!(
"TESSERA_ADMIN_TOKEN is unset; snapshot, orbit, reconstitute, and pairing APIs are open to loopback clients only" "explicit local development mode: loopback APIs allow anonymous access; do not proxy this listener"
); );
} else { } else {
tracing::info!( tracing::info!(
@@ -30,6 +78,9 @@ impl AdminGate {
pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> { pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> {
let presented = presented_token(headers); let presented = presented_token(headers);
match &self.token { match &self.token {
Some(_) if self.token_expired(chrono::Utc::now().timestamp()) => {
Err(StatusCode::UNAUTHORIZED)
}
Some(expected) => { Some(expected) => {
if presented.is_some_and(|value| tokens_match(expected, value)) { if presented.is_some_and(|value| tokens_match(expected, value)) {
Ok(()) Ok(())
@@ -37,12 +88,36 @@ impl AdminGate {
Err(StatusCode::UNAUTHORIZED) Err(StatusCode::UNAUTHORIZED)
} }
} }
None if peer.ip().is_loopback() => Ok(()), 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), 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> { fn presented_token(headers: &HeaderMap) -> Option<&str> {
if let Some(value) = headers if let Some(value) = headers
.get("x-tessera-admin-token") .get("x-tessera-admin-token")
@@ -65,6 +140,17 @@ fn presented_token(headers: &HeaderMap) -> Option<&str> {
} }
} }
/// `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 { pub(crate) fn tokens_match(expected: &str, presented: &str) -> bool {
let expected = expected.as_bytes(); let expected = expected.as_bytes();
let presented = presented.as_bytes(); let presented = presented.as_bytes();
@@ -86,15 +172,26 @@ mod tests {
} }
#[test] #[test]
fn loopback_without_a_token_is_the_only_open_path() { fn short_admin_tokens_are_refused() {
let gate = AdminGate { token: None }; 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(); let headers = HeaderMap::new();
assert!(gate assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers) .authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_ok()); .is_err());
assert!(gate assert!(gate
.authorize(peer(IpAddr::V6(Ipv6Addr::LOCALHOST)), &headers) .authorize(peer(IpAddr::V6(Ipv6Addr::LOCALHOST)), &headers)
.is_ok()); .is_err());
assert!(gate assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 4))), &headers) .authorize(peer(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 4))), &headers)
.is_err()); .is_err());
@@ -104,6 +201,8 @@ mod tests {
fn a_configured_token_is_required_on_loopback() { fn a_configured_token_is_required_on_loopback() {
let gate = AdminGate { let gate = AdminGate {
token: Some("secret-token".into()), token: Some("secret-token".into()),
local_development: false,
..Default::default()
}; };
let mut headers = HeaderMap::new(); let mut headers = HeaderMap::new();
assert!(gate assert!(gate
@@ -132,38 +231,112 @@ mod tests {
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers) .authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_err()); .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)] #[derive(Clone)]
pub struct SessionGate { pub struct SessionGate {
config: Option<std::sync::Arc<OperatorConfig>>, config: Option<std::sync::Arc<OperatorConfig>>,
state: std::sync::Arc<std::sync::Mutex<SessionState>>, db: crate::db::Db,
} /// Fingerprint of the OIDC configuration (issuer, client, admin mapping).
/// OIDC sessions only count while the same configuration is active.
#[derive(Default)] oidc_fp: Option<String>,
struct SessionState {
sessions: std::collections::HashMap<uuid::Uuid, BrowserSession>,
attempts: std::collections::VecDeque<std::time::Instant>,
} }
struct OperatorConfig { struct OperatorConfig {
name: String, name: String,
password_hash: 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)] #[derive(Clone)]
pub struct BrowserSession { pub struct BrowserSession {
pub id: uuid::Uuid, pub id: uuid::Uuid,
pub csrf: uuid::Uuid, pub csrf: String,
pub actor: String, pub actor: String,
expires: std::time::Instant, 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 { impl SessionGate {
pub const COOKIE: &str = "__Host-tessera-session"; pub const COOKIE: &str = "__Host-tessera-session";
pub const DURATION: std::time::Duration = std::time::Duration::from_secs(8 * 3600); pub const DURATION: std::time::Duration =
std::time::Duration::from_secs(crate::db::sessions::ABSOLUTE_SECS as u64);
pub fn from_env() -> anyhow::Result<Self> { 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") { let config = match std::env::var("TESSERA_OPERATOR_PASSWORD_HASH") {
Ok(password_hash) => { Ok(password_hash) => {
let name = let name =
@@ -182,6 +355,7 @@ impl SessionGate {
"operator password requires Argon2id" "operator password requires Argon2id"
); );
Some(std::sync::Arc::new(OperatorConfig { Some(std::sync::Arc::new(OperatorConfig {
fingerprint: fingerprint(&password_hash),
name, name,
password_hash, password_hash,
})) }))
@@ -191,60 +365,152 @@ impl SessionGate {
}; };
Ok(Self { Ok(Self {
config, config,
state: Default::default(), db,
oidc_fp,
}) })
} }
/// Any browser login method is configured (emergency password and/or OIDC).
pub fn enabled(&self) -> bool { 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() self.config.is_some()
} }
pub fn active(&self, headers: &HeaderMap) -> Option<BrowserSession> { 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 id = cookie_id(headers)?;
let mut state = self.state.lock().unwrap(); let stored = match self.db.lookup_session(&id.to_string(), now) {
state Ok(found) => found?,
.sessions Err(error) => {
.retain(|_, session| session.expires > std::time::Instant::now()); tracing::error!("session lookup failed: {error:#}");
state.sessions.get(&id).cloned() 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> { pub fn login(&self, headers: &HeaderMap, password: &str) -> Result<BrowserSession, StatusCode> {
use argon2::PasswordVerifier; use argon2::PasswordVerifier;
let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?; let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?;
{
let mut state = self.state.lock().unwrap();
state
.attempts
.retain(|attempt| attempt.elapsed() < std::time::Duration::from_secs(60));
if state.attempts.len() >= 10 {
return Err(StatusCode::TOO_MANY_REQUESTS);
}
state.attempts.push_back(std::time::Instant::now());
}
let hash = argon2::PasswordHash::new(&config.password_hash) let hash = argon2::PasswordHash::new(&config.password_hash)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
argon2::Argon2::default() argon2::Argon2::default()
.verify_password(password.as_bytes(), &hash) .verify_password(password.as_bytes(), &hash)
.map_err(|_| StatusCode::UNAUTHORIZED)?; .map_err(|_| StatusCode::UNAUTHORIZED)?;
if let Some(id) = cookie_id(headers) { let internal = |error: anyhow::Error| {
self.remove(id); tracing::error!("session create failed: {error:#}");
} StatusCode::INTERNAL_SERVER_ERROR
let session = BrowserSession {
id: uuid::Uuid::new_v4(),
csrf: uuid::Uuid::new_v4(),
actor: config.name.clone(),
expires: std::time::Instant::now() + Self::DURATION,
}; };
let mut state = self.state.lock().unwrap(); // A new ID on every login: a pre-existing cookie never survives (fixation).
state if let Some(old) = cookie_id(headers) {
.sessions self.remove(old);
.retain(|_, session| session.expires > std::time::Instant::now()); }
state.sessions.insert(session.id, session.clone()); let now = unix_now();
Ok(session) 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) { pub fn remove(&self, id: uuid::Uuid) {
self.state.lock().unwrap().sessions.remove(&id); if let Err(error) = self.db.revoke_session(&id.to_string()) {
tracing::error!("session revoke failed: {error:#}");
}
} }
} }
@@ -282,25 +548,204 @@ pub fn print_operator_hash() -> anyhow::Result<()> {
#[cfg(test)] #[cfg(test)]
impl SessionGate { impl SessionGate {
pub fn fixture() -> Self { pub fn fixture(db: crate::db::Db) -> Self {
use argon2::password_hash::{PasswordHasher, SaltString}; use argon2::password_hash::{PasswordHasher, SaltString};
let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap(); let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap();
let password_hash = argon2::Argon2::default() let password_hash = argon2::Argon2::default()
.hash_password(b"fixture-operator-password", &salt) .hash_password(b"fixture-operator-password", &salt)
.unwrap() .unwrap()
.to_string(); .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 { Self {
config: Some(std::sync::Arc::new(OperatorConfig { config: Some(std::sync::Arc::new(OperatorConfig {
name: "fixture-operator".into(), name: name.into(),
fingerprint: fingerprint(&password_hash),
password_hash, password_hash,
})), })),
state: Default::default(), db,
oidc_fp: None,
} }
} }
pub fn expire(&self) { /// Same database, no operator configured (hash unset after a restart).
for session in self.state.lock().unwrap().sessions.values_mut() { pub fn without_operator(db: crate::db::Db) -> Self {
session.expires = std::time::Instant::now(); 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

@@ -1,30 +1,48 @@
use super::routes::{require_admin, require_admin_mutation}; 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 crate::state::HubState;
use async_compression::tokio::bufread::GzipEncoder;
use axum::body::Bytes;
use axum::{ use axum::{
body::Body, body::Body,
extract::{ConnectInfo, Path, State}, extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, StatusCode}, http::{header, HeaderMap, HeaderValue, Method, StatusCode},
response::{IntoResponse, Response}, response::Response,
routing::get, routing::get,
Router, Router,
}; };
use futures_core::Stream;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::pin::Pin;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio_util::io::ReaderStream; use tokio_util::io::ReaderStream;
use uuid::Uuid; 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> { pub(super) fn routes() -> Router<HubState> {
Router::new() Router::new()
.route("/api/v1/snapshots/:id", axum::routing::delete(delete)) .route("/api/v1/snapshots/:id", axum::routing::delete(delete))
.route("/api/v1/snapshots/:id/download", get(download)) .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( async fn download(
method: Method,
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> { ) -> Result<Response, StatusCode> {
require_admin(&state, peer, &headers)?; // 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 let snapshot = state
.vault .vault
.read() .read()
@@ -33,38 +51,127 @@ async fn download(
.map_err(internal)? .map_err(internal)?
.filter(|snapshot| snapshot.manifest.provider != "legacy-history") .filter(|snapshot| snapshot.manifest.provider != "legacy-history")
.ok_or(StatusCode::NOT_FOUND)?; .ok_or(StatusCode::NOT_FOUND)?;
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?; 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"); let path = staging.path().join("download");
let size = state state
.export_snapshot(id, path.clone()) .export_snapshot(id, path.clone())
.await .await
.map_err(internal)?; .map_err(internal)?;
let file = tokio::fs::File::open(path).await.map_err(internal)?; let mut file = tokio::fs::File::open(&path).await.map_err(internal)?;
let extension = match snapshot 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 .manifest
.restore_hints .restore_hints
.get("format") .get("application_id")
.and_then(|format| format.as_str()) .and_then(|v| v.as_str())
{ .and_then(|v| Uuid::parse_str(v).ok());
Some("plain") => "sql", let zone = application.and_then(|application| {
Some("sql_gzip") => "sql.gz", state
Some("sqlite") => "sqlite", .db
Some("tar") => "tar", .capture_profiles()
_ => "dump", .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))
}; };
Ok(( let body = Guarded::new(
[ stream,
(header::CONTENT_TYPE, "application/octet-stream".to_owned()), permit,
( staging,
header::CONTENT_DISPOSITION, state.db.clone(),
format!("attachment; filename=\"{id}.{extension}\""), actor.principal.clone(),
), id,
(header::CONTENT_LENGTH, size.to_string()), actor.request_id,
(header::CACHE_CONTROL, "no-store".to_owned()), );
], let mut response = Response::new(Body::from_stream(body));
Body::from_stream(ReaderStream::new(file)), let headers = response.headers_mut();
) headers.insert(
.into_response()) 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( async fn delete(
@@ -73,14 +180,19 @@ async fn delete(
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?; let actor = admin_write(&state, peer, &headers)?;
let mut vault = state.vault.clone().write_owned().await; let mut vault = state.vault.clone().write_owned().await;
if state.db.snapshot_in_restore(id).map_err(internal)? if state.db.snapshot_in_restore(id).map_err(internal)?
|| state.db.offsite_pending(id).map_err(internal)? || state.active_exports().await.contains(&id) || state.db.offsite_pending(id).map_err(internal)?
|| state.active_exports().await.contains(&id)
{ {
return Err(StatusCode::CONFLICT); return Err(StatusCode::CONFLICT);
} }
if vault.get_snapshot(id).map_err(internal)?.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") { if vault
.get_snapshot(id)
.map_err(internal)?
.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history")
{
return Err(StatusCode::NOT_FOUND); return Err(StatusCode::NOT_FOUND);
} }
state state

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

@@ -1,4 +1,5 @@
use super::routes::{require_admin, require_admin_mutation, upload_token}; use super::routes::{admin_write, authenticate, upload_token};
use crate::auth::Permission;
use crate::state::HubState; use crate::state::HubState;
use axum::{ use axum::{
body::{Body, HttpBody}, body::{Body, HttpBody},
@@ -11,7 +12,8 @@ use base64::Engine;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::{net::SocketAddr, pin::Pin, time::Duration}; use std::{net::SocketAddr, pin::Pin, time::Duration};
use tessera_core::job::{ use tessera_core::job::{
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport, ResticCaptureCommit, CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport,
ResticCaptureCommit,
}; };
use tessera_core::{restore::DatabaseIdentity, SnapshotManifest}; use tessera_core::{restore::DatabaseIdentity, SnapshotManifest};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
@@ -23,6 +25,10 @@ pub(super) fn routes() -> Router<HubState> {
"/api/v1/capture-profiles", "/api/v1/capture-profiles",
get(profiles).post(register_profile), 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-profiles/:id/jobs", post(enqueue))
.route("/api/v1/capture-jobs", get(history)) .route("/api/v1/capture-jobs", get(history))
.route("/api/v1/capture-jobs/:id", get(job)) .route("/api/v1/capture-jobs/:id", get(job))
@@ -38,8 +44,15 @@ async fn profiles(
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> { ) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
require_admin(&state, peer, &headers)?; let actor = authenticate(&state, peer, &headers, false)?;
state.db.capture_profiles().map(Json).map_err(internal) 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( async fn register_profile(
@@ -48,7 +61,7 @@ async fn register_profile(
headers: HeaderMap, headers: HeaderMap,
Json(profile): Json<CaptureProfile>, Json(profile): Json<CaptureProfile>,
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> { ) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?; let actor = admin_write(&state, peer, &headers)?;
if profile if profile
.retention .retention
.is_some_and(|retention| !retention.is_valid()) .is_some_and(|retention| !retention.is_valid())
@@ -77,16 +90,92 @@ async fn register_profile(
Ok((StatusCode::CREATED, Json(profile))) 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( async fn enqueue(
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> { ) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?; 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 let job = state
.db .db
.enqueue_capture(id, &actor.name, now()) .enqueue_capture(id, &actor.id(), now())
.map_err(internal)? .map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?; .ok_or(StatusCode::NOT_FOUND)?;
Ok((StatusCode::ACCEPTED, Json(job))) Ok((StatusCode::ACCEPTED, Json(job)))
@@ -105,7 +194,17 @@ async fn history(
headers: HeaderMap, headers: HeaderMap,
Query(filter): Query<JobFilter>, Query(filter): Query<JobFilter>,
) -> Result<Json<Vec<CaptureJob>>, StatusCode> { ) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
require_admin(&state, peer, &headers)?; 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 if filter
.status .status
.as_deref() .as_deref()
@@ -119,24 +218,40 @@ async fn history(
filter.application_id, filter.application_id,
filter.status.as_deref(), filter.status.as_deref(),
filter.limit.unwrap_or(50).clamp(1, 200), filter.limit.unwrap_or(50).clamp(1, 200),
visible.restriction().as_deref(),
) )
.map(Json) .map(Json)
.map_err(internal) .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( async fn events(
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> { ) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
require_admin(&state, peer, &headers)?; let actor = authenticate(&state, peer, &headers, false)?;
state let job = job_in_scope(&state, &actor, id)?;
.db state.db.capture_events(job.id).map(Json).map_err(internal)
.capture_job(id)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
state.db.capture_events(id).map(Json).map_err(internal)
} }
async fn job( async fn job(
@@ -145,36 +260,41 @@ async fn job(
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Json<CaptureJob>, StatusCode> { ) -> Result<Json<CaptureJob>, StatusCode> {
require_admin(&state, peer, &headers)?; let actor = authenticate(&state, peer, &headers, false)?;
state job_in_scope(&state, &actor, id).map(Json)
.db
.capture_job(id)
.map_err(internal)?
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
} }
async fn claim( async fn claim(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(application): Path<Uuid>, Path(application): Path<Uuid>,
) -> Result<Json<Option<CaptureLease>>, StatusCode> { ) -> Result<Json<Option<CaptureLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let mut lease = state.db.claim_capture(outpost, application, now()).map_err(internal)?; let mut lease = state
.db
.claim_capture(outpost, application, now())
.map_err(internal)?;
if let Some(lease) = &mut lease { if let Some(lease) = &mut lease {
lease.restic |= lease.profile.format == CaptureFormat::Filesystem lease.restic |= lease.profile.format == CaptureFormat::Filesystem
|| state.vault.read().await.outpost_repository_configured(lease.profile.orbit_id).map_err(internal)?; || state
.vault
.read()
.await
.outpost_repository_configured(lease.profile.orbit_id)
.map_err(internal)?;
} }
Ok(Json(lease)) Ok(Json(lease))
} }
async fn report( async fn report(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Result<Json<CaptureReport>, JsonRejection>, body: Result<Json<CaptureReport>, JsonRejection>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
if !state if !state
.db .db
@@ -188,11 +308,12 @@ async fn report(
async fn upload( async fn upload(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Body, body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?) let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
.map_err(|_| StatusCode::BAD_REQUEST)?; .map_err(|_| StatusCode::BAD_REQUEST)?;
let job = state let job = state
@@ -201,8 +322,16 @@ async fn upload(
.map_err(internal)? .map_err(internal)?
.ok_or(StatusCode::CONFLICT)?; .ok_or(StatusCode::CONFLICT)?;
if job.profile.format == CaptureFormat::Filesystem if job.profile.format == CaptureFormat::Filesystem
|| state.db.restic_required(job.profile.orbit_id).map_err(internal)? || state
|| state.vault.read().await.outpost_repository_configured(job.profile.orbit_id).map_err(internal)? .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); return Err(StatusCode::CONFLICT);
} }
@@ -214,7 +343,12 @@ async fn upload(
.map_err(|_| StatusCode::BAD_REQUEST)?; .map_err(|_| StatusCode::BAD_REQUEST)?;
let identity: DatabaseIdentity = let identity: DatabaseIdentity =
serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?; serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?;
if !job.profile.format.engine().is_some_and(|engine| identity.valid(engine)) { if !job
.profile
.format
.engine()
.is_some_and(|engine| identity.valid(engine))
{
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
} }
Ok(identity) Ok(identity)
@@ -270,21 +404,29 @@ async fn upload(
async fn commit_restic( async fn commit_restic(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
Json(commit): Json<ResticCaptureCommit>, Json(commit): Json<ResticCaptureCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
let job = state.db.capture_upload(outpost, id, commit.lease_id, now()) let job = state
.map_err(internal)?.ok_or(StatusCode::CONFLICT)?; .db
.capture_upload(outpost, id, commit.lease_id, now())
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if let Some(snapshot) = job.snapshot_id { if let Some(snapshot) = job.snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot }))); return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
} }
let engine = job.profile.format.engine(); let engine = job.profile.format.engine();
if commit.identity.as_ref().is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine))) if commit
|| (engine.is_some() && !commit.sha256.as_ref().is_some_and(|hash| { .identity
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) .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()) || (engine.is_none() && commit.sha256.is_some())
{ {
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
@@ -302,7 +444,11 @@ async fn commit_restic(
} }
Ok(()) Ok(())
}) })
}).await.map_err(internal)?.map_err(internal)?.ok_or(StatusCode::CONFLICT)?; })
.await
.map_err(internal)?
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if created && state.prune_orbit(orbit_id).await.is_err() { if created && state.prune_orbit(orbit_id).await.is_err() {
tracing::warn!(%id, %orbit_id, "could not apply capture retention"); tracing::warn!(%id, %orbit_id, "could not apply capture retention");
} }
@@ -407,11 +553,51 @@ pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a
.ok_or(StatusCode::BAD_REQUEST) .ok_or(StatusCode::BAD_REQUEST)
} }
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> { 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 token = upload_token(state, headers)?;
let id = state let id = state
.db .db
.upload_token_outpost(token) .upload_token_outpost(token, chrono::Utc::now().timestamp())
.map_err(internal)? .map_err(internal)?
.ok_or(StatusCode::UNAUTHORIZED)?; .ok_or(StatusCode::UNAUTHORIZED)?;
let id = Uuid::parse_str(&id).map_err(internal)?; let id = Uuid::parse_str(&id).map_err(internal)?;

View File

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

@@ -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

@@ -1,11 +1,11 @@
use super::{ use super::{
jobs::{header_value, internal, now, outpost, receive_payload}, jobs::{header_value, internal, now, outpost, receive_payload},
routes::{require_admin, require_admin_mutation}, routes::{admin_read, admin_write},
}; };
use crate::state::HubState; use crate::state::HubState;
use axum::{ use axum::{
body::Body, body::Body,
extract::{rejection::JsonRejection, ConnectInfo, Path, State}, extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
http::{header, HeaderMap, StatusCode}, http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response}, response::{IntoResponse, Response},
routing::{get, post}, routing::{get, post},
@@ -27,9 +27,13 @@ use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> { pub(super) fn routes() -> Router<HubState> {
Router::new() Router::new()
.route("/api/v1/restore-targets", post(register)) .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/capture-profiles/:id/restore-targets", get(targets))
.route("/api/v1/snapshots/:id/restore-targets", get(snapshot_targets)) .route(
.route("/api/v1/restore-jobs", post(enqueue)) "/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/snapshots/:id/restore-jobs", get(history))
.route("/api/v1/restore-jobs/:id", get(job).delete(cancel)) .route("/api/v1/restore-jobs/:id", get(job).delete(cancel))
.route("/api/v1/restore-jobs/:id/reconcile", post(reconcile)) .route("/api/v1/restore-jobs/:id/reconcile", post(reconcile))
@@ -46,7 +50,7 @@ async fn register(
headers: HeaderMap, headers: HeaderMap,
Json(target): Json<RestoreTarget>, Json(target): Json<RestoreTarget>,
) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> { ) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?; let actor = admin_write(&state, peer, &headers)?;
if target.name.trim().is_empty() if target.name.trim().is_empty()
|| target.name.len() > 128 || target.name.len() > 128
|| target.name.chars().any(char::is_control) || target.name.chars().any(char::is_control)
@@ -56,7 +60,8 @@ async fn register(
} }
let profiles = state.db.capture_profiles().map_err(internal)?; let profiles = state.db.capture_profiles().map_err(internal)?;
if !profiles.iter().any(|profile| { if !profiles.iter().any(|profile| {
profile.application_id == target.application_id && profile.format.engine() == Some(target.engine) profile.application_id == target.application_id
&& profile.format.engine() == Some(target.engine)
}) { }) {
return Err(StatusCode::UNPROCESSABLE_ENTITY); return Err(StatusCode::UNPROCESSABLE_ENTITY);
} }
@@ -78,13 +83,50 @@ async fn register(
Ok((StatusCode::CREATED, Json(target))) 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( async fn targets(
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
Path(application): Path<Uuid>, Path(application): Path<Uuid>,
) -> Result<Json<Vec<RestoreTarget>>, StatusCode> { ) -> Result<Json<Vec<RestoreTarget>>, StatusCode> {
require_admin(&state, peer, &headers)?; admin_read(&state, peer, &headers)?;
state state
.db .db
.restore_targets(application) .restore_targets(application)
@@ -105,7 +147,7 @@ async fn snapshot_targets(
headers: HeaderMap, headers: HeaderMap,
Path(snapshot): Path<Uuid>, Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> { ) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
require_admin(&state, peer, &headers)?; admin_read(&state, peer, &headers)?;
let vault = state.vault.read().await; let vault = state.vault.read().await;
let snap = vault let snap = vault
.get_snapshot(snapshot) .get_snapshot(snapshot)
@@ -125,7 +167,10 @@ async fn snapshot_targets(
} else { } else {
Some("Outpost is no longer paired") Some("Outpost is no longer paired")
}; };
SnapshotTarget { target, ineligible_reason } SnapshotTarget {
target,
ineligible_reason,
}
}) })
.collect(); .collect();
Ok(Json(responses)) Ok(Json(responses))
@@ -137,7 +182,7 @@ async fn enqueue(
headers: HeaderMap, headers: HeaderMap,
Json(request): Json<RestoreRequest>, Json(request): Json<RestoreRequest>,
) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> { ) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?; let actor = admin_write(&state, peer, &headers)?;
if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id) if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id)
{ {
return Err(StatusCode::BAD_REQUEST); return Err(StatusCode::BAD_REQUEST);
@@ -156,7 +201,7 @@ async fn enqueue(
request.snapshot_id, request.snapshot_id,
application, application,
request.target_id, request.target_id,
&actor.name, &actor.id(),
&artifact, &artifact,
now(), now(),
) )
@@ -165,7 +210,7 @@ async fn enqueue(
Ok((StatusCode::ACCEPTED, Json(job))) Ok((StatusCode::ACCEPTED, Json(job)))
} }
pub(super) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArtifact)> { pub(crate) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArtifact)> {
let hints = &manifest.restore_hints; let hints = &manifest.restore_hints;
let application = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?; let application = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
let format = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) { let format = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
@@ -189,17 +234,49 @@ pub(super) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArti
format, format,
identity, identity,
sha256, 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( async fn job(
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Json<RestoreJob>, StatusCode> { ) -> Result<Json<RestoreJob>, StatusCode> {
require_admin(&state, peer, &headers)?; admin_read(&state, peer, &headers)?;
state state
.db .db
.restore_job(id, now()) .restore_job(id, now())
@@ -214,7 +291,7 @@ async fn history(
headers: HeaderMap, headers: HeaderMap,
Path(snapshot): Path<Uuid>, Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> { ) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
require_admin(&state, peer, &headers)?; admin_read(&state, peer, &headers)?;
state state
.db .db
.restore_history(snapshot, now()) .restore_history(snapshot, now())
@@ -222,16 +299,36 @@ async fn history(
.map_err(internal) .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( async fn cancel(
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?; let actor = admin_write(&state, peer, &headers)?;
if !state if !state
.db .db
.cancel_restore(id, &actor.name, now()) .cancel_restore(id, &actor.id(), now())
.map_err(internal)? .map_err(internal)?
{ {
return Err(StatusCode::CONFLICT); return Err(StatusCode::CONFLICT);
@@ -250,27 +347,34 @@ async fn reconcile(
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
Json(body): Json<Reconcile>, Json(body): Json<Reconcile>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, (StatusCode, Json<serde_json::Value>)> {
let actor = require_admin_mutation(&state, peer, &headers)?; 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}") { if body.confirmation != format!("RECONCILE {id}") {
return Err(StatusCode::BAD_REQUEST); return Err(plain(StatusCode::BAD_REQUEST));
} }
if !state if !state
.db .db
.reconcile_restore(id, &actor.name, now()) .reconcile_restore(id, &actor.id(), now())
.map_err(internal)? .map_err(|error| plain(internal(error)))?
{ {
return Err(StatusCode::CONFLICT); return Err((
StatusCode::CONFLICT,
Json(serde_json::json!({
"error": "only a restore job in recovery_required can be reconciled"
})),
));
} }
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }
async fn claim( async fn claim(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(target): Path<Uuid>, Path(target): Path<Uuid>,
) -> Result<Json<Option<RestoreLease>>, StatusCode> { ) -> Result<Json<Option<RestoreLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?; let outpost = outpost(&state, peer.map(|ConnectInfo(addr)| addr), &headers)?;
state state
.db .db
.claim_restore(outpost, target, now()) .claim_restore(outpost, target, now())
@@ -278,8 +382,12 @@ async fn claim(
.map_err(internal) .map_err(internal)
} }
fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCode> { fn auth(
let outpost = outpost(state, headers)?; state: &HubState,
peer: Option<ConnectInfo<SocketAddr>>,
headers: &HeaderMap,
) -> Result<(Uuid, Uuid), StatusCode> {
let outpost = outpost(state, peer.map(|ConnectInfo(addr)| addr), headers)?;
let token = let token =
header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?; header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?;
Ok(( Ok((
@@ -290,10 +398,11 @@ fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCod
async fn payload( async fn payload(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> { ) -> Result<Response, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let (job, artifact, _) = state let (job, artifact, _) = state
.db .db
.restore_access(outpost, id, token, now()) .restore_access(outpost, id, token, now())
@@ -332,29 +441,40 @@ async fn payload(
async fn report( async fn report(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Result<Json<RestoreProgress>, JsonRejection>, body: Result<Json<RestoreProgress>, JsonRejection>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?; 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 if !state
.db .db
.report_restore(outpost, id, token, progress, now()) .report_restore(outpost, id, token, progress, reason.as_deref(), now())
.map_err(internal)? .map_err(internal)?
{ {
return Err(StatusCode::CONFLICT); return Err(StatusCode::CONFLICT);
} }
if let Some(reason) = &reason {
tracing::warn!(job = %id, ?progress, %reason, "restore step failed");
}
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }
async fn safety( async fn safety(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
body: Body, body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> { ) -> Result<Json<serde_json::Value>, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
let (job, _, safety_id) = state let (job, _, safety_id) = state
.db .db
.restore_access(outpost, id, token, now()) .restore_access(outpost, id, token, now())
@@ -426,10 +546,11 @@ async fn safety(
async fn apply( async fn apply(
State(state): State<HubState>, State(state): State<HubState>,
peer: Option<ConnectInfo<SocketAddr>>,
headers: HeaderMap, headers: HeaderMap,
Path(id): Path<Uuid>, Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> { ) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?; let (outpost, token) = auth(&state, peer, &headers)?;
if !state if !state
.db .db
.authorize_apply(outpost, id, token, now()) .authorize_apply(outpost, id, token, now())

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
use crate::admin::{tokens_match, SessionGate}; use crate::admin::{tokens_match, SessionGate};
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::state::HubState; use crate::state::HubState;
use axum::{ use axum::{
extract::{ConnectInfo, State}, extract::{ConnectInfo, State},
@@ -12,9 +13,12 @@ use std::net::SocketAddr;
#[derive(Serialize)] #[derive(Serialize)]
struct Status { struct Status {
login_enabled: bool, login_enabled: bool,
oidc_enabled: bool,
authorized: bool, authorized: bool,
admin: bool,
actor: Option<String>, actor: Option<String>,
csrf: Option<String>, csrf: Option<String>,
expires_at: Option<i64>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -27,6 +31,11 @@ pub(super) fn routes() -> Router<HubState> {
Router::new() Router::new()
.route("/api/v1/operator/session", get(status).delete(logout)) .route("/api/v1/operator/session", get(status).delete(logout))
.route("/api/v1/operator/login", post(login)) .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( async fn status(
@@ -35,44 +44,254 @@ async fn status(
headers: HeaderMap, headers: HeaderMap,
) -> (HeaderMap, Json<Status>) { ) -> (HeaderMap, Json<Status>) {
let browser = state.sessions.active(&headers); let browser = state.sessions.active(&headers);
let authorized = browser.is_some() // The app opens for an administrator or for anyone holding a live grant that lets them read an orbit.
|| (!state.sessions.enabled() && state.admin.token.is_none() && peer.ip().is_loopback()); 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(), no_store(),
Json(Status { Json(Status {
login_enabled: state.sessions.enabled(), login_enabled: state.sessions.password_enabled(),
oidc_enabled: state.oidc.is_some(),
authorized, authorized,
admin: browser.as_ref().map_or(authorized, |session| session.admin),
actor: browser.as_ref().map(|session| session.actor.clone()), 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()), 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( async fn login(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>, State(state): State<HubState>,
headers: HeaderMap, headers: HeaderMap,
Json(input): Json<Login>, Json(input): Json<Login>,
) -> Result<(HeaderMap, Json<Status>), StatusCode> { ) -> 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 { if input.password.is_empty() || input.password.len() > 1024 {
return Err(StatusCode::UNAUTHORIZED); 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 gate = state.sessions.clone();
let session = tokio::task::spawn_blocking(move || gate.login(&headers, &input.password)) let attempt = tokio::task::spawn_blocking(move || {
.await let _permit = permit; // released when hashing is done, not when the handler returns
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)??; 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 state
.db .db
.audit("operator.login", &session.actor) .audit("operator.login", &session.actor)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store(); let mut headers = no_store();
headers.insert(header::SET_COOKIE, cookie(Some(&session.id.to_string()))?); headers.insert(
header::SET_COOKIE,
session_cookie(Some(&session.id.to_string()))?,
);
Ok(( Ok((
headers, headers,
Json(Status { Json(Status {
login_enabled: true, login_enabled: true,
oidc_enabled: state.oidc.is_some(),
authorized: true, authorized: true,
admin: true,
actor: Some(session.actor), actor: Some(session.actor),
expires_at: Some(session.expires_at),
csrf: Some(session.csrf.to_string()), csrf: Some(session.csrf.to_string()),
}), }),
)) ))
@@ -88,13 +307,23 @@ async fn logout(
.ok_or(StatusCode::UNAUTHORIZED)?; .ok_or(StatusCode::UNAUTHORIZED)?;
require_csrf(&headers, &session.csrf.to_string())?; require_csrf(&headers, &session.csrf.to_string())?;
state.sessions.remove(session.id); 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 state
.db .db
.audit("operator.logout", &session.actor) .audit("operator.logout", &session.actor)
.await .await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store(); let mut headers = no_store();
headers.insert(header::SET_COOKIE, cookie(None)?); headers.insert(header::SET_COOKIE, session_cookie(None)?);
Ok((StatusCode::NO_CONTENT, headers)) Ok((StatusCode::NO_CONTENT, headers))
} }
@@ -116,7 +345,7 @@ fn no_store() -> HeaderMap {
headers headers
} }
fn cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> { pub(super) fn session_cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
let value = format!( let value = format!(
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}", "{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
SessionGate::COOKIE, SessionGate::COOKIE,
@@ -140,10 +369,11 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn operator_session_requires_csrf_and_expires_without_disabling_cli() { async fn operator_session_requires_csrf_and_expires_without_disabling_cli() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault") let mut state =
.await HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault-passphrase")
.unwrap(); .await
state.sessions = SessionGate::fixture(); .unwrap();
state.sessions = SessionGate::fixture(state.db.clone());
state.admin.token = Some("fixture-api-token".into()); state.admin.token = Some("fixture-api-token".into());
let app = crate::api::router(state.clone()); let app = crate::api::router(state.clone());
let request = |method: &str, uri: &str, body: &'static str| { let request = |method: &str, uri: &str, body: &'static str| {
@@ -250,5 +480,94 @@ mod tests {
[], |row| row.get(0), [], |row| row.get(0),
).unwrap(); ).unwrap();
assert_eq!(audited, 3); 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,5 +1,13 @@
pub(crate) mod access;
mod audit;
pub(crate) mod credentials;
mod jobs; mod jobs;
pub use jobs::ProfileChange;
pub(crate) mod oidc_login;
pub(crate) mod refresh;
pub(crate) mod relations;
mod restore; mod restore;
pub mod sessions;
pub(crate) use restore::restore_target_mismatch; pub(crate) use restore::restore_target_mismatch;
use anyhow::Result; use anyhow::Result;
@@ -72,14 +80,6 @@ impl Db {
total INTEGER, total INTEGER,
created_at TEXT NOT NULL created_at TEXT NOT NULL
); );
CREATE TABLE IF NOT EXISTS 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
);
CREATE TABLE IF NOT EXISTS upload_ranges ( CREATE TABLE IF NOT EXISTS upload_ranges (
session_id TEXT NOT NULL, session_id TEXT NOT NULL,
start_off INTEGER NOT NULL, start_off INTEGER NOT NULL,
@@ -94,13 +94,21 @@ impl Db {
"INTEGER NOT NULL DEFAULT 0", "INTEGER NOT NULL DEFAULT 0",
)?; )?;
ensure_column(&conn, "orbits", "retention", "TEXT")?; ensure_column(&conn, "orbits", "retention", "TEXT")?;
conn.execute( ensure_column(
"INSERT OR IGNORE INTO outposts(id, name, pairing_state) &conn,
SELECT outpost_id, outpost_name, 'active' FROM wormhole_tokens WHERE state = 'active'", "orbits",
[], "outpost_id",
"TEXT REFERENCES outposts(id)",
)?; )?;
credentials::migrate(&conn)?;
jobs::migrate(&conn)?; jobs::migrate(&conn)?;
restore::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(()) Ok(())
} }
@@ -139,6 +147,45 @@ impl Db {
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) 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<()> { pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( conn.execute(
@@ -217,67 +264,60 @@ impl Db {
&self, &self,
id: &str, id: &str,
orbit_id: &str, orbit_id: &str,
outpost_id: Uuid,
total: Option<i64>, total: Option<i64>,
) -> Result<()> { ) -> Result<()> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( let inserted = conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, offset, total, sealed, created_at) VALUES (?1, ?2, 0, ?3, 0, datetime('now'))", "INSERT INTO upload_sessions (id, orbit_id, outpost_id, offset, total, sealed, created_at)
params![id, orbit_id, total], 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(()) Ok(())
} }
pub fn insert_wormhole_token( pub fn bind_legacy_outpost(&self, orbit: Uuid, outpost: Uuid) -> Result<bool> {
&self,
token: &str,
outpost_id: &str,
code: &str,
expires_at: &str,
) -> Result<()> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
conn.execute( Ok(conn.execute(
"INSERT INTO wormhole_tokens (token, outpost_id, code, state, expires_at) VALUES (?1, ?2, ?3, 'code_shown', ?4)", "UPDATE orbits SET outpost_id=?2 WHERE id=?1 AND provider='wormhole' AND dry_run=0
params![token, outpost_id, code, expires_at], 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')",
Ok(()) params![orbit.to_string(), outpost.to_string()],
)? == 1)
} }
pub fn claim_wormhole_code( pub fn legacy_upload_owned_by(&self, orbit: Uuid, outpost: Uuid) -> Result<bool> {
&self, Ok(self.conn.lock().unwrap().query_row(
code: &str, "SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1 AND outpost_id=?2
outpost_name: &str, AND provider='wormhole' AND dry_run=0)",
now: &str, params![orbit.to_string(), outpost.to_string()],
) -> Result<Option<(String, String)>> { |row| row.get(0),
let mut conn = self.conn.lock().unwrap(); )?)
let tx = conn.transaction()?;
let claimed: Option<(String, String)> = tx.query_row(
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2
WHERE token = (SELECT token FROM wormhole_tokens
WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3
ORDER BY expires_at DESC LIMIT 1)
RETURNING token, outpost_id",
params![code, outpost_name, now],
|row| Ok((row.get(0)?, row.get(1)?)),
).optional()?;
if let Some((_, outpost)) = &claimed {
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, now],
)?;
}
tx.commit()?;
Ok(claimed)
} }
pub fn list_outposts(&self) -> Result<Vec<OutpostSummary>> { pub fn list_outposts(&self) -> Result<Vec<OutpostSummary>> {
let conn = self.conn.lock().unwrap(); 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 mut stmt = conn
.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?;
let rows = stmt.query_map([], |row| { let rows = stmt.query_map([], |row| {
let id = Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| { let id = Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| {
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(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(OutpostSummary {
id,
name: row.get(1)?,
last_seen: row.get(2)?,
pairing_state: row.get(3)?,
})
})?; })?;
Ok(rows.collect::<rusqlite::Result<_>>()?) Ok(rows.collect::<rusqlite::Result<_>>()?)
} }
@@ -292,18 +332,10 @@ impl Db {
Ok(()) Ok(())
} }
pub fn upload_token_outpost(&self, token: &str) -> Result<Option<String>> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
"SELECT outpost_id FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1",
params![token], |row| row.get(0),
).optional()?)
}
pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> { pub fn upload_session(&self, id: &str) -> Result<Option<UploadSession>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare( let mut stmt = conn.prepare(
"SELECT orbit_id, total, sealed FROM upload_sessions WHERE id = ?1", "SELECT orbit_id, total, sealed, outpost_id FROM upload_sessions WHERE id = ?1",
)?; )?;
let mut rows = stmt.query(params![id])?; let mut rows = stmt.query(params![id])?;
let Some(row) = rows.next()? else { let Some(row) = rows.next()? else {
@@ -316,6 +348,7 @@ impl Db {
orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?, orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?,
total: total.unwrap_or(0).max(0) as u64, total: total.unwrap_or(0).max(0) as u64,
sealed: sealed != 0, sealed: sealed != 0,
outpost_id: row.get(3)?,
})) }))
} }
@@ -385,6 +418,7 @@ impl Db {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct UploadSession { pub struct UploadSession {
pub orbit_id: Uuid, pub orbit_id: Uuid,
pub outpost_id: Option<String>,
pub total: u64, pub total: u64,
pub sealed: bool, pub sealed: bool,
} }
@@ -397,7 +431,10 @@ fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Re
return Ok(()); return Ok(());
} }
} }
conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?; conn.execute(
&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"),
[],
)?;
Ok(()) Ok(())
} }

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

@@ -103,6 +103,13 @@ fn read_job(row: &Row<'_>) -> rusqlite::Result<CaptureJob> {
}) })
} }
/// 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 { impl Db {
pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> { pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
@@ -113,7 +120,7 @@ impl Db {
SELECT 1 FROM orbits WHERE id = ?2 AND provider = 'wormhole' AND dry_run = 0 SELECT 1 FROM orbits WHERE id = ?2 AND provider = 'wormhole' AND dry_run = 0
AND COALESCE(json_extract(provider_config, '$.source'), ?6) = ?6 AND COALESCE(json_extract(provider_config, '$.source'), ?6) = ?6
) )
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active') AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?5)
ON CONFLICT DO NOTHING", ON CONFLICT DO NOTHING",
params![profile.application_id.to_string(), profile.orbit_id.to_string(), params![profile.application_id.to_string(), profile.orbit_id.to_string(),
profile.outpost_id.to_string(), serde_json::to_string(profile)?, now, profile.outpost_id.to_string(), serde_json::to_string(profile)?, now,
@@ -122,6 +129,51 @@ impl Db {
Ok(changed == 1) 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>> { pub fn capture_profiles(&self) -> Result<Vec<CaptureProfile>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let mut stmt = let mut stmt =
@@ -133,7 +185,7 @@ impl Db {
pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> { pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare( let mut stmt = conn.prepare(
"SELECT p.profile, COALESCE(MAX(j.schedule_slot), p.registered_at) "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) FROM capture_profiles p LEFT JOIN capture_jobs j USING(application_id)
GROUP BY p.application_id", GROUP BY p.application_id",
)?; )?;
@@ -146,7 +198,7 @@ impl Db {
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at, schedule_slot) "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 SELECT ?1, application_id, 'scheduler', ?4, ?4, ?3 FROM capture_profiles p
WHERE application_id = ?2 WHERE application_id = ?2
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active') 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", ON CONFLICT(application_id, schedule_slot) DO NOTHING",
params![Uuid::new_v4().to_string(), application.to_string(), slot, now], params![Uuid::new_v4().to_string(), application.to_string(), slot, now],
)?; )?;
@@ -160,15 +212,10 @@ impl Db {
now: i64, now: i64,
) -> Result<Option<CaptureJob>> { ) -> Result<Option<CaptureJob>> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
let id = Uuid::new_v4(); match insert_capture_job(&conn, application_id, actor, now)? {
conn.execute( Some(id) => capture_job(&conn, id),
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at) None => Ok(None),
SELECT ?1, application_id, ?3, ?4, ?4 FROM capture_profiles p }
WHERE application_id = ?2
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')",
params![id.to_string(), application_id.to_string(), actor, now],
)?;
capture_job(&conn, id)
} }
pub fn capture_jobs( pub fn capture_jobs(
@@ -176,14 +223,25 @@ impl Db {
application: Option<Uuid>, application: Option<Uuid>,
status: Option<&str>, status: Option<&str>,
limit: u16, limit: u16,
orbits: Option<&[String]>,
) -> Result<Vec<CaptureJob>> { ) -> Result<Vec<CaptureJob>> {
let conn = self.conn.lock().unwrap(); 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!( 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) "{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" 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( let rows = stmt.query_map(
params![application.map(|id| id.to_string()), status, limit], params![
application.map(|id| id.to_string()),
status,
limit,
restriction
],
read_job, read_job,
)?; )?;
Ok(rows.collect::<rusqlite::Result<_>>()?) Ok(rows.collect::<rusqlite::Result<_>>()?)
@@ -415,6 +473,26 @@ impl Db {
} }
} }
/// 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( fn capture_upload(
conn: &Connection, conn: &Connection,
outpost: Uuid, outpost: Uuid,
@@ -490,11 +568,7 @@ mod tests {
assert!(!db.register_capture_profile(&a, 100).unwrap()); assert!(!db.register_capture_profile(&a, 100).unwrap());
assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none()); assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none());
for (id, token) in [(outpost, "token-a"), (other, "token-b")] { for (id, token) in [(outpost, "token-a"), (other, "token-b")] {
db.insert_wormhole_token(token, &id.to_string(), token, "9999") db.insert_test_credential(token, &id.to_string(), "agent");
.unwrap();
db.claim_wormhole_code(token, "agent", "2026")
.unwrap()
.unwrap();
} }
assert!(db.register_capture_profile(&a, 100).unwrap()); assert!(db.register_capture_profile(&a, 100).unwrap());
assert!(db.register_capture_profile(&b, 100).unwrap()); assert!(db.register_capture_profile(&b, 100).unwrap());
@@ -585,8 +659,7 @@ mod tests {
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap(); let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
db.migrate().await.unwrap(); db.migrate().await.unwrap();
let outpost = Uuid::new_v4(); let outpost = Uuid::new_v4();
db.insert_wormhole_token("token", &outpost.to_string(), "code", "9999").unwrap(); db.insert_test_credential("token", &outpost.to_string(), "agent");
db.claim_wormhole_code("code", "agent", "2026").unwrap().unwrap();
let profile = profile(&db, outpost).await; let profile = profile(&db, outpost).await;
let app = profile.application_id; let app = profile.application_id;
let now = chrono::Utc::now().timestamp(); let now = chrono::Utc::now().timestamp();
@@ -600,12 +673,23 @@ mod tests {
let lease = db.claim_capture(outpost, app, now).unwrap().unwrap(); let lease = db.claim_capture(outpost, app, now).unwrap().unwrap();
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running"); assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running");
for progress in [CaptureProgress::Dumping, progress] { for progress in [CaptureProgress::Dumping, progress] {
assert!(db.report_capture(outpost, job.id, CaptureReport { assert!(db
lease_id: lease.lease_id, progress, .report_capture(
}, now).unwrap()); outpost,
job.id,
CaptureReport {
lease_id: lease.lease_id,
progress,
},
now
)
.unwrap());
} }
if expected == "completed" { if expected == "completed" {
assert!(db.publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(())).unwrap().is_some()); 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); assert_eq!(db.list_orbits().await.unwrap()[0].last_status, expected);
} }
@@ -621,11 +705,7 @@ mod tests {
let db = Db::connect(&path).await.unwrap(); let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap(); db.migrate().await.unwrap();
let outpost = Uuid::new_v4(); let outpost = Uuid::new_v4();
db.insert_wormhole_token("test", &outpost.to_string(), "code", "9999") db.insert_test_credential("test", &outpost.to_string(), "agent");
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
let mut a = profile(&db, outpost).await; let mut a = profile(&db, outpost).await;
let mut b = profile(&db, outpost).await; let mut b = profile(&db, outpost).await;
a.schedule = Some(CaptureSchedule { a.schedule = Some(CaptureSchedule {
@@ -642,17 +722,17 @@ mod tests {
} }
let tick = crate::scheduler::tick_capture_schedules; let tick = crate::scheduler::tick_capture_schedules;
tick(&db, registered).unwrap(); tick(&db, registered).unwrap();
assert!(db.capture_jobs(None, None, 100).unwrap().is_empty()); 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(); let now = Utc.with_ymd_and_hms(2026, 11, 8, 19, 5, 0).unwrap();
tick(&db, now).unwrap(); tick(&db, now).unwrap();
drop(db); drop(db);
let db = Db::connect(&path).await.unwrap(); let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap(); db.migrate().await.unwrap();
tick(&db, now).unwrap(); tick(&db, now).unwrap();
let all = db.capture_jobs(None, Some("queued"), 100).unwrap(); let all = db.capture_jobs(None, Some("queued"), 100, None).unwrap();
assert_eq!(all.len(), 4); assert_eq!(all.len(), 4);
let history = db let history = db
.capture_jobs(Some(a.application_id), Some("queued"), 100) .capture_jobs(Some(a.application_id), Some("queued"), 100, None)
.unwrap(); .unwrap();
assert_eq!(history.len(), 2); assert_eq!(history.len(), 2);
assert!(history.iter().all(|job| job.actor == "scheduler")); assert!(history.iter().all(|job| job.actor == "scheduler"));
@@ -678,7 +758,7 @@ mod tests {
.unwrap()); .unwrap());
} }
let failed = db let failed = db
.capture_jobs(Some(a.application_id), Some("failed"), 100) .capture_jobs(Some(a.application_id), Some("failed"), 100, None)
.unwrap(); .unwrap();
assert_eq!(failed.len(), 1); assert_eq!(failed.len(), 1);
let events = db.capture_events(first.job_id).unwrap(); let events = db.capture_events(first.job_id).unwrap();
@@ -690,4 +770,120 @@ mod tests {
["queued", "claimed", "dumping", "dump_failed"] ["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

@@ -27,17 +27,20 @@ pub(super) fn migrate(conn: &Connection) -> Result<()> {
lease_token TEXT, lease_token TEXT,
lease_until INTEGER, lease_until INTEGER,
attempt_safety_id TEXT, attempt_safety_id TEXT,
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_target ON restore_jobs(target_id, status);
CREATE INDEX IF NOT EXISTS restore_jobs_snapshot ON restore_jobs(snapshot_id, safety_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(()) Ok(())
} }
const VIEW: &str = const VIEW: &str =
"SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at, "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.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"; FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> { fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
@@ -63,6 +66,7 @@ fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
.map_err(|err| invalid_column(6, err))?, .map_err(|err| invalid_column(6, err))?,
created_at: row.get(7)?, created_at: row.get(7)?,
updated_at: row.get(8)?, updated_at: row.get(8)?,
failure_reason: row.get(11)?,
}) })
} }
@@ -72,7 +76,7 @@ pub(crate) fn restore_target_mismatch(
) -> Option<&'static str> { ) -> Option<&'static str> {
if Some(target.engine) != artifact.format.engine() { if Some(target.engine) != artifact.format.engine() {
Some("Database engine differs from the snapshot") Some("Database engine differs from the snapshot")
} else if target.identity == artifact.identity { } else if target.identity == artifact.identity && !artifact.rollback {
Some("Target is the source database") Some("Target is the source database")
} else { } else {
None None
@@ -86,7 +90,7 @@ impl Db {
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile) "INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
SELECT ?1, ?2, ?3, ?4, ?5 SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2) WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active') AND EXISTS (SELECT 1 FROM outpost_credentials WHERE outpost_id = ?3 AND state = 'active' AND expires_at > ?6)
ON CONFLICT DO NOTHING", ON CONFLICT DO NOTHING",
params![ params![
target.id.to_string(), target.id.to_string(),
@@ -94,24 +98,45 @@ impl Db {
target.outpost_id.to_string(), target.outpost_id.to_string(),
serde_json::to_string(&(target.engine, &target.identity))?, serde_json::to_string(&(target.engine, &target.identity))?,
serde_json::to_string(target)?, serde_json::to_string(target)?,
chrono::Utc::now().timestamp(),
], ],
)?; )?;
Ok(changed == 1) Ok(changed == 1)
} }
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> { /// Change the display name of a restore target. Its id, identity and Outpost are not touched, so
Ok(self.restore_targets_with_activity(application)? /// relations and jobs that refer to it stay valid. Returns false for an unknown target.
.into_iter().map(|(target, _)| target).collect()) 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_with_activity(&self, application: Uuid) -> Result<Vec<(RestoreTarget, bool)>> { 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 conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare( let mut stmt = conn.prepare(
"SELECT t.profile, EXISTS (SELECT 1 FROM wormhole_tokens "SELECT t.profile, EXISTS (SELECT 1 FROM outpost_credentials
WHERE outpost_id = t.outpost_id AND state = 'active') 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", FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id",
)?; )?;
let rows = stmt.query_map([application.to_string()], |row| Ok((json(row, 0)?, row.get(1)?)))?; 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<_>>()?) Ok(rows.collect::<rusqlite::Result<_>>()?)
} }
@@ -126,37 +151,9 @@ impl Db {
) -> Result<Option<RestoreJob>> { ) -> Result<Option<RestoreJob>> {
let mut conn = self.conn.lock().unwrap(); let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let registered: Option<RestoreTarget> = tx.query_row( let job = enqueue_restore_in(&tx, snapshot, application, target, actor, artifact, now)?;
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = t.outpost_id AND state = 'active')",
params![target.to_string(), application.to_string()],
|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,
)?;
tx.commit()?; tx.commit()?;
Ok(Some(job)) Ok(job)
} }
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> { pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
@@ -181,11 +178,23 @@ impl Db {
Ok(rows.collect::<rusqlite::Result<_>>()?) 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> { pub fn snapshot_in_restore(&self, id: Uuid) -> Result<bool> {
let conn = self.conn.lock().unwrap(); let conn = self.conn.lock().unwrap();
Ok(conn.query_row( Ok(conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1) "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'))", 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), [id.to_string()], |row| row.get(0),
)?) )?)
} }
@@ -292,6 +301,22 @@ impl Db {
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() { if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
return Ok(false); 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", 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])?; params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
audit( audit(
@@ -309,6 +334,7 @@ impl Db {
id: Uuid, id: Uuid,
token: Uuid, token: Uuid,
progress: RestoreProgress, progress: RestoreProgress,
reason: Option<&str>,
now: i64, now: i64,
) -> Result<bool> { ) -> Result<bool> {
let mut conn = self.conn.lock().unwrap(); let mut conn = self.conn.lock().unwrap();
@@ -338,6 +364,24 @@ impl Db {
if !matches!(progress, RestoreProgress::Heartbeat) { if !matches!(progress, RestoreProgress::Heartbeat) {
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?; 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()?; tx.commit()?;
Ok(true) Ok(true)
} }
@@ -378,6 +422,48 @@ impl Db {
} }
} }
/// 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( fn restore_access(
conn: &Connection, conn: &Connection,
outpost: Uuid, outpost: Uuid,
@@ -429,11 +515,7 @@ mod tests {
let db = Db::connect(&path).await.unwrap(); let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap(); db.migrate().await.unwrap();
let outpost = Uuid::new_v4(); let outpost = Uuid::new_v4();
db.insert_wormhole_token("synthetic-token", &outpost.to_string(), "code", "9999") db.insert_test_credential("synthetic-token", &outpost.to_string(), "agent");
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
let orbit = Uuid::new_v4(); let orbit = Uuid::new_v4();
db.upsert_orbit(&OrbitRow { db.upsert_orbit(&OrbitRow {
id: orbit, id: orbit,
@@ -480,16 +562,30 @@ mod tests {
let artifact = RestoreArtifact { let artifact = RestoreArtifact {
format: CaptureFormat::PostgresCustom, format: CaptureFormat::PostgresCustom,
sha256: "0".repeat(64), sha256: "0".repeat(64),
rollback: false,
identity: DatabaseIdentity { identity: DatabaseIdentity {
instance: "123".into(), instance: "123".into(),
database: "source".into(), database: "source".into(),
}, },
}; };
let registered = db.restore_targets_with_activity(app).unwrap().pop().unwrap(); let registered = db
.restore_targets_with_activity(app)
.unwrap()
.pop()
.unwrap();
assert!(registered.1); assert!(registered.1);
let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() }; let same_source = RestoreArtifact {
assert_eq!(restore_target_mismatch(&registered.0, &same_source), Some("Target is the source database")); identity: registered.0.identity.clone(),
assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none()); ..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 let job = db
.enqueue_restore(snapshot, app, target, "fixture", &artifact, 100) .enqueue_restore(snapshot, app, target, "fixture", &artifact, 100)
.unwrap() .unwrap()
@@ -507,10 +603,24 @@ mod tests {
.authorize_apply(outpost, job.id, lease.token, 104) .authorize_apply(outpost, job.id, lease.token, 104)
.unwrap()); .unwrap());
assert!(db assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104) .report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Checking,
None,
104
)
.unwrap()); .unwrap());
assert!(db assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105) .report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Safety,
None,
105
)
.unwrap()); .unwrap());
assert!(db assert!(db
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!( .record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
@@ -544,6 +654,12 @@ mod tests {
.unwrap()); .unwrap());
let interrupted = db.restore_job(job.id, late).unwrap().unwrap(); let interrupted = db.restore_job(job.id, late).unwrap().unwrap();
assert_eq!(interrupted.status, "recovery_required"); 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_eq!(interrupted.safety_snapshot_id, Some(safety));
assert!(db.snapshot_in_restore(snapshot).unwrap()); assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(db.snapshot_in_restore(safety).unwrap()); assert!(db.snapshot_in_restore(safety).unwrap());

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,12 @@
mod admin; mod admin;
mod api; mod api;
mod auth;
mod db; mod db;
mod exports;
mod limits;
mod mtls; mod mtls;
mod oidc;
mod refresh;
mod scheduler; mod scheduler;
mod state; mod state;
mod upload; mod upload;
@@ -22,6 +27,14 @@ async fn main() -> Result<()> {
let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into()); let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into());
let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "127.0.0.1:8787".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") let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE")
.ok() .ok()
.filter(|value| !value.is_empty()) .filter(|value| !value.is_empty())
@@ -37,6 +50,13 @@ async fn main() -> Result<()> {
} }
let mut 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") if std::env::var("TESSERA_SEED_DEMO")
.map(|v| v == "1" || v == "true") .map(|v| v == "1" || v == "true")
@@ -62,14 +82,16 @@ async fn main() -> Result<()> {
state.configure_offsite()?; state.configure_offsite()?;
state.reconcile_capture_catalog().await?; state.reconcile_capture_catalog().await?;
state.start_offsite_worker(); state.start_offsite_worker();
scheduler::start_audit_retention(state.db.clone(), audit_retention);
scheduler::start_orbit_scheduler(state.clone()).await?; scheduler::start_orbit_scheduler(state.clone()).await?;
refresh::start(state.clone());
if state.sessions.enabled() { if state.sessions.enabled() {
tracing::info!("operator sessions enabled; CLI access uses a separate admin token"); tracing::info!("operator sessions enabled; CLI access uses a separate admin token");
} else { } else {
state.admin.log_policy(); state.admin.log_policy();
} }
if let Some(wormhole) = mtls::from_env()? { if let Some(wormhole) = wormhole {
state.wormhole_mtls = true; state.wormhole_mtls = true;
state.accept_plain_upload = false; state.accept_plain_upload = false;
let mut tls_state = state.clone(); let mut tls_state = state.clone();
@@ -84,14 +106,7 @@ async fn main() -> Result<()> {
tracing::info!("plain HTTP uploads are closed; wormhole clients use {listen_addr}"); tracing::info!("plain HTTP uploads are closed; wormhole clients use {listen_addr}");
} }
let admin_token_unset = state.admin.token.is_none();
let app = api::router(state); let app = api::router(state);
let addr: SocketAddr = listen.parse()?;
if addr.ip().is_unspecified() && admin_token_unset {
tracing::warn!(
"listening on {addr}; backup APIs reject non-loopback clients until TESSERA_ADMIN_TOKEN is set"
);
}
tracing::info!("Tessera hub listening on {addr}"); tracing::info!("Tessera hub listening on {addr}");
let listener = tokio::net::TcpListener::bind(addr).await?; let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve( axum::serve(

View File

@@ -6,14 +6,12 @@ use axum::Router;
use hyper::body::Incoming; use hyper::body::Incoming;
use hyper_util::rt::TokioIo; use hyper_util::rt::TokioIo;
use hyper_util::service::TowerToHyperService; use hyper_util::service::TowerToHyperService;
use rustls::pki_types::{CertificateDer, PrivateKeyDer}; use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier; use rustls::server::WebPkiClientVerifier;
use rustls::RootCertStore; use rustls::RootCertStore;
use rustls::ServerConfig; use rustls::ServerConfig;
use std::convert::Infallible; use std::convert::Infallible;
use std::fs::File;
use std::future::Future; use std::future::Future;
use std::io::BufReader;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::Path; use std::path::Path;
use std::pin::Pin; use std::pin::Pin;
@@ -36,15 +34,12 @@ pub fn from_env() -> Result<Option<WormholeMtls>> {
if !enabled { if !enabled {
return Ok(None); return Ok(None);
} }
let cert = std::env::var("TESSERA_WORMHOLE_CERT").context( let cert = std::env::var("TESSERA_WORMHOLE_CERT")
"TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled", .context("TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled")?;
)?; let key = std::env::var("TESSERA_WORMHOLE_KEY")
let key = std::env::var("TESSERA_WORMHOLE_KEY").context( .context("TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled")?;
"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 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") let listen = std::env::var("TESSERA_WORMHOLE_LISTEN")
.unwrap_or_else(|_| "127.0.0.1:8788".into()) .unwrap_or_else(|_| "127.0.0.1:8788".into())
.parse() .parse()
@@ -80,7 +75,16 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
mtls.listen mtls.listen
); );
loop { loop {
let (tcp, _) = listener.accept().await.context("accept wormhole mTLS")?; 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 acceptor = acceptor.clone();
let app = app.clone(); let app = app.clone();
tokio::spawn(async move { tokio::spawn(async move {
@@ -88,7 +92,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
return; return;
}; };
let io = TokioIo::new(tls); let io = TokioIo::new(tls);
let service = TowerToHyperService::new(HyperApp(app)); let service = TowerToHyperService::new(HyperApp(app, peer));
let _ = hyper::server::conn::http1::Builder::new() let _ = hyper::server::conn::http1::Builder::new()
.serve_connection(io, service) .serve_connection(io, service)
.await; .await;
@@ -97,7 +101,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
} }
#[derive(Clone)] #[derive(Clone)]
struct HyperApp(Router); struct HyperApp(Router, SocketAddr);
impl Service<Request<Incoming>> for HyperApp { impl Service<Request<Incoming>> for HyperApp {
type Response = Response; type Response = Response;
@@ -110,9 +114,15 @@ impl Service<Request<Incoming>> for HyperApp {
fn call(&mut self, request: Request<Incoming>) -> Self::Future { fn call(&mut self, request: Request<Incoming>) -> Self::Future {
let app = self.0.clone(); 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 { Box::pin(async move {
Ok(app Ok(app
.oneshot(request.map(Body::new)) .oneshot(request)
.await .await
.unwrap_or_else(|error| match error {})) .unwrap_or_else(|error| match error {}))
}) })
@@ -120,26 +130,134 @@ impl Service<Request<Incoming>> for HyperApp {
} }
pub fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> { pub fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?); CertificateDer::pem_file_iter(path)
rustls_pemfile::certs(&mut reader) .with_context(|| format!("open {}", path.display()))?
.collect::<Result<Vec<_>, _>>() .collect::<Result<Vec<_>, _>>()
.context("parse certificate") .context("parse certificate")
} }
pub fn load_key(path: &Path) -> Result<PrivateKeyDer<'static>> { pub fn load_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?); PrivateKeyDer::from_pem_file(path).context("parse private key (none found in file?)")
rustls_pemfile::private_key(&mut reader)
.context("parse private key")?
.context("certificate file has no private key")
} }
pub fn load_ca(path: &Path) -> Result<RootCertStore> { pub fn load_ca(path: &Path) -> Result<RootCertStore> {
let mut roots = RootCertStore::empty(); let mut roots = RootCertStore::empty();
for cert in load_certs(path)? { for cert in load_certs(path)? {
roots.add(cert).map_err(|error| anyhow::anyhow!("client CA: {error}"))?; roots
.add(cert)
.map_err(|error| anyhow::anyhow!("client CA: {error}"))?;
} }
if roots.is_empty() { if roots.is_empty() {
anyhow::bail!("client CA file contained no certificates"); anyhow::bail!("client CA file contained no certificates");
} }
Ok(roots) 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

@@ -32,6 +32,51 @@ pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
Ok(()) Ok(())
} }
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> { pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> {
if expression.split_whitespace().count() == 5 { if expression.split_whitespace().count() == 5 {
Schedule::from_str(&format!("0 {expression}")) Schedule::from_str(&format!("0 {expression}"))
@@ -116,6 +161,16 @@ pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime<Utc>) ->
mod tests { mod tests {
use super::*; 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] #[test]
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() { fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap(); let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();

View File

@@ -5,7 +5,8 @@ use std::collections::{HashMap, HashSet};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use tessera_core::decay::{ use tessera_core::decay::{
evaluate_capture_retention, evaluate_gfs, CaptureRetention, RetentionPolicy, SnapshotRef, evaluate_capture_retention, evaluate_gfs, evaluate_safety_retention, CaptureRetention,
RetentionPolicy, SafetyRef, SnapshotRef,
}; };
use tessera_core::job::CaptureProfile; use tessera_core::job::CaptureProfile;
@@ -40,6 +41,10 @@ pub struct HubState {
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>, pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
pub admin: AdminGate, pub admin: AdminGate,
pub sessions: SessionGate, 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, pub wormhole_mtls: bool,
/// Token uploads are accepted on this listener. Plain HTTP turns this off /// Token uploads are accepted on this listener. Plain HTTP turns this off
/// when wormhole mTLS is required, so those routes are not a bypass. /// when wormhole mTLS is required, so those routes are not a bypass.
@@ -61,15 +66,26 @@ impl HubState {
Vault::init(&vault_path, vault_pass)? Vault::init(&vault_path, vault_pass)?
}; };
let admin = AdminGate::from_env()?;
let oidc_config = crate::oidc::OidcConfig::from_env(admin.local_development)?;
Ok(Self { Ok(Self {
db, db: db.clone(),
data_dir, data_dir,
offsite: None, offsite: None,
vault: Arc::new(RwLock::new(vault)), vault: Arc::new(RwLock::new(vault)),
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())), reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
active_orbits: Arc::new(Mutex::new(HashSet::new())), active_orbits: Arc::new(Mutex::new(HashSet::new())),
admin: AdminGate::from_env(), admin,
sessions: SessionGate::from_env()?, 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, wormhole_mtls: false,
accept_plain_upload: true, accept_plain_upload: true,
}) })
@@ -130,12 +146,13 @@ impl HubState {
for id in jobs { for id in jobs {
let offsite = offsite.clone(); let offsite = offsite.clone();
let prepared = state.vault.read().await.prepare_offsite_copy(id); let prepared = state.vault.read().await.prepare_offsite_copy(id);
let success = match prepared { let result = match prepared {
Ok(copy) => offsite.copy_capture(copy).await.is_ok(), Ok(copy) => offsite.copy_capture(copy).await,
Err(_) => false, Err(error) => Err(error),
}; };
if !success { let success = result.is_ok();
tracing::warn!(%id, "off-site capture copy failed"); 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() { if state.db.set_offsite_result(id, success).is_err() {
tracing::warn!(%id, "could not save off-site copy status"); tracing::warn!(%id, "could not save off-site copy status");
@@ -194,15 +211,28 @@ impl HubState {
let Some(profile) = profile else { let Some(profile) = profile else {
return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref()); return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref());
}; };
let snapshots = vault let (safety, captures): (Vec<_>, Vec<_>) = vault
.list_snapshots()? .list_snapshots()?
.into_iter() .into_iter()
.filter(|snapshot| snapshot.manifest.orbit_id == orbit_id) .filter(|snapshot| snapshot.manifest.orbit_id == orbit_id)
.partition(|snapshot| snapshot.manifest.is_restore_safety());
let snapshots = captures
.into_iter()
.map(|snapshot| SnapshotRef { .map(|snapshot| SnapshotRef {
id: snapshot.id, id: snapshot.id,
taken_at: snapshot.taken_at, taken_at: snapshot.taken_at,
}) })
.collect(); .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) { let expired = match ManagedRetention::resolve(&profile, retention) {
ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots), ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots),
ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => { ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => {
@@ -210,8 +240,14 @@ impl HubState {
} }
}; };
let mut deletable = Vec::new(); let mut deletable = Vec::new();
let expired = expired
.into_iter()
.chain(evaluate_safety_retention(safety, chrono::Utc::now()));
for id in expired { for id in expired {
if !active_exports.contains(&id) && !db.offsite_pending(id)? && !db.snapshot_in_restore(id)? { if !active_exports.contains(&id)
&& !db.offsite_pending(id)?
&& !db.snapshot_in_restore(id)?
{
deletable.push(id); deletable.push(id);
} }
} }

View File

@@ -26,9 +26,9 @@ pub fn contiguous_from_zero(ranges: &[ByteRange]) -> u64 {
} }
pub fn write_at(file: &mut File, offset: u64, data: &[u8], total: u64) -> io::Result<ByteRange> { 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(|| { let end = offset
io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows") .checked_add(data.len() as u64)
})?; .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows"))?;
if end > total { if end > total {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
@@ -47,10 +47,7 @@ mod tests {
#[test] #[test]
fn out_of_order_chunks_cover_the_object() { fn out_of_order_chunks_cover_the_object() {
assert_eq!( assert_eq!(contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]), 0);
contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]),
0
);
assert_eq!( assert_eq!(
contiguous_from_zero(&[ contiguous_from_zero(&[
ByteRange { start: 4, end: 8 }, ByteRange { start: 4, end: 8 },

View File

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

View File

@@ -30,12 +30,15 @@ pub struct CaptureResult {
pub restore_hints: Value, 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 { match kind {
ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)), ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)),
ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)), ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)),
ProviderKind::Command => anyhow::bail!( ProviderKind::Command => {
"command provider is outside this release; use filesystem or postgres" anyhow::bail!("command provider is outside this release; use filesystem or postgres")
), }
} }
} }

View File

@@ -72,7 +72,12 @@ impl PostgresSource {
self.dump_archive(file, "custom", true).await self.dump_archive(file, "custom", true).await
} }
async fn dump_archive(&self, file: fs::File, format: &str, preserve_permissions: bool) -> Result<()> { async fn dump_archive(
&self,
file: fs::File,
format: &str,
preserve_permissions: bool,
) -> Result<()> {
let mut args = dump_args(format)?; let mut args = dump_args(format)?;
if !preserve_permissions { if !preserve_permissions {
args.extend(["--no-owner".into(), "--no-acl".into()]); args.extend(["--no-owner".into(), "--no-acl".into()]);
@@ -287,7 +292,7 @@ async fn run_pg(
.env_remove("PGPASSWORD") .env_remove("PGPASSWORD")
.stdin(process.stdin) .stdin(process.stdin)
.stdout(process.stdout) .stdout(process.stdout)
.stderr(Stdio::null()) .stderr(Stdio::piped())
.kill_on_drop(true) .kill_on_drop(true)
.spawn() .spawn()
.context("starting PostgreSQL client")? .context("starting PostgreSQL client")?
@@ -296,13 +301,41 @@ async fn run_pg(
.context("waiting for PostgreSQL client")?; .context("waiting for PostgreSQL client")?;
anyhow::ensure!( anyhow::ensure!(
output.status.success(), output.status.success(),
"{} failed ({})", "{} failed ({}){}",
process.program, process.program,
output.status output.status,
client_reason(&output.stderr)
); );
Ok(output) 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> { fn write_pgpass(target: &PgTarget, any_database: bool) -> Result<tempfile::NamedTempFile> {
let fields = [ let fields = [
&target.host, &target.host,
@@ -353,13 +386,31 @@ impl BackupProvider for PostgresProvider {
#[cfg(test)] #[cfg(test)]
mod tests { 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 super::*;
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
#[test] #[test]
fn pg_dump_keeps_the_url_out_of_argv() { fn pg_dump_keeps_the_url_out_of_argv() {
let target = let target =
parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap(); parse_postgres_url("postgres://migrator:s%3Acret@example.invalid:5433/billing")
.unwrap();
assert_eq!(target.password, "s:cret"); assert_eq!(target.password, "s:cret");
let args = dump_args("custom").unwrap(); let args = dump_args("custom").unwrap();
let pgpass = write_pgpass(&target, false).unwrap(); let pgpass = write_pgpass(&target, false).unwrap();

View File

@@ -20,6 +20,11 @@ pub enum PostgresReset {
#[serde(default = "public")] #[serde(default = "public")]
schema: String, 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, RecreateDatabase,
} }
@@ -118,6 +123,15 @@ impl PostgresRestore {
writeln!(script, "CREATE 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 => { PostgresReset::RecreateDatabase => {
ensure!( ensure!(
expected expected
@@ -137,12 +151,23 @@ impl PostgresRestore {
writeln!(script, "BEGIN;")?; 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(); let key = uuid::Uuid::new_v4().simple();
writeln!(script, "\\restrict {key}")?; writeln!(script, "\\restrict {key}")?;
let skip_timeout = self.omit_transaction_timeout; let skip_timeout = self.omit_transaction_timeout;
let skip_extension = self.omit_pg_stat_statements; let skip_extension = self.omit_pg_stat_statements;
let create_public = let create_public = match &self.mode {
matches!(&self.mode, PostgresReset::Schema { schema } if schema == "public"); PostgresReset::Schema { schema } => schema == "public",
PostgresReset::UserSchemas => true,
PostgresReset::RecreateDatabase => false,
};
let post_sql = self.post_restore_sql.clone(); let post_sql = self.post_restore_sql.clone();
tokio::task::spawn_blocking(move || { tokio::task::spawn_blocking(move || {
append_dump( append_dump(
@@ -152,6 +177,9 @@ impl PostgresRestore {
skip_extension, skip_extension,
create_public, 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 { if let Some(path) = post_sql {
io::copy( io::copy(
&mut fs::File::open(path).context("read local post-restore SQL")?, &mut fs::File::open(path).context("read local post-restore SQL")?,
@@ -165,12 +193,43 @@ impl PostgresRestore {
.await? .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<()> { pub async fn apply(&self, script: File) -> Result<()> {
let database = match self.mode { let database = match self.mode {
PostgresReset::RecreateDatabase => Some("postgres"), PostgresReset::RecreateDatabase => Some("postgres"),
PostgresReset::Schema { .. } => None, PostgresReset::Schema { .. } | PostgresReset::UserSchemas => None,
}; };
let args = ["-X", "-w", "-q", "-v", "ON_ERROR_STOP=1", "-f", "-"].map(String::from); // 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 self.connection
.run("psql", &args, database, Stdio::from(script), Stdio::null()) .run("psql", &args, database, Stdio::from(script), Stdio::null())
.await?; .await?;
@@ -178,6 +237,12 @@ impl PostgresRestore {
} }
} }
/// 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 { fn literal(value: &str) -> String {
format!("'{}'", value.replace('\'', "''")) format!("'{}'", value.replace('\'', "''"))
} }
@@ -188,19 +253,29 @@ fn identifier(value: &str) -> String {
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> { async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
let file = tempfile::tempfile()?; let file = tempfile::tempfile()?;
let status = Command::new(executable) // 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) .args(args)
.stdin(Stdio::from(input)) .stdin(Stdio::from(input))
.stdout(Stdio::from(file.try_clone()?)) .stdout(Stdio::from(file.try_clone()?))
.stderr(Stdio::null()) .stderr(Stdio::piped())
.kill_on_drop(true) .kill_on_drop(true)
.status() .spawn()
.context("prepare PostgreSQL restore script")?
.wait_with_output()
.await .await
.context("prepare PostgreSQL restore script")?; .context("prepare PostgreSQL restore script")?;
ensure!( if !output.status.success() {
status.success(), if executable == "pg_restore" {
"{executable} rejected the restore archive" 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!( ensure!(
file.metadata()?.len() > 0, file.metadata()?.len() > 0,
"empty PostgreSQL restore script" "empty PostgreSQL restore script"
@@ -208,6 +283,146 @@ async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
Ok(file) 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( fn append_dump(
data: File, data: File,
script: &mut File, script: &mut File,
@@ -263,3 +478,420 @@ fn append_dump(
} }
Ok(()) 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

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

View File

@@ -43,7 +43,7 @@ impl VaultKey {
if let Some(parent) = salt_path.parent() { if let Some(parent) = salt_path.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
} }
fs::write(salt_path, &salt)?; fs::write(salt_path, salt)?;
restrict_secret_file(salt_path)?; restrict_secret_file(salt_path)?;
let spec = KdfSpec::argon2id(); let spec = KdfSpec::argon2id();
fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?; fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?;

View File

@@ -10,8 +10,28 @@ use std::{
use tokio::process::Command; use tokio::process::Command;
use uuid::Uuid; 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 { pub struct Offsite {
repo: restic::Repository, repo: restic::Repository,
limits: Limits,
} }
pub struct OffsiteCopy { pub struct OffsiteCopy {
@@ -46,15 +66,16 @@ impl Offsite {
path: PathBuf::from(repository), path: PathBuf::from(repository),
password: password.into(), password: password.into(),
}, },
limits: LIMITS,
}) })
} }
fn command(&self) -> Command { fn command(&self) -> Command {
let mut command = Command::from(self.repo.command()); let mut command = Command::from(self.repo.command());
command command
.args(["-o", "s3.retries=1", "--stuck-request-timeout=15s"]) .args(["-o", "s3.retries=3", "--stuck-request-timeout=60s"])
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stderr(Stdio::null()) .stderr(Stdio::piped())
.kill_on_drop(true); .kill_on_drop(true);
command command
} }
@@ -63,9 +84,16 @@ impl Offsite {
restic::validate_id(id)?; restic::validate_id(id)?;
let mut password = tempfile::NamedTempFile::new()?; let mut password = tempfile::NamedTempFile::new()?;
writeln!(password, "{}", source.password)?; writeln!(password, "{}", source.password)?;
let probe = run(self.command().args(["snapshots", "--json"]), 10).await?; let probe = run(
self.command().args(["snapshots", "--json"]),
self.limits.probe,
)
.await?;
if probe.status.code() == Some(10) { if probe.status.code() == Some(10) {
safe(run(self.command().arg("init"), 30).await?, "init")?; safe(
run(self.command().arg("init"), self.limits.init).await?,
"init",
)?;
} else { } else {
safe(probe, "probe")?; safe(probe, "probe")?;
} }
@@ -82,7 +110,7 @@ impl Offsite {
.arg("--from-password-file") .arg("--from-password-file")
.arg(password.path()) .arg(password.path())
.arg(id), .arg(id),
3600, self.limits.copy,
) )
.await?, .await?,
"copy", "copy",
@@ -90,28 +118,36 @@ impl Offsite {
Ok(()) 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>> { async fn tagged_snapshot(&self, snapshot: Uuid) -> Result<Option<String>> {
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
struct Copy { struct Copy {
id: String, id: String,
} }
let output = safe( let output = run(
run( self.command().args([
self.command().args([ "snapshots",
"snapshots", "--json",
"--json", "--tag",
"--tag", &restic::tessera_tag(snapshot),
&restic::tessera_tag(snapshot), ]),
]), self.limits.list,
15, )
) .await?;
.await?, // Exit code 10: the repository does not exist yet, so nothing has been copied.
"list", 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)?; let mut snapshots: Vec<Copy> = serde_json::from_slice(&output.stdout)?;
Ok(snapshots.pop().map(|copy| copy.id)) 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> { pub async fn restore(&self, snapshot: Uuid, dest: &Path) -> Result<u64> {
let id = self let id = self
.tagged_snapshot(snapshot) .tagged_snapshot(snapshot)
@@ -136,14 +172,25 @@ impl Offsite {
)?; )?;
let size = file.as_file().metadata()?.len(); let size = file.as_file().metadata()?.len();
file.as_file().sync_all()?; file.as_file().sync_all()?;
file.persist(dest)?; file.persist_noclobber(dest)?;
Ok(size) Ok(size)
} }
pub async fn copy_capture(&self, copy: OffsiteCopy) -> Result<()> { 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?; self.copy_from(&copy.source, &copy.restic_id).await?;
ensure!( ensure!(
self.tagged_snapshot(copy.snapshot).await?.is_some(), self.tagged_snapshot_retrying(copy.snapshot)
.await?
.is_some(),
"off-site snapshot tag not found after copy" "off-site snapshot tag not found after copy"
); );
Ok(()) Ok(())
@@ -156,15 +203,173 @@ async fn run(command: &mut Command, seconds: u64) -> Result<Output> {
command.spawn()?.wait_with_output(), command.spawn()?.wait_with_output(),
) )
.await .await
.context("off-site Restic operation timed out")??; .with_context(|| format!("off-site Restic operation timed out after {seconds}s"))??;
Ok(result) Ok(result)
} }
fn safe(output: Output, step: &str) -> Result<Output> { fn safe(output: Output, step: &str) -> Result<Output> {
ensure!( ensure!(
output.status.success(), output.status.success(),
"off-site Restic {step} failed ({})", "off-site Restic {step} failed ({}){}",
output.status output.status,
stderr_tail(&output.stderr)
); );
Ok(output) 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

@@ -14,7 +14,8 @@ use tessera_core::decay::{
use tessera_core::manifest::SnapshotManifest; use tessera_core::manifest::SnapshotManifest;
use uuid::Uuid; 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)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredSnapshot { pub struct StoredSnapshot {
@@ -42,6 +43,9 @@ struct OutpostRepository {
password: String, 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 { impl Vault {
pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> { pub fn init(root: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
if passphrase == "dev-vault-key" { if passphrase == "dev-vault-key" {
@@ -49,6 +53,10 @@ impl Vault {
"refusing to initialize a vault with the published dev passphrase; choose a private passphrase" "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(); let root = root.as_ref().to_path_buf();
fs::create_dir_all(root.join("data"))?; fs::create_dir_all(root.join("data"))?;
fs::create_dir_all(root.join("snapshots"))?; fs::create_dir_all(root.join("snapshots"))?;
@@ -80,6 +88,16 @@ impl Vault {
anyhow::bail!("vault not initialized"); anyhow::bail!("vault not initialized");
} }
restrict_dir(&root.join("keys"))?; 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 salt = root.join("keys/tessera.salt");
let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let key = VaultKey::derive_from_passphrase(passphrase, &salt)?;
let index = Self::load_index(&root)?; let index = Self::load_index(&root)?;
@@ -173,11 +191,15 @@ impl Vault {
restic_id: &str, restic_id: &str,
) -> Result<StoredSnapshot> { ) -> Result<StoredSnapshot> {
let config = self.outpost_config(manifest.orbit_id)?; let config = self.outpost_config(manifest.orbit_id)?;
anyhow::ensure!(config.outpost_id == outpost_id, "repository belongs to another outpost"); anyhow::ensure!(
config.outpost_id == outpost_id,
"repository belongs to another outpost"
);
let repo = self.outpost_repository(manifest.orbit_id, config); let repo = self.outpost_repository(manifest.orbit_id, config);
let id = manifest.snapshot_id; let id = manifest.snapshot_id;
let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD); let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD);
let summary = repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?; let summary =
repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?;
Ok(StoredSnapshot { Ok(StoredSnapshot {
id, id,
taken_at: Utc::now(), taken_at: Utc::now(),
@@ -310,7 +332,13 @@ impl Vault {
repo.init() repo.init()
.context("opening the deduplicated vault (restic must be on PATH)")?; .context("opening the deduplicated vault (restic must be on PATH)")?;
let mut cmd = repo.command(); let mut cmd = repo.command();
cmd.args(["backup", "--json", "--quiet", "--tag", &restic::tessera_tag(manifest.snapshot_id)]); cmd.args([
"backup",
"--json",
"--quiet",
"--tag",
&restic::tessera_tag(manifest.snapshot_id),
]);
if dry_run { if dry_run {
cmd.arg("--dry-run"); cmd.arg("--dry-run");
} }
@@ -339,7 +367,10 @@ impl Vault {
} }
pub fn import_legacy_payload( pub fn import_legacy_payload(
&self, manifest: SnapshotManifest, payload: File, taken_at: chrono::DateTime<Utc>, &self,
manifest: SnapshotManifest,
payload: File,
taken_at: chrono::DateTime<Utc>,
) -> Result<bool> { ) -> Result<bool> {
let id = manifest.snapshot_id; let id = manifest.snapshot_id;
let receipts = self.root.join("keys/legacy-imports"); let receipts = self.root.join("keys/legacy-imports");
@@ -351,7 +382,8 @@ impl Vault {
} }
let snapshots = self.root.join("snapshots"); let snapshots = self.root.join("snapshots");
let already_imported = || -> Result<bool> { let already_imported = || -> Result<bool> {
Ok(self.has_published_snapshot(id)? || snapshots.join(format!("{id}.expired")).try_exists()?) Ok(self.has_published_snapshot(id)?
|| snapshots.join(format!("{id}.expired")).try_exists()?)
}; };
let imported = if already_imported()? { let imported = if already_imported()? {
false false
@@ -378,18 +410,32 @@ impl Vault {
} }
pub fn legacy_import_exists(&self, id: Uuid) -> Result<bool> { pub fn legacy_import_exists(&self, id: Uuid) -> Result<bool> {
Ok(self.root.join("keys/legacy-imports").join(id.to_string()).try_exists()?) 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<()> { pub fn verify_prepared_payload(
&self,
snap: &StoredSnapshot,
expected: &[u8; 32],
) -> Result<()> {
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
let id = snap.tree_root.strip_prefix(restic::PREFIX).context("prepared payload is missing")?; let id = snap
.tree_root
.strip_prefix(restic::PREFIX)
.context("prepared payload is missing")?;
let mut file = tempfile::tempfile()?; let mut file = tempfile::tempfile()?;
self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?; self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?;
file.seek(SeekFrom::Start(0))?; file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new(); let mut digest = Sha256::new();
std::io::copy(&mut file, &mut digest)?; std::io::copy(&mut file, &mut digest)?;
anyhow::ensure!(digest.finalize()[..] == expected[..], "stored payload checksum mismatch"); anyhow::ensure!(
digest.finalize()[..] == expected[..],
"stored payload checksum mismatch"
);
Ok(()) Ok(())
} }
@@ -405,7 +451,11 @@ impl Vault {
} }
pub fn has_published_snapshot(&self, id: Uuid) -> Result<bool> { pub fn has_published_snapshot(&self, id: Uuid) -> Result<bool> {
Ok(self.root.join("snapshots").join(format!("{id}.json.enc")).try_exists()?) Ok(self
.root
.join("snapshots")
.join(format!("{id}.json.enc"))
.try_exists()?)
} }
fn index_path(&self) -> PathBuf { fn index_path(&self) -> PathBuf {
@@ -552,15 +602,33 @@ impl Vault {
} }
pub fn prepare_offsite_copy(&self, id: Uuid) -> Result<crate::OffsiteCopy> { 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")))?; let snapshot =
anyhow::ensure!(snapshot.manifest.restore_hints.get("job_id").is_some(), "snapshot is not a capture job"); self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?;
let (source, restic_id) = if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { anyhow::ensure!(
let orbit = snapshot.manifest.orbit_id; snapshot.manifest.restore_hints.get("job_id").is_some(),
(self.outpost_repository(orbit, self.outpost_config(orbit)?), id) "snapshot is not a capture job"
} else { );
(self.restic.clone(), snapshot.tree_root.strip_prefix(restic::PREFIX).context("capture Restic snapshot missing")?) let (source, restic_id) =
}; if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
Ok(crate::OffsiteCopy { snapshot: id, source, restic_id: restic_id.to_owned() }) 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>> { pub fn get_snapshot(&self, id: Uuid) -> Result<Option<StoredSnapshot>> {
@@ -574,7 +642,9 @@ impl Vault {
} }
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> { pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let snap = self.get_snapshot(id)?.context("snapshot metadata not found")?; let snap = self
.get_snapshot(id)?
.context("snapshot metadata not found")?;
let parent = dest let parent = dest
.parent() .parent()
.filter(|p| !p.as_os_str().is_empty()) .filter(|p| !p.as_os_str().is_empty())
@@ -583,7 +653,11 @@ impl Vault {
let mut temp = tempfile::NamedTempFile::new_in(parent)?; let mut temp = tempfile::NamedTempFile::new_in(parent)?;
if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) { if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit_id = snap.manifest.orbit_id; let orbit_id = snap.manifest.orbit_id;
let path = if snap.manifest.restore_hints["format"] == "tar" { "/" } else { restic::PAYLOAD }; let path = if snap.manifest.restore_hints["format"] == "tar" {
"/"
} else {
restic::PAYLOAD
};
self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?) self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?)
.dump(id, path, temp.reopen()?)?; .dump(id, path, temp.reopen()?)?;
} else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) { } else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
@@ -598,7 +672,8 @@ impl Vault {
} }
let len = temp.as_file().metadata()?.len(); let len = temp.as_file().metadata()?.len();
temp.as_file().sync_all()?; temp.as_file().sync_all()?;
temp.persist(dest)?; // never replace a file that is already there
temp.persist_noclobber(dest)?;
Ok(len) Ok(len)
} }
@@ -682,9 +757,15 @@ impl Vault {
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> { pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let snaps = self.list_snapshots()?; let snaps = self.list_snapshots()?;
self.prune_snapshots(preset, None, snaps.into_iter() self.prune_snapshots(
.filter(|snapshot| snapshot.manifest.provider != "legacy-history" preset,
&& snapshot.manifest.restore_hints.get("job_id").is_none())) 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( pub fn prune_orbit_with_decay(
@@ -699,7 +780,7 @@ impl Vault {
retention, retention,
snaps snaps
.into_iter() .into_iter()
.filter(|s| s.manifest.orbit_id == orbit_id), .filter(|s| s.manifest.orbit_id == orbit_id && !s.manifest.is_restore_safety()),
) )
} }
@@ -766,7 +847,7 @@ mod tests {
rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes); rand::rngs::StdRng::seed_from_u64(7).fill_bytes(&mut bytes);
let file = source.join("large.bin"); let file = source.join("large.bin");
fs::write(&file, &bytes).unwrap(); fs::write(&file, &bytes).unwrap();
let mut vault = Vault::init(dir.path().join("vault"), "secret").unwrap(); let mut vault = Vault::init(dir.path().join("vault"), "secret-test-passphrase").unwrap();
let manifest = SnapshotManifest { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -819,7 +900,7 @@ mod tests {
#[test] #[test]
fn init_snap_list_restore() { fn init_snap_list_restore() {
let dir = tempdir().unwrap(); 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 { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -829,9 +910,7 @@ mod tests {
paths: vec![], paths: vec![],
restore_hints: serde_json::json!({}), restore_hints: serde_json::json!({}),
}; };
let snap = vault let snap = vault.snapshot(manifest, b"payload bytes", false).unwrap();
.snapshot(manifest, b"payload bytes", false)
.unwrap();
let list = vault.list_snapshots().unwrap(); let list = vault.list_snapshots().unwrap();
assert_eq!(list.len(), 1); assert_eq!(list.len(), 1);
assert_eq!(list[0].id, snap.id); assert_eq!(list[0].id, snap.id);
@@ -844,7 +923,7 @@ mod tests {
#[test] #[test]
fn dry_run_writes_nothing() { fn dry_run_writes_nothing() {
let dir = tempdir().unwrap(); 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 { let manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(), snapshot_id: Uuid::new_v4(),
orbit_id: Uuid::new_v4(), orbit_id: Uuid::new_v4(),
@@ -861,7 +940,7 @@ mod tests {
#[test] #[test]
fn orbit_decay_keeps_other_orbits_recoverable() { fn orbit_decay_keeps_other_orbits_recoverable() {
let dir = tempdir().unwrap(); 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 orbit_id = Uuid::new_v4(); let orbit_id = Uuid::new_v4();
let other_id = Uuid::new_v4(); let other_id = Uuid::new_v4();
let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap(); let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap();
@@ -898,7 +977,7 @@ mod tests {
#[test] #[test]
fn new_snapshots_are_encrypted_and_legacy_json_still_reads() { fn new_snapshots_are_encrypted_and_legacy_json_still_reads() {
let dir = tempdir().unwrap(); 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 legacy_id = Uuid::new_v4(); let legacy_id = Uuid::new_v4();
let legacy = StoredSnapshot { let legacy = StoredSnapshot {
id: legacy_id, id: legacy_id,
@@ -918,7 +997,9 @@ mod tests {
new_data_chunks: None, new_data_chunks: None,
}; };
fs::write( fs::write(
dir.path().join("snapshots").join(format!("{legacy_id}.json")), dir.path()
.join("snapshots")
.join(format!("{legacy_id}.json")),
serde_json::to_string(&legacy).unwrap(), serde_json::to_string(&legacy).unwrap(),
) )
.unwrap(); .unwrap();
@@ -955,6 +1036,15 @@ mod tests {
assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6); 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] #[test]
fn init_rejects_published_dev_passphrase() { fn init_rejects_published_dev_passphrase() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();

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"]

View File

@@ -13,6 +13,8 @@ tessera-agent --hub-url https://backup.example.org --credentials /etc/tessera/wo
tessera-agent --credentials /etc/tessera/wormhole.json --capture-profiles /etc/tessera/capture.json run 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. 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 ## Register an application
@@ -33,6 +35,12 @@ For CLI setup, create an orbit using `tessera orbit billing --provider wormhole`
} }
``` ```
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. 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. 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.
@@ -85,7 +93,21 @@ Use the snapshot detail to download or remove an archive. Database snapshots can
## Operator sign-in ## Operator sign-in
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: 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 ```bash
read -rs -p 'Operator password: ' tessera_operator_password; printf '\n' read -rs -p 'Operator password: ' tessera_operator_password; printf '\n'
@@ -93,7 +115,18 @@ export TESSERA_OPERATOR_PASSWORD_HASH="$(printf '%s\n' "$tessera_operator_passwo
unset tessera_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 or a hub restart. 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. 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 ## Optional S3 copy
@@ -131,11 +164,19 @@ On the target agent, add a `targets` map under the application UUID, keyed by th
} }
``` ```
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. 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. 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. 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.
Choose the snapshot and target in **Restore**. 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. 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 ## Import legacy archives
@@ -148,3 +189,244 @@ tessera legacy-import --bucket legacy-bucket --prefix billing/ --orbit-id ORBIT_
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). 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. 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

@@ -1,50 +0,0 @@
# Paritas Backup & Restore Center MBU
Inventaris 10 November 2026. Targetnya adalah Tessera dapat mengambil alih backup dan restore database di backup.mbugroup.id, termasuk pemulihan dari arsip lama. Uji awal memakai topologi yang ditemukan di deployment dan data sintetis di lingkungan terisolasi.
## Deployment yang diperiksa
- Teleport `mbu-backup-jumphost` memiliki IP publik yang cocok dengan DNS situs. Nginx meneruskan trafik ke port lokal 8088. Docker Compose menjalankan container `backup-restore-center` dari `/opt/apps-backup`, dengan source dan data dipasang dari host.
- Situs mengarahkan pengguna ke login. Source yang terpasang menunjukkan sesi browser, dashboard per aplikasi, riwayat dengan filter aplikasi dan status, pembaruan otomatis selama job aktif, log job, serta audit login dan tindakan.
- Cron host mengantrekan backup semua aplikasi pada 19.00 UTC atau 02.00 WIB hari berikutnya. Worker menjalankan antrean FIFO per aplikasi dan memulihkan status job yang tertinggal saat restart. Batas satu perintah adalah 1.800 detik.
- Inventaris S3 berisi 228 objek `.sql.gz` dengan total 7.486.456.004 byte. Dump terbesar sekitar 66 MB. Konfigurasi aktif menghapus dump yang lebih tua dari 14 hari dan mempertahankan minimal satu per aplikasi. Lima backup adalah fallback berbasis jumlah. Dashboard mendukung unduh lewat URL bertanda tangan dan hapus per backup. File staging lokal dibersihkan setelah job.
- Snapshot read-only SQLite berisi 968 baris job, termasuk backup dan restore gagal. Tiga timer retensi systemd pada host menunjuk ke direktori set terpisah di bawah `/var/lib`. Inventaris 228 objek mencakup katalog aplikasi web.
## Kasus penerimaan dari deployment
| Kasus | Aplikasi | Yang harus dibuktikan |
| --- | --- | --- |
| PostgreSQL langsung | `lti`, `presensi`, `sso`, `helpdesk`, `manbu` | Capture dengan TLS, restore ke target terdaftar, verifikasi skema dan isi. Sertakan target bernama `manbu_development`. |
| PostgreSQL dengan penyesuaian restore | `daily_checklist` | Reset schema, jalankan SQL pascarestore, serta bedakan error kompatibilitas yang ditoleransi dari kegagalan yang harus terlihat. |
| PostgreSQL lewat bastion | `odoo_mas`, `odoo_fta` | Gunakan host key yang dipin. Uji reset berupa pembuatan ulang database pada target sementara untuk MAS. FTA harus bisa capture dengan target restore kosong. |
| MySQL lewat SSH | `boiler` | Gunakan fixture MySQL dengan routine, event, view, dan DEFINER. Verifikasi dump konsisten, kompatibilitas restore, dan rollback dengan backup pengaman pada target seperti staging. |
| Backup tanpa target | `dashboard_management`, `odoo_fta` | Backup manual dan terjadwal tetap tersedia. Permintaan restore ke database ditolak sampai ada target terdaftar. |
| Arsip lama | Kesepuluh aplikasi | Rekonsiliasi per aplikasi, waktu, ukuran, format, dan identitas objek. Uji migrasi ulang tanpa duplikasi serta restore sampel dari PostgreSQL dan MySQL. |
Untuk restore database, operator memilih snapshot dan target, lalu mengetik konfirmasi. Backup pengaman target harus selesai dan tersimpan sebelum perubahan pertama. Uji target salah, sumber produksi sebagai target, kegagalan backup pengaman, kegagalan di tengah restore, dan pemulihan dari backup pengaman. PostgreSQL lama menggunakan SQL polos terkompresi tanpa owner dan ACL. Restore lama memiliki penanganan kompatibilitas untuk `transaction_timeout` dan `pg_stat_statements`.
## Peta kapabilitas untuk ditinjau
| Modul | Tanggung jawab dan selisih Tessera | Bergantung pada |
| --- | --- | --- |
| `operator-access` | Sesi browser dan audit operator. Tessera punya token admin untuk API. Canvas belum dapat beroperasi dengan token itu. Uji juga membuktikan respons daftar orbit mengandung kredensial provider. | — |
| `database-capture` | Profil aplikasi dengan secret reference, PostgreSQL langsung atau melalui bastion, dan MySQL lewat SSH. Tessera sudah dapat dump PostgreSQL langsung, tetapi parser membuang parameter query URL seperti `sslmode`. | — |
| `backup-catalog` | Penyimpanan off-host S3, metadata, daftar, unduh, hapus, dan retensi 14 hari atau fallback jumlah. Tessera sudah memakai Restic lokal serta retensi GFS. | — |
| `database-recovery` | Target yang diizinkan, konfirmasi, backup pengaman, restore database, dan SQL pascarestore. Reconstitute saat ini mengekspor payload ke path di hub. | `database-capture`, `backup-catalog` |
| `job-operations` | Jadwal WIB, antrean persisten per aplikasi, batas waktu, status dan log per fase, serta pemulihan setelah restart. Tessera sudah memiliki orbit manual dan cron UTC. Jadwal sekarang menunggu capture satu per satu dalam satu tick dan mengecek waktu eksekusi berikutnya tanpa catatan eksekusi per slot. | `operator-access`, `database-capture`, `backup-catalog`, `database-recovery` |
| `legacy-transition` | Impor atau akses arsip lama, rekonsiliasi riwayat operasional, uji paralel dan peralihan. | `backup-catalog`, `database-recovery`, `job-operations` |
Urutan usulan dimulai dengan akses operator dan kontrak rahasia, lalu capture dan katalog, restore database, operasi job, dan transisi. Fitur Tessera yang melampaui layanan lama dan masuk uji regresi mencakup enkripsi dan deduplikasi Restic, retensi GFS, serta capture filesystem dan outpost Wormhole.
## Bukti uji awal
- PostgreSQL 14 sementara dengan data sintetis berhasil melewati pembuatan orbit, capture manual, penyegelan Restic, ekspor lewat Reconstitute, dan `pg_restore` manual ke database kedua. Isi baris diverifikasi di target. Ini menguji jalur ekspor yang ada.
- API tanpa autentikasi pada hub bertoken mengembalikan 401. Daftar orbit dengan token mengembalikan URL koneksi yang mengandung password sintetis.
- Rust workspace lulus 22 tes dan tes Restic yang biasanya diabaikan juga lulus ketika dijalankan terpisah. Sepuluh tes web, typecheck, dan build lulus.
- Pemeriksaan produksi membaca source, metadata agregat job, dan inventaris objek. Validasi koneksi dan restore terhadap data produksi, uji paralel, serta peralihan belum dijalankan.
## Implementasi dan bukti fixture
Lihat [panduan capture database](DATABASE-CAPTURE.md) dan [matriks fixture](../tests/mbu/README.md). Jalur lokal mencakup PostgreSQL langsung dan lewat bastion, MySQL langsung dan lewat SSH, antrean per aplikasi, jadwal zona waktu, histori fase, katalog Restic, dan salinan S3. Fixture juga mencakup restore PostgreSQL/MySQL ke target terdaftar, verifikasi safety backup, rekonsiliasi gangguan, serta impor arsip SQL dan histori SQLite. [Runbook peralihan](MBU-CUTOVER.md) memisahkan bukti fixture dari penerimaan staging MBU.
Inventaris Teleport bisa dibaca lewat Machine ID. Verifikasi placement dan versi pada host produksi menunggu akun OS yang diizinkan pada node terkait. Angka inventaris arsip lama di atas tetap merupakan hasil pemeriksaan awal.

View File

@@ -1,56 +0,0 @@
# Runbook peralihan Tessera MBU
Status per 10 November 2026. Rehearsal lokal memakai data sintetis dan endpoint loopback. Akses staging MBU, sampel arsip lama, dan window produksi memerlukan persetujuan operator.
## Siapkan staging
1. Konfirmasi node dan akun OS yang disetujui untuk MAS, FTA, dan Boiler. Catat versi server dan client, jalur direct atau SSH, host key, dan hak backup/restore. Letakkan secret di agent atau host SSH yang menjalankan client.
2. Sediakan data dir Tessera, operator HTTPS, kredensial API terpisah, dan prefix Restic S3 staging. Gunakan akses baca pada bucket arsip lama. Catat pemilik tiga timer retensi host dan integrasi di luar dashboard lama.
3. Daftarkan sepuluh aplikasi dengan UUID stabil, jadwal 02.00 WIB, dan target uji yang disetujui. Pakai [peta paritas](MBU-BACKUP-PARITY.md). FTA dan Dashboard Management cukup menjalankan capture.
4. Jalankan [fixture lokal](../tests/mbu/README.md), lalu ulangi manual dan jadwal per aplikasi pada staging. Catat ID job, waktu slot, usia snapshot terbaru, durasi, ukuran, hasil checksum dan pemulihan, ID safety backup, serta status salinan S3.
## Rekonsiliasi arsip
1. Jalankan `tessera legacy-import --inventory-only` per prefix. Bandingkan key, ETag, waktu sumber, ukuran, dan total dengan inventaris lama. Simpan laporan JSON bersama bukti staging.
2. Impor ke vault staging dan ulangi untuk memeriksa idempotensi. Pulihkan sampel PostgreSQL dan MySQL yang disetujui ke target sementara. Impor salinan SQLite lama yang konsisten dan simpan ID arsip histori untuk `tessera legacy-history`.
3. Bandingkan delta objek setelah uji paralel. Ulangi inventaris dan impor sebelum peralihan. Simpan jumlah, byte, dan daftar selisih per aplikasi.
## Simulasikan rollback
1. Jalankan restore ke target sementara. Putuskan agent setelah reset pada kasus recreate. Restart hub, tunggu lease berakhir, dan pastikan status `recovery_required` menahan target dan kedua snapshot.
2. Hentikan proses apply sebelumnya dan verifikasi sesi database sudah berhenti. Unduh safety backup dari job. Pulihkan ke target sementara yang sama dengan client engine, verifikasi schema, isi, dan izin, lalu masukkan konfirmasi `RECONCILE <job-id>`. Catat hasil verifikasi dan audit.
3. Simulasikan repo primer tidak tersedia. Pulihkan arsip dari prefix S3 memakai UUID snapshot. Bandingkan checksum dan isi database dengan baseline. Catat apakah salinan dan password recovery tersedia dari host lain.
4. Uji peralihan trafik di staging. Kembalikan routing ke layanan lama dan pastikan operator dapat menjalankan backup serta membuka histori. Cocokkan jadwal dan integrasi eksternal setelah rollback.
## Keputusan operator
Penuhi bukti per aplikasi sebelum operator menyetujui perubahan domain. Catat window, pemilik keputusan, target yang diuji, periode paralel, batas freshness dan durasi, serta perubahan Nginx atau DNS yang dibutuhkan. Tahan peralihan bila ada arsip yang belum terekonsiliasi, salinan S3 tidak dapat dipulihkan, jadwal terlewat, restore menghasilkan isi berbeda, atau target masih terkunci.
Pada window yang disetujui, ambil inventaris delta terakhir, verifikasi backup terbaru tiap aplikasi, lalu alihkan trafik. Cek sign-in, histori, backup manual, dan download. Pantau siklus 02.00 WIB. Pertahankan layanan dan artefak lama selama periode rollback yang disepakati.
Jika kriteria rollback tercapai, kembalikan routing, aktifkan jadwal lama sesuai keputusan operator, dan catat job atau objek Tessera sejak peralihan untuk rekonsiliasi. Tunda restore pada target yang statusnya belum diketahui sampai safety backup dan hasil verifikasi tersedia.
## Hasil rehearsal lokal
Ketiga outpost memproses 10 backup manual dan 10 backup dari scheduler. Semua 20 snapshot tersalin ke S3 fixture. Delapan target dipulihkan dan diperiksa isinya. Dua aplikasi capture-only tetap dapat backup. Download arsip LTI berhasil setelah repo primer dipindahkan sementara.
| Aplikasi | Manual (detik) | Terjadwal (detik) | Freshness (detik) | Ukuran (byte) | Restore |
| --- | ---: | ---: | ---: | ---: | --- |
| lti | 3 | 5 | 39 | 1391 | Lulus |
| presensi | 3 | 5 | 39 | 1416 | Lulus |
| sso | 4 | 5 | 39 | 1391 | Lulus |
| helpdesk | 3 | 5 | 39 | 1416 | Lulus |
| manbu | 4 | 6 | 38 | 1401 | Lulus |
| daily_checklist | 2 | 10 | 34 | 1071 | Lulus |
| odoo_mas | 3 | 6 | 38 | 1416 | Lulus |
| odoo_fta | 2 | 6 | 38 | 1416 | Capture-only |
| dashboard_management | 2 | 5 | 39 | 1476 | Capture-only |
| boiler | 3 | 6 | 38 | 3132 | Lulus |
Freshness diukur setelah semua salinan selesai. Fixture PostgreSQL terpisah menguji putus agent setelah reset, restart hub, penolakan permit lama, pemulihan safety dump, dan audit rekonsiliasi.
## Bukti yang menunggu staging MBU
- Akun OS yang disetujui, versi client/server, dan jalur sebenarnya pada MAS, FTA, dan Boiler.
- Rekonsiliasi arsip asli serta restore sampel yang telah disetujui.
- Metrik uji paralel, kepemilikan integrasi eksternal, drill routing, dan persetujuan operator untuk window produksi.

View File

@@ -139,8 +139,8 @@ Tone: short sentences, metaphor in headings, facts in telemetry panels.
## Security baseline ## Security baseline
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 the published passphrase `dev-vault-key`. 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. 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:** `TESSERA_ADMIN_TOKEN` is optional and local. When it is unset, the hub logs that snapshot, orbit list/create/run, reconstitute, and pairing routes are open to loopback peers only; every other peer gets 401. When it is set, every peer, including loopback, must send `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. The compare is constant time. `/health`, OpenAPI, wormhole claim, and wormhole upload are not on this gate. The default listen address is `127.0.0.1:8787`. The canvas does not send the token, so a token-protected hub and a Docker-published port (the peer inside the container is not loopback) will 401 those routes from the page. OIDC is not implemented. 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. 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`. 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. 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.

View File

@@ -7,19 +7,64 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep
- **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. - **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. - 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. - 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. An incoming meteor represents a confirmed new snapshot. The source flares, the meteor spirals inward, and the core brightens and spins up before the new recovery point flashes. A failed capture pulses its source marker and shows text feedback. Rehearsals show text feedback. - 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. - 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** expands the map and keeps summary counts, motion controls, and a floating navigation dock. The map and dock spring into position within the current browser viewport. Use **Exit big screen** or Escape to return to the workspace. - **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 uses text and a sliding underline. The Big Screen dock uses labeled icons and a liquid highlight. - 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 icon dock at the bottom. - 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. - 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.
## Consoles
- 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.
## Data and rendering ## Data and rendering
- The map preserves each orbit's assigned slot across polling updates. Layout and snapshot grouping live in `web/src/lib/galaxyLayout.ts`. - 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. - 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. - 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 scene uses SVG with static artwork and one animation clock. The clock pauses when the tab is hidden. Labels are laid out in screen coordinates. - 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.
## Black hole renderer
- 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.
## Orbit activity
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 ## Animation guideline
@@ -27,7 +72,7 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep
- 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 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 `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. - 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.
- Use a single progress value for a staged effect. Derive the capture flare, flight, absorption, and recovery-point flash from the scene clock. If the snapshot list is still refreshing, let the impact finish and hold the flash until its confirmed snapshot arrives. - 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. - 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. - 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.

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] [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

View File

@@ -1,47 +0,0 @@
# Rencana upgrade Tessera dan agent untuk MBU
## Tujuan
Satu alur operator untuk backup dan restore database, dengan profil bertipe untuk variasi engine, jalur jaringan, dan kebijakan restore. Penerimaan mengacu pada inventaris dan kasus asli di [peta paritas MBU](../docs/MBU-BACKUP-PARITY.md). Implementasi dimulai dengan fixture terisolasi dan diakhiri dengan uji paralel sebelum peralihan produksi.
## Kontrak yang diusulkan
| Bagian | Keputusan |
| --- | --- |
| Profil aplikasi | ID aplikasi dan orbit stabil. Hub menyimpan pemetaan agent, profil, target yang diizinkan, jadwal, serta kebijakan retensi. Agent menyimpan konfigurasi koneksi dan referensi rahasia. Profil bertipe memisahkan engine, cara koneksi, format dump, dan mode restore. Manifest membawa metadata teknis yang aman. |
| Koneksi | PostgreSQL mendukung koneksi langsung dan tunnel SSH, dengan TLS eksplisit sesuai profil serta identitas server yang tetap diverifikasi ketika profil mewajibkannya. MySQL mendukung koneksi lokal/langsung dan eksekusi lewat SSH. Agent ditempatkan dekat database jika jalur jaringan mengizinkan. SSH memakai host key terdaftar dan identitas khusus. |
| Job | Hub mengantrekan job manual dan terjadwal di SQLite. Agent menarik job yang ditugaskan lewat koneksi keluar dan melaporkan fase, heartbeat, hasil, dan log yang disanitasi. Job memakai ID stabil, lease dengan identitas percobaan, dan slot jadwal unik. Job satu aplikasi diserialkan dan aplikasi lain bisa berjalan paralel. |
| Data backup | Gunakan ulang transfer Restic Wormhole dan katalog Tessera. Publikasikan restore point setelah dump selesai, artefak valid, dan penyimpanan terkonfirmasi. Simpan ukuran, waktu sumber, engine, format dan asal artefak. Bersihkan staging privat setelah kondisi terminal. Simpan salinan off-host di S3 dengan verifikasi pemulihan independen. |
| Restore | Hanya agent yang ditugaskan ke target terdaftar yang boleh menerima payload restore. Konfirmasi mengikat snapshot dan target. Validasi akses, format, integritas, identitas target, dan kapasitas sebelum perubahan. Target terkunci sampai hasil diketahui. Simpan dan verifikasi backup pengaman sebelum reset. Laporkan gangguan setelah reset sebagai pemulihan diperlukan sampai operator merekonsiliasi atau menggunakan backup pengaman. |
| Akses | Pisahkan identitas browser operator, token API/CLI, dan identitas agent. Scope upload dan klaim job per outpost dan tugas, serta scope baca payload restore ke job yang disetujui. Sesi browser membutuhkan proteksi CSRF untuk mutasi dan audit actor. Respons dan log mengecualikan kredensial. |
| Migrasi | Gunakan prefix/repository Tessera terpisah dari arsip lama selama uji paralel. Impor dari akses baca saja memakai identitas objek yang stabil serta simpan waktu sumber. Riwayat lama dapat dipertahankan sebagai arsip baca saja jika ID dan log dapat ditelusuri. |
Profil standar yang diuji mencakup PostgreSQL dengan TLS, PostgreSQL lewat tunnel, MySQL langsung dan SSH, PostgreSQL dengan reset schema atau recreate database, post-restore SQL yang disediakan lokal, dan aplikasi capture-only. Transformasi dump lama dibatasi ke kasus kompatibilitas yang dibuktikan pada fixture. Perintah bebas dari hub berada di luar kontrak. Capture, jalur transfer dan provider yang sudah ada tetap memiliki uji regresi.
## Dependensi dan urutan
1. **Identitas dan job capture pertama** — T01–T05. Tutup paparan rahasia, bangun antrean manual dan klaim yang terikat agent, lalu buktikan PostgreSQL dari hub sampai snapshot.
2. **Variasi capture dan penjadwalan** — T06–T11. Validasi placement dan jalur SSH pada MAS/FTA dan Boiler sedini mungkin. Jadwal dan histori bergantung pada jalur job yang telah berjalan.
3. **Katalog dan restore aman** — T12–T19. Verifikasi penyimpanan off-host dan retensi, kemudian akses payload per job, safety backup, PostgreSQL dan MySQL, serta penanganan gangguan.
4. **Alur browser dan pengambilalihan** — T20–T24. Sajikan alur yang sudah teruji, rekonsiliasi arsip, jalankan uji paralel, lalu tinjau peralihan.
Pekerjaan profil koneksi bisa dikerjakan independen setelah capture PostgreSQL langsung lulus. Pekerjaan restore menunggu kontrak akses payload dan safety backup. Daftar langkah, file perkiraan, dan checkpoint ada di [daftar tugas](todo.md).
## Risiko dan mitigasi
| Risiko | Mitigasi |
| --- | --- |
| Restore menimpa sumber atau target yang salah | Daftarkan target dengan identitas yang diverifikasi oleh agent, kredensial terbatas untuk target, tolak sumber/alias, dan ikat konfirmasi ke snapshot dan target. Simulasikan target salah serta safety backup gagal. |
| Lease putus setelah reset atau commit | Fencing mencegah laporan percobaan lama mengubah hasil. Job restore yang telah diberi izin masuk fase destruktif ditahan untuk rekonsiliasi jika hasil tidak diketahui. Commit capture bisa diulang berdasarkan ID job tanpa membuat restore point kedua. |
| Retensi menghapus snapshot yang masih diperlukan | Pin snapshot input dan backup pengaman sampai job dan pemulihan selesai. Terapkan kebijakan per orbit setelah capture sukses, dengan perlindungan minimal satu arsip pada mode umur. |
| Restore lintas versi sukses sebagian | Uji PostgreSQL dan MySQL dengan versi sumber/target MBU, izin realistis, owner/ACL, extension, view, DEFINER, routine, dan event. Filter hanya pola yang telah diverifikasi, lalu cocokkan schema dan data. |
| Rahasia bocor atau agent menyasar orbit lain | Uji token salah, lease kadaluarsa, redaksi log/JSON, izin staging, pemisahan repository, dan autentikasi perangkat. Tinjau penyimpanan kredensial lama sebelum paparan hub ke pengguna tambahan. |
| Backup gagal saat host mati atau repo rusak | Terapkan batas waktu, catat fase kegagalan, dan buktikan restore dari salinan off-host ketika hub/repo utama tidak tersedia. |
| Peralihan kehilangan histori atau backup terbaru | Inventaris ulang saat migrasi, rekonsiliasi identitas objek, ukuran, dan hitungan per aplikasi. Pertahankan layanan lama sebagai rollback sampai uji paralel dan restore lulus. |
## Hal yang perlu dikonfirmasi dari deployment
- Lokasi agent yang diizinkan, jalur jaringan nyata, dan versi client/server untuk `odoo_mas`, `odoo_fta`, dan `boiler`. Gunakan Teleport untuk inventaris, lalu fixture dengan topologi serupa untuk uji gagal.
- Endpoint dan izin S3 untuk salinan Tessera, batas bandwidth/ruang staging, serta periode uji paralel. Default untuk fixture adalah data sintetis, prefix terpisah, dan backup harian pukul 02.00 WIB.
- Kepemilikan tiga timer retensi host dan integrasi di luar katalog web. Evaluasi sebelum peralihan domain agar job eksternal tetap bisa berjalan.
- Uji produksi dan peralihan mengikuti persetujuan operasional atas target, window, dan rollback. Restore verifikasi memakai target sementara yang telah disetujui.

View File

@@ -1,36 +0,0 @@
# Rencana implementasi pencarian Tessera
## Pengalaman pengguna
Tombol **Search** dan `⌘K` / `Ctrl+K` membuka kolom pencarian di tengah bagian atas layar, dengan fokus langsung ke input. Panel ringkas menampilkan pintasan layar saat kolom kosong. Saat pengguna mengetik, panel menyesuaikan tinggi dan menampilkan hasil yang dikelompokkan sebagai **Navigation**, **Orbits**, dan **Snapshots**. Tombol panah memindahkan sorotan, `Enter` membuka hasil, dan `Esc` menutup pencarian. Setiap hasil juga bisa dipilih dengan klik atau sentuhan.
Pola hasil yang muncul saat mengetik dan navigasi papan ketik mengikuti [Spotlight di Mac](https://support.apple.com/en-gb/guide/mac-help/-mchlp1008/mac) dan [pintasan Spotlight](https://support.apple.com/en-gb/guide/mac-help/mh26783/26/mac/26). Gunakan `⌘K` / `Ctrl+K` karena `⌘Space` digunakan Spotlight macOS.
## Keputusan desain
- Gunakan warna gelap dan aksen amber Tessera, kaca tipis pada panel, ikon garis, serta font mono untuk pintasan dan metadata. Tempatkan pemicu di sisi kanan topbar dan pertahankan aksesnya saat topbar beralih ke Big Screen. Di layar sempit, gunakan pemicu ikon berlabel aksesibel dan batasi tinggi daftar terhadap viewport dinamis agar hasil dapat digulir.
- Gunakan `uiSpring` untuk buka/tutup dan `gentleSpring` untuk perubahan tinggi, dengan posisi atas panel tetap. Pertahankan identitas panel dan nilai animasinya ketika target berubah. Perubahan tinggi mengikuti isi dan batas viewport. Saat keluar, panel langsung melepas area klik dan fokus. Mode reduced motion menerapkan target secara langsung, termasuk saat preferensi berubah di tengah animasi. Ikuti [panduan animasi Tessera](../docs/UI.md#animation-guideline).
- Gunakan metadata navigasi yang sama dengan HUDRail dan data orbit/snapshot yang sudah diambil oleh `App`. Cari nama, ID, provider orbit, dan tanggal snapshot yang ditampilkan. Cocokkan tanpa membedakan kapitalisasi, urutkan kecocokan persis lalu awalan lalu substring dalam tiap kelompok, dan batasi tampilan ke delapan hasil dengan akses yang tetap tersedia untuk setiap kategori yang cocok. Untuk kecocokan snapshot setara, tampilkan yang terbaru dulu. Gunakan ID stabil agar polling tidak memindahkan pilihan aktif jika hasilnya masih tersedia.
- Gunakan handler yang sudah ada untuk membuka layar, memilih orbit di Vault, dan membuka Snapshot detail. Outposts dan Restore muncul sebagai tujuan navigasi. Pencarian tahap awal mencakup metadata ringkasan orbit dan snapshot, dengan status jika salah satu sumber masih dimuat atau gagal. Pemilihan hasil membuka tujuan tanpa menjalankan operasi backup atau restore.
- Buat dialog berlabel dengan latar inert dan fokus Tab yang tetap di dalam dialog. Gunakan combobox/listbox dengan `aria-activedescendant`, status hasil, dan tombol tutup. Kembalikan fokus ke pemicu saat dibatalkan atau arahkan ke tujuan saat hasil dibuka. Abaikan tombol navigasi pencarian selama komposisi IME. [Pola combobox WAI-ARIA](https://www.w3.org/WAI/ARIA/apg/patterns/combobox/) · [Pola dialog modal WAI-ARIA](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/)
## Urutan pekerjaan
1. Buka pencarian dan navigasi ke layar yang sudah ada.
2. Temukan dan buka orbit atau snapshot dari data yang sudah tersedia.
3. Selesaikan transisi panel dan verifikasi interaksi di browser.
Kriteria penerimaan, dependensi, dan checkpoint ada di [daftar tugas](search-todo.md).
## Risiko dan mitigasi
| Risiko | Mitigasi |
| --- | --- |
| Escape menutup pencarian dan HUDPanel atau Big Screen sekaligus | Tangani Escape saat pencarian aktif sebelum listener yang ada. Cegah pengulangan tombol ikut menutup lapisan di bawahnya. Uji dari kedua mode. |
| Fokus hilang saat hasil membuka panel atau orbit yang sebelumnya inert | Pindahkan fokus setelah tujuan aktif. Gunakan register atau kontrol Vault yang terlihat di Big Screen, dan heading panel saat membuka snapshot atau konsol. |
| Polling menghapus atau menggeser hasil | Simpan pilihan berdasarkan ID. Gunakan hasil pertama jika pilihan hilang dan abaikan Enter bila daftar kosong. |
| Animasi meloncat saat query berubah cepat atau panel dibuka kembali | Retarget panel yang sama. Uji pembalikan sebelum transisi selesai, resize, dan perubahan preferensi reduced motion saat aplikasi berjalan. |
## Asumsi untuk ditinjau
Pencarian berlaku di seluruh UI, memakai label berbahasa Inggris sesuai antarmuka saat ini, dan memakai data yang sudah tersedia di klien. Tinjau cakupan ini dan urutan pekerjaan sebelum implementasi.

View File

@@ -1,71 +0,0 @@
# Daftar tugas pencarian Tessera
## Tugas 1 — Buka pencarian dan pilih tujuan navigasi
Hubungkan komponen pencarian global ke `App`, dengan entri navigasi yang memakai label dan tujuan yang sama dengan HUDRail.
**Kriteria penerimaan**
- [x] Search dan `⌘K` / `Ctrl+K` membuka panel dari Vault, konsol samping, dan Big Screen. Input langsung menerima fokus.
- [x] Query kosong menampilkan tujuan navigasi. Mengetik menyaringnya, panah atas/bawah memindahkan pilihan, dan Enter, klik, atau sentuhan membuka tujuan yang benar.
- [x] Tab tetap di dalam dialog. Escape, tombol tutup, dan klik di luar mengembalikan fokus. Escape pertama hanya menutup pencarian dan menahan Escape tidak menutup lapisan berikutnya.
**Verifikasi**
- [x] Jalankan `npm run typecheck` dari `web/`. Uji pembukaan, perpindahan fokus, pembatalan, dan pemilihan tujuan di Vault, HUDPanel, serta Big Screen dengan papan ketik dan pointer.
**Dependensi** — Tidak ada.
**Perkiraan lingkup** — M, 4 berkas. `web/src/App.tsx`, `web/src/components/hud/HUDRail.tsx`, `web/src/components/hud/VaultSearch.tsx`, `web/src/index.css`.
## Tugas 2 — Temukan orbit dan snapshot
Tambahkan hasil dari data orbit dan snapshot yang dipakai Vault. Kaitkan pilihan ke alur inspeksi yang sudah tersedia.
**Kriteria penerimaan**
- [x] Hasil muncul saat mengetik, dikelompokkan berdasarkan tipe, dan mengikuti urutan kecocokan di rencana. Nama duplikat bisa dibedakan dengan metadata. Query kosong, tanpa hasil, dan sumber yang belum tersedia punya tampilan yang berbeda.
- [x] Memilih orbit membuka Vault dengan orbit terpilih, termasuk orbit di luar 55 slot awal. Memilih snapshot membuka detail yang benar, termasuk ringkasan dari hub lama tanpa `orbit_id`.
- [x] Papan ketik tetap berfungsi setelah polling memperbarui atau menghapus hasil. Enter tanpa hasil dan selama komposisi IME tidak mengaktifkan tujuan.
**Verifikasi**
- [x] Jalankan `npm run typecheck` dan `npm test` dari `web/`. Tambahkan uji matcher terfokus untuk prioritas, nama duplikat, hasil lintas kategori, dan batas jumlah. Uji pilihan orbit dan snapshot di browser dengan fixture.
**Dependensi** — Tugas 1.
**Perkiraan lingkup** — M, maksimal 5 berkas. `web/src/App.tsx`, `web/src/components/hud/VaultSearch.tsx`, `web/src/lib/vaultSearch.ts`, `web/scripts/search.test.mjs`, `web/package.json`.
## Checkpoint — Pencarian dapat digunakan
- [x] Typecheck, tes web, dan build lulus. Pengguna bisa membuka ketiga jenis hasil dari awal sampai akhir.
- [x] Review cakupan dan perilaku pencarian sebelum menyelesaikan animasi.
## Tugas 3 — Selesaikan animasi dan tata letak
Gunakan spring Tessera untuk transisi panel, serta dokumentasikan pintasan dan cakupan hasil pada panduan UI.
**Kriteria penerimaan**
- [x] Panel masuk dan keluar pada lintasan yang sama. Tinggi daftar menyesuaikan hasil dari posisi visual saat ini, sementara input tetap pada posisi dan fokusnya. Buka kembali sebelum panel selesai menutup tanpa lompatan atau penguncian input.
- [x] Reduced motion meniadakan perjalanan animasi. Di layar sempit dan saat papan ketik virtual terbuka, input dan tombol tutup tetap terjangkau serta daftar dapat digulir tanpa overflow horizontal.
- [x] Saat penutupan dimulai, panel keluar dari urutan fokus dan melepas area klik. Sorotan papan ketik terbaca dan pilihan aktif diumumkan melalui semantik combobox.
**Verifikasi**
- [x] Jalankan `npm run typecheck`, `npm test`, dan `npm run build` dari `web/`. Uji buka-tutup-buka, pengetikan cepat, perubahan preferensi reduced motion, viewport sempit, dan fokus di browser. Periksa nama dialog, combobox, daftar, dan pilihan aktif melalui accessibility tree.
**Dependensi** — Tugas 2.
**Perkiraan lingkup** — M, 3 berkas. `web/src/components/hud/VaultSearch.tsx`, `web/src/index.css`, `docs/UI.md`.
## Checkpoint — Siap ditinjau
- [x] Kriteria seluruh tugas lulus, hasil verifikasi browser tercatat, dan perubahan pada berkas yang sedang dikerjakan pengguna tetap terjaga.
## Hasil verifikasi — 10 November 2026
- `npm run typecheck`, `npm test` (10 tes), `npm run build`, dan `git diff --check` lulus.
- Fixture Chromium dengan 62 orbit menguji kedua pintasan, fokus dan Tab, pembatalan, Escape yang ditahan, orbit di luar 55 slot awal, snapshot tanpa `orbit_id`, polling, IME, dan ketiga jenis tujuan. Fixture mencatat nol permintaan tulis.
- Chromium memverifikasi buka-tutup-buka, pengetikan cepat, perubahan reduced motion, serta nama dialog, combobox, listbox, dan opsi aktif melalui accessibility tree.
- Emulasi sentuhan pada viewport 320 × 240 memverifikasi input, tombol tutup, daftar yang dapat digulir, dan tap pada hasil. Ukuran tersebut menyimulasikan ruang saat keyboard virtual terbuka.

View File

@@ -1,472 +0,0 @@
# Daftar tugas upgrade Tessera dan agent untuk MBU
Lihat [rencana implementasi](plan.md) dan [inventaris paritas](../docs/MBU-BACKUP-PARITY.md). Path pendek `api/`, `db.rs`, `admin.rs`, `state.rs`, dan `scheduler.rs` mengacu pada `crates/tessera-hub/src/`. Nama file baru bersifat perkiraan. Harness fixture PostgreSQL, MySQL, SSH, dan S3 diperluas pada tugas pertama yang memerlukan masing-masing fixture.
## Bukti implementasi
- Fixture lokal dan browser dicatat di [harness MBU](../tests/mbu/README.md). Checklist bertanda selesai merujuk pada pengujian terisolasi.
- T06 menunggu akun OS Teleport yang diizinkan untuk konfirmasi versi dan placement. Inventaris resource dan matriks fixture sudah dicatat.
- T23 telah direkonsiliasi dengan PostgreSQL, MySQL, dan histori SQLite sintetis. Persetujuan dan pengujian sampel arsip MBU asli masih terbuka.
- T24 mencatat hasil rehearsal 10 aplikasi dan drill pemulihan lokal di [runbook cutover](../docs/MBU-CUTOVER.md). Bukti uji paralel, rekonsiliasi delta, drill routing di staging MBU, dan persetujuan operator masih terbuka.
Pada setiap checkpoint, jalankan `rtk cargo test --workspace`, `rtk cargo test -p tessera-store -- --ignored` dengan Restic di PATH, dan `rtk cargo build --workspace`. Untuk perubahan UI, tambahkan `rtk proxy npm --prefix web test`, `rtk proxy npm --prefix web run typecheck`, `rtk proxy npm --prefix web run build`, serta verifikasi browser pada alur yang berubah.
## T01 — Redaksi konfigurasi orbit
Pisahkan representasi internal orbit dari respons publik API dan skema OpenAPI.
**Kriteria penerimaan**
- [x] GET dan POST orbit tidak mengembalikan DSN, password, token, atau referensi rahasia internal.
- [x] Orbit lama tetap dapat dijalankan. Uji kontrak memeriksa respons dengan kredensial sintetis dan alur UI/CLI yang membaca orbit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — Tidak ada.
**Perkiraan lingkup** — M. `api/routes.rs, db.rs`, `web/src/api.ts`, `crates/tessera-cli/src/main.rs`.
## T02 — Antrekan capture manual
Tambahkan job capture persisten yang bisa dibuat dan dibaca operator dengan ID aplikasi dan status.
**Kriteria penerimaan**
- [x] API menyimpan job dan actor. Profil atau outpost tak terdaftar ditolak.
- [x] Restart hub mempertahankan job queued. Migrasi membuka salinan SQLite lama tanpa kehilangan orbit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — Tidak ada.
**Perkiraan lingkup** — M. `api/mod.rs, api/jobs.rs, db.rs`, `crates/tessera-core/src/job.rs`.
## T03 — Klaim job oleh agent
Bangun polling keluar dari agent dengan assignment, lease, heartbeat, dan laporan fase.
**Kriteria penerimaan**
- [x] Token outpost lain dan lease usang tidak bisa klaim atau menulis hasil. Satu aplikasi menjalankan satu job dan dua aplikasi dapat berjalan paralel.
- [x] Lease capture kedaluwarsa dapat dicoba ulang. Uji dua agent dan restart hub di tengah job.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Dua agent fixture berlomba untuk job yang sama. Hanya assignment dan lease aktif yang diterima.
**Dependensi** — T02.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-core/src/job.rs`, `crates/tessera-agent/src/{main,jobs}.rs`.
### Checkpoint setelah T03
- [x] Hub menerima job manual dengan assignment dan lease yang teruji.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T04 — Buat dump PostgreSQL di agent
Pakai ulang provider PostgreSQL untuk profil lokal bertipe dengan rahasia, kebijakan TLS, timeout, dan file staging privat.
**Kriteria penerimaan**
- [x] Fixture PostgreSQL dengan TLS menghasilkan dump yang bisa dibaca dan berisi data yang diharapkan. TLS yang salah dan dump parsial menghasilkan job gagal.
- [x] Rahasia sintetis tidak muncul di argumen proses, respons, atau log. File sementara dibersihkan setelah gagal.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T03.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/postgres.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
## T05 — Publikasikan snapshot database
Hubungkan hasil capture ke upload Restic Wormhole dan katalog berisi metadata engine/format serta ID job.
**Kriteria penerimaan**
- [x] Job manual menghasilkan satu restore point yang bisa diekspor dan dipulihkan di PostgreSQL sementara.
- [x] Putuskan koneksi setelah upload dan setelah commit. Retry mengembalikan snapshot yang sama. Upload parsial dan commit dari outpost lain tidak terpublikasi.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent -p tessera-store` dan `rtk cargo build --workspace`.
- [x] PostgreSQL sementara → agent → Restic → ekspor → restore ke database kedua. Bandingkan skema dan isi.
**Dependensi** — T04.
**Perkiraan lingkup** — M. `api/routes.rs, api/jobs.rs`, `crates/tessera-agent/src/{jobs,main}.rs`, `crates/tessera-store/src/vault.rs`.
### Checkpoint setelah T05
- [x] PostgreSQL langsung menghasilkan satu snapshot meski commit diulang.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T06 — Petakan placement agent MBU
Inventaris read-only dari Teleport untuk pilihan lokasi agent dan buat fixture topologi yang dapat diulang.
**Kriteria penerimaan**
- [ ] Catat jalur direct atau SSH yang tersedia, versi engine dan client, serta kebutuhan izin untuk MAS, FTA, dan Boiler tanpa mencatat rahasia.
- [x] Fixture dapat memodelkan jalur yang tersedia dan jalur yang sengaja terputus.
**Verifikasi**
- [ ] Cocokkan inventaris Teleport dengan matriks fixture dan catat keputusan placement.
**Dependensi** — T05.
**Perkiraan lingkup** — S. `docs/MBU-BACKUP-PARITY.md`, `tests/mbu/README.md`.
## T07 — Capture PostgreSQL lewat bastion
Tambahkan transport tunnel bertipe dengan host key pinning dan port lokal yang terisolasi.
**Kriteria penerimaan**
- [x] Fixture MAS dan FTA menghasilkan snapshot melalui bastion. Host key salah, timeout, dan kehilangan tunnel menggagalkan job serta membersihkan proses.
- [x] Aplikasi capture-only seperti FTA tetap bisa backup tanpa target restore.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T05, T06.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{postgres,ssh}.rs`, `crates/tessera-agent/src/{profiles,jobs}.rs`.
## T08 — Capture MySQL langsung
Tambahkan adapter dump MySQL bertipe, kredensial lokal, dan integrasi metadata snapshot yang sama.
**Kriteria penerimaan**
- [x] Dump fixture berisi view, routine, dan event. Error engine menggagalkan job dan tidak memublikasikan snapshot.
- [x] Uji dump MySQL dengan data utf8mb4 dan kredensial fixture yang tidak muncul di log.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T05, T06.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{lib,mysql}.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
### Checkpoint setelah T08
- [x] Bastion PostgreSQL dan MySQL langsung lulus dengan data fixture.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T09 — Capture MySQL lewat SSH
Jalankan dump melalui SSH yang dipin untuk topologi Boiler dan alirkan hasil ke staging agent.
**Kriteria penerimaan**
- [x] Topologi Boiler menghasilkan snapshot yang dapat diekspor. Host key berubah atau proses remote gagal tidak menghasilkan snapshot.
- [x] Jalur lokal dan remote menghasilkan metadata engine/format yang bisa dibaca dengan kontrak yang sama.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Gunakan fixture MySQL di balik SSH dengan host key benar dan salah. Validasi output serta status terminal.
**Dependensi** — T07, T08.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{mysql,ssh}.rs`, `crates/tessera-agent/src/{profiles,jobs}.rs`.
## T10 — Jadwalkan job capture
Hub membuat job dengan slot jadwal persisten dan zona waktu per profil.
**Kriteria penerimaan**
- [x] Jadwal 02.00 Asia/Jakarta membuat satu job per slot yang jatuh tempo. Restart atau tick ganda tidak membuat duplikat.
- [x] Agent offline mempertahankan job queued. Uji dengan jam fixture untuk jadwal terlewat dan dua aplikasi yang jatuh tempo bersamaan.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — T05.
**Perkiraan lingkup** — M. `scheduler.rs, db.rs, api/jobs.rs`, `crates/tessera-core/src/job.rs`.
## T11 — Sajikan histori dan log job
Sediakan riwayat status dan log fase melalui API operator dengan redaksi dan batas ukuran.
**Kriteria penerimaan**
- [x] Filter aplikasi dan status stabil setelah restart. Job gagal menampilkan fase dan penyebab operasional yang tersanitasi.
- [x] Payload berisi rahasia sintetis, token, dan karakter kontrol tidak bocor ke daftar, detail, atau audit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T03, T05.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-agent/src/jobs.rs`.
### Checkpoint setelah T11
- [x] Tiga jalur capture MBU dapat dijadwalkan dan ditelusuri.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T12 — Pulihkan dari salinan S3
Tambahkan jalur penyimpanan off-host yang dapat diverifikasi dengan pemulihan independen.
**Kriteria penerimaan**
- [x] Snapshot agent tersalin ke lokasi S3 terisolasi dan dapat dipulihkan saat repo utama tidak tersedia.
- [x] Gagal menulis salinan terlihat di status. Retry tidak menduplikasi entri katalog dan kredensial S3 tidak bocor.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-store -p tessera-hub` dan `rtk cargo build --workspace`.
- [x] Putuskan akses repo utama dan pulihkan snapshot hanya dari salinan off-host.
**Dependensi** — T05.
**Perkiraan lingkup** — M. `crates/tessera-store/src/{restic,vault}.rs`, `crates/tessera-hub/src/{state,main}.rs`, `compose.yaml`.
## T13 — Kelola lifecycle arsip
Terapkan retensi berdasarkan umur dan jumlah, serta unduh dan hapus terotorisasi di katalog.
**Kriteria penerimaan**
- [x] Kebijakan 14 hari menyisakan minimal satu per aplikasi. Fallback simpan lima dan retensi GFS lulus uji.
- [x] Unduh mengirim artefak yang benar, penghapusan diaudit, dan snapshot yang masih dipakai job tidak dapat dihapus.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-core -p tessera-store -p tessera-hub` dan `rtk cargo build --workspace`.
**Dependensi** — T05, T12.
**Perkiraan lingkup** — M. `crates/tessera-core/src/decay.rs`, `crates/tessera-store/src/vault.rs`, `api/routes.rs, api/jobs.rs, state.rs`.
### Checkpoint setelah T13
- [x] Katalog lulus pemulihan off-host dan retensi per aplikasi.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T14 — Antrekan restore terotorisasi
Daftarkan target per aplikasi dan buat job restore yang mengikat konfirmasi ke snapshot, target, dan agent.
**Kriteria penerimaan**
- [x] Target asing, capture-only, mismatch engine, dan konfirmasi salah ditolak sebelum lease.
- [x] Snapshot dipin secara persisten selama job. Scope token restore hanya berlaku untuk agent dan job itu.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-core` dan `rtk cargo build --workspace`.
**Dependensi** — T03, T13.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs, api/mod.rs`, `crates/tessera-core/src/{job,reconstitute}.rs`.
## T15 — Kirim payload restore ke target
Beri agent jalur baca terbatas untuk mengambil dan memverifikasi artefak snapshot ke staging privat.
**Kriteria penerimaan**
- [x] Agent yang ditugaskan bisa membaca snapshot yang dipilih. Token capture, snapshot lain, dan lease kedaluwarsa ditolak.
- [x] Artefak rusak atau staging penuh gagal sebelum target tersentuh. Uji dengan checksum yang sengaja salah.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent -p tessera-store` dan `rtk cargo build --workspace`.
**Dependensi** — T14.
**Perkiraan lingkup** — M. `api/jobs.rs`, `crates/tessera-store/src/vault.rs`, `crates/tessera-agent/src/{jobs,http}.rs`.
## T16 — Verifikasi backup pengaman
Agent memverifikasi identitas target dan menyimpan dump pengaman sebelum fase destruktif diizinkan.
**Kriteria penerimaan**
- [x] Verifikasi target menolak endpoint sumber, alias, dan target yang berubah sejak didaftarkan. Job paralel ke target yang sama menunggu.
- [x] Kegagalan backup atau commit pengaman membuat data target tetap utuh. Snapshot pengaman tercatat, dapat dibaca, dan dipin sebelum reset.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Paksa penyimpanan safety backup gagal dan bandingkan data target sebelum serta sesudah job.
**Dependensi** — T15.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`, `crates/tessera-core/src/job.rs`.
### Checkpoint setelah T16
- [x] Restore request, akses artefak, dan safety backup lulus uji negatif.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T17 — Pulihkan PostgreSQL ke target
Tambahkan apply PostgreSQL untuk custom dump dan SQL polos terkompresi dengan reset schema atau recreate database serta SQL pascarestore lokal.
**Kriteria penerimaan**
- [x] Fixture LTI/Manbu, Daily Checklist, dan MAS memverifikasi isi, schema, reset, dan post-restore SQL pada target sementara.
- [x] Uji owner/ACL, transaction_timeout, dan pg_stat_statements dengan fixture lintas versi. Error di luar aturan kompatibilitas tetap terlihat.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T07, T16.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{lib,postgres,postgres_restore}.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
## T18 — Pulihkan MySQL ke target
Tambahkan apply MySQL untuk target lokal atau SSH dengan aturan kompatibilitas per profil.
**Kriteria penerimaan**
- [x] Fixture Boiler staging memverifikasi schema, isi, view, DEFINER, routine, dan event setelah restore.
- [x] Uji dengan izin target terbatas dan kegagalan apply yang dilaporkan bersama ID backup pengaman.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-providers -p tessera-agent` dan `rtk cargo build --workspace`.
**Dependensi** — T09, T16.
**Perkiraan lingkup** — M. `crates/tessera-providers/src/{mysql,mysql_restore,ssh}.rs`, `crates/tessera-agent/src/{jobs,profiles}.rs`.
## T19 — Tangani restore yang terputus
Jadikan transisi ke fase destruktif dan status pemulihan persisten, dengan jalur rekonsiliasi atau restore safety snapshot.
**Kriteria penerimaan**
- [x] Putus koneksi atau restart setelah izin reset menahan target dalam status pemulihan diperlukan. Percobaan lama tidak boleh mulai apply kedua.
- [x] Operator dapat memulihkan dari snapshot pengaman, memverifikasi data target, lalu melepas lock dengan jejak audit.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub -p tessera-agent` dan `rtk cargo build --workspace`.
- [x] Putuskan koneksi tepat setelah reset, restart hub, lalu pulihkan target dari safety snapshot.
**Dependensi** — T17, T18.
**Perkiraan lingkup** — M. `api/jobs.rs, db.rs`, `crates/tessera-core/src/job.rs`, `crates/tessera-agent/src/jobs.rs`.
### Checkpoint setelah T19
- [x] PostgreSQL dan MySQL dipulihkan ke target sementara dan dapat pulih setelah gangguan.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T20 — Masuk ke dashboard sebagai operator
Tambahkan sesi browser ke dashboard dan audit actor dengan proteksi CSRF, tetap dukung token API/CLI.
**Kriteria penerimaan**
- [x] Login/logout, kedaluwarsa sesi, proteksi CSRF, dan identitas audit teruji di browser. Token admin tidak disimpan di browser.
- [x] Hub bertoken tetap menerima CLI yang sah. Browser tanpa sesi tidak bisa membaca atau menjalankan operasi sensitif.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-hub` dan `rtk cargo build --workspace`, ditambah tes/build web dan uji browser.
**Dependensi** — T01.
**Perkiraan lingkup** — M. `admin.rs, api/mod.rs, api/session.rs`, `web/src/App.tsx, web/src/api.ts`.
## T21 — Jalankan backup dari dashboard
Tampilkan aplikasi, snapshot, status dan log job, serta tindakan backup, unduh, dan hapus dari UI.
**Kriteria penerimaan**
- [x] Di browser, pilih aplikasi, jalankan backup, lihat fase/log, unduh artefak yang benar, lalu hapus fixture dengan konfirmasi.
- [x] Filter histori, kondisi kosong, job gagal, dan backup pada aplikasi tanpa target bisa diuji dari UI.
**Verifikasi**
- [x] Jalankan tes dan build web, lalu uji kriteria di browser dengan fixture.
**Dependensi** — T11, T13, T20.
**Perkiraan lingkup** — M. `web/src/{api.ts,App.tsx,components/orbits/OrbitsView.tsx,components/vault/SnapshotSheet.tsx,components/orbits/JobHistory.tsx}`.
## T22 — Jalankan restore dari dashboard
Hubungkan wizard ke target yang diizinkan, konfirmasi, status safety backup, dan hasil pemulihan.
**Kriteria penerimaan**
- [x] Browser dapat memilih snapshot dan target, mengonfirmasi, memantau job, dan melihat ID backup pengaman jika apply gagal.
- [x] Restore ditolak untuk aplikasi capture-only. Jalur ekspor filesystem yang lama tetap berfungsi.
**Verifikasi**
- [x] Jalankan tes dan build web, lalu uji kriteria di browser dengan fixture.
**Dependensi** — T19, T20.
**Perkiraan lingkup** — M. `web/src/api.ts`, `web/src/components/reconstitute/ReconstituteWizard.tsx`, `web/src/components/vault/SnapshotSheet.tsx`, `docs/UI.md`.
### Checkpoint setelah T22
- [x] Operator bisa masuk, backup, dan restore melalui browser.
- [x] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.
## T23 — Rekonsiliasi arsip layanan lama
Tambahkan impor read-only objek SQL lama dan pertahankan akses ke histori operasional yang terkait.
**Kriteria penerimaan**
- [x] Inventaris per aplikasi merekonsiliasi identitas, tanggal, ukuran, dan hitungan. Pengulangan impor tidak membuat duplikat dan histori lama dapat ditelusuri.
- [ ] Sampel arsip PostgreSQL dan MySQL yang disetujui berhasil dipulihkan pada target sementara. Uji retensi tidak menghapus objek dari sumber.
**Verifikasi**
- [x] Jalankan `rtk cargo test -p tessera-cli -p tessera-store` dan `rtk cargo build --workspace`.
**Dependensi** — T12, T13, T19.
**Perkiraan lingkup** — M. `crates/tessera-cli/src/{main,legacy_import}.rs`, `crates/tessera-store/src/vault.rs`, `tests/mbu/README.md`.
## T24 — Buktikan kesiapan peralihan
Jalankan matriks 10 aplikasi secara paralel, dokumentasikan pemulihan off-host dan runbook peralihan/rollback.
**Kriteria penerimaan**
- [ ] Backup manual dan jadwal MBU, pemulihan target sementara, serta skenario failure lulus. Ukur freshness, durasi, ukuran dan kemampuan pemulihan off-host.
- [ ] Rekonsiliasi delta sejak impor dan pastikan kepemilikan job di luar katalog. Operator meninjau hasil, window peralihan, dan kriteria rollback sebelum penggantian domain.
**Verifikasi**
- [ ] Jalankan verifikasi checkpoint dan simpan hasil matriks staging serta uji pemulihan.
- [ ] Jalankan runbook di staging, catat bukti per aplikasi dan hasil drill rollback.
**Dependensi** — T10, T19, T21, T22, T23.
**Perkiraan lingkup** — S. `docs/MBU-BACKUP-PARITY.md`, `docs/MBU-CUTOVER.md`, `tests/mbu/README.md`.
### Checkpoint setelah T24
- [ ] Arsip lama terekonsiliasi dan bukti uji paralel siap ditinjau.
- [ ] Jalankan pemeriksaan checkpoint dan tinjau bukti sebelum lanjut.

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());
}
}

View File

@@ -1,4 +1,4 @@
# MBU backup fixtures # 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. 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.
@@ -7,14 +7,14 @@ rtk proxy npm --prefix web run build
rtk cargo build --workspace rtk cargo build --workspace
rtk cargo test --workspace rtk cargo test --workspace
rtk cargo test -p tessera-store -- --ignored rtk cargo test -p tessera-store -- --ignored
rtk proxy python3 tests/mbu/restic-orbits.py rtk proxy python3 tests/fixtures/restic-orbits.py
rtk proxy python3 tests/mbu/capture-postgres.py rtk proxy python3 tests/fixtures/capture-postgres.py
rtk proxy python3 tests/mbu/capture-mysql.py rtk proxy python3 tests/fixtures/capture-mysql.py
rtk proxy python3 tests/mbu/restore-postgres.py rtk proxy python3 tests/fixtures/restore-postgres.py
rtk proxy python3 tests/mbu/offsite.py rtk proxy python3 tests/fixtures/offsite.py
rtk proxy python3 tests/mbu/browser.py rtk proxy python3 tests/fixtures/browser.py
rtk proxy python3 tests/mbu/legacy-import.py rtk proxy python3 tests/fixtures/legacy-import.py
rtk proxy python3 tests/mbu/matrix.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. - 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.
@@ -27,11 +27,13 @@ rtk proxy python3 tests/mbu/matrix.py
- The legacy import fixture reads compressed SQL archives from S3, restores synthetic samples, and verifies history access and idempotency after local GC. - 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. - 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.
## Placement inventory and fixture mapping ## Fixture mapping
Read-only Teleport inventory on 10 November 2026 showed `odoo-clone`, `production-FTA`, `fta-prod`, `broiler-production`, `broiler-staging` and `mbu-backup-jumphost`. Database inventory reported the Broiler resource `mbu-production` with the MySQL protocol. MAS and FTA had no matching database resource in the approved inventory. The returned metadata had no server-version labels. The approved Machine ID could list resources, but the attempted `devops` OS login returned `unknown user devops` on `odoo-clone`, `production-FTA`, `broiler-production`, and `mbu-backup-jumphost`. Verification of deployed client/server versions, routes and privileges requires an authorized existing OS login on the applicable nodes.
| Case | Fixture | Placement to validate | | Case | Fixture | Placement to validate |
| --- | --- | --- | | --- | --- | --- |
| MAS and FTA | PostgreSQL TLS behind 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. | | Direct PostgreSQL | TLS to a loopback server, mismatched hostname case | Run the agent where it can reach the database with the same TLS policy. |
| Boiler | MySQL behind a 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. | | 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.

View File

@@ -89,8 +89,8 @@ def main():
assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result
continue continue
assert result["status"] == "completed", (name, result) assert result["status"] == "completed", (name, result)
target = root / f"{name}.sql" target = root / "hub" / "exports" / f"{name}.sql"
session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)}) session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": target.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
sql = target.read_text() sql = target.read_text()
assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰")) assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰"))

View File

@@ -125,8 +125,8 @@ def main():
assert failed["snapshot_id"] is None assert failed["snapshot_id"] is None
snapshots = api("snapshots") snapshots = api("snapshots")
assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]} assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]}
dump = root / "backup.dump" dump = root / "hub" / "exports" / "backup.dump"
session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)}) session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": dump.name})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed") wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump) command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump)
restored = command("psql", *pg, "-d", "target_db", "-Atc", restored = command("psql", *pg, "-d", "target_db", "-Atc",
@@ -174,7 +174,7 @@ def main():
}) })
assert "provider_config" not in legacy assert "provider_config" not in legacy
command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture", command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture",
env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin"}, stdout=DEVNULL) env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef"}, stdout=DEVNULL)
assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots")) assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots"))
for log in (hub_log, agent_log): for log in (hub_log, agent_log):
log.seek(0) log.seek(0)

View File

@@ -49,7 +49,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
hub_port = port() hub_port = port()
env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key", env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key",
"TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"), "TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"),
"TESSERA_ADMIN_TOKEN": "fixture-admin", **(settings or {})} "TESSERA_ADMIN_TOKEN": "fixture-admin-token-0123456789abcdef", **(settings or {})}
hub_url = f"http://127.0.0.1:{hub_port}" hub_url = f"http://127.0.0.1:{hub_port}"
log = cleanup.enter_context((root / "hub.log").open("w+")) log = cleanup.enter_context((root / "hub.log").open("w+"))
hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log) hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log)
@@ -57,7 +57,7 @@ def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False
def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None): def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None):
payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None
headers = {"Authorization": "Bearer fixture-admin", "Content-Type": "application/json"} headers = {"Authorization": "Bearer fixture-admin-token-0123456789abcdef", "Content-Type": "application/json"}
if token: if token:
headers["X-Tessera-Upload-Token"] = token headers["X-Tessera-Upload-Token"] = token
headers.update(extra or {}) headers.update(extra or {})

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