Compare commits

..

36 Commits

Author SHA1 Message Date
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
152 changed files with 33173 additions and 1720 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"]

1
.claude/launch.json Normal file
View File

@@ -0,0 +1 @@
{"version":"0.0.1","configurations":[{"name":"web","runtimeExecutable":"npm","runtimeArgs":["--prefix","web","run","dev"],"port":5173}]}

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

@@ -0,0 +1,35 @@
name: ci
on: [push, pull_request]
jobs:
rust:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@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@1.89.0
with: { components: "rustfmt, clippy" }
- uses: Swatinem/rust-cache@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@v4
- uses: EmbarkStudios/cargo-deny-action@v2
- run: cargo install cargo-audit --locked && cargo audit
web:
runs-on: ubuntu-latest
defaults: { run: { working-directory: web } }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@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

2
.serena/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/cache
/project.local.yml

189
.serena/project.yml Normal file
View File

@@ -0,0 +1,189 @@
# the name by which the project can be referenced within Serena/when chatting with the LLM.
project_name: "tessera"
# list of language servers to start when using the LSP backend; choose from:
# ada al angular ansible astro
# bash bsl clojure cpp cpp_ccls
# crystal csharp csharp_omnisharp cue dart
# deno elixir elm erlang fortran
# fsharp gdscript gleam go groovy
# haskell haxe hlsl html java
# json julia julia_fatou kotlin latex
# lean4 lua lua_emmylua luau markdown
# matlab msl nextflow nix ocaml
# pascal perl php php_devsense php_phpactor
# php_phpantom powershell python python_basedpyright python_jedi
# python_pyrefly python_ty qml r rego
# ruby ruby_solargraph rust scala scss
# solidity svelte swift systemverilog terraform
# toml typescript typescript_tsgo typescript_vts vue
# vbnet wolfram yaml zig
# (This list may be outdated; generated with scripts/print_language_list.py;
# For the current list, see values of the LanguageServerId enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py)
# For some languages, there are several alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Angular projects, use angular (subsumes typescript+html; requires `npm install` in the project root)
# - For Astro projects, use astro (subsumes typescript/javascript for .astro projects; requires npm)
# - For Svelte projects, use svelte (subsumes typescript/javascript for .svelte projects; requires npm)
# - For Deno projects, use deno (serves the same .ts/.js files as typescript; requires the deno CLI on PATH)
# - For SCSS / Sass / plain CSS, use scss (some-sass-language-server handles all three)
# - For Free Pascal/Lazarus, use pascal
# - External Python adapters may add further registered IDs; install the adapter package first
# and then use its ID here, for example: example
# Special requirements:
# Some language servers require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple language servers, the first language server that supports a given file will be used for that file.
# The first language server is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
language_servers:
- typescript
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# optional shell command to run before the language backend (LSP or JetBrains) is initialised.
# the command runs in the project root directory and is only executed if the project is trusted
# (see trusted_project_path_patterns in the global configuration).
# serena waits for the command to exit: a non-zero exit code is logged as an error but does not
# abort activation. a per-project timeout (activation_command_timeout, default 180s) is the safety
# backstop for non-terminating commands; on expiry the process is killed and activation continues.
# example: activation_command: "npx nx run-many -t build"
activation_command:
# maximum time in seconds to wait for activation_command to complete before killing it (default 180s).
# must be a positive number.
activation_command_timeout: 180.0
# line ending convention to use when writing source files.
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
line_ending:
# The language backend to use for this project.
# If not set, the global setting from serena_config.yml is used.
# Valid values: LSP, JetBrains
# Note: the backend is fixed at startup. If a project with a different backend
# is activated post-init, an error will be returned.
language_backend:
# The interface through which the agent (LLM) accesses Serena's functionality (overrides the global setting).
# Valid values: tools, REPL (see the global configuration for details); leave empty to use the global setting.
# Note: the interface is fixed at startup. If a project is activated post-init, its setting is not applied.
agent_interface:
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the options.
# The settings are considered only if the project is trusted (see global configuration to define trusted projects).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#language-server-specific-settings
ls_specific_settings: {}
# list of workspace folder paths (LSP backend only).
# These folders will be used to build up Serena's symbol index.
# Paths must be within the project root and should thus be relative to the project root.
# Furthermore, the paths should not be filtered by ignore settings.
# Default setting: The entire project root folder (".") is considered.
# In (large) monorepos, this can be used to index only subfolders of the project root, e.g.
# ls_workspace_folders:
# - "./subproject1"
# - "./subproject2"
ls_workspace_folders:
- "."
# list of additional workspace folder paths for cross-package reference support.
# Paths can be absolute or relative to the project root.
# Each folder is registered as an LSP workspace folder, enabling language servers to discover
# symbols and references across package boundaries, but these folders are not indexed by Serena,
# i.e. the respective symbols will not be found using Serena's symbol search tools.
# Example:
# additional_workspace_folders:
# - ../sibling-package
# - ../shared-lib
ls_additional_workspace_folders: []
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Important: quote patterns that start with `*`, otherwise YAML treats them as aliases.
# Example:
# ignored_paths:
# - "examples/**"
# - ".worktrees/**"
# - "**/bin/**"
# - "**/obj/**"
# Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names (and tool markers) to exclude.
# This extends the existing exclusions (e.g. from the global configuration)
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
excluded_tools: []
# list of tools (and tool markers) to include that would otherwise be disabled (particularly optional tools
# that are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
fixed_tools: []
# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.find_symbol") to exclude from the REPL.
# Add "marker:editing" to exclude all editing functions.
# This extends the existing exclusions (e.g. from the global configuration).
excluded_apis: []
# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.get_diagnostics_for_symbol") to include in the REPL
# that would otherwise be disabled (particularly optional methods, which are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
included_apis: []
# list of mode names that are to be activated by default, overriding the setting in the global configuration.
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# If the setting is undefined/empty, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# Therefore, you can set this to [] if you do not want the default modes defined in the global config to apply
# for this project.
# This setting can, in turn, be overridden by CLI parameters (--mode).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
default_modes:
# list of mode names to be activated additionally for this project, e.g. ["query-projects"]
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
added_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
# time budget (seconds) per tool call for the retrieval of additional symbol information
# such as docstrings or parameter information.
# This overrides the corresponding setting in the global configuration; see the documentation there.
# If null or missing, use the setting from the global configuration.
symbol_info_budget:
# list of regex patterns which, when matched, mark a memory entry as read‑only.
# Extends the list from the global configuration, merging the two lists.
read_only_memory_patterns: []
# list of regex patterns for memories to completely ignore.
# Matching memories will not appear in list_memories or activate_project output
# and cannot be accessed via read_memory or write_memory.
# To access ignored memory files, use the read_file tool on the raw file path.
# Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: []

10
CHANGELOG.md Normal file
View File

@@ -0,0 +1,10 @@
# Changelog
## Unreleased (0.1.0 candidate)
- 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.

1890
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -29,9 +29,9 @@ rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha2 = "=0.10.8"
rusqlite = { version = "=0.31.0", features = ["bundled"] }
rusqlite = { version = "=0.41.1", features = ["bundled"] }
thiserror = "1.0"
tokio = { version = "=1.40.0", features = ["full"] }
tokio = { version = "1.51.6", features = ["full"] }
tokio-cron-scheduler = "0.13"
tower = "0.5"
tower-http = { version = "0.6", features = ["fs", "trace", "cors"] }

View File

@@ -5,7 +5,7 @@ RUN npm ci
COPY web/ ./
RUN npm run build
FROM rust:1.88-bookworm AS rust
FROM rust:1.89-bookworm AS rust
WORKDIR /build
COPY Cargo.toml Cargo.lock* ./
COPY crates ./crates

View File

@@ -18,7 +18,12 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
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.
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`, 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
@@ -32,7 +37,7 @@ Compose publishes **127.0.0.1:8787** only. The process inside the container list
### CLI
```bash
cargo build --release -p tessera-cli
cargo build --release -p tessera-cli # the binary is named `tessera`
export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
./target/release/tessera init
./target/release/tessera orbit nightly --path ./docs
@@ -69,6 +74,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).
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 after changing the file (a reload signal was not enough in testing).
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.
@@ -79,6 +86,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.
## Access model
Browser users sign in with OIDC (or the emergency operator) and receive only the permissions an administrator granted:
`orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download`, globally or per orbit. Everything else is
administrator-only. A person may also be allowed to refresh one staging database from its production source through a
relation grant; they see no other data. Outposts authenticate with their own digest-stored tokens. Production and
staging are separated by explicit, versioned relations, and an overwrite is re-authorised right before it is applied.
## Architecture
See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tessera-store`, `tessera-providers`, `tessera-hub`, `tessera-agent`, `tessera-cli`.
@@ -88,9 +103,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.
- Wormhole pairing codes and upload tokens are stored in SQLite and survive a hub restart. Chunks are written at the given offset. When the bytes cover `total_bytes`, the hub seals them into the vault and deletes the `.part` file. `total_bytes` is required.
- Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent needs `TESSERA_WORMHOLE_CLIENT_CERT` and `TESSERA_WORMHOLE_CLIENT_KEY` for that listener. Configure `TESSERA_WORMHOLE_CA` when the hub certificate uses a private CA.
- PostgreSQL captures still run a full `pg_dump` into a private temporary file. Restic can deduplicate matching bytes in the resulting dump. Allow temporary disk space for one full dump per concurrent capture. The 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).
The release image includes `pg_dump`; a native hub needs it on `PATH`.
- 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

9
SECURITY.md Normal file
View File

@@ -0,0 +1,9 @@
# Security policy
Report vulnerabilities privately to the maintainers (use the repository's private security advisory feature, or the
contact listed on the project page). Do not open a public issue for a vulnerability. Expect an acknowledgement within a
few days.
Supported: the latest release. Tessera holds encrypted backups: keep `TESSERA_VAULT_PASSPHRASE` and the `vault`
directory together, serve the hub over HTTPS outside loopback, and set `TESSERA_TRUSTED_PROXIES` only for proxies you
operate. Hardening notes and the auth design are in `docs/DATABASE-CAPTURE.md` and `docs/auth-endpoint-contract.md`.

View File

@@ -5,6 +5,7 @@ services:
- "127.0.0.1:8787:8787"
environment:
TESSERA_LISTEN: "0.0.0.0:8787"
TESSERA_LOCAL_DEVELOPMENT: "false"
TESSERA_DATA_DIR: /data
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE}
TESSERA_ADMIN_TOKEN:

View File

@@ -3,6 +3,7 @@ name = "tessera-agent"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[[bin]]
name = "tessera-agent"
@@ -23,6 +24,5 @@ base64 = "0.22"
tempfile.workspace = true
sha2.workspace = true
hex.workspace = true
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
rustls-pemfile = "=2.2.0"
rustls = { version = "=0.23.46", default-features = false, features = ["ring", "std"] }
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>>> {
let mut reader =
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
rustls_pemfile::certs(&mut reader)
use rustls::pki_types::{pem::PemObject, CertificateDer};
CertificateDer::pem_file_iter(path)
.with_context(|| format!("open {}", path.display()))?
.collect::<Result<Vec<_>, _>>()
.context("parse certificate")
}
fn load_key(path: &std::path::Path) -> Result<rustls::pki_types::PrivateKeyDer<'static>> {
let mut reader =
BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
rustls_pemfile::private_key(&mut reader)
.context("parse private key")?
.context("no private key in client key file")
use rustls::pki_types::{pem::PemObject, PrivateKeyDer};
PrivateKeyDer::from_pem_file(path).context("parse private key in client key file")
}
#[allow(dead_code)]

View File

@@ -13,7 +13,8 @@ use std::{
time::Duration,
};
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_providers::{MysqlSource, PostgresSource};
@@ -83,9 +84,9 @@ pub async fn run(cli: &Cli, path: &Path) -> Result<()> {
"capture timeout must be positive"
);
anyhow::ensure!(
profiles
.values()
.all(|profile| profile.source.is_some() || !profile.paths.is_empty() || !profile.targets.is_empty()),
profiles.values().all(|profile| profile.source.is_some()
|| !profile.paths.is_empty()
|| !profile.targets.is_empty()),
"application requires a source or at least one restore target"
);
let url = cli
@@ -195,7 +196,11 @@ async fn capture(hub: &Arc<Hub>, lease: &CaptureLease, profile: &Profile) -> Res
}
let identity = match before {
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) =>
{
Some(identity)
@@ -248,39 +253,73 @@ async fn commit_backup(
identity: Option<DatabaseIdentity>,
) -> Result<()> {
let result = tokio::time::timeout(Duration::from_secs(profile.timeout_seconds), async {
let repository = profile.restic_repository.as_deref().context("configure the profile Restic repository")?;
let repository = profile
.restic_repository
.as_deref()
.context("configure the profile Restic repository")?;
let mut command = crate::restic_command(repository)?;
if let Some(path) = &profile.restic_password_file {
command.env_remove("RESTIC_PASSWORD").env_remove("RESTIC_PASSWORD_COMMAND")
command
.env_remove("RESTIC_PASSWORD")
.env_remove("RESTIC_PASSWORD_COMMAND")
.env("RESTIC_PASSWORD_FILE", path);
}
if let Some(path) = &profile.rest_server_password_file {
let password = tokio::fs::read_to_string(path).await.context("read Rest Server password")?;
command.env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string())
.env("RESTIC_REST_PASSWORD", password.trim_end_matches(['\r', '\n']));
let password = tokio::fs::read_to_string(path)
.await
.context("read Rest Server password")?;
command
.env("RESTIC_REST_USERNAME", lease.profile.orbit_id.to_string())
.env(
"RESTIC_REST_PASSWORD",
password.trim_end_matches(['\r', '\n']),
);
}
command.args(["backup", "--json", "--quiet", "--tag", &format!("tessera-{}", lease.job_id)]);
command.args([
"backup",
"--json",
"--quiet",
"--tag",
&format!("tessera-{}", lease.job_id),
]);
let sha256 = if let Some(mut file) = stage {
let (file, hash) = tokio::task::spawn_blocking(move || {
let (_, hash) = digest_file(&mut file)?;
file.seek(SeekFrom::Start(0))?;
Ok::<_, anyhow::Error>((file, hash))
}).await??;
command.args(["--stdin", "--stdin-filename", "payload"]).stdin(Stdio::from(file));
})
.await??;
command
.args(["--stdin", "--stdin-filename", "payload"])
.stdin(Stdio::from(file));
Some(hash)
} else {
command.arg("--").args(&profile.paths);
None
};
let snapshot_id = crate::restic_snapshot(command).await?;
let body = serde_json::to_value(ResticCaptureCommit { lease_id: lease.lease_id, snapshot_id, identity, sha256 })?;
let body = serde_json::to_value(ResticCaptureCommit {
lease_id: lease.lease_id,
snapshot_id,
identity,
sha256,
})?;
for _ in 0..3 {
if hub.post(format!("capture/{}/restic", lease.job_id), body.clone(), None).await.is_ok() {
if hub
.post(
format!("capture/{}/restic", lease.job_id),
body.clone(),
None,
)
.await
.is_ok()
{
return Ok(());
}
}
anyhow::bail!("could not register the Restic snapshot")
}).await;
})
.await;
match result {
Ok(Ok(())) => Ok(()),
failure => {
@@ -320,6 +359,33 @@ impl Hub {
.await?
}
/// Like `post` for a restore report, with the reason for a failure in a header.
pub(super) async fn post_with_reason(
self: &Arc<Self>,
path: String,
body: serde_json::Value,
restore: Uuid,
reason: Option<String>,
) -> Result<String> {
let hub = Arc::clone(self);
tokio::task::spawn_blocking(move || {
let restore = restore.to_string();
let mut headers = vec![
("x-tessera-upload-token", hub.token.as_str()),
("x-tessera-restore-token", restore.as_str()),
];
if let Some(reason) = reason.as_deref() {
headers.push((tessera_core::restore::FAILURE_REASON_HEADER, reason));
}
http::post_json(
&format!("{}/api/v1/wormhole/{path}", hub.url),
&body,
&headers,
)
})
.await?
}
async fn report(
self: &Arc<Self>,
lease: &CaptureLease,

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"]
.as_str()
.context("hub did not register the Restic snapshot")?;
info!(
snapshot,
registered,
"committed Restic backup"
);
info!(snapshot, registered, "committed Restic backup");
Ok(())
}
fn restic_command(repository: &str) -> Result<tokio::process::Command> {
let authority = repository
.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"
);
let mut command = tokio::process::Command::new("restic");
command.env("RESTIC_REPOSITORY", repository)
command
.env("RESTIC_REPOSITORY", repository)
.env_remove("RESTIC_REPOSITORY_FILE")
.stdin(std::process::Stdio::null())
.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> {
let output = command.output().await.context("starting restic (install restic on PATH)")?;
anyhow::ensure!(output.status.success(), "restic backup failed ({})", output.status);
let output = command
.output()
.await
.context("starting restic (install restic on PATH)")?;
anyhow::ensure!(
output.status.success(),
"restic backup failed ({})",
output.status
);
let summary: serde_json::Value = serde_json::from_str(
std::str::from_utf8(&output.stdout)?
.lines()
.last()
.context("missing restic summary")?,
)?;
Ok(summary["snapshot_id"].as_str().context("missing restic snapshot ID")?.to_owned())
Ok(summary["snapshot_id"]
.as_str()
.context("missing restic snapshot ID")?
.to_owned())
}

View File

@@ -117,8 +117,8 @@ async fn run(
.await;
let script = match downloaded {
Ok(Ok(script)) => script,
_ => {
report(hub, lease, RestoreProgress::InvalidPayload).await?;
other => {
report_failed(hub, lease, RestoreProgress::InvalidPayload, why(other)).await?;
return Ok(());
}
};
@@ -144,8 +144,8 @@ async fn run(
.await;
let identity = match verified {
Ok(Ok(identity)) => identity,
_ => {
report(hub, lease, RestoreProgress::WrongTarget).await?;
other => {
report_failed(hub, lease, RestoreProgress::WrongTarget, why(other)).await?;
return Ok(());
}
};
@@ -171,7 +171,7 @@ async fn run(
})
.await;
if !matches!(safety, Ok(Ok(()))) {
report(hub, lease, RestoreProgress::SafetyFailed).await?;
report_failed(hub, lease, RestoreProgress::SafetyFailed, why(safety)).await?;
return Ok(());
}
@@ -182,20 +182,35 @@ async fn run(
Some(lease.token),
)
.await?;
let applied = matches!(
tokio::time::timeout(timeout, target.apply(script)).await,
Ok(Ok(()))
);
report(
hub,
lease,
if applied {
RestoreProgress::Applied
} else {
RestoreProgress::ApplyFailed
},
match tokio::time::timeout(timeout, target.apply(script)).await {
Ok(Ok(())) => report(hub, lease, RestoreProgress::Applied).await,
other => report_failed(hub, lease, RestoreProgress::ApplyFailed, why(other)).await,
}
}
/// Why a step did not succeed, in words: the error chain, or that it ran out of time.
fn why<T>(result: Result<Result<T>, tokio::time::error::Elapsed>) -> String {
match result {
Ok(Ok(_)) => "unknown".into(),
Ok(Err(error)) => format!("{error:#}"),
Err(_) => "timed out".into(),
}
}
async fn report_failed(
hub: &Arc<Hub>,
lease: &RestoreLease,
progress: RestoreProgress,
reason: String,
) -> Result<()> {
hub.post_with_reason(
format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?,
lease.token,
tessera_core::restore::clean_failure_reason(&reason),
)
.await
.await?;
Ok(())
}
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> {

View File

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

View File

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

View File

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

View File

@@ -61,8 +61,13 @@ impl RetentionPolicy {
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum CaptureRetention {
Age { days: u16 },
Count { #[serde(default = "fallback_count")] keep: u16 },
Age {
days: u16,
},
Count {
#[serde(default = "fallback_count")]
keep: u16,
},
}
fn fallback_count() -> u16 {
@@ -90,13 +95,57 @@ pub fn evaluate_capture_retention(
now: DateTime<Utc>,
) -> Vec<Uuid> {
snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id)));
snapshots.into_iter().enumerate().skip(1).filter_map(|(index, snapshot)| {
let expired = match policy {
CaptureRetention::Age { days } => now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days),
CaptureRetention::Count { keep } => index >= usize::from(keep),
};
expired.then_some(snapshot.id)
}).collect()
snapshots
.into_iter()
.enumerate()
.skip(1)
.filter_map(|(index, snapshot)| {
let expired = match policy {
CaptureRetention::Age { days } => {
now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days)
}
CaptureRetention::Count { keep } => index >= usize::from(keep),
};
expired.then_some(snapshot.id)
})
.collect()
}
/// A restore safety copy, for its own retention.
#[derive(Debug, Clone)]
pub struct SafetyRef {
pub id: Uuid,
pub taken_at: DateTime<Utc>,
pub target: String,
}
/// Safety copies kept per restore target regardless of age.
pub const SAFETY_KEEP_PER_TARGET: usize = 3;
/// Safety copies younger than this are always kept, however many there are.
pub const SAFETY_KEEP_DAYS: i64 = 7;
/// Which safety copies to forget. Each target keeps its newest few and everything from the last week, so the
/// newest copy of a target is never forgotten here, and a burst of restores cannot erase the way back from
/// the previous one. (A copy that a restore still depends on is protected separately, by the caller.)
pub fn evaluate_safety_retention(snapshots: Vec<SafetyRef>, now: DateTime<Utc>) -> Vec<Uuid> {
let mut targets: std::collections::BTreeMap<String, Vec<SafetyRef>> = Default::default();
for snapshot in snapshots {
targets
.entry(snapshot.target.clone())
.or_default()
.push(snapshot);
}
let mut forget = Vec::new();
for (_, mut copies) in targets {
copies.sort_unstable_by_key(|s| std::cmp::Reverse((s.taken_at, s.id)));
for (index, copy) in copies.into_iter().enumerate() {
let recent = now.signed_duration_since(copy.taken_at).num_days() < SAFETY_KEEP_DAYS;
if index >= SAFETY_KEEP_PER_TARGET && !recent {
forget.push(copy.id);
}
}
}
forget
}
/// Keep the newest snapshot in each of the most recent occupied UTC periods.
@@ -175,7 +224,10 @@ pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec<SnapshotRef>) ->
let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new();
for s in &snapshots {
let key = (s.taken_at.year(), s.taken_at.month());
if let Some(pos) = months.iter().position(|(y, m, _)| *y == key.0 && *m == key.1) {
if let Some(pos) = months
.iter()
.position(|(y, m, _)| *y == key.0 && *m == key.1)
{
if s.taken_at > months[pos].2.taken_at {
months[pos] = (key.0, key.1, s.clone());
}
@@ -204,14 +256,23 @@ mod tests {
#[test]
fn capture_retention_keeps_one_old_archive_or_the_latest_five() {
let now = Utc::now();
let snapshots: Vec<_> = (0..6).map(|i| SnapshotRef {
id: Uuid::new_v4(),
taken_at: now - Duration::days(15 + i),
}).collect();
assert_eq!(evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now),
snapshots[1..].iter().map(|snap| snap.id).collect::<Vec<_>>());
assert_eq!(evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now),
[snapshots[5].id]);
let snapshots: Vec<_> = (0..6)
.map(|i| SnapshotRef {
id: Uuid::new_v4(),
taken_at: now - Duration::days(15 + i),
})
.collect();
assert_eq!(
evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now),
snapshots[1..]
.iter()
.map(|snap| snap.id)
.collect::<Vec<_>>()
);
assert_eq!(
evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now),
[snapshots[5].id]
);
}
#[test]
@@ -309,4 +370,75 @@ mod tests {
let forget = evaluate_decay(&policy, snaps);
assert_eq!(forget.len(), 3);
}
fn safety(day: u32, target: &str) -> SafetyRef {
SafetyRef {
id: Uuid::new_v4(),
taken_at: Utc.with_ymd_and_hms(2026, 11, day, 4, 0, 0).unwrap(),
target: target.into(),
}
}
#[test]
fn safety_snapshots_keep_the_newest_few_per_target_and_anything_recent() {
let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap();
let old: Vec<_> = (1..=6).map(|d| safety(d, "staging")).collect(); // all older than a week
let recent = safety(28, "staging");
let mut all = old.clone();
all.push(recent.clone());
let forgotten = evaluate_safety_retention(all, now);
// newest three overall (recent, day 6, day 5) stay; days 1..=4 go
assert_eq!(forgotten.len(), 4);
assert!(!forgotten.contains(&recent.id));
assert!(!forgotten.contains(&old[5].id) && !forgotten.contains(&old[4].id));
assert!(old[..4].iter().all(|s| forgotten.contains(&s.id)));
}
#[test]
fn a_recent_safety_snapshot_is_never_forgotten_even_beyond_the_count() {
let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap();
let burst: Vec<_> = (24..=29).map(|d| safety(d, "staging")).collect(); // six in the last week
assert!(evaluate_safety_retention(burst, now).is_empty());
}
#[test]
fn targets_are_counted_separately_and_each_keeps_at_least_its_newest() {
let now = Utc.with_ymd_and_hms(2027, 6, 1, 0, 0, 0).unwrap(); // everything is very old
let all = vec![safety(1, "staging"), safety(2, "staging"), safety(1, "dev")];
let forgotten = evaluate_safety_retention(all.clone(), now);
assert!(
forgotten.is_empty(),
"three or fewer per target are always kept"
);
let many: Vec<_> = (1..=5)
.map(|d| safety(d, "staging"))
.chain([safety(1, "dev")])
.collect();
let forgotten = evaluate_safety_retention(many.clone(), now);
assert_eq!(forgotten.len(), 2);
assert!(
!forgotten.contains(&many[5].id),
"the only snapshot of another target stays"
);
}
#[test]
fn a_manifest_knows_whether_it_is_a_restore_safety_copy() {
let mut manifest = crate::manifest::SnapshotManifest {
snapshot_id: Uuid::nil(),
orbit_id: Uuid::nil(),
orbit_name: "x".into(),
labels: vec!["postgres".into()],
provider: "postgres".into(),
paths: vec![],
restore_hints: serde_json::json!({"job_id": "j"}),
};
assert!(!manifest.is_restore_safety());
manifest.labels = vec!["restore-safety".into()];
assert!(manifest.is_restore_safety());
manifest.labels = vec![];
manifest.restore_hints = serde_json::json!({"safety_for": "job", "target_id": "t"});
assert!(manifest.is_restore_safety());
assert_eq!(manifest.safety_target().as_deref(), Some("t"));
}
}

View File

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

View File

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

View File

@@ -79,6 +79,9 @@ pub struct RestoreJob {
pub safety_snapshot_id: Option<Uuid>,
pub created_at: i64,
pub updated_at: i64,
/// Why the job failed, as the agent reported it (cleaned). Only administrators ever see it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure_reason: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
@@ -95,6 +98,27 @@ pub struct RestoreLease {
pub artifact: RestoreArtifact,
}
/// Header on a restore report that carries the reason for a failure.
pub const FAILURE_REASON_HEADER: &str = "x-tessera-failure-reason";
const FAILURE_REASON_MAX: usize = 300;
/// Make a failure reason safe to store, log and send in a header: printable ASCII on one line, at most 300
/// bytes. Anything else becomes a space (control characters) or `?` (non-ASCII). Empty input gives `None`.
pub fn clean_failure_reason(text: &str) -> Option<String> {
let mapped: String = text
.chars()
.map(|c| match c {
c if c.is_ascii_graphic() => c,
c if c.is_ascii() => ' ',
_ => '?',
})
.collect();
let line = mapped.split_whitespace().collect::<Vec<_>>().join(" ");
let line: String = line.chars().take(FAILURE_REASON_MAX).collect();
let line = line.trim_end().to_string();
(!line.is_empty()).then_some(line)
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RestoreProgress {

View File

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

View File

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

View File

@@ -3,6 +3,7 @@ name = "tessera-hub"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[[bin]]
name = "tessera-hub"
@@ -34,15 +35,23 @@ uuid.workspace = true
hex.workspace = true
sha2.workspace = true
base64 = "0.22"
async-compression = { version = "=0.4.36", default-features = false, features = ["tokio", "gzip"] }
futures-core = "0.3"
rustix = { version = "=1.1.6", default-features = false, features = ["fs", "std"] }
governor = { version = "=0.10.4", default-features = false, features = ["std"] }
openidconnect = { version = "=4.1.0", default-features = false, features = ["reqwest", "rustls-tls"] }
tempfile.workspace = true
indexmap = "=2.2.6"
hyper = { version = "=1.12.0", features = ["server", "http1"] }
hyper-util = { version = "=0.1.21", features = ["tokio"] }
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
rustls-pemfile = "=2.2.0"
rustls = { version = "=0.23.46", default-features = false, features = ["ring", "std"] }
tokio-rustls = "=0.26.2"
tower = { workspace = true }
[dev-dependencies]
rcgen = "=0.13.2"
wiremock = "=0.6.5"
futures-util = "0.3"
rsa = { version = "=0.9.10", features = ["sha2"] }
hmac.workspace = true
tokio.workspace = true

View File

@@ -1,24 +1,69 @@
use axum::http::{HeaderMap, StatusCode};
use std::net::SocketAddr;
#[derive(Clone, Debug)]
#[derive(Clone, Debug, Default)]
pub struct AdminGate {
pub token: Option<String>,
/// Unix time after which the shared admin token is refused. The token is a
/// transition aid for CLI/automation, not a permanent credential.
pub token_expires_at: Option<i64>,
pub local_development: bool,
}
impl AdminGate {
pub fn from_env() -> Self {
pub fn from_env() -> anyhow::Result<Self> {
let token = std::env::var("TESSERA_ADMIN_TOKEN")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty());
Self { token }
let local_development = match std::env::var("TESSERA_LOCAL_DEVELOPMENT").as_deref() {
Ok("1" | "true") => true,
Ok("0" | "false" | "") | Err(std::env::VarError::NotPresent) => false,
_ => anyhow::bail!("TESSERA_LOCAL_DEVELOPMENT must be true, false, 1 or 0"),
};
let token_expires_at = match std::env::var("TESSERA_ADMIN_TOKEN_EXPIRES")
.ok()
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
{
None => None,
Some(value) => Some(parse_end_date(&value)?),
};
Ok(Self {
token,
token_expires_at,
local_development,
})
}
pub fn validate_listener(&self, addr: SocketAddr) -> anyhow::Result<()> {
anyhow::ensure!(!self.local_development || addr.ip().is_loopback(),
"TESSERA_LOCAL_DEVELOPMENT requires a loopback listener; never expose it through a proxy");
Ok(())
}
/// The shared admin token is configured and not past its end date.
pub fn token_active(&self) -> bool {
self.token.is_some() && !self.token_expired(chrono::Utc::now().timestamp())
}
pub fn token_expired(&self, now: i64) -> bool {
self.token_expires_at.is_some_and(|end| now >= end)
}
pub fn log_policy(&self) {
if 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!(
"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 {
tracing::info!(
@@ -30,6 +75,9 @@ impl AdminGate {
pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> {
let presented = presented_token(headers);
match &self.token {
Some(_) if self.token_expired(chrono::Utc::now().timestamp()) => {
Err(StatusCode::UNAUTHORIZED)
}
Some(expected) => {
if presented.is_some_and(|value| tokens_match(expected, value)) {
Ok(())
@@ -37,7 +85,15 @@ impl AdminGate {
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),
}
}
@@ -65,6 +121,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 {
let expected = expected.as_bytes();
let presented = presented.as_bytes();
@@ -86,15 +153,19 @@ mod tests {
}
#[test]
fn loopback_without_a_token_is_the_only_open_path() {
let gate = AdminGate { token: None };
fn loopback_without_credentials_is_denied_even_behind_a_local_proxy() {
let gate = AdminGate {
token: None,
local_development: false,
..Default::default()
};
let headers = HeaderMap::new();
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_ok());
.is_err());
assert!(gate
.authorize(peer(IpAddr::V6(Ipv6Addr::LOCALHOST)), &headers)
.is_ok());
.is_err());
assert!(gate
.authorize(peer(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 4))), &headers)
.is_err());
@@ -104,6 +175,8 @@ mod tests {
fn a_configured_token_is_required_on_loopback() {
let gate = AdminGate {
token: Some("secret-token".into()),
local_development: false,
..Default::default()
};
let mut headers = HeaderMap::new();
assert!(gate
@@ -132,38 +205,114 @@ mod tests {
.authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers)
.is_err());
}
#[test]
fn development_is_explicit_loopback_only_and_rejects_forwarded_requests() {
let gate = AdminGate {
token: None,
local_development: true,
..Default::default()
};
for addr in ["127.0.0.1:8787", "[::1]:8787"] {
assert!(gate.validate_listener(addr.parse().unwrap()).is_ok());
assert!(gate
.authorize(addr.parse().unwrap(), &HeaderMap::new())
.is_ok());
}
for addr in ["0.0.0.0:8787", "[::]:8787", "192.0.2.1:8787"] {
assert!(gate.validate_listener(addr.parse().unwrap()).is_err());
assert!(gate
.authorize(addr.parse().unwrap(), &HeaderMap::new())
.is_err());
}
for name in [
"forwarded",
"x-forwarded-for",
"x-forwarded-host",
"x-forwarded-proto",
] {
let mut headers = HeaderMap::new();
headers.insert(name, HeaderValue::from_static("synthetic-proxy"));
assert!(gate
.authorize("127.0.0.1:8787".parse().unwrap(), &headers)
.is_err());
}
}
}
/// Issuer of the break-glass operator row. It is not an `https://` URL, so no
/// OIDC provider can ever produce an identity that maps onto it.
pub const EMERGENCY_ISSUER: &str = "local:emergency";
#[derive(Clone)]
pub struct SessionGate {
config: Option<std::sync::Arc<OperatorConfig>>,
state: std::sync::Arc<std::sync::Mutex<SessionState>>,
}
#[derive(Default)]
struct SessionState {
sessions: std::collections::HashMap<uuid::Uuid, BrowserSession>,
attempts: std::collections::VecDeque<std::time::Instant>,
db: crate::db::Db,
/// Fingerprint of the OIDC configuration (issuer, client, admin mapping).
/// OIDC sessions only count while the same configuration is active.
oidc_fp: Option<String>,
}
struct OperatorConfig {
name: String,
password_hash: String,
/// Sessions are bound to this value, so unsetting or rotating the operator
/// hash invalidates every emergency session even though they persist.
fingerprint: String,
}
#[derive(Clone)]
pub struct BrowserSession {
pub id: uuid::Uuid,
pub csrf: uuid::Uuid,
pub csrf: String,
pub actor: String,
expires: std::time::Instant,
/// Read by per-user revoke and the OIDC login path (M3/M5).
#[allow(dead_code)]
pub user_id: String,
pub auth_method: String,
/// May use the management API. A signed-in user without a grant is `false`.
pub admin: bool,
pub groups: Vec<String>,
pub expires_at: i64,
}
impl BrowserSession {
pub fn subject(&self) -> crate::auth::Subject {
crate::auth::Subject {
user_id: Some(self.user_id.clone()),
groups: self.groups.clone(),
admin: self.admin,
}
}
/// Audit identity. Never derived from IdP-supplied names: OIDC users are
/// identified by their stable user id, so a username of "operator" cannot
/// be mistaken for the emergency account.
pub fn principal(&self) -> crate::auth::Principal {
match self.auth_method.as_str() {
"oidc" => crate::auth::Principal::Oidc(self.user_id.clone()),
_ => crate::auth::Principal::Emergency(self.actor.clone()),
}
}
}
fn fingerprint(password_hash: &str) -> String {
use sha2::{Digest, Sha256};
hex::encode(Sha256::digest(format!(
"tessera-operator-credential-v1:{password_hash}"
)))
}
fn unix_now() -> i64 {
chrono::Utc::now().timestamp()
}
impl SessionGate {
pub const COOKIE: &str = "__Host-tessera-session";
pub const DURATION: std::time::Duration = std::time::Duration::from_secs(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") {
Ok(password_hash) => {
let name =
@@ -182,6 +331,7 @@ impl SessionGate {
"operator password requires Argon2id"
);
Some(std::sync::Arc::new(OperatorConfig {
fingerprint: fingerprint(&password_hash),
name,
password_hash,
}))
@@ -191,60 +341,152 @@ impl SessionGate {
};
Ok(Self {
config,
state: Default::default(),
db,
oidc_fp,
})
}
/// Any browser login method is configured (emergency password and/or OIDC).
pub fn enabled(&self) -> bool {
self.config.is_some() || self.oidc_fp.is_some()
}
/// The emergency password form is available.
pub fn password_enabled(&self) -> bool {
self.config.is_some()
}
pub fn active(&self, headers: &HeaderMap) -> Option<BrowserSession> {
self.active_at(headers, unix_now())
}
pub(crate) fn active_at(&self, headers: &HeaderMap, now: i64) -> Option<BrowserSession> {
let id = cookie_id(headers)?;
let mut state = self.state.lock().unwrap();
state
.sessions
.retain(|_, session| session.expires > std::time::Instant::now());
state.sessions.get(&id).cloned()
let stored = match self.db.lookup_session(&id.to_string(), now) {
Ok(found) => found?,
Err(error) => {
tracing::error!("session lookup failed: {error:#}");
return None;
}
};
// Sessions only count while the credential/configuration that created
// them is still the active one, so unsetting or rotating either revokes them.
let expected = match stored.auth_method.as_str() {
"password" => self
.config
.as_ref()
.map(|config| config.fingerprint.as_str()),
"oidc" => self.oidc_fp.as_deref(),
_ => None,
}?;
if stored.credential_fp.as_deref() != Some(expected) {
return None;
}
Some(BrowserSession {
id,
csrf: crate::db::sessions::csrf_token(&id.to_string()),
actor: stored.display_name,
user_id: stored.user_id,
auth_method: stored.auth_method,
admin: stored.admin,
groups: stored.groups,
expires_at: stored.expires_at,
})
}
pub fn login(&self, headers: &HeaderMap, password: &str) -> Result<BrowserSession, StatusCode> {
use argon2::PasswordVerifier;
let config = self.config.as_ref().ok_or(StatusCode::NOT_FOUND)?;
{
let 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)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
argon2::Argon2::default()
.verify_password(password.as_bytes(), &hash)
.map_err(|_| StatusCode::UNAUTHORIZED)?;
if let Some(id) = cookie_id(headers) {
self.remove(id);
}
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 internal = |error: anyhow::Error| {
tracing::error!("session create failed: {error:#}");
StatusCode::INTERNAL_SERVER_ERROR
};
let mut state = self.state.lock().unwrap();
state
.sessions
.retain(|_, session| session.expires > std::time::Instant::now());
state.sessions.insert(session.id, session.clone());
Ok(session)
// A new ID on every login: a pre-existing cookie never survives (fixation).
if let Some(old) = cookie_id(headers) {
self.remove(old);
}
let now = unix_now();
let user_id = self
.db
.upsert_user(EMERGENCY_ISSUER, &config.name, &config.name, now)
.map_err(internal)?;
let id = uuid::Uuid::new_v4();
let created = self
.db
.create_session(
&id.to_string(),
&user_id,
"password",
Some(&config.fingerprint),
true,
&[],
now,
)
.map_err(internal)?;
if !created {
// Inactive user row: the break-glass account has been disabled.
return Err(StatusCode::UNAUTHORIZED);
}
Ok(BrowserSession {
id,
csrf: crate::db::sessions::csrf_token(&id.to_string()),
actor: config.name.clone(),
user_id,
auth_method: "password".into(),
admin: true,
groups: vec![],
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
})
}
/// Start an OIDC-backed session for a verified identity. The caller has
/// already validated the ID token; `admin` comes from the configured mapping.
pub fn create_oidc(
&self,
user_id: &str,
display_name: &str,
admin: bool,
groups: &[String],
now: i64,
) -> anyhow::Result<BrowserSession> {
let fp = self
.oidc_fp
.as_deref()
.ok_or_else(|| anyhow::anyhow!("OIDC is not configured"))?;
let id = uuid::Uuid::new_v4();
anyhow::ensure!(
self.db.create_session(
&id.to_string(),
user_id,
"oidc",
Some(fp),
admin,
groups,
now
)?,
"user is disabled"
);
Ok(BrowserSession {
id,
csrf: crate::db::sessions::csrf_token(&id.to_string()),
actor: display_name.to_string(),
user_id: user_id.to_string(),
auth_method: "oidc".into(),
admin,
groups: groups.to_vec(),
expires_at: now + crate::db::sessions::ABSOLUTE_SECS,
})
}
pub fn remove(&self, id: uuid::Uuid) {
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 +524,204 @@ pub fn print_operator_hash() -> anyhow::Result<()> {
#[cfg(test)]
impl SessionGate {
pub fn fixture() -> Self {
pub fn fixture(db: crate::db::Db) -> Self {
use argon2::password_hash::{PasswordHasher, SaltString};
let salt = SaltString::encode_b64(b"synthetic-fixture").unwrap();
let password_hash = argon2::Argon2::default()
.hash_password(b"fixture-operator-password", &salt)
.unwrap()
.to_string();
Self::with_hash(db, "fixture-operator", password_hash)
}
pub fn with_hash(db: crate::db::Db, name: &str, password_hash: String) -> Self {
Self {
config: Some(std::sync::Arc::new(OperatorConfig {
name: "fixture-operator".into(),
name: name.into(),
fingerprint: fingerprint(&password_hash),
password_hash,
})),
state: Default::default(),
db,
oidc_fp: None,
}
}
pub fn expire(&self) {
for session in self.state.lock().unwrap().sessions.values_mut() {
session.expires = std::time::Instant::now();
/// Same database, no operator configured (hash unset after a restart).
pub fn without_operator(db: crate::db::Db) -> Self {
Self {
config: None,
db,
oidc_fp: None,
}
}
pub fn with_oidc(mut self, fingerprint: &str) -> Self {
self.oidc_fp = Some(fingerprint.into());
self
}
pub fn expire(&self) {
self.db.expire_all_sessions();
}
}
#[cfg(test)]
mod session_gate_tests {
use super::*;
use axum::http::HeaderValue;
fn hash(password: &str, salt: &[u8]) -> String {
use argon2::password_hash::{PasswordHasher, SaltString};
argon2::Argon2::default()
.hash_password(password.as_bytes(), &SaltString::encode_b64(salt).unwrap())
.unwrap()
.to_string()
}
fn cookie(session: &BrowserSession) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
axum::http::header::COOKIE,
HeaderValue::from_str(&format!("{}={}", SessionGate::COOKIE, session.id)).unwrap(),
);
headers
}
async fn db() -> (tempfile::TempDir, crate::db::Db) {
let dir = tempfile::tempdir().unwrap();
let db = crate::db::Db::connect(&dir.path().join("t.db"))
.await
.unwrap();
db.migrate().await.unwrap();
(dir, db)
}
#[tokio::test]
async fn a_session_outlives_a_restart_only_with_the_same_operator_credential() {
let (_dir, db) = db().await;
let first = SessionGate::with_hash(
db.clone(),
"ops",
hash("correct-horse-battery", b"salt-number-one"),
);
let session = first
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
// restart with the same credential: still valid
let restarted = SessionGate::with_hash(
db.clone(),
"ops",
hash("correct-horse-battery", b"salt-number-one"),
);
assert!(restarted.active(&cookie(&session)).is_some());
// hash rotated after a suspected compromise: old cookie is dead
let rotated = SessionGate::with_hash(
db.clone(),
"ops",
hash("another-long-password", b"salt-number-two"),
);
assert!(rotated.active(&cookie(&session)).is_none());
// emergency login disabled by unsetting the hash: old cookie is dead
assert!(SessionGate::without_operator(db.clone())
.active(&cookie(&session))
.is_none());
// and it comes back only if the exact credential is configured again
assert!(restarted.active(&cookie(&session)).is_some());
}
#[tokio::test]
async fn login_replaces_a_presented_session_id() {
let (_dir, db) = db().await;
let gate =
SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one"));
let old = gate
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
let new = gate.login(&cookie(&old), "correct-horse-battery").unwrap();
assert_ne!(old.id, new.id);
assert!(gate.active(&cookie(&old)).is_none());
assert!(gate.active(&cookie(&new)).is_some());
assert_eq!(
old.user_id, new.user_id,
"same break-glass user row across logins"
);
}
#[tokio::test]
async fn absolute_expiry_and_user_revoke_apply_to_the_gate() {
let (_dir, db) = db().await;
let gate = SessionGate::with_hash(
db.clone(),
"ops",
hash("correct-horse-battery", b"salt-number-one"),
);
let session = gate
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
let now = unix_now();
assert!(gate.active_at(&cookie(&session), now + 60).is_some());
assert!(gate
.active_at(&cookie(&session), now + crate::db::sessions::ABSOLUTE_SECS)
.is_none());
assert_eq!(db.revoke_user_sessions(&session.user_id).unwrap(), 1);
assert!(gate.active(&cookie(&session)).is_none());
assert!(gate
.login(&HeaderMap::new(), "correct-horse-battery")
.is_ok());
}
#[tokio::test]
async fn the_csrf_token_is_stable_for_a_session_and_not_the_cookie() {
let (_dir, db) = db().await;
let gate =
SessionGate::with_hash(db, "ops", hash("correct-horse-battery", b"salt-number-one"));
let session = gate
.login(&HeaderMap::new(), "correct-horse-battery")
.unwrap();
let again = gate.active(&cookie(&session)).unwrap();
assert_eq!(session.csrf, again.csrf);
assert!(!session.csrf.contains(&session.id.to_string()));
}
#[tokio::test]
async fn oidc_sessions_end_when_the_oidc_configuration_changes_or_is_removed() {
let (_dir, db) = db().await;
let user = db
.upsert_user("https://idp.example", "alice", "Alice", unix_now())
.unwrap();
let gate = SessionGate::without_operator(db.clone()).with_oidc("fp-a");
let session = gate
.create_oidc(&user, "Alice", true, &[], unix_now())
.unwrap();
assert_eq!(session.principal().fields().0, format!("oidc:{user}"));
assert!(gate.active(&cookie(&session)).is_some());
// admin mapping changed (different fingerprint) or OIDC switched off: dead
assert!(SessionGate::without_operator(db.clone())
.with_oidc("fp-b")
.active(&cookie(&session))
.is_none());
assert!(SessionGate::without_operator(db.clone())
.active(&cookie(&session))
.is_none());
// configuration restored: the same session is valid again
assert!(SessionGate::without_operator(db)
.with_oidc("fp-a")
.active(&cookie(&session))
.is_some());
}
#[tokio::test]
async fn an_oidc_display_name_never_becomes_the_emergency_principal() {
let (_dir, db) = db().await;
let user = db
.upsert_user("https://idp.example", "mallory", "operator", unix_now())
.unwrap();
let session = SessionGate::without_operator(db)
.with_oidc("fp")
.create_oidc(&user, "operator", false, &[], unix_now())
.unwrap();
let (id, kind, method) = session.principal().fields();
assert_eq!((kind, method), ("user", "oidc"));
assert!(id.starts_with("oidc:") && !id.contains("emergency"));
}
}

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,122 @@
//! 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")
.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);
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")] {
let mut request = Request::builder()
.uri(&path)
.extension(ConnectInfo("127.0.0.1:9000".parse::<SocketAddr>().unwrap()));
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")
.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 async_compression::tokio::bufread::GzipEncoder;
use axum::body::Bytes;
use axum::{
body::Body,
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
http::{header, HeaderMap, HeaderValue, Method, StatusCode},
response::Response,
routing::get,
Router,
};
use futures_core::Stream;
use std::net::SocketAddr;
use std::pin::Pin;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio_util::io::ReaderStream;
use uuid::Uuid;
/// Frames sent to the client: small and bounded, whatever the size of the snapshot.
const CHUNK: usize = 64 * 1024;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/snapshots/:id", axum::routing::delete(delete))
.route("/api/v1/snapshots/:id/download", get(download))
}
/// Download a snapshot as a file. The order matters: authenticate, find the snapshot, check the
/// permission on its orbit, and only then admit the export, so a caller who may not download can
/// never use up the export slots or disk.
async fn download(
method: Method,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
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
.vault
.read()
@@ -33,38 +51,127 @@ async fn download(
.map_err(internal)?
.filter(|snapshot| snapshot.manifest.provider != "legacy-history")
.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 size = state
state
.export_snapshot(id, path.clone())
.await
.map_err(internal)?;
let file = tokio::fs::File::open(path).await.map_err(internal)?;
let extension = match snapshot
let mut file = tokio::fs::File::open(&path).await.map_err(internal)?;
let size = file.metadata().await.map_err(internal)?.len();
let mut head = vec![0u8; 512];
let read = file.read(&mut head).await.map_err(internal)?;
head.truncate(read);
file.seek(std::io::SeekFrom::Start(0))
.await
.map_err(internal)?;
let plan = exports::plan(&snapshot.manifest.restore_hints, &head);
// The profile's schedule zone makes the time in the name match the one people see in their schedule.
let application = snapshot
.manifest
.restore_hints
.get("format")
.and_then(|format| format.as_str())
{
Some("plain") => "sql",
Some("sql_gzip") => "sql.gz",
Some("sqlite") => "sqlite",
Some("tar") => "tar",
_ => "dump",
.get("application_id")
.and_then(|v| v.as_str())
.and_then(|v| Uuid::parse_str(v).ok());
let zone = application.and_then(|application| {
state
.db
.capture_profiles()
.ok()?
.into_iter()
.find(|p| p.application_id == application)?
.schedule
.map(|s| s.timezone)
});
let orbit_name = state
.db
.orbit_names()
.ok()
.and_then(|names| names.get(&snapshot.manifest.orbit_id).cloned())
.unwrap_or_else(|| snapshot.manifest.orbit_name.clone());
let file_name = exports::download_name(
&orbit_name,
snapshot.taken_at,
zone.as_deref(),
snapshot
.manifest
.restore_hints
.get("engine")
.and_then(|v| v.as_str()),
id,
plan.extension,
);
audit(AuditAction::ExportReady, AuditOutcome::Succeeded)?;
let reader = tokio::io::BufReader::with_capacity(CHUNK, file);
let stream: Pin<Box<dyn Stream<Item = std::io::Result<Bytes>> + Send>> = if plan.compress {
Box::pin(ReaderStream::with_capacity(GzipEncoder::new(reader), CHUNK))
} else {
Box::pin(ReaderStream::with_capacity(reader, CHUNK))
};
Ok((
[
(header::CONTENT_TYPE, "application/octet-stream".to_owned()),
(
header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{id}.{extension}\""),
),
(header::CONTENT_LENGTH, size.to_string()),
(header::CACHE_CONTROL, "no-store".to_owned()),
],
Body::from_stream(ReaderStream::new(file)),
)
.into_response())
let body = Guarded::new(
stream,
permit,
staging,
state.db.clone(),
actor.principal.clone(),
id,
actor.request_id,
);
let mut response = Response::new(Body::from_stream(body));
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static(plan.content_type),
);
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(&exports::content_disposition(&file_name)).map_err(internal)?,
);
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
);
// The exact size is only known when the bytes are sent as they are. Never `Content-Encoding`: this
// is the file itself, and a browser must not unpack it.
if !plan.compress {
headers.insert(header::CONTENT_LENGTH, HeaderValue::from(size));
}
Ok(response)
}
async fn delete(
@@ -73,14 +180,19 @@ async fn delete(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> 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;
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);
}
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);
}
state

