Files
tessera/docs/DATABASE-CAPTURE.md
Adnan Zahir 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

322 lines
24 KiB
Markdown

# Managed database backups
A capture profile maps one application and Wormhole orbit to a paired outpost. The hub stores the assignment, format, schedule, and retention policy. The agent reads connection settings and password references from its local profile file. Each application has one active capture lease. An agent can serve several applications in parallel.
## Pair an agent
Build the hub, CLI and agent with `cargo build --workspace`. Put Restic on the hub and the database client for the source server version on the agent. SSH profiles also use OpenSSH on the agent. MySQL remote capture runs the server-compatible `mysqldump` on the SSH host.
Generate a pairing code in **Outposts** or call `POST /api/v1/wormhole/pairing` with operator credentials. On the agent, create the credential file once.
```sh
tessera-agent --hub-url https://backup.example.org --credentials /etc/tessera/wormhole.json pair CODE --name database-outpost
tessera-agent --credentials /etc/tessera/wormhole.json --capture-profiles /etc/tessera/capture.json run
```
The credentials file is owner-only and contains the hub URL, outpost UUID and upload token. Keep it outside the repository. TLS uses the system trust store. Set `TESSERA_WORMHOLE_CA` for a private CA and configure both `TESSERA_WORMHOLE_CLIENT_CERT` and `TESSERA_WORMHOLE_CLIENT_KEY` for a hub that requires mTLS. Plain HTTP capture is available on loopback for local testing.
## Register an application
In **Orbits**, choose **Database** or **Filesystem / Folder**, then **Via Outpost**. Save the orbit and register its Outpost backup profile. Pick the paired Outpost, application UUID, and optional daily UTC schedule. Database profiles also need an engine.
For **Via Hub**, give the hub a readable folder path or a reachable PostgreSQL/MySQL endpoint and an absolute password-file path. Mount these files into the container when applicable. TLS verifies the server identity by default. Provide a CA file for a private CA. The hub needs a matching database client on its PATH. The bundled hub image includes `pg_dump` and `mysqldump`. Use a compatible client for the source server version.
For CLI setup, create an orbit using `tessera orbit billing --provider wormhole` and save its returned UUID. Use the UUID of the paired outpost shown in **Outposts**. Choose a stable application UUID and submit the following object to `POST /api/v1/capture-profiles` using the hub's admin API token or authenticated operator session.
```json
{
"application_id": "e1656c14-0d87-4572-a548-b66cc283e61f",
"orbit_id": "393e5c00-65b8-4084-a521-099732948a6c",
"outpost_id": "c7072265-89ab-493a-8dbe-948c1e9aa24c",
"format": "postgres_custom",
"schedule": { "hour": 2, "timezone": "Asia/Jakarta" }
}
```
A schedule is optional. Scheduled jobs catch up from the time the profile was registered and stay queued while the outpost is offline. Retention defaults to 14 days and keeps the newest archive. Use `"retention": {"mode": "count"}` for five archives or set its `keep` value explicitly. An orbit's custom GFS policy applies when the profile has no explicit retention override. The offline CLI decay command only processes legacy snapshots.
Set the same application UUID in the agent's local JSON file. Each entry has a `source` and an optional `timeout_seconds` (default 3600). The password file contains one line and should be readable only by the service account.
```json
{
"e1656c14-0d87-4572-a548-b66cc283e61f": {
"source": {
"engine": "postgres",
"host": "billing.internal",
"database": "billing",
"user": "backup",
"password_file": "/etc/tessera/billing.password",
"tls": { "mode": "verify_full_with_ca", "ca_file": "/etc/tessera/database-ca.pem" }
}
}
}
```
| Case | Format | Agent source |
| --- | --- | --- |
| Direct PostgreSQL | `postgres_custom` or `postgres_sql` | Example above. Port defaults to 5432. TLS defaults to `verify_full`. |
| PostgreSQL through SSH | `postgres_custom` or `postgres_sql` | Add a `bastion` object. Keep the PostgreSQL hostname that the server certificate covers. |
| Direct MySQL | `mysql_sql` | Use `"engine": "mysql", "transport": "direct"`, host, database, user, password file and MySQL TLS policy. Port defaults to 3306. TLS modes include `verify_identity_with_ca` with a CA file and `required`. |
| MySQL through SSH | `mysql_sql` | Use `"engine": "mysql", "transport": "ssh"`, `bastion`, `database` and `defaults_file`. The latter is an absolute path to a private MySQL client options file on the SSH host. |
The `bastion` object has `host`, `user`, `identity_file`, `known_hosts_file` and an optional `port` (default 22). Use an absolute path for each file. Record the authorized SSH server host key in the pinned known-hosts file. The SSH login needs forwarding permission for PostgreSQL or permission to run the MySQL client and read its options file for remote MySQL.
## Run and inspect a backup
Open **Orbits → Outpost backup jobs**, select an application, and queue a backup. In the API, use `POST /api/v1/capture-profiles/{application-id}/jobs`. Poll `GET /api/v1/capture-jobs/{job-id}` for status and its `/events` endpoint for phase history. The list endpoint supports `application_id`, `status`, and `limit` filters. Successful captures expose their engine, format, and job ID in the snapshot catalog.
New Outpost orbits require the current agent and an incremental Restic repository. Follow the Rest Server and repository setup in [the README](../README.md#incremental-wormhole-transfers-for-filesystem-archives) for each orbit. Use the same repository password in the hub's orbit key and the agent's password file. Add these fields to the application's agent profile:
```json
{
"restic_repository": "rest:https://backup.example.org/<orbit-id>/",
"restic_password_file": "/etc/tessera/keys/repository-password",
"rest_server_password_file": "/etc/tessera/keys/rest-server-password"
}
```
The Rest Server login is the orbit ID when `rest_server_password_file` is set. For a private Rest Server CA, configure `RESTIC_CACERT` on the agent. A filesystem profile uses `"paths": ["/path/to/folder"]` in place of `source` and `"format": "filesystem"` on the hub.
The agent sends new Restic chunks and snapshot metadata. The hub registers the snapshot after checking the lease and repository. One capture job produces one catalog ID across retries. A logical database backup needs room on the executor for one private temporary dump per concurrent capture. A database can run with its normal logging settings. The dump is read in full at the source, and Restic performs deduplication before transfer to the repository.
Existing database orbits keep the legacy full-upload path until their Restic repository is configured. That path validates length and SHA-256 at ingest, stages on both sides, and has a 100 GiB upload limit.
Use the snapshot detail to download or remove an archive. Database snapshots can also be exported to a file on the hub. Use **Database recovery options** to apply a verified database archive to a registered target.
## Operator sign-in
Authentication is required by default, including requests from loopback and a
local reverse proxy. Before upgrading, configure the emergency operator hash/name
and/or the separate API admin token. Startup refuses a hub without credentials.
An existing install with neither configured must bootstrap credentials locally
before restarting; there is no first-user auto-admin or public registration.
Use a named individual emergency operator, not a shared daily SSO account.
For synthetic local development only, `TESSERA_LOCAL_DEVELOPMENT=true` explicitly
enables anonymous loopback access when no operator/token is configured. Both
listeners must bind loopback; wildcard and non-loopback binds are rejected.
Forwarded requests are rejected in this mode, but that is not a proxy trust
boundary: never reverse-proxy a development listener. Compose keeps the mode off
and needs operator/API credentials even with a localhost published port.
Generate an Argon2id hash and set `TESSERA_OPERATOR_PASSWORD_HASH` to the result. The hub reads the password from stdin in hash mode. For example, from an interactive Bash shell:
```bash
read -rs -p 'Operator password: ' tessera_operator_password; printf '\n'
export TESSERA_OPERATOR_PASSWORD_HASH="$(printf '%s\n' "$tessera_operator_password" | tessera-hub --hash-operator-password)"
unset tessera_operator_password
```
Set `TESSERA_OPERATOR_NAME` for the audited identity, or use the default `operator`. Serve the browser over HTTPS outside loopback. Sessions expire after eight hours 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.
The hub retries failed copies and reports their state on the capture job. Local retention and deletion protect pending copies. Off-site archives remain available independently after local catalog removal. To recover without the hub or its primary repository, use the off-site Restic password and S3 credentials with these commands:
```sh
restic -r "$TESSERA_OFFSITE_REPOSITORY" --password-file "$TESSERA_OFFSITE_PASSWORD_FILE" snapshots --tag "tessera-<snapshot-uuid>"
restic -r "$TESSERA_OFFSITE_REPOSITORY" --password-file "$TESSERA_OFFSITE_PASSWORD_FILE" dump <restic-id-from-first-command> /payload > recovered.dump
```
## Register a restore target
Configure target credentials on the assigned agent. A target can use a different outpost from its source. PostgreSQL identifies a logical database by cluster system identifier and database name. MySQL uses the server UUID and database name. PostgreSQL source and target roles need read access to `pg_catalog.pg_control_system()` to verify identity. A capture with an unavailable source identity remains available for export.
From a restorable snapshot, open **Database recovery options** and select **Register restore target**. For API setup, call `POST /api/v1/restore-targets` with `id`, `application_id`, `outpost_id`, `name`, `engine` and `identity`. The identity has `instance` and `database`. Query the values on the target.
- PostgreSQL uses `SELECT system_identifier, current_database() FROM pg_catalog.pg_control_system()`.
- MySQL uses `SELECT LOWER(@@server_uuid), DATABASE()`.
On the target agent, add a `targets` map under the application UUID, keyed by the registered target UUID. A target-only outpost can omit the application's `source`. An example PostgreSQL entry follows.
```json
{
"engine": "postgres",
"connection": {
"host": "staging-db.internal",
"database": "billing_staging",
"user": "restore",
"password_file": "/etc/tessera/staging.password",
"tls": { "mode": "verify_full_with_ca", "ca_file": "/etc/tessera/database-ca.pem" }
},
"mode": { "reset": "schema", "schema": "public" }
}
```
Use `{"reset":"recreate_database"}` to recreate the registered PostgreSQL database. It requires access to the `postgres` maintenance database and permission to drop and create the target database. Schema mode resets the named schema and applies the dump in a transaction. 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 MySQL target uses `"engine":"mysql"` and the same `connection` fields as a direct or SSH MySQL source. `recreate_database` drops and recreates the registered database before applying SQL. `use_target_definer` rewrites supported dump DEFINER clauses to the connected MySQL user.
Open the snapshot and choose its recovery options, then pick the target in **Restore**. **Activity** lists recent restore jobs across all snapshots (`GET /api/v1/restore-jobs?limit=`, newest first, at most 200) and flags any that need reconciliation. The required confirmation includes both UUIDs. The hub verifies the safety archive before issuing the single-use apply permit. If the job reports `recovery_required`, stop any old apply process and verify its database session has ended. Recover the target with the linked safety archive, verify data and permissions, then confirm reconciliation to release the lock. Session-authenticated file exports use a filename in the hub's private `exports` directory.
## Import legacy archives
Run the CLI against the staging vault. Use an AWS CLI profile with `s3:ListBucket` scoped to the legacy prefix and `s3:GetObject` on the objects in that prefix.
```sh
tessera legacy-import --bucket legacy-bucket --prefix billing/ --orbit-id ORBIT_UUID --application billing --engine postgres --inventory-only
```
Repeat without `--inventory-only` to import. The JSON report includes the source key, ETag, size, last-modified timestamp, and Tessera snapshot ID. Conditional reads reject changed objects between listing and download. A persistent receipt prevents reimport after local retention and GC. [AWS S3 CLI inventory](https://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects-v2.html), [AWS S3 conditional download](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-object.html).
Add `--history /path/to/consistent-history.sqlite` to archive a consistent SQLite export of the old job history. Save the reported history ID and retrieve it with `tessera legacy-history HISTORY_UUID history.sqlite` on the vault host. Inspect the retrieved copy read-only. Legacy SQL archives retain their original bytes and can be applied to a temporary database with the matching engine client.
## OIDC sign-in (single issuer)
Set `TESSERA_OIDC_ISSUER` to enable browser SSO (authorization code + PKCE S256,
Tessera is a confidential client). When it is set, these are also required:
| Variable | Meaning |
| --- | --- |
| `TESSERA_OIDC_CLIENT_ID`, `TESSERA_OIDC_CLIENT_SECRET` | Client registered at the IdP. The secret is only read from the environment and never logged. |
| `TESSERA_OIDC_REDIRECT_URL` | Public, static callback, exactly `https://<hub>/api/v1/auth/oidc/callback`. It is never derived from `Host` or `X-Forwarded-*`. |
| `TESSERA_OIDC_ADMIN_SUBJECTS` | Comma-separated `sub` values that may administer the hub. |
| `TESSERA_OIDC_ADMIN_GROUPS` | Comma-separated group names that may administer the hub. |
| `TESSERA_OIDC_GROUPS_CLAIM` | ID-token claim that carries groups (default `groups`; string or array of strings). |
| `TESSERA_OIDC_CA_FILE` | Optional PEM bundle for an IdP behind a private CA. |
At least one admin subject or group is mandatory, otherwise startup fails: with
no mapping nobody could administer the hub. Issuer and redirect URL must be
`https://`; plain http is accepted only for a loopback host together with
`TESSERA_LOCAL_DEVELOPMENT=true`.
Behaviour to know about:
- Users are identified by `(issuer, subject)`, never by email or display name.
There is no auto-link by email and no first-user-becomes-admin.
- A user who signs in but matches no admin mapping gets a "No access yet" page and
`403` on every management API. They can still call `GET /api/v1/me` and sign out.
- Group membership is read at sign-in. A change at the IdP applies at the next
sign-in, at most 8 hours later (absolute session limit); there is no back-channel
logout or SCIM yet.
- Changing the issuer, client ID, admin subjects/groups or groups claim ends every
existing OIDC session. Rotating the client secret does not.
- Sign-out ends the Tessera session only. The IdP session stays, so the next
"Sign in with SSO" may not ask for a password. RP-initiated logout is not implemented.
- ID tokens must be signed with RS256 (the library default). An IdP that signs
with another algorithm is rejected until that is made configurable.
- The emergency operator password keeps working beside SSO and is shown under
"Emergency operator sign-in" when SSO is on.
- No IdP token is stored or sent to the browser; the browser only receives the
Tessera session cookie.
## Outpost credentials, rotation and request limits
**Storage.** The hub keeps only SHA-256 digests of pairing codes and Outpost upload
tokens. A pairing code is shown once (10 minute lifetime, single use). The upload
token does not exist until the agent claims the code; it is returned once and never
stored or logged. Tokens are 256-bit random values. They expire after
`TESSERA_OUTPOST_TOKEN_DAYS` days (default 365).
**Upgrading an existing hub.** On first start the old clear-text `wormhole_tokens`
table is moved to digests and dropped, with `secure_delete` on so freed pages are
zeroed. Paired agents keep working with their current token and get a fresh
lifetime from the migration (the old `expires_at` was the pairing code's expiry).
Copies and backups of the old database still contain the clear-text tokens:
**rotate every Outpost token after upgrading** and treat old backups as sensitive.
Do not downgrade to a binary that predates this change; it would not understand the
new tables. Back up `tessera.db` first and rehearse on a copy.
**Rotate** (admin only). `POST /api/v1/wormhole/outposts/{id}/rotate?grace_minutes=60`
returns the new `upload_token` once. The previous token keeps working for the grace
period (default 60, maximum 1440, `0` cuts it at once) so you can put the new value
in the agent's `TESSERA_UPLOAD_TOKEN` and restart it. There is no agent
self-rotation yet: the operator delivers the new token.
**Revoke** (admin only). `POST /api/v1/wormhole/outposts/{id}/revoke` refuses every
token of that Outpost on its next request; it must be paired again. Both actions are
audited (`outpost.credential_rotate`, `outpost.credential_revoke`).
**Limits.** Unauthenticated and expensive endpoints are limited per source with
`governor`: emergency login (5 burst, 10/min per source, plus a looser 60/min account
ceiling), pairing claim (5 burst, 10/min per source, 120/min overall), SSO start and
callback. At most 2 Argon2 verifications run at once; further attempts get `429`
immediately. A denial is written to the audit log at most once a minute per source.
- The source is the TCP peer address. `X-Forwarded-For` is only used when the peer
is listed in `TESSERA_TRUSTED_PROXIES` (comma-separated IPs), read right to left
past trusted hops. Behind a reverse proxy **set this**, otherwise every user
shares the proxy's budget. IPv6 sources are keyed by /64.
- The account ceiling is deliberately looser than the per-source limit. With one
break-glass account, a tight account lock would let anyone lock the operator out.
- Limiter state is in memory: it resets when the hub restarts and is not shared
between hub processes.
**Shared admin token.** `TESSERA_ADMIN_TOKEN` is a transition aid. 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.