View File

@@ -0,0 +1,584 @@
//! 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")
.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));
}

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")
.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 axum::{
body::{Body, HttpBody},
@@ -11,7 +12,8 @@ use base64::Engine;
use sha2::{Digest, Sha256};
use std::{net::SocketAddr, pin::Pin, time::Duration};
use tessera_core::job::{
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport, ResticCaptureCommit,
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport,
ResticCaptureCommit,
};
use tessera_core::{restore::DatabaseIdentity, SnapshotManifest};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
@@ -23,6 +25,10 @@ pub(super) fn routes() -> Router<HubState> {
"/api/v1/capture-profiles",
get(profiles).post(register_profile),
)
.route(
"/api/v1/capture-profiles/:id",
axum::routing::put(update_profile),
)
.route("/api/v1/capture-profiles/:id/jobs", post(enqueue))
.route("/api/v1/capture-jobs", get(history))
.route("/api/v1/capture-jobs/:id", get(job))
@@ -38,8 +44,15 @@ async fn profiles(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state.db.capture_profiles().map(Json).map_err(internal)
let actor = authenticate(&state, peer, &headers, false)?;
let visible = super::gate::visible(&state, &actor, Permission::OrbitRead)?;
let profiles = state.db.capture_profiles().map_err(internal)?;
Ok(Json(
profiles
.into_iter()
.filter(|profile| visible.contains(profile.orbit_id))
.collect(),
))
}
async fn register_profile(
@@ -48,7 +61,7 @@ async fn register_profile(
headers: HeaderMap,
Json(profile): Json<CaptureProfile>,
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
if profile
.retention
.is_some_and(|retention| !retention.is_valid())
@@ -77,16 +90,92 @@ async fn register_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(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> 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
.db
.enqueue_capture(id, &actor.name, now())
.enqueue_capture(id, &actor.id(), now())
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok((StatusCode::ACCEPTED, Json(job)))
@@ -105,7 +194,17 @@ async fn history(
headers: HeaderMap,
Query(filter): Query<JobFilter>,
) -> 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
.status
.as_deref()
@@ -119,24 +218,40 @@ async fn history(
filter.application_id,
filter.status.as_deref(),
filter.limit.unwrap_or(50).clamp(1, 200),
visible.restriction().as_deref(),
)
.map(Json)
.map_err(internal)
}
/// A capture job, if the caller may read its orbit; otherwise 404.
fn job_in_scope(
state: &HubState,
actor: &super::routes::OperatorActor,
id: Uuid,
) -> Result<CaptureJob, StatusCode> {
let job = state.db.capture_job(id).map_err(internal)?;
match job {
Some(job) => {
super::gate::scoped(state, actor, Permission::OrbitRead, job.profile.orbit_id)?;
Ok(job)
}
None => {
super::gate::admin_only(state, actor).map_err(|_| StatusCode::NOT_FOUND)?;
Err(StatusCode::NOT_FOUND)
}
}
}
async fn events(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state
.db
.capture_job(id)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
state.db.capture_events(id).map(Json).map_err(internal)
let actor = authenticate(&state, peer, &headers, false)?;
let job = job_in_scope(&state, &actor, id)?;
state.db.capture_events(job.id).map(Json).map_err(internal)
}
async fn job(
@@ -145,13 +260,8 @@ async fn job(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<CaptureJob>, StatusCode> {
require_admin(&state, peer, &headers)?;
state
.db
.capture_job(id)
.map_err(internal)?
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
let actor = authenticate(&state, peer, &headers, false)?;
job_in_scope(&state, &actor, id).map(Json)
}
async fn claim(
@@ -160,10 +270,18 @@ async fn claim(
Path(application): Path<Uuid>,
) -> Result<Json<Option<CaptureLease>>, StatusCode> {
let outpost = outpost(&state, &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 {
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))
}
@@ -201,8 +319,16 @@ async fn upload(
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if job.profile.format == CaptureFormat::Filesystem
|| state.db.restic_required(job.profile.orbit_id).map_err(internal)?
|| state.vault.read().await.outpost_repository_configured(job.profile.orbit_id).map_err(internal)?
|| state
.db
.restic_required(job.profile.orbit_id)
.map_err(internal)?
|| state
.vault
.read()
.await
.outpost_repository_configured(job.profile.orbit_id)
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
@@ -214,7 +340,12 @@ async fn upload(
.map_err(|_| StatusCode::BAD_REQUEST)?;
let identity: DatabaseIdentity =
serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?;
if !job.profile.format.engine().is_some_and(|engine| identity.valid(engine)) {
if !job
.profile
.format
.engine()
.is_some_and(|engine| identity.valid(engine))
{
return Err(StatusCode::BAD_REQUEST);
}
Ok(identity)
@@ -275,16 +406,23 @@ async fn commit_restic(
Json(commit): Json<ResticCaptureCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?;
let job = state.db.capture_upload(outpost, id, commit.lease_id, now())
.map_err(internal)?.ok_or(StatusCode::CONFLICT)?;
let job = state
.db
.capture_upload(outpost, id, commit.lease_id, now())
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if let Some(snapshot) = job.snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
}
let engine = job.profile.format.engine();
if commit.identity.as_ref().is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine)))
|| (engine.is_some() && !commit.sha256.as_ref().is_some_and(|hash| {
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
}))
if commit
.identity
.as_ref()
.is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine)))
|| (engine.is_some()
&& !commit.sha256.as_ref().is_some_and(|hash| {
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
}))
|| (engine.is_none() && commit.sha256.is_some())
{
return Err(StatusCode::BAD_REQUEST);
@@ -302,7 +440,11 @@ async fn commit_restic(
}
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() {
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
}
@@ -408,10 +550,38 @@ pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a
}
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
let result = authenticate_outpost(state, headers);
let (actor, resource, outcome) = match result {
Ok(id) => (
Principal::Outpost(id),
AuditResource::Outpost(id),
AuditOutcome::Allowed,
),
Err(_) => (
Principal::Anonymous,
AuditResource::Api,
AuditOutcome::Denied,
),
};
state
.db
.audit_event(
&actor,
AuditAction::Authentication,
resource,
outcome,
Uuid::new_v4(),
)
.map_err(internal)?;
result
}
fn authenticate_outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
let token = upload_token(state, headers)?;
let id = state
.db
.upload_token_outpost(token)
.upload_token_outpost(token, chrono::Utc::now().timestamp())
.map_err(internal)?
.ok_or(StatusCode::UNAUTHORIZED)?;
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;
#[cfg(test)]
mod credentials_tests;
#[cfg(test)]
mod export_tests;
mod gate;
mod jobs;
mod oidc;
#[cfg(test)]
mod oidc_tests;
mod orbit;
mod refresh;
#[cfg(test)]
mod refresh_tests;
mod relations;
mod restore;
mod routes;
mod session;
pub use orbit::run_orbit_internal;
pub(crate) use relations::identity_facts;
pub(crate) use restore::artifact;
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")
.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")
.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,372 @@
//! 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>,
}
fn view(state: &HubState, run: &RefreshRun, admin: bool) -> 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(),
})
}
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>,
}
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)?
async fn snapshot_fits(
state: &HubState,
relation: &str,
snapshot: Uuid,
) -> Result<bool, StatusCode> {
let Some(source) = state.db.relation_source_orbit(relation).map_err(internal)? else {
return Ok(false);
};
let manifest = state
.vault
.read()
.await
.get_snapshot(snapshot)
.map_err(internal)?
.map(|s| s.manifest);
Ok(manifest.is_some_and(|manifest| {
manifest.orbit_id.to_string() == source
&& !manifest.is_restore_safety()
&& crate::api::artifact(&manifest).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();
if let Some(snapshot) = body.snapshot_id {
if !snapshot_fits(&state, &relation, snapshot).await? {
return Ok(reason(
StatusCode::UNPROCESSABLE_ENTITY,
"snapshot_unusable",
));
}
}
// 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,
body.snapshot_id,
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, "capturing");
}
let status = if created {
StatusCode::ACCEPTED
} else {
StatusCode::OK
};
Ok((
status,
no_store(),
Json(view(&state, &run, actor.subject.admin)?),
)
.into_response())
}
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 views = runs
.iter()
.map(|run| view(&state, run, actor.subject.admin))
.collect::<Result<Vec<_>, _>>()?;
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(&state, &run, actor.subject.admin)?)))
}
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(&state, &run, actor.subject.admin)?)).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::{
jobs::{header_value, internal, now, outpost, receive_payload},
routes::{require_admin, require_admin_mutation},
routes::{admin_read, admin_write},
};
use crate::state::HubState;
use axum::{
body::Body,
extract::{rejection::JsonRejection, ConnectInfo, Path, State},
extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
@@ -27,9 +27,13 @@ use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/restore-targets", post(register))
.route("/api/v1/restore-targets/:id", axum::routing::put(rename))
.route("/api/v1/capture-profiles/:id/restore-targets", get(targets))
.route("/api/v1/snapshots/:id/restore-targets", get(snapshot_targets))
.route("/api/v1/restore-jobs", post(enqueue))
.route(
"/api/v1/snapshots/:id/restore-targets",
get(snapshot_targets),
)
.route("/api/v1/restore-jobs", post(enqueue).get(recent))
.route("/api/v1/snapshots/:id/restore-jobs", get(history))
.route("/api/v1/restore-jobs/:id", get(job).delete(cancel))
.route("/api/v1/restore-jobs/:id/reconcile", post(reconcile))
@@ -46,7 +50,7 @@ async fn register(
headers: HeaderMap,
Json(target): Json<RestoreTarget>,
) -> 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()
|| target.name.len() > 128
|| target.name.chars().any(char::is_control)
@@ -56,7 +60,8 @@ async fn register(
}
let profiles = state.db.capture_profiles().map_err(internal)?;
if !profiles.iter().any(|profile| {
profile.application_id == target.application_id && profile.format.engine() == Some(target.engine)
profile.application_id == target.application_id
&& profile.format.engine() == Some(target.engine)
}) {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
@@ -78,13 +83,50 @@ async fn register(
Ok((StatusCode::CREATED, Json(target)))
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Rename {
name: String,
}
/// Same rules as at registration: not blank, at most 128 characters, no control characters.
fn valid_target_name(name: &str) -> bool {
!name.trim().is_empty() && name.len() <= 128 && !name.chars().any(char::is_control)
}
async fn rename(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<Rename>,
) -> Result<StatusCode, StatusCode> {
let actor = admin_write(&state, peer, &headers)?;
let name = body.name.trim();
if !valid_target_name(name) {
return Err(StatusCode::BAD_REQUEST);
}
if !state.db.rename_restore_target(id, name).map_err(internal)? {
return Err(StatusCode::NOT_FOUND);
}
state
.db
.audit(
"restore_target.renamed",
&format!("actor={actor} target={id}"),
)
.await
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}
async fn targets(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(application): Path<Uuid>,
) -> Result<Json<Vec<RestoreTarget>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state
.db
.restore_targets(application)
@@ -105,7 +147,7 @@ async fn snapshot_targets(
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
let vault = state.vault.read().await;
let snap = vault
.get_snapshot(snapshot)
@@ -125,7 +167,10 @@ async fn snapshot_targets(
} else {
Some("Outpost is no longer paired")
};
SnapshotTarget { target, ineligible_reason }
SnapshotTarget {
target,
ineligible_reason,
}
})
.collect();
Ok(Json(responses))
@@ -137,7 +182,7 @@ async fn enqueue(
headers: HeaderMap,
Json(request): Json<RestoreRequest>,
) -> 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)
{
return Err(StatusCode::BAD_REQUEST);
@@ -156,7 +201,7 @@ async fn enqueue(
request.snapshot_id,
application,
request.target_id,
&actor.name,
&actor.id(),
&artifact,
now(),
)
@@ -165,7 +210,7 @@ async fn enqueue(
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 application = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
let format = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
@@ -199,7 +244,7 @@ async fn job(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<RestoreJob>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state
.db
.restore_job(id, now())
@@ -214,7 +259,7 @@ async fn history(
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
require_admin(&state, peer, &headers)?;
admin_read(&state, peer, &headers)?;
state
.db
.restore_history(snapshot, now())
@@ -222,16 +267,36 @@ async fn history(
.map_err(internal)
}
#[derive(Deserialize)]
struct Recent {
limit: Option<u32>,
}
/// The newest restore jobs across all snapshots. The activity log reads this instead of asking snapshot by snapshot.
async fn recent(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Query(query): Query<Recent>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
admin_read(&state, peer, &headers)?;
state
.db
.restore_recent(query.limit.unwrap_or(50).clamp(1, 200), now())
.map(Json)
.map_err(internal)
}
async fn cancel(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
let actor = admin_write(&state, peer, &headers)?;
if !state
.db
.cancel_restore(id, &actor.name, now())
.cancel_restore(id, &actor.id(), now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
@@ -250,17 +315,23 @@ async fn reconcile(
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<Reconcile>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
) -> Result<StatusCode, (StatusCode, Json<serde_json::Value>)> {
let plain = |status: StatusCode| (status, Json(serde_json::Value::Null));
let actor = admin_write(&state, peer, &headers).map_err(plain)?;
if body.confirmation != format!("RECONCILE {id}") {
return Err(StatusCode::BAD_REQUEST);
return Err(plain(StatusCode::BAD_REQUEST));
}
if !state
.db
.reconcile_restore(id, &actor.name, now())
.map_err(internal)?
.reconcile_restore(id, &actor.id(), now())
.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)
}
@@ -338,13 +409,22 @@ async fn report(
) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
// Why a step failed, in the agent's words. Cleaned again here: the agent is trusted with the job, not
// with what ends up in the database and the log.
let reason = headers
.get(tessera_core::restore::FAILURE_REASON_HEADER)
.and_then(|value| value.to_str().ok())
.and_then(tessera_core::restore::clean_failure_reason);
if !state
.db
.report_restore(outpost, id, token, progress, now())
.report_restore(outpost, id, token, progress, reason.as_deref(), now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
if let Some(reason) = &reason {
tracing::warn!(job = %id, ?progress, %reason, "restore step failed");
}
Ok(StatusCode::NO_CONTENT)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
use crate::admin::{tokens_match, SessionGate};
use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal};
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, State},
@@ -12,9 +13,12 @@ use std::net::SocketAddr;
#[derive(Serialize)]
struct Status {
login_enabled: bool,
oidc_enabled: bool,
authorized: bool,
admin: bool,
actor: Option<String>,
csrf: Option<String>,
expires_at: Option<i64>,
}
#[derive(Deserialize)]
@@ -27,6 +31,11 @@ pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/operator/session", get(status).delete(logout))
.route("/api/v1/operator/login", post(login))
.route("/api/v1/me", get(me))
.route(
"/api/v1/me/preferences",
get(preferences).put(set_preferences),
)
}
async fn status(
@@ -35,44 +44,254 @@ async fn status(
headers: HeaderMap,
) -> (HeaderMap, Json<Status>) {
let browser = state.sessions.active(&headers);
let authorized = browser.is_some()
|| (!state.sessions.enabled() && state.admin.token.is_none() && peer.ip().is_loopback());
// The app opens for an administrator or for anyone holding a live grant that lets them read an orbit.
let reads_something = browser.as_ref().is_some_and(|session| {
let now = chrono::Utc::now().timestamp();
!session.admin
&& (state
.db
.permitted_orbits(Some(&session.user_id), &session.groups, "orbit.read", now)
.is_ok_and(|p| p.everywhere || !p.orbits.is_empty())
// someone who may only refresh a staging database still gets in, to that one screen
|| state.db.granted_relations(Some(&session.user_id), &session.groups, now).is_ok_and(|r| !r.is_empty()))
});
let authorized = browser.as_ref().is_some_and(|session| session.admin)
|| reads_something
|| (browser.is_none()
&& !state.sessions.enabled()
&& state.admin.token.is_none()
&& state.admin.authorize(peer, &headers).is_ok());
(
no_store(),
Json(Status {
login_enabled: state.sessions.enabled(),
login_enabled: state.sessions.password_enabled(),
oidc_enabled: state.oidc.is_some(),
authorized,
admin: browser.as_ref().map_or(authorized, |session| session.admin),
actor: browser.as_ref().map(|session| session.actor.clone()),
expires_at: browser.as_ref().map(|session| session.expires_at),
csrf: browser.map(|session| session.csrf.to_string()),
}),
)
}
#[derive(Serialize)]
struct MyGrant {
permission: String,
/// `None` = every orbit.
orbit_id: Option<String>,
}
#[derive(Serialize)]
struct Me {
id: String,
kind: &'static str,
auth_method: &'static str,
display_name: String,
admin: bool,
capabilities: Vec<String>,
grants: Vec<MyGrant>,
/// Ids of the relations this person may refresh through (everything, for an administrator).
refresh_relations: Vec<String>,
}
/// The caller's own identity and what it may use: `admin`, its live grants, and the relations it may refresh through.
async fn me(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Me>), StatusCode> {
// Identity only, no gate: a signed-in user without any grant still gets this (empty grants).
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
let (id, kind, auth_method) = actor.principal.fields();
let grants: Vec<MyGrant> = if actor.subject.admin {
vec![]
} else {
state
.db
.grants_of(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
chrono::Utc::now().timestamp(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.into_iter()
.map(|(permission, orbit_id)| MyGrant {
permission,
orbit_id,
})
.collect()
};
let mut capabilities: Vec<String> = if actor.subject.admin {
vec!["admin".into()]
} else {
let mut names: Vec<String> = grants.iter().map(|g| g.permission.clone()).collect();
names.dedup();
names
};
capabilities.sort();
let refresh_relations = if actor.subject.admin {
vec![]
} else {
state
.db
.granted_relations(
actor.subject.user_id.as_deref(),
&actor.subject.groups,
chrono::Utc::now().timestamp(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
};
Ok((
no_store(),
Json(Me {
id,
kind,
auth_method,
display_name: actor.name.clone(),
admin: actor.subject.admin,
capabilities,
grants,
refresh_relations,
}),
))
}
/// Display choices an account keeps across browsers. Every key has a closed set of values.
const LOOKS: [&str; 2] = ["window", "radar"];
#[derive(Serialize)]
struct Preferences {
look: Option<String>,
}
/// The caller's own preferences. A caller without an account (the legacy token, local
/// development) simply has none.
async fn preferences(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(HeaderMap, Json<Preferences>), StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, false)?;
let stored = match actor.subject.user_id.as_deref() {
Some(user) => state
.db
.preferences(user)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?,
None => Default::default(),
};
let look = stored
.get("look")
.filter(|value| LOOKS.contains(&value.as_str()))
.cloned();
Ok((no_store(), Json(Preferences { look })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetPreferences {
look: Option<String>,
}
async fn set_preferences(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(body): Json<SetPreferences>,
) -> Result<StatusCode, StatusCode> {
let actor = super::routes::authenticate(&state, peer, &headers, true)?;
let user = actor
.subject
.user_id
.as_deref()
.ok_or(StatusCode::NOT_FOUND)?;
if let Some(look) = body.look {
if !LOOKS.contains(&look.as_str()) {
return Err(StatusCode::BAD_REQUEST);
}
state
.db
.set_preference(user, "look", &look, chrono::Utc::now().timestamp())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
}
Ok(StatusCode::NO_CONTENT)
}
async fn login(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(input): Json<Login>,
) -> Result<(HeaderMap, Json<Status>), StatusCode> {
// Cheap checks first: per-source budget, then the account ceiling, then a
// bounded number of concurrent Argon2 verifications. A flood is refused
// before it can cost CPU or memory, and it only spends its own source's budget.
let source = state.limits.source(Some(peer), &headers);
if !state.limits.login_allowed(source) {
if state.limits.audit_denial(source) {
let _ = state.db.audit_event(
&Principal::Anonymous,
AuditAction::Login,
AuditResource::Session,
AuditOutcome::Denied,
uuid::Uuid::new_v4(),
);
}
return Err(StatusCode::TOO_MANY_REQUESTS);
}
if input.password.is_empty() || input.password.len() > 1024 {
return Err(StatusCode::UNAUTHORIZED);
}
let permit = state
.limits
.argon2
.clone()
.try_acquire_owned()
.map_err(|_| StatusCode::TOO_MANY_REQUESTS)?;
let gate = state.sessions.clone();
let session = tokio::task::spawn_blocking(move || gate.login(&headers, &input.password))
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)??;
let attempt = tokio::task::spawn_blocking(move || {
let _permit = permit; // released when hashing is done, not when the handler returns
gate.login(&headers, &input.password)
})
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let (principal, outcome) = match &attempt {
Ok(session) => (
Principal::Emergency(session.actor.clone()),
AuditOutcome::Succeeded,
),
Err(_) => (Principal::Anonymous, AuditOutcome::Failed),
};
state
.db
.audit_event(
&principal,
AuditAction::Login,
AuditResource::Session,
outcome,
uuid::Uuid::new_v4(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let session = attempt?;
state
.db
.audit("operator.login", &session.actor)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store();
headers.insert(header::SET_COOKIE, cookie(Some(&session.id.to_string()))?);
headers.insert(
header::SET_COOKIE,
session_cookie(Some(&session.id.to_string()))?,
);
Ok((
headers,
Json(Status {
login_enabled: true,
oidc_enabled: state.oidc.is_some(),
authorized: true,
admin: true,
actor: Some(session.actor),
expires_at: Some(session.expires_at),
csrf: Some(session.csrf.to_string()),
}),
))
@@ -88,13 +307,23 @@ async fn logout(
.ok_or(StatusCode::UNAUTHORIZED)?;
require_csrf(&headers, &session.csrf.to_string())?;
state.sessions.remove(session.id);
state
.db
.audit_event(
&session.principal(),
AuditAction::Logout,
AuditResource::Session,
AuditOutcome::Succeeded,
uuid::Uuid::new_v4(),
)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
state
.db
.audit("operator.logout", &session.actor)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store();
headers.insert(header::SET_COOKIE, cookie(None)?);
headers.insert(header::SET_COOKIE, session_cookie(None)?);
Ok((StatusCode::NO_CONTENT, headers))
}
@@ -116,7 +345,7 @@ fn no_store() -> HeaderMap {
headers
}
fn cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
pub(super) fn session_cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
let value = format!(
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
SessionGate::COOKIE,
@@ -143,7 +372,7 @@ mod tests {
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
.await
.unwrap();
state.sessions = SessionGate::fixture();
state.sessions = SessionGate::fixture(state.db.clone());
state.admin.token = Some("fixture-api-token".into());
let app = crate::api::router(state.clone());
let request = |method: &str, uri: &str, body: &'static str| {
@@ -250,5 +479,93 @@ mod tests {
[], |row| row.get(0),
).unwrap();
assert_eq!(audited, 3);
let actor_count: i64 = connection.query_row(
"SELECT COUNT(*) FROM audit_events WHERE action IN ('auth.login','auth.logout')
AND actor_id='emergency:fixture-operator' AND actor_kind='user' AND auth_method='password'",
[], |row| row.get(0),
).unwrap();
assert_eq!(actor_count, 3);
let failed_count: i64 = connection.query_row(
"SELECT COUNT(*) FROM audit_events WHERE action='auth.login' AND outcome='failed' AND actor_id='anonymous'",
[], |row| row.get(0),
).unwrap();
assert_eq!(failed_count, 1);
let values: String = connection.query_row(
"SELECT group_concat(actor_id || action || coalesce(resource_id,'') || auth_method) FROM audit_events",
[], |row| row.get(0),
).unwrap();
for secret in [
"fixture-operator-password",
"fixture-api-token",
"Bearer",
"wrong",
] {
assert!(!values.contains(secret));
}
}
#[tokio::test]
async fn me_reports_the_caller_and_rejects_anonymous() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
.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;
pub use jobs::ProfileChange;
pub(crate) mod oidc_login;
pub(crate) mod refresh;
pub(crate) mod relations;
mod restore;
pub mod sessions;
pub(crate) use restore::restore_target_mismatch;
use anyhow::Result;
@@ -72,14 +80,6 @@ impl Db {
total INTEGER,
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 (
session_id TEXT NOT NULL,
start_off INTEGER NOT NULL,
@@ -94,13 +94,21 @@ impl Db {
"INTEGER NOT NULL DEFAULT 0",
)?;
ensure_column(&conn, "orbits", "retention", "TEXT")?;
conn.execute(
"INSERT OR IGNORE INTO outposts(id, name, pairing_state)
SELECT outpost_id, outpost_name, 'active' FROM wormhole_tokens WHERE state = 'active'",
[],
ensure_column(
&conn,
"orbits",
"outpost_id",
"TEXT REFERENCES outposts(id)",
)?;
credentials::migrate(&conn)?;
jobs::migrate(&conn)?;
restore::migrate(&conn)?;
audit::migrate(&conn)?;
sessions::migrate(&conn)?;
oidc_login::migrate(&conn)?;
access::migrate(&conn)?;
relations::migrate(&conn)?;
refresh::migrate(&conn)?;
Ok(())
}
@@ -139,6 +147,45 @@ impl Db {
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
/// Current names of all orbits, by id. Snapshots keep the name they were written under; what people see
/// is the name the orbit has now.
pub fn orbit_names(&self) -> Result<std::collections::HashMap<Uuid, String>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name FROM orbits")?;
let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
Ok(rows
.filter_map(Result::ok)
.filter_map(|(id, name)| Some((Uuid::parse_str(&id).ok()?, name)))
.collect())
}
/// Change an orbit's name. `None` for an unknown orbit, `Some(false)` when another orbit has the name
/// (compared without regard to case), `Some(true)` when renamed.
pub fn rename_orbit(&self, id: Uuid, name: &str) -> Result<Option<bool>> {
let conn = self.conn.lock().unwrap();
let exists: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE id = ?1)",
params![id.to_string()],
|r| r.get(0),
)?;
if !exists {
return Ok(None);
}
let taken: bool = conn.query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE lower(name) = lower(?2) AND id <> ?1)",
params![id.to_string(), name],
|r| r.get(0),
)?;
if taken {
return Ok(Some(false));
}
conn.execute(
"UPDATE orbits SET name = ?2 WHERE id = ?1",
params![id.to_string(), name],
)?;
Ok(Some(true))
}
pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
@@ -217,67 +264,60 @@ impl Db {
&self,
id: &str,
orbit_id: &str,
outpost_id: Uuid,
total: Option<i64>,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, offset, total, sealed, created_at) VALUES (?1, ?2, 0, ?3, 0, datetime('now'))",
params![id, orbit_id, total],
let inserted = conn.execute(
"INSERT INTO upload_sessions (id, orbit_id, outpost_id, offset, total, sealed, created_at)
SELECT ?1, id, ?3, 0, ?4, 0, datetime('now') FROM orbits
WHERE id = ?2 AND outpost_id = ?3 AND provider = 'wormhole' AND dry_run = 0",
params![id, orbit_id, outpost_id.to_string(), total],
)?;
anyhow::ensure!(
inserted == 1,
"Outpost assignment changed during upload initialization"
);
Ok(())
}
pub fn insert_wormhole_token(
&self,
token: &str,
outpost_id: &str,
code: &str,
expires_at: &str,
) -> Result<()> {
pub fn bind_legacy_outpost(&self, orbit: Uuid, outpost: Uuid) -> Result<bool> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO wormhole_tokens (token, outpost_id, code, state, expires_at) VALUES (?1, ?2, ?3, 'code_shown', ?4)",
params![token, outpost_id, code, expires_at],
)?;
Ok(())
Ok(conn.execute(
"UPDATE orbits SET outpost_id=?2 WHERE id=?1 AND provider='wormhole' AND dry_run=0
AND NOT EXISTS (SELECT 1 FROM capture_profiles WHERE orbit_id=?1)
AND EXISTS (SELECT 1 FROM outposts WHERE id=?2 AND pairing_state='active')",
params![orbit.to_string(), outpost.to_string()],
)? == 1)
}
pub fn claim_wormhole_code(
&self,
code: &str,
outpost_name: &str,
now: &str,
) -> Result<Option<(String, String)>> {
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 legacy_upload_owned_by(&self, orbit: Uuid, outpost: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM orbits WHERE id=?1 AND outpost_id=?2
AND provider='wormhole' AND dry_run=0)",
params![orbit.to_string(), outpost.to_string()],
|row| row.get(0),
)?)
}
pub fn list_outposts(&self) -> Result<Vec<OutpostSummary>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?;
let mut stmt = conn
.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?;
let rows = stmt.query_map([], |row| {
let id = Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| {
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
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<_>>()?)
}
@@ -292,18 +332,10 @@ impl Db {
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>> {
let conn = self.conn.lock().unwrap();
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 Some(row) = rows.next()? else {
@@ -316,6 +348,7 @@ impl Db {
orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?,
total: total.unwrap_or(0).max(0) as u64,
sealed: sealed != 0,
outpost_id: row.get(3)?,
}))
}
@@ -385,6 +418,7 @@ impl Db {
#[derive(Debug, Clone)]
pub struct UploadSession {
pub orbit_id: Uuid,
pub outpost_id: Option<String>,
pub total: u64,
pub sealed: bool,
}
@@ -397,7 +431,10 @@ fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Re
return Ok(());
}
}
conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?;
conn.execute(
&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"),
[],
)?;
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,125 @@
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(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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 {
pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> {
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
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",
params![profile.application_id.to_string(), profile.orbit_id.to_string(),
profile.outpost_id.to_string(), serde_json::to_string(profile)?, now,
@@ -122,6 +129,51 @@ impl Db {
Ok(changed == 1)
}
/// Change the parts of a profile an operator may edit. Absent = unchanged, `Some(None)` = cleared.
///
/// A changed schedule moves the schedule cursor up to `now` (the cursor is the later of the newest
/// scheduled job and `registered_at`), so a slot that is already past under the new schedule is never
/// replayed: the first job comes from the next slot. Returns `None` when there is no such profile.
pub fn update_capture_profile(
&self,
application: Uuid,
change: ProfileChange,
now: i64,
) -> Result<Option<CaptureProfile>> {
let conn = self.conn.lock().unwrap();
let current: Option<CaptureProfile> = conn
.query_row(
"SELECT profile FROM capture_profiles WHERE application_id = ?1",
params![application.to_string()],
|row| parse_profile(row, 0),
)
.optional()?;
let Some(mut profile) = current else {
return Ok(None);
};
let schedule_changed = change.schedule.as_ref().is_some_and(|new| {
serde_json::to_string(new).ok() != serde_json::to_string(&profile.schedule).ok()
});
if let Some(schedule) = change.schedule {
profile.schedule = schedule;
}
if let Some(retention) = change.retention {
profile.retention = retention;
}
conn.execute(
"UPDATE capture_profiles SET profile = ?2,
registered_at = CASE WHEN ?4 THEN max(registered_at, ?3) ELSE registered_at END
WHERE application_id = ?1",
params![
application.to_string(),
serde_json::to_string(&profile)?,
now,
schedule_changed
],
)?;
Ok(Some(profile))
}
pub fn capture_profiles(&self) -> Result<Vec<CaptureProfile>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
@@ -133,7 +185,7 @@ impl Db {
pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> {
let conn = self.conn.lock().unwrap();
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)
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)
SELECT ?1, application_id, 'scheduler', ?4, ?4, ?3 FROM capture_profiles p
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",
params![Uuid::new_v4().to_string(), application.to_string(), slot, now],
)?;
@@ -160,15 +212,10 @@ impl Db {
now: i64,
) -> Result<Option<CaptureJob>> {
let conn = self.conn.lock().unwrap();
let id = Uuid::new_v4();
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 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)
match insert_capture_job(&conn, application_id, actor, now)? {
Some(id) => capture_job(&conn, id),
None => Ok(None),
}
}
pub fn capture_jobs(
@@ -176,14 +223,25 @@ impl Db {
application: Option<Uuid>,
status: Option<&str>,
limit: u16,
orbits: Option<&[String]>,
) -> Result<Vec<CaptureJob>> {
let conn = self.conn.lock().unwrap();
// The orbit restriction is part of the query, before LIMIT, so a restricted
// caller still gets a full page of their own jobs.
let mut stmt = conn.prepare(&format!(
"{JOB_VIEW} WHERE (?1 IS NULL OR j.application_id = ?1) AND (?2 IS NULL OR j.status = ?2)
AND (?4 IS NULL OR j.application_id IN (
SELECT application_id FROM capture_profiles WHERE orbit_id IN (SELECT value FROM json_each(?4))))
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
))?;
let restriction = orbits.map(serde_json::to_string).transpose()?;
let rows = stmt.query_map(
params![application.map(|id| id.to_string()), status, limit],
params![
application.map(|id| id.to_string()),
status,
limit,
restriction
],
read_job,
)?;
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(
conn: &Connection,
outpost: Uuid,
@@ -490,11 +568,7 @@ mod tests {
assert!(!db.register_capture_profile(&a, 100).unwrap());
assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none());
for (id, token) in [(outpost, "token-a"), (other, "token-b")] {
db.insert_wormhole_token(token, &id.to_string(), token, "9999")
.unwrap();
db.claim_wormhole_code(token, "agent", "2026")
.unwrap()
.unwrap();
db.insert_test_credential(token, &id.to_string(), "agent");
}
assert!(db.register_capture_profile(&a, 100).unwrap());
assert!(db.register_capture_profile(&b, 100).unwrap());
@@ -585,8 +659,7 @@ mod tests {
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("token", &outpost.to_string(), "code", "9999").unwrap();
db.claim_wormhole_code("code", "agent", "2026").unwrap().unwrap();
db.insert_test_credential("token", &outpost.to_string(), "agent");
let profile = profile(&db, outpost).await;
let app = profile.application_id;
let now = chrono::Utc::now().timestamp();
@@ -600,12 +673,23 @@ mod tests {
let lease = db.claim_capture(outpost, app, now).unwrap().unwrap();
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running");
for progress in [CaptureProgress::Dumping, progress] {
assert!(db.report_capture(outpost, job.id, CaptureReport {
lease_id: lease.lease_id, progress,
}, now).unwrap());
assert!(db
.report_capture(
outpost,
job.id,
CaptureReport {
lease_id: lease.lease_id,
progress,
},
now
)
.unwrap());
}
if expected == "completed" {
assert!(db.publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(())).unwrap().is_some());
assert!(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);
}
@@ -621,11 +705,7 @@ mod tests {
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("test", &outpost.to_string(), "code", "9999")
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
db.insert_test_credential("test", &outpost.to_string(), "agent");
let mut a = profile(&db, outpost).await;
let mut b = profile(&db, outpost).await;
a.schedule = Some(CaptureSchedule {
@@ -642,17 +722,17 @@ mod tests {
}
let tick = crate::scheduler::tick_capture_schedules;
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();
tick(&db, now).unwrap();
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
tick(&db, now).unwrap();
let all = db.capture_jobs(None, Some("queued"), 100).unwrap();
let all = db.capture_jobs(None, Some("queued"), 100, None).unwrap();
assert_eq!(all.len(), 4);
let history = db
.capture_jobs(Some(a.application_id), Some("queued"), 100)
.capture_jobs(Some(a.application_id), Some("queued"), 100, None)
.unwrap();
assert_eq!(history.len(), 2);
assert!(history.iter().all(|job| job.actor == "scheduler"));
@@ -678,7 +758,7 @@ mod tests {
.unwrap());
}
let failed = db
.capture_jobs(Some(a.application_id), Some("failed"), 100)
.capture_jobs(Some(a.application_id), Some("failed"), 100, None)
.unwrap();
assert_eq!(failed.len(), 1);
let events = db.capture_events(first.job_id).unwrap();
@@ -690,4 +770,120 @@ mod tests {
["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,653 @@
//! 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,
}
/// 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:";
/// A relation's source orbit, for checking that a snapshot belongs to it.
impl Db {
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,
snapshot: Option<Uuid>,
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 busy: Option<String> = tx
.query_row("SELECT id FROM refresh_runs WHERE target_id=?1 AND status IN ('capturing','restoring','recovery_required')", params![relation.target_id], |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));
}
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(_) => 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 run.capture_job_id.starts_with(EXISTING) {
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 run.capture_job_id.starts_with(EXISTING) => {
// 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_until INTEGER,
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_snapshot ON restore_jobs(snapshot_id, safety_id, status);",
)?;
// databases created before failure reasons existed
ensure_column(conn, "restore_jobs", "failure_reason", "TEXT")?;
Ok(())
}
const VIEW: &str =
"SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at,
j.updated_at, j.artifact, j.attempt_safety_id
j.updated_at, j.artifact, j.attempt_safety_id, j.failure_reason
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
@@ -63,6 +66,7 @@ fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
.map_err(|err| invalid_column(6, err))?,
created_at: row.get(7)?,
updated_at: row.get(8)?,
failure_reason: row.get(11)?,
})
}
@@ -86,7 +90,7 @@ impl Db {
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
AND EXISTS (SELECT 1 FROM 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",
params![
target.id.to_string(),
@@ -94,24 +98,45 @@ impl Db {
target.outpost_id.to_string(),
serde_json::to_string(&(target.engine, &target.identity))?,
serde_json::to_string(target)?,
chrono::Utc::now().timestamp(),
],
)?;
Ok(changed == 1)
}
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
Ok(self.restore_targets_with_activity(application)?
.into_iter().map(|(target, _)| target).collect())
/// Change the display name of a restore target. Its id, identity and Outpost are not touched, so
/// relations and jobs that refer to it stay valid. Returns false for an unknown target.
pub fn rename_restore_target(&self, id: Uuid, name: &str) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"UPDATE restore_targets SET profile = json_set(profile, '$.name', ?2) WHERE id = ?1",
params![id.to_string(), name],
)?;
Ok(changed == 1)
}
pub fn restore_targets_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 mut stmt = conn.prepare(
"SELECT t.profile, EXISTS (SELECT 1 FROM wormhole_tokens
WHERE outpost_id = t.outpost_id AND state = 'active')
"SELECT t.profile, EXISTS (SELECT 1 FROM outpost_credentials
WHERE outpost_id = t.outpost_id AND state = 'active' AND expires_at > ?2)
FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id",
)?;
let rows = stmt.query_map([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<_>>()?)
}
@@ -126,37 +151,9 @@ impl Db {
) -> Result<Option<RestoreJob>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
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 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,
)?;
let job = enqueue_restore_in(&tx, snapshot, application, target, actor, artifact, now)?;
tx.commit()?;
Ok(Some(job))
Ok(job)
}
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
@@ -181,11 +178,23 @@ impl Db {
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The newest restore jobs across every snapshot, newest first, for the activity log.
pub fn restore_recent(&self, limit: u32, now: i64) -> Result<Vec<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
let mut stmt = conn.prepare(&format!("{VIEW} ORDER BY j.rowid DESC LIMIT ?1"))?;
let rows = stmt.query_map([limit], read_job)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn snapshot_in_restore(&self, id: Uuid) -> Result<bool> {
let conn = self.conn.lock().unwrap();
Ok(conn.query_row(
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1)
AND status IN ('queued','running','applying','recovery_required'))",
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),
)?)
}
@@ -292,6 +301,22 @@ impl Db {
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
return Ok(false);
}
// A refresh is only allowed to overwrite its target while what authorised it still holds. The check
// and the flip to `applying` are one transaction, and the agent applies nothing without this answer.
// Restores an administrator queued directly have no run and behave exactly as before.
if let Some(run) = super::refresh::run_for_restore(&tx, &id.to_string())? {
if let Some(reason) = super::refresh::invalid_reason(&tx, &run, now)? {
super::refresh::block(&tx, &run, reason, now)?;
tx.execute("UPDATE restore_jobs SET status='cancelled', phase='cancelled', updated_at=?2 WHERE id=?1 AND status='running'", params![id.to_string(), now])?;
audit(
&tx,
"restore.apply_refused",
&format!("job={id} run={} reason={reason}", run.id),
)?;
tx.commit()?;
return Ok(false);
}
}
tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1",
params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
audit(
@@ -309,6 +334,7 @@ impl Db {
id: Uuid,
token: Uuid,
progress: RestoreProgress,
reason: Option<&str>,
now: i64,
) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
@@ -338,6 +364,24 @@ impl Db {
if !matches!(progress, RestoreProgress::Heartbeat) {
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
}
let failed = matches!(
progress,
RestoreProgress::InvalidPayload
| RestoreProgress::WrongTarget
| RestoreProgress::SafetyFailed
| RestoreProgress::ApplyFailed
);
if let (true, Some(reason)) = (failed, reason) {
tx.execute(
"UPDATE restore_jobs SET failure_reason = ?2 WHERE id = ?1",
params![id.to_string(), reason],
)?;
audit(
&tx,
"restore.failed",
&format!("job={id} phase={phase} reason={reason}"),
)?;
}
tx.commit()?;
Ok(true)
}
@@ -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(
conn: &Connection,
outpost: Uuid,
@@ -429,11 +515,7 @@ mod tests {
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("synthetic-token", &outpost.to_string(), "code", "9999")
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
db.insert_test_credential("synthetic-token", &outpost.to_string(), "agent");
let orbit = Uuid::new_v4();
db.upsert_orbit(&OrbitRow {
id: orbit,
@@ -485,11 +567,24 @@ mod tests {
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);
let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() };
assert_eq!(restore_target_mismatch(&registered.0, &same_source), Some("Target is the source database"));
assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none());
let same_source = RestoreArtifact {
identity: registered.0.identity.clone(),
..artifact.clone()
};
assert_eq!(
restore_target_mismatch(&registered.0, &same_source),
Some("Target is the source database")
);
assert!(db
.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100)
.unwrap()
.is_none());
let job = db
.enqueue_restore(snapshot, app, target, "fixture", &artifact, 100)
.unwrap()
@@ -507,10 +602,24 @@ mod tests {
.authorize_apply(outpost, job.id, lease.token, 104)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104)
.report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Checking,
None,
104
)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105)
.report_restore(
outpost,
job.id,
lease.token,
RestoreProgress::Safety,
None,
105
)
.unwrap());
assert!(db
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
@@ -544,6 +653,12 @@ mod tests {
.unwrap());
let interrupted = db.restore_job(job.id, late).unwrap().unwrap();
assert_eq!(interrupted.status, "recovery_required");
let recent = db.restore_recent(10, late).unwrap();
assert_eq!(
recent.iter().map(|item| item.id).collect::<Vec<_>>(),
vec![next.id, job.id]
);
assert_eq!(db.restore_recent(1, late).unwrap().len(), 1);
assert_eq!(interrupted.safety_snapshot_id, Some(safety));
assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(db.snapshot_in_restore(safety).unwrap());

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,599 @@
//! 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::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,
}
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,
}
}
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 permit lives as long as the response body.
pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result<OwnedSemaphorePermit, Refused> {
let permit = self
.permits
.clone()
.try_acquire_owned()
.map_err(|_| Refused::Busy)?;
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.
Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace),
_ => Ok(permit),
}
}
}
#[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: OwnedSemaphorePermit,
_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: OwnedSemaphorePermit,
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(
"lti",
taken(),
Some("Asia/Jakarta"),
Some("postgres"),
id(),
"dump",
);
assert_eq!(name, "lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump");
let name = download_name("boiler", taken(), None, Some("mysql"), id(), "sql.gz");
assert_eq!(name, "boiler_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(
"lti",
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("lti", taken(), None, Some("postgres"), id(), "dump");
let b = download_name("lti", 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("lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump");
assert_eq!(
header,
"attachment; filename=\"lti_2026-11-15T0230+0700_postgres_a1b2c3d4.dump\"; \
filename*=UTF-8''lti_2026-11-15T0230%2B0700_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"
);
}
}

View File

@@ -0,0 +1,269 @@
//! 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,
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)),
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();
}
}
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()
}
/// 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 api;
mod auth;
mod db;
mod exports;
mod limits;
mod mtls;
mod oidc;
mod refresh;
mod scheduler;
mod state;
mod upload;
@@ -22,6 +27,13 @@ async fn main() -> Result<()> {
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 addr: SocketAddr = listen.parse()?;
let admin = admin::AdminGate::from_env()?;
admin.validate_listener(addr)?;
let wormhole = mtls::from_env()?;
if let Some(config) = &wormhole {
admin.validate_listener(config.listen)?;
}
let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE")
.ok()
.filter(|value| !value.is_empty())
@@ -37,6 +49,13 @@ async fn main() -> Result<()> {
}
let mut state = HubState::bootstrap(&data_dir, &vault_pass).await?;
// Exports a crash left half-written; nothing is serving yet, so nothing can be using them.
let swept = exports::sweep_stale(std::path::Path::new(&data_dir));
if swept > 0 {
tracing::info!("removed {swept} unfinished snapshot export(s) from a previous run");
}
anyhow::ensure!(state.sessions.enabled() || state.admin.token_active() || state.admin.local_development,
"configure a named emergency operator and/or TESSERA_ADMIN_TOKEN; anonymous local access requires explicit TESSERA_LOCAL_DEVELOPMENT=true");
if std::env::var("TESSERA_SEED_DEMO")
.map(|v| v == "1" || v == "true")
@@ -63,13 +82,14 @@ async fn main() -> Result<()> {
state.reconcile_capture_catalog().await?;
state.start_offsite_worker();
scheduler::start_orbit_scheduler(state.clone()).await?;
refresh::start(state.clone());
if state.sessions.enabled() {
tracing::info!("operator sessions enabled; CLI access uses a separate admin token");
} else {
state.admin.log_policy();
}
if let Some(wormhole) = mtls::from_env()? {
if let Some(wormhole) = wormhole {
state.wormhole_mtls = true;
state.accept_plain_upload = false;
let mut tls_state = state.clone();
@@ -84,14 +104,7 @@ async fn main() -> Result<()> {
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 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}");
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(

View File

@@ -6,14 +6,12 @@ use axum::Router;
use hyper::body::Incoming;
use hyper_util::rt::TokioIo;
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::RootCertStore;
use rustls::ServerConfig;
use std::convert::Infallible;
use std::fs::File;
use std::future::Future;
use std::io::BufReader;
use std::net::SocketAddr;
use std::path::Path;
use std::pin::Pin;
@@ -36,15 +34,12 @@ pub fn from_env() -> Result<Option<WormholeMtls>> {
if !enabled {
return Ok(None);
}
let cert = std::env::var("TESSERA_WORMHOLE_CERT").context(
"TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled",
)?;
let key = std::env::var("TESSERA_WORMHOLE_KEY").context(
"TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled",
)?;
let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA").context(
"TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled",
)?;
let cert = std::env::var("TESSERA_WORMHOLE_CERT")
.context("TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled")?;
let key = std::env::var("TESSERA_WORMHOLE_KEY")
.context("TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled")?;
let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA")
.context("TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled")?;
let listen = std::env::var("TESSERA_WORMHOLE_LISTEN")
.unwrap_or_else(|_| "127.0.0.1:8788".into())
.parse()
@@ -80,7 +75,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
mtls.listen
);
loop {
let (tcp, _) = listener.accept().await.context("accept wormhole mTLS")?;
let (tcp, peer) = listener.accept().await.context("accept wormhole mTLS")?;
let acceptor = acceptor.clone();
let app = app.clone();
tokio::spawn(async move {
@@ -88,7 +83,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
return;
};
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()
.serve_connection(io, service)
.await;
@@ -97,7 +92,7 @@ pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> {
}
#[derive(Clone)]
struct HyperApp(Router);
struct HyperApp(Router, SocketAddr);
impl Service<Request<Incoming>> for HyperApp {
type Response = Response;
@@ -110,9 +105,15 @@ impl Service<Request<Incoming>> for HyperApp {
fn call(&mut self, request: Request<Incoming>) -> Self::Future {
let app = self.0.clone();
let mut request = request.map(Body::new);
// The TLS listener has no `into_make_service_with_connect_info`; supply the peer here
// so handlers that rate limit by source see the real address.
request
.extensions_mut()
.insert(axum::extract::ConnectInfo(self.1));
Box::pin(async move {
Ok(app
.oneshot(request.map(Body::new))
.oneshot(request)
.await
.unwrap_or_else(|error| match error {}))
})
@@ -120,26 +121,134 @@ impl Service<Request<Incoming>> for HyperApp {
}
pub fn load_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
rustls_pemfile::certs(&mut reader)
CertificateDer::pem_file_iter(path)
.with_context(|| format!("open {}", path.display()))?
.collect::<Result<Vec<_>, _>>()
.context("parse certificate")
}
pub fn load_key(path: &Path) -> Result<PrivateKeyDer<'static>> {
let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?);
rustls_pemfile::private_key(&mut reader)
.context("parse private key")?
.context("certificate file has no private key")
PrivateKeyDer::from_pem_file(path).context("parse private key (none found in file?)")
}
pub fn load_ca(path: &Path) -> Result<RootCertStore> {
let mut roots = RootCertStore::empty();
for cert in load_certs(path)? {
roots.add(cert).map_err(|error| anyhow::anyhow!("client CA: {error}"))?;
roots
.add(cert)
.map_err(|error| anyhow::anyhow!("client CA: {error}"))?;
}
if roots.is_empty() {
anyhow::bail!("client CA file contained no certificates");
}
Ok(roots)
}
#[cfg(test)]
mod tests {
use super::*;
use rcgen::{
BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, KeyPair,
};
/// Agents reach pairing and upload routes over mTLS. Those handlers rate limit
/// by source, which needs the peer address; this proves it is supplied on that
/// listener (without it every agent request would fail in the extractor).
#[tokio::test]
async fn agent_requests_over_mtls_carry_their_peer_address() {
let ca_key = KeyPair::generate().unwrap();
let mut ca_params = CertificateParams::new(vec![]).unwrap();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
ca_params
.distinguished_name
.push(DnType::CommonName, "tessera-test-ca");
let ca = ca_params.self_signed(&ca_key).unwrap();
let server_key = KeyPair::generate().unwrap();
let server = CertificateParams::new(vec!["localhost".into()])
.unwrap()
.signed_by(&server_key, &ca, &ca_key)
.unwrap();
let client_key = KeyPair::generate().unwrap();
let mut client_params = CertificateParams::new(vec!["agent".into()]).unwrap();
client_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
let client = client_params.signed_by(&client_key, &ca, &ca_key).unwrap();
let dir = tempfile::tempdir().unwrap();
let write = |name: &str, pem: String| {
let path = dir.path().join(name);
std::fs::write(&path, pem).unwrap();
path
};
let port = {
let probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
probe.local_addr().unwrap().port()
};
let mtls = WormholeMtls {
listen: SocketAddr::from(([127, 0, 0, 1], port)),
cert: load_certs(&write("server.pem", server.pem())).unwrap(),
key: load_key(&write("server.key", server_key.serialize_pem())).unwrap(),
client_ca: load_ca(&write("ca.pem", ca.pem())).unwrap(),
};
let mut state = crate::state::HubState::bootstrap(
dir.path().join("hub").to_str().unwrap(),
"synthetic-vault",
)
.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,167 @@
//! 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),
"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 artifact = manifest
.as_ref()
.and_then(crate::api::artifact)
.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 && !manifest.is_restore_safety()
});
if !belongs {
state
.db
.block_refresh_run(&run.id, "snapshot_not_restorable", now())?;
audit_run(state, &run.id, "blocked");
return Ok(true);
}
let target = state.db.restore_target(Uuid::parse_str(&run.target_id)?)?;
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

@@ -5,7 +5,8 @@ use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
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;
@@ -40,6 +41,10 @@ pub struct HubState {
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
pub admin: AdminGate,
pub sessions: SessionGate,
pub oidc: Option<std::sync::Arc<crate::oidc::OidcProvider>>,
pub limits: Arc<crate::limits::Limits>,
pub exports: Arc<crate::exports::ExportGate>,
pub refresh: Arc<crate::refresh::RefreshConfig>,
pub wormhole_mtls: bool,
/// Token uploads are accepted on this listener. Plain HTTP turns this off
/// when wormhole mTLS is required, so those routes are not a bypass.
@@ -61,15 +66,26 @@ impl HubState {
Vault::init(&vault_path, vault_pass)?
};
let admin = AdminGate::from_env()?;
let oidc_config = crate::oidc::OidcConfig::from_env(admin.local_development)?;
Ok(Self {
db,
db: db.clone(),
data_dir,
offsite: None,
vault: Arc::new(RwLock::new(vault)),
reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())),
active_orbits: Arc::new(Mutex::new(HashSet::new())),
admin: AdminGate::from_env(),
sessions: SessionGate::from_env()?,
admin,
sessions: SessionGate::from_env(
db.clone(),
oidc_config.as_ref().map(|c| c.fingerprint()),
)?,
limits: Arc::new(crate::limits::Limits::from_env()?),
exports: Arc::new(crate::exports::ExportGate::from_env()),
refresh: Arc::new(crate::refresh::RefreshConfig::from_env()),
oidc: oidc_config
.map(|c| crate::oidc::OidcProvider::new(c).map(Arc::new))
.transpose()?,
wormhole_mtls: false,
accept_plain_upload: true,
})
@@ -130,12 +146,13 @@ impl HubState {
for id in jobs {
let offsite = offsite.clone();
let prepared = state.vault.read().await.prepare_offsite_copy(id);
let success = match prepared {
Ok(copy) => offsite.copy_capture(copy).await.is_ok(),
Err(_) => false,
let result = match prepared {
Ok(copy) => offsite.copy_capture(copy).await,
Err(error) => Err(error),
};
if !success {
tracing::warn!(%id, "off-site capture copy failed");
let success = result.is_ok();
if let Err(error) = &result {
tracing::warn!(%id, error = %format!("{error:#}"), "off-site capture copy failed");
}
if state.db.set_offsite_result(id, success).is_err() {
tracing::warn!(%id, "could not save off-site copy status");
@@ -194,15 +211,28 @@ impl HubState {
let Some(profile) = profile else {
return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref());
};
let snapshots = vault
let (safety, captures): (Vec<_>, Vec<_>) = vault
.list_snapshots()?
.into_iter()
.filter(|snapshot| snapshot.manifest.orbit_id == orbit_id)
.partition(|snapshot| snapshot.manifest.is_restore_safety());
let snapshots = captures
.into_iter()
.map(|snapshot| SnapshotRef {
id: snapshot.id,
taken_at: snapshot.taken_at,
})
.collect();
// Safety copies of restore targets have their own retention: they never count as a backup of
// the application, so they can neither displace a capture nor be displaced by one.
let safety: Vec<_> = safety
.into_iter()
.map(|snapshot| SafetyRef {
id: snapshot.id,
taken_at: snapshot.taken_at,
target: snapshot.manifest.safety_target().unwrap_or_default(),
})
.collect();
let expired = match ManagedRetention::resolve(&profile, retention) {
ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots),
ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => {
@@ -210,8 +240,14 @@ impl HubState {
}
};
let mut deletable = Vec::new();
let expired = expired
.into_iter()
.chain(evaluate_safety_retention(safety, chrono::Utc::now()));
for id in expired {
if !active_exports.contains(&id) && !db.offsite_pending(id)? && !db.snapshot_in_restore(id)? {
if !active_exports.contains(&id)
&& !db.offsite_pending(id)?
&& !db.snapshot_in_restore(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> {
let end = offset.checked_add(data.len() as u64).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows")
})?;
let end = offset
.checked_add(data.len() as u64)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows"))?;
if end > total {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
@@ -47,10 +47,7 @@ mod tests {
#[test]
fn out_of_order_chunks_cover_the_object() {
assert_eq!(
contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]),
0
);
assert_eq!(contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]), 0);
assert_eq!(
contiguous_from_zero(&[
ByteRange { start: 4, end: 8 },

View File

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

View File

@@ -30,12 +30,15 @@ pub struct CaptureResult {
pub restore_hints: Value,
}
pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result<Box<dyn BackupProvider>> {
pub fn provider_from_config(
kind: &ProviderKind,
config: &Value,
) -> Result<Box<dyn BackupProvider>> {
match kind {
ProviderKind::Filesystem => Ok(Box::new(FilesystemProvider::from_config(config)?)),
ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)),
ProviderKind::Command => anyhow::bail!(
"command provider is outside this release; use filesystem or postgres"
),
ProviderKind::Command => {
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
}
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)?;
if !preserve_permissions {
args.extend(["--no-owner".into(), "--no-acl".into()]);
@@ -287,7 +292,7 @@ async fn run_pg(
.env_remove("PGPASSWORD")
.stdin(process.stdin)
.stdout(process.stdout)
.stderr(Stdio::null())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.context("starting PostgreSQL client")?
@@ -296,13 +301,41 @@ async fn run_pg(
.context("waiting for PostgreSQL client")?;
anyhow::ensure!(
output.status.success(),
"{} failed ({})",
"{} failed ({}){}",
process.program,
output.status
output.status,
client_reason(&output.stderr)
);
Ok(output)
}
/// The reason a PostgreSQL client gave for failing, reduced to what is safe to report: only the primary
/// `ERROR:`/`FATAL:` lines. `DETAIL`, `CONTEXT`, `LINE`, `STATEMENT` and `HINT` are left out because they
/// quote rows and statements, and the location prefix (`psql:-:1234:`) is not needed. At most two lines.
pub(crate) fn client_reason(stderr: &[u8]) -> String {
let text = String::from_utf8_lossy(stderr);
let lines: Vec<String> = text
.lines()
.filter_map(|line| {
let line = line.trim();
let line = match line.find(": ").filter(|_| line.starts_with("psql:")) {
Some(_) => line.splitn(4, ':').nth(3).unwrap_or(line).trim(),
None => line,
};
let primary = ["ERROR:", "FATAL:", "pg_dump: error:", "pg_restore: error:"]
.iter()
.any(|prefix| line.starts_with(prefix));
primary.then(|| line.to_string())
})
.take(2)
.collect();
if lines.is_empty() {
String::new()
} else {
format!(": {}", lines.join(" | "))
}
}
fn write_pgpass(target: &PgTarget, any_database: bool) -> Result<tempfile::NamedTempFile> {
let fields = [
&target.host,
@@ -353,6 +386,23 @@ impl BackupProvider for PostgresProvider {
#[cfg(test)]
mod tests {
#[test]
fn a_client_failure_names_its_error_without_quoting_data() {
let stderr =
b"psql:-:42: ERROR: duplicate key value violates unique constraint \"users_pkey\"\n\
DETAIL: Key (email)=(alice@example.test) already exists.\n\
CONTEXT: COPY users, line 7: \"7\\talice@example.test\"\n\
psql:-:99: ERROR: schema \"drizzle\" already exists\n";
let reason = client_reason(stderr);
assert_eq!(
reason,
": ERROR: duplicate key value violates unique constraint \"users_pkey\" | ERROR: schema \"drizzle\" already exists"
);
assert!(!reason.contains("alice") && !reason.contains("COPY"));
assert_eq!(client_reason(b""), "");
assert_eq!(client_reason(b"just noise\n"), "");
}
use super::*;
use std::os::unix::fs::PermissionsExt;

View File

@@ -20,6 +20,11 @@ pub enum PostgresReset {
#[serde(default = "public")]
schema: String,
},
/// Empty every non-system schema of the database (not only `public`), in the same transaction as the
/// restore. For databases that keep tables in several schemas, so that a dump's `CREATE SCHEMA` for
/// one of them does not collide with the copy already there. Roles, extensions' own catalog entries,
/// publications and other objects that live outside schemas are left alone.
UserSchemas,
RecreateDatabase,
}
@@ -118,6 +123,15 @@ impl PostgresRestore {
writeln!(script, "CREATE SCHEMA public;")?;
}
}
PostgresReset::UserSchemas => {
writeln!(script, "BEGIN;")?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(
script,
"DO $tessera$\nDECLARE s text;\nBEGIN\n FOR s IN SELECT nspname FROM pg_catalog.pg_namespace\n WHERE nspname !~ '^pg_' AND nspname <> 'information_schema'\n LOOP\n EXECUTE pg_catalog.format('DROP SCHEMA %I CASCADE', s);\n END LOOP;\nEND\n$tessera$;"
)?;
writeln!(script, "CREATE SCHEMA public;")?;
}
PostgresReset::RecreateDatabase => {
ensure!(
expected
@@ -137,12 +151,23 @@ impl PostgresRestore {
writeln!(script, "BEGIN;")?;
}
}
// The dump's own CREATE EXTENSION for pg_stat_statements is left out on request, but the reset has
// already dropped the extension the target had. Put it back where it was so its views and functions
// survive; a target that never had it still does not get it.
let preserved = if self.omit_pg_stat_statements {
self.extension_schema("pg_stat_statements").await?
} else {
None
};
let key = uuid::Uuid::new_v4().simple();
writeln!(script, "\\restrict {key}")?;
let skip_timeout = self.omit_transaction_timeout;
let skip_extension = self.omit_pg_stat_statements;
let create_public =
matches!(&self.mode, PostgresReset::Schema { schema } if schema == "public");
let create_public = match &self.mode {
PostgresReset::Schema { schema } => schema == "public",
PostgresReset::UserSchemas => true,
PostgresReset::RecreateDatabase => false,
};
let post_sql = self.post_restore_sql.clone();
tokio::task::spawn_blocking(move || {
append_dump(
@@ -152,6 +177,9 @@ impl PostgresRestore {
skip_extension,
create_public,
)?;
if let Some(schema) = preserved {
script.write_all(keep_extension_sql("pg_stat_statements", &schema).as_bytes())?;
}
if let Some(path) = post_sql {
io::copy(
&mut fs::File::open(path).context("read local post-restore SQL")?,
@@ -165,12 +193,43 @@ impl PostgresRestore {
.await?
}
/// The schema an extension is installed in on the target right now, if it is installed.
async fn extension_schema(&self, name: &str) -> Result<Option<String>> {
let query = format!(
"SELECT n.nspname FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = {}",
literal(name)
);
let args = ["-X", "-w", "-q", "-At", "-c"]
.map(String::from)
.into_iter()
.chain([query])
.collect::<Vec<_>>();
let output = self
.connection
.run("psql", &args, None, Stdio::null(), Stdio::piped())
.await?;
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok((!text.is_empty()).then_some(text))
}
pub async fn apply(&self, script: File) -> Result<()> {
let database = match self.mode {
PostgresReset::RecreateDatabase => Some("postgres"),
PostgresReset::Schema { .. } => 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
.run("psql", &args, database, Stdio::from(script), Stdio::null())
.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 {
format!("'{}'", value.replace('\'', "''"))
}
@@ -188,19 +253,29 @@ fn identifier(value: &str) -> String {
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
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)
.stdin(Stdio::from(input))
.stdout(Stdio::from(file.try_clone()?))
.stderr(Stdio::null())
.stderr(Stdio::piped())
.kill_on_drop(true)
.status()
.spawn()
.context("prepare PostgreSQL restore script")?
.wait_with_output()
.await
.context("prepare PostgreSQL restore script")?;
ensure!(
status.success(),
"{executable} rejected the restore archive"
);
if !output.status.success() {
if executable == "pg_restore" {
let local = local_client_version("pg_restore").await;
anyhow::bail!(
"{}",
explain_restore_failure(header.as_ref(), local.as_deref(), &output.stderr)
);
}
anyhow::bail!("{executable} rejected the restore archive");
}
ensure!(
file.metadata()?.len() > 0,
"empty PostgreSQL restore script"
@@ -208,6 +283,146 @@ async fn convert(input: File, executable: &str, args: &[&str]) -> Result<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(
data: File,
script: &mut File,
@@ -263,3 +478,420 @@ fn append_dump(
}
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
edition.workspace = true
license.workspace = true
publish = false
[dependencies]
tessera-core = { path = "../tessera-core" }

View File

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

View File

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

View File

@@ -14,7 +14,8 @@ use tessera_core::decay::{
use tessera_core::manifest::SnapshotManifest;
use uuid::Uuid;
const RESTIC_CONFIG: &str = "{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n";
const RESTIC_CONFIG: &str =
"{\n \"version\": 2,\n \"id\": \"tessera-restic-layout-v1\",\n \"tessera\": true\n}\n";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredSnapshot {
@@ -173,11 +174,15 @@ impl Vault {
restic_id: &str,
) -> Result<StoredSnapshot> {
let config = self.outpost_config(manifest.orbit_id)?;
anyhow::ensure!(config.outpost_id == outpost_id, "repository belongs to another outpost");
anyhow::ensure!(
config.outpost_id == outpost_id,
"repository belongs to another outpost"
);
let repo = self.outpost_repository(manifest.orbit_id, config);
let id = manifest.snapshot_id;
let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD);
let summary = repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?;
let summary =
repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?;
Ok(StoredSnapshot {
id,
taken_at: Utc::now(),
@@ -310,7 +315,13 @@ impl Vault {
repo.init()
.context("opening the deduplicated vault (restic must be on PATH)")?;
let mut cmd = repo.command();
cmd.args(["backup", "--json", "--quiet", "--tag", &restic::tessera_tag(manifest.snapshot_id)]);
cmd.args([
"backup",
"--json",
"--quiet",
"--tag",
&restic::tessera_tag(manifest.snapshot_id),
]);
if dry_run {
cmd.arg("--dry-run");
}
@@ -339,7 +350,10 @@ impl Vault {
}
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> {
let id = manifest.snapshot_id;
let receipts = self.root.join("keys/legacy-imports");
@@ -351,7 +365,8 @@ impl Vault {
}
let snapshots = self.root.join("snapshots");
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()? {
false
@@ -378,18 +393,32 @@ impl Vault {
}
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};
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()?;
self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?;
file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
std::io::copy(&mut file, &mut digest)?;
anyhow::ensure!(digest.finalize()[..] == expected[..], "stored payload checksum mismatch");
anyhow::ensure!(
digest.finalize()[..] == expected[..],
"stored payload checksum mismatch"
);
Ok(())
}
@@ -405,7 +434,11 @@ impl Vault {
}
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 {
@@ -552,15 +585,33 @@ impl Vault {
}
pub fn prepare_offsite_copy(&self, id: Uuid) -> Result<crate::OffsiteCopy> {
let snapshot = self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?;
anyhow::ensure!(snapshot.manifest.restore_hints.get("job_id").is_some(), "snapshot is not a capture job");
let (source, restic_id) = if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit = snapshot.manifest.orbit_id;
(self.outpost_repository(orbit, self.outpost_config(orbit)?), id)
} else {
(self.restic.clone(), snapshot.tree_root.strip_prefix(restic::PREFIX).context("capture Restic snapshot missing")?)
};
Ok(crate::OffsiteCopy { snapshot: id, source, restic_id: restic_id.to_owned() })
let snapshot =
self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?;
anyhow::ensure!(
snapshot.manifest.restore_hints.get("job_id").is_some(),
"snapshot is not a capture job"
);
let (source, restic_id) =
if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit = snapshot.manifest.orbit_id;
(
self.outpost_repository(orbit, self.outpost_config(orbit)?),
id,
)
} else {
(
self.restic.clone(),
snapshot
.tree_root
.strip_prefix(restic::PREFIX)
.context("capture Restic snapshot missing")?,
)
};
Ok(crate::OffsiteCopy {
snapshot: id,
source,
restic_id: restic_id.to_owned(),
})
}
pub fn get_snapshot(&self, id: Uuid) -> Result<Option<StoredSnapshot>> {
@@ -574,7 +625,9 @@ impl Vault {
}
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
.parent()
.filter(|p| !p.as_os_str().is_empty())
@@ -583,7 +636,11 @@ impl Vault {
let mut temp = tempfile::NamedTempFile::new_in(parent)?;
if let Some(id) = snap.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit_id = snap.manifest.orbit_id;
let path = if snap.manifest.restore_hints["format"] == "tar" { "/" } else { restic::PAYLOAD };
let path = if snap.manifest.restore_hints["format"] == "tar" {
"/"
} else {
restic::PAYLOAD
};
self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?)
.dump(id, path, temp.reopen()?)?;
} else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
@@ -682,9 +739,15 @@ impl Vault {
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let snaps = self.list_snapshots()?;
self.prune_snapshots(preset, None, snaps.into_iter()
.filter(|snapshot| snapshot.manifest.provider != "legacy-history"
&& snapshot.manifest.restore_hints.get("job_id").is_none()))
self.prune_snapshots(
preset,
None,
snaps.into_iter().filter(|snapshot| {
snapshot.manifest.provider != "legacy-history"
&& snapshot.manifest.restore_hints.get("job_id").is_none()
&& !snapshot.manifest.is_restore_safety()
}),
)
}
pub fn prune_orbit_with_decay(
@@ -699,7 +762,7 @@ impl Vault {
retention,
snaps
.into_iter()
.filter(|s| s.manifest.orbit_id == orbit_id),
.filter(|s| s.manifest.orbit_id == orbit_id && !s.manifest.is_restore_safety()),
)
}
@@ -829,9 +892,7 @@ mod tests {
paths: vec![],
restore_hints: serde_json::json!({}),
};
let snap = vault
.snapshot(manifest, b"payload bytes", false)
.unwrap();
let snap = vault.snapshot(manifest, b"payload bytes", false).unwrap();
let list = vault.list_snapshots().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].id, snap.id);
@@ -918,7 +979,9 @@ mod tests {
new_data_chunks: None,
};
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(),
)
.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
```
Always pass `--credentials`: only then is the upload token written to the file and kept out of the terminal. Without it, `pair` prints `TESSERA_UPLOAD_TOKEN=…` to stdout, where shell history, logs and CI output can capture it. The file must not exist yet, and its directory must be writable by the account that runs `pair` (for a service account, use its home directory rather than a root-owned `/etc` path, or create the file as root and `chown` it to the service account with mode 0600 before `run`).
The credentials file is owner-only and contains the hub URL, outpost UUID and upload token. Keep it outside the repository. TLS uses the system trust store. Set `TESSERA_WORMHOLE_CA` for a private CA and configure both `TESSERA_WORMHOLE_CLIENT_CERT` and `TESSERA_WORMHOLE_CLIENT_KEY` for a hub that requires mTLS. Plain HTTP capture is available on loopback for local testing.
## Register an application
@@ -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.
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,6 +93,20 @@ Use the snapshot detail to download or remove an archive. Database snapshots can
## Operator sign-in
Authentication is required by default, including requests from loopback and a
local reverse proxy. Before upgrading, configure the emergency operator hash/name
and/or the separate API admin token. Startup refuses a hub without credentials.
An existing install with neither configured must bootstrap credentials locally
before restarting; there is no first-user auto-admin or public registration.
Use a named individual emergency operator, not a shared daily SSO account.
For synthetic local development only, `TESSERA_LOCAL_DEVELOPMENT=true` explicitly
enables anonymous loopback access when no operator/token is configured. Both
listeners must bind loopback; wildcard and non-loopback binds are rejected.
Forwarded requests are rejected in this mode, but that is not a proxy trust
boundary: never reverse-proxy a development listener. Compose keeps the mode off
and needs operator/API credentials even with a localhost published port.
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
@@ -95,6 +117,17 @@ 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.
Legacy full-upload agents now need an explicit orbit assignment. With operator
CSRF or an admin API token, call `PUT /api/v1/orbits/{orbit-id}/outpost` with
`{"outpost_id":"<paired-outpost-uuid>"}`. Only active paired Outposts and legacy
Wormhole orbits are accepted; managed capture assignment remains on its profile.
Existing unassigned orbits and upload sessions without an owner fail closed.
Review the mapping, bind the orbit, then restart the upload to obtain a new owned
session. No owner is inferred from a name or an old token. This does not delete
old snapshots or partial uploads; operators can remove abandoned partial files
after stopping the old agent. Rebinding invalidates in-flight uploads from the
previous Outpost.
## Optional S3 copy
Configure `TESSERA_OFFSITE_REPOSITORY=s3:https://s3.example.org/tessera-backups/managed` with a dedicated prefix and point `TESSERA_OFFSITE_PASSWORD_FILE` to the independent Restic password. Supply AWS credentials via the hub service environment or the provider's credential chain. In Docker, mount the password file at the container path using a read-only mount.
@@ -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.
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
@@ -148,3 +189,224 @@ 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).
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. 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.
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. 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

@@ -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.
- Select a star or use the orbit register. The register prioritizes failed and active jobs and supports the up/down arrow keys. The inspector includes the capture action and full snapshot history.
- The first three recovery points of the selected orbit appear as moons when the map has room. Select a moon or history entry to review the snapshot and start a restore. Escape closes the console. Restore countdown and polling continue if the console closes.
- Hub connectivity is separate from backup health. Capture targets the named orbit. 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.
- **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.
- 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.
- 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.
- 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.
- **Big Screen** is a holographic visor. The map fills the viewport, and every piece of the workspace has a counterpart there and springs to it with `useScreenTransition` rather than popping. There are no panels or plates, only light: thin mint lines and glowing text, a vignette and faint scan over the scene, four corner brackets and a glass edge. Top left, the brand and the map's mode (Flowing, or Locked with the orbit). Top right, the four telemetry readings with their lamps. Bottom left, the legend. Bottom centre, the systems as text, the active one held in a glowing frame (it can still be dragged), and an ember label for Activity while something needs you. Bottom right, the Window | Radar words with a sliding underline, the motion and exit keys, then search and sign out as outlined circles, with the hub's state above them. The register, the inspector, the canopy frame and the sill captions fade out; every orbit is labelled on the map, each on a dark glass chip so the radar's grid cannot swallow it (up to 60, each placed clear of the others; the workspace map shows 12), and the picked orbit's label stands off its star on an elbowed leader line, with its status beneath. Use **Exit big screen** or Escape to return to the workspace. Below 900 px the legend is hidden and the controls sit above the systems; below 520 px the brand and telemetry are hidden too and the view switch shows icons.
- Drag the active navbar item sideways and release to open the destination. The regular navbar is a tray of switches with a sliding pill. Big Screen uses the same text tabs with a glowing frame in place of the pill.
- The navbar stays available above the side panel so you can switch directly between consoles. In the regular workspace it becomes a floating text dock in the same top position. Big Screen keeps its tabs at the bottom.
- Use **Search**, **⌘K**, or **Ctrl+K** from the vault, a console, or Big Screen. An empty field shows navigation shortcuts. Type to find destinations, orbits by name, ID, or provider, and snapshots by orbit name, ID, or displayed capture date. Search uses the summaries already loaded by the vault. Use the arrow keys and Enter, or select a result with a pointer. Escape closes search and returns focus to its button. Search is a spotlight panel over a dimmed, lightly blurred deck: a large input, grouped results with a kind label on the right (the active row adds an Enter mark), a footer of key hints and the result count, and a "No signal" message when nothing matches.
## 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
- The map preserves each orbit's assigned slot across polling updates. Layout and snapshot grouping live in `web/src/lib/galaxyLayout.ts`.
- Snapshot summaries carry `orbit_id`. When connected to an older hub, the UI groups by name only if the name is unique.
- Successful capture preserves HTTP 204 and supplies `X-Tessera-Snapshot-Id` when it retained a new snapshot. Automatic decay applies to that orbit's history.
- The 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. `web/blackhole-proto.html` is a standalone page for tuning the look; Vite serves it in development and the build ignores it. Add `?throttle=N` to emulate a GPU N times slower.
## 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
@@ -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 `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.
- 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.
- 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,89 @@
# Kontrak otorisasi HTTP
Inventaris A01, 11 November 2026. Gate saat ini masih admin global; kolom
permission/scope adalah kontrak yang harus diterapkan A11–A12, bukan klaim RBAC
sudah tersedia. A02 menutup isolasi upload legacy; A03 menghapus fallback loopback.
Gate (M5): `authenticate` lalu resolve resource lalu gate. Permission yang dapat diberikan ke non-admin hanya `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download`; semua permission lain hanya dimiliki administrator terkonfigurasi (403 tanpa lookup resource). Resource di luar scope = 404, terlihat tapi tanpa izin = 403, daftar tanpa satu pun akses = 403. Tes `access_tests` membangkitkan matriks dari tabel ini.
Human = sesi user aktif atau service token dengan grant; token Outpost ditolak.
Mutasi cookie memerlukan CSRF. Anonymous/token salah: 401; resource di luar scope:
404; aksi tanpa permission pada resource terlihat: 403. Parsing request invalid
dapat menghasilkan 400/415/422 sebelum gate, tetapi tidak boleh mengakses data.
Outpost = token aktif, assignment owner dan lease/fence bila berlaku; bukan token
admin/browser. Semua status/data job hanya di scope owner/admin yang berizin.
| Route | Methods | Principal | Permission | Scope | Data yang boleh keluar |
| --- | --- | --- | --- | --- | --- |
| /health | GET | public | — | — | liveness statis |
| /api-doc/openapi.json | GET | public | — | — | schema tanpa config/secret |
| /api/v1/operator/session | GET | public | — | current session | status, actor, CSRF sesi sendiri; no-store |
| /api/v1/operator/session | DELETE | human | session.self | current session | tidak ada; CSRF wajib |
| /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 | daftar grant, grant refresh per relasi, role, permission yang dapat diberikan dan yang khusus admin; no-store |
| /api/v1/access/grants | POST,PUT | human | access.manage | admin | POST: grant baru (role, permission, atau daftar permission; scope global/orbit; expiry); PUT: ganti atau perpanjang sekumpulan grant orang/grup dan orbit yang sama secara atomik; alasan penolakan dalam `{"reason"}`; diaudit per id |
| /api/v1/access/grants/:id | DELETE | human | access.manage | admin | tidak ada; berlaku pada request berikutnya; diaudit |
| /api/v1/access/users | GET | human | access.manage | admin | daftar user (tanpa kredensial); no-store |
| /api/v1/access/users/:id | PUT | human | access.manage | admin | tidak ada; menonaktifkan juga memutus semua sesi; tidak untuk diri sendiri/akun darurat |
| /api/v1/access/users/:id/revoke-sessions | POST | human | access.manage | admin | tidak ada; semua sesi user berakhir |
| /api/v1/me/preferences | GET,PUT | human | session.self | current account | pilihan tampilan sendiri (look: window atau radar); no-store; CSRF pada PUT; token/dev tanpa akun: GET kosong, PUT 404 |
| /api/v1/orbits/:id | PUT | human | orbit.manage | admin | hanya name (1-128, tanpa karakter kontrol, unik tanpa memedulikan huruf besar); id, provider, jadwal, retensi tidak berubah; snapshot lama tampil dengan nama terkini; diaudit `orbit.renamed` |
| /api/v1/orbits/:id/environment | PUT | human | orbit.manage | admin | tidak ada; menandai sumber (production/staging/development); diaudit |
| /api/v1/restore-targets/:id | PUT | human | relation.manage | admin | hanya name (1-128, tanpa karakter kontrol); id, identity, outpost, relasi, dan job lama tidak berubah; diaudit `restore_target.renamed` |
| /api/v1/restore-targets/:id/environment | PUT | human | relation.manage | admin | relasi aktif ke target yang diberi label production berakhir seketika; diaudit |
| /api/v1/relations | GET,POST | human | relation.manage | admin | daftar relasi, orbit dan target untuk wizard (dengan identity); POST membuat relasi atau menyebut aturan yang menolak |
| /api/v1/relations/:id | PUT,DELETE | human | relation.manage | admin | PUT = versi baru (id baru, grant tidak ikut); DELETE menonaktifkan; diaudit |
| /api/v1/relations/:id/access | GET,POST | human | relation.manage | admin | grant refresh.run per relasi (user atau grup, expiry); diaudit |
| /api/v1/relations/:id/access/:grant | DELETE | human | relation.manage | admin | berlaku pada request berikutnya; diaudit |
| /api/v1/refresh-relations | GET | human | refresh.run | relasi yang di-grant | nama dan environment saja; tanpa identity, host, Outpost, application id; 403 bila tanpa grant |
| /api/v1/refresh-runs | GET,POST | human | refresh.run | relasi yang di-grant | POST: relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; `snapshot_id` opsional: restore snapshot yang sudah ada milik orbit sumber relasi itu (bukan safety, bukan orbit lain; 422 `snapshot_unusable`), tanpa itu run mengambil capture baru; tidak memilih target; 404 bila bukan pemegang grant; GET: run milik sendiri atau relasi yang di-grant (admin: semua), tanpa snapshot id dan pemohon untuk non-admin |
| /api/v1/refresh-runs/:id | GET,DELETE | human | refresh.run | admin, pemohon, atau pemegang grant relasinya | GET 404 bagi yang lain; DELETE hanya pemohon atau admin (pemegang grant lain 403) dan hanya sebelum apply, sesudahnya 409 |
| /api/v1/operator/login | POST | public | — | emergency account | cookie opaque dan CSRF; limiter, no-store |
| /api/v1/snapshots | GET | human | snapshot.read | orbit | metadata aman terfilter |
| /api/v1/snapshots/:id | DELETE | human | snapshot.delete | snapshot→orbit | tidak ada; cek pin |
| /api/v1/snapshots/:id/download | GET | human | snapshot.download | snapshot→orbit | arsip mentah: gzip atau format yang sudah terkompresi (`.sql.gz`, `.tar.gz`, `.sqlite.gz`, `.dump`), tanpa Content-Encoding, no-store, nosniff; HEAD 405; slot ekspor dan disk dibatasi |
| /api/v1/orbits | GET | human | orbit.read | orbit | metadata tanpa provider_config |
| /api/v1/orbits | POST | human | orbit.manage | admin | metadata aman |
| /api/v1/orbits/:id/retention | PUT | human | retention.manage | orbit | tidak ada |
| /api/v1/orbits/:id/run | POST | human | capture.run | orbit | job/status aman |
| /api/v1/orbits/:id/outpost | PUT | human | outpost.manage | orbit | assignment eksplisit legacy; managed lewat capture profile |
| /api/v1/reconstitute | POST | human | recovery.manage | snapshot→orbit | sesi restore administratif, bukan self-service |
| /api/v1/reconstitute/:id | GET,DELETE | human | recovery.manage | restore session→snapshot→orbit | status aman; cancel sebelum apply |
| /api/v1/wormhole/outposts | GET | human | outpost.manage | admin | nama/status; tanpa token |
| /api/v1/wormhole/pairing | POST | human | outpost.manage | admin | code berumur pendek |
| /api/v1/wormhole/claim | POST | public | pairing.consume | one-time code | token baru sekali ke claimant; limiter per sumber + global, kode tersimpan sebagai digest |
| /api/v1/wormhole/outposts/:id/rotate | POST | human | outpost.manage | paired Outpost | token baru sekali (no-store); token lama hidup selama grace; audit |
| /api/v1/wormhole/outposts/:id/revoke | POST | human | outpost.manage | Outpost | tidak ada; semua kredensial ditolak pada request berikutnya; audit |
| /api/v1/wormhole/upload/init | POST | outpost | upload.assigned | orbit owner | session ID milik owner |
| /api/v1/wormhole/upload/chunk | POST | outpost | upload.assigned | session owner + orbit owner | tidak ada |
| /api/v1/wormhole/restic/commit | POST | outpost | upload.assigned | orbit owner + repository owner | snapshot ID owner |
| /api/v1/capture-profiles | GET | human | orbit.read | profile→orbit | profile terfilter; tanpa DSN |
| /api/v1/capture-profiles | POST | human | orbit.manage | orbit | profile aman |
| /api/v1/capture-profiles/:id | PUT | human | orbit.manage | admin | hanya schedule dan retention (absen = tetap, null = hapus); validasi sama dengan POST; kursor jadwal maju ke saat perubahan; diaudit |
| /api/v1/capture-profiles/:id/jobs | POST | human | capture.run | profile→orbit | job aman |
| /api/v1/capture-jobs | GET | human | orbit.read | job→orbit | histori terfilter |
| /api/v1/capture-jobs/:id | GET | human | orbit.read | job→orbit | status aman |
| /api/v1/capture-jobs/:id/events | GET | human | orbit.read | job→orbit | phase/timestamp tanpa log DB |
| /api/v1/wormhole/capture/:application/claim | POST | outpost | capture.assigned | profile owner | lease milik owner |
| /api/v1/wormhole/capture/:id/report | POST | outpost | capture.assigned | job owner + lease | tidak ada |
| /api/v1/wormhole/capture/:id/payload | POST | outpost | capture.assigned | job owner + lease | tidak ada |
| /api/v1/wormhole/capture/:id/restic | POST | outpost | capture.assigned | job owner + lease + repository | commit owner |
| /api/v1/restore-targets | POST | human | orbit.manage | target→orbit | identity terverifikasi admin; tanpa kredensial |
| /api/v1/capture-profiles/:id/restore-targets | GET | human | recovery.manage | admin | identity target (instance/database) hanya untuk admin sampai self-service M6; tanpa kredensial |
| /api/v1/snapshots/:id/restore-targets | GET | human | recovery.manage | admin | identity target hanya untuk admin sampai self-service M6; tanpa kredensial |
| /api/v1/restore-jobs | GET,POST | human | recovery.manage | admin | restore administratif dan daftar terbaru; refresh.run lewat relasi terpisah (M6) |
| /api/v1/snapshots/:id/restore-jobs | GET | human | recovery.manage | admin | histori restore memuat target dan aktor; admin saja sampai M6 |
| /api/v1/restore-jobs/:id | GET,DELETE | human | recovery.manage | job→snapshot + target | status aman; cancel sebelum apply |
| /api/v1/restore-jobs/:id/reconcile | POST | human | recovery.manage | job→target | status recovery admin |
| /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 hanya agent |
| /api/v1/wormhole/restore/:id/report | POST | outpost | restore.assigned | job owner + lease/fence | tidak ada |
| /api/v1/wormhole/restore/:id/safety | POST | outpost | restore.assigned | job owner + lease/fence | safety snapshot owner |
| /api/v1/wormhole/restore/:id/apply | POST | outpost | restore.assigned | job owner + lease/fence | izin apply setelah revalidasi |
SPA/assets publik berisi UI statis, bukan data vault. GET juga menerima HEAD sesuai
Axum, dengan gate sama. Aksi refresh internal tidak memberikan capture.run bebas
atau snapshot.download. Recovery legacy tetap jalur admin dan tidak menjadi jalan
pintas refresh self-service.

View File

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

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

@@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Build a clean, single-commit tree for the public repository. Nothing is pushed.
# Usage: scripts/export-public.sh /path/to/empty-dir
set -euo pipefail
out="${1:?target directory}"
[ -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"
# Deployment-specific and planning material stays in the private repository.
rm -rf "$out/tasks" "$out/tests/mbu" "$out/docs/MBU-BACKUP-PARITY.md" "$out/docs/MBU-CUTOVER.md" "$out/floorplan" "$out/graft"
if grep -rIlE "mbugroup|backup\.mbu|hafizh|senkensha\.space" "$out" --exclude-dir=node_modules --exclude=export-public.sh >/dev/null; then
echo "private references remain:" >&2
grep -rIlE "mbugroup|backup\.mbu|hafizh|senkensha\.space" "$out" --exclude-dir=node_modules --exclude=export-public.sh >&2
exit 1
fi
echo "clean tree at $out; review it, then: git init && git add -A && git commit"

View File

@@ -0,0 +1,212 @@
# Rencana implementasi auth, OIDC, RBAC, dan self-service data
Tanggal: 11 November 2026. Status: fondasi A01–A04 diimplementasikan; A00 masih memiliki temuan audit. OIDC, RBAC scoped dan workflow self-service belum tersedia.
Daftar tugas: [auth-self-service-todo.md](auth-self-service-todo.md).
Riset library/tool per task dan keputusan reuse: [auth-self-service-libraries.md](auth-self-service-libraries.md).
Rencana MBU pada plan.md/todo.md dipertahankan; ini perluasan akses dan workflow di atas capture/restore yang sudah tersedia.
## 1. Hasil yang dituju
DevOps mendaftarkan sumber production dan tujuan staging, memverifikasi identitas database, membuat relasi berarah, dan memberi akses kepada akun/grup. QA masuk dengan akun sendiri, memilih relasi yang diizinkan, meminta dump baru, dan memulihkan snapshot hasil job itu ke staging. Developer masuk dengan akun sendiri, memilih orbit yang diizinkan, dan mengunduh snapshot sebagai arsip terkompresi; dapat meminta capture baru jika diberi izin terpisah.
Tidak ada persetujuan DevOps per eksekusi setelah relasi dan grant disiapkan. QA tetap mengonfirmasi tujuan yang akan ditimpa. Hak restore tidak otomatis memberikan hak download, dan hak download tidak otomatis memberikan hak capture.
## 2. Asumsi dan batas awal
- Satu organisasi dan satu hub aktif, SQLite tetap digunakan. Multi-tenant/multi-replica bukan bagian rilis ini.
- Satu issuer OIDC tepercaya per deployment pada rilis awal; login normal melalui SSO. Akun lokal yang ada menjadi admin darurat, bukan akun bersama pengguna harian.
- Kredensial database tetap di agent/config lokal DevOps; pengguna tidak boleh memasukkan host, DSN, perintah SQL, atau path tujuan bebas.
- MVP QA memakai capture profile database managed yang sudah memiliki metadata integritas/identitas dan Outpost. Orbit hub/legacy yang belum restore-ready tetap dapat dilihat/diunduh sesuai grant tetapi tidak ditawarkan sebagai sumber refresh otomatis. UI menyebut alasan dan langkah konversinya.
- Production adalah sumber; target production ditolak oleh workflow self-service meskipun admin memiliki banyak izin. Pemulihan bencana production tetap melalui jalur administrasi terpisah.
- Data asli dapat diizinkan sesuai kebutuhan tim. Tidak menambahkan masking diam-diam; ekspor raw production adalah izin eksplisit dengan pemberitahuan dan audit. Data yang sudah diunduh tidak dapat dicabut dari laptop oleh Tessera.
- Durasi dump, versi PostgreSQL/MySQL, IdP, batas unduhan, dan kebijakan raw-data mengikuti deployment; angka awal di bawah adalah default usulan.
## 3. Peta capability dan urutan
| Modul | Tanggung jawab | Dependensi |
| --- | --- | --- |
| access-foundation | Principal, gate server, audit, isolasi agent/token | — |
| identity | OIDC, sesi individual, akun darurat | access-foundation |
| scoped-access | Grant aksi/resource, role, administrasi akses | identity |
| orbit-relations | Environment, binding target, relasi sumber → tujuan | scoped-access |
| refresh | Capture baru → snapshot spesifik → restore durable | orbit-relations |
| compressed-export | Ekspor terkompresi, kuota, streaming, audit | scoped-access |
| release-verification | Migrasi, regresi, uji IdP dan dua user story | semua |
Urutan: compatibility spike library (A00) → tutup celah akses → identitas → permission → relasi → refresh dan export → rollout. Perbaikan isolasi/fail-closed A01–A03 tidak perlu menunggu spike library yang independen.
Tidak menambah policy engine eksternal, message broker, atau workflow engine; gunakan gate terpusat dan transaksi/job SQLite yang sudah ada.
Temuan aktual A00: baseline sesuai rencana tetapi RustSec tidak bersih (10 vulnerability baseline dan warning unsound Tokio). Spike membuktikan tower-sessions 0.15 dapat dipakai melalui Extension tanpa upgrade Axum. Time/TLS fixture telah diperbaiki; remediation SQLite/Tokio runtime dan triage RSA tetap wajib sebelum dependency auth siap rilis. A05 dapat melanjutkan primitive existing secara independen; A07/A09/A11 tidak boleh menganggap A00 sudah diterima. Bila patched SQLite memerlukan compiler/binding baru, buat slice upgrade tersendiri dengan fixture DB lama. Bukti: `tests/auth-compat/README.md`.
## 4. Model akses
RBAC menentukan kumpulan aksi; grant resource dan relasi menentukan di mana aksi berlaku. Nama QA/developer tidak otomatis memberikan akses seluruh production.
| Aksi | Admin DevOps | QA pada scope grant | Developer pada scope grant |
| --- | --- | --- | --- |
| Lihat orbit/snapshot dan status yang aman | Ya | Ya | Ya |
| Kelola orbit/profile/Outpost/relasi | Ya | Tidak | Tidak |
| Kelola user/group/grant/token | Ya | Tidak | Tidak |
| Minta capture baru | Ya | Bila diberi capture.run | Bila diberi capture.run |
| Refresh staging | Ya, tetap lewat relasi valid | Bila diberi refresh.run pada relasi | Hanya bila diberi grant tersebut |
| Download snapshot raw | Grant eksplisit untuk data sensitif | Default tidak | Bila diberi snapshot.download |
| Ubah retensi/hapus snapshot/reconcile recovery | Ya | Tidak | Tidak |
| Restore production melalui self-service | Tidak | Tidak | Tidak |
Permission awal: orbit.read, snapshot.read, capture.run, refresh.run, snapshot.download, orbit.manage, relation.manage, access.manage, outpost.manage, retention.manage, snapshot.delete, recovery.manage, audit.read. Backend memeriksa permission pada resource aktual; daftar/filter UI hanya membantu pengalaman pengguna.
Principal memuat ID stabil, jenis user/service/outpost, status aktif, dan auth method. Tidak memakai display name/email sebagai identitas unik. Service token mendapatkan grant eksplisit; token agen tidak pernah menjadi token pengguna.
QA dengan refresh.run pada relasi boleh memicu capture sebagai langkah internal workflow itu, tetapi tidak memperoleh endpoint capture bebas atau download payload. Grant snapshot.download pada orbit berlaku pada snapshot orbit tersebut, termasuk snapshot baru; ini dinyatakan jelas di UI admin. Histori workflow dapat dilihat pemilik dan admin; user lain memerlukan grant scope yang sesuai.
Aturan gate: authenticated + active + aksi diizinkan + resource dalam scope + constraint relasi/identitas terpenuhi. Resource di luar scope dikembalikan konsisten sebagai 404; role tidak berhak pada resource yang terlihat mendapat 403. Semua endpoint lama, endpoint agent, ekspor, dan akses langsung lewat UUID harus tercantum dalam matriks otorisasi.
## 5. Identitas OIDC dan sesi
- Hub menjadi confidential OIDC client; Authorization Code + PKCE S256. Secret dan token IdP hanya di backend.
- Discovery dari issuer terkonfigurasi HTTPS; exact issuer matching, client authentication sesuai metadata/provider yang didukung, redirect URI publik statis. Jangan membentuk callback dari Host/X-Forwarded-* yang tidak tepercaya.
- Validasi state, nonce, PKCE, signature/alg allowlist, iss, aud, azp bila relevan, exp/iat dan clock skew terbatas. Transaksi login singkat, sekali pakai, dan diikat ke browser; JWKS cache bounded dengan refresh terkendali untuk kid baru, tanpa menerima token yang gagal verifikasi.
- Identitas unik (issuer, subject). Email/display name hanya atribut. Tidak auto-link akun berdasarkan email dan tidak auto-admin bagi user pertama yang masuk.
- User baru tanpa grant mendapat halaman belum memiliki akses. Bootstrap admin memakai konfigurasi subject eksplisit/operasi lokal yang diaudit, bukan role dari parameter callback.
- Grup OIDC dipetakan lewat konfigurasi claim yang diizinkan, dengan mapping eksplisit. Direct user grants tersedia. Claim grup hilang/terpotong tidak memperluas hak; jelaskan cara sinkronisasi per IdP.
- Sesi opaque server-side, simpan digest ID sesi di SQLite, cookie __Host-/HttpOnly/Secure. Absolute timeout 8 jam dan idle timeout 30 menit sebagai default usulan; privilege sensitif memakai auth recent, misalnya 15 menit.
- Cookie sesi utama tetap Strict bila memungkinkan. Gunakan cookie korelasi OIDC terpisah SameSite=Lax untuk callback GET; jangan mengendurkan semua cookie karena redirect IdP. Callback POST/form_post belum didukung pada MVP.
- Logout selalu mencabut sesi lokal; RP-initiated logout bila provider mendukung, tidak mengklaim logout global bila tidak tersedia. Back-channel logout diuji bila diaktifkan; minimum ada expiry/re-auth dan revoke sesi oleh admin.
- Perubahan grant/deaktivasi user lokal berlaku pada request berikutnya, termasuk job sebelum apply. Perubahan grup/deaktivasi di IdP disinkronkan pada login/re-auth; tanpa back-channel/SCIM revokasi IdP tidak instan dan dibatasi lifetime sesi. Jangan menjanjikan revokasi langsung dari IdP.
- MFA untuk admin dan akses raw production diwajibkan oleh kebijakan IdP deployment; auth_time/max_age dipakai untuk recent-auth. Interpretasi acr/amr harus spesifik issuer dan diuji, bukan asumsi universal string MFA.
- Kandidat utama OIDC: openidconnect + supported async HTTP client. Kandidat sesi: tower-sessions dengan adapter rusqlite; limiter: governor; kompresi: async-compression. Tidak menulis JWT/JWKS verifier, cookie/session middleware atau algoritma limiter sendiri. Versi final menunggu A00 (MSRV/advisory/trait compatibility). Lihat riset library untuk alternatif dan batas tanggung jawabnya.
Akun darurat lokal: identitas bernama, Argon2id dengan parameter minimum tervalidasi, limiter terpisah, audit dan recent-auth. Tidak ada registrasi/reset password publik pada MVP. Limiter memakai kombinasi sumber tepercaya, backoff akun, dan batas global yang tidak mengunci semua user dengan 10 request; tidak percaya forwarded IP dari klien bebas.
## 6. Model data dan migrasi
Gunakan migrasi aditif bernomor dan transaksi, dengan foreign key, unique constraints, indeks lookup dan status yang tervalidasi. Nama tabel berikut usulan, bukan kewajiban menambah satu tabel untuk setiap konsep.
- users: id, issuer, subject, display_name, active, timestamps; UNIQUE(issuer, subject).
- sessions: token_digest, user_id, csrf digest, created_at, last_seen, expires_at, auth_time, auth method. OIDC login_transactions menyimpan korelasi/PKCE singkat dan konsumsi sekali pakai; token rahasia tidak dicatat ke log.
- access_grants: principal user/group/service, permission/role, scope_type, scope_id, optional expiry, created_by. Mapping grup disimpan eksplisit dan dapat diaudit.
- Orbit metadata: environment production/staging/development, data classification, binding restore_target_id opsional. Restore target tetap membawa identitas database dan outpost yang sudah ada; orbit target tidak wajib menjalankan jadwal backup.
- orbit_relations: id, source_orbit_id, target_orbit_id, active, version, creator. Relasi berarah, tidak otomatis simetris/transitif; cegah sumber=target dan alias identitas database yang sama. Perubahan identitas/tujuan membuat versi baru dan menonaktifkan relasi lama, bukan mengubah job diam-diam.
- refresh_runs: requester_id, relation_id/version, capture_job_id, snapshot_id, restore_job_id, status, timestamps, idempotency key, error code aman. Unique child job links mencegah duplikasi.
- Token Outpost/service: token ID, digest, principal, state, expiry/rotation metadata. Simpan plaintext hanya saat benar-benar perlu menyerahkan token pairing; desain generate-on-claim agar token aktif tidak disimpan mentah. Pairing code disimpan digest, expiry dan konsumsi atomik.
- Upload session wajib memiliki outpost_id dan orbit ownership. Sesi lama tanpa owner ditolak/ditutup, tidak diberi owner hasil tebakan.
- Audit: actor ID, auth method, action, resource, outcome, request/correlation ID, timestamp, detail allowlist; tidak menyimpan payload DB, secret, token atau signed URL.
Migrasi tidak mengubah snapshot lama atau menyimpulkan relasi dari kesamaan application_id/nama. Admin meninjau mapping orbit → target dan grant. Token lama dimigrasi ke digest di tempat lalu plaintext dihapus; rotasi tetap diperlukan karena salinan database/backup lama mungkin memuat token. Shared admin token lama hanya untuk transisi eksplisit dengan batas akhir dan audit, bukan fallback permanen.
## 7. Relasi production → staging
Wizard DevOps memilih orbit production dan orbit staging, mengikat capture profile sumber dan restore target tujuan, memeriksa engine/format/versi yang didukung dan identitas target, lalu memberi grup/user izin refresh pada relasi. Host/DSN/password tidak ditampilkan kepada QA/developer.
Pemeriksaan bukan sekadar label environment: gunakan identitas instance+database yang sudah ada, cek alias sumber/tujuan, Outpost aktif, kredensial terbatas, dan validasi agent sebelum reset. Default self-service menolak target production dan format non-restore-ready. Kesamaan application_id tetap prasyarat kompatibilitas yang ada, bukan pengganti relasi eksplisit.
## 8. Workflow QA
1. QA login, melihat relasi yang diberi grant, sumber production, tujuan staging dan peringatan staging akan ditimpa.
2. QA mengonfirmasi relasi/versi tujuan dan memilih Refresh. POST memakai CSRF dan idempotency key; server menyimpan run dan job capture secara durable.
3. Worker memakai antrean capture yang ada. Capture baru harus menjadi job khusus run, bukan memilih latest snapshot global atau memakai backup lama jika capture gagal.
4. Saat commit capture terverifikasi, tautkan snapshot_id tepat dari capture_job_id, pin snapshot, dan evaluasi ulang user aktif, grant, relasi/versi, expiry request dan kesiapan target.
5. Antrekan restore persis sekali. Konfirmasi run mengikat relasi/versi target sejak awal; tidak menerima target_id pengganti dari browser setelah capture selesai.
6. Agent tujuan memakai lease/fencing, verifikasi checksum dan identitas, buat safety backup dan memperoleh izin apply sebelum perubahan destruktif.
7. UI menunjukkan queued → capturing → snapshot_ready → restoring → completed; kegagalan membedakan capture_failed, blocked/revoked, restore_failed, cancelled, recovery_required. Tampilkan waktu mulai/selesai capture dan identitas snapshot.
Terbaru berarti consistent dump dari job yang diminta; bukan jaminan identik dengan production pada detik restore selesai. Konsistensi mengikuti kemampuan engine/provider; fixture membuktikan transaksi dump dan timestamp, bukan klaim real-time atau konsistensi lintas database.
Satu run aktif per target (termasuk proses capture) dengan constraint/lock durable; request kedua mendapat conflict dan referensi run yang boleh dilihat. Tidak menumpuk antrean restore lama ke staging. Capture sumber diserialkan memakai aturan job saat ini; batas ukuran/waktu dan global concurrency mencegah beban production berlebihan.
Restart memulihkan run dari state SQLite dan hubungan child job, bukan memori/task spawn semata. Cancel sebelum apply membatalkan pekerjaan yang aman; setelah apply tidak mengklaim rollback otomatis. Pencabutan akses sebelum apply memblokir apply; setelah apply dimulai utamakan menyelesaikan pemulihan aman dan audit, bukan mematikan proses database di tengah jalan. Lease hilang setelah reset tetap recovery_required sampai admin reconcile. Snapshot dan safety backup dipin sampai aman dilepas.
## 9. Workflow developer dan kompresi
Developer melihat orbit/snapshot dalam scope. Tombol Download memerlukan snapshot.download dan kebijakan raw-data orbit. Capture baru adalah aksi terpisah; snapshot lama tetap dapat dipilih dengan timestamp jelas.
Gunakan ekspor vault yang ada, kemudian hasilkan arsip unduhan: SQL → .sql.gz; tar filesystem → .tar.gz; PostgreSQL custom dump yang sudah terkompresi dipertahankan sebagai .dump bila metadata menjamin kompresi, selain itu .dump.gz. SQLite → .sqlite.gz. Format/encoding diputuskan dari metadata tervalidasi, bukan ekstensi saja. Jangan mengubah format internal backup/restore hanya untuk download.
Gunakan kompresi gzip streaming atau temporary artifact privat dengan quota/disk admission, batas concurrency, timeout, cleanup sukses/gagal/client disconnect/restart. Jangan menampung seluruh dump di memori atau membuat direktori world-readable. Pin snapshot selama export dan pertahankan lifetime file/direktori sampai body response selesai; evaluasi ulang handler catalog.rs saat ini yang membuat TempDir lokal sebelum stream dikonsumsi.
Endpoint download memakai cookie same-origin atau service token scoped, Cache-Control no-store dan Content-Disposition filename aman. Tidak meneruskan cookie/token ke storage publik, tidak menaruh bearer di query URL, dan tidak membuat tautan publik permanen. Browser memakai native navigation/download, bukan menahan seluruh response sebagai Blob JS. Audit membedakan export requested/ready, stream finished/disconnected; stream selesai bukan bukti file tersimpan di laptop. Berikan format, source/capture timestamp, ukuran dan checksum arsip hasil kompresi bila artifact sudah disiapkan.
MVP mulai dengan download existing snapshot. Jika perlu menunggu ekspor besar, tambahkan job export pendek TTL dengan polling status, bukan HTTP timeout sangat panjang. Kontrak awal harus menetapkan ambang ukuran/waktu berdasarkan benchmark fixture; pilih streaming langsung jika cukup, durable export hanya jika bukti memerlukannya.
## 10. API dan UI yang terdampak
- Pertahankan operator/session sebagai kompatibilitas; tambahkan /auth/oidc/login dan /auth/oidc/callback, identitas /me dan logout lokal. /me mengembalikan identitas/capabilities aman, bukan token IdP.
- Admin APIs: user status/session revoke, role/grant, mapping grup, environment/binding orbit, relation CRUD/version, token rotate/revoke dan audit list.
- Self-service: GET relasi yang boleh digunakan, POST /refresh-runs, GET /refresh-runs/:id, cancel sebelum apply. Client tidak dapat mengirim actor, snapshot hasil capture, atau tujuan arbitrary.
- Semua list/detail snapshot/orbit/job/target difilter scope; download handler tetap memeriksa grant sendiri. Akses raw restore payload hanya agent dan lease yang sesuai.
- UI DevOps: konfigurasi relasi/grant, status agent, audit dan recovery. UI QA: Refresh staging dan progres terpadu. UI developer: pilih snapshot/format/Download dan capture baru bila diizinkan.
- Reuse OperatorGate, OrbitsView, CaptureProfileForm, RestoreTargetForm, DatabaseRestore, JobHistory, SnapshotSheet dan komponen UI rumah. Tambahkan komponen hanya untuk flow relasi dan refresh yang belum ada.
- Perbarui OpenAPI security scheme/requirements, TS types/client, fixture/demo, CLI dan dokumentasi. CLI tetap local HTTP sesuai guard saat ini; jangan mengklaim OIDC CLI/device-flow sudah didukung. Remote automation memakai HTTPS dengan service token scoped melalui client yang mendukungnya.
## 11. Perbaikan seluruh temuan audit
| Temuan | Implementasi | Bukti penerimaan |
| --- | --- | --- |
| Upload lintas Outpost | Owner orbit/session, gate semua jalur legacy, token lifecycle | A tidak dapat init/chunk/seal pada resource B |
| Fallback loopback/proxy | Auth wajib secara default, mode local-development eksplisit dan binding loopback | Proxy lokal tanpa login tetap 401; mode dev tidak boleh bind wildcard |
| RBAC tidak ada | Role + grant resource/relasi + gate per request | Matriks aksi/resource lulus termasuk UUID langsung |
| Limiter global | Rate sumber/backoff akun/batas global, batas concurrency hash, audit deny | Flood satu sumber tidak menghabiskan semua kuota login user sah |
| Token mentah/permanen | Digest, rotate/revoke, expiry policy, migrasi dan re-pair terkontrol | DB baru tidak memuat token aktif mentah; token dicabut ditolak |
| Sesi idle panjang | Idle/absolute timeout, revoke, recent-auth, emergency account | Expired/revoked/old-auth ditolak server |
| Audit tidak lengkap | Structured actor/outcome untuk auth, policy, capture, restore, export, retention | Tidak ada mutasi sensitif tanpa event yang dapat ditelusuri |
| OIDC belum ada | Code+PKCE, token verification, issuer identity, mapping grup | Provider target dan kasus negatif lulus |
## 12. Strategi verifikasi dan standar
Acuan: OWASP ASVS 5.0 (target kontrol relevan setara L2 untuk auth/session/authorization/data handling; bukan klaim sertifikasi), OWASP Authorization/Authentication/Session Management, OIDC Core 1.0 errata 2 dan RFC 9700.
- Unit/property/table tests: permission matrix, scope inheritance snapshot→orbit, unknown permission deny, relasi berarah, environment, token parsing/digests, timeout dan transition state.
- HTTP integration: setiap endpoint anonymous/user/service/outpost, CSRF, direct UUID, metadata redaction, forged actor, invalid target, permission revoked saat job queued/capturing dan sebelum apply.
- OIDC mock provider: signature salah, alg salah, iss/aud/nonce/state salah, callback replay, expired token, JWKS rotation/outage, discovery mismatch, grup hilang dan email sama dengan subject berbeda. Uji browser nyata untuk cookie cross-site callback.
- Database/agent fixture: PostgreSQL dan MySQL production sintetis → capture → staging; compare schema/data, safety snapshot, wrong target, lease lama, disconnect/restart, idempotent retry, race dua permintaan dan retensi bersamaan.
- Export fixture: gzip magic/decompression, checksum konten, file besar, memori bounded, disk penuh, quota exceeded, pembatalan browser dan cleanup restart.
- Deployment fixture: reverse proxy lokal, HTTPS/header trust, no-auth startup, CSP/frame-ancestors/HSTS pada lapisan yang sesuai, no-store untuk data sensitif; jangan membuka CORS luas.
- End-to-end tiga akun DevOps/QA/developer ditambah user tanpa grant. QA refresh tanpa izin download; developer download tanpa izin restore. Akses production sebagai target ditolak.
- Cek dependency advisory/lockfile sebelum release, dokumentasi crate terkini saat memilih/mengintegrasikan library, dan review auth secara khusus.
Per slice jalankan tes fokus. Checkpoint: rtk cargo test --workspace; rtk cargo build --workspace; rtk proxy npm --prefix web test; rtk proxy npm --prefix web run typecheck; rtk proxy npm --prefix web run build. Fixture Restic: rtk cargo test -p tessera-store -- --ignored dengan prasyarat harness tests/mbu/README.md. Uji browser/IdP dan fixture DB adalah gate terpisah, tidak digantikan compile.
## 13. Migrasi, rollout, dan rollback
1. Backup SQLite/config dan inventaris versi tanpa membaca/mencatat rahasia. Uji migrasi pada salinan fixture termasuk orbit legacy, token dan job berjalan.
2. Rilis perbaikan isolasi/fail-closed lebih dahulu; dokumentasikan perubahan mode auth supaya instalasi lokal tidak terkunci tanpa bootstrap admin.
3. Bootstrap admin dan OIDC di staging; petakan grant dan relasi eksplisit. Tidak memberikan akses semua production kepada grup baru secara default.
4. Rehearsal dengan data sintetis, lalu subset aplikasi yang sudah disetujui. Enable self-service per relasi setelah uji capture, restore, safety dan download lulus.
5. Cabut token shared transisi, rotasi agen bila perlu, tinjau audit dan disk/DB load. Production secrets/deploy/destructive restore tetap mengikuti otorisasi operasional terpisah.
6. Rollback operasional: nonaktifkan request baru dan relasi, drain job aman, tahan recovery_required, revoke sesi/token terkait. Jangan downgrade binary lama yang mengabaikan RBAC. Restore DB sebelum migrasi hanya setelah rekonsiliasi job dan kredensial; bukan rollback otomatis yang menghapus audit/job baru.
## 14. Keputusan deployment yang masih dibutuhkan
- IdP/issuer yang dipakai, nama claim grup, grup admin/QA/developer, kemampuan MFA/re-auth/logout. Default desain generic OIDC confidential client; uji satu IdP target sebelum dukungan dinyatakan.
- Aplikasi mana yang mengizinkan raw production di staging dan laptop; siapa pemilik grant dan berapa masa berlakunya. Default tidak ada akses sampai grant dibuat.
- Ukuran dump terbesar, batas concurrency dan window capture yang aman; ukur fixture sebelum menetapkan batas final.
- Versi engine target, provisioning konfigurasi agent/restore target, dan kebutuhan local restore developer (file unduhan saja pada rilis ini).
- Kebijakan retention safety backup, TTL request refresh, audit dan export artifact. Default usulan idle 30m/absolute 8h/recent-auth 15m; refresh queued kedaluwarsa setelah 1h sebelum mulai, artifact sementara maksimal 1h bila mode artifact dipakai. Angka ini harus disesuaikan durasi capture nyata.
## 15. Di luar lingkup rilis
Tidak membuat user/password manager lengkap, multi-tenant, multi-issuer, SCIM, OIDC device flow CLI, arbitrary restore host, local database provisioning, masking engine generik, approval per refresh, atau workflow engine baru. Penambahan hanya bila kebutuhan deployment membuktikannya.
## Referensi
- https://asvs.owasp.org/
- https://openid.net/specs/openid-connect-core-1_0.html
- https://www.rfc-editor.org/rfc/rfc9700.html
- https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html
- https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
## 16. Keputusan reuse setelah riset library
Gunakan dokumen riset sebagai acuan A00–A25. Ini memperjelas keputusan awal untuk tidak menambah policy/workflow engine tanpa kebutuhan:
- OIDC memakai openidconnect; account/group/grant mapping tetap milik Tessera.
- tower-sessions diprioritaskan untuk lifecycle sesi. Adapter rusqlite, digest storage, concurrent revoke, absolute deadline dan recent-auth harus dibuktikan; stock SQLx store tidak ditambahkan otomatis.
- governor + Tokio Semaphore menggantikan algoritma limiter manual.
- Casbin embedded boleh dipakai bila spike membuktikan total implementasi lebih kecil daripada typed gate + SQL grants. Baseline tetap gate bertipe dengan aksi tetap; tidak membangun policy language generik.
- async-compression membuat file gzip; CompressionLayer bukan pengganti arsip download. flate2 hanya alternatif bila memakai blocking artifact worker.
- rusqlite_migration dipakai bila kompatibel dan mempermudah baseline/migrasi; tidak mengganti ORM/storage semata demi adapter.
- wiremock + Playwright Test + Keycloak fixture untuk pengujian; IdP organisasi tetap pilihan pertama untuk produksi.
- Restic, antrean SQLite/lease, provider DB, UI rumah/React Query, tracing dan utoipa dipakai ulang. Apalis/Temporal/OpenFGA ditunda sampai ada kebutuhan skala/graph lintas layanan.
Tidak ada dependency yang sudah ditambahkan. Tidak ada jaminan semua versi latest kompatibel dengan Axum 0.7, rusqlite 0.31 dan image Rust 1.88. A00 menghasilkan pilihan versi/pin atau keputusan upgrade terpisah sebelum implementasi slice terkait.

View File

@@ -0,0 +1,374 @@
# Tugas auth dan self-service data
Rencana: [auth-self-service-plan.md](auth-self-service-plan.md). Riset library: [auth-self-service-libraries.md](auth-self-service-libraries.md). Status mengikuti bukti di bawah; fitur produk penuh belum selesai. Path hub relatif ke crates/tessera-hub/src kecuali disebutkan. Nama file baru adalah usulan; ikuti struktur aktual saat implementasi. Setiap task ditargetkan S/M (maksimal sekitar lima file utama); pecah lagi jika kontrak/fixture nyata membuat lingkup membesar.
Tes fokus per task; checkpoint menjalankan cargo workspace tests/build dan web test/typecheck/build sebagaimana rencana. Tidak memerlukan deploy atau data production untuk mengerjakan task ini.
## A00 — Compatibility spike dan keputusan dependency
**Dependensi:** —. Dapat dikerjakan independen dari perbaikan akses A01–A03.
**Lingkup:** fixture spike terisolasi; manifest/lockfile percobaan; Dockerfile baseline; dokumen riset library. Tidak mengubah runtime auth sebelum keputusan.
Buktikan openidconnect, tower-sessions + rusqlite adapter, governor dan async-compression terhadap Axum 0.7/Tower 0.5/rusqlite 0.31/Rust 1.88. Bandingkan Casbin dengan typed scoped gate melalui matriks izin yang sama; nilai rusqlite_migration tanpa membawa dua SQLite bindings. Pisahkan eksperimen jika lebih dari lima file utama.
- [ ] Penerimaan: Pilihan versi/features/license/MSRV/advisory dicatat; tidak menambah ORM/layanan kedua tanpa pengurangan biaya nyata; keputusan Casbin/session adapter beserta kode yang digantikan jelas.
- [ ] Verifikasi: Compile fixture terhadap workspace constraints, cek dependency tree/SQLite links dan audit; buktikan session create collision/revoke race, policy deny/revoke dan gzip content. Hapus fixture percobaan yang tidak dipakai secara aman saat implementasi selesai.
**Bukti parsial A00 (11 November 2026):** [fixture dan hasil](../tests/auth-compat/README.md), enam tes executable pada Rust 1.88. Axum 0.7/Tower 0.5 kompatibel dengan tower-sessions 0.15 melalui Extension; satu SQLite binding. Audit baseline: 10 vulnerability + warning Tokio; spike awal 12, setelah perbaikan time/TLS tersisa SQLite/RSA serta warning Tokio. **A00 belum selesai**: remediation baseline, triage RSA, cargo-deny, dan revoke-vs-rotation/user epoch belum tuntas. Tidak ada library auth baru dalam runtime.
## A01 — Inventaris endpoint dan kontrak otorisasi
**Reuse/library:** Reuse utoipa + axum/tower test harness; inventaris policy tetap domain.
**Dependensi:** —.
**Lingkup:** api/{routes,jobs,restore,catalog,session}.rs.
Daftarkan semua route manusia/agen dan aksi, scope, status deny, serta data yang boleh dikembalikan.
- [x] Penerimaan: Semua path router tercantum di `auth-endpoint-contract.md`, termasuk aturan agent/lease dan jalur recovery legacy. Permission scoped masih kontrak untuk A11–A12.
- [x] Verifikasi: `rtk cargo test -p tessera-hub auth_contract` — 2 passed (11 November 2026): inventory seluruh path dibandingkan source router; fixture HTTP seluruh human GET menolak anonymous dan token Outpost. Matriks mutasi/scoped penuh tetap A12.
## A02 — Tutup upload lintas Outpost
**Reuse/library:** Reuse rusqlite transaksi/constraints dan assignment agen; owner check tetap domain.
**Dependensi:** A01.
**Lingkup:** api/routes.rs; db.rs; upload.rs.
Ikat orbit dan upload session ke Outpost, migrasikan sesi lama tanpa owner menjadi tidak dapat digunakan.
- [x] Penerimaan: Owner orbit/session wajib; legacy tanpa owner ditolak. Endpoint admin `PUT /api/v1/orbits/:id/outpost` mengikat legacy ke Outpost aktif; managed assignment tetap capture profile.
- [x] Verifikasi: `rtk cargo test -p tessera-hub legacy_uploads_are_owned` lulus: dua Outpost, unbound orbit, leaked session, retry owner, foreign final chunk/seal, unowned session, foreign Restic commit dan race rebind/commit deterministik. Owner direvalidasi di lock vault sebelum seal/commit.
## A03 — Wajibkan auth dan bootstrap admin
**Reuse/library:** Reuse axum gate/startup config; proxy auth hanya tambahan.
**Dependensi:** A01.
**Lingkup:** admin.rs; main.rs; state.rs; docs/DATABASE-CAPTURE.md; compose.yaml.
Ganti no-auth otomatis dengan mode development eksplisit, siapkan bootstrap admin darurat.
- [x] Penerimaan: Default deny termasuk loopback; startup meminta operator/token atau development eksplisit. Mode dev menolak wildcard/non-loopback di kedua listener; migrasi/bootstrap emergency didokumentasikan.
- [x] Verifikasi: IPv4/IPv6, wildcard, forwarded headers dan HTTP proxy tanpa kredensial lulus. Browser sintetis Chrome DevTools: sign-in → vault kosong → sign-out lulus; console bersih. Playwright gagal launch karena browser binary belum terpasang; bukan hasil lulus Playwright.
### Checkpoint setelah A03
- [x] Tes fokus/regresi: cargo test --workspace 39 passed, 1 ignored sebelum A04; cargo build --workspace lulus. Web test 10 passed, typecheck/build lulus. Tes Restic ignored dijalankan eksplisit: 1 passed.
- [x] Kasus negatif lulus; fixture positif memakai kredensial eksplisit. Tidak melemahkan assertion/validasi.
- [x] Kontrak route dan batas migrasi/dukungan diperbarui; A00 dan OIDC/scoped/self-service tetap terbuka.
## A04 — Struktur principal dan audit
**Reuse/library:** Reuse serde/tracing dan durable audit SQLite; log tidak menggantikan audit.
**Dependensi:** A01.
**Lingkup:** admin.rs; db.rs; api/routes.rs; modul auth/audit baru.
Buat identitas stabil manusia/service/outpost dan event audit structured yang dapat dipakai slice berikutnya.
- [x] Penerimaan: Principal server-derived emergency user/service/Outpost/anonymous; audit typed memuat actor, auth method, action, resource, outcome dan ID. Tabel audit_events aditif mempertahankan audit_log tanpa kolom payload/detail bebas.
- [x] Verifikasi: Tes hub 21 passed setelah A04; reopen/migrasi idempotent, actor login/logout dan redaction, deny resource orbit/session asing. Authentication dibedakan dari authorization setelah review. Coverage semua aksi dan korelasi request penuh tetap A23; user OIDC persisten tetap A07/A09.
## A05 — Simpan digest kredensial dan migrasikan token
**Reuse/library:** Reuse sha2/hmac/rand; subtle sebagai dependency langsung bila diimpor.
**Dependensi:** A02,A04.
**Lingkup:** db.rs; admin.rs; api/routes.rs; agent credentials fixtures.
Migrasikan token aktif ke digest, generate token pairing saat claim, dan konsumsi pairing code secara atomik.
- [ ] Penerimaan: Plaintext token aktif tidak ada di DB baru; token lama yang dimigrasikan tetap dikenali hanya melalui digest; claim replay ditolak.
- [ ] Verifikasi: Tes migrasi/claim konkuren dan inspeksi fixture SQLite dengan token sintetis.
## A06 — Rotasi dan pencabutan token
**Reuse/library:** Reuse primitives dan transaksi token; opaque token, bukan JWT baru.
**Dependensi:** A05.
**Lingkup:** api/token.rs baru; db token module; admin.rs; web/src/api.ts.
Sediakan API admin untuk service/Outpost token lifecycle dan expiry; UI diberikan setelah permission siap.
- [ ] Penerimaan: Token dicabut/expired ditolak pada request berikutnya; rotasi memiliki batas transisi eksplisit dan audit.
- [ ] Verifikasi: Tes token lama/baru, lease agen setelah revoke, dan clock expiry.
## A07 — Sesi individual persisten
**Reuse/library:** Prioritas tower-sessions + adapter rusqlite setelah A00; tanpa SQLx otomatis.
**Dependensi:** A00,A03,A04.
**Lingkup:** admin.rs; api/session.rs; db session module; state.rs.
Persist digest session, user ID, CSRF, idle/absolute expiry dan auth_time; rotate saat login.
- [ ] Penerimaan: Logout/revoke/expiry berlaku server-side; sesi lama tidak di-upgrade menjadi user baru; restart tidak kehilangan kebijakan expiry.
- [ ] Verifikasi: Tes fake clock, session fixation, CSRF, restart dan recent-auth.
## A08 — Limiter login dan akun darurat
**Reuse/library:** governor + Tokio Semaphore + Argon2id existing; tower_governor opsional.
**Dependensi:** A00,A07.
**Lingkup:** admin.rs; api/session.rs; auth tests; docs auth.
Pisahkan rate sumber/backoff akun/global safety dan batasi concurrent password verification.
- [ ] Penerimaan: Flood satu sumber tidak mengunci kuota seluruh login; hash lemah ditolak; failed login diaudit tanpa password.
- [ ] Verifikasi: Tes burst/concurrency dan spoofed forwarded IP; dokumentasi recovery admin.
### Checkpoint setelah A08
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A09 — Login OIDC server-side
**Reuse/library:** openidconnect + supported async HTTP client setelah A00; tanpa verifier buatan sendiri.
**Dependensi:** A00,A07.
**Lingkup:** Cargo.toml/Cargo.lock; auth/oidc.rs baru; api/session.rs; state.rs.
Pilih library berdasar dokumentasi/advisory/MSRV; implementasikan discovery, code+PKCE, browser correlation, callback validation dan unique issuer/subject.
- [ ] Penerimaan: State/nonce/issuer/audience/signature/expiry/replay invalid ditolak; token tidak dikirim ke browser; unknown user tanpa grant.
- [ ] Verifikasi: Mock issuer dengan JWKS rotation/outage; browser nyata cross-site callback.
## A10 — UI login dan lifecycle OIDC
**Reuse/library:** Reuse OperatorGate dan backend session; IdP existing, Keycloak fixture; tanpa SDK token React.
**Dependensi:** A09.
**Lingkup:** web OperatorGate.tsx; web/api.ts; auth/oidc.rs; api/session.rs; docs auth.
Tampilkan SSO, sesi individual, local logout/revoke dan provider logout bila didukung; paparkan keterbatasan revokasi IdP.
- [ ] Penerimaan: SSO masuk/keluar berfungsi; akun emergency terpisah; group missing tidak memperluas akses.
- [ ] Verifikasi: E2E pada IdP target: MFA/re-auth, logout dan user tanpa grant.
## A11 — Grant scoped dan policy gate
**Reuse/library:** Spike Casbin embedded vs typed gate + SQL grants; hasil A00 menentukan; domain safety tetap terpisah.
**Dependensi:** A00,A04,A07.
**Lingkup:** core access model baru; db access module; hub auth policy; policy tests.
Definisikan permission/role, user/group/service grants dan scope orbit/relasi; gunakan gate deny-by-default.
- [ ] Penerimaan: Grant lintas orbit ditolak; refresh tidak memberikan download/capture bebas; admin sensitif mengikuti batas data/environment.
- [ ] Verifikasi: Tes table-driven seluruh matriks aksi/resource, expiry grant dan unknown permission.
## A12 — Terapkan policy pada seluruh API
**Reuse/library:** Reuse axum extractor/middleware dan gate A11; row filtering eksplisit.
**Dependensi:** A11.
**Lingkup:** api/routes.rs; api/jobs.rs; api/restore.rs; api/catalog.rs; api/session.rs.
Ganti gate admin generik dengan policy aksi/resource; filter list dan detail serta pisahkan payload agent.
- [ ] Penerimaan: Direct UUID tidak memintas scope; tidak ada metadata resource lain bocor; token jenis salah ditolak.
- [ ] Verifikasi: Jalankan kontrak A01 dan dua-user HTTP fixtures, termasuk download dan job history.
## A13 — Administrasi akses dan mapping grup
**Reuse/library:** Reuse React Query/komponen rumah + IdP groups; admin grant Tessera tetap lokal.
**Dependensi:** A10,A12.
**Lingkup:** api/access.rs baru; db access module; web/api.ts; UI access baru; OperatorGate.tsx.
DevOps dapat memberi/mencabut grant, menonaktifkan user/sesi dan memetakan grup issuer secara eksplisit.
- [ ] Penerimaan: Perubahan hak berlaku request berikutnya; tidak auto-link email; UI non-admin tidak dapat mengubah grant.
- [ ] Verifikasi: E2E DevOps memberi QA grant, QA memakai akses, DevOps revoke, QA langsung ditolak.
### Checkpoint setelah A13
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A14 — Environment dan binding orbit tujuan
**Reuse/library:** Reuse core models/rusqlite/provider identity; tanpa graph DB baru.
**Dependensi:** A12.
**Lingkup:** core orbit/restore models; db.rs; api/routes.rs; RestoreTargetForm.tsx; web/api.ts.
Tambahkan metadata environment/classification dan binding orbit staging ke restore target terverifikasi.
- [ ] Penerimaan: Orbit target tanpa jadwal capture tetap valid; identity alias source/target ditolak; tidak ada host/secret bebas di UI pengguna.
- [ ] Verifikasi: Tes migrasi additive dan binding target engine/identity salah.
## A15 — Relasi berarah dan grant refresh
**Reuse/library:** Reuse SQLite constraints + selected gate; OpenFGA ditunda.
**Dependensi:** A13,A14.
**Lingkup:** core relation model; db relations; api/relations.rs; web/api.ts.
Simpan relasi source→target aktif berversi, periksa compatibility dan scope, tampilkan relasi yang diizinkan.
- [ ] Penerimaan: Tidak simetris/transitif; same application tanpa relasi tidak cukup; production target ditolak; edit tidak mengganti tujuan job lama.
- [ ] Verifikasi: Tes relasi terbalik, target production, source alias dan versi stale.
## A16 — Wizard DevOps untuk konfigurasi self-service
**Reuse/library:** Reuse form/profile/target rumah dan React Query; tanpa admin framework baru.
**Dependensi:** A15.
**Lingkup:** OrbitsView.tsx; CaptureProfileForm.tsx; RestoreTargetForm.tsx; UI relation baru; web/api.ts.
Satukan pendaftaran sumber/tujuan, relasi dan assignment akses memakai API yang ada.
- [ ] Penerimaan: DevOps menyiapkan production/staging dan grant tanpa konfigurasi tambahan oleh QA; sumber non-ready menunjukkan alasan.
- [ ] Verifikasi: Browser E2E setup dua orbit, agent offline dan incompatible format.
### Checkpoint setelah A16
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A17 — Run refresh durable dan capture baru
**Reuse/library:** Reuse durable SQLite job/lease; Apalis ditunda.
**Dependensi:** A15.
**Lingkup:** core refresh model; db refresh module; api/refresh.rs; db/jobs.rs; api/mod.rs.
POST refresh menyimpan actor/relasi versi/idempotency dan capture child job; satu run aktif per target.
- [ ] Penerimaan: Double submit memberi satu run; capture gagal tidak menggunakan snapshot lama; sumber memakai capture managed saja pada MVP.
- [ ] Verifikasi: Tes transaksi rollback, concurrent requests, capture serialization dan request TTL.
## A18 — Hubungkan snapshot tepat ke restore
**Reuse/library:** Reuse Restic + worker/job existing; Temporal ditunda.
**Dependensi:** A17.
**Lingkup:** db refresh module; db/jobs.rs; db/restore.rs; state.rs; scheduler.rs.
Proses commit snapshot spesifik capture_job_id, pin input dan enqueue satu restore child memakai worker recovery persisten.
- [ ] Penerimaan: Snapshot bukan latest global; restart sebelum/sesudah enqueue tidak membuat restore ganda; retensi tidak menghapus input.
- [ ] Verifikasi: Crash/retry fixture pada setiap transisi dan race retention/delete.
## A19 — Revalidasi sebelum apply dan pemulihan
**Reuse/library:** Reuse restore fencing/safety/provider dan gate; safe cancel tetap domain.
**Dependensi:** A18.
**Lingkup:** api/restore.rs; db/restore.rs; db refresh module; agent restore.rs; policy tests.
Periksa user/grant/relasi saat dequeue dan sebelum apply; hubungkan cancel, safety backup dan recovery_required.
- [ ] Penerimaan: Revoke sebelum apply mencegah reset; cancel setelah apply tidak mengklaim rollback; lease lama tidak dapat apply.
- [ ] Verifikasi: DB fixture revoke saat capture, queued, safety dan applying; disconnect/reset safety failure.
## A20 — UI refresh QA
**Reuse/library:** Reuse DatabaseRestore/JobHistory/React Query; backend sebagai sumber state.
**Dependensi:** A16,A19.
**Lingkup:** DatabaseRestore.tsx; JobHistory.tsx; UI refresh baru; web/api.ts; App.tsx.
Sajikan sumber/tujuan terotorisasi, konfirmasi staging dan progres capture→restore beserta failure/recovery.
- [ ] Penerimaan: QA selesai tanpa DevOps per run; tidak melihat tombol/endpoint download tanpa grant; timestamp snapshot jelas.
- [ ] Verifikasi: Browser E2E QA refresh, retry, cancel dan recovery admin dengan API deny assertion.
### Checkpoint setelah A20
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A21 — Ekspor terkompresi dengan resource bounded
**Reuse/library:** async-compression tokio+gzip setelah A00; flate2 alternatif blocking; jangan pakai CompressionLayer untuk file gzip.
**Dependensi:** A00,A12.
**Lingkup:** api/catalog.rs; store export path; Cargo.toml/Cargo.lock bila diperlukan; export fixtures.
Pakai kompresor yang sudah tersedia/layak, streaming atau private temp artifact; pin snapshot dan cleanup lifetime sampai response selesai.
- [ ] Penerimaan: SQL/tar/SQLite dikompresi; custom dump metadata ditangani benar; tidak menampung seluruh dump di RAM; quota/disk errors aman.
- [ ] Verifikasi: Magic/decompress/content checksum; large-file memory benchmark; disk penuh/disconnect/restart cleanup.
## A22 — Download developer dan audit ekspor
**Reuse/library:** Native browser download + Playwright; tanpa file-saver/Blob seluruh dump.
**Dependensi:** A13,A21.
**Lingkup:** SnapshotSheet.tsx; web/api.ts; api/catalog.rs; audit tests; docs download.
Tampilkan format/ukuran/waktu capture dan native download; raw production grant eksplisit; audit outcome stream.
- [ ] Penerimaan: Developer scoped dapat mengunduh/membuka arsip; QA tanpa download grant ditolak; URL bukan public bearer link.
- [ ] Verifikasi: E2E developer/QA/user asing dan pemeriksaan no-store/filename/cleanup.
## A23 — Lengkapi audit semua aksi sensitif
**Reuse/library:** Reuse audit SQLite + tracing/tower-http request ID; coverage event eksplisit.
**Dependensi:** A06,A12,A19,A22.
**Lingkup:** api/routes.rs; api/jobs.rs; api/catalog.rs; api/access.rs; audit module.
Cakup orbit create, retention, pairing, grant, login deny, capture/restore/export termasuk kegagalan dan actor individual.
- [ ] Penerimaan: Tidak ada mutasi sensitif tanpa event; query audit hanya admin berizin; detail bebas secret/DB payload.
- [ ] Verifikasi: Contract audit tests dari matriks A01; sanitasi log dan failure injection.
### Checkpoint setelah A23
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## A24 — Kontrak publik, migrasi dan regresi
**Reuse/library:** Evaluasi rusqlite_migration setelah A00; reuse utoipa, tambah cargo-deny/audit tooling.
**Dependensi:** A20,A22,A23.
**Lingkup:** OpenAPI routes; docs/SPEC.md; docs/DATABASE-CAPTURE.md; demo fixtures; CLI fixtures.
Sinkronkan API/TS/OpenAPI security, demo grant sintetis, dokumentasi token transisi dan kompatibilitas CLI/local.
- [ ] Penerimaan: Migrasi DB lama mempertahankan snapshot/job; legacy unowned ditolak; rollback tidak menggunakan binary yang memintas RBAC.
- [ ] Verifikasi: Build/test workspace+web; fixture migration backward-data compatibility dan CLI regresi.
## A25 — Rehearsal dan rollout terbatas
**Reuse/library:** wiremock + Playwright Test + Keycloak disposable dan harness MBU existing; tanpa dependency runtime IdP wajib.
**Dependensi:** A24.
**Lingkup:** tests/mbu harness; auth e2e fixtures; docs rollout; compose.yaml.
Jalankan IdP/proxy/DB/browser rehearsal, ukur quota/timeouts, pilot relasi yang disetujui dan dokumentasikan bukti.
- [ ] Penerimaan: Dua user story dan seluruh kasus deny lulus; ada runbook emergency/revoke/recovery dan batas dukungan IdP jelas.
- [ ] Verifikasi: PostgreSQL/MySQL fixtures + IdP target; review kontrol ASVS relevan; approval operasional terpisah sebelum deploy/data nyata.
### Checkpoint setelah A25
- [ ] Tes fokus dan regresi checkpoint lulus; catat command dan hasil.
- [ ] Gate keamanan slice terverifikasi dengan kasus negatif; tidak melemahkan assertion/validasi.
- [ ] Kontrak dan batas dukungan diperbarui sebelum slice berikutnya.
## Traceability temuan audit
| Temuan | Task |
| --- | --- |
| Isolasi upload | A01–A02, A05–A06 |
| Fallback loopback | A03 |
| RBAC/individual identity | A04, A07, A09–A16 |
| Login DoS/limiter | A08 |
| Token plaintext/lifecycle | A05–A06 |
| Session timeout/re-auth | A07–A10 |
| Audit tidak lengkap | A04, A23 |
| OIDC compatibility | A09–A10, A25 |
| QA production→staging | A14–A20 |
| Developer compressed download | A21–A22 |

140
tasks/auth-plan.md Normal file
View File

@@ -0,0 +1,140 @@
# Auth Tessera: rencana per milestone
Dibuat 14 November 2026, menggantikan rencana A00–A25 (arsip: `archive/`).
Referensi yang tetap berlaku: [kontrak endpoint](auth-endpoint-contract.md), [riset library](auth-self-service-libraries.md), [spike kompatibilitas](../tests/auth-compat/README.md).
Tujuan: login per orang lewat OIDC dengan sesi persisten, lalu hak akses per scope, lalu workflow self-service. Setiap milestone bisa dirilis sendiri dan punya kriteria selesai yang bisa dibuktikan. Milestone M4 ke atas ditulis kasar dan dipecah ulang saat tiba gilirannya.
Prinsip: pakai library untuk protokol (OIDC, rate limit, gzip), tulis sendiri hanya aturan domain Tessera. Satu hub, satu issuer, SQLite. Tidak ada policy engine, broker, atau workflow engine baru.
## M0 — Fondasi (selesai)
Auth wajib secara default, mode development eksplisit dan loopback saja, upload terikat pemilik Outpost, `Principal` dan `audit_events` bertipe, kontrak endpoint, login operator + CSRF.
Bukti: `cargo test -p tessera-hub` (kontrak, upload ownership, sesi operator).
Catatan: perubahan ini masih uncommitted di working tree. Commit sebelum M1.
## M1 — Baseline dependency (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: workspace siap menerima `openidconnect` tanpa pin yang bentrok.
- rustls 0.23.23 → 0.23.46 (webpki 0.102.8 → 0.103.17), tokio 1.40.0 → 1.54.1 (pin `1.51.6`), rusqlite 0.31.0 → 0.41.1 (libsqlite3-sys 0.28 → 0.39.1).
- Compiler 1.88.0 → **1.89.0** (`rust-toolchain.toml`, `Dockerfile`), karena rusqlite 0.41 butuh 1.89. Tidak ada perubahan source untuk rusqlite/tokio.
- `rustls-pemfile` (unmaintained) dibuang; PEM dibaca lewat `rustls::pki_types::pem` di `mtls.rs` dan agent `http.rs`.
- `deny.toml` ditambahkan (advisories, lisensi permisif eksplisit, bans, sources); semua crate internal `publish = false`.
Bukti: `cargo test --workspace` hijau (jumlah tes sama dengan sebelum upgrade), `cargo audit` 0 vulnerability (sisa 1 warning: `proc-macro-error` unmaintained, transitif), `cargo deny check` ok. Hub booting di salinan DB dev lama (`integrity_check` ok), `/health` dan `/api/v1/orbits` merespons.
Belum terbukti: build image Docker `rust:1.89`, dan tes Restic ignored. Belum ada CI di repo, jadi gate ini baru jalan manual (`cargo audit`, `cargo deny check`).
Sisa catatan: `rsa` 0.9 (RUSTSEC-2023-0071) baru muncul saat `openidconnect` masuk di M3; dikecualikan dengan alasan reachability di sana, bukan sekarang.
## M2 — User dan sesi persisten (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: identitas per orang dan sesi yang bertahan setelah restart.
- Tabel `users` (UNIQUE issuer+subject, `active`, `generation`) dan `sessions` (digest SHA-256 dari ID, user, generation, auth method, credential fingerprint, auth_time, last_seen, expires_at) di `db/sessions.rs`. Store sendiri di rusqlite, bukan `tower-sessions`.
- Validasi sesi satu statement: user aktif, generation cocok, absolute 8 jam, idle 30 menit; geser idle lewat UPDATE-only (tidak bisa menghidupkan baris yang sudah dicabut). Revoke per user menaikkan generation dan menghapus baris dalam satu transaksi. Foreign key SQLite tidak aktif di koneksi ini, jadi tidak diandalkan.
- Akun darurat adalah baris user dengan issuer `local:emergency` (bukan URL, tidak bisa ditabrak issuer OIDC). Sesi password terikat ke fingerprint hash operator: hash dilepas atau diganti saat restart membuat cookie lama mati. Ini menjaga perilaku lama (restart memutus sesi) sekarang sesi persisten.
- CSRF diturunkan dari ID sesi dengan prefix berbeda dari digest penyimpanan, jadi tidak perlu disimpan dan tidak bisa dipakai sebagai kunci.
- `authorize_operator` melakukan satu lookup sesi per request (sebelumnya dua).
- `GET /api/v1/me` (identitas, kind, auth method, nama, capabilities; no-store) masuk kontrak endpoint. `GET /operator/session` kini juga mengembalikan `expires_at`.
Bukti: `cargo test --workspace` hijau (hub 33 tes, naik dari 21: deadline dengan clock injeksi, hanya digest tersimpan, touch setelah revoke, revoke per user lalu login ulang, user nonaktif, restart/reopen DB, hash diganti/dilepas, fixation, `/me`); `cargo audit` 0 vulnerability, `cargo deny` ok. Proses nyata: login, restart dengan hash sama → 200, hash diganti → 401, hash dilepas → cookie tidak dianggap sesi, hash asli lagi → sesi pulih.
Belum ada: endpoint HTTP revoke per user dan nonaktifkan user (fungsi store `revoke_user_sessions` sudah ada dan dites; endpoint admin menunggu M5), pembersihan sesi kedaluwarsa hanya terjadi saat ada login baru, dan limiter login masih in-memory (M4).
## M3 — Login OIDC (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: SSO berfungsi sebagai login utama; akun darurat tetap ada.
- `openidconnect` 4.1 (reqwest + rustls), confidential client, code + PKCE S256, redirect URI statis, redirect HTTP dimatikan, timeout connect 5 detik dan total 15 detik. Konfigurasi `TESSERA_OIDC_*` divalidasi saat startup (https wajib, http hanya loopback + local development, mapping admin wajib). Dokumentasi ada di `docs/DATABASE-CAPTURE.md`.
- Transaksi login satu kali pakai (digest state dan cookie korelasi SameSite=Lax terpisah, TTL 10 menit, maksimal 500 baris). Percobaan apa pun, termasuk dari browser tanpa cookie, menghanguskan transaksi.
- Verifikasi ID token oleh library: signature RS256, iss, aud (audiens lain ditolak), azp, exp, nonce, access-token hash. Metadata dan JWKS di-cache 10 menit; saat IdP mati cache lama tetap dipakai; kegagalan signature memicu satu refresh (dibatasi 60 detik) lalu coba ulang.
- Identitas (issuer, subject) tanpa auto-link email. Admin hanya dari config (subject atau grup di claim terverifikasi; claim hilang atau salah bentuk tidak memberi apa pun). User tanpa grant mendapat sesi tapi `403` di semua API manajemen; `/me`, status sesi, dan logout tetap jalan. Principal audit `oidc:<users.id>`, tidak pernah dari nama IdP.
- Sesi OIDC terikat ke fingerprint config (issuer, client, mapping admin): mengubah mapping atau mematikan OIDC mengakhiri sesi.
- UI: tombol "Sign in with SSO", form password darurat dipisah, halaman "No access yet", pesan error dari kode tetap (`auth_error`).
Bukti: `cargo test --workspace` hijau (hub 51 tes, stabil 5/5 run). Tes end-to-end dengan IdP palsu dan token yang ditandatangani kunci RSA uji: admin lewat subject dan grup, user tanpa grant, claim grup rusak, email sama subject beda, nonce/issuer/audience/azp/expired/signature penyerang/alg none/HS256 salah, replay/cookie salah/state palsu/transaksi kedaluwarsa, rotasi JWKS dan pembatasan refresh, IdP mati (cold dan warm), OIDC nonaktif → 404. `cargo audit` hanya warning `proc-macro-error`; `rsa` dikecualikan dengan alasan tertulis (`deny.toml`, `.cargo/audit.toml`). Rehearsal nyata: Keycloak 26.1 di Docker + hub nyata + browser: login Alice (grup admin) → UI terbuka, `/me` oidc admin; Bob → "No access yet", `/orbits` 403; logout lokal; pesan error callback palsu. Cookie `__Host-` Secure bekerja di `http://localhost`. DB dan log tidak memuat token, secret, atau password.
Belum ada / batas: RP-initiated logout dan back-channel logout (logout hanya mengakhiri sesi Tessera, sesi IdP tetap), re-auth dan `max_age` untuk akses sensitif, ES256/PS256 (hanya RS256), limiter pada `/login` dan `/callback` (M4; yang ada hanya batas 500 transaksi pending), revokasi perubahan grup IdP hanya saat sign-in berikutnya (maksimal 8 jam), uji dengan IdP organisasi target, uji logout/MFA di IdP target.
Catatan operasional: image Keycloak 26.1 tertinggal di Docker lokal (~500 MB), container sudah dihapus.
## M4 — Hardening kredensial (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: tidak ada rahasia aktif yang tersimpan mentah dan endpoint publik tidak bisa dibanjiri.
- Pairing code dan token Outpost hanya tersimpan sebagai digest SHA-256 (`db/credentials.rs`: `pairing_codes`, `outpost_credentials`). Token dibuat saat klaim (256 bit dari OsRng) dan hanya ada di respons klaim. Masa berlaku `TESSERA_OUTPOST_TOKEN_DAYS` (default 365).
- Migrasi di tempat dari `wormhole_tokens`: token aktif tetap berfungsi dan mendapat masa berlaku baru dari waktu migrasi (expiry lama adalah expiry kode, bukan token); kode belum terpakai tetap dengan expiry-nya, token pra-cetak dibuang; tabel lama di-drop dengan `secure_delete`. Tidak ada referensi `wormhole_tokens` di luar migrasi.
- Rotate (`POST /wormhole/outposts/:id/rotate?grace_minutes=`; token lama hidup selama grace, 0 = langsung putus) dan revoke (`.../revoke`), keduanya admin-only dan diaudit. Outpost yang dicabut ditolak pada request berikutnya, termasuk di endpoint yang membawa lease, dan harus di-pair ulang.
- `governor` per sumber untuk login darurat, klaim pairing, dan SSO login/callback; plafon akun dan klaim global lebih longgar; semaphore Argon2 (2 permit) dengan `try_acquire` dan permit dibawa ke dalam `spawn_blocking`. Sumber = alamat peer; `X-Forwarded-For` hanya dari `TESSERA_TRUSTED_PROXIES`, dibaca kanan ke kiri; IPv6 per /64; penolakan diaudit maksimal sekali per menit per sumber.
- Listener mTLS sekarang menyuplai alamat peer ke handler.
- Token admin bersama bisa diberi tanggal akhir (`TESSERA_ADMIN_TOKEN_EXPIRES`); lewat tanggal ditolak (dan tidak jatuh ke mode development anonim); tiap pemakaian tercatat sebagai `legacy-admin-token`.
Bukti: `cargo test --workspace` hijau (hub 70 tes), `cargo audit` hanya `proc-macro-error`, `cargo deny` ok. Tes: tidak ada token/kode mentah di file DB (termasuk `-wal`/`-journal`, dengan sanity check bahwa scan benar-benar membaca file), klaim sekali pakai, expiry/revoke/rotasi dengan clock injeksi, migrasi legacy (token aktif dengan expiry lama tetap jalan, scrub, idempoten), pairing→claim lewat HTTP nyata, revoke → 401 di endpoint upload dan endpoint lease, flood satu sumber tidak menghabiskan kuota sumber lain dan header palsu tidak membantu, audit penolakan sekali per menit, Argon2 terbatas dan permit dilepas, token admin kedaluwarsa, tes lewat listener mTLS sungguhan (gagal 500 bila penyisipan peer dilepas). Proses nyata pada DB bergaya lama dengan token sintetis: migrasi, token lama tetap 200, tidak ada teks mentah di file DB, pairing/rotate/revoke via HTTP, audit sesuai, tidak ada token di DB maupun log.
Belum ada / batas: rotasi oleh agen sendiri (operator yang mengantar token baru; grace window jadi jembatannya), tanggal akhir token admin sengaja tetap opsional (keputusan Sen, 14 November 2026; peringatan saat start bila `TESSERA_ADMIN_TOKEN_EXPIRES` tidak diset, jadi token bisa tetap permanen sampai tanggal itu dipasang), limiter di memori (reset saat restart, tidak dibagi antar proses), tidak ada `Retry-After` di respons 429, endpoint list Outpost belum menampilkan status/expiry kredensial, tidak ada UI untuk rotate/revoke, backup DB lama masih memuat token mentah sehingga rotasi setelah upgrade wajib. Migrasi hanya diuji pada salinan; belum dijalankan pada hub produksi.
## M5 — Hak akses per scope (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: user biasa hanya melihat dan memakai orbit yang diberikan; administrator tetap memegang semuanya.
- Model: permission bertipe (`auth.rs`) dan tabel `access_grants` (user atau grup IdP, permission, global atau satu orbit, expiry, pembuat). Tanpa Casbin. Hanya `orbit.read`, `snapshot.read`, `capture.run`, `snapshot.download` yang dapat diberikan ke non-admin; semua permission lain (kelola orbit/profil/Outpost/retensi, hapus snapshot, restore, akses) hanya dimiliki administrator terkonfigurasi dan tidak dapat didelegasikan. Role `viewer`, `capturer`, `downloader` hanya jalan pintas yang diperluas menjadi permission (selalu termasuk `orbit.read`).
- Satu gate (`api/gate.rs`): `authenticate` (401 atau CSRF 403), resolve resource, lalu `admin_only` / `scoped` / `visible`. Orbit tanpa `orbit.read` = 404, terlihat tapi tanpa izin = 403, daftar tanpa akses sama sekali = 403, route admin-only = 403 tanpa lookup resource. `require_admin*` dihapus agar compiler memaksa tiap handler memilih gate. Grant dibaca dari DB di setiap request (tidak ada cache), jadi cabut grant, expiry, nonaktifkan user, dan "sign out everywhere" berlaku di request berikutnya.
- Filter sebelum LIMIT untuk riwayat capture job (`json_each` di SQL), daftar snapshot/orbit/profil terfilter, grup diambil dari token saat sign-in dan disimpan di sesi (batas 64 grup x 128 karakter).
- Atribusi memakai identitas stabil (`oidc:<users.id>`, `emergency:<nama>`, `legacy-admin-token`), tidak pernah nama dari IdP; pekerjaan baru tidak bisa menyamar sebagai `scheduler`. (Baris lama di DB tetap memuat nama lama.)
- API admin: `/api/v1/access/grants` (GET/POST/DELETE), `/access/users` (GET, PUT aktif/nonaktif, revoke-sessions). Validasi: permission tidak dikenal atau bukan prefix, tidak dapat diberikan, role tidak dikenal, role dan permission bersamaan, user/orbit tidak ada, expiry lampau atau lebih dari 2 tahun, grup terlalu panjang, duplikat 409; admin tidak bisa menonaktifkan diri sendiri atau akun darurat. Semua perubahan diaudit per id.
- UI: tab Access (admin) untuk memberi dan mencabut akses, daftar orang yang sudah sign in; non-admin hanya melihat Vault dan Activity, tombol capture/download/hapus/restore sesuai grant, dan tidak memanggil endpoint admin. `/me` mengembalikan `admin`, `capabilities`, `grants`.
- Kontrak endpoint diperbarui: tiga endpoint restore (`restore-targets` dua rute dan `snapshots/:id/restore-jobs`) dan `restore-jobs` GET kini admin-only (identity database tujuan; lihat plan bagian 7) sampai self-service M6.
Bukti: `cargo test --workspace` hijau (hub 83 tes, 12 tes baru). Matriks dibangkitkan dari file kontrak dengan resource nyata di dua orbit untuk enam jenis pemanggil (anonim, tanpa grant, viewer orbit lain, viewer, capturer, downloader, anggota grup, admin): route baru yang tidak ada resepnya membuat tes gagal, user tanpa grant tidak pernah mendapat 2xx, dan tiga mutasi sengaja (download hanya butuh `orbit.read`, reconcile tanpa gate admin, daftar job tanpa filter) semuanya tertangkap. Rehearsal browser nyata dengan Keycloak 26.1: Bob "No access yet" -> Alice memberi viewer pada `wiki` lewat tab Access -> Bob melihat 1 orbit dan 14 snapshot (admin 12 orbit dan 185), hanya tab Vault dan Activity, semua request 200 tanpa 403/404 dan tanpa `restore-jobs`/`access` -> grant dicabut -> UI Bob kembali ke "No access yet" pada siklus polling berikutnya.
UI Access memakai komponen yang sama dengan form lain (`Select` bertema dan `DatePicker` kustom dengan navigasi keyboard). Pilihan tampilan Window/Radar disimpan per akun (`/api/v1/me/preferences`, tabel `user_preferences`), bukan hanya di browser.
Keputusan Sen (14 November 2026): admin tetap boleh mengunduh semua snapshot tanpa grant eksplisit (rencana awal meminta grant untuk data sensitif; kebijakan data mentah per orbit dipertimbangkan lagi di M6).
Belum ada / batas: principal `service` bergrant (hanya user dan grup; token admin lama = admin), grant atas nama grup berlaku dari token saat sign-in, UI tidak menyembunyikan satu per satu aksi untuk orbit tanpa izin di semua panel (backend tetap menolak), tidak ada pra-otorisasi user yang belum pernah sign in, tidak ada UI per-orbit untuk melihat siapa saja yang punya akses, pencarian vault masih menampilkan konsol admin untuk non-admin (navigasi diabaikan).
## M6 — Self-service data (dipecah 14 November 2026, menunggu konfirmasi urutan)
Desain rinci lama: `archive/auth-self-service-plan.md` bagian 7–9. M6 menyentuh restore ke database sungguhan, jadi dipecah menjadi empat sub-milestone yang masing-masing bisa dirilis dan diuji sendiri.
### M6a — Download terkompresi untuk developer (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: `GET /snapshots/:id/download` mengirim arsip yang memang terkompresi, bukan dump mentah.
- Format ditentukan dari isi file (magic byte) dan metadata, bukan dari nama: SQL polos jadi `.sql.gz`, tar jadi `.tar.gz`, SQLite jadi `.sqlite.gz`, arsip filesystem hub jadi `.tessera-fs.gz`, konten tak dikenal jadi `.dump.gz`; `pg_dump -Fc` tetap `.dump`; gzip/zstd/xz/bzip2/zip tidak dikompresi dua kali (isi menang atas label). Tabel diturunkan dari setiap produsen manifest yang ada (agen, provider hub, restic filesystem, wormhole lama, SQLite lama, demo). Konsumen endpoint ini hanya tautan unduh di UI; agen dan CLI tidak memakainya.
- Header jujur: tanpa `Content-Encoding`, `Content-Length` hanya untuk byte yang dikirim apa adanya, `application/gzip`, `nosniff`, `no-store`; HEAD 405 (tidak menjalankan ekspor).
- Urutan: autentikasi, cari snapshot, cek izin pada orbitnya, baru admission (semaphore, default 2, dan sisa disk 512 MiB) sehingga pemanggil tanpa izin tidak dapat menghabiskan slot. Permit dan direktori ekspor ikut hidup bersama body respons; frame dibatasi 64 KiB.
- Audit `export.requested/ready/finished/disconnected` per snapshot dan principal; direktori `tessera-export-*` dihapus saat selesai, klien putus, dan saat start berikutnya setelah crash (hanya awalan itu, hanya di level atas data dir).
Bukti: `cargo test --workspace` hijau (hub 94 tes). Tes: tiap jenis snapshot dengan hasil dekompresi sama persis dengan byte asli, header, 24 MiB dialirkan dalam frame di bawah 256 KiB, audit dan pembersihan untuk unduhan selesai dan ditinggalkan, batas satu slot (ditolak seketika, slot kembali), disk tidak cukup (507), HEAD, pemanggil tanpa izin tidak memakai slot, sweep hanya menyentuh milik sendiri; tiga mutasi sengaja tertangkap (Content-Length pada gzip, PGDMP dikompres ganda, unduhan ditinggalkan tercatat selesai). Proses nyata dengan producer asli (orbit filesystem via restic): `.tar.gz`, `gunzip -t` ok, hasil ekstrak identik dengan file asli (termasuk 24 MiB acak); curl dibatasi lajunya lalu dibunuh di tengah: direktori ekspor hilang dan tercatat `export.disconnected`; stale dir dibersihkan saat restart tanpa menyentuh folder lain; HEAD 405. `cargo audit`/`deny` tidak berubah (async-compression 0.4.36, rustix 1.1.6, tanpa duplikat baru).
Batas: snapshot yang tersimpan sebagai chunk vault dibaca utuh ke memori saat diekspor (hanya yang berbasis restic dan tahap kompresi yang terbatas); SQL asli dari PostgreSQL/MySQL baru diuji lewat fixture, rehearsal dengan database sungguhan ada di M6d; tidak ada checksum arsip hasil kompresi karena streaming; sisa `.tmp*` dari kode lama tidak disapu.
### M6b — Environment dan relasi production → staging (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: DevOps menyatakan "sumber X boleh menimpa target Y", dan hak memakainya bisa diberikan per relasi.
- Environment (production/staging/development) di orbit sumber dan di restore target (bukan orbit placeholder, supaya staging tidak muncul di galaksi, scheduler, retensi, dan binding Outpost lama). Belum dilabeli = ditolak; target berlabel production ditolak.
- `orbit_relations` berarah (sumber orbit managed ke restore target), berversi (retarget membuat id baru, versi berikutnya, yang lama `replaced`), tidak simetris/transitif, satu relasi aktif per pasangan (indeks unik parsial). Aturan dengan kode penolakan: sumber tidak dikenal atau belum dilabeli, bukan capture profile managed, format tidak restore-ready, target tidak dikenal atau belum dilabeli atau production, aplikasi target berbeda, engine berbeda, target cocok dengan database yang di-capture sebagai production/belum diklasifikasi (dibaca dari `source_identity` snapshot semua orbit; backup staging/development milik target sendiri tidak dihitung), Outpost tidak aktif, duplikat. Fakta yang ada di DB diperiksa ulang di dalam transaksi; sumber tanpa snapshot ditandai `verified=false` agar M6c memeriksa ulang sebelum apply.
- Relasi mati di transaksi yang sama saat target di-relabel production atau Outpost dicabut, dan `usable` dihitung ulang saat dibaca (kredensial kedaluwarsa); diaudit.
- Hak `refresh.run` per id relasi di tabel sendiri `relation_grants` (user atau grup, expiry), tanpa global dan tanpa ikut ke versi baru (fail-safe); `refresh.run` bukan permission `access_grants` sehingga `scoped` dan `visible` tidak pernah menerimanya; gerbang relasi sendiri (`gate::relation`, `visible_relations`).
- API (admin, `relation.manage`): `/orbits/:id/environment`, `/restore-targets/:id/environment`, `/relations` (GET untuk wizard dengan identity, POST), `/relations/:id` (PUT retarget, DELETE), `/relations/:id/access` (+ `/:grant`). Orang dengan grant relasi hanya melihat `GET /refresh-relations`: nama dan environment, tanpa identity, host, Outpost, atau application id. `POST /restore-jobs` admin tidak diubah.
- UI: konsol Relations (admin) dengan `Select` yang sama: label environment, form hubungkan sumber ke target (hanya target yang cocok ditawarkan), retarget, akhiri, dan siapa yang boleh refresh.
Bukti: `cargo test --workspace` hijau (hub 106 tes; 12 tes baru: 9 store, 5 HTTP termasuk matriks yang diperluas dengan jenis `RelationList`, fixture relasi di dua orbit, dan pemanggil yang hanya punya grant relasi). Tes: setiap aturan punya penolakannya sendiri, arah, versi, grant tidak ikut retarget, relabel production dan revoke Outpost mematikan relasi seketika, kredensial kedaluwarsa membuatnya tidak usable, database production berlabel staging tertangkap lewat snapshot, grant per user dan grup dengan expiry, tampilan refresher tanpa identity/host. Empat mutasi sengaja tertangkap (daftar refresher menampilkan semua, retarget tanpa gerbang admin, target production diterima, relabel tidak mematikan relasi). Rehearsal browser dengan hub asli (data sintetis): label environment lewat Select, hanya sumber yang siap dan target yang cocok ditawarkan, relasi dibuat (version 1, "not yet compared"), grup diberi akses, retarget menjadi version 2 dengan akses kosong, relabel target production mengakhiri relasi dan UI menampilkan pemberitahuan.
Catatan untuk M6d: pengguna yang hanya punya grant relasi belum dianggap `authorized` oleh status sesi dan vault UI memanggil `/orbits` dan `/snapshots` saat load (403); UI QA harus menangani itu (hitung grant relasi atau wajibkan viewer pada orbit sumber).
Belum ada / batas: relasi belum menjalankan apa pun (M6c); sumber yang di-capture tidak di-cek terhadap target yang sama bila snapshot-nya belum ada (ditandai belum dibandingkan); pendaftaran restore target masih lewat Orbits console dan memerlukan Outpost aktif; ekstra: form login tanpa SSO tidak lagi menampilkan label "Details" dan memakai gaya field yang sama.
### M6c — Refresh run durable (backend) (selesai di working tree, belum di-commit, 14 November 2026)
Hasil: satu permintaan "refresh staging" menjalankan capture baru lalu restore snapshot hasil capture itu, tanpa persetujuan DevOps per eksekusi.
- `refresh_runs` (di SQLite, bertahan setelah restart): `capturing`, `restoring`, lalu `completed`, `capture_failed`, `restore_failed`, `blocked` (dengan alasan), `expired`, `cancelled`, `recovery_required`, `reconciled`. Satu run aktif per target (indeks unik parsial), kunci idempotensi per pemohon, plafon run serentak (`TESSERA_REFRESH_MAX_ACTIVE`), TTL sampai mulai menimpa (`TESSERA_REFRESH_TTL_MINUTES`, default 120 menit; setelah apply dimulai tidak pernah dipotong).
- Run dan capture job dibuat dalam satu transaksi; run mengikuti `capture_job_id`-nya sendiri (id snapshot sama dengan id job), bukan "snapshot terbaru", sehingga capture gagal tidak pernah memakai snapshot lama. Restore di-enqueue dan dikaitkan dalam satu transaksi dengan penjaga `restore_job_id IS NULL`; setiap langkah aman diulang setelah crash. Snapshot dipin sejak run dimulai lewat `snapshot_in_restore` (dipakai prune retensi dan hapus manual).
- Pemeriksaan ulang sebelum menimpa: `authorize_apply` memeriksa dalam transaksi yang sama dengan perpindahan ke `applying` bahwa relasi masih aktif dan usable, pemohon masih user aktif, grant yang mengotorisasi masih ada dan belum kedaluwarsa, TTL belum lewat, dan target bukan database sumber. Bila tidak, restore dibatalkan, run `blocked`, agen mendapat 409 (agen tidak menimpa apa pun tanpa 2xx; dicek di `tessera-agent`). Restore yang diantrekan admin langsung (`POST /restore-jobs`) tidak punya run dan berperilaku persis seperti sebelumnya (ada tesnya). Sesudah apply dimulai, run diselesaikan, bukan dibatalkan.
- Driver (`refresh.rs`) hanya melihat DB setiap 3 detik; pembacaan manifest snapshot dilakukan di luar kunci DB, lalu transaksi memvalidasi ulang sebelum meng-enqueue restore. Alasan penolakan sebelum restore: relasi berakhir atau tidak usable, user dinonaktifkan, akses dicabut, kedaluwarsa, target cocok dengan database production yang di-capture, target ditolak oleh pemeriksaan restore.
- API: `POST /refresh-runs` (relation_id + konfirmasi `REFRESH <sumber> TO <target> v<versi>` + kunci idempotensi; 404 bagi yang bukan pemegang grant; 409 `stale_confirmation`, `run_active` dengan id hanya bagi yang boleh melihatnya, `source_unavailable`, `relation_unusable`), `GET /refresh-runs`, `GET /refresh-runs/:id`, `DELETE /refresh-runs/:id` (pemohon atau admin, sebelum apply). Non-admin tidak melihat id snapshot, pemohon, atau identity database. Audit `refresh.*` per run.
Bukti: `cargo test --workspace` hijau. 13 tes refresh yang menjalankan agen lewat endpoint Outpost sungguhan (claim, report, payload dengan manifest dan hint asli, claim restore, safety, apply): alur penuh dengan snapshot milik run (bukan yang lama), double submit satu run, dua kunci pada satu target satu run dan satu 409, capture gagal tidak memakai snapshot lama, pencabutan (grant dihapus, user dinonaktifkan, relasi di-retarget, target di-relabel production, Outpost dicabut) pada tiap tahap (saat capture, setelah capture sebelum restore diantrekan, restore diantrekan, setelah safety backup sebelum apply) selalu berakhir `blocked` dengan restore dibatalkan dan apply ditolak 409, setelah apply dimulai tidak ada yang membatalkan, restore admin tidak tersentuh, pin dari awal (hapus ditolak, prune melewatkannya) dan dilepas saat selesai, TTL, konfirmasi basi dan plafon, visibilitas dan pembatalan, kepemilikan langkah yang diulang, target = sumber atau cocok dengan production. Matriks akses diperluas dengan jenis `RunRow` dan run fixture. Mutasi sengaja tertangkap: guard apply dihapus, pin dihapus, sinkronisasi mengabaikan hilangnya otorisasi, tanpa kedaluwarsa, semua orang bisa membaca run, pemegang grant bisa membatalkan run orang lain. Proses nyata (hub sungguhan, data sintetis, agen disimulasikan dengan curl ke endpoint Outpost): loop driver menggerakkan run ke `restoring` sendiri dengan restore memakai snapshot milik run, run bertahan setelah hub dimatikan dan dinyalakan lagi, relabel target menjadi production membuat run `blocked` dan restore `cancelled`.
Belum ada / batas: UI QA (M6d); sumber yang dibuat lewat API memakai jalur commit Restic (payload langsung ditolak 409), jadi rehearsal dengan agen, Restic, dan PostgreSQL asli ada di M6d; untuk grant grup, hub hanya memeriksa bahwa grant masih ada, bukan bahwa orang itu masih anggota grup (dicatat di dokumentasi); admin yang diturunkan lewat konfigurasi tidak menghentikan run yang sudah dimulai; pemanggilan gate relasi saat memulai run bersifat berlapis (pencarian grant memberi 404 yang sama), jadi mutasi yang menghapusnya hanya menghilangkan satu baris audit.
### M6d — UI refresh QA dan rehearsal nyata
Hasil: QA menekan "Refresh staging" dan melihat progres; developer mengunduh `.gz`.
- UI QA (relasi yang boleh dipakai, peringatan staging akan ditimpa, konfirmasi, progres, error yang dibedakan) dan tampilan developer.
- Rehearsal nyata: PostgreSQL production sintetis dan staging di Docker, agen nyata, capture → restore, bandingkan skema dan data, revoke di tengah run, retry, unduh `.gz` dan muat ulang.
Selesai bila: e2e browser untuk QA dan developer dengan assertion API deny, dan hasilnya dicatat di sini.
Hasil (selesai, belum di-commit):
- Backend: orang yang hanya punya grant relasi (tanpa `orbit.read`) kini `authorized` (bisa masuk aplikasi) dan `/me.refresh_relations` memuat relasinya; semua endpoint vault tetap 403. Tes baru `someone_who_may_only_refresh_gets_into_the_app_but_sees_nothing_else`. Hub 120 tes hijau, web 75 tes, typecheck dan build bersih.
- UI: konsol "Refresh" (`components/refresh/RefreshView.tsx`): kartu per relasi, peringatan staging ditimpa + kotak centang sebelum tombol aktif, kunci idempotensi per percobaan, progres dari fase capture/restore, "data per" waktu snapshot, tombol batal (nonaktif saat menimpa), pesan terpisah untuk capture_failed / restore_failed / recovery_required / blocked (dengan alasan) / expired / cancelled. Item rail "Refresh" untuk admin dan pemegang grant; yang hanya boleh refresh mendapat layar tunggal tanpa memuat query vault.
- Rehearsal nyata (data sintetis; PostgreSQL 14.25 prod + staging di Docker, hub dan agen nyata, jalur payload langsung karena `rest-server` tidak ada): refresh admin selesai; skema dan data staging identik dengan prod (dump tanpa baris `\restrict` cocok); staging yang berisi tabel dan baris asing kembali persis seperti prod. Relasi dihapus di tengah run -> `blocked: relation_ended`, staging tidak berubah (baris sentinel tetap). Relasi baru + run ulang -> selesai, sentinel hilang, baris baru prod muncul.
- Browser nyata (Keycloak 26.1, Vite -> hub): `qa` "No access yet" -> admin memberi grant relasi -> layar Refresh saja; centang + Overwrite -> progres -> selesai, staging terisi data prod terbaru; request jaringan hanya `refresh-relations`/`refresh-runs`, tanpa 403. Dari sesi QA: orbits/snapshots/capture-jobs/restore-jobs/relations/access (users, grants)/capture-profiles 403; POST restore-jobs 403; POST relations (body valid) 403; refresh dengan konfirmasi salah 409, tanpa CSRF 403, relasi tak dikenal 404; respons relasi hanya id, versi, nama, environment, usable. Grant dicabut -> UI kembali ke "No access yet" pada poll berikutnya. `dev` (viewer 1 orbit): 1 orbit, 7 snapshot, hanya tab Vault dan Activity; refresh, relasi, restore-jobs, access semuanya 403.
- Unduhan: dump PostgreSQL custom diunduh sebagai `.dump` apa adanya (sudah terkompresi, `PGDMP`, `pg_restore --list` valid); bungkus gzip hanya untuk SQL polos, sesuai desain M6a. Jadi "unduh .gz" berlaku untuk SQL, bukan untuk format custom.
- Belum diverifikasi: tampilan admin (item rail Refresh) di browser nyata; Restic via `rest-server` TLS (agen wajib `rest:https://`, tidak ada di mesin ini); `cargo deny`/`cargo audit` tidak terpasang di shell ini (tidak ada perubahan dependensi di M6d, hasil M6c tetap berlaku). 422 untuk body kosong pada POST non-admin hanyalah urutan parse sebelum gate; dengan body valid 403.
Di luar M6: approval per refresh, masking data, restore lokal developer, multi-hub. Kebijakan data mentah: izin eksplisit adalah grant `snapshot.download` itu sendiri (UI memberi peringatan); tidak ada flag klasifikasi tambahan kecuali Sen meminta.
## M7 — Rilis
Migrasi pada salinan DB nyata, rehearsal dengan IdP target, dokumentasi bootstrap admin dan rollback, review keamanan khusus auth.
## Di luar lingkup
Multi-tenant, multi-issuer, SCIM, device flow untuk CLI, manajemen password publik, policy engine generik, approval per refresh.
## Urutan dan dependensi
M0 → M1 → M2 → M3 → M4 → M5 → M6 → M7. M4 tidak bergantung pada M3 dan boleh dikerjakan paralel setelah M2.

View File

@@ -0,0 +1,137 @@
# Pilihan library dan tool untuk auth/self-service Tessera
Riset: 11 November 2026. Rekomendasi awal kini dilengkapi spike terisolasi dengan manifest/lockfile dan enam tes: [hasil A00](../tests/auth-compat/README.md). Tidak ada dependency auth/layanan baru pada runtime. A00 belum diterima karena audit dan verifikasi tersisa. Versi/features/MSRV/license serta temuan RustSec nyata dicatat di hasil tersebut. Rencana per milestone: [auth-plan.md](auth-plan.md) (rencana A00–A25 lama ada di archive/; label A-nomor di dokumen ini merujuk ke sana).
## Keputusan singkat
1. Pakai **openidconnect** untuk OIDC, bersama HTTP client yang didukung; jangan membuat OAuth/JWT/JWKS verifier sendiri.
2. Prioritaskan **tower-sessions** untuk sesi/cookie/rotasi. Tetap perlu storage adapter rusqlite dan aturan absolute timeout/revocation Tessera. Adopsi setelah compatibility spike, bukan menyalin API latest ke Axum 0.7.
3. Pakai **governor** untuk algoritma rate-limit, Tokio Semaphore untuk concurrency. tower_governor opsional bila versi middleware cocok.
4. Pakai **async-compression** untuk gzip asynchronous. flate2 alternatif jika pipeline akhirnya berupa synchronous artifact worker. Pilih satu jalur, bukan keduanya tanpa kebutuhan.
5. Evaluasi **Casbin embedded** untuk evaluasi permission, tetapi jangan mengganti model domain dengan policy string. Untuk scope tetap/sederhana, typed permission + query rusqlite yang ada tetap baseline terkecil. Tidak ada keputusan final Casbin sebelum tes policy/revocation.
6. Gunakan ulang **Restic, antrean/lease SQLite, provider DB, React Query, komponen UI, tracing dan utoipa** yang sudah ada.
7. Test tooling: **wiremock**, **Playwright Test**, dan **Keycloak sebagai IdP fixture**. Reuse IdP organisasi untuk deployment bila sudah ada; Keycloak bukan dependency produksi wajib.
8. **rusqlite_migration** layak untuk migrasi bernomor bila cocok versi SQLite binding. **cargo-deny/cargo-audit** untuk gate supply chain. Tidak mengganti rusqlite dengan ORM semata-mata demi satu adapter.
## Kondisi repo yang menentukan pilihan
- Cargo workspace: axum 0.7, tower 0.5, tower-http 0.6, rusqlite =0.31.0 bundled, tokio =1.40.0, argon2 =0.5.3, utoipa 4.2; image build Rust 1.88 (Dockerfile).
- Frontend: React 19, TanStack React Query 5, Vite 6, TypeScript 5.6. Komponen dan API client rumah sudah tersedia.
- Cargo.lock memuat subtle sebagai dependency transitif; openidconnect, reqwest, governor, tower-sessions, async-compression, flate2, wiremock belum ditemukan dalam lock saat riset.
- Restore provider sudah memakai executable gzip untuk membaca sebagian arsip; itu tidak otomatis berarti executable tersebut tersedia di seluruh instalasi hub/native.
- Tidak ada satu paket yang menggantikan seluruh auth/RBAC/restore. Library mengurangi kode protokol, algoritma dan transport; keputusan izin terhadap database production tetap milik aplikasi.
## Matriks setiap task
| Task | Library/tool yang dipakai atau dievaluasi | Keputusan dan pekerjaan Tessera yang tersisa |
| --- | --- | --- |
| A01 kontrak endpoint | utoipa + axum/tower::ServiceExt yang sudah ada [S15] | Reuse untuk kontrak/OpenAPI dan tes request; tetap tulis matriks aksi/resource, bukan menebak permission dari HTTP method. |
| A02 isolasi Outpost | rusqlite transactions/FK/unique constraints + identitas agent yang ada | Reuse. Tidak ada crate RBAC yang otomatis mengetahui pemilik orbit/upload. Simpan owner dan periksa di boundary init/chunk/seal. |
| A03 fail-closed/bootstrap | axum middleware dan deployment HTTPS yang ada | Reuse gate/startup config. Auth proxy hanya tambahan; jangan menggantikan backend authorization dengan trusted header tanpa trust boundary eksplisit. |
| A04 principal/audit | serde + tracing + SQLite audit [S14] | Reuse. tracing untuk diagnostics; audit durable perlu insert transaksi dan actor/resource/outcome yang didesain aplikasi. |
| A05 digest token | RustCrypto sha2/hmac + rand yang sudah ada; subtle direct [S7] | Reuse primitives. CSPRNG untuk token high-entropy, digest untuk lookup dan constant-time comparison untuk secret relevan. Tidak perlu JWT untuk token opaque. |
| A06 lifecycle token | primitives A05 + tabel/transaksi SQLite | Domain code kecil untuk rotate/revoke/expiry dan audit. Vault/IdP tidak otomatis mencabut token Outpost lokal. |
| A07 sesi | tower-sessions, custom rusqlite SessionStore [S2] | Kandidat utama; library mengelola lifecycle sesi. Adapter menyimpan digest ID dan record aman; absolute deadline, recent-auth, per-user revoke tetap aturan lokal. |
| A08 limiter/emergency | governor + Tokio Semaphore; Argon2id existing [S4,S7,S13] | Pakai algoritma standar. Key tepercaya, backoff akun, quota global, TTL cleanup dan audit tetap dikonfigurasi; state limiter lokal hanya cocok satu hub. |
| A09 OIDC | openidconnect + supported async HTTP client/reqwest [S1] | Rekomendasi adopsi. Discovery, PKCE dan ID-token verification dari library; transaksi callback/state, JWKS refresh strategy dan account mapping tetap integrasi aplikasi. |
| A10 login/logout UI | tower-sessions + redirect server + IdP existing/Keycloak fixture [S2,S9] | Reuse OperatorGate. Tidak perlu SDK OIDC React karena code flow dan token di backend. Logout lokal wajib; global/logout callback mengikuti dukungan IdP. |
| A11 RBAC scoped | Casbin embedded kandidat; typed gate + rusqlite baseline [S3] | Spike keduanya dengan matriks yang sama. Casbin dipilih bila mengurangi kode keseluruhan; cek relasi/environment/lease di domain tetap wajib. |
| A12 enforcement semua API | axum extractor/middleware + selected A11 gate | Reuse. Framework tidak memfilter row/list otomatis; per-resource scope dan safe output tetap di handler/query. |
| A13 admin grant/grup | selected A11 + IdP groups; React Query existing | UI mengelola grant Tessera, bukan membangun user directory atau password manager. Grup diverifikasi issuer dan mapping eksplisit. |
| A14 environment/target | core models + rusqlite + provider identity checks yang ada | Reuse dan perluas data model. Tidak perlu graph DB/ORM untuk binding orbit → restore target. |
| A15 relasi berarah | SQLite FK/unique + selected gate A11 | Domain code. OpenFGA alternatif ketika graph izin lintas banyak aplikasi benar-benar diperlukan, bukan untuk satu tabel relasi [S10]. |
| A16 wizard DevOps | komponen UI rumah + React Query existing | Reuse form/profile/target; jangan menambah admin framework/form framework hanya untuk wizard ini. |
| A17 run durable | existing job tables/transactions + idempotency constraint | Reuse. Apalis dapat mengelola background job tetapi tidak mengganti assignment agen/lease/domain state yang sudah ada [S11]. |
| A18 capture→restore | existing queue/worker + Restic snapshot spesifik [S12] | Reuse. Pin snapshot dan link child jobs secara transaksi; Temporal ditunda karena migrasi orchestration/service tambahan belum memberi manfaat [S11]. |
| A19 revoke/safety/recovery | existing restore lease/fencing/provider + gate A11 | Reuse. Library auth tidak dapat menjamin safe cancel setelah reset DB; state machine recovery tetap milik Tessera. |
| A20 UI QA | DatabaseRestore/JobHistory + React Query existing | Reuse polling/status; tidak perlu workflow designer atau state-machine UI library. Backend adalah sumber state persisten. |
| A21 kompresi | async-compression(tokio,gzip) + ReaderStream + tempfile existing [S5] | Adopsi gzip adapter. flate2 alternatif artifact blocking worker; jangan menggunakan HTTP CompressionLayer sebagai pengganti file .gz [S5,S6]. |
| A22 download developer | browser native download + existing API/catalog; Playwright [S8] | Tanpa file-saver/Blob buffer besar. Grant, pin, quota, lifetime temp dan audit tetap server-side. |
| A23 audit lengkap | tracing + audit SQLite yang ada; request IDs tower-http [S6,S14] | Reuse. Log observability bukan pengganti audit transaksi; redaksi dan event coverage harus diuji. |
| A24 migrasi/kontrak | rusqlite_migration kandidat; utoipa existing; cargo-deny/audit [S15,S16,S17] | Adopsi migration helper jika kompatibel dan lebih kecil dari runner lokal; jangan upgrade DB binding/ORM besar tanpa manfaat terukur. |
| A25 rehearsal/rollout | wiremock + Playwright Test + Keycloak fixture + harness MBU [S8,S9,S18] | Dev tools, bukan runtime wajib. Test IdP nyata, proxy, PostgreSQL/MySQL, revoke dan download; tidak menggantikan rollout rehearsal dengan unit test. |
## OIDC: openidconnect, bukan auth protokol buatan sendiri
Dokumentasinya menyediakan discovery, code flow dengan PKCE, typed token dan validator ID token. Pakai async client dan nonaktifkan HTTP redirect untuk discovery/token/JWKS request. Rekomendasi: openidconnect menjadi satu-satunya lapisan protokol OIDC; jangan menambahkan jsonwebtoken verifier paralel untuk token yang sama. [S1]
Tetap perlu: issuer config, callback URL statis, browser correlation sekali pakai, membership/grant, error redaction, kebijakan algorithm/claims, cache/refresh JWKS dan outage behavior. Dukungan fitur library tidak membuktikan flow aplikasi aman; uji misuse/replay.
Context7 resolve untuk openidconnect tidak menemukan paket yang relevan pada sesi ini; dokumentasi crate resmi dipakai sebagai fallback. Nomor versi di docs latest bukan pin implementasi.
## Sesi: tower-sessions dan biaya adapter
tower-sessions menawarkan SessionStore, expiry, cookie dan rotasi sesi. Gunakan implementasi create yang collision-safe. Prioritas integrasi: custom adapter terhadap koneksi/database rusqlite yang sudah ada; jangan menambah SQLx dan pool kedua hanya agar dapat memakai stock SQLite store. Adapter wajib diuji untuk concurrent request vs revoke agar sesi yang dihapus tidak hidup kembali. [S2]
Idle dan absolute timeout tidak otomatis menjadi satu kebijakan hanya dengan satu expiry option. Absolute auth deadline, auth_time dan status user tetap diperiksa di gate. Digest ID di key adapter tidak boleh dibatalkan dengan menserialisasi raw ID ke kolom record lain.
axum-login bukan OIDC provider/client dan tidak menyelesaikan scope resource. Changelog menyatakan 0.17 pindah ke Axum 0.8; tower-sessions 0.14 pindah ke axum-core 0.5. Karena repo Axum 0.7, jangan pin versi lama hanya karena bisa compile tanpa menilai security fixes. Spike membandingkan compatible maintained release/backport dengan upgrade Axum terpisah. [S2,S19]
## RBAC: Casbin vs scoped gate kecil
Casbin menyediakan evaluator RBAC dengan domain. Itu berguna bila tim memerlukan inheritance/custom roles/policy model yang berubah; enforcer embedded tidak memerlukan service OpenFGA. Namun casbin-rs tidak membundel SQL adapter di core; source-of-truth SQLite, reload/invalidation dan safe concurrent policy update tetap harus dirancang. [S3]
**Keputusan usulan saat ini:** pertahankan typed permission + SQL grants sebagai baseline untuk daftar aksi tetap dan relasi eksplisit. Jalankan spike Casbin sebelum implementasi A11; adopsi bila total kode evaluator+adapter+query filter+tests lebih kecil dan revokasi tetap konsisten. Tidak membuat engine policy generik sendiri.
Kriteria spike: seluruh matriks QA/developer/admin/service/outpost lulus, no-grant deny, relasi terbalik deny, filter daftar konsisten, revoke berlaku request berikutnya dan sebelum apply, tidak ada cache grant stale setelah mutation gagal. Resource label production dan safety identity tetap domain guard yang tidak dapat dibypass policy role admin.
OpenFGA cocok sebagai kandidat evolusi bila authorization menjadi graph bersama lintas layanan; menambah service/source-of-truth izin pada satu-hub MVP belum proporsional. Keputusan ini adalah penilaian kecocokan terhadap arsitektur Tessera, bukan kekurangan kemampuan OpenFGA. [S10]
## Limiter, CSRF, dan token
governor menghindari algoritma limiter buatan sendiri; tower_governor menyediakan integrasi request key. Jangan memakai SmartIpKeyExtractor secara buta di endpoint publik: proxy tepercaya harus menormalisasi sumber IP. Tokios semaphore membatasi operasi hash/export aktif; bukan pengganti durable per-target lock. [S4,S13]
Argon2id yang terpasang tetap digunakan untuk password. Token random high-entropy memakai digest sha2/hmac yang sudah ada; validasi equality memakai subtle yang ditambahkan sebagai dependency langsung jika diimpor. Tidak mengandalkan crate transitif tanpa deklarasi. CSRF synchronizer token dan OIDC state adalah dua kontrol terpisah; gunakan random generator dan constant-time primitive standar, bukan suite auth tambahan untuk beberapa baris glue. [S7]
## Job/capture/restore: gunakan yang sudah berjalan
Restic tetap untuk snapshot/export; provider pg_dump/pg_restore/mysql dan job/lease/fencing yang ada tetap dipakai. Tambahkan durable parent refresh run, bukan scheduler paralel. Apalis dan Temporal adalah alternatif nyata, tetapi migrasi akan menduplikasi atau mengganti queue, retry dan recovery yang sudah teruji. Evaluasi ulang hanya jika muncul distributed workers lintas hub, branching orchestration besar, atau operasi queue lokal menjadi beban nyata. [S11,S12]
Library umum tidak membuktikan restore aman. Verifikasi database identity, safety snapshot, retensi pin, idempotency dan pemeriksaan ulang grant sebelum apply tetap domain Tessera.
## Download: file terkompresi harus benar-benar sebuah arsip
Rekomendasi async-compression dengan fitur tokio dan gzip saja, membungkus reader lalu ReaderStream existing. Batasi concurrency CPU/disk; async I/O tidak menjamin kerja kompresi bebas beban CPU. flate2 cocok bila hasil dibuat oleh worker blocking lebih dahulu. [S5]
CompressionLayer tower-http mengompresi representasi HTTP dan bisa didekompresi oleh client; itu bukan kontrak attachment .sql.gz yang tersimpan sebagai gzip. Payload arsip, ekstensi, content type dan checksum harus selaras. Jangan menggandakan kompresi format yang sudah compressed tanpa alasan. [S6]
Tidak perlu download SDK frontend. Native download + cookie same-origin dan Playwright download assertion mencukupi. Cleanup stream/temp dan metadata filesize tetap diuji; bila ukuran gzip belum diketahui jangan mengirim Content-Length hasil uncompressed. [S8]
## Migrasi dan verifikasi dependency
rusqlite_migration memakai PRAGMA user_version untuk urutan migrasi. Cocok secara konsep, tetapi versinya erat dengan rusqlite dan MSRV; baseline schema existing harus ditandai dengan benar dan tidak boleh ada dua runner yang menguasai user_version. Jika memaksa upgrade bindings besar, tetap gunakan transaksi rusqlite dengan runner minimal yang sudah diaudit. [S16]
Sebelum dependency final dipilih:
- Catat versi, license, MSRV dan tanggal/advisory dari sumber resmi; verifikasi pada image Rust 1.88 yang dipakai repo atau buat task upgrade compiler tersendiri.
- cargo tree untuk memastikan tidak ada incompatible duplicate http/axum-core/tower traits atau dua libsqlite3-sys dengan links konflik. Compile workspace, bukan contoh hello-world saja.
- cargo-deny untuk licenses/sources/bans/advisories dan cargo-audit untuk RustSec. Hasil tanpa advisory bukan bukti kode aman. npm audit untuk dependency frontend/test yang baru. [S17]
- Feature minimal, lockfile committed saat implementasi, uji boundary dan bandingkan kode/infrastruktur yang benar-benar dihapus. Tidak memilih versi latest otomatis.
## Pengujian yang dipakai
wiremock untuk discovery/JWKS/token/error fixtures; response token harus menggunakan kunci test terkontrol agar invalid signature/nonce/issuer/replay benar-benar diuji. Mock HTTP bukan sertifikasi OIDC. Keycloak disposable membuktikan integrasi IdP lengkap dan Playwright membuktikan browser callback/cookie/native download; harness PostgreSQL/MySQL/Restic MBU dipakai ulang. [S8,S9,S18]
Tidak menambah Testcontainers, proptest atau framework UI baru sebelum harness yang ada terbukti tidak cukup. Testcontainers dapat dipertimbangkan terpisah bila lifecycle fixture shell menjadi sumber kegagalan; bukan prasyarat rilis ini.
## Sumber primer
- S1: [openidconnect crate](https://docs.rs/openidconnect/latest/openidconnect/).
- S2: [tower-sessions](https://github.com/maxcountryman/tower-sessions), [changelog](https://github.com/maxcountryman/tower-sessions/blob/main/CHANGELOG.md); juga di-query melalui Context7 /maxcountryman/tower-sessions.
- S3: [casbin-rs](https://github.com/apache/casbin-rs), [RBAC domains](https://casbin.apache.org/docs/rbac-with-domains/); juga di-query melalui Context7 /apache/casbin-rs.
- S4: [governor](https://docs.rs/governor/latest/governor/), [tower_governor](https://docs.rs/tower_governor/latest/tower_governor/).
- S5: [async-compression](https://docs.rs/async-compression/latest/async_compression/), [flate2](https://docs.rs/flate2/latest/flate2/).
- S6: [tower-http](https://docs.rs/tower-http/latest/tower_http/).
- S7: [subtle](https://docs.rs/subtle/latest/subtle/), [Argon2](https://docs.rs/argon2/latest/argon2/).
- S8: [Playwright downloads](https://playwright.dev/docs/downloads), [assertions](https://playwright.dev/docs/test-assertions).
- S9: [Keycloak OIDC endpoints](https://www.keycloak.org/securing-apps/oidc-layers).
- S10: [OpenFGA modeling](https://openfga.dev/docs/modeling/getting-started).
- S11: [Apalis](https://docs.rs/apalis/latest/apalis/), [Temporal architecture overview](https://docs.temporal.io/evaluate/understanding-temporal).
- S12: [Restic restore/export](https://restic.readthedocs.io/en/stable/050_restore.html).
- S13: [Tokio Semaphore](https://docs.rs/tokio/latest/tokio/sync/struct.Semaphore.html).
- S14: [tracing](https://docs.rs/tracing/latest/tracing/).
- S15: [utoipa](https://docs.rs/utoipa/latest/utoipa/).
- S16: [rusqlite_migration](https://docs.rs/rusqlite_migration/latest/rusqlite_migration/), [SQLite PRAGMA](https://www.sqlite.org/pragma.html#pragma_user_version).
- S17: [cargo-deny](https://embarkstudios.github.io/cargo-deny/), [RustSec/cargo-audit](https://rustsec.org/).
- S18: [wiremock Rust](https://docs.rs/wiremock/latest/wiremock/).
- S19: [axum-login changelog](https://github.com/maxcountryman/axum-login/blob/main/CHANGELOG.md).

12
tasks/release-plan.md Normal file
View File

@@ -0,0 +1,12 @@
# Rilis publik (ditahan)
Status: repo siap rilis, belum dirilis. Rilis hanya setelah paritas backup-center terbukti di environment MBU (sesi `tessera-mbu-swap`) dan Sen memberi go.
Sudah: rustfmt + `clippy -D warnings` bersih; README dan CHANGELOG diperbarui; SECURITY.md; CI (`.github/workflows/ci.yml`: fmt, clippy, test, cargo-deny/audit, web); kontrak endpoint dipindah ke `docs/`; `scripts/export-public.sh` membuat tree satu-commit tanpa `tasks/`, `tests/mbu`, dokumen MBU, dan memeriksa referensi privat. Tree hasil ekspor sudah dibuktikan ter-build dan lulus tes sendiri (hub 120, web 75).
Belum / keputusan Sen:
- Riwayat git (40 commit, memuat dokumen MBU dan email penulis) tidak ikut: repo publik dimulai dari tree ekspor sebagai satu commit.
- `cargo-deny` dan `cargo-audit` tidak terpasang di mesin ini; dijalankan oleh CI. `rsa` RUSTSEC-2023-0071 dikecualikan dengan alasan tertulis.
- M7: migrasi pada salinan DB nyata, rehearsal IdP target, dokumentasi bootstrap admin dan rollback, review keamanan khusus auth.
- Biner agent Linux dan image agent belum dipaketkan (Dockerfile hanya hub).
- Nama repo, kontak keamanan, dan versi final (0.1.0) ditentukan saat rilis.

View File

@@ -0,0 +1,30 @@
# Restore di dalam Vault (dibangun)
Keputusan Sen: tidak ada menu baru. Halaman Refresh dihapus; di detail snapshot tombol "Export file on hub" diganti
"Restore", modal restore mendapat selector restore point, lalu hitung mundur dan stepper.
## Alur
1. Klik orbit. 2. Capture bila ingin yang terbaru, atau klik snapshot yang ada. 3. Detail snapshot: tombol Restore
(nonaktif dengan teks "No restore point" bila admin belum membuat relasi). 4. Modal: selector Development/Staging bila
keduanya ada. 5. Begin restore -> hitung mundur 10 detik (Abort tidak mengirim apa pun) -> stepper Checking, Safety copy,
Applying, Completed (Abort masih bisa sampai Applying).
## Yang dibangun
- Izin: tanpa skema baru. Melihat snapshot dan menekan Capture memakai grant orbit yang sudah ada (viewer + capture.run);
Restore memakai grant relasi `refresh.run` yang sudah ada. Pemegang hanya grant relasi tidak lagi punya layar sendiri.
- `POST /api/v1/refresh-runs` menerima `snapshot_id`: restore snapshot yang sudah ada milik orbit sumber relasi (bukan
safety, bukan orbit lain), memakai mesin run yang sama (idempotensi, satu run per target, batal sampai applying,
otorisasi ulang sebelum menimpa). Tanpa `snapshot_id` perilaku lama (capture baru) tetap ada sebagai API.
- `GET /api/v1/refresh-relations` memuat `source_orbit_id`; `GET /api/v1/snapshots` memuat `kind` (capture|safety); UI
menyembunyikan safety.
- Admin: modal yang sama, plus "Other registered target..." (jalur lama dengan ketik konfirmasi).
- Dihapus dari UI: halaman Refresh, layar khusus pemegang refresh, "Export file on hub".
## Belum dikerjakan
- Endpoint `POST /api/v1/reconstitute` (export ke berkas hub) masih ada sebagai API admin: CLI dan fixture `tests/mbu`
masih memakainya. Hapus (beserta folder exports) sebagai keputusan terpisah sebelum rilis publik.
- "Restore ke dua target sekaligus" dilakukan sebagai dua restore berurutan oleh orang yang sama (modal tetap terbuka
setelah selesai: "Restore again" / ganti restore point). Belum ada tombol "keduanya" sekali klik.

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

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

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

File diff suppressed because it is too large Load Diff

View File

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

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

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

View File

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

39
web/blackhole-proto.html Normal file
View File

@@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Black hole prototype</title>
<style>
html, body { margin: 0; height: 100%; background: #0a0c10; color: #d9dad6; font: 12px/1.4 ui-monospace, monospace; overflow: hidden; }
canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; cursor: grab; }
canvas:active { cursor: grabbing; }
#panel { position: fixed; top: 12px; left: 12px; width: 250px; max-height: calc(100% - 24px); overflow: auto; padding: 10px 12px; background: #111418e6; border: 1px solid #2b3138; border-radius: 8px; backdrop-filter: blur(10px); }
#panel.hidden { display: none; }
#panel h1 { margin: 0 0 6px; font-size: 12px; letter-spacing: .1em; text-transform: uppercase; color: #e8b57e; }
#panel label { display: grid; grid-template-columns: 78px 1fr 38px; gap: 6px; align-items: center; margin: 4px 0; }
#panel input[type=range] { width: 100%; }
#panel .row { display: flex; gap: 8px; margin-top: 8px; flex-wrap: wrap; }
#panel button { font: inherit; color: inherit; background: #191d22; border: 1px solid #393e45; border-radius: 5px; padding: 4px 8px; cursor: pointer; }
#panel pre { margin: 8px 0 0; white-space: pre-wrap; color: #9298a0; }
.tag { position: fixed; pointer-events: none; font: 500 10px/1 ui-monospace, monospace; letter-spacing: .1em; text-transform: uppercase; color: #e8b57e; opacity: 0; white-space: nowrap; }
.tag::before { content: ""; display: inline-block; width: 22px; height: 1px; background: #e8b57e99; vertical-align: middle; margin-right: 6px; }
.tag.left { transform: translateX(-100%); }
.tag.left::before { display: none; }
.tag.left::after { content: ""; display: inline-block; width: 22px; height: 1px; background: #e8b57e99; vertical-align: middle; margin-left: 6px; }
.tag.mint { color: #8bcbb3; }
.tag.mint::before { display: none; }
#modes { display: flex; gap: 6px; margin: 4px 0 8px; }
#modes button.on { border-color: #e8b57e; color: #ffe2c9; }
#fail { position: fixed; inset: 0; display: none; place-items: center; text-align: center; }
</style>
</head>
<body>
<canvas id="stage"></canvas>
<div id="fail">WebGL2 is not available in this browser.</div>
<div class="tag" id="tagShadow">Shadow · 3√3 M</div>
<div class="tag" id="tagDisk">Accretion disk · 6–26 M</div>
<div id="panel"><h1>Black hole</h1><div id="modes"></div></div>
<script type="module" src="/src/proto/blackhole-proto.ts"></script>
</body>
</html>

109
web/scripts/access.test.mjs Normal file
View File

@@ -0,0 +1,109 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
branchState, expiryState, groupGrants, hasNoEffect, neededBy, personAccess, reasonText, roleLabel, seenGroups, setMany, setPermission,
} from "../src/lib/access.ts";
const roles = [
{ name: "viewer", permissions: ["orbit.read", "snapshot.read"] },
{ name: "capturer", permissions: ["orbit.read", "snapshot.read", "capture.run"] },
{ name: "downloader", permissions: ["orbit.read", "snapshot.read", "snapshot.download"] },
];
const NOW = 1_000_000;
const grant = (id, principal, permission, extra = {}) => ({
id, principal_type: "user", principal, permission, scope_type: "global", scope_id: null, expires_at: null, created_by: "t", created_at: 1, ...extra,
});
test("ticking a permission ticks what it needs; unticking removes what depends on it", () => {
const download = setPermission(new Set(), "snapshot.download", true);
assert.deepEqual([...download].sort(), ["orbit.read", "snapshot.download", "snapshot.read"]);
const noList = setPermission(download, "snapshot.read", false);
assert.deepEqual([...noList], ["orbit.read"], "download needs list, so it goes too");
assert.deepEqual(neededBy(new Set(["orbit.read", "capture.run"]), "orbit.read"), ["capture.run"]);
assert.deepEqual(neededBy(new Set(["orbit.read"]), "orbit.read"), []);
});
test("a branch reports all, some or none and ticks as a whole", () => {
const ids = ["snapshot.read", "snapshot.download"];
assert.equal(branchState(new Set(), ids), "none");
assert.equal(branchState(new Set(["snapshot.read"]), ids), "some");
const all = setMany(new Set(), ids, true);
assert.equal(branchState(all, ids), "all");
assert.ok(all.has("orbit.read"));
assert.equal(branchState(setMany(all, ids, false), ids), "none");
});
test("names a set of permissions from the hub's roles, never inventing one", () => {
assert.equal(roleLabel(["snapshot.read", "orbit.read"], roles), "Viewer");
assert.equal(roleLabel(["orbit.read", "snapshot.read", "capture.run"], roles), "Capturer");
assert.equal(roleLabel(["orbit.read", "snapshot.read", "capture.run", "snapshot.download"], roles), "Capturer + download");
assert.equal(roleLabel(["capture.run"], roles), "Custom");
assert.equal(roleLabel([], roles), "Custom");
assert.equal(roleLabel(["orbit.read"], []), "Custom", "no roles known: always custom");
});
test("one row per person, orbit and end date, with permissions in tree order", () => {
const rows = groupGrants([
grant("1", "u", "capture.run"), grant("2", "u", "orbit.read"), grant("3", "u", "snapshot.read"),
grant("4", "u", "orbit.read", { scope_type: "orbit", scope_id: "o1" }),
grant("5", "u", "snapshot.read", { expires_at: 5 }),
grant("6", "dev", "orbit.read", { principal_type: "group" }),
]);
assert.equal(rows.length, 4);
assert.deepEqual(rows[0].permissions, ["orbit.read", "snapshot.read", "capture.run"]);
assert.deepEqual(rows[0].ids, ["1", "2", "3"]);
});
test("expiry is none, soon (within two weeks) or expired", () => {
assert.equal(expiryState(null, NOW), "none");
assert.equal(expiryState(NOW, NOW), "expired", "expiry is exclusive, as on the hub");
assert.equal(expiryState(NOW + 86_400, NOW), "soon");
assert.equal(expiryState(NOW + 30 * 86_400, NOW), "none");
});
test("a grant without orbit.read has no effect, unless another grant of theirs supplies it", () => {
const all = [grant("1", "u", "capture.run", { scope_type: "orbit", scope_id: "o1" })];
const [row] = groupGrants(all);
assert.equal(hasNoEffect(row, all, [], NOW), true);
const withGlobal = [...all, grant("2", "u", "orbit.read")];
assert.equal(hasNoEffect(row, withGlobal, [], NOW), false, "a global orbit.read covers it");
const otherOrbit = [...all, grant("3", "u", "orbit.read", { scope_type: "orbit", scope_id: "o2" })];
assert.equal(hasNoEffect(row, otherOrbit, [], NOW), true, "another orbit does not");
const viaGroup = [...all, grant("4", "qa", "orbit.read", { principal_type: "group" })];
assert.equal(hasNoEffect(row, viaGroup, ["qa"], NOW), false, "a group of theirs supplies it");
assert.equal(hasNoEffect(row, viaGroup, [], NOW), true, "a group they are not in does not");
const expired = [grant("5", "u", "capture.run", { expires_at: NOW - 1 })];
assert.equal(hasNoEffect(groupGrants(expired)[0], expired, [], NOW), false, "an expired grant is shown as expired instead");
});
test("a person is an administrator, waiting, or described by everything that reaches them", () => {
const user = (extra) => ({ id: "u", issuer: "i", display_name: "U", active: true, created_at: 1, last_login_at: 1, is_emergency: false, admin: false, groups: [], ...extra });
assert.equal(personAccess(user({ admin: true }), [], [], roles, NOW).kind, "admin");
assert.equal(personAccess(user(), [], [], roles, NOW).kind, "waiting");
const viaGroup = personAccess(user({ groups: ["dev"] }), [grant("1", "dev", "orbit.read", { principal_type: "group" }), grant("2", "dev", "snapshot.read", { principal_type: "group" })], [], roles, NOW);
assert.deepEqual([viaGroup.kind, viaGroup.label, viaGroup.via], ["granted", "Viewer", ["dev"]]);
const refreshOnly = personAccess(
user(), [],
[{ id: "r", principal_type: "user", principal: "u", relation_id: "x", version: 1, active: true, source_name: "prod", target_name: "stg", expires_at: null, created_at: 1 }],
roles, NOW,
);
assert.deepEqual([refreshOnly.kind, refreshOnly.refresh], ["granted", ["prod → stg"]]);
const ended = personAccess(
user(), [],
[{ id: "r", principal_type: "user", principal: "u", relation_id: "x", version: 1, active: false, source_name: "prod", target_name: "stg", expires_at: null, created_at: 1 }],
roles, NOW,
);
assert.equal(ended.kind, "waiting", "a grant on an ended relation gives nothing");
assert.equal(personAccess(user(), [grant("1", "u", "capture.run")], [], roles, NOW).noEffect, true);
});
test("seen groups are counted once per person and sorted by size", () => {
const u = (groups) => ({ groups });
assert.deepEqual(seenGroups([u(["dev", "qa"]), u(["dev", "dev"]), u(undefined)]), [{ name: "dev", people: 2 }, { name: "qa", people: 1 }]);
});
test("refusal codes become sentences and unknown ones fall back", () => {
assert.match(reasonText("already_granted", "x"), /Already granted/);
assert.equal(reasonText("something_new", "fallback"), "fallback");
assert.equal(reasonText(undefined, "fallback"), "fallback");
});

View File

@@ -0,0 +1,80 @@
import assert from "node:assert/strict";
import test from "node:test";
import { activityCounts, buildActivity, dayLabel } from "../src/lib/activity.ts";
const NOW = Date.parse("2026-11-14T12:00:00Z");
const sec = (iso) => Date.parse(iso) / 1000;
const snapshot = (id, orbit_name, taken_at, size_bytes = 1024 ** 3) => ({ id, orbit_name, orbit_id: orbit_name, taken_at, size_bytes });
const target = { id: "t", name: "pg-staging", outpost_id: "o", engine: "postgres", application_id: "a", identity: { instance: "1", database: "orders" } };
const restore = (id, status, phase, at, extra = {}) => ({ id, snapshot_id: "s1", target, actor: "sen", status, phase, safety_snapshot_id: null, created_at: sec(at), updated_at: sec(at), ...extra });
const orbit = (id, last_status, extra = {}) => ({ id, name: id, provider: "filesystem", source: "filesystem", access: "hub", last_status, dry_run: false, ...extra });
const build = (input) => buildActivity({ snapshots: [], orbits: [], captureJobs: [], restoreJobs: [], now: NOW, ...input });
test("puts what needs a person first, then running work, then history newest first", () => {
const snapshots = [snapshot("s1", "media-vault", "2026-11-14T02:00:00Z"), snapshot("s2", "nightly-pg", "2026-11-13T01:00:00Z")];
const restoreJobs = [
restore("done", "completed", "completed", "2026-11-12T15:00:00Z"),
restore("locked", "recovery_required", "apply_failed", "2026-11-13T22:10:00Z"),
restore("live", "running", "safety", "2026-11-14T10:52:00Z"),
];
const entries = build({ snapshots, restoreJobs });
assert.deepEqual(entries.map(({ group }) => group), ["needs", "running", "history", "history", "history"]);
assert.deepEqual(entries.map(({ id }) => id), ["restore-locked", "restore-live", "snapshot-s1", "snapshot-s2", "restore-done"]);
assert.deepEqual(activityCounts(entries), { running: 1, needs: 1 });
});
test("names a restore by direction and tells where it leads", () => {
const [entry] = build({ snapshots: [snapshot("s1", "media-vault", "2026-11-14T02:00:00Z")], restoreJobs: [restore("a", "completed", "completed", "2026-11-14T03:00:00Z")] })
.filter(({ kind }) => kind === "restore");
assert.match(entry.title, /^media-vault · .+ → pg-staging \/ orders$/);
assert.deepEqual(entry.opens, { kind: "snapshot", id: "s1" });
const [orphan] = build({ restoreJobs: [restore("b", "completed", "completed", "2026-11-14T03:00:00Z", { snapshot_id: "gone-1234-5678" })] });
assert.equal(orphan.opens, null);
assert.match(orphan.title, /^Snapshot gone-123 →/);
});
test("shows the step of a job in flight and ends each state in the right tone", () => {
const entries = build({ restoreJobs: [
restore("q", "queued", "queued", "2026-11-14T10:00:00Z"),
restore("s", "running", "safety", "2026-11-14T10:01:00Z"),
restore("p", "applying", "applying", "2026-11-14T10:02:00Z"),
restore("f", "failed", "wrong_target", "2026-11-14T09:00:00Z"),
restore("c", "cancelled", "cancelled", "2026-11-14T08:00:00Z"),
restore("r", "reconciled", "reconciled", "2026-11-14T07:00:00Z"),
] });
const by = Object.fromEntries(entries.map((entry) => [entry.id, entry]));
assert.equal(by["restore-q"].progress, 0);
assert.equal(by["restore-s"].progress, 2);
assert.equal(by["restore-p"].progress, 3);
assert.deepEqual([by["restore-f"].tone, by["restore-c"].tone, by["restore-r"].tone], ["red", "grey", "green"]);
assert.equal(by["restore-r"].state, "Recovered");
});
test("folds an outpost backup into its snapshot, and keeps unfinished or failed ones", () => {
const orbits = [orbit("mail", "running", { access: "outpost", application_id: "app" })];
const profile = { application_id: "app", orbit_id: "mail", outpost_id: "o", format: "filesystem" };
const job = (id, status, phase, snapshot_id = null) => ({ id, profile, actor: "schedule", status, phase, created_at: sec("2026-11-14T09:00:00Z"), snapshot_id, offsite_status: null });
const entries = build({
snapshots: [snapshot("s1", "mail", "2026-11-14T09:05:00Z")],
orbits,
captureJobs: [job("done", "completed", "completed", "s1"), job("live", "running", "uploading"), job("bad", "failed", "upload_failed")],
});
assert.equal(entries.filter(({ kind }) => kind === "backup").length, 3);
const stored = entries.find(({ id }) => id === "snapshot-s1");
assert.match(stored.meta, /via Outpost · by schedule/);
assert.equal(entries.find(({ id }) => id === "backup-live").progress, 3);
assert.equal(entries.find(({ id }) => id === "backup-bad").tone, "red");
assert.equal(entries.some(({ id }) => id.startsWith("orbit-mail")), false);
});
test("reads a hub orbit's last status when the hub keeps no job list for it", () => {
const entries = build({ orbits: [orbit("a", "running"), orbit("b", "failed"), orbit("c", "completed")], now: NOW });
assert.deepEqual(entries.map(({ id, group }) => [id, group]), [["orbit-b-failed", "needs"], ["orbit-a-running", "running"]]);
assert.equal(entries[0].at, null);
});
test("labels days relative to now", () => {
assert.equal(dayLabel(NOW - 3600_000, NOW), "Today");
assert.equal(dayLabel(NOW - 86_400_000, NOW), "Yesterday");
assert.notEqual(dayLabel(NOW - 5 * 86_400_000, NOW), "Today");
});

View File

@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import { layoutFor } from "../src/lib/blackhole/layout.ts";
import { SCENE_WIDTH } from "../src/lib/galaxyLayout.ts";
import { CRITICAL_IMPACT } from "../src/lib/blackhole/geodesic.ts";
const panel = { left: 100, top: 50, width: 800, height: 600 };
test("the hole sits at the centre of the galaxy frame, relative to the panel", () => {
const frame = { left: 100 + 70, top: 50 + 60, width: 660, height: 480 };
const { centerX, centerY } = layoutFor(frame, panel);
assert.ok(Math.abs(centerX - (70 + 330) / 800) < 1e-9);
assert.ok(Math.abs(centerY - (60 + 240) / 600) < 1e-9);
});
test("the shadow has a fixed radius in scene units and scales with the frame", () => {
const atNative = layoutFor({ left: 0, top: 0, width: SCENE_WIDTH, height: 480 }, panel);
assert.ok(Math.abs(atNative.pxPerM * CRITICAL_IMPACT - 34) < 1e-9);
const doubled = layoutFor({ left: 0, top: 0, width: SCENE_WIDTH * 2, height: 960 }, panel);
assert.ok(Math.abs(doubled.pxPerM - atNative.pxPerM * 2) < 1e-9);
});
test("a frame moving under a transition moves the hole with it", () => {
const before = layoutFor({ left: 200, top: 100, width: 600, height: 436 }, panel);
const after = layoutFor({ left: 240, top: 140, width: 600, height: 436 }, panel);
assert.ok(Math.abs(after.centerX - before.centerX - 40 / 800) < 1e-9);
assert.ok(Math.abs(after.centerY - before.centerY - 40 / 600) < 1e-9);
assert.equal(after.pxPerM, before.pxPerM);
});

View File

@@ -132,7 +132,8 @@ try {
await page.getByRole("button", { name: "Capture Load test orbit 1", exact: true }).click();
await page.getByText("Snapshot secured from Load test orbit 1.", { exact: true }).waitFor();
await page.waitForFunction(() => Number(document.querySelector(".capture-arrival").getAttribute("opacity")) > 0.1);
// The clicked orbit's rocket is on screen (rockets are marked with data-orbit; other orbits may be running too).
await page.waitForFunction(() => Number(document.querySelector('.rocket[data-orbit="orbit-0"]')?.getAttribute("opacity")) > 0.1);
await page.waitForFunction(() => Number(
document.querySelector("[data-vault-core]").style.getPropertyValue("--capture-absorption"),
) > 0.2);
@@ -144,8 +145,10 @@ try {
await page.locator("#register-orbit-1").click();
await page.getByRole("button", { name: "Capture Load test orbit 2", exact: true }).click();
await page.getByText("Capture failed for Load test orbit 2.", { exact: true }).waitFor();
await page.waitForFunction(() => Number(document.querySelector(".capture-flare").getAttribute("opacity")) > 0.1);
assert.equal(await page.locator(".capture-arrival").getAttribute("opacity"), "0");
await page.waitForFunction(() => Number(document.querySelector(".rocket-flare").getAttribute("opacity")) > 0.1);
// A failed backup explodes and its rocket is gone.
assert.equal(await page.evaluate(() =>
[...document.querySelectorAll('.rocket[data-orbit="orbit-1"]')].filter(node => Number(node.getAttribute("opacity")) > 0).length), 0);
const workspaceWidth = await frame.evaluate(element => element.getBoundingClientRect().width);
await page.getByRole("button", { name: "Big screen", exact: true }).click();

View File

@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { capturePhases, assignOrbitSlots, orbitPose, groupSnapshots, moonPoses } from "../src/lib/galaxyLayout.ts";
import { assignOrbitSlots, elevationOf, orbitPose, groupSnapshots, moonPoses, project, tiltOf, trailAngle } from "../src/lib/galaxyLayout.ts";
import { placeLabels } from "../src/lib/galaxyLabelLayout.ts";
test("slot identities survive reordering, insertion and removal", () => {
@@ -63,24 +63,62 @@ test("labels respect screen bounds and preserve priority in a crowded scene", ()
assert.ok(labels[0].x >= 0 && labels[0].x + 72 <= 140);
});
test("capture flares before flight, then absorbs and highlights the snapshot", () => {
const flare = capturePhases(0.06);
assert.equal(flare.flare, 1);
assert.equal(flare.flight, 0);
assert.equal(flare.highlight, 0);
const arrival = capturePhases(0.84);
assert.equal(arrival.flight, 1);
assert.equal(arrival.absorption, 1);
assert.equal(arrival.highlight, 0);
assert.equal(capturePhases(0.94).absorption, 0);
assert.equal(capturePhases(0.94).highlight, 0);
assert.equal(capturePhases(0.97).highlight, 1);
assert.deepEqual(capturePhases(1), { flare: 0, flight: 1, absorption: 0, highlight: 0, failure: 0 });
});
test("the selected label searches farther when nearby orbit markers crowd it out", () => {
const selected = { id: "focused", x: 140, y: 140, width: 60 };
const cluster = { x: 61, y: 61, width: 158, height: 158 };
assert.deepEqual(placeLabels([selected], 300, 300, [cluster]), []);
assert.equal(placeLabels([selected], 300, 300, [cluster], selected.id)[0]?.id, selected.id);
});
test("a marker's trail points back along the direction it came from", () => {
const slots = assignOrbitSlots(Array.from({ length: 30 }, (_, i) => String(i)));
for (const slot of slots.values()) {
for (const time of [0, 3.7, 41]) {
const now = orbitPose(slot, time);
const next = orbitPose(slot, time + 0.01);
const tail = Math.atan2(-(next.y - now.y), -(next.x - now.x));
const diff = Math.atan2(Math.sin(trailAngle(slot, time) - tail), Math.cos(trailAngle(slot, time) - tail));
assert.ok(Math.abs(diff) < 0.01, `trail off by ${diff}`);
}
}
});
test("the default view is the map's own view, and a turned view is the same orbit seen from elsewhere", () => {
const slot = { radius: 190, angle: 0.4, speed: 0.033 };
assert.deepEqual(orbitPose(slot, 3, { yaw: 0, lift: 0 }), orbitPose(slot, 3));
assert.equal(tiltOf({ yaw: 0, lift: 0 }), 0.68);
// The orbit plane is a circle: turning the camera round it only moves a marker along its own ellipse.
const turned = orbitPose(slot, 3, { yaw: 1.1, lift: 0 });
const tilt = tiltOf({ yaw: 1.1, lift: 0 });
assert.ok(Math.abs((turned.x / 190) ** 2 + (turned.y / (190 * tilt)) ** 2 - 1) < 1e-9);
// Raising the camera opens the ellipse towards a circle; lowering it flattens it towards a line.
assert.ok(tiltOf({ yaw: 0, lift: 0.4 }) > 0.68);
assert.ok(tiltOf({ yaw: 0, lift: -0.5 }) < 0.4);
assert.ok(tiltOf({ yaw: 0, lift: 9 }) <= 1 && tiltOf({ yaw: 0, lift: -9 }) > 0);
});
test("project agrees with orbitPose for a point on the orbit", () => {
const slot = { radius: 128, angle: 1.9, speed: 0.047 };
const view = { yaw: -0.8, lift: 0.3 };
const angle = slot.angle + 2 * slot.speed;
const direct = orbitPose(slot, 2, view);
const projected = project(Math.cos(angle) * slot.radius, Math.sin(angle) * slot.radius, view);
assert.ok(Math.abs(direct.x - projected.x) < 1e-9 && Math.abs(direct.y - projected.y) < 1e-9);
});
test("a trail points back along the turned orbit", () => {
const slot = { radius: 190, angle: 0.4, speed: 0.033 };
const view = { yaw: 0.9, lift: 0.2 };
const now = orbitPose(slot, 5, view);
const before = orbitPose(slot, 5 - 0.01, view);
const tail = Math.atan2(before.y - now.y, before.x - now.x);
const diff = Math.atan2(Math.sin(trailAngle(slot, 5, view) - tail), Math.cos(trailAngle(slot, 5, view) - tail));
assert.ok(Math.abs(diff) < 0.05);
});
test("raising the camera raises the disk's view too, within bounds", () => {
assert.equal(elevationOf(0), (8 * Math.PI) / 180);
assert.ok(elevationOf(0.3) > elevationOf(0) && elevationOf(-0.3) < elevationOf(0));
assert.ok(elevationOf(-99) > 0 && elevationOf(99) < Math.PI / 2);
for (let lift = -0.55; lift < 0.7; lift += 0.05) assert.ok(elevationOf(lift + 0.05) > elevationOf(lift));
});

View File

@@ -0,0 +1,40 @@
import assert from "node:assert/strict";
import test from "node:test";
import { CRITICAL_IMPACT, HORIZON, deflection, traceImpact, traceRay } from "../src/lib/blackhole/geodesic.ts";
test("a ray inside the critical impact parameter is captured and one outside escapes", () => {
assert.equal(traceImpact(CRITICAL_IMPACT * 0.94).outcome, "captured");
assert.equal(traceImpact(CRITICAL_IMPACT * 1.06).outcome, "escaped");
});
test("the shadow edge sits at the analytic 3√3 within the step error", () => {
let captured = 0;
let escaped = 10;
for (let i = 0; i < 24; i++) {
const mid = (captured + escaped) / 2;
const { outcome } = traceImpact(mid, 48, { maxSteps: 900 });
if (outcome === "escaped") escaped = mid;
else captured = mid;
}
assert.ok(Math.abs(escaped - CRITICAL_IMPACT) / CRITICAL_IMPACT < 0.03, `edge at ${escaped}`);
});
test("weak-field deflection follows 4M/b plus the second-order term", () => {
const b = 20;
const expected = 4 / b + (15 * Math.PI) / 4 / (b * b);
const angle = deflection(traceImpact(b, 400, { maxSteps: 600 }));
assert.ok(Math.abs(angle - expected) / expected < 0.1, `${angle} vs ${expected}`);
});
test("a ray that falls radially is captured at the horizon", () => {
const trace = traceRay([0, 0, 30], [0, 0, -1]);
assert.equal(trace.outcome, "captured");
assert.ok(trace.minRadius < HORIZON);
});
test("a ray in the disk plane never crosses it and a skewed ray crosses it once", () => {
assert.equal(traceImpact(9).crossings.length, 0);
const skew = traceRay([9, 14, 40], [0, -0.3, -0.95]);
assert.equal(skew.crossings.length, 1);
assert.equal(skew.crossings[0].point[1], 0);
});

108
web/scripts/look.test.mjs Normal file
View File

@@ -0,0 +1,108 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createLook, jumpLook, requestLook, stepLook, styleAt, waveParams, WAVE_FEATHER } from "../src/lib/blackhole/look.ts";
import { farthestCornerM } from "../src/lib/blackhole/layout.ts";
const run = (look, seconds, fps = 60) => {
const progress = [];
for (let i = 0; i < seconds * fps; i++) {
stepLook(look, 1 / fps);
progress.push(look.progress);
}
return progress;
};
test("the wave expands from the hole, never overshoots, and settles on the new look", () => {
const look = createLook(0);
requestLook(look, 1);
assert.equal(look.running, true);
assert.equal(look.progress, 0);
const progress = run(look, 3);
for (let i = 1; i < progress.length; i++) {
assert.ok(progress[i] >= progress[i - 1] - 1e-12, "progress never goes backwards");
assert.ok(progress[i] <= 1, "progress never overshoots");
}
assert.equal(look.running, false);
assert.equal(look.from, 1);
assert.equal(look.to, 1);
const finishedAt = progress.findIndex((value) => value === 1);
assert.ok(finishedAt > 20 && finishedAt < 150, `settled after ${finishedAt} frames`);
});
test("a request made mid-wave waits for the wave to finish instead of reversing it", () => {
const look = createLook(0);
requestLook(look, 1);
run(look, 0.3);
const before = look.progress;
requestLook(look, 0);
assert.equal(look.queued, 0);
assert.equal(look.to, 1, "the running wave keeps its target");
assert.ok(look.progress >= before);
run(look, 4);
assert.equal(look.running, false);
assert.equal(look.to, 0, "the queued look ran afterwards");
});
test("asking for the look that is already showing does nothing, and the queue follows the latest request", () => {
const look = createLook(1);
requestLook(look, 1);
assert.equal(look.running, false);
requestLook(look, 0);
assert.equal(look.running, true);
requestLook(look, 1);
assert.equal(look.queued, 1, "asking for the old look mid-wave queues it");
requestLook(look, 0);
assert.equal(look.queued, undefined, "asking for the running target again cancels the queue");
assert.equal(look.to, 0);
});
test("pixels inside the front show the new look and pixels outside keep the old one", () => {
const look = createLook(0);
requestLook(look, 1);
run(look, 0.4);
const wave = waveParams(look, 50);
assert.equal(styleAt(wave, 0), 1);
assert.equal(styleAt(wave, wave.waveRadius + 1), 0);
const middle = styleAt(wave, wave.waveRadius - WAVE_FEATHER / 2);
assert.ok(middle > 0 && middle < 1, "the front is soft");
});
test("the front covers the whole picture by the time the wave finishes, and fades as it goes", () => {
const look = createLook(0);
requestLook(look, 1);
const fronts = [];
const radii = [];
for (let i = 0; i < 240 && look.running; i++) {
stepLook(look, 1 / 60);
const wave = waveParams(look, 50);
fronts.push(wave.waveFront);
radii.push(wave.waveRadius);
}
for (let i = 1; i < fronts.length; i++) {
assert.ok(fronts[i] <= fronts[i - 1] + 1e-12);
assert.ok(radii[i] >= radii[i - 1] - 1e-12);
}
const settled = waveParams(look, 50);
assert.equal(settled.waveFront, 0);
assert.equal(settled.styleFrom, 1);
assert.equal(styleAt(settled, 49), 1);
});
test("the wave has to travel as far as the farthest corner", () => {
const radius = farthestCornerM({ x: 300, y: 200 }, { width: 800, height: 600 }, 10);
assert.ok(Math.abs(radius - Math.hypot(500, 400) / 10) < 1e-9);
});
test("jumping to a look drops any wave and any queued request", () => {
const look = createLook(0);
requestLook(look, 1);
run(look, 0.2);
requestLook(look, 0);
jumpLook(look, 1);
assert.equal(look.running, false);
assert.equal(look.from, 1);
assert.equal(look.to, 1);
assert.equal(look.queued, undefined);
assert.equal(waveParams(look, 50).waveFront, 0);
assert.equal(styleAt(waveParams(look, 50), 40), 1);
});

View File

@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createActivity, intentFor, observeStatuses } from "../src/lib/orbitActivity.ts";
const map = (entries) => new Map(Object.entries(entries));
const run = (state, entries, causes) => observeStatuses(state, map(entries), causes ? map(causes) : undefined);
test("the first observation is a baseline: running orbits start circling, finished ones stay settled", () => {
const state = createActivity();
const events = run(state, { a: "running", b: "completed", c: "failed", d: "queued", e: "rehearsing", f: "idle" });
assert.deepEqual(events, [
{ kind: "begin", id: "a", intent: "circle" },
{ kind: "begin", id: "d", intent: "pad" },
{ kind: "begin", id: "e", intent: "ghost" },
]);
assert.equal(state.intents.get("b"), "none");
});
test("a status that has not changed produces nothing", () => {
const state = createActivity();
run(state, { a: "running", b: "completed" });
assert.deepEqual(run(state, { a: "running", b: "completed" }), []);
});
test("a running backup that completes launches, and one that fails reports its cause", () => {
const state = createActivity();
run(state, { a: "running", b: "running", c: "running" });
const events = run(state, { a: "completed", b: "failed", c: "failed" }, { c: "transfer" });
assert.deepEqual(events, [
{ kind: "launch", id: "a" },
{ kind: "fail", id: "b", cause: "unknown" },
{ kind: "fail", id: "c", cause: "transfer" },
]);
});
test("queued becoming running is the same rocket changing pace, then it launches", () => {
const state = createActivity();
run(state, { a: "queued" });
assert.deepEqual(run(state, { a: "running" }), [{ kind: "begin", id: "a", intent: "circle" }]);
assert.deepEqual(run(state, { a: "completed" }), [{ kind: "launch", id: "a" }]);
});
test("a rehearsal lands instead of launching", () => {
const state = createActivity();
run(state, { a: "rehearsing" });
assert.deepEqual(run(state, { a: "rehearsed" }), [{ kind: "land", id: "a" }]);
});
test("a backup that finished between two polls still gets its outcome", () => {
const state = createActivity();
run(state, { a: "idle", b: "failed", c: "completed", d: "completed" });
const events = run(state, { a: "completed", b: "completed", c: "failed", d: "completed" });
assert.deepEqual(events, [
{ kind: "launch", id: "a" },
{ kind: "launch", id: "b" },
{ kind: "fail", id: "c", cause: "unknown" },
]);
});
test("an orbit that appears later is treated like one present at load", () => {
const state = createActivity();
run(state, { a: "completed" });
const events = run(state, { a: "completed", b: "running", c: "completed" });
assert.deepEqual(events, [{ kind: "begin", id: "b", intent: "circle" }]);
});
test("a backup that stops without a verdict, or whose orbit is deleted, lets the rocket go quietly", () => {
const state = createActivity();
run(state, { a: "running", b: "running" });
assert.deepEqual(run(state, { a: "idle", b: "running" }), [{ kind: "dismiss", id: "a" }]);
assert.deepEqual(run(state, { a: "idle" }), [{ kind: "dismiss", id: "b" }]);
});
test("intents follow the status while a backup is going", () => {
assert.equal(intentFor("queued"), "pad");
assert.equal(intentFor("running"), "circle");
assert.equal(intentFor("rehearsing"), "ghost");
for (const status of ["completed", "failed", "idle", "rehearsed", "", "mystery"]) assert.equal(intentFor(status), "none");
});

View File

@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import test from "node:test";
import { FRAME_BUDGET_MS, FREEZE_BUDGET_MS, QUALITY_TIERS, chooseTier, initialTier } from "../src/lib/blackhole/quality.ts";
const samples = (ms, count = 30) => Array.from({ length: count }, () => ms);
test("the governor steps down one tier when the median render time exceeds the budget", () => {
assert.equal(chooseTier({ tier: 0, samples: samples(FRAME_BUDGET_MS + 4), sinceChangeMs: 5000 }), 1);
assert.equal(chooseTier({ tier: 0, samples: samples(FRAME_BUDGET_MS - 4), sinceChangeMs: 5000 }), 0);
});
test("the governor ignores a lone spike, too few samples and a tier that has not settled", () => {
const spiky = [...samples(4, 29), 90];
assert.equal(chooseTier({ tier: 1, samples: spiky, sinceChangeMs: 5000 }), 1);
assert.equal(chooseTier({ tier: 1, samples: samples(40, 5), sinceChangeMs: 5000 }), 1);
assert.equal(chooseTier({ tier: 1, samples: samples(40), sinceChangeMs: 200 }), 1);
});
test("the governor stops at the lowest tier and never steps back up", () => {
const last = QUALITY_TIERS.length - 1;
assert.equal(chooseTier({ tier: last, samples: samples(80), sinceChangeMs: 5000 }), last);
assert.equal(chooseTier({ tier: 2, samples: samples(0.5), sinceChangeMs: 5000 }), 2);
});
test("motion only freezes when the lowest animated tier is clearly failing", () => {
const minimal = QUALITY_TIERS.findIndex(({ name }) => name === "minimal");
assert.equal(chooseTier({ tier: minimal, samples: samples(FREEZE_BUDGET_MS - 4), sinceChangeMs: 5000 }), minimal);
assert.equal(chooseTier({ tier: minimal, samples: samples(FREEZE_BUDGET_MS + 4), sinceChangeMs: 5000 }), minimal + 1);
assert.equal(QUALITY_TIERS[minimal + 1].maxFps, 0);
});
test("tiers get strictly cheaper and software rendering starts at the bottom", () => {
for (let i = 1; i < QUALITY_TIERS.length; i++) {
assert.ok(QUALITY_TIERS[i].scale <= QUALITY_TIERS[i - 1].scale);
assert.ok(QUALITY_TIERS[i].steps <= QUALITY_TIERS[i - 1].steps);
assert.ok(QUALITY_TIERS[i].maxFps <= QUALITY_TIERS[i - 1].maxFps);
}
assert.equal(initialTier({ software: true, pixels: 1e6 }), QUALITY_TIERS.length - 1);
assert.equal(initialTier({ software: false, cores: 8, memoryGb: 16, pixels: 2e6 }), 0);
assert.equal(initialTier({ software: false, cores: 4, pixels: 2e6 }), 1);
});

View File

@@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import test from "node:test";
import { STAGES, isFinal, outcomeOf, progressOf, relationLabels } from "../src/lib/restoreRun.ts";
const run = (status, restore_phase = null, blocked_reason = null) => ({ status, restore_phase, blocked_reason });
test("the four stages follow the restore job's phase", () => {
assert.deepEqual(STAGES, ["Checking", "Safety copy", "Applying", "Completed"]);
// the run is created first; the restore job appears a moment later
assert.equal(progressOf(run("capturing")).index, 0);
for (const phase of ["queued", "claimed", "checking"]) assert.equal(progressOf(run("restoring", phase)).index, 0, phase);
for (const phase of ["safety", "ready"]) assert.equal(progressOf(run("restoring", phase)).index, 1, phase);
assert.equal(progressOf(run("restoring", "applying")).index, 2);
assert.deepEqual(progressOf(run("completed", "completed")), { index: 4, state: "done" });
assert.equal(progressOf(run("restoring", "applying")).state, "running");
// the restore job finishes a moment before the run is marked completed: that gap must not look like a restart
assert.deepEqual(progressOf(run("restoring", "completed")), { index: 4, state: "done" });
assert.equal(isFinal(run("restoring")), false);
assert.equal(isFinal(run("completed")), true);
});
test("a run that stopped says at which stage and why it counts as failed or merely cancelled", () => {
assert.deepEqual(progressOf(run("restore_failed", "invalid_payload")), { index: 0, state: "failed" });
assert.deepEqual(progressOf(run("restore_failed", "safety_failed")), { index: 1, state: "failed" });
assert.deepEqual(progressOf(run("recovery_required", "apply_failed")), { index: 2, state: "failed" });
assert.deepEqual(progressOf(run("blocked", "checking", "access_revoked")), { index: 0, state: "failed" });
assert.deepEqual(progressOf(run("cancelled", "safety")), { index: 1, state: "cancelled" });
assert.equal(progressOf(run("expired")).state, "failed");
});
test("what the person is told never contains the database's own words", () => {
const done = outcomeOf(run("completed"), { target: "Development", orbit: "broiler", when: "Nov 15, 11:57 AM" });
assert.equal(done.tone, "good");
assert.match(done.detail, /Development now holds broiler as of Nov 15, 11:57 AM/);
assert.match(outcomeOf(run("restore_failed", "apply_failed"), { target: "Development" }).detail, /ask an administrator/i);
assert.match(outcomeOf(run("recovery_required"), { target: "Staging" }).title, /interrupted/i);
assert.match(outcomeOf(run("blocked", null, "access_revoked"), { target: "Staging" }).detail, /access to this restore was removed/);
assert.equal(outcomeOf(run("cancelled"), { target: "Staging" }).tone, "plain");
assert.equal(outcomeOf(run("restoring", "safety"), { target: "Staging" }).tone, "busy");
});
test("restore points are named by environment, and by target only when two share one", () => {
const rel = (id, env, name) => ({ id, target_environment: env, target_name: name, usable: true });
assert.deepEqual(
relationLabels([rel("a", "staging", "s1"), rel("b", "development", "d1")]).map((r) => r.label),
["Staging", "Development"],
);
assert.deepEqual(
relationLabels([rel("a", "staging", "s1"), rel("b", "staging", "s2")]).map((r) => r.label),
["Staging · s1", "Staging · s2"],
);
assert.equal(relationLabels([rel("a", null, "odd")])[0].label, "odd");
});

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