feat: add managed database capture and operator restore

PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-10 23:26:49 +07:00
parent 30a1a9b8f0
commit 6320b6f244
96 changed files with 11061 additions and 725 deletions

109
Cargo.lock generated
View File

@@ -347,6 +347,16 @@ dependencies = [
"windows-link",
]
[[package]]
name = "chrono-tz"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
dependencies = [
"chrono",
"phf",
]
[[package]]
name = "cipher"
version = "0.4.4"
@@ -412,6 +422,16 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "core-foundation"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@@ -1045,6 +1065,12 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "openssl-probe"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1"
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -1095,6 +1121,24 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "phf"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
dependencies = [
"phf_shared",
]
[[package]]
name = "phf_shared"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
dependencies = [
"siphasher",
]
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -1326,6 +1370,18 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pemfile"
version = "2.2.0"
@@ -1377,12 +1433,44 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags",
"core-foundation",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "serde"
version = "1.0.229"
@@ -1497,6 +1585,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "siphasher"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "slab"
version = "0.4.12"
@@ -1595,10 +1689,14 @@ dependencies = [
"anyhow",
"base64",
"clap",
"hex",
"rustls",
"rustls-native-certs",
"rustls-pemfile",
"serde",
"serde_json",
"sha2",
"tempfile",
"tessera-core",
"tessera-providers",
"tokio",
@@ -1612,9 +1710,13 @@ name = "tessera-cli"
version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
"clap",
"hex",
"serde",
"serde_json",
"sha2",
"tempfile",
"tessera-core",
"tessera-demo",
"tessera-providers",
@@ -1657,9 +1759,11 @@ name = "tessera-hub"
version = "0.1.0"
dependencies = [
"anyhow",
"argon2",
"axum",
"base64",
"chrono",
"chrono-tz",
"cron",
"hex",
"hyper",
@@ -1673,6 +1777,7 @@ dependencies = [
"rustls-pemfile",
"serde",
"serde_json",
"sha2",
"tempfile",
"tessera-core",
"tessera-demo",
@@ -1680,6 +1785,7 @@ dependencies = [
"tessera-store",
"tokio",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
"tracing",
@@ -1694,11 +1800,14 @@ version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"regex",
"serde",
"serde_json",
"tempfile",
"tessera-core",
"tokio",
"tracing",
"uuid",
"walkdir",
]

View File

@@ -13,12 +13,14 @@ COPY --from=web /build/dist ./web/dist
RUN cargo build --release -p tessera-hub
FROM restic/restic:0.19.1 AS restic
FROM mysql:8.4 AS mysql-client
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client && rm -rf /var/lib/apt/lists/*
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client libstdc++6 && rm -rf /var/lib/apt/lists/*
COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/
COPY --from=restic /usr/bin/restic /usr/local/bin/restic
RUN restic version
COPY --from=mysql-client /usr/bin/mysqldump /usr/local/bin/mysqldump
RUN restic version && mysqldump --version
ENV TESSERA_LISTEN=0.0.0.0:8787
ENV TESSERA_DATA_DIR=/data
EXPOSE 8787

View File

@@ -18,7 +18,7 @@ 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.
`TESSERA_ADMIN_TOKEN` is optional. When it is unset, the hub logs that snapshot, orbit, reconstitute, and pairing routes are open to loopback clients only. When it is set, every client, including loopback, must send `Authorization: Bearer <token>` or `X-Tessera-Admin-Token`. `/health`, the OpenAPI document, wormhole claim, and wormhole upload stay outside that check: claim uses the pairing code, and upload uses the upload token. The canvas does not send an admin token. A Docker-published connection is not loopback inside the container, so those backup routes answer 401 there until you set a token and call them with it.
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).
### Docker Compose
@@ -42,7 +42,7 @@ export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase'
## Deduplicated backups
New captures use Restic. Filesystem orbits back up files directly and share encrypted chunks in `vault/restic`. Each successful run creates a complete restore point. The API reports `size_bytes` for the logical backup, `stored_bytes` for new packed data and metadata, and `new_data_chunks` for newly stored payload chunks. An identical backup can add metadata while reporting zero new data chunks.
New captures use Restic. Orbits select **Filesystem / Folder** or **Database**, then **Via Hub** or **Via Outpost**. Filesystem orbits executed by the hub back up files directly and share encrypted chunks in `vault/restic`. Each successful run creates a complete restore point. The API reports `size_bytes` for the logical backup, `stored_bytes` for new packed data and metadata, and `new_data_chunks` for newly stored payload chunks. An identical backup can add metadata while reporting zero new data chunks.
Restore a new filesystem or Restic outpost snapshot to a file such as `restore.tar`. PostgreSQL and legacy upload restores still produce the original payload bytes. Existing snapshots use their original storage and restore format. Keep the entire `vault` directory and its passphrase together when moving a Tessera installation.
@@ -59,9 +59,15 @@ tessera orbit archive --path /srv/archive --keep-daily 7 --keep-weekly 2 --keep-
tessera retention <orbit-id> --keep-daily 7 --keep-weekly 2 --keep-monthly 6 --keep-yearly 3
```
The API accepts `{"retention":{"keep_daily":7,"keep_weekly":2,"keep_monthly":6,"keep_yearly":3}}` as part of `POST /api/v1/orbits` or as the body of `PUT /api/v1/orbits/{id}/retention`. Omitted tiers default to zero. To switch back to a preset, send `{"decay_preset":"week-of-dailies"}` to the same `PUT` endpoint or use `tessera retention <orbit-id> --preset week-of-dailies`. Saving applies the policy after the next successful capture. The separate `tessera decay --preset` command still applies its selected preset across the vault.
The API accepts `{"retention":{"keep_daily":7,"keep_weekly":2,"keep_monthly":6,"keep_yearly":3}}` as part of `POST /api/v1/orbits` or as the body of `PUT /api/v1/orbits/{id}/retention`. Omitted tiers default to zero. To switch back to a preset, send `{"decay_preset":"week-of-dailies"}` to the same `PUT` endpoint or use `tessera retention <orbit-id> --preset week-of-dailies`. Saving applies the policy after the next successful capture. The separate `tessera decay --preset` command applies its selected preset to legacy snapshots. Managed captures use their profile policy.
### Incremental Wormhole transfers
### Managed database backups
[Pair an agent and register a capture profile](docs/DATABASE-CAPTURE.md) for PostgreSQL or MySQL. Profiles support direct connections and pinned SSH, scheduled capture, job history, downloads, and optional S3 copies. The managed path stores dumps in the hub's existing Restic repository.
### Incremental Wormhole transfers for filesystem archives
The same repository setup is used by new [Outpost backup profiles](docs/DATABASE-CAPTURE.md).
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.
@@ -81,7 +87,7 @@ 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 that uses `https://` needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`.
- 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`.
- 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`.

View File

@@ -7,6 +7,15 @@ services:
TESSERA_LISTEN: "0.0.0.0:8787"
TESSERA_DATA_DIR: /data
TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE}
TESSERA_ADMIN_TOKEN:
TESSERA_OPERATOR_PASSWORD_HASH:
TESSERA_OPERATOR_NAME:
TESSERA_OFFSITE_REPOSITORY:
TESSERA_OFFSITE_PASSWORD_FILE:
AWS_ACCESS_KEY_ID:
AWS_SECRET_ACCESS_KEY:
AWS_SESSION_TOKEN:
AWS_REGION:
RUST_LOG: tessera_hub=info
volumes:
- tessera-data:/data

View File

@@ -20,5 +20,9 @@ tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace = true
base64 = "0.22"
tempfile.workspace = true
sha2.workspace = true
hex.workspace = true
rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] }
rustls-pemfile = "=2.2.0"
rustls-native-certs = "0.8"

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,235 @@
use crate::{
http,
jobs::{digest_file, Hub, Source},
};
use anyhow::{ensure, Context, Result};
use serde::Deserialize;
use std::{collections::HashMap, fs::File, sync::Arc, time::Duration};
use tessera_core::{
job::{CaptureFormat, CAPTURE_HEARTBEAT_SECONDS},
restore::{DatabaseIdentity, RestoreLease, RestoreProgress},
};
use tessera_providers::{MysqlRestore, PostgresRestore};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(tag = "engine", rename_all = "snake_case")]
pub(super) enum Target {
Postgres(PostgresRestore),
Mysql(MysqlRestore),
}
impl Target {
async fn identity(&self) -> Result<DatabaseIdentity> {
match self {
Self::Postgres(target) => target.connection.identity().await,
Self::Mysql(target) => target.connection.identity().await,
}
}
async fn prepare(&self, input: File, lease: &RestoreLease) -> Result<File> {
match (self, lease.artifact.format) {
(
Self::Postgres(target),
format @ (CaptureFormat::PostgresCustom | CaptureFormat::PostgresSql),
) => {
target
.prepare(input, format, &lease.job.target.identity)
.await
}
(Self::Mysql(target), CaptureFormat::MysqlSql) => {
target.prepare(input, &lease.job.target.identity).await
}
_ => anyhow::bail!("local restore target engine does not match the assignment"),
}
}
async fn safety(&self, stage: File) -> Result<()> {
match self {
Self::Postgres(target) => target.connection.safety_dump_to(stage).await,
Self::Mysql(target) => target.connection.dump_to(stage).await,
}
}
async fn apply(&self, script: File) -> Result<()> {
match self {
Self::Postgres(target) => target.apply(script).await,
Self::Mysql(target) => target.apply(script).await,
}
}
}
pub(super) async fn poll(
hub: &Arc<Hub>,
application: Uuid,
source: Option<&Source>,
targets: &HashMap<Uuid, Target>,
timeout_seconds: u64,
) -> Result<bool> {
for (target_id, target) in targets {
let reply = hub
.post(
format!("restore-targets/{target_id}/claim"),
serde_json::Value::Null,
None,
)
.await?;
let Some(lease) = serde_json::from_str::<Option<RestoreLease>>(&reply)? else {
continue;
};
ensure!(
lease.job.target.id == *target_id && lease.job.target.application_id == application,
"hub returned an unexpected restore target"
);
let work = run(
hub,
&lease,
target,
source,
Duration::from_secs(timeout_seconds),
);
tokio::pin!(work);
loop {
tokio::select! {
biased;
result = &mut work => return result.map(|()| true),
_ = tokio::time::sleep(Duration::from_secs(CAPTURE_HEARTBEAT_SECONDS)) => {
report(hub, &lease, RestoreProgress::Heartbeat).await?;
}
}
}
}
Ok(false)
}
async fn run(
hub: &Arc<Hub>,
lease: &RestoreLease,
target: &Target,
source: Option<&Source>,
timeout: Duration,
) -> Result<()> {
report(hub, lease, RestoreProgress::Checking).await?;
let downloaded = tokio::time::timeout(timeout, async {
let input = download(hub, lease, timeout).await?;
target.prepare(input, lease).await
})
.await;
let script = match downloaded {
Ok(Ok(script)) => script,
_ => {
report(hub, lease, RestoreProgress::InvalidPayload).await?;
return Ok(());
}
};
let verified = tokio::time::timeout(timeout, async {
let identity = target.identity().await?;
ensure!(
identity == lease.job.target.identity && identity != lease.artifact.identity,
"restore target identity does not match"
);
if let Some(source) = source {
if let Ok(Ok(source_identity)) =
tokio::time::timeout(Duration::from_secs(10), source.identity()).await
{
ensure!(
source_identity != identity,
"target resolves to the local backup source"
);
}
}
Ok::<_, anyhow::Error>(identity)
})
.await;
let identity = match verified {
Ok(Ok(identity)) => identity,
_ => {
report(hub, lease, RestoreProgress::WrongTarget).await?;
return Ok(());
}
};
report(hub, lease, RestoreProgress::Safety).await?;
let safety = tokio::time::timeout(timeout, async {
let stage = tempfile::tempfile().context("create private safety staging")?;
target.safety(stage.try_clone()?).await?;
ensure!(
target.identity().await? == identity,
"target changed during safety capture"
);
hub.upload(
format!("restore/{}/safety", lease.job.id),
stage,
timeout,
"x-tessera-restore-token",
lease.token,
None,
)
.await?;
Ok::<_, anyhow::Error>(())
})
.await;
if !matches!(safety, Ok(Ok(()))) {
report(hub, lease, RestoreProgress::SafetyFailed).await?;
return Ok(());
}
// The permit is single-use. A lost response leaves the target locked for reconciliation.
hub.post(
format!("restore/{}/apply", lease.job.id),
serde_json::Value::Null,
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
},
)
.await
}
async fn report(hub: &Arc<Hub>, lease: &RestoreLease, progress: RestoreProgress) -> Result<()> {
hub.post(
format!("restore/{}/report", lease.job.id),
serde_json::to_value(progress)?,
Some(lease.token),
)
.await?;
Ok(())
}
async fn download(hub: &Arc<Hub>, lease: &RestoreLease, timeout: Duration) -> Result<File> {
let hub = hub.clone();
let id = lease.job.id;
let token = lease.token.to_string();
let digest = lease.artifact.sha256.clone();
tokio::task::spawn_blocking(move || {
let mut file = tempfile::tempfile().context("create private restore staging")?;
let size = http::get_file(
&format!("{}/api/v1/wormhole/restore/{id}/payload", hub.url),
&mut file,
&[
("x-tessera-upload-token", &hub.token),
("x-tessera-restore-token", &token),
],
timeout,
)?;
let (bytes, computed) = digest_file(&mut file)?;
ensure!(
size == bytes && computed == digest,
"restore payload checksum mismatch"
);
Ok(file)
})
.await?
}

View File

@@ -14,6 +14,10 @@ tessera-store = { path = "../tessera-store" }
tessera-demo = { path = "../tessera-demo" }
tessera-providers = { path = "../tessera-providers" }
anyhow.workspace = true
chrono.workspace = true
tempfile.workspace = true
sha2.workspace = true
hex.workspace = true
clap.workspace = true
serde.workspace = true
serde_json.workspace = true

View File

@@ -1,6 +1,6 @@
use anyhow::{Context, Result};
use std::io::{Read, Write};
use std::net::TcpStream;
use std::net::{IpAddr, TcpStream};
pub fn get(url: &str) -> Result<String> {
request("GET", url, None, None)
@@ -24,8 +24,21 @@ fn request(
content_type: Option<&str>,
) -> Result<String> {
let (host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
if let Ok(token) = std::env::var("TESSERA_ADMIN_TOKEN") {
let token = token.trim();
if !token.is_empty() {
anyhow::ensure!(
host == "localhost" || host.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback()),
"the HTTP CLI requires a loopback hub URL when using an admin token"
);
anyhow::ensure!(
token.bytes().all(|byte| byte.is_ascii_graphic()),
"invalid admin token"
);
req.push_str(&format!("Authorization: Bearer {token}\r\n"));
}
}
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some(ct) = content_type {
@@ -36,6 +49,7 @@ fn request(
} else {
req.push_str("\r\n");
}
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;

View File

@@ -0,0 +1,287 @@
use anyhow::{ensure, Context, Result};
use chrono::{DateTime, Utc};
use clap::{Args, ValueEnum};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::{self, Read, Seek, SeekFrom},
path::PathBuf,
process::{Command, Stdio},
};
use tessera_core::SnapshotManifest;
use tessera_store::Vault;
use uuid::Uuid;
#[derive(Args, Clone)]
pub struct ImportArgs {
#[arg(long)]
bucket: String,
#[arg(long)]
prefix: String,
#[arg(long)]
endpoint: Option<String>,
#[arg(long)]
orbit_id: Uuid,
#[arg(long)]
application: String,
#[arg(long, value_enum)]
engine: Engine,
/// Consistent SQLite export of the old service's job history.
#[arg(long)]
history: Option<PathBuf>,
/// Reconcile counts, times and sizes without downloading or writing snapshots.
#[arg(long)]
inventory_only: bool,
}
#[derive(Clone, Copy, ValueEnum)]
enum Engine {
Postgres,
Mysql,
}
impl Engine {
fn name(self) -> &'static str {
match self {
Self::Postgres => "postgres",
Self::Mysql => "mysql",
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Listing {
#[serde(default)]
contents: Vec<Object>,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all(deserialize = "PascalCase"))]
struct Object {
key: String,
#[serde(rename(deserialize = "ETag"))]
etag: String,
size: u64,
last_modified: DateTime<Utc>,
}
#[derive(Deserialize)]
#[serde(rename_all = "PascalCase")]
struct Downloaded {
#[serde(rename = "ETag")]
etag: String,
content_length: u64,
last_modified: DateTime<Utc>,
}
#[derive(Serialize)]
struct Entry {
snapshot_id: Uuid,
#[serde(flatten)]
object: Object,
status: &'static str,
}
#[derive(Serialize)]
struct Report {
application: String,
bucket: String,
prefix: String,
count: usize,
bytes: u64,
history_snapshot_id: Option<Uuid>,
objects: Vec<Entry>,
}
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
ensure!(
!args.prefix.is_empty() && args.prefix.ends_with('/'),
"provide a per-application prefix ending in '/'"
);
ensure!(
!args.application.trim().is_empty()
&& args.application.len() <= 128
&& !args.application.chars().any(char::is_control),
"invalid application name"
);
if let Some(endpoint) = &args.endpoint {
ensure!(
(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:"))
&& !endpoint.contains(['@', '?', '#', '\r', '\n']),
"use an HTTPS S3 endpoint without embedded credentials"
);
}
let output = aws(&args, "list-objects-v2")
.arg(format!("--prefix={}", args.prefix))
.output()
.context("run AWS CLI S3 inventory")?;
ensure!(
output.status.success(),
"could not list legacy S3 objects ({})",
output.status
);
let listing: Listing =
serde_json::from_slice(&output.stdout).context("parse legacy S3 inventory")?;
let mut objects = Vec::new();
let mut bytes = 0u64;
for object in listing.contents {
if !object.key.starts_with(&args.prefix)
|| !(object.key.ends_with(".sql") || object.key.ends_with(".sql.gz"))
{
continue;
}
ensure!(
object.size > 0 && !object.etag.is_empty() && object.etag != "*",
"invalid legacy archive metadata"
);
bytes = bytes
.checked_add(object.size)
.context("legacy inventory byte count overflow")?;
let key = serde_json::to_vec(&(
"s3-legacy",
&args.endpoint,
&args.bucket,
&object.key,
&object.etag,
object.size,
object.last_modified,
args.orbit_id,
))?;
let snapshot_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, &key);
let status = if args.inventory_only {
"inventoried"
} else if vault.legacy_import_exists(snapshot_id)? {
"already_imported"
} else if import_object(vault, &args, &object, snapshot_id)? {
"imported"
} else {
"already_imported"
};
objects.push(Entry {
snapshot_id,
object,
status,
});
}
let history_snapshot_id = if args.inventory_only {
None
} else {
args.history
.as_ref()
.map(|path| import_history(vault, path))
.transpose()?
};
let report = Report {
application: args.application,
bucket: args.bucket,
prefix: args.prefix,
count: objects.len(),
bytes,
history_snapshot_id,
objects,
};
println!("{}", serde_json::to_string_pretty(&report)?);
Ok(())
}
fn aws(args: &ImportArgs, operation: &str) -> Command {
let mut cmd = Command::new("aws");
cmd.args([
"--no-cli-pager",
"--no-cli-auto-prompt",
"--output",
"json",
"s3api",
operation,
])
.arg(format!("--bucket={}", args.bucket))
.stdin(Stdio::null())
.stderr(Stdio::null());
if let Some(endpoint) = &args.endpoint {
cmd.arg(format!("--endpoint-url={endpoint}"));
}
cmd
}
fn import_object(vault: &Vault, args: &ImportArgs, object: &Object, id: Uuid) -> Result<bool> {
let file = tempfile::NamedTempFile::new()?;
let output = aws(args, "get-object")
.arg(format!("--key={}", object.key))
.arg(format!("--if-match={}", object.etag))
.arg(file.path())
.output()
.context("run conditional AWS CLI S3 download")?;
ensure!(
output.status.success(),
"legacy archive download failed ({})",
output.status
);
let received: Downloaded =
serde_json::from_slice(&output.stdout).context("parse downloaded object metadata")?;
ensure!(
received.etag == object.etag
&& received.last_modified == object.last_modified
&& received.content_length == object.size
&& file.as_file().metadata()?.len() == object.size,
"legacy object changed since inventory"
);
let mut file = file.reopen()?;
let format = if object.key.ends_with(".sql.gz") {
let mut signature = [0; 2];
file.read_exact(&mut signature)?;
ensure!(
signature == [0x1f, 0x8b],
"legacy archive is missing a gzip header"
);
file.seek(SeekFrom::Start(0))?;
"sql_gzip"
} else {
"plain"
};
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: args.orbit_id,
orbit_name: args.application.clone(),
provider: args.engine.name().into(),
labels: vec!["legacy-import".into()],
paths: vec![],
restore_hints: serde_json::json!({
"format": format, "legacy": { "bucket": args.bucket, "key": object.key,
"etag": object.etag, "bytes": object.size, "last_modified": object.last_modified }
}),
};
vault.import_legacy_payload(manifest, file, object.last_modified)
}
fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
let mut original = File::open(path).context("open legacy history export")?;
let mut signature = [0; 16];
original.read_exact(&mut signature)?;
ensure!(
&signature == b"SQLite format 3\0",
"legacy history must be a consistent SQLite export"
);
original.seek(SeekFrom::Start(0))?;
let mut staged = tempfile::tempfile()?;
let bytes = io::copy(&mut original, &mut staged)?;
staged.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
io::copy(&mut staged, &mut digest)?;
let checksum = hex::encode(digest.finalize());
let key = format!("legacy-history:{checksum}");
let id = Uuid::new_v5(&Uuid::NAMESPACE_URL, key.as_bytes());
let taken_at: DateTime<Utc> = original.metadata()?.modified()?.into();
let manifest = SnapshotManifest {
snapshot_id: id,
orbit_id: Uuid::nil(),
orbit_name: "Legacy operator history".into(),
provider: "legacy-history".into(),
labels: vec!["legacy-history".into()],
paths: vec![],
restore_hints: serde_json::json!({"format": "sqlite", "sha256": checksum, "legacy_bytes": bytes}),
};
vault.import_legacy_payload(manifest, staged, taken_at)?;
Ok(id)
}

View File

@@ -1,4 +1,5 @@
mod http;
mod legacy_import;
use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
@@ -50,6 +51,13 @@ enum Commands {
orbit: Option<String>,
},
List,
/// Reconcile and import immutable legacy SQL archives from an S3 prefix.
LegacyImport(legacy_import::ImportArgs),
/// Export the private legacy operator-history SQLite archive.
LegacyHistory {
snapshot_id: Uuid,
output: String,
},
Reconstitute {
snapshot_id: Uuid,
target: String,
@@ -163,6 +171,25 @@ fn main() -> Result<()> {
}
Commands::Snap { orbit } => cmd_snap(&cli, orbit)?,
Commands::List => cmd_list(&cli)?,
Commands::LegacyImport(args) => {
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
legacy_import::run(&vault, args)?;
}
Commands::LegacyHistory {
snapshot_id,
output,
} => {
let vault = Vault::open(vault_path(&cli.data_dir), require_passphrase(&cli)?)?;
let snapshot = vault
.get_snapshot(snapshot_id)?
.context("legacy history archive not found")?;
anyhow::ensure!(
snapshot.manifest.provider == "legacy-history",
"snapshot is not a legacy history archive"
);
vault.restore_snapshot(snapshot_id, std::path::Path::new(&output))?;
println!("Exported legacy history {snapshot_id}");
}
Commands::Reconstitute {
snapshot_id,
target,
@@ -257,8 +284,10 @@ fn cmd_orbit(
serde_json::json!({ "connection_url": path.context("--path or connection url required")? })
}
"wormhole" => {
anyhow::ensure!(path.is_none() && schedule.is_none() && !dry_run,
"Wormhole paths and scheduling are set on the outpost");
anyhow::ensure!(
path.is_none() && schedule.is_none() && !dry_run,
"Wormhole paths and scheduling are set on the outpost"
);
serde_json::json!({})
}
_ => anyhow::bail!("unknown provider"),

View File

@@ -58,6 +58,47 @@ 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 },
}
fn fallback_count() -> u16 {
5
}
impl Default for CaptureRetention {
fn default() -> Self {
Self::Age { days: 14 }
}
}
impl CaptureRetention {
pub fn is_valid(self) -> bool {
match self {
Self::Age { days } => days > 0,
Self::Count { keep } => keep > 0,
}
}
}
pub fn evaluate_capture_retention(
policy: CaptureRetention,
mut snapshots: Vec<SnapshotRef>,
now: DateTime<Utc>,
) -> Vec<Uuid> {
snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id)));
snapshots.into_iter().enumerate().skip(1).filter_map(|(index, snapshot)| {
let expired = match policy {
CaptureRetention::Age { days } => now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days),
CaptureRetention::Count { keep } => index >= usize::from(keep),
};
expired.then_some(snapshot.id)
}).collect()
}
/// Keep the newest snapshot in each of the most recent occupied UTC periods.
pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec<SnapshotRef>) -> Vec<Uuid> {
if !policy.has_tiers() {
@@ -160,6 +201,19 @@ mod tests {
use super::*;
use chrono::{Duration, TimeZone, Timelike};
#[test]
fn capture_retention_keeps_one_old_archive_or_the_latest_five() {
let now = Utc::now();
let snapshots: Vec<_> = (0..6).map(|i| SnapshotRef {
id: Uuid::new_v4(),
taken_at: now - Duration::days(15 + i),
}).collect();
assert_eq!(evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now),
snapshots[1..].iter().map(|snap| snap.id).collect::<Vec<_>>());
assert_eq!(evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now),
[snapshots[5].id]);
}
#[test]
fn gfs_keeps_the_newest_in_each_period_and_combines_tiers() {
let policy = RetentionPolicy {

View File

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

View File

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

View File

@@ -0,0 +1,109 @@
use crate::job::CaptureFormat;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Engine {
Postgres,
Mysql,
}
impl CaptureFormat {
pub fn engine(self) -> Option<Engine> {
match self {
Self::PostgresCustom | Self::PostgresSql => Some(Engine::Postgres),
Self::MysqlSql => Some(Engine::Mysql),
Self::Filesystem => None,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DatabaseIdentity {
pub instance: String,
pub database: String,
}
impl DatabaseIdentity {
pub fn valid(&self, engine: Engine) -> bool {
let instance_valid = match engine {
Engine::Postgres => self
.instance
.parse::<u64>()
.is_ok_and(|id| id.to_string() == self.instance),
Engine::Mysql => {
Uuid::parse_str(&self.instance).is_ok_and(|id| id.to_string() == self.instance)
}
};
instance_valid
&& (1..=255).contains(&self.database.len())
&& !self.database.chars().any(char::is_control)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RestoreTarget {
pub id: Uuid,
pub application_id: Uuid,
pub outpost_id: Uuid,
pub name: String,
pub engine: Engine,
pub identity: DatabaseIdentity,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RestoreRequest {
pub snapshot_id: Uuid,
pub target_id: Uuid,
pub confirmation: String,
}
impl RestoreRequest {
pub fn confirmation(snapshot: Uuid, target: Uuid) -> String {
format!("RESTORE {snapshot} TO {target}")
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RestoreJob {
pub id: Uuid,
pub snapshot_id: Uuid,
pub target: RestoreTarget,
pub actor: String,
pub status: String,
pub phase: String,
pub safety_snapshot_id: Option<Uuid>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RestoreArtifact {
pub format: CaptureFormat,
pub identity: DatabaseIdentity,
pub sha256: String,
}
#[derive(Deserialize, Serialize)]
pub struct RestoreLease {
pub job: RestoreJob,
pub token: Uuid,
pub artifact: RestoreArtifact,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RestoreProgress {
Heartbeat,
Checking,
Safety,
InvalidPayload,
WrongTarget,
SafetyFailed,
Applied,
ApplyFailed,
}

View File

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

View File

@@ -14,8 +14,10 @@ tessera-store = { path = "../tessera-store" }
tessera-providers = { path = "../tessera-providers" }
tessera-demo = { path = "../tessera-demo" }
anyhow.workspace = true
argon2.workspace = true
axum.workspace = true
chrono.workspace = true
chrono-tz = "0.10"
cron.workspace = true
include_dir = "0.7"
rand.workspace = true
@@ -23,12 +25,14 @@ serde.workspace = true
serde_json.workspace = true
rusqlite.workspace = true
tokio.workspace = true
tokio-util = { version = "0.7", features = ["io"] }
tower-http.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
utoipa.workspace = true
uuid.workspace = true
hex.workspace = true
sha2.workspace = true
base64 = "0.22"
tempfile.workspace = true
indexmap = "=2.2.6"

View File

@@ -65,7 +65,7 @@ fn presented_token(headers: &HeaderMap) -> Option<&str> {
}
}
fn tokens_match(expected: &str, presented: &str) -> bool {
pub(crate) fn tokens_match(expected: &str, presented: &str) -> bool {
let expected = expected.as_bytes();
let presented = presented.as_bytes();
let mut diff = expected.len() ^ presented.len();
@@ -133,3 +133,174 @@ mod tests {
.is_err());
}
}
#[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>,
}
struct OperatorConfig {
name: String,
password_hash: String,
}
#[derive(Clone)]
pub struct BrowserSession {
pub id: uuid::Uuid,
pub csrf: uuid::Uuid,
pub actor: String,
expires: std::time::Instant,
}
impl SessionGate {
pub const COOKIE: &str = "__Host-tessera-session";
pub const DURATION: std::time::Duration = std::time::Duration::from_secs(8 * 3600);
pub fn from_env() -> anyhow::Result<Self> {
let config = match std::env::var("TESSERA_OPERATOR_PASSWORD_HASH") {
Ok(password_hash) => {
let name =
std::env::var("TESSERA_OPERATOR_NAME").unwrap_or_else(|_| "operator".into());
anyhow::ensure!(
(1..=64).contains(&name.len())
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)),
"invalid operator name"
);
let parsed = argon2::PasswordHash::new(&password_hash)
.map_err(|_| anyhow::anyhow!("invalid operator Argon2id hash"))?;
anyhow::ensure!(
parsed.algorithm.as_str() == "argon2id",
"operator password requires Argon2id"
);
Some(std::sync::Arc::new(OperatorConfig {
name,
password_hash,
}))
}
Err(std::env::VarError::NotPresent) => None,
Err(_) => anyhow::bail!("operator password hash must be UTF-8"),
};
Ok(Self {
config,
state: Default::default(),
})
}
pub fn enabled(&self) -> bool {
self.config.is_some()
}
pub fn active(&self, headers: &HeaderMap) -> 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()
}
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 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)
}
pub fn remove(&self, id: uuid::Uuid) {
self.state.lock().unwrap().sessions.remove(&id);
}
}
fn cookie_id(headers: &HeaderMap) -> Option<uuid::Uuid> {
headers
.get_all(axum::http::header::COOKIE)
.iter()
.filter_map(|header| header.to_str().ok())
.flat_map(|line| line.split(';'))
.find_map(|pair| {
let (name, id) = pair.trim().split_once('=')?;
(name == SessionGate::COOKIE)
.then(|| uuid::Uuid::parse_str(id).ok())
.flatten()
})
}
pub fn print_operator_hash() -> anyhow::Result<()> {
use argon2::password_hash::{rand_core::OsRng, PasswordHasher, SaltString};
use std::io::BufRead;
let mut password = String::new();
std::io::stdin().lock().read_line(&mut password)?;
let password = password.trim_end_matches(['\n', '\r']);
anyhow::ensure!(
(12..=1024).contains(&password.len()),
"operator password must be 12–1024 bytes"
);
let salt = SaltString::generate(&mut OsRng);
let hash = argon2::Argon2::default()
.hash_password(password.as_bytes(), &salt)
.map_err(|_| anyhow::anyhow!("could not hash operator password"))?;
println!("{hash}");
Ok(())
}
#[cfg(test)]
impl SessionGate {
pub fn fixture() -> 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 {
config: Some(std::sync::Arc::new(OperatorConfig {
name: "fixture-operator".into(),
password_hash,
})),
state: Default::default(),
}
}
pub fn expire(&self) {
for session in self.state.lock().unwrap().sessions.values_mut() {
session.expires = std::time::Instant::now();
}
}
}

View File

@@ -0,0 +1,108 @@
use super::routes::{require_admin, require_admin_mutation};
use crate::state::HubState;
use axum::{
body::Body,
extract::{ConnectInfo, Path, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::get,
Router,
};
use std::net::SocketAddr;
use tokio_util::io::ReaderStream;
use uuid::Uuid;
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))
}
async fn download(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
require_admin(&state, peer, &headers)?;
let snapshot = state
.vault
.read()
.await
.get_snapshot(id)
.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)?;
let path = staging.path().join("download");
let size = 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
.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",
};
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())
}
async fn delete(
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 mut vault = state.vault.clone().write_owned().await;
if state.db.snapshot_in_restore(id).map_err(internal)?
|| state.db.offsite_pending(id).map_err(internal)? || state.active_exports().await.contains(&id)
{
return Err(StatusCode::CONFLICT);
}
if vault.get_snapshot(id).map_err(internal)?.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") {
return Err(StatusCode::NOT_FOUND);
}
state
.db
.audit(
"snapshot.delete_requested",
&format!("actor={actor} snapshot={id}"),
)
.await
.map_err(internal)?;
tokio::task::spawn_blocking(move || vault.forget(&[id]))
.await
.map_err(internal)?
.map_err(internal)?;
state
.db
.audit("snapshot.deleted", &format!("actor={actor} snapshot={id}"))
.await
.map_err(internal)?;
Ok(StatusCode::NO_CONTENT)
}
fn internal(_: impl std::fmt::Display) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}

View File

@@ -0,0 +1,428 @@
use super::routes::{require_admin, require_admin_mutation, upload_token};
use crate::state::HubState;
use axum::{
body::{Body, HttpBody},
extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
http::{header, HeaderMap, StatusCode},
routing::{get, post},
Json, Router,
};
use base64::Engine;
use sha2::{Digest, Sha256};
use std::{net::SocketAddr, pin::Pin, time::Duration};
use tessera_core::job::{
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport, ResticCaptureCommit,
};
use tessera_core::{restore::DatabaseIdentity, SnapshotManifest};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route(
"/api/v1/capture-profiles",
get(profiles).post(register_profile),
)
.route("/api/v1/capture-profiles/:id/jobs", post(enqueue))
.route("/api/v1/capture-jobs", get(history))
.route("/api/v1/capture-jobs/:id", get(job))
.route("/api/v1/capture-jobs/:id/events", get(events))
.route("/api/v1/wormhole/capture/:application/claim", post(claim))
.route("/api/v1/wormhole/capture/:id/report", post(report))
.route("/api/v1/wormhole/capture/:id/payload", post(upload))
.route("/api/v1/wormhole/capture/:id/restic", post(commit_restic))
}
async fn profiles(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state.db.capture_profiles().map(Json).map_err(internal)
}
async fn register_profile(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(profile): Json<CaptureProfile>,
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
if profile
.retention
.is_some_and(|retention| !retention.is_valid())
{
return Err(StatusCode::BAD_REQUEST);
}
if let Some(schedule) = &profile.schedule {
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
}
let _vault = state.vault.write().await;
if !state
.db
.register_capture_profile(&profile, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
state
.db
.audit(
"capture.profile_registered",
&format!("actor={actor} application={}", profile.application_id),
)
.await
.map_err(internal)?;
Ok((StatusCode::CREATED, Json(profile)))
}
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 job = state
.db
.enqueue_capture(id, &actor.name, now())
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
Ok((StatusCode::ACCEPTED, Json(job)))
}
#[derive(serde::Deserialize)]
struct JobFilter {
application_id: Option<Uuid>,
status: Option<String>,
limit: Option<u16>,
}
async fn history(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Query(filter): Query<JobFilter>,
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
require_admin(&state, peer, &headers)?;
if filter
.status
.as_deref()
.is_some_and(|status| !matches!(status, "queued" | "running" | "completed" | "failed"))
{
return Err(StatusCode::BAD_REQUEST);
}
state
.db
.capture_jobs(
filter.application_id,
filter.status.as_deref(),
filter.limit.unwrap_or(50).clamp(1, 200),
)
.map(Json)
.map_err(internal)
}
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)
}
async fn job(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
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)
}
async fn claim(
State(state): State<HubState>,
headers: HeaderMap,
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)?;
if let Some(lease) = &mut lease {
lease.restic |= lease.profile.format == CaptureFormat::Filesystem
|| state.vault.read().await.outpost_repository_configured(lease.profile.orbit_id).map_err(internal)?;
}
Ok(Json(lease))
}
async fn report(
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Result<Json<CaptureReport>, JsonRejection>,
) -> Result<StatusCode, StatusCode> {
let outpost = outpost(&state, &headers)?;
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
if !state
.db
.report_capture(outpost, id, body, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}
async fn upload(
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> {
let outpost = outpost(&state, &headers)?;
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
.map_err(|_| StatusCode::BAD_REQUEST)?;
let job = state
.db
.capture_upload(outpost, id, lease, now())
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if job.profile.format == CaptureFormat::Filesystem
|| state.db.restic_required(job.profile.orbit_id).map_err(internal)?
|| state.vault.read().await.outpost_repository_configured(job.profile.orbit_id).map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
let identity = headers
.get("x-tessera-source-identity")
.map(|header| {
let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(header.as_bytes())
.map_err(|_| StatusCode::BAD_REQUEST)?;
let identity: DatabaseIdentity =
serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?;
if !job.profile.format.engine().is_some_and(|engine| identity.valid(engine)) {
return Err(StatusCode::BAD_REQUEST);
}
Ok(identity)
})
.transpose()?;
let (file, expected) = receive_payload(&state, &headers, body, job.profile.format).await?;
if let Some(snapshot) = job.snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
}
let orbit_id = job.profile.orbit_id;
let manifest = capture_manifest(&state, &job, identity, Some(hex::encode(expected))).await?;
let vault = state.vault.clone().read_owned().await;
let db = state.db.clone();
let offsite_enabled = state.offsite.is_some();
let (snapshot, created) = tokio::task::spawn_blocking(move || {
// SQLite fencing covers metadata publication. Restic work happens before the transaction.
let prepared = if vault.has_published_snapshot(id)? {
None
} else {
Some(vault.prepare_payload(manifest, file, false)?)
};
let mut wrote = false;
let published = db.publish_capture(outpost, id, lease, offsite_enabled, |_| {
if !vault.has_published_snapshot(id)? {
vault.publish_prepared(
prepared
.as_ref()
.ok_or_else(|| anyhow::anyhow!("prepared snapshot missing"))?,
)?;
wrote = true;
}
Ok(())
})?;
// Preserve a prepared copy on an ambiguous commit error for reconciliation.
if !wrote {
if let Some(snap) = prepared.as_ref() {
if let Err(error) = vault.discard_prepared(snap) {
tracing::warn!(%id, %error, "could not discard unpublished capture");
}
}
}
Ok::<_, anyhow::Error>(published)
})
.await
.map_err(internal)?
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
if created && state.prune_orbit(orbit_id).await.is_err() {
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
}
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
}
async fn commit_restic(
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
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)?;
if let Some(snapshot) = job.snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
}
let engine = job.profile.format.engine();
if commit.identity.as_ref().is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine)))
|| (engine.is_some() && !commit.sha256.as_ref().is_some_and(|hash| {
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
}))
|| (engine.is_none() && commit.sha256.is_some())
{
return Err(StatusCode::BAD_REQUEST);
}
let orbit_id = job.profile.orbit_id;
let manifest = capture_manifest(&state, &job, commit.identity, commit.sha256).await?;
let vault = state.vault.clone().read_owned().await;
let db = state.db.clone();
let offsite = state.offsite.is_some() && engine.is_some();
let (snapshot, created) = tokio::task::spawn_blocking(move || {
let prepared = vault.prepare_outpost_capture(manifest, outpost, &commit.snapshot_id)?;
db.publish_capture(outpost, id, commit.lease_id, offsite, |_| {
if !vault.has_published_snapshot(id)? {
vault.publish_prepared(&prepared)?;
}
Ok(())
})
}).await.map_err(internal)?.map_err(internal)?.ok_or(StatusCode::CONFLICT)?;
if created && state.prune_orbit(orbit_id).await.is_err() {
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
}
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
}
async fn capture_manifest(
state: &HubState,
job: &CaptureJob,
identity: Option<DatabaseIdentity>,
digest: Option<String>,
) -> Result<SnapshotManifest, StatusCode> {
let id = job.id;
let orbit_id = job.profile.orbit_id;
let orbit = state
.db
.list_orbits()
.await
.map_err(internal)?
.into_iter()
.find(|orbit| orbit.id == orbit_id)
.ok_or(StatusCode::NOT_FOUND)?;
let (engine, format) = match job.profile.format {
CaptureFormat::PostgresCustom => ("postgres", "custom"),
CaptureFormat::PostgresSql => ("postgres", "plain"),
CaptureFormat::MysqlSql => ("mysql", "plain"),
CaptureFormat::Filesystem => ("filesystem", "tar"),
};
Ok(SnapshotManifest {
snapshot_id: id,
orbit_id,
orbit_name: orbit.name,
labels: vec![engine.into()],
provider: engine.into(),
paths: vec![],
restore_hints: serde_json::json!({
"engine": engine, "format": format, "job_id": id, "outpost_id": job.profile.outpost_id,
"application_id": job.profile.application_id, "sha256": digest,
"queued_at": job.created_at, "uploaded_at": now(), "source_identity": identity
}),
})
}
pub(super) async fn receive_payload(
state: &HubState,
headers: &HeaderMap,
mut body: Body,
format: CaptureFormat,
) -> Result<(std::fs::File, [u8; 32]), StatusCode> {
let length = header_value(headers, header::CONTENT_LENGTH.as_str())?
.parse::<u64>()
.map_err(|_| StatusCode::BAD_REQUEST)?;
if length == 0 || length > 100 * 1024 * 1024 * 1024 {
return Err(StatusCode::PAYLOAD_TOO_LARGE);
}
let mut expected = [0u8; 32];
hex::decode_to_slice(header_value(headers, "x-tessera-sha256")?, &mut expected)
.map_err(|_| StatusCode::BAD_REQUEST)?;
let file = tempfile::tempfile_in(&state.data_dir).map_err(internal)?;
let mut file = tokio::fs::File::from_std(file);
let mut digest = Sha256::new();
let mut bytes = 0;
loop {
let next = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx));
let Some(frame) = tokio::time::timeout(Duration::from_secs(30), next)
.await
.map_err(|_| StatusCode::REQUEST_TIMEOUT)?
else {
break;
};
let frame = frame.map_err(|_| StatusCode::BAD_REQUEST)?;
if let Ok(chunk) = frame.into_data() {
bytes += chunk.len() as u64;
if bytes > length {
return Err(StatusCode::BAD_REQUEST);
}
digest.update(&chunk);
file.write_all(&chunk).await.map_err(internal)?;
}
}
if bytes != length || digest.finalize()[..] != expected {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
file.flush().await.map_err(internal)?;
if format == CaptureFormat::PostgresCustom {
let mut signature = [0; 5];
file.seek(std::io::SeekFrom::Start(0))
.await
.map_err(internal)?;
if file.read_exact(&mut signature).await.is_err() || &signature != b"PGDMP" {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
}
Ok((file.into_std().await, expected))
}
pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, StatusCode> {
headers
.get(name)
.and_then(|value| value.to_str().ok())
.ok_or(StatusCode::BAD_REQUEST)
}
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
let token = upload_token(state, headers)?;
let id = state
.db
.upload_token_outpost(token)
.map_err(internal)?
.ok_or(StatusCode::UNAUTHORIZED)?;
let id = Uuid::parse_str(&id).map_err(internal)?;
state.db.touch_outpost(id).map_err(internal)?;
Ok(id)
}
pub(super) fn now() -> i64 {
chrono::Utc::now().timestamp()
}
pub(super) fn internal(_: impl std::fmt::Display) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}

View File

@@ -1,5 +1,9 @@
mod catalog;
mod jobs;
mod orbit;
mod restore;
mod routes;
mod session;
pub use orbit::run_orbit_internal;
pub use routes::router;

View File

@@ -2,15 +2,50 @@ use crate::db::OrbitRow;
use crate::state::HubState;
use anyhow::{Context, Result};
use tessera_core::manifest::SnapshotManifest;
use tessera_providers::{FilesystemConfig, PostgresProvider};
use tessera_providers::{FilesystemConfig, MysqlSource, PostgresProvider, PostgresSource};
use uuid::Uuid;
pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<Option<Uuid>> {
let orbits = state.db.list_orbits().await?;
let orbit = orbits
.into_iter()
.find(|o| o.id == orbit_id)
.context("orbit not found")?;
#[derive(serde::Deserialize)]
#[serde(tag = "engine", rename_all = "snake_case")]
pub(super) enum DatabaseSource {
Postgres(PostgresSource),
Mysql(MysqlSource),
}
impl DatabaseSource {
pub(super) fn valid_endpoint(&self) -> bool {
let (host, port, database, user, password_file) = match self {
Self::Postgres(source) if source.bastion.is_none() => (
&source.host,
source.port,
&source.database,
&source.user,
&source.password_file,
),
Self::Mysql(MysqlSource::Direct {
host,
port,
database,
user,
password_file,
..
}) => (host, *port, database, user, password_file),
_ => return false,
};
port != 0
&& password_file.is_absolute()
&& [host, database, user]
.iter()
.all(|value| !value.trim().is_empty() && !value.chars().any(char::is_control))
}
}
pub async fn run_orbit_internal(state: HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
anyhow::ensure!(
orbit.provider != "wormhole",
"Wormhole backups are started by the outpost agent"
);
let orbit_id = orbit.id;
anyhow::ensure!(
state.active_orbits.lock().await.insert(orbit_id),
"orbit already running"
@@ -49,6 +84,23 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>
manifest.paths = config.paths;
(None, config.max_file_bytes)
}
"database" => {
let source = serde_json::from_value::<DatabaseSource>(config)?;
let file = tempfile::tempfile()?;
let (engine, format) = match source {
DatabaseSource::Postgres(source) => {
source.dump_to(file.try_clone()?, "plain").await?;
("postgres", "plain")
}
DatabaseSource::Mysql(source) => {
source.dump_to(file.try_clone()?).await?;
("mysql", "plain")
}
};
manifest.provider = engine.into();
manifest.restore_hints = serde_json::json!({"engine": engine, "format": format});
(Some(file), None)
}
"postgres" => {
let provider = PostgresProvider::from_config(&config)?;
let file = tempfile::tempfile()?;

View File

@@ -0,0 +1,441 @@
use super::{
jobs::{header_value, internal, now, outpost, receive_payload},
routes::{require_admin, require_admin_mutation},
};
use crate::state::HubState;
use axum::{
body::Body,
extract::{rejection::JsonRejection, ConnectInfo, Path, State},
http::{header, HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
Json, Router,
};
use serde::Deserialize;
use std::net::SocketAddr;
use tessera_core::{
job::CaptureFormat,
restore::{
Engine, RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreRequest,
RestoreTarget,
},
SnapshotManifest,
};
use tokio_util::io::ReaderStream;
use uuid::Uuid;
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/restore-targets", post(register))
.route("/api/v1/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-jobs", get(history))
.route("/api/v1/restore-jobs/:id", get(job).delete(cancel))
.route("/api/v1/restore-jobs/:id/reconcile", post(reconcile))
.route("/api/v1/wormhole/restore-targets/:id/claim", post(claim))
.route("/api/v1/wormhole/restore/:id/payload", get(payload))
.route("/api/v1/wormhole/restore/:id/report", post(report))
.route("/api/v1/wormhole/restore/:id/safety", post(safety))
.route("/api/v1/wormhole/restore/:id/apply", post(apply))
}
async fn register(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(target): Json<RestoreTarget>,
) -> Result<(StatusCode, Json<RestoreTarget>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
if target.name.trim().is_empty()
|| target.name.len() > 128
|| target.name.chars().any(char::is_control)
|| !target.identity.valid(target.engine)
{
return Err(StatusCode::BAD_REQUEST);
}
let profiles = state.db.capture_profiles().map_err(internal)?;
if !profiles.iter().any(|profile| {
profile.application_id == target.application_id && profile.format.engine() == Some(target.engine)
}) {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
if !state
.db
.register_restore_target(&target)
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
state
.db
.audit(
"restore.target_registered",
&format!("actor={actor} target={}", target.id),
)
.await
.map_err(internal)?;
Ok((StatusCode::CREATED, Json(target)))
}
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)?;
state
.db
.restore_targets(application)
.map(Json)
.map_err(internal)
}
#[derive(serde::Serialize)]
struct SnapshotTarget {
#[serde(flatten)]
target: RestoreTarget,
ineligible_reason: Option<&'static str>,
}
async fn snapshot_targets(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<SnapshotTarget>>, StatusCode> {
require_admin(&state, peer, &headers)?;
let vault = state.vault.read().await;
let snap = vault
.get_snapshot(snapshot)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
let (application, artifact) =
artifact(&snap.manifest).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
let targets = state
.db
.restore_targets_with_activity(application)
.map_err(internal)?;
let responses = targets
.into_iter()
.map(|(target, active)| {
let ineligible_reason = if active {
crate::db::restore_target_mismatch(&target, &artifact)
} else {
Some("Outpost is no longer paired")
};
SnapshotTarget { target, ineligible_reason }
})
.collect();
Ok(Json(responses))
}
async fn enqueue(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(request): Json<RestoreRequest>,
) -> Result<(StatusCode, Json<RestoreJob>), StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
if request.confirmation != RestoreRequest::confirmation(request.snapshot_id, request.target_id)
{
return Err(StatusCode::BAD_REQUEST);
}
// The catalogue lock serializes creation of the durable pin with deletion.
let vault = state.vault.read().await;
let snap = vault
.get_snapshot(request.snapshot_id)
.map_err(internal)?
.ok_or(StatusCode::NOT_FOUND)?;
let (application, artifact) =
artifact(&snap.manifest).ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
let job = state
.db
.enqueue_restore(
request.snapshot_id,
application,
request.target_id,
&actor.name,
&artifact,
now(),
)
.map_err(internal)?
.ok_or(StatusCode::UNPROCESSABLE_ENTITY)?;
Ok((StatusCode::ACCEPTED, Json(job)))
}
pub(super) fn artifact(manifest: &SnapshotManifest) -> Option<(Uuid, RestoreArtifact)> {
let hints = &manifest.restore_hints;
let application = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
let format = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
("postgres", "custom") => CaptureFormat::PostgresCustom,
("postgres", "plain") => CaptureFormat::PostgresSql,
("mysql", "plain") => CaptureFormat::MysqlSql,
_ => return None,
};
let sha256 = hints.get("sha256")?.as_str()?.to_owned();
if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let identity: tessera_core::restore::DatabaseIdentity =
serde_json::from_value(hints.get("source_identity")?.clone()).ok()?;
if !format.engine().is_some_and(|engine| identity.valid(engine)) {
return None;
}
Some((
application,
RestoreArtifact {
format,
identity,
sha256,
},
))
}
async fn job(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Json<RestoreJob>, StatusCode> {
require_admin(&state, peer, &headers)?;
state
.db
.restore_job(id, now())
.map_err(internal)?
.map(Json)
.ok_or(StatusCode::NOT_FOUND)
}
async fn history(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(snapshot): Path<Uuid>,
) -> Result<Json<Vec<RestoreJob>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state
.db
.restore_history(snapshot, 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)?;
if !state
.db
.cancel_restore(id, &actor.name, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}
#[derive(Deserialize)]
struct Reconcile {
confirmation: String,
}
async fn reconcile(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(body): Json<Reconcile>,
) -> Result<StatusCode, StatusCode> {
let actor = require_admin_mutation(&state, peer, &headers)?;
if body.confirmation != format!("RECONCILE {id}") {
return Err(StatusCode::BAD_REQUEST);
}
if !state
.db
.reconcile_restore(id, &actor.name, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}
async fn claim(
State(state): State<HubState>,
headers: HeaderMap,
Path(target): Path<Uuid>,
) -> Result<Json<Option<RestoreLease>>, StatusCode> {
let outpost = outpost(&state, &headers)?;
state
.db
.claim_restore(outpost, target, now())
.map(Json)
.map_err(internal)
}
fn auth(state: &HubState, headers: &HeaderMap) -> Result<(Uuid, Uuid), StatusCode> {
let outpost = outpost(state, headers)?;
let token =
header_value(headers, "x-tessera-restore-token").map_err(|_| StatusCode::UNAUTHORIZED)?;
Ok((
outpost,
Uuid::parse_str(token).map_err(|_| StatusCode::UNAUTHORIZED)?,
))
}
async fn payload(
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<Response, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let (job, artifact, _) = state
.db
.restore_access(outpost, id, token, now())
.map_err(internal)?
.filter(|(job, _, _)| job.phase == "checking")
.ok_or(StatusCode::FORBIDDEN)?;
let staging = tempfile::tempdir_in(&state.data_dir).map_err(internal)?;
let path = staging.path().join("restore");
let size = state
.export_snapshot(job.snapshot_id, path.clone())
.await
.map_err(internal)?;
if state
.db
.restore_access(outpost, id, token, now())
.map_err(internal)?
.is_none_or(|(job, _, _)| job.phase != "checking")
{
return Err(StatusCode::FORBIDDEN);
}
let file = tokio::fs::File::open(path).await.map_err(internal)?;
Ok((
[
(header::CONTENT_TYPE, "application/octet-stream".to_owned()),
(header::CONTENT_LENGTH, size.to_string()),
(header::CACHE_CONTROL, "no-store".to_owned()),
(
axum::http::HeaderName::from_static("x-tessera-sha256"),
artifact.sha256,
),
],
Body::from_stream(ReaderStream::new(file)),
)
.into_response())
}
async fn report(
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Result<Json<RestoreProgress>, JsonRejection>,
) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let Json(progress) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
if !state
.db
.report_restore(outpost, id, token, progress, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}
async fn safety(
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
body: Body,
) -> Result<Json<serde_json::Value>, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
let (job, _, safety_id) = state
.db
.restore_access(outpost, id, token, now())
.map_err(internal)?
.filter(|(job, _, _)| matches!(job.phase.as_str(), "safety" | "ready"))
.ok_or(StatusCode::FORBIDDEN)?;
let (format, provider, format_name) = match job.target.engine {
Engine::Postgres => (CaptureFormat::PostgresCustom, "postgres", "custom"),
Engine::Mysql => (CaptureFormat::MysqlSql, "mysql", "plain"),
};
let (file, expected) = receive_payload(&state, &headers, body, format).await?;
if let Some(snapshot) = job.safety_snapshot_id {
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
}
let vault = state.vault.clone().read_owned().await;
let db = state.db.clone();
let saved = tokio::task::spawn_blocking(move || {
let input = vault
.get_snapshot(job.snapshot_id)?
.ok_or_else(|| anyhow::anyhow!("pinned snapshot missing"))?;
let manifest = SnapshotManifest {
snapshot_id: safety_id,
orbit_id: input.manifest.orbit_id,
orbit_name: input.manifest.orbit_name,
provider: provider.into(),
labels: vec!["restore-safety".into()],
paths: vec![],
restore_hints: serde_json::json!({
"format": format_name, "safety_for": id, "target_id": job.target.id,
"sha256": hex::encode(expected),
}),
};
let prepared = if vault.has_published_snapshot(safety_id)? {
None
} else {
let prepared = vault.prepare_payload(manifest, file, false)?;
if let Err(error) = vault.verify_prepared_payload(&prepared, &expected) {
let _ = vault.discard_prepared(&prepared);
return Err(error);
}
Some(prepared)
};
let mut wrote = false;
let result = db.record_safety(outpost, id, token, now(), |expected_id| {
anyhow::ensure!(expected_id == safety_id, "stale safety snapshot");
if !vault.has_published_snapshot(safety_id)? {
vault.publish_prepared(
prepared
.as_ref()
.ok_or_else(|| anyhow::anyhow!("safety snapshot missing"))?,
)?;
wrote = true;
}
Ok(())
})?;
if !wrote {
if let Some(prepared) = &prepared {
let _ = vault.discard_prepared(prepared);
}
}
Ok::<_, anyhow::Error>(result)
})
.await
.map_err(internal)?
.map_err(internal)?
.ok_or(StatusCode::CONFLICT)?;
Ok(Json(serde_json::json!({ "snapshot_id": saved })))
}
async fn apply(
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
let (outpost, token) = auth(&state, &headers)?;
if !state
.db
.authorize_apply(outpost, id, token, now())
.map_err(internal)?
{
return Err(StatusCode::CONFLICT);
}
Ok(StatusCode::NO_CONTENT)
}

View File

@@ -1,5 +1,5 @@
use crate::db::OrbitRow;
use crate::state::HubState;
use crate::state::{HubState, ManagedRetention};
use crate::upload::write_at;
use axum::{
extract::{ConnectInfo, Path, State},
@@ -9,6 +9,8 @@ use axum::{
Json, Router,
};
use base64::Engine;
use rand::Rng;
use tessera_core::OutpostSummary;
use include_dir::{include_dir, Dir};
use std::fs::{File, OpenOptions};
use std::net::SocketAddr;
@@ -39,8 +41,11 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist");
),
components(schemas(
SnapshotSummary,
OrbitRow,
CaptureSnapshotSummary,
OrbitResponse,
CreateOrbitRequest,
OrbitSource,
OrbitAccess,
RetentionUpdate,
RetentionPolicy,
ReconstituteRequest,
@@ -62,14 +67,107 @@ struct SnapshotSummary {
taken_at: chrono::DateTime<chrono::Utc>,
orbit_name: String,
size_bytes: u64,
capture: Option<CaptureSnapshotSummary>,
stored_bytes: Option<u64>,
new_data_chunks: Option<u64>,
}
#[derive(serde::Serialize, utoipa::ToSchema)]
struct CaptureSnapshotSummary {
job_id: Uuid,
application_id: Uuid,
engine: &'static str,
format: &'static str,
restore_ready: bool,
}
impl CaptureSnapshotSummary {
fn from_manifest(manifest: &SnapshotManifest) -> Option<Self> {
let hints = &manifest.restore_hints;
let job_id = Uuid::parse_str(hints.get("job_id")?.as_str()?).ok()?;
let application_id = Uuid::parse_str(hints.get("application_id")?.as_str()?).ok()?;
let (engine, format) = match (manifest.provider.as_str(), hints.get("format")?.as_str()?) {
("postgres", "custom") => ("postgres", "custom"),
("postgres", "plain") => ("postgres", "plain"),
("mysql", "plain") => ("mysql", "plain"),
_ => return None,
};
Some(Self {
job_id, application_id, engine, format,
restore_ready: super::restore::artifact(manifest).is_some(),
})
}
}
#[derive(serde::Serialize, utoipa::ToSchema)]
struct OrbitResponse {
id: Uuid,
name: String,
provider: String,
source: Option<OrbitSource>,
access: OrbitAccess,
schedule: Option<String>,
decay_preset: String,
retention: Option<RetentionPolicy>,
dry_run: bool,
last_status: String,
application_id: Option<Uuid>,
#[schema(value_type = Option<Object>)]
capture_schedule: Option<tessera_core::job::CaptureSchedule>,
#[schema(value_type = Option<Object>)]
capture_retention: Option<tessera_core::decay::CaptureRetention>,
retention_source: &'static str,
}
impl From<OrbitRow> for OrbitResponse {
fn from(row: OrbitRow) -> Self {
let source = match row.provider.as_str() {
"filesystem" => Some(OrbitSource::Filesystem),
"postgres" | "database" => Some(OrbitSource::Database),
"wormhole" => serde_json::from_str::<serde_json::Value>(&row.provider_config)
.ok().and_then(|config| serde_json::from_value(config["source"].clone()).ok()),
_ => None,
};
let access = if row.provider == "wormhole" { OrbitAccess::Outpost } else { OrbitAccess::Hub };
Self {
source,
access,
id: row.id,
name: row.name,
provider: row.provider,
schedule: row.schedule,
decay_preset: row.decay_preset,
retention: row.retention,
dry_run: row.dry_run,
last_status: row.last_status,
application_id: None,
capture_schedule: None,
capture_retention: None,
retention_source: "orbit",
}
}
}
#[derive(Clone, Copy, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
enum OrbitSource {
Filesystem,
Database,
}
#[derive(serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
#[serde(rename_all = "snake_case")]
enum OrbitAccess {
Hub,
Outpost,
}
#[derive(serde::Deserialize, utoipa::ToSchema)]
struct CreateOrbitRequest {
name: String,
provider: String,
provider: Option<String>,
source: Option<OrbitSource>,
access: Option<OrbitAccess>,
provider_config: serde_json::Value,
schedule: Option<String>,
decay_preset: Option<String>,
@@ -133,12 +231,53 @@ struct ReconstituteStartResponse {
session: ReconstituteSession,
}
fn require_admin(
pub(super) struct OperatorActor {
pub(super) name: String,
browser: bool,
}
impl std::fmt::Display for OperatorActor {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.name.fmt(formatter)
}
}
pub(super) fn require_admin(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
) -> Result<(), StatusCode> {
state.admin.authorize(peer, headers)
authorize_operator(state, peer, headers, false).map(|_| ())
}
pub(super) fn require_admin_mutation(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
) -> Result<OperatorActor, StatusCode> {
authorize_operator(state, peer, headers, true)
}
fn authorize_operator(
state: &HubState,
peer: SocketAddr,
headers: &HeaderMap,
mutation: bool,
) -> Result<OperatorActor, StatusCode> {
if state.admin.token.is_some() && state.admin.authorize(peer, headers).is_ok() {
return Ok(OperatorActor { name: "api-token".into(), browser: false });
}
if let Some(session) = state.sessions.active(headers) {
if mutation {
super::session::require_csrf(headers, &session.csrf.to_string())?;
}
return Ok(OperatorActor { name: session.actor, browser: true });
}
if !state.sessions.enabled() {
state.admin.authorize(peer, headers)?;
return Ok(OperatorActor { name: "loopback".into(), browser: false });
}
Err(StatusCode::UNAUTHORIZED)
}
pub fn router(state: HubState) -> Router {
@@ -153,6 +292,7 @@ pub fn router(state: HubState) -> Router {
"/api/v1/reconstitute/:id",
get(reconstitute_status).delete(abort_reconstitute),
)
.route("/api/v1/wormhole/outposts", get(outposts))
.route("/api/v1/wormhole/pairing", post(pairing_start))
.route("/api/v1/wormhole/claim", post(pairing_claim))
.route("/api/v1/wormhole/upload/init", post(wormhole_upload_init))
@@ -161,6 +301,10 @@ pub fn router(state: HubState) -> Router {
"/api/v1/wormhole/restic/commit",
post(wormhole_restic_commit),
)
.merge(super::jobs::routes())
.merge(super::catalog::routes())
.merge(super::session::routes())
.merge(super::restore::routes())
.with_state(state);
let api = api.route(
@@ -188,10 +332,12 @@ async fn list_snapshots(
let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let out = snaps
.into_iter()
.filter(|s| s.manifest.provider != "legacy-history")
.map(|s| SnapshotSummary {
id: s.id,
orbit_id: s.manifest.orbit_id,
taken_at: s.taken_at,
capture: CaptureSnapshotSummary::from_manifest(&s.manifest),
orbit_name: s.manifest.orbit_name,
size_bytes: s.size_bytes,
stored_bytes: s.stored_bytes,
@@ -201,36 +347,103 @@ async fn list_snapshots(
Ok(Json(out))
}
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitRow])))]
#[utoipa::path(get, path = "/api/v1/orbits", responses((status = 200, body = [OrbitResponse])))]
async fn list_orbits(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<OrbitRow>>, StatusCode> {
) -> Result<Json<Vec<OrbitResponse>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state
let profiles: std::collections::HashMap<_, _> = state
.db
.list_orbits()
.await
.map(Json)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
.capture_profiles()
.map_err(super::jobs::internal)?
.into_iter()
.map(|profile| (profile.orbit_id, profile))
.collect();
let rows = state.db.list_orbits().await.map_err(super::jobs::internal)?;
let responses = rows
.into_iter()
.map(|row| {
let mut response = OrbitResponse::from(row);
if let Some(profile) = profiles.get(&response.id) {
response.application_id = Some(profile.application_id);
response.source = Some(if profile.format == tessera_core::job::CaptureFormat::Filesystem {
OrbitSource::Filesystem
} else {
OrbitSource::Database
});
response.capture_schedule = profile.schedule.clone();
(response.capture_retention, response.retention_source) =
match ManagedRetention::resolve(profile, response.retention) {
ManagedRetention::Orbit(_) => (None, "orbit"),
ManagedRetention::Profile(policy) => (Some(policy), "profile"),
ManagedRetention::Default(policy) => (Some(policy), "default"),
};
}
response
})
.collect();
Ok(Json(responses))
}
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))]
#[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitResponse), (status = 400)))]
async fn create_orbit(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Json(req): Json<CreateOrbitRequest>,
) -> Result<Json<OrbitRow>, (StatusCode, &'static str)> {
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
) -> Result<Json<OrbitResponse>, (StatusCode, &'static str)> {
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
if req.name.trim().is_empty() {
return Err((StatusCode::BAD_REQUEST, "orbit name is required"));
}
let (decay_preset, retention) = retention_settings(req.decay_preset, req.retention)?;
let (provider, config) = match (req.source, req.access, req.provider.as_deref()) {
(Some(OrbitSource::Filesystem), Some(OrbitAccess::Hub), None) => {
let config: tessera_providers::FilesystemConfig = serde_json::from_value(req.provider_config.clone())
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid filesystem configuration"))?;
if config.paths.is_empty() || config.paths.iter().any(|path| path.trim().is_empty()) {
return Err((StatusCode::BAD_REQUEST, "at least one filesystem path is required"));
}
("filesystem", req.provider_config)
}
(Some(OrbitSource::Database), Some(OrbitAccess::Hub), None) => {
let source: super::orbit::DatabaseSource = serde_json::from_value(req.provider_config.clone())
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid database configuration"))?;
if !source.valid_endpoint() {
return Err((StatusCode::BAD_REQUEST, "invalid database endpoint or password file path"));
}
("database", req.provider_config)
}
(Some(source), Some(OrbitAccess::Outpost), None)
if req.provider_config.as_object().is_some_and(|config| config.is_empty())
&& !req.dry_run.unwrap_or(false) =>
{
("wormhole", serde_json::json!({ "source": source }))
}
(None, None, Some("filesystem" | "postgres" | "wormhole")) =>
(req.provider.as_deref().unwrap(), req.provider_config),
_ => return Err((StatusCode::BAD_REQUEST, "invalid backup source or access")),
};
let schedule = req.schedule.filter(|expression| !expression.trim().is_empty());
if let Some(expression) = &schedule {
if provider == "wormhole" {
return Err((StatusCode::BAD_REQUEST, "set the schedule on the Outpost capture profile"));
}
crate::scheduler::orbit_schedule(expression)
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid cron schedule (UTC)"))?;
}
if provider == "postgres" {
tessera_providers::PostgresProvider::from_config(&config)
.map_err(|_| (StatusCode::BAD_REQUEST, "invalid PostgreSQL connection URL or dump format"))?;
}
let row = OrbitRow {
id: Uuid::new_v4(),
name: req.name,
provider: req.provider,
provider_config: serde_json::to_string(&req.provider_config).unwrap_or_else(|_| "{}".into()),
schedule: req.schedule,
provider: provider.to_owned(),
provider_config: config.to_string(),
schedule,
decay_preset,
retention,
dry_run: req.dry_run.unwrap_or(false),
@@ -241,7 +454,7 @@ async fn create_orbit(
.upsert_orbit(&row)
.await
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not save orbit"))?;
Ok(Json(row))
Ok(Json(row.into()))
}
fn retention_settings(
@@ -274,7 +487,7 @@ async fn update_orbit_retention(
Path(id): Path<Uuid>,
Json(req): Json<RetentionUpdate>,
) -> Result<StatusCode, (StatusCode, &'static str)> {
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?;
if req.decay_preset.is_none() && req.retention.is_none() {
return Err((
StatusCode::BAD_REQUEST,
@@ -297,15 +510,23 @@ async fn update_orbit_retention(
Ok(StatusCode::NO_CONTENT)
}
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault")))))]
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault"))), (status = 404), (status = 409)))]
async fn trigger_orbit(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<(StatusCode, HeaderMap), (StatusCode, String)> {
require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
let snapshot_id = crate::api::run_orbit_internal(state, id)
require_admin_mutation(&state, peer, &headers).map_err(|status| (status, "unauthorized".into()))?;
let orbit = state.db.list_orbits().await
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not read orbits".into()))?
.into_iter()
.find(|orbit| orbit.id == id)
.ok_or((StatusCode::NOT_FOUND, "orbit not found".into()))?;
if orbit.provider == "wormhole" {
return Err((StatusCode::CONFLICT, "queue the capture through its Outpost profile or run the legacy agent".into()));
}
let snapshot_id = crate::api::run_orbit_internal(state, orbit)
.await
.map_err(|error| {
tracing::warn!(orbit_id = %id, %error, "capture did not complete");
@@ -331,7 +552,17 @@ async fn start_reconstitute(
headers: HeaderMap,
Json(req): Json<ReconstituteRequest>,
) -> Result<Json<ReconstituteStartResponse>, StatusCode> {
require_admin(&state, peer, &headers)?;
let actor = require_admin_mutation(&state, peer, &headers)?;
let destination = if actor.browser {
browser_export_path(&state, &req.target_path)?
} else {
req.target_path.clone().into()
};
let vault = state.vault.read().await;
if vault.get_snapshot(req.snapshot_id).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.is_none_or(|snapshot| snapshot.manifest.provider == "legacy-history") {
return Err(StatusCode::NOT_FOUND);
}
let session_id = Uuid::new_v4();
let session = ReconstituteSession {
snapshot_id: req.snapshot_id,
@@ -344,9 +575,9 @@ async fn start_reconstitute(
.write()
.await
.insert(session_id, session.clone());
drop(vault);
let state_bg = state.clone();
let target = req.target_path;
tokio::spawn(async move {
for remaining in (0..RECONSTITUTE_GRACE_SECS).rev() {
{
@@ -371,14 +602,7 @@ async fn start_reconstitute(
s.state = ReconstituteState::Restoring;
s.seconds_remaining = 0;
}
let dest = std::path::PathBuf::from(&target);
let result = {
let vault = state_bg.vault.clone().read_owned().await;
tokio::task::spawn_blocking(move || vault.restore_snapshot(req.snapshot_id, &dest))
.await
.map_err(anyhow::Error::from)
.and_then(|result| result)
};
let result = state_bg.export_snapshot(req.snapshot_id, destination).await;
let mut map = state_bg.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&session_id) {
s.state = if result.is_ok() {
@@ -396,6 +620,39 @@ async fn start_reconstitute(
}))
}
fn browser_export_path(state: &HubState, requested: &str) -> Result<std::path::PathBuf, StatusCode> {
use std::path::{Component, Path};
let mut components = Path::new(requested).components();
let Some(Component::Normal(name)) = components.next() else { return Err(StatusCode::BAD_REQUEST) };
if components.next().is_some() || name.len() > 255 {
return Err(StatusCode::BAD_REQUEST);
}
let directory = state.data_dir.join("exports");
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
match builder.create(&directory) {
Ok(()) => (),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => (),
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
}
let metadata = std::fs::symlink_metadata(&directory).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if !metadata.is_dir() {
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o077 != 0 {
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
}
Ok(directory.join(name))
}
async fn reconstitute_status(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
@@ -413,7 +670,7 @@ async fn abort_reconstitute(
headers: HeaderMap,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
require_admin(&state, peer, &headers)?;
require_admin_mutation(&state, peer, &headers)?;
let mut map = state.reconstitute_sessions.write().await;
if let Some(s) = map.get_mut(&id) {
if matches!(
@@ -427,23 +684,27 @@ async fn abort_reconstitute(
Err(StatusCode::BAD_REQUEST)
}
async fn outposts(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<Vec<OutpostSummary>>, StatusCode> {
require_admin(&state, peer, &headers)?;
state.db.list_outposts().map(Json).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
#[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))]
async fn pairing_start(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<Json<PairingResponse>, StatusCode> {
require_admin(&state, peer, &headers)?;
let code: String = (0..6)
.map(|_| {
let n = rand::random::<u8>() % 36;
if n < 10 {
(b'0' + n) as char
} else {
(b'A' + n - 10) as char
}
})
.collect();
require_admin_mutation(&state, peer, &headers)?;
const ALPHABET: &[u8] = b"23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
let code: String = {
let mut random = rand::thread_rng();
(0..12).map(|_| ALPHABET[random.gen_range(0..ALPHABET.len())] as char).collect()
};
let expires = chrono::Utc::now() + chrono::Duration::minutes(10);
let outpost_id = Uuid::new_v4();
let upload_token = hex::encode(Uuid::new_v4().as_bytes());
@@ -467,10 +728,14 @@ async fn pairing_claim(
State(state): State<HubState>,
Json(req): Json<ClaimRequest>,
) -> Result<Json<ClaimResponse>, StatusCode> {
let name = req.outpost_name.trim();
if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) {
return Err(StatusCode::BAD_REQUEST);
}
let now = chrono::Utc::now().to_rfc3339();
let claimed = state
.db
.claim_wormhole_code(&req.code, &req.outpost_name, &now)
.claim_wormhole_code(&req.code, name, &now)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::GONE)?;
let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| {
@@ -482,7 +747,7 @@ async fn pairing_claim(
});
state
.db
.audit("wormhole.paired", &req.outpost_name)
.audit("wormhole.paired", name)
.await
.ok();
let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
@@ -499,7 +764,8 @@ async fn wormhole_upload_init(
headers: axum::http::HeaderMap,
Json(body): Json<UploadInit>,
) -> Result<Json<serde_json::Value>, StatusCode> {
verify_upload_token(&state, &headers)?;
super::jobs::outpost(&state, &headers)?;
reject_managed_orbit(&state, body.orbit_id)?;
if state
.vault
.read()
@@ -538,12 +804,13 @@ async fn wormhole_upload_chunk(
headers: axum::http::HeaderMap,
Json(body): Json<UploadChunk>,
) -> Result<StatusCode, StatusCode> {
verify_upload_token(&state, &headers)?;
super::jobs::outpost(&state, &headers)?;
let session = state
.db
.upload_session(&body.session_id.to_string())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
reject_managed_orbit(&state, session.orbit_id)?;
if session.sealed {
return Err(StatusCode::CONFLICT);
}
@@ -608,16 +875,7 @@ fn restrict_part(path: &std::path::Path) {
let _ = path;
}
fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> {
let token = upload_token(state, headers)?;
if state.upload_token_valid(token) {
Ok(())
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
fn upload_token<'a>(state: &HubState, headers: &'a HeaderMap) -> Result<&'a str, StatusCode> {
pub(super) fn upload_token<'a>(state: &HubState, headers: &'a HeaderMap) -> Result<&'a str, StatusCode> {
if !state.accept_plain_upload {
return Err(StatusCode::FORBIDDEN);
}
@@ -633,13 +891,7 @@ async fn wormhole_restic_commit(
headers: HeaderMap,
Json(body): Json<ResticCommit>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let token = upload_token(&state, &headers)?;
let outpost_id = state
.db
.upload_token_outpost(token)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.and_then(|id| Uuid::parse_str(&id).ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
let outpost_id = super::jobs::outpost(&state, &headers)?;
if body.snapshot_id.len() != 64 || !body.snapshot_id.bytes().all(|b| b.is_ascii_hexdigit()) {
return Err(StatusCode::BAD_REQUEST);
}
@@ -653,6 +905,7 @@ async fn wormhole_restic_commit(
.ok_or(StatusCode::NOT_FOUND)?;
let orbit_id = orbit.id;
let mut vault = state.vault.clone().write_owned().await;
reject_managed_orbit(&state, orbit_id)?;
let (snapshot, created) = tokio::task::spawn_blocking(move || {
let manifest = SnapshotManifest {
snapshot_id: Uuid::nil(),
@@ -689,6 +942,15 @@ async fn wormhole_restic_commit(
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
}
fn reject_managed_orbit(state: &HubState, orbit_id: Uuid) -> Result<(), StatusCode> {
if state.db.managed_orbit(orbit_id).map_err(super::jobs::internal)?
|| state.db.restic_required(orbit_id).map_err(super::jobs::internal)?
{
return Err(StatusCode::FORBIDDEN);
}
Ok(())
}
async fn seal_upload(
state: &HubState,
session_id: Uuid,
@@ -715,6 +977,7 @@ async fn seal_upload(
restore_hints: serde_json::json!({ "session_id": session_id }),
};
let vault = state.vault.clone().read_owned().await;
reject_managed_orbit(state, orbit_id)?;
if vault
.outpost_repository_configured(orbit_id)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
@@ -776,3 +1039,142 @@ fn content_type(path: &str) -> &'static str {
"text/html"
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::{to_bytes, Body};
use axum::http::Request;
use tower::ServiceExt;
#[tokio::test]
async fn orbit_creation_validates_cron_and_direct_run_preserves_wormhole_status() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault").await.unwrap();
state.admin.token = None;
state.accept_plain_upload = true;
let app = router(state.clone());
let post = |path: &str, body: serde_json::Value| {
Request::post(path)
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json")
.header("x-tessera-upload-token", "fixture-token")
.body(Body::from(body.to_string()))
.unwrap()
};
for (provider, schedule, expected) in [
("filesystem", Some("bad cron"), StatusCode::BAD_REQUEST),
("postgres", None, StatusCode::BAD_REQUEST),
("filesystem", Some("0 2 * * *"), StatusCode::OK),
("wormhole", None, StatusCode::OK),
] {
let response = app.clone().oneshot(post("/api/v1/orbits", serde_json::json!({
"name": provider, "provider": provider, "provider_config": {}, "schedule": schedule
}))).await.unwrap();
assert_eq!(response.status(), expected);
}
let rows = state.db.list_orbits().await.unwrap();
assert_eq!(rows.len(), 2);
let orbit = rows.iter().find(|row| row.provider == "wormhole").unwrap();
let response = app.clone().oneshot(post(
&format!("/api/v1/orbits/{}/run", orbit.id), serde_json::Value::Null,
)).await.unwrap();
assert_eq!(response.status(), StatusCode::CONFLICT);
assert_eq!(state.db.list_orbits().await.unwrap()[1].last_status, "idle");
let outpost = Uuid::new_v4();
state.db.insert_wormhole_token("fixture-token", &outpost.to_string(), "fixture-code", "9999").unwrap();
state.db.claim_wormhole_code("fixture-code", "fixture", "2026").unwrap().unwrap();
{
let conn = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
conn.execute("UPDATE outposts SET last_seen = NULL", []).unwrap();
}
let response = app.oneshot(post("/api/v1/wormhole/upload/init", serde_json::json!({
"orbit_id": orbit.id, "total_bytes": 42
}))).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(state.db.list_outposts().unwrap()[0].last_seen.is_some());
}
#[tokio::test]
async fn new_orbits_validate_source_access_and_keep_provider_internal() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault").await.unwrap();
state.admin.token = None;
let app = router(state);
for (source, access, config, expected) in [
("filesystem", "hub", serde_json::json!({"paths": ["/data/source"]}), StatusCode::OK),
("filesystem", "hub", serde_json::json!({"paths": []}), StatusCode::BAD_REQUEST),
("filesystem", "outpost", serde_json::json!({}), StatusCode::OK),
("database", "outpost", serde_json::json!({}), StatusCode::OK),
("vm", "outpost", serde_json::json!({}), StatusCode::UNPROCESSABLE_ENTITY),
] {
let request = Request::post("/api/v1/orbits")
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(serde_json::json!({
"name": "test", "source": source, "access": access, "provider_config": config,
}).to_string())).unwrap();
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(response.status(), expected);
if expected == StatusCode::OK {
let body = axum::body::to_bytes(response.into_body(), 65536).await.unwrap();
let orbit: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(orbit["source"], source);
assert_eq!(orbit["access"], access);
assert!(orbit.get("provider_config").is_none());
}
}
}
#[tokio::test]
async fn orbit_responses_and_schema_hide_provider_config() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "test-vault")
.await
.unwrap();
state.admin.token = None;
let app = router(state.clone());
let input = serde_json::json!({
"name": "billing",
"provider": "postgres",
"provider_config": {
"connection_url": "postgres://user:synthetic-password@db/billing",
"token": "synthetic-token",
"secret_ref": "synthetic-reference",
}
});
let request = |method: &str, uri: &str, body: Body| {
Request::builder()
.method(method)
.uri(uri)
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json")
.body(body)
.unwrap()
};
for (method, path, body) in [
("POST", "/api/v1/orbits", Body::from(input.to_string())),
("GET", "/api/v1/orbits", Body::empty()),
("GET", "/api-doc/openapi.json", Body::empty()),
] {
let response = app.clone().oneshot(request(method, path, body)).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = to_bytes(response.into_body(), 100_000).await.unwrap();
let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let orbit = match path {
"/api-doc/openapi.json" => &json["components"]["schemas"]["OrbitResponse"]["properties"],
_ if method == "GET" => &json[0],
_ => &json,
};
assert!(orbit.get("id").is_some());
assert!(orbit.get("provider_config").is_none());
assert!(!String::from_utf8_lossy(&bytes).contains("synthetic-"));
}
let rows = state.db.list_orbits().await.unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&rows[0].provider_config).unwrap(),
input["provider_config"]
);
}
}

View File

@@ -0,0 +1,254 @@
use crate::admin::{tokens_match, SessionGate};
use crate::state::HubState;
use axum::{
extract::{ConnectInfo, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
#[derive(Serialize)]
struct Status {
login_enabled: bool,
authorized: bool,
actor: Option<String>,
csrf: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Login {
password: String,
}
pub(super) fn routes() -> Router<HubState> {
Router::new()
.route("/api/v1/operator/session", get(status).delete(logout))
.route("/api/v1/operator/login", post(login))
}
async fn status(
ConnectInfo(peer): ConnectInfo<SocketAddr>,
State(state): State<HubState>,
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());
(
no_store(),
Json(Status {
login_enabled: state.sessions.enabled(),
authorized,
actor: browser.as_ref().map(|session| session.actor.clone()),
csrf: browser.map(|session| session.csrf.to_string()),
}),
)
}
async fn login(
State(state): State<HubState>,
headers: HeaderMap,
Json(input): Json<Login>,
) -> Result<(HeaderMap, Json<Status>), StatusCode> {
if input.password.is_empty() || input.password.len() > 1024 {
return Err(StatusCode::UNAUTHORIZED);
}
let gate = state.sessions.clone();
let session = tokio::task::spawn_blocking(move || gate.login(&headers, &input.password))
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)??;
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()))?);
Ok((
headers,
Json(Status {
login_enabled: true,
authorized: true,
actor: Some(session.actor),
csrf: Some(session.csrf.to_string()),
}),
))
}
async fn logout(
State(state): State<HubState>,
headers: HeaderMap,
) -> Result<(StatusCode, HeaderMap), StatusCode> {
let session = state
.sessions
.active(&headers)
.ok_or(StatusCode::UNAUTHORIZED)?;
require_csrf(&headers, &session.csrf.to_string())?;
state.sessions.remove(session.id);
state
.db
.audit("operator.logout", &session.actor)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut headers = no_store();
headers.insert(header::SET_COOKIE, cookie(None)?);
Ok((StatusCode::NO_CONTENT, headers))
}
pub(super) fn require_csrf(headers: &HeaderMap, expected: &str) -> Result<(), StatusCode> {
if headers
.get("x-tessera-csrf")
.and_then(|value| value.to_str().ok())
.is_some_and(|value| tokens_match(expected, value))
{
Ok(())
} else {
Err(StatusCode::FORBIDDEN)
}
}
fn no_store() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
headers
}
fn cookie(id: Option<&str>) -> Result<HeaderValue, StatusCode> {
let value = format!(
"{}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
SessionGate::COOKIE,
id.unwrap_or_default(),
if id.is_some() {
SessionGate::DURATION.as_secs()
} else {
0
},
);
HeaderValue::from_str(&value).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::{to_bytes, Body};
use axum::http::Request;
use tower::ServiceExt;
#[tokio::test]
async fn operator_session_requires_csrf_and_expires_without_disabling_cli() {
let dir = tempfile::tempdir().unwrap();
let mut state = HubState::bootstrap(dir.path().to_str().unwrap(), "fixture-vault")
.await
.unwrap();
state.sessions = SessionGate::fixture();
state.admin.token = Some("fixture-api-token".into());
let app = crate::api::router(state.clone());
let request = |method: &str, uri: &str, body: &'static str| {
Request::builder()
.method(method)
.uri(uri)
.extension(ConnectInfo("127.0.0.1:1234".parse::<SocketAddr>().unwrap()))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body))
.unwrap()
};
let anonymous = app
.clone()
.oneshot(request("GET", "/api/v1/orbits", ""))
.await
.unwrap();
assert_eq!(anonymous.status(), StatusCode::UNAUTHORIZED);
let denied = app
.clone()
.oneshot(request(
"POST",
"/api/v1/operator/login",
r#"{"password":"wrong"}"#,
))
.await
.unwrap();
assert_eq!(denied.status(), StatusCode::UNAUTHORIZED);
let login = app
.clone()
.oneshot(request(
"POST",
"/api/v1/operator/login",
r#"{"password":"fixture-operator-password"}"#,
))
.await
.unwrap();
assert_eq!(login.status(), StatusCode::OK);
let set_cookie = login.headers()[header::SET_COOKIE].to_str().unwrap();
assert!(set_cookie.contains("HttpOnly; Secure; SameSite=Strict"));
let cookie = HeaderValue::from_str(set_cookie.split(';').next().unwrap()).unwrap();
let bytes = to_bytes(login.into_body(), 1024).await.unwrap();
let status: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(status["actor"], "fixture-operator");
let csrf = HeaderValue::from_str(status["csrf"].as_str().unwrap()).unwrap();
let mut action = request("POST", "/api/v1/wormhole/pairing", "");
action.headers_mut().insert(header::COOKIE, cookie.clone());
let denied = app.clone().oneshot(action).await.unwrap();
assert_eq!(denied.status(), StatusCode::FORBIDDEN);
let mut action = request("POST", "/api/v1/wormhole/pairing", "");
action.headers_mut().insert(header::COOKIE, cookie.clone());
action.headers_mut().insert("x-tessera-csrf", csrf.clone());
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::OK
);
let mut action = request("DELETE", "/api/v1/operator/session", "");
action.headers_mut().insert(header::COOKIE, cookie.clone());
action.headers_mut().insert("x-tessera-csrf", csrf);
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::NO_CONTENT
);
let mut action = request("GET", "/api/v1/orbits", "");
action.headers_mut().insert(header::COOKIE, cookie);
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
let login = app
.clone()
.oneshot(request(
"POST",
"/api/v1/operator/login",
r#"{"password":"fixture-operator-password"}"#,
))
.await
.unwrap();
let cookie = HeaderValue::from_str(
login.headers()[header::SET_COOKIE]
.to_str()
.unwrap()
.split(';')
.next()
.unwrap(),
)
.unwrap();
state.sessions.expire();
let mut action = request("GET", "/api/v1/orbits", "");
action.headers_mut().insert(header::COOKIE, cookie);
assert_eq!(
app.clone().oneshot(action).await.unwrap().status(),
StatusCode::UNAUTHORIZED
);
let mut cli = request("GET", "/api/v1/orbits", "");
cli.headers_mut().insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer fixture-api-token"),
);
assert_eq!(app.oneshot(cli).await.unwrap().status(), StatusCode::OK);
let connection = rusqlite::Connection::open(dir.path().join("tessera.db")).unwrap();
let audited: i64 = connection.query_row(
"SELECT COUNT(*) FROM audit_log WHERE event IN ('operator.login','operator.logout') AND detail = 'fixture-operator'",
[], |row| row.get(0),
).unwrap();
assert_eq!(audited, 3);
}
}

View File

@@ -1,8 +1,12 @@
mod jobs;
mod restore;
pub(crate) use restore::restore_target_mismatch;
use anyhow::Result;
use rusqlite::{params, Connection, OptionalExtension};
use std::path::Path;
use std::sync::{Arc, Mutex};
use tessera_core::decay::RetentionPolicy;
use tessera_core::{decay::RetentionPolicy, OutpostSummary};
use uuid::Uuid;
#[derive(Clone)]
@@ -10,7 +14,7 @@ pub struct Db {
conn: Arc<Mutex<Connection>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
#[derive(Clone)]
pub struct OrbitRow {
pub id: Uuid,
pub name: String,
@@ -18,7 +22,6 @@ pub struct OrbitRow {
pub provider_config: String,
pub schedule: Option<String>,
pub decay_preset: String,
#[serde(default)]
pub retention: Option<RetentionPolicy>,
pub dry_run: bool,
pub last_status: String,
@@ -91,12 +94,24 @@ 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'",
[],
)?;
jobs::migrate(&conn)?;
restore::migrate(&conn)?;
Ok(())
}
pub async fn list_orbits(&self) -> Result<Vec<OrbitRow>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status, retention FROM orbits ORDER BY name")?;
let mut stmt = conn.prepare("SELECT o.id, o.name, o.provider, o.provider_config, o.schedule, o.decay_preset, o.dry_run,
CASE WHEN p.application_id IS NULL THEN o.last_status ELSE COALESCE((
SELECT j.status FROM capture_jobs j WHERE j.application_id = p.application_id
ORDER BY j.created_at DESC, j.rowid DESC LIMIT 1
), 'idle') END, o.retention
FROM orbits o LEFT JOIN capture_profiles p ON p.orbit_id = o.id ORDER BY o.name")?;
let rows = stmt.query_map([], |r| {
Ok(OrbitRow {
id: Uuid::parse_str(&r.get::<_, String>(0)?).unwrap_or_else(|_| Uuid::new_v4()),
@@ -233,26 +248,48 @@ impl Db {
outpost_name: &str,
now: &str,
) -> Result<Option<(String, String)>> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"UPDATE wormhole_tokens SET state = 'active', outpost_name = ?2 WHERE code = ?1 AND state = 'code_shown' AND expires_at > ?3",
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],
)?;
if changed != 1 {
return Ok(None);
|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],
)?;
}
let mut stmt = conn.prepare(
"SELECT token, outpost_id FROM wormhole_tokens WHERE code = ?1 AND state = 'active'",
)?;
let mut rows = stmt.query(params![code])?;
let Some(row) = rows.next()? else {
return Ok(None);
};
Ok(Some((row.get(0)?, row.get(1)?)))
tx.commit()?;
Ok(claimed)
}
pub fn upload_token_active(&self, token: &str) -> Result<bool> {
Ok(self.upload_token_outpost(token)?.is_some())
pub fn list_outposts(&self) -> Result<Vec<OutpostSummary>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT id, name, last_seen, pairing_state FROM outposts ORDER BY name, id")?;
let rows = stmt.query_map([], |row| {
let id = Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| {
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
})?;
Ok(OutpostSummary { id, name: row.get(1)?, last_seen: row.get(2)?, pairing_state: row.get(3)? })
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn touch_outpost(&self, id: Uuid) -> Result<()> {
let now = chrono::Utc::now();
let recent = (now - chrono::Duration::seconds(30)).to_rfc3339();
self.conn.lock().unwrap().execute(
"UPDATE outposts SET last_seen = ?2 WHERE id = ?1 AND (last_seen IS NULL OR last_seen < ?3)",
params![id.to_string(), now.to_rfc3339(), recent],
)?;
Ok(())
}
pub fn upload_token_outpost(&self, token: &str) -> Result<Option<String>> {

View File

@@ -0,0 +1,693 @@
use super::*;
use rusqlite::{types::Type, Row, TransactionBehavior};
use tessera_core::job::{
CaptureEvent, CaptureJob, CaptureLease, CaptureProfile, CaptureProgress, CaptureReport,
CAPTURE_LEASE_SECONDS,
};
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS capture_profiles (
application_id TEXT PRIMARY KEY,
orbit_id TEXT NOT NULL UNIQUE,
outpost_id TEXT NOT NULL,
profile TEXT NOT NULL,
registered_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS capture_jobs (
id TEXT PRIMARY KEY,
application_id TEXT NOT NULL,
actor TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
phase TEXT NOT NULL DEFAULT 'queued',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
lease_id TEXT,
lease_until INTEGER,
snapshot_id TEXT,
schedule_slot INTEGER,
offsite_status TEXT,
offsite_attempt_at INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS capture_jobs_queue
ON capture_jobs(application_id, status, created_at);
CREATE INDEX IF NOT EXISTS capture_jobs_history
ON capture_jobs(application_id, created_at);
CREATE TABLE IF NOT EXISTS capture_events (
id INTEGER PRIMARY KEY, job_id TEXT NOT NULL, at INTEGER NOT NULL, phase TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS capture_events_job ON capture_events(job_id, id);
CREATE TRIGGER IF NOT EXISTS capture_events_queued AFTER INSERT ON capture_jobs
BEGIN
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
END;
CREATE TRIGGER IF NOT EXISTS capture_events_progress AFTER UPDATE OF phase ON capture_jobs
WHEN OLD.phase <> NEW.phase OR OLD.lease_id IS NOT NEW.lease_id
BEGIN
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
DELETE FROM capture_events WHERE job_id = NEW.id AND id < COALESCE((
SELECT id FROM capture_events WHERE job_id = NEW.id ORDER BY id DESC LIMIT 1 OFFSET 63
), 0);
END;",
)?;
ensure_column(
conn,
"capture_profiles",
"registered_at",
"INTEGER NOT NULL DEFAULT 0",
)?;
ensure_column(conn, "capture_jobs", "schedule_slot", "INTEGER")?;
ensure_column(conn, "capture_jobs", "offsite_status", "TEXT")?;
ensure_column(
conn,
"capture_jobs",
"offsite_attempt_at",
"INTEGER NOT NULL DEFAULT 0",
)?;
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS capture_jobs_slot ON capture_jobs(application_id, schedule_slot)",
[],
)?;
Ok(())
}
const JOB_VIEW: &str = "SELECT j.id, p.profile, j.actor, j.status, j.phase, j.created_at,
j.updated_at, j.snapshot_id, j.offsite_status FROM capture_jobs j JOIN capture_profiles p USING(application_id)";
pub(super) fn invalid_column(
index: usize,
error: impl std::error::Error + Send + Sync + 'static,
) -> rusqlite::Error {
rusqlite::Error::FromSqlConversionFailure(index, Type::Text, Box::new(error))
}
fn parse_profile(row: &Row<'_>, index: usize) -> rusqlite::Result<CaptureProfile> {
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn read_job(row: &Row<'_>) -> rusqlite::Result<CaptureJob> {
Ok(CaptureJob {
id: Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))?,
profile: parse_profile(row, 1)?,
actor: row.get(2)?,
status: row.get(3)?,
phase: row.get(4)?,
created_at: row.get(5)?,
updated_at: row.get(6)?,
snapshot_id: row
.get::<_, Option<String>>(7)?
.map(|value| Uuid::parse_str(&value))
.transpose()
.map_err(|err| invalid_column(7, err))?,
offsite_status: row.get(8)?,
})
}
impl Db {
pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"INSERT INTO capture_profiles (application_id, orbit_id, outpost_id, profile, registered_at)
SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (
SELECT 1 FROM orbits WHERE id = ?2 AND provider = 'wormhole' AND dry_run = 0
AND COALESCE(json_extract(provider_config, '$.source'), ?6) = ?6
)
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
ON CONFLICT DO NOTHING",
params![profile.application_id.to_string(), profile.orbit_id.to_string(),
profile.outpost_id.to_string(), serde_json::to_string(profile)?, now,
if profile.format.engine().is_some() { "database" } else { "filesystem" }],
)?;
Ok(changed == 1)
}
pub fn capture_profiles(&self) -> Result<Vec<CaptureProfile>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT profile FROM capture_profiles ORDER BY application_id")?;
let rows = stmt.query_map([], |row| parse_profile(row, 0))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT p.profile, COALESCE(MAX(j.schedule_slot), p.registered_at)
FROM capture_profiles p LEFT JOIN capture_jobs j USING(application_id)
GROUP BY p.application_id",
)?;
let rows = stmt.query_map([], |row| Ok((parse_profile(row, 0)?, row.get(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn enqueue_scheduled_capture(&self, application: Uuid, slot: i64, now: i64) -> Result<()> {
self.conn.lock().unwrap().execute(
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at, schedule_slot)
SELECT ?1, application_id, 'scheduler', ?4, ?4, ?3 FROM capture_profiles p
WHERE application_id = ?2
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')
ON CONFLICT(application_id, schedule_slot) DO NOTHING",
params![Uuid::new_v4().to_string(), application.to_string(), slot, now],
)?;
Ok(())
}
pub fn enqueue_capture(
&self,
application_id: Uuid,
actor: &str,
now: i64,
) -> Result<Option<CaptureJob>> {
let conn = self.conn.lock().unwrap();
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)
}
pub fn capture_jobs(
&self,
application: Option<Uuid>,
status: Option<&str>,
limit: u16,
) -> Result<Vec<CaptureJob>> {
let conn = self.conn.lock().unwrap();
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)
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
))?;
let rows = stmt.query_map(
params![application.map(|id| id.to_string()), status, limit],
read_job,
)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn capture_events(&self, job: Uuid) -> Result<Vec<CaptureEvent>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT at, phase FROM capture_events WHERE job_id = ?1 ORDER BY id")?;
let rows = stmt.query_map([job.to_string()], |row| {
Ok(CaptureEvent {
at: row.get(0)?,
phase: row.get(1)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn capture_job(&self, id: Uuid) -> Result<Option<CaptureJob>> {
capture_job(&self.conn.lock().unwrap(), id)
}
pub fn capture_profile_for_orbit(&self, orbit: Uuid) -> Result<Option<CaptureProfile>> {
Ok(self
.conn
.lock()
.unwrap()
.query_row(
"SELECT profile FROM capture_profiles WHERE orbit_id = ?1",
[orbit.to_string()],
|row| parse_profile(row, 0),
)
.optional()?)
}
pub fn managed_orbit(&self, orbit_id: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM capture_profiles WHERE orbit_id = ?1)",
[orbit_id.to_string()],
|row| row.get(0),
)?)
}
pub fn pending_offsite(&self) -> Result<Vec<Uuid>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT id FROM capture_jobs WHERE offsite_status IN ('pending', 'failed')
ORDER BY offsite_attempt_at, rowid LIMIT 10",
)?;
let rows = stmt.query_map([], |row| {
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn set_offsite_result(&self, job: Uuid, success: bool) -> Result<()> {
self.conn.lock().unwrap().execute(
"UPDATE capture_jobs SET offsite_status = ?2, offsite_attempt_at = ?3 WHERE id = ?1",
params![
job.to_string(),
if success { "copied" } else { "failed" },
chrono::Utc::now().timestamp()
],
)?;
Ok(())
}
pub fn offsite_pending(&self, id: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT EXISTS(SELECT 1 FROM capture_jobs WHERE snapshot_id = ?1 AND offsite_status IN ('pending', 'failed'))",
[id.to_string()], |row| row.get(0),
)?)
}
pub fn restic_required(&self, orbit: Uuid) -> Result<bool> {
Ok(self.conn.lock().unwrap().query_row(
"SELECT json_extract(provider_config, '$.source') IS NOT NULL FROM orbits WHERE id = ?1",
[orbit.to_string()], |row| row.get(0),
).optional()?.unwrap_or(false))
}
pub fn capture_upload(
&self,
outpost: Uuid,
id: Uuid,
lease: Uuid,
now: i64,
) -> Result<Option<CaptureJob>> {
capture_upload(&self.conn.lock().unwrap(), outpost, id, lease, now)
}
pub fn publish_capture(
&self,
outpost: Uuid,
id: Uuid,
lease: Uuid,
offsite_enabled: bool,
publish: impl FnOnce(&CaptureJob) -> Result<()>,
) -> Result<Option<(Uuid, bool)>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let now = chrono::Utc::now().timestamp();
let Some(job) = capture_upload(&tx, outpost, id, lease, now)? else {
return Ok(None);
};
if let Some(snapshot_id) = job.snapshot_id {
return Ok(Some((snapshot_id, false)));
}
publish(&job)?;
tx.execute(
"UPDATE capture_jobs SET status = 'completed', phase = 'completed', snapshot_id = ?1, updated_at = ?2, offsite_status = ?3
WHERE id = ?1",
params![id.to_string(), now, offsite_enabled.then_some("pending")],
)?;
tx.execute(
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.completed', ?1)",
[format!("actor={} job={id} snapshot={id}", job.actor)],
)?;
tx.commit()?;
Ok(Some((id, true)))
}
pub fn incomplete_publications(&self) -> Result<Vec<Uuid>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT id FROM capture_jobs WHERE status IN ('running', 'failed')")?;
let rows = stmt.query_map([], |row| {
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn reconcile_capture(
&self,
snapshot: Uuid,
orbit: Uuid,
offsite_enabled: bool,
) -> Result<()> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
let changed = tx.execute(
"UPDATE capture_jobs SET status = 'completed', phase = 'completed',
snapshot_id = id, updated_at = ?3, offsite_status = ?4
WHERE id = ?1 AND status <> 'completed' AND application_id IN (
SELECT application_id FROM capture_profiles WHERE orbit_id = ?2
)",
params![
snapshot.to_string(),
orbit.to_string(),
chrono::Utc::now().timestamp(),
offsite_enabled.then_some("pending")
],
)?;
if changed == 1 {
tx.execute(
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.reconciled', ?1)",
[format!("snapshot={snapshot}")],
)?;
}
tx.commit()?;
Ok(())
}
pub fn claim_capture(
&self,
outpost: Uuid,
application: Uuid,
now: i64,
) -> Result<Option<CaptureLease>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let candidate = tx.query_row(
"SELECT j.id, p.profile, json_extract(o.provider_config, '$.source') IS NOT NULL
FROM capture_jobs j JOIN capture_profiles p USING(application_id) JOIN orbits o ON o.id = p.orbit_id
WHERE p.outpost_id = ?1 AND p.application_id = ?2
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
AND NOT EXISTS (SELECT 1 FROM capture_jobs active WHERE active.application_id = j.application_id
AND active.status = 'running' AND active.lease_until > ?3)
AND NOT EXISTS (SELECT 1 FROM restore_jobs r JOIN restore_targets t ON t.id = r.target_id
WHERE t.application_id = j.application_id AND
(r.status IN ('applying','recovery_required') OR (r.status = 'running' AND r.lease_until > ?3)))
ORDER BY j.created_at, j.rowid LIMIT 1",
params![outpost.to_string(), application.to_string(), now],
|row| Ok((row.get::<_, String>(0)?, parse_profile(row, 1)?, row.get::<_, bool>(2)?)),
).optional()?;
let Some((id, profile, restic)) = candidate else {
return Ok(None);
};
let job_id = Uuid::parse_str(&id)?;
let lease_id = Uuid::new_v4();
tx.execute(
"UPDATE capture_jobs SET status = 'running', phase = 'claimed',
lease_id = ?2, lease_until = ?3, updated_at = ?4 WHERE id = ?1",
params![id, lease_id.to_string(), now + CAPTURE_LEASE_SECONDS, now],
)?;
tx.commit()?;
Ok(Some(CaptureLease {
job_id,
profile,
lease_id,
restic,
}))
}
pub fn report_capture(
&self,
outpost: Uuid,
job: Uuid,
report: CaptureReport,
now: i64,
) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let (phase, prior, status) = match report.progress {
CaptureProgress::Heartbeat => (None, None, "running"),
CaptureProgress::Dumping => (Some("dumping"), Some("claimed"), "running"),
CaptureProgress::Uploading => (Some("uploading"), Some("dumping"), "running"),
CaptureProgress::DumpFailed => (Some("dump_failed"), Some("dumping"), "failed"),
CaptureProgress::UploadFailed => (Some("upload_failed"), Some("uploading"), "failed"),
};
let changed = conn.execute(
"UPDATE capture_jobs SET status = ?6, phase = COALESCE(?5, phase), updated_at = ?4, lease_until = ?7
WHERE id = ?1 AND lease_id = ?2 AND status = 'running' AND lease_until > ?4
AND (?8 IS NULL OR phase = ?8 OR phase = ?5)
AND application_id IN (SELECT application_id FROM capture_profiles WHERE outpost_id = ?3)",
params![job.to_string(), report.lease_id.to_string(), outpost.to_string(), now,
phase, status, now + CAPTURE_LEASE_SECONDS, prior],
)?;
Ok(changed == 1)
}
}
fn capture_upload(
conn: &Connection,
outpost: Uuid,
id: Uuid,
lease: Uuid,
now: i64,
) -> Result<Option<CaptureJob>> {
Ok(conn.query_row(
&format!("{JOB_VIEW} WHERE j.id = ?1 AND p.outpost_id = ?2 AND j.lease_id = ?3
AND (j.status = 'completed' OR (j.status = 'running' AND j.phase = 'uploading' AND j.lease_until > ?4))"),
params![id.to_string(), outpost.to_string(), lease.to_string(), now],
read_job,
).optional()?)
}
fn capture_job(conn: &Connection, id: Uuid) -> Result<Option<CaptureJob>> {
Ok(conn
.query_row(
&format!("{JOB_VIEW} WHERE j.id = ?1"),
[id.to_string()],
read_job,
)
.optional()?)
}
#[cfg(test)]
mod tests {
use super::*;
use tessera_core::job::CaptureFormat;
async fn profile(db: &Db, outpost_id: Uuid) -> CaptureProfile {
let orbit_id = Uuid::new_v4();
db.upsert_orbit(&OrbitRow {
id: orbit_id,
name: "fixture".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
CaptureProfile {
application_id: Uuid::new_v4(),
orbit_id,
outpost_id,
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
}
}
#[tokio::test]
async fn queue_survives_restart_and_fences_competing_agents() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("old.db");
Connection::open(&path).unwrap().execute_batch(
"CREATE TABLE orbits (id TEXT PRIMARY KEY, name TEXT, provider TEXT, provider_config TEXT,
schedule TEXT, decay_preset TEXT, dry_run INTEGER, last_status TEXT);
INSERT INTO orbits VALUES ('20200000-0000-0000-0000-000000000000', 'old', 'postgres',
'{\"connection_url\":\"synthetic-secret\"}', NULL, 'week-of-dailies', 0, 'idle');"
).unwrap();
let outpost = Uuid::new_v4();
let other = Uuid::new_v4();
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let a = profile(&db, outpost).await;
let b = profile(&db, outpost).await;
let app = a.application_id;
assert!(!db.register_capture_profile(&a, 100).unwrap());
assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none());
for (id, token) in [(outpost, "token-a"), (other, "token-b")] {
db.insert_wormhole_token(token, &id.to_string(), token, "9999")
.unwrap();
db.claim_wormhole_code(token, "agent", "2026")
.unwrap()
.unwrap();
}
assert!(db.register_capture_profile(&a, 100).unwrap());
assert!(db.register_capture_profile(&b, 100).unwrap());
let queued = db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
db.enqueue_capture(b.application_id, "fixture", 100)
.unwrap()
.unwrap();
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
assert!(
db.list_orbits()
.await
.unwrap()
.iter()
.any(|orbit| orbit.name == "old"
&& orbit.provider_config.contains("synthetic-secret"))
);
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "queued");
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().actor, "fixture");
assert!(db.claim_capture(other, app, 100).unwrap().is_none());
let second = Db::connect(&path).await.unwrap();
let race = std::thread::scope(|scope| {
let first = scope.spawn(|| db.claim_capture(outpost, app, 100).unwrap());
let second = scope.spawn(|| second.claim_capture(outpost, app, 100).unwrap());
[first.join().unwrap(), second.join().unwrap()]
});
assert_eq!(race.iter().flatten().count(), 1);
let lease = race.into_iter().flatten().next().unwrap();
assert_eq!(lease.job_id, queued.id);
assert!(db
.claim_capture(outpost, b.application_id, 101)
.unwrap()
.is_some());
let report = |lease_id, progress| CaptureReport { lease_id, progress };
assert!(!db
.report_capture(
other,
queued.id,
report(lease.lease_id, CaptureProgress::Dumping),
101
)
.unwrap());
assert!(db
.report_capture(
outpost,
queued.id,
report(lease.lease_id, CaptureProgress::Dumping),
101
)
.unwrap());
drop(db);
let db = Db::connect(&path).await.unwrap();
let retry = db.claim_capture(outpost, app, 191).unwrap().unwrap();
assert_eq!(retry.job_id, queued.id);
assert_ne!(retry.lease_id, lease.lease_id);
assert!(!db
.report_capture(
outpost,
queued.id,
report(lease.lease_id, CaptureProgress::Heartbeat),
192
)
.unwrap());
assert!(db
.report_capture(
outpost,
queued.id,
report(retry.lease_id, CaptureProgress::Dumping),
192
)
.unwrap());
assert!(db
.report_capture(
outpost,
queued.id,
report(retry.lease_id, CaptureProgress::DumpFailed),
193
)
.unwrap());
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "failed");
assert!(db.claim_capture(outpost, app, 194).unwrap().is_some());
}
#[tokio::test]
async fn managed_orbit_uses_latest_job_even_after_a_success() {
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("token", &outpost.to_string(), "code", "9999").unwrap();
db.claim_wormhole_code("code", "agent", "2026").unwrap().unwrap();
let profile = profile(&db, outpost).await;
let app = profile.application_id;
let now = chrono::Utc::now().timestamp();
assert!(db.register_capture_profile(&profile, now).unwrap());
for (progress, expected) in [
(CaptureProgress::Uploading, "completed"),
(CaptureProgress::DumpFailed, "failed"),
] {
let job = db.enqueue_capture(app, "fixture", now).unwrap().unwrap();
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "queued");
let lease = db.claim_capture(outpost, app, now).unwrap().unwrap();
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running");
for progress in [CaptureProgress::Dumping, progress] {
assert!(db.report_capture(outpost, job.id, CaptureReport {
lease_id: lease.lease_id, progress,
}, now).unwrap());
}
if expected == "completed" {
assert!(db.publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(())).unwrap().is_some());
}
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, expected);
}
}
#[tokio::test]
async fn daily_slots_are_caught_up_once_and_offline_jobs_are_visible() {
use chrono::{TimeZone, Utc};
use tessera_core::job::CaptureSchedule;
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("jobs.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("test", &outpost.to_string(), "code", "9999")
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
let mut a = profile(&db, outpost).await;
let mut b = profile(&db, outpost).await;
a.schedule = Some(CaptureSchedule {
hour: 2,
minute: 0,
timezone: "Asia/Jakarta".into(),
});
b.schedule = a.schedule.clone();
let registered = Utc.with_ymd_and_hms(2026, 11, 7, 18, 0, 0).unwrap();
for p in [&a, &b] {
assert!(db
.register_capture_profile(p, registered.timestamp())
.unwrap());
}
let tick = crate::scheduler::tick_capture_schedules;
tick(&db, registered).unwrap();
assert!(db.capture_jobs(None, None, 100).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();
assert_eq!(all.len(), 4);
let history = db
.capture_jobs(Some(a.application_id), Some("queued"), 100)
.unwrap();
assert_eq!(history.len(), 2);
assert!(history.iter().all(|job| job.actor == "scheduler"));
let first = db
.claim_capture(outpost, a.application_id, now.timestamp())
.unwrap()
.unwrap();
for (progress, offset) in [
(CaptureProgress::Dumping, 1),
(CaptureProgress::Heartbeat, 2),
(CaptureProgress::DumpFailed, 3),
] {
assert!(db
.report_capture(
outpost,
first.job_id,
CaptureReport {
lease_id: first.lease_id,
progress
},
now.timestamp() + offset
)
.unwrap());
}
let failed = db
.capture_jobs(Some(a.application_id), Some("failed"), 100)
.unwrap();
assert_eq!(failed.len(), 1);
let events = db.capture_events(first.job_id).unwrap();
assert_eq!(
events
.iter()
.map(|event| event.phase.as_str())
.collect::<Vec<_>>(),
["queued", "claimed", "dumping", "dump_failed"]
);
}
}

View File

@@ -0,0 +1,560 @@
use super::{jobs::invalid_column, *};
use rusqlite::{Row, Transaction, TransactionBehavior};
use tessera_core::{
job::CAPTURE_LEASE_SECONDS,
restore::{RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreTarget},
};
pub(super) fn migrate(conn: &Connection) -> Result<()> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS restore_targets (
id TEXT PRIMARY KEY,
application_id TEXT NOT NULL,
outpost_id TEXT NOT NULL,
identity TEXT NOT NULL UNIQUE,
profile TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS restore_jobs (
id TEXT PRIMARY KEY,
snapshot_id TEXT NOT NULL,
target_id TEXT NOT NULL,
actor TEXT NOT NULL,
artifact TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued',
phase TEXT NOT NULL DEFAULT 'queued',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
lease_token TEXT,
lease_until INTEGER,
attempt_safety_id TEXT,
safety_id TEXT
);
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);",
)?;
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
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
Uuid::parse_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn json<T: serde::de::DeserializeOwned>(row: &Row<'_>, index: usize) -> rusqlite::Result<T> {
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
}
fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
Ok(RestoreJob {
id: uuid(row, 0)?,
snapshot_id: uuid(row, 1)?,
target: json(row, 2)?,
actor: row.get(3)?,
status: row.get(4)?,
phase: row.get(5)?,
safety_snapshot_id: row
.get::<_, Option<String>>(6)?
.map(|id| Uuid::parse_str(&id))
.transpose()
.map_err(|err| invalid_column(6, err))?,
created_at: row.get(7)?,
updated_at: row.get(8)?,
})
}
pub(crate) fn restore_target_mismatch(
target: &RestoreTarget,
artifact: &RestoreArtifact,
) -> Option<&'static str> {
if Some(target.engine) != artifact.format.engine() {
Some("Database engine differs from the snapshot")
} else if target.identity == artifact.identity {
Some("Target is the source database")
} else {
None
}
}
impl Db {
pub fn register_restore_target(&self, target: &RestoreTarget) -> Result<bool> {
let conn = self.conn.lock().unwrap();
let changed = conn.execute(
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
SELECT ?1, ?2, ?3, ?4, ?5
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
ON CONFLICT DO NOTHING",
params![
target.id.to_string(),
target.application_id.to_string(),
target.outpost_id.to_string(),
serde_json::to_string(&(target.engine, &target.identity))?,
serde_json::to_string(target)?,
],
)?;
Ok(changed == 1)
}
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
Ok(self.restore_targets_with_activity(application)?
.into_iter().map(|(target, _)| target).collect())
}
pub fn restore_targets_with_activity(&self, application: Uuid) -> Result<Vec<(RestoreTarget, bool)>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT t.profile, EXISTS (SELECT 1 FROM wormhole_tokens
WHERE outpost_id = t.outpost_id AND state = 'active')
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)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
pub fn enqueue_restore(
&self,
snapshot: Uuid,
application: Uuid,
target: Uuid,
actor: &str,
artifact: &RestoreArtifact,
now: i64,
) -> Result<Option<RestoreJob>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let 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,
)?;
tx.commit()?;
Ok(Some(job))
}
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
Ok(conn
.query_row(
&format!("{VIEW} WHERE j.id = ?1"),
[id.to_string()],
read_job,
)
.optional()?)
}
pub fn restore_history(&self, snapshot: Uuid, now: i64) -> Result<Vec<RestoreJob>> {
let conn = self.conn.lock().unwrap();
expire_destructive(&conn, now)?;
let mut stmt = conn.prepare(&format!(
"{VIEW} WHERE j.snapshot_id = ?1 ORDER BY j.rowid DESC LIMIT 25"
))?;
let rows = stmt.query_map([snapshot.to_string()], read_job)?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
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'))",
[id.to_string()], |row| row.get(0),
)?)
}
pub fn claim_restore(
&self,
outpost: Uuid,
target: Uuid,
now: i64,
) -> Result<Option<RestoreLease>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
expire_destructive(&tx, now)?;
let selected = tx.query_row(
&format!("{VIEW} WHERE t.id = ?1 AND t.outpost_id = ?2
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
AND NOT EXISTS (
SELECT 1 FROM restore_jobs active JOIN restore_targets owner ON owner.id = active.target_id
WHERE owner.application_id = t.application_id
AND (active.status IN ('applying','recovery_required')
OR (active.status = 'running' AND active.lease_until > ?3))
)
AND NOT EXISTS (
SELECT 1 FROM capture_jobs c WHERE c.application_id = t.application_id
AND c.status = 'running' AND c.lease_until > ?3
)
ORDER BY j.created_at, j.rowid LIMIT 1"),
params![target.to_string(), outpost.to_string(), now],
|row| Ok((read_job(row)?, json(row, 9)?)),
).optional()?;
let Some((mut job, artifact)) = selected else {
tx.commit()?;
return Ok(None);
};
let token = Uuid::new_v4();
tx.execute(
"UPDATE restore_jobs SET status = 'running', phase = 'claimed', lease_token = ?2, lease_until = ?3,
attempt_safety_id = ?4, safety_id = NULL, updated_at = ?5 WHERE id = ?1",
params![job.id.to_string(), token.to_string(), now + CAPTURE_LEASE_SECONDS,
Uuid::new_v4().to_string(), now],
)?;
job.status = "running".into();
job.phase = "claimed".into();
job.safety_snapshot_id = None;
job.updated_at = now;
tx.commit()?;
Ok(Some(RestoreLease {
job,
token,
artifact,
}))
}
pub fn restore_access(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
restore_access(&self.conn.lock().unwrap(), outpost, id, token, now)
}
pub fn record_safety(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
publish: impl FnOnce(Uuid) -> Result<()>,
) -> Result<Option<Uuid>> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, expected)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(None);
};
if job.status != "running" {
return Ok(None);
}
if let Some(safety) = job.safety_snapshot_id {
return Ok(Some(safety));
}
if job.phase != "safety" {
return Ok(None);
}
publish(expected)?;
tx.execute("UPDATE restore_jobs SET phase = 'ready', safety_id = ?2, updated_at = ?3 WHERE id = ?1",
params![id.to_string(), expected.to_string(), now])?;
audit(
&tx,
"restore.safety_committed",
&format!("job={id} snapshot={expected}"),
)?;
tx.commit()?;
Ok(Some(expected))
}
pub fn authorize_apply(&self, outpost: Uuid, id: Uuid, token: Uuid, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(false);
};
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
return Ok(false);
}
tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1",
params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
audit(
&tx,
"restore.apply_authorized",
&format!("job={id} target={}", job.target.id),
)?;
tx.commit()?;
Ok(true)
}
pub fn report_restore(
&self,
outpost: Uuid,
id: Uuid,
token: Uuid,
progress: RestoreProgress,
now: i64,
) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
return Ok(false);
};
let (status, phase) = match progress {
RestoreProgress::Heartbeat => (job.status.as_str(), job.phase.as_str()),
RestoreProgress::Checking if job.phase == "claimed" => ("running", "checking"),
RestoreProgress::Safety if job.phase == "checking" => ("running", "safety"),
RestoreProgress::InvalidPayload if job.phase == "checking" => {
("failed", "invalid_payload")
}
RestoreProgress::WrongTarget if job.phase == "checking" => ("failed", "wrong_target"),
RestoreProgress::SafetyFailed if matches!(job.phase.as_str(), "safety" | "ready") => {
("failed", "safety_failed")
}
RestoreProgress::Applied if job.status == "applying" => ("completed", "completed"),
RestoreProgress::ApplyFailed if job.status == "applying" => {
("recovery_required", "apply_failed")
}
_ => return Ok(false),
};
tx.execute("UPDATE restore_jobs SET status = ?2, phase = ?3, updated_at = ?4, lease_until = ?5 WHERE id = ?1",
params![id.to_string(), status, phase, now, now + CAPTURE_LEASE_SECONDS])?;
if !matches!(progress, RestoreProgress::Heartbeat) {
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
}
tx.commit()?;
Ok(true)
}
pub fn reconcile_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
expire_destructive(&tx, now)?;
let changed = tx.execute(
"UPDATE restore_jobs SET status = 'reconciled', phase = 'reconciled', updated_at = ?2
WHERE id = ?1 AND status = 'recovery_required'",
params![id.to_string(), now],
)?;
if changed == 1 {
audit(
&tx,
"restore.reconciled",
&format!("actor={actor} job={id}"),
)?;
}
tx.commit()?;
Ok(changed == 1)
}
pub fn cancel_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let changed = tx.execute(
"UPDATE restore_jobs SET status = 'cancelled', phase = 'cancelled', updated_at = ?2
WHERE id = ?1 AND status IN ('queued','running')",
params![id.to_string(), now],
)?;
if changed == 1 {
audit(&tx, "restore.cancelled", &format!("actor={actor} job={id}"))?;
}
tx.commit()?;
Ok(changed == 1)
}
}
fn restore_access(
conn: &Connection,
outpost: Uuid,
id: Uuid,
token: Uuid,
now: i64,
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
Ok(conn
.query_row(
&format!(
"{VIEW} WHERE j.id = ?1 AND t.outpost_id = ?2 AND j.lease_token = ?3
AND j.lease_until > ?4 AND j.status IN ('running', 'applying')"
),
params![id.to_string(), outpost.to_string(), token.to_string(), now],
|row| Ok((read_job(row)?, json(row, 9)?, uuid(row, 10)?)),
)
.optional()?)
}
fn expire_destructive(conn: &Connection, now: i64) -> Result<()> {
conn.execute(
"UPDATE restore_jobs SET status = 'recovery_required', phase = 'lease_lost', updated_at = ?1
WHERE status = 'applying' AND lease_until <= ?1",
[now],
)?;
Ok(())
}
fn audit(tx: &Transaction<'_>, event: &str, detail: &str) -> Result<()> {
tx.execute(
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), ?1, ?2)",
params![event, detail],
)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tessera_core::{
job::{CaptureFormat, CaptureProfile},
restore::{DatabaseIdentity, Engine},
};
#[tokio::test]
async fn expired_apply_survives_restart_and_fences_the_target_until_reconciled() {
let root = tempfile::tempdir().unwrap();
let path = root.path().join("restore.db");
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let outpost = Uuid::new_v4();
db.insert_wormhole_token("synthetic-token", &outpost.to_string(), "code", "9999")
.unwrap();
db.claim_wormhole_code("code", "fixture", "2026")
.unwrap()
.unwrap();
let orbit = Uuid::new_v4();
db.upsert_orbit(&OrbitRow {
id: orbit,
name: "fixture".into(),
provider: "wormhole".into(),
provider_config: "{}".into(),
schedule: None,
decay_preset: "week-of-dailies".into(),
retention: None,
dry_run: false,
last_status: "idle".into(),
})
.await
.unwrap();
let app = Uuid::new_v4();
assert!(db
.register_capture_profile(
&CaptureProfile {
application_id: app,
orbit_id: orbit,
outpost_id: outpost,
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
},
100
)
.unwrap());
let target = Uuid::new_v4();
assert!(db
.register_restore_target(&RestoreTarget {
id: target,
application_id: app,
outpost_id: outpost,
name: "target".into(),
engine: Engine::Postgres,
identity: DatabaseIdentity {
instance: "123".into(),
database: "target".into()
},
})
.unwrap());
let snapshot = Uuid::new_v4();
let artifact = RestoreArtifact {
format: CaptureFormat::PostgresCustom,
sha256: "0".repeat(64),
identity: DatabaseIdentity {
instance: "123".into(),
database: "source".into(),
},
};
let registered = db.restore_targets_with_activity(app).unwrap().pop().unwrap();
assert!(registered.1);
let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() };
assert_eq!(restore_target_mismatch(&registered.0, &same_source), Some("Target is the source database"));
assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none());
let job = db
.enqueue_restore(snapshot, app, target, "fixture", &artifact, 100)
.unwrap()
.unwrap();
let next_snapshot = Uuid::new_v4();
let next = db
.enqueue_restore(next_snapshot, app, target, "fixture", &artifact, 101)
.unwrap()
.unwrap();
let lease = db.claim_restore(outpost, target, 102).unwrap().unwrap();
assert_eq!(lease.job.id, job.id);
assert!(db.claim_restore(outpost, target, 103).unwrap().is_none());
assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 104)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104)
.unwrap());
assert!(db
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105)
.unwrap());
assert!(db
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
"synthetic write failure"
))
.is_err());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 107)
.unwrap());
let safety = db
.record_safety(outpost, job.id, lease.token, 108, |_| Ok(()))
.unwrap()
.unwrap();
assert!(db
.authorize_apply(outpost, job.id, lease.token, 109)
.unwrap());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, 110)
.unwrap());
drop(db);
let db = Db::connect(&path).await.unwrap();
db.migrate().await.unwrap();
let late = 109 + CAPTURE_LEASE_SECONDS;
assert!(db.claim_restore(outpost, target, late).unwrap().is_none());
assert!(db
.restore_access(outpost, job.id, lease.token, late)
.unwrap()
.is_none());
assert!(!db
.authorize_apply(outpost, job.id, lease.token, late)
.unwrap());
let interrupted = db.restore_job(job.id, late).unwrap().unwrap();
assert_eq!(interrupted.status, "recovery_required");
assert_eq!(interrupted.safety_snapshot_id, Some(safety));
assert!(db.snapshot_in_restore(snapshot).unwrap());
assert!(db.snapshot_in_restore(safety).unwrap());
assert!(db.reconcile_restore(job.id, "fixture", late + 1).unwrap());
assert!(!db.snapshot_in_restore(snapshot).unwrap());
assert!(!db.snapshot_in_restore(safety).unwrap());
let retry = db
.claim_restore(outpost, target, late + 2)
.unwrap()
.unwrap();
assert_eq!(retry.job.id, next.id);
assert_ne!(retry.token, lease.token);
}
}

View File

@@ -13,6 +13,9 @@ use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> Result<()> {
if std::env::args().nth(1).as_deref() == Some("--hash-operator-password") {
return admin::print_operator_hash();
}
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env().add_directive("tessera_hub=info".parse()?))
.init();
@@ -56,8 +59,15 @@ async fn main() -> Result<()> {
}
}
state.configure_offsite()?;
state.reconcile_capture_catalog().await?;
state.start_offsite_worker();
scheduler::start_orbit_scheduler(state.clone()).await?;
state.admin.log_policy();
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()? {
state.wormhole_mtls = true;

View File

@@ -1,46 +1,130 @@
use crate::state::HubState;
use anyhow::Result;
use anyhow::{Context, Result};
use chrono::{DateTime, NaiveTime, TimeZone, Utc};
use chrono_tz::Tz;
use cron::Schedule;
use std::str::FromStr;
use tessera_core::job::CaptureSchedule;
use tokio::time::{sleep, Duration};
use tracing::{error, info};
pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
let db = state.db.clone();
tokio::spawn(async move {
loop {
if let Err(e) = tick_schedules(state.clone()).await {
if let Err(e) = tick_capture_schedules(&db, Utc::now()) {
error!("capture scheduler tick: {e}");
}
sleep(Duration::from_secs(30)).await;
}
});
tokio::spawn(async move {
let mut previous = Utc::now();
loop {
let now = Utc::now();
if let Err(e) = tick_schedules(state.clone(), previous, now).await {
error!("scheduler tick: {e}");
}
previous = now;
sleep(Duration::from_secs(30)).await;
}
});
Ok(())
}
async fn tick_schedules(state: HubState) -> Result<()> {
pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> {
if expression.split_whitespace().count() == 5 {
Schedule::from_str(&format!("0 {expression}"))
} else {
Schedule::from_str(expression)
}
}
async fn tick_schedules(
state: HubState,
previous: DateTime<Utc>,
now: DateTime<Utc>,
) -> Result<()> {
let orbits = state.db.list_orbits().await?;
let now = chrono::Utc::now();
for orbit in orbits {
let Some(cron_expr) = orbit.schedule.as_ref() else {
if orbit.provider == "wormhole" {
continue;
}
let Some(cron_expr) = orbit
.schedule
.as_deref()
.filter(|expr| !expr.trim().is_empty())
else {
continue;
};
let schedule = match Schedule::from_str(cron_expr) {
let schedule = match orbit_schedule(cron_expr) {
Ok(s) => s,
Err(e) => {
error!("bad cron on orbit {}: {e}", orbit.name);
continue;
}
};
let upcoming = schedule.upcoming(chrono::Utc).take(1).collect::<Vec<_>>();
if let Some(next) = upcoming.first() {
let delta = (*next - now).num_seconds().abs();
if delta < 35 {
info!("scheduler firing orbit {}", orbit.name);
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit.id).await {
error!("orbit {} failed: {e}", orbit.name);
}
if schedule
.after(&previous)
.next()
.is_some_and(|slot| slot <= now)
{
info!("scheduler firing orbit {}", orbit.name);
let orbit_id = orbit.id;
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit).await {
error!("orbit {orbit_id} failed: {e}");
}
}
}
Ok(())
}
pub fn capture_schedule(schedule: &CaptureSchedule) -> Option<(NaiveTime, Tz)> {
let time = NaiveTime::from_hms_opt(u32::from(schedule.hour), u32::from(schedule.minute), 0)?;
Some((time, schedule.timezone.parse().ok()?))
}
pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime<Utc>) -> Result<()> {
for (profile, cursor) in db.capture_schedule_cursors()? {
let Some(schedule) = &profile.schedule else {
continue;
};
let (time, tz) = capture_schedule(schedule).context("invalid stored capture schedule")?;
let start = DateTime::from_timestamp(cursor, 0).context("invalid schedule cursor")?;
let end = now.with_timezone(&tz).date_naive();
let mut date = start.with_timezone(&tz).date_naive();
for _ in 0..32 {
if date > end {
break;
}
if let Some(slot) = tz.from_local_datetime(&date.and_time(time)).earliest() {
if slot.timestamp() > cursor && slot <= now {
db.enqueue_scheduled_capture(
profile.application_id,
slot.timestamp(),
now.timestamp(),
)?;
}
}
date = date.succ_opt().context("schedule date overflow")?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();
let slot = Utc.with_ymd_and_hms(2026, 11, 10, 2, 0, 0).unwrap();
for expression in ["0 2 * * *", "0 0 2 * * *"] {
let schedule = orbit_schedule(expression).unwrap();
assert_eq!(schedule.after(&before).next(), Some(slot));
assert!(schedule.after(&slot).next().unwrap() > slot);
}
assert!(orbit_schedule("60 2 * * *").is_err());
}
}

View File

@@ -1,23 +1,45 @@
use crate::admin::AdminGate;
use crate::admin::{AdminGate, SessionGate};
use crate::db::Db;
use anyhow::Result;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use tessera_core::reconstitute::ReconstituteSession;
use tessera_store::Vault;
use tessera_core::decay::{
evaluate_capture_retention, evaluate_gfs, CaptureRetention, RetentionPolicy, SnapshotRef,
};
use tessera_core::job::CaptureProfile;
use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState};
use tessera_store::{Offsite, Vault};
use tokio::sync::{Mutex, RwLock};
use uuid::Uuid;
pub(crate) enum ManagedRetention {
Orbit(RetentionPolicy),
Profile(CaptureRetention),
Default(CaptureRetention),
}
impl ManagedRetention {
pub(crate) fn resolve(profile: &CaptureProfile, orbit: Option<RetentionPolicy>) -> Self {
match (profile.retention, orbit) {
(Some(policy), _) => Self::Profile(policy),
(None, Some(policy)) => Self::Orbit(policy),
(None, None) => Self::Default(CaptureRetention::default()),
}
}
}
#[derive(Clone)]
pub struct HubState {
pub db: Db,
pub data_dir: PathBuf,
pub vault_passphrase: String,
pub offsite: Option<Arc<Offsite>>,
pub vault: Arc<RwLock<Vault>>,
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
pub admin: AdminGate,
pub sessions: SessionGate,
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.
@@ -42,26 +64,197 @@ impl HubState {
Ok(Self {
db,
data_dir,
vault_passphrase: vault_pass.to_string(),
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()?,
wormhole_mtls: false,
accept_plain_upload: true,
})
}
pub fn upload_token_valid(&self, token: &str) -> bool {
self.db.upload_token_active(token).unwrap_or(false)
pub fn configure_offsite(&mut self) -> Result<()> {
let Some(repository) = std::env::var_os("TESSERA_OFFSITE_REPOSITORY") else {
return Ok(());
};
let repository = repository
.to_str()
.ok_or_else(|| anyhow::anyhow!("off-site repository must be UTF-8"))?;
let password = std::env::var_os("TESSERA_OFFSITE_PASSWORD_FILE").ok_or_else(|| {
anyhow::anyhow!("TESSERA_OFFSITE_PASSWORD_FILE is required for off-site copies")
})?;
self.offsite = Some(Arc::new(Offsite::new(
repository,
std::path::Path::new(&password),
)?));
Ok(())
}
pub async fn reconcile_capture_catalog(&self) -> Result<()> {
let vault = self.vault.clone().read_owned().await;
let db = self.db.clone();
let offsite_enabled = self.offsite.is_some();
tokio::task::spawn_blocking(move || {
for id in db.incomplete_publications()? {
let Some(snap) = vault.get_snapshot(id)? else {
continue;
};
if snap
.manifest
.restore_hints
.get("job_id")
.and_then(|id| id.as_str())
.and_then(|id| Uuid::parse_str(id).ok())
== Some(snap.id)
{
let offsite = offsite_enabled && snap.manifest.restore_hints["format"] != "tar";
db.reconcile_capture(snap.id, snap.manifest.orbit_id, offsite)?;
}
}
Ok(())
})
.await?
}
pub fn start_offsite_worker(&self) {
let Some(offsite) = self.offsite.clone() else {
return;
};
let state = self.clone();
tokio::spawn(async move {
loop {
match state.db.pending_offsite() {
Ok(jobs) => {
for id in jobs {
let offsite = offsite.clone();
let prepared = state.vault.read().await.prepare_offsite_copy(id);
let success = match prepared {
Ok(copy) => offsite.copy_capture(copy).await.is_ok(),
Err(_) => false,
};
if !success {
tracing::warn!(%id, "off-site capture copy failed");
}
if state.db.set_offsite_result(id, success).is_err() {
tracing::warn!(%id, "could not save off-site copy status");
}
}
}
Err(_) => tracing::warn!("could not read off-site copy queue"),
}
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
}
});
}
pub async fn export_snapshot(&self, snapshot: Uuid, dest: PathBuf) -> Result<u64> {
let vault = self.vault.clone().read_owned().await;
let local_dest = dest.clone();
let (local, published) = tokio::task::spawn_blocking(move || {
(
vault.restore_snapshot(snapshot, &local_dest),
vault.has_published_snapshot(snapshot),
)
})
.await?;
if local.is_err() && published? {
if let Some(offsite) = &self.offsite {
return offsite.restore(snapshot, &dest).await;
}
}
local
}
pub async fn active_exports(&self) -> HashSet<Uuid> {
self.reconstitute_sessions
.read()
.await
.values()
.filter_map(|session| {
matches!(
session.state,
ReconstituteState::Countdown
| ReconstituteState::Confirming
| ReconstituteState::Restoring
)
.then_some(session.snapshot_id)
})
.collect()
}
pub async fn prune_orbit(&self, orbit_id: Uuid) -> Result<Vec<Uuid>> {
let mut vault = self.vault.clone().write_owned().await;
let (preset, retention) = self.db.orbit_retention(orbit_id)?;
let profile = self.db.capture_profile_for_orbit(orbit_id)?;
let active_exports = self.active_exports().await;
let db = self.db.clone();
tokio::task::spawn_blocking(move || {
vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref())
let Some(profile) = profile else {
return vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref());
};
let snapshots = vault
.list_snapshots()?
.into_iter()
.filter(|snapshot| snapshot.manifest.orbit_id == orbit_id)
.map(|snapshot| SnapshotRef {
id: snapshot.id,
taken_at: snapshot.taken_at,
})
.collect();
let expired = match ManagedRetention::resolve(&profile, retention) {
ManagedRetention::Orbit(policy) => evaluate_gfs(&policy, snapshots),
ManagedRetention::Profile(policy) | ManagedRetention::Default(policy) => {
evaluate_capture_retention(policy, snapshots, chrono::Utc::now())
}
};
let mut deletable = Vec::new();
for id in expired {
if !active_exports.contains(&id) && !db.offsite_pending(id)? && !db.snapshot_in_restore(id)? {
deletable.push(id);
}
}
vault.forget(&deletable)?;
Ok(deletable)
})
.await?
}
}
#[cfg(test)]
mod tests {
use super::*;
use tessera_core::job::CaptureFormat;
#[test]
fn managed_retention_prefers_profile_then_orbit_then_default() {
let mut profile = CaptureProfile {
application_id: Uuid::nil(),
orbit_id: Uuid::nil(),
outpost_id: Uuid::nil(),
format: CaptureFormat::PostgresCustom,
schedule: None,
retention: None,
};
let orbit = RetentionPolicy {
keep_daily: 3,
keep_weekly: 0,
keep_monthly: 0,
keep_yearly: 0,
};
assert!(matches!(
ManagedRetention::resolve(&profile, None),
ManagedRetention::Default(CaptureRetention::Age { days: 14 })
));
assert!(matches!(
ManagedRetention::resolve(&profile, Some(orbit)),
ManagedRetention::Orbit(policy) if policy == orbit
));
profile.retention = Some(CaptureRetention::Count { keep: 5 });
assert!(matches!(
ManagedRetention::resolve(&profile, Some(orbit)),
ManagedRetention::Profile(CaptureRetention::Count { keep: 5 })
));
}
}

View File

@@ -12,4 +12,7 @@ serde.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["process", "fs"] }
tracing.workspace = true
tempfile.workspace = true
regex = "1"
uuid.workspace = true
walkdir.workspace = true

View File

@@ -1,8 +1,16 @@
mod filesystem;
mod mysql;
mod mysql_restore;
mod postgres;
mod postgres_restore;
mod ssh;
pub use filesystem::*;
pub use mysql::MysqlSource;
pub use mysql_restore::MysqlRestore;
pub use postgres::*;
pub use postgres_restore::{PostgresReset, PostgresRestore};
pub use ssh::SshEndpoint;
use anyhow::Result;
use async_trait::async_trait;

View File

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

View File

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

View File

@@ -1,13 +1,13 @@
use super::{BackupProvider, CaptureResult};
use super::{ssh::loopback_listener, BackupProvider, CaptureResult, SshEndpoint};
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;
use std::fs::{self, OpenOptions};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::process::Stdio;
use tessera_core::config::ProviderKind;
use tessera_core::{config::ProviderKind, restore::DatabaseIdentity};
use tokio::process::Command;
#[derive(Debug, Clone, Deserialize)]
@@ -25,7 +25,6 @@ pub struct PostgresProvider {
config: PostgresConfig,
}
#[derive(Debug)]
struct PgTarget {
host: String,
port: String,
@@ -34,19 +33,118 @@ struct PgTarget {
dbname: String,
}
struct PgpassFile {
path: PathBuf,
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PostgresSource {
pub host: String,
#[serde(default = "default_port")]
pub port: u16,
pub database: String,
pub user: String,
pub password_file: PathBuf,
#[serde(default)]
pub tls: PostgresTls,
pub bastion: Option<SshEndpoint>,
}
impl Drop for PgpassFile {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
fn default_port() -> u16 {
5432
}
#[derive(Default, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum PostgresTls {
#[default]
VerifyFull,
VerifyFullWithCa {
ca_file: PathBuf,
},
Require,
Disable,
}
impl PostgresSource {
pub async fn dump_to(&self, file: fs::File, format: &str) -> Result<()> {
self.dump_archive(file, format, false).await
}
pub async fn safety_dump_to(&self, file: fs::File) -> Result<()> {
self.dump_archive(file, "custom", true).await
}
async fn dump_archive(&self, file: fs::File, format: &str, preserve_permissions: bool) -> Result<()> {
let mut args = dump_args(format)?;
if !preserve_permissions {
args.extend(["--no-owner".into(), "--no-acl".into()]);
}
self.run(
"pg_dump",
&args,
None,
Stdio::null(),
Stdio::from(file.try_clone()?),
)
.await?;
anyhow::ensure!(file.metadata()?.len() > 0, "pg_dump produced an empty file");
Ok(())
}
pub async fn identity(&self) -> Result<DatabaseIdentity> {
let args = ["-X", "-w", "-At", "-v", "ON_ERROR_STOP=1", "-c",
"SELECT json_build_object('instance', system_identifier::text, 'database', pg_catalog.current_database()) FROM pg_catalog.pg_control_system()"];
let args = args.map(String::from);
let output = self
.run("psql", &args, None, Stdio::null(), Stdio::piped())
.await?;
serde_json::from_slice(&output.stdout).context("invalid PostgreSQL identity")
}
pub(crate) async fn run(
&self,
program: &str,
args: &[String],
database: Option<&str>,
stdin: Stdio,
stdout: Stdio,
) -> Result<std::process::Output> {
let password =
fs::read_to_string(&self.password_file).context("read PostgreSQL password file")?;
let mut target = PgTarget {
host: self.host.clone(),
port: self.port.to_string(),
dbname: database.unwrap_or(&self.database).to_owned(),
user: self.user.clone(),
password: password.trim_end_matches(['\r', '\n']).to_owned(),
};
anyhow::ensure!(
!target.host.contains(',') && self.port != 0,
"invalid PostgreSQL endpoint"
);
let spec = PgProcess {
program,
args,
stdin,
stdout,
};
if let Some(bastion) = &self.bastion {
let listener = loopback_listener().await?;
target.port = listener.local_addr()?.port().to_string();
let forwarding = bastion.forward(listener, &self.host, self.port);
tokio::select! {
result = run_pg(&target, spec, Some((&self.tls, true))) => result,
result = forwarding => { result?; anyhow::bail!("SSH forwarding stopped"); }
}
} else {
run_pg(&target, spec, Some((&self.tls, false))).await
}
}
}
impl PostgresProvider {
pub fn from_config(config: &serde_json::Value) -> Result<Self> {
let config: PostgresConfig = serde_json::from_value(config.clone())?;
parse_postgres_url(&config.connection_url)?;
dump_args(&config.format)?;
Ok(Self { config })
}
@@ -59,30 +157,17 @@ impl PostgresProvider {
async fn dump(&self, stdout: Stdio) -> Result<std::process::Output> {
let target = parse_postgres_url(&self.config.connection_url)?;
let args = dump_args(&self.config.format)?;
let pgpass = write_pgpass(&target)?;
let mut cmd = Command::new("pg_dump");
let output = cmd
.args(args)
.env("PGPASSFILE", &pgpass.path)
.env("PGHOST", &target.host)
.env("PGPORT", &target.port)
.env("PGUSER", &target.user)
.env("PGDATABASE", &target.dbname)
.env_remove("PGPASSWORD")
.stdout(stdout)
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.context("pg_dump failed to start")?
.wait_with_output()
.await
.context("waiting for pg_dump")?;
anyhow::ensure!(
output.status.success(),
"pg_dump failed: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok(output)
run_pg(
&target,
PgProcess {
program: "pg_dump",
args: &args,
stdin: Stdio::null(),
stdout,
},
None,
)
.await
}
fn restore_hints(&self) -> serde_json::Value {
@@ -121,11 +206,15 @@ fn parse_postgres_url(url: &str) -> Result<PgTarget> {
.strip_prefix("postgres://")
.or_else(|| url.strip_prefix("postgresql://"))
.context("postgres connection_url must start with postgres:// or postgresql://")?;
let (userinfo, hostpart) = rest.split_once('@').context("connection url is missing userinfo")?;
let (userinfo, hostpart) = rest
.split_once('@')
.context("connection url is missing userinfo")?;
let (user, password) = userinfo
.split_once(':')
.context("connection url is missing a password")?;
let (hostport, dbpath) = hostpart.split_once('/').context("connection url is missing a database")?;
let (hostport, dbpath) = hostpart
.split_once('/')
.context("connection url is missing a database")?;
let dbname = dbpath.split('?').next().unwrap_or(dbpath);
let (host, port) = if let Some(host) = hostport.strip_prefix('[') {
let (host, port) = host
@@ -153,42 +242,89 @@ fn escape_pgpass(value: &str) -> String {
value.replace('\\', "\\\\").replace(':', "\\:")
}
fn write_pgpass(target: &PgTarget) -> Result<PgpassFile> {
let path = std::env::temp_dir().join(format!(
"tessera-pgpass-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.context("create pgpass file")?;
restrict_secret_file(&path)?;
let line = format!(
"{}:{}:{}:{}:{}\n",
escape_pgpass(&target.host),
escape_pgpass(&target.port),
escape_pgpass(&target.dbname),
escape_pgpass(&target.user),
escape_pgpass(&target.password)
);
file.write_all(line.as_bytes())?;
Ok(PgpassFile { path })
struct PgProcess<'a> {
program: &'a str,
args: &'a [String],
stdin: Stdio,
stdout: Stdio,
}
fn restrict_secret_file(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
async fn run_pg(
target: &PgTarget,
process: PgProcess<'_>,
tls: Option<(&PostgresTls, bool)>,
) -> Result<std::process::Output> {
let pgpass = write_pgpass(target, tls.is_some())?;
let mut cmd = Command::new(process.program);
if let Some((tls, forwarded)) = tls {
// Local profiles explicitly control the libpq endpoint and TLS policy.
for (name, _) in std::env::vars_os() {
if name.to_string_lossy().starts_with("PG") {
cmd.env_remove(name);
}
}
if forwarded {
cmd.env("PGHOSTADDR", "127.0.0.1");
}
let mode = match tls {
PostgresTls::VerifyFull => "verify-full",
PostgresTls::VerifyFullWithCa { ca_file } => {
cmd.env("PGSSLROOTCERT", ca_file);
"verify-full"
}
PostgresTls::Require => "require",
PostgresTls::Disable => "disable",
};
cmd.env("PGSSLMODE", mode).env("PGGSSENCMODE", "disable");
}
#[cfg(not(unix))]
let _ = path;
Ok(())
let output = cmd
.args(process.args)
.env("PGPASSFILE", pgpass.path())
.env("PGHOST", &target.host)
.env("PGPORT", &target.port)
.env("PGUSER", &target.user)
.env("PGDATABASE", &target.dbname)
.env_remove("PGPASSWORD")
.stdin(process.stdin)
.stdout(process.stdout)
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.context("starting PostgreSQL client")?
.wait_with_output()
.await
.context("waiting for PostgreSQL client")?;
anyhow::ensure!(
output.status.success(),
"{} failed ({})",
process.program,
output.status
);
Ok(output)
}
fn write_pgpass(target: &PgTarget, any_database: bool) -> Result<tempfile::NamedTempFile> {
let fields = [
&target.host,
&target.port,
&target.dbname,
&target.user,
&target.password,
];
anyhow::ensure!(
fields
.iter()
.all(|field| !field.is_empty() && !field.contains(['\n', '\r', '\0'])),
"invalid PostgreSQL connection field"
);
let mut file = tempfile::NamedTempFile::new().context("create pgpass file")?;
let mut fields = fields.map(|value| escape_pgpass(value));
if any_database {
fields[2] = "*".into();
}
let line = fields.join(":");
writeln!(file, "{line}")?;
Ok(file)
}
fn dump_args(format: &str) -> Result<Vec<String>> {
@@ -222,14 +358,17 @@ mod tests {
#[test]
fn pg_dump_keeps_the_url_out_of_argv() {
let target = parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap();
let target =
parse_postgres_url("postgres://migrator:s%3Acret@db.internal:5433/billing").unwrap();
assert_eq!(target.password, "s:cret");
let args = dump_args("custom").unwrap();
let pgpass = write_pgpass(&target).unwrap();
let rendered = fs::read_to_string(&pgpass.path).unwrap();
let pgpass = write_pgpass(&target, false).unwrap();
let rendered = fs::read_to_string(pgpass.path()).unwrap();
assert!(rendered.contains("s\\:cret"));
assert!(!args.iter().any(|arg| arg.contains("s:cret") || arg.contains("postgres://")));
let mode = fs::metadata(&pgpass.path).unwrap().permissions().mode() & 0o777;
assert!(!args
.iter()
.any(|arg| arg.contains("s:cret") || arg.contains("postgres://")));
let mode = fs::metadata(pgpass.path()).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let joined = args.join(" ");
assert!(!joined.contains(&target.password));

View File

@@ -0,0 +1,265 @@
use crate::PostgresSource;
use anyhow::{ensure, Context, Result};
use serde::Deserialize;
use std::{
fs::{self, File},
io::{self, BufRead, BufReader, Read, Seek, SeekFrom, Write},
path::PathBuf,
process::Stdio,
};
use tessera_core::{
job::CaptureFormat,
restore::{DatabaseIdentity, Engine},
};
use tokio::process::Command;
#[derive(Deserialize)]
#[serde(tag = "reset", rename_all = "snake_case", deny_unknown_fields)]
pub enum PostgresReset {
Schema {
#[serde(default = "public")]
schema: String,
},
RecreateDatabase,
}
fn public() -> String {
"public".into()
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PostgresRestore {
pub connection: PostgresSource,
pub mode: PostgresReset,
pub post_restore_sql: Option<PathBuf>,
#[serde(default)]
pub omit_transaction_timeout: bool,
#[serde(default)]
pub omit_pg_stat_statements: bool,
}
impl PostgresRestore {
pub async fn prepare(
&self,
mut dump: File,
format: CaptureFormat,
expected: &DatabaseIdentity,
) -> Result<File> {
ensure!(
expected.valid(Engine::Postgres) && expected.database == self.connection.database,
"PostgreSQL target identity does not match the local profile"
);
ensure!(
!matches!(
expected.database.as_str(),
"postgres" | "template0" | "template1"
),
"system database restore is forbidden"
);
let help = Command::new("psql")
.arg("--help=commands")
.kill_on_drop(true)
.output()
.await?;
ensure!(
help.status.success()
&& help
.stdout
.windows(b"\\restrict".len())
.any(|word| word == b"\\restrict"),
"PostgreSQL restore requires a psql client with restricted mode"
);
dump.seek(SeekFrom::Start(0))?;
let mut data = match format {
CaptureFormat::PostgresCustom => {
convert(
dump,
"pg_restore",
&["--no-owner", "--no-privileges", "--file=-"],
)
.await?
}
CaptureFormat::PostgresSql => {
let mut signature = [0; 2];
dump.read_exact(&mut signature)?;
dump.seek(SeekFrom::Start(0))?;
if signature == [0x1f, 0x8b] {
convert(dump, "gzip", &["-dc"]).await?
} else {
dump
}
}
_ => anyhow::bail!("invalid PostgreSQL dump format"),
};
data.seek(SeekFrom::Start(0))?;
let mut script = tempfile::tempfile()?;
writeln!(script, "SET standard_conforming_strings = on;")?;
let instance = literal(&expected.instance);
let database = literal(&expected.database);
match &self.mode {
PostgresReset::Schema { schema } => {
ensure!(
!schema.is_empty()
&& schema.len() <= 63
&& !schema.chars().any(char::is_control)
&& schema != "information_schema"
&& !schema.starts_with("pg_"),
"invalid target schema"
);
writeln!(script, "BEGIN;")?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(
script,
"DROP SCHEMA IF EXISTS {} CASCADE;",
identifier(schema)
)?;
if schema == "public" {
writeln!(script, "CREATE SCHEMA public;")?;
}
}
PostgresReset::RecreateDatabase => {
ensure!(
expected
.database
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'),
"recreate mode requires an alphanumeric database identifier"
);
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND EXISTS (SELECT 1 FROM pg_catalog.pg_database WHERE datname = {database}))::int) FROM pg_catalog.pg_control_system();")?;
let name = identifier(&expected.database);
writeln!(
script,
"DROP DATABASE {name};\nCREATE DATABASE {name};\n\\connect {}",
expected.database
)?;
writeln!(script, "SELECT 1 / ((system_identifier::text = {instance} AND pg_catalog.current_database() = {database})::int) FROM pg_catalog.pg_control_system();")?;
writeln!(script, "BEGIN;")?;
}
}
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 post_sql = self.post_restore_sql.clone();
tokio::task::spawn_blocking(move || {
append_dump(
data,
&mut script,
skip_timeout,
skip_extension,
create_public,
)?;
if let Some(path) = post_sql {
io::copy(
&mut fs::File::open(path).context("read local post-restore SQL")?,
&mut script,
)?;
}
writeln!(script, "\nCOMMIT;\n\\unrestrict {key}")?;
script.seek(SeekFrom::Start(0))?;
Ok(script)
})
.await?
}
pub async fn apply(&self, script: File) -> Result<()> {
let database = match self.mode {
PostgresReset::RecreateDatabase => Some("postgres"),
PostgresReset::Schema { .. } => None,
};
let args = ["-X", "-w", "-q", "-v", "ON_ERROR_STOP=1", "-f", "-"].map(String::from);
self.connection
.run("psql", &args, database, Stdio::from(script), Stdio::null())
.await?;
Ok(())
}
}
fn literal(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
fn identifier(value: &str) -> String {
format!("\"{}\"", value.replace('"', "\"\""))
}
async fn convert(input: File, executable: &str, args: &[&str]) -> Result<File> {
let file = tempfile::tempfile()?;
let status = Command::new(executable)
.args(args)
.stdin(Stdio::from(input))
.stdout(Stdio::from(file.try_clone()?))
.stderr(Stdio::null())
.kill_on_drop(true)
.status()
.await
.context("prepare PostgreSQL restore script")?;
ensure!(
status.success(),
"{executable} rejected the restore archive"
);
ensure!(
file.metadata()?.len() > 0,
"empty PostgreSQL restore script"
);
Ok(file)
}
fn append_dump(
data: File,
script: &mut File,
skip_timeout: bool,
skip_extension: bool,
create_public: bool,
) -> Result<()> {
let mut input = BufReader::new(data);
let mut header = true;
let mut extension_statement = false;
let mut copy_data = false;
let mut line = Vec::new();
while input.read_until(b'\n', &mut line)? > 0 {
let text = line.strip_suffix(b"\n").unwrap_or(&line);
if copy_data {
script.write_all(&line)?;
copy_data = text != b"\\.";
line.clear();
continue;
}
if text.starts_with(b"-- Name: ") {
extension_statement = skip_extension
&& (text.starts_with(b"-- Name: pg_stat_statements; Type: EXTENSION;")
|| text.starts_with(b"-- Name: EXTENSION pg_stat_statements; Type: COMMENT;"));
header = false;
}
// Tessera installs its own restricted-mode key. Archive-generated keys are redundant.
let own_restriction = [b"\\restrict ".as_slice(), b"\\unrestrict ".as_slice()]
.iter()
.any(|prefix| {
text.strip_prefix(*prefix)
.is_some_and(|key| !key.is_empty() && key.iter().all(u8::is_ascii_alphanumeric))
});
let extension = extension_statement
&& (text
.starts_with(b"CREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA ")
|| text.starts_with(b"COMMENT ON EXTENSION pg_stat_statements IS "));
if !text.is_empty() && !text.starts_with(b"--") {
extension_statement = false;
}
if !(own_restriction
|| extension
|| header && skip_timeout && text == b"SET transaction_timeout = 0;")
{
if create_public && text == b"CREATE SCHEMA public;" {
writeln!(script, "CREATE SCHEMA IF NOT EXISTS public;")?;
} else {
script.write_all(&line)?;
}
}
copy_data = text.starts_with(b"COPY ") && text.ends_with(b" FROM stdin;");
line.clear();
}
Ok(())
}

View File

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

View File

@@ -8,7 +8,9 @@
mod crypto;
mod index;
mod offsite;
mod restic;
mod vault;
pub use offsite::{Offsite, OffsiteCopy};
pub use vault::*;

View File

@@ -0,0 +1,170 @@
use crate::restic;
use anyhow::{ensure, Context, Result};
use std::{
fs,
io::Write,
path::{Path, PathBuf},
process::{Output, Stdio},
time::Duration,
};
use tokio::process::Command;
use uuid::Uuid;
pub struct Offsite {
repo: restic::Repository,
}
pub struct OffsiteCopy {
pub(crate) snapshot: Uuid,
pub(crate) source: restic::Repository,
pub(crate) restic_id: String,
}
impl Offsite {
pub fn new(repository: &str, password_file: &Path) -> Result<Self> {
let location = repository
.strip_prefix("s3:https://")
.or_else(|| {
repository
.strip_prefix("s3:http://")
.filter(|rest| rest.starts_with("127.0.0.1:"))
})
.context("off-site repository requires an S3 HTTPS endpoint")?;
let parts: Vec<_> = location.splitn(3, '/').collect();
ensure!(
parts.len() == 3
&& parts.iter().all(|part| !part.is_empty())
&& !repository.contains(['@', '?', '#', '\n', '\r']),
"use a dedicated S3 bucket prefix without embedded credentials"
);
let password =
fs::read_to_string(password_file).context("read off-site Restic password")?;
let password = password.trim_end_matches(['\r', '\n']);
ensure!(!password.is_empty(), "off-site Restic password is empty");
Ok(Self {
repo: restic::Repository {
path: PathBuf::from(repository),
password: password.into(),
},
})
}
fn command(&self) -> Command {
let mut command = Command::from(self.repo.command());
command
.args(["-o", "s3.retries=1", "--stuck-request-timeout=15s"])
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true);
command
}
async fn copy_from(&self, source: &restic::Repository, id: &str) -> Result<()> {
restic::validate_id(id)?;
let mut password = tempfile::NamedTempFile::new()?;
writeln!(password, "{}", source.password)?;
let probe = run(self.command().args(["snapshots", "--json"]), 10).await?;
if probe.status.code() == Some(10) {
safe(run(self.command().arg("init"), 30).await?, "init")?;
} else {
safe(probe, "probe")?;
}
safe(
run(
self.command()
.env_remove("RESTIC_FROM_PASSWORD")
.env_remove("RESTIC_FROM_PASSWORD_COMMAND")
.env_remove("RESTIC_FROM_REPOSITORY_FILE")
.env_remove("RESTIC_FROM_KEY_HINT")
.arg("copy")
.arg("--from-repo")
.arg(&source.path)
.arg("--from-password-file")
.arg(password.path())
.arg(id),
3600,
)
.await?,
"copy",
)?;
Ok(())
}
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 mut snapshots: Vec<Copy> = serde_json::from_slice(&output.stdout)?;
Ok(snapshots.pop().map(|copy| copy.id))
}
pub async fn restore(&self, snapshot: Uuid, dest: &Path) -> Result<u64> {
let id = self
.tagged_snapshot(snapshot)
.await?
.context("snapshot not found in off-site repository")?;
restic::validate_id(&id)?;
let parent = dest
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent)?;
let file = tempfile::NamedTempFile::new_in(parent)?;
safe(
run(
self.command()
.args(["dump", &id, restic::PAYLOAD])
.stdout(Stdio::from(file.reopen()?)),
3600,
)
.await?,
"dump",
)?;
let size = file.as_file().metadata()?.len();
file.as_file().sync_all()?;
file.persist(dest)?;
Ok(size)
}
pub async fn copy_capture(&self, copy: OffsiteCopy) -> Result<()> {
self.copy_from(&copy.source, &copy.restic_id).await?;
ensure!(
self.tagged_snapshot(copy.snapshot).await?.is_some(),
"off-site snapshot tag not found after copy"
);
Ok(())
}
}
async fn run(command: &mut Command, seconds: u64) -> Result<Output> {
let result = tokio::time::timeout(
Duration::from_secs(seconds),
command.spawn()?.wait_with_output(),
)
.await
.context("off-site Restic operation timed out")??;
Ok(result)
}
fn safe(output: Output, step: &str) -> Result<Output> {
ensure!(
output.status.success(),
"off-site Restic {step} failed ({})",
output.status
);
Ok(output)
}

View File

@@ -8,6 +8,11 @@ pub(crate) const PREFIX: &str = "restic:";
pub(crate) const OUTPOST_PREFIX: &str = "restic-outpost:";
pub(crate) const PAYLOAD: &str = "/payload";
pub(crate) fn tessera_tag(snapshot: uuid::Uuid) -> String {
format!("tessera-{snapshot}")
}
#[derive(Clone)]
pub(crate) struct Repository {
pub path: PathBuf,
pub password: String,
@@ -25,6 +30,10 @@ pub(crate) struct Summary {
struct Snapshot {
id: String,
summary: Option<Summary>,
#[serde(default)]
tags: Vec<String>,
#[serde(default)]
paths: Vec<String>,
}
impl Repository {
@@ -109,7 +118,12 @@ impl Repository {
Ok(())
}
pub fn snapshot_summary(&self, id: &str) -> Result<Summary> {
pub fn snapshot_summary(
&self,
id: &str,
tag: Option<&str>,
expected_path: Option<&str>,
) -> Result<Summary> {
validate_id(id)?;
let output = checked(
self.command().args(["snapshots", "--json", id]).output()?,
@@ -118,7 +132,11 @@ impl Repository {
let snapshots: Vec<Snapshot> = serde_json::from_slice(&output.stdout)?;
snapshots
.into_iter()
.find(|snap| snap.id == id)
.find(|snap| {
snap.id == id
&& tag.is_none_or(|tag| snap.tags.iter().any(|value| value == tag))
&& expected_path.is_none_or(|path| snap.paths == [path])
})
.and_then(|snap| snap.summary)
.context("outpost snapshot or backup summary is missing")
}

View File

@@ -148,7 +148,7 @@ impl Vault {
return Ok(Some((id, false)));
}
let repo = self.outpost_repository(manifest.orbit_id, config);
let summary = repo.snapshot_summary(restic_id)?;
let summary = repo.snapshot_summary(restic_id, None, None)?;
manifest.snapshot_id = id;
manifest.restore_hints = serde_json::json!({ "format": "tar" });
self.write_snapshot(
@@ -166,6 +166,29 @@ impl Vault {
Ok(Some((id, true)))
}
pub fn prepare_outpost_capture(
&self,
manifest: SnapshotManifest,
outpost_id: Uuid,
restic_id: &str,
) -> Result<StoredSnapshot> {
let config = self.outpost_config(manifest.orbit_id)?;
anyhow::ensure!(config.outpost_id == outpost_id, "repository belongs to another outpost");
let repo = self.outpost_repository(manifest.orbit_id, config);
let id = manifest.snapshot_id;
let expected_path = (manifest.provider != "filesystem").then_some(restic::PAYLOAD);
let summary = repo.snapshot_summary(restic_id, Some(&restic::tessera_tag(id)), expected_path)?;
Ok(StoredSnapshot {
id,
taken_at: Utc::now(),
manifest,
size_bytes: summary.total_bytes_processed,
tree_root: format!("{}{restic_id}", restic::OUTPOST_PREFIX),
stored_bytes: Some(summary.data_added_packed),
new_data_chunks: Some(summary.data_blobs),
})
}
pub fn snapshot_files(
&self,
mut manifest: SnapshotManifest,
@@ -209,7 +232,7 @@ impl Vault {
manifest.restore_hints = serde_json::json!({ "format": "tar" });
let exclude = restic::literal_pattern(&vault)?;
self.restic_snapshot(manifest, dry_run, |cmd| {
cmd.args(["--force", "--exclude", &exclude]);
cmd.args(["--exclude", &exclude]);
if let Some(max) = max_file_bytes {
cmd.arg("--exclude-larger-than").arg(max.to_string());
}
@@ -218,6 +241,19 @@ impl Vault {
}
pub fn snapshot_payload(
&self,
manifest: SnapshotManifest,
payload: File,
dry_run: bool,
) -> Result<StoredSnapshot> {
let snap = self.prepare_payload(manifest, payload, dry_run)?;
if !dry_run {
self.publish_prepared(&snap)?;
}
Ok(snap)
}
pub fn prepare_payload(
&self,
manifest: SnapshotManifest,
mut payload: File,
@@ -227,13 +263,13 @@ impl Vault {
// Restic rejects empty stdin. A relative filename keeps the same restore path.
let temp = tempfile::tempdir()?;
File::create(temp.path().join("payload"))?;
return self.restic_snapshot(manifest, dry_run, |cmd| {
return self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
cmd.current_dir(temp.path())
.args(["--force", "--", "payload"]);
});
}
payload.seek(SeekFrom::Start(0))?;
self.restic_snapshot(manifest, dry_run, |cmd| {
self.prepare_restic_snapshot(manifest, dry_run, |cmd| {
cmd.args(["--stdin", "--stdin-filename", restic::PAYLOAD])
.stdin(Stdio::from(payload));
})
@@ -244,6 +280,19 @@ impl Vault {
manifest: SnapshotManifest,
dry_run: bool,
source: impl FnOnce(&mut Command),
) -> Result<StoredSnapshot> {
let snap = self.prepare_restic_snapshot(manifest, dry_run, source)?;
if !dry_run {
self.publish_prepared(&snap)?;
}
Ok(snap)
}
fn prepare_restic_snapshot(
&self,
manifest: SnapshotManifest,
dry_run: bool,
source: impl FnOnce(&mut Command),
) -> Result<StoredSnapshot> {
let taken_at = Utc::now();
let temp;
@@ -261,7 +310,7 @@ impl Vault {
repo.init()
.context("opening the deduplicated vault (restic must be on PATH)")?;
let mut cmd = repo.command();
cmd.args(["backup", "--json", "--quiet"]);
cmd.args(["backup", "--json", "--quiet", "--tag", &restic::tessera_tag(manifest.snapshot_id)]);
if dry_run {
cmd.arg("--dry-run");
}
@@ -286,12 +335,79 @@ impl Vault {
stored_bytes: Some(summary.data_added_packed),
new_data_chunks: Some(summary.data_blobs),
};
if !dry_run {
self.write_snapshot(&snap, false)?;
}
Ok(snap)
}
pub fn import_legacy_payload(
&self, manifest: SnapshotManifest, payload: File, taken_at: chrono::DateTime<Utc>,
) -> Result<bool> {
let id = manifest.snapshot_id;
let receipts = self.root.join("keys/legacy-imports");
fs::create_dir_all(&receipts)?;
restrict_dir(&receipts)?;
let receipt = receipts.join(id.to_string());
if receipt.try_exists()? {
return Ok(false);
}
let snapshots = self.root.join("snapshots");
let already_imported = || -> Result<bool> {
Ok(self.has_published_snapshot(id)? || snapshots.join(format!("{id}.expired")).try_exists()?)
};
let imported = if already_imported()? {
false
} else {
let mut prepared = self.prepare_payload(manifest, payload, false)?;
prepared.taken_at = taken_at;
match self.publish_prepared(&prepared) {
Ok(()) => true,
Err(_) if already_imported()? => {
self.discard_prepared(&prepared)?;
false
}
Err(error) => return Err(error),
}
};
let marker = tempfile::NamedTempFile::new_in(&receipts)?;
marker.as_file().sync_all()?;
match marker.persist_noclobber(&receipt) {
Ok(_) => sync_directory(&receipts)?,
Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => (),
Err(error) => return Err(error.into()),
}
Ok(imported)
}
pub fn legacy_import_exists(&self, id: Uuid) -> Result<bool> {
Ok(self.root.join("keys/legacy-imports").join(id.to_string()).try_exists()?)
}
pub fn verify_prepared_payload(&self, snap: &StoredSnapshot, expected: &[u8; 32]) -> Result<()> {
use sha2::{Digest, Sha256};
let id = snap.tree_root.strip_prefix(restic::PREFIX).context("prepared payload is missing")?;
let mut file = tempfile::tempfile()?;
self.restic.dump(id, restic::PAYLOAD, file.try_clone()?)?;
file.seek(SeekFrom::Start(0))?;
let mut digest = Sha256::new();
std::io::copy(&mut file, &mut digest)?;
anyhow::ensure!(digest.finalize()[..] == expected[..], "stored payload checksum mismatch");
Ok(())
}
pub fn publish_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
self.write_snapshot(snap, false)
}
pub fn discard_prepared(&self, snap: &StoredSnapshot) -> Result<()> {
if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
self.restic.forget(&[id.to_owned()])?;
}
Ok(())
}
pub fn has_published_snapshot(&self, id: Uuid) -> Result<bool> {
Ok(self.root.join("snapshots").join(format!("{id}.json.enc")).try_exists()?)
}
fn index_path(&self) -> PathBuf {
self.root.join("index/tessera-main.json")
}
@@ -435,13 +551,30 @@ impl Vault {
Ok(out)
}
pub fn prepare_offsite_copy(&self, id: Uuid) -> Result<crate::OffsiteCopy> {
let snapshot = self.read_snapshot_file(&self.root.join("snapshots").join(format!("{id}.json.enc")))?;
anyhow::ensure!(snapshot.manifest.restore_hints.get("job_id").is_some(), "snapshot is not a capture job");
let (source, restic_id) = if let Some(id) = snapshot.tree_root.strip_prefix(restic::OUTPOST_PREFIX) {
let orbit = snapshot.manifest.orbit_id;
(self.outpost_repository(orbit, self.outpost_config(orbit)?), id)
} else {
(self.restic.clone(), snapshot.tree_root.strip_prefix(restic::PREFIX).context("capture Restic snapshot missing")?)
};
Ok(crate::OffsiteCopy { snapshot: id, source, restic_id: restic_id.to_owned() })
}
pub fn get_snapshot(&self, id: Uuid) -> Result<Option<StoredSnapshot>> {
for suffix in [".json.enc", ".json"] {
let path = self.root.join("snapshots").join(format!("{id}{suffix}"));
if path.try_exists()? {
return self.read_snapshot_file(&path).map(Some);
}
}
Ok(None)
}
pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result<u64> {
let enc = self.root.join("snapshots").join(format!("{id}.json.enc"));
let plain = self.root.join("snapshots").join(format!("{id}.json"));
let path = if enc.exists() { enc } else { plain };
let snap = self
.read_snapshot_file(&path)
.context("snapshot metadata")?;
let snap = self.get_snapshot(id)?.context("snapshot metadata not found")?;
let parent = dest
.parent()
.filter(|p| !p.as_os_str().is_empty())
@@ -450,8 +583,9 @@ 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 };
self.outpost_repository(orbit_id, self.outpost_config(orbit_id)?)
.dump(id, "/", temp.reopen()?)?;
.dump(id, path, temp.reopen()?)?;
} else if let Some(id) = snap.tree_root.strip_prefix(restic::PREFIX) {
let path = if snap.manifest.provider == "filesystem" {
"/"
@@ -548,7 +682,9 @@ 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())
self.prune_snapshots(preset, None, snaps.into_iter()
.filter(|snapshot| snapshot.manifest.provider != "legacy-history"
&& snapshot.manifest.restore_hints.get("job_id").is_none()))
}
pub fn prune_orbit_with_decay(

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

@@ -0,0 +1,150 @@
# 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
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.
## 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.
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.
## 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.

50
docs/MBU-BACKUP-PARITY.md Normal file
View File

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

56
docs/MBU-CUTOVER.md Normal file
View File

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

View File

@@ -4,14 +4,15 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep
## Viewport and consoles
- **Flowing** animates the projected orbits and the black hole's accretion disk. Pause or resume from the map toolbar. The map eases to a stop before showing labels and moons in **Locked** mode. Selecting an orbit also locks the map. Reduced motion locks it immediately.
- **Flowing** animates the projected orbits and the black hole's accretion disk. Pause or resume from the map toolbar. The map coasts to a visual stop, then reveals labels and moons in **Locked** mode, starting with the selected orbit. Resuming reverses that reveal. Selecting an orbit also locks the map. Reduced motion locks it immediately.
- Select a star or use the orbit register. The register prioritizes failed and active jobs and supports the up/down arrow keys. The inspector includes the capture action and full snapshot history.
- 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. Failures and rehearsals show text feedback.
- 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.
- 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 browser can show it in native fullscreen. Use **Exit big screen** or Escape to return to the workspace.
- **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.
## Data and rendering
@@ -22,10 +23,12 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep
## Animation guideline
- Use the installed Framer Motion API from `motion/react`. Declarative `motion` components inherit the physics spring from `MotionConfig` in `web/src/main.tsx`. Imperative animations share `uiSpring` from `web/src/lib/motion.ts`. Tune stiffness, damping, and mass for the interaction.
- Use the installed Framer Motion API from `motion/react`. Declarative `motion` components inherit the physics spring from `MotionConfig` in `web/src/main.tsx`. Use `uiSpring` for direct controls, `gentleSpring` for reveal and layout travel, and `ambientSpring` for scene effects. The tokens in `web/src/lib/motion.ts` define stiffness, damping, mass, and rest thresholds.
- Keep the element, its React key, and its MotionValues stable while a target can change. Update the scalar `animate` target, call `animate(value, nextTarget, uiSpring)` on the same MotionValue, or call `.set(nextTarget)` on a `useSpring` value. Motion automatically replaces the active animation and inherits the live value and velocity. Leave `from`, `velocity`, and fixed timing options unset for these retargets. For colors and other compound styles, spring a numeric mix amount or progress value and derive the visual property from it.
- Keep `AnimatePresence` mounted and use a stable child key so a reopening element can reverse its exit. Make an exiting overlay inert and release its hit area immediately. Track direct manipulation one-to-one and seed the spring with release velocity when handing control over from an external gesture.
- Keep CSS state changes immediate. Use Motion springs for visual transitions, including hover and loading feedback. Reserve repeating springs for ambient indicators and give them a static state under reduced motion. For continuous simulation, keep the path on its existing clock and spring its speed or progress. A new event can start a distinct path at its own origin.
- 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.
- Measure the destination frame on a mode change or resize. Spring the map's center and size from its current visual rectangle, and recompute the collision layout once the frame settles.
- Honor live changes to `prefers-reduced-motion`. The app applies declarative targets immediately. Imperative effects must stop and jump to the appropriate static state themselves. Verify reversals before settling, the final target, and reduced motion in a browser.
## Local verification
@@ -45,4 +48,11 @@ cargo build --locked -p tessera-hub
To preview a populated scene, start the hub with `TESSERA_SEED_DEMO=1` and a fresh temporary `TESSERA_DATA_DIR`. Open the vault and select an orbit with snapshots to review the locked layout.
The optional `web/scripts/capture-galaxy.mjs` screenshot helper uses a local Playwright and Chromium installation. It captures Flowing and Locked into the system temporary directory by default.
The optional `web/scripts/capture-galaxy.mjs` helper uses a local Playwright and Chromium installation. It saves Flowing and Locked screenshots in the system temporary directory by default. To exercise 55 orbits and simulated successful and failed captures against a running web build, use the browser fixture. It measures median and p95 frame intervals with Chromium CPU throttling and checks reversal, capture feedback, resizing, and reduced motion.
```sh
TESSERA_GALAXY_FIXTURE=1 CPU_THROTTLE=4 FRAME_P95_MAX_MS=33.4 \
TESSERA_URL=http://127.0.0.1:5173 node web/scripts/capture-galaxy.mjs
```
Set `VIEWPORT_WIDTH=3840 VIEWPORT_HEIGHT=2160` for a 4K viewport. Set `VERIFY_ANIMATION=0` to record a fixture baseline on older builds. If Playwright or Chromium is installed outside the web workspace, point `PLAYWRIGHT_MODULE` and `CHROMIUM_PATH` at those installations.

47
tasks/plan.md Normal file
View File

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

36
tasks/search-plan.md Normal file
View File

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

71
tasks/search-todo.md Normal file
View File

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

472
tasks/todo.md Normal file
View File

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

37
tests/mbu/README.md Normal file
View File

@@ -0,0 +1,37 @@
# MBU backup fixtures
Use a clean development host with Restic, PostgreSQL client/server tools, MySQL client tools, OpenSSL, OpenSSH, Docker, AWS CLI, Node.js and Python 3.9+. The SSH fixture uses a temporary loopback `sshd` and generated keys. Some Linux hosts require the distro's SSH privilege separation directory to exist before a non-root fixture can start.
```sh
rtk proxy npm --prefix web run build
rtk cargo build --workspace
rtk cargo test --workspace
rtk cargo test -p tessera-store -- --ignored
rtk proxy python3 tests/mbu/restic-orbits.py
rtk proxy python3 tests/mbu/capture-postgres.py
rtk proxy python3 tests/mbu/capture-mysql.py
rtk proxy python3 tests/mbu/restore-postgres.py
rtk proxy python3 tests/mbu/offsite.py
rtk proxy python3 tests/mbu/browser.py
rtk proxy python3 tests/mbu/legacy-import.py
rtk proxy python3 tests/mbu/matrix.py
```
- Restic orbits requires `rest-server` and `htpasswd` on PATH. It checks the four source/access combinations with a TLS Rest Server, re-runs after small changes, and verifies filesystem and PostgreSQL restores. Add `--mysql` to include MySQL capture and restore through both access modes.
- PostgreSQL covers direct TLS, verified PostgreSQL TLS through a pinned bastion, a mismatched hostname, a wrong host key, partial upload, a competing outpost, retry after a dropped reply, and a real restore to a second database.
- MySQL starts `mysql:9.2` by default. Use the matching `mysqldump` on PATH. Set `TESSERA_FIXTURE_MYSQL_IMAGE` to test a different server with a compatible client. The fixture covers direct and SSH capture, host-key failure, an engine error, and restore of data with a view, routine, and event.
- S3 starts `motoserver/moto:5.1.12` on loopback. It checks failed copy, retry, and export with the primary Restic repository offline.
- The browser test uses Playwright from Node's resolution path or `TESSERA_PLAYWRIGHT_MODULE` and its bundled Chromium or `TESSERA_FIXTURE_CHROME`. The fixture submits backup and restore jobs as an operator, exercises a capture-only profile, and verifies recovery status, the safety ID, and filesystem export. A fixture outpost handles the scoped job protocol.
- PostgreSQL restore verifies target identity, scoped payload access, checksum rejection, safety pinning, schema and recreate modes, a PostgreSQL 17 dump restored to PostgreSQL 14, restricted psql commands, and restart after reset. The fixture uses the PostgreSQL 14 host tools and the postgres:17 container for the newer source.
- The legacy import fixture reads compressed SQL archives from S3, restores synthetic samples, and verifies history access and idempotency after local GC.
- The matrix pairs three outposts, runs ten application profiles against isolated databases, exercises a scheduler tick for 02.00 WIB, and checks manual capture, scheduled capture, registered restore targets, and S3 copies. Its JSON output records durations, freshness, size and restore results.
## Placement inventory and fixture mapping
Read-only Teleport inventory on 10 November 2026 showed `odoo-clone`, `production-FTA`, `fta-prod`, `broiler-production`, `broiler-staging` and `mbu-backup-jumphost`. Database inventory reported the Broiler resource `mbu-production` with the MySQL protocol. MAS and FTA had no matching database resource in the approved inventory. The returned metadata had no server-version labels. The approved Machine ID could list resources, but the attempted `devops` OS login returned `unknown user devops` on `odoo-clone`, `production-FTA`, `broiler-production`, and `mbu-backup-jumphost`. Verification of deployed client/server versions, routes and privileges requires an authorized existing OS login on the applicable nodes.
| Case | Fixture | Placement to validate |
| --- | --- | --- |
| MAS and FTA | PostgreSQL TLS behind a loopback SSH bastion, wrong host key case | Run near the database if there is direct access. Otherwise use a pinned SSH forward to the database and validate the PostgreSQL server hostname. |
| Boiler | MySQL behind a pinned SSH login, wrong host key and engine-error cases | Use the matched MySQL client on the SSH host and a private client options file. |

115
tests/mbu/browser.mjs Normal file
View File

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

108
tests/mbu/browser.py Normal file
View File

@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Run the operator UI against a fixture outpost that commits a small SQL archive."""
from contextlib import ExitStack
from hashlib import sha256
from pathlib import Path
from subprocess import Popen
from tempfile import TemporaryDirectory
from uuid import uuid4
import base64
import json
import sqlite3
import tarfile
from fixture import BIN, command, pair, register_capture, start_hub, stop, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-browser-")))
password = "fixture-browser-password"
digest = command(BIN / "tessera-hub", "--hash-operator-password",
input=password + "\n", text=True, capture_output=True).stdout.strip()
api, url, _, _ = start_hub(cleanup, root, {
"TESSERA_OPERATOR_PASSWORD_HASH": digest,
"TESSERA_OPERATOR_NAME": "fixture-browser",
})
agent = pair(api, "Browser fixture outpost")
app = register_capture(api, agent["outpost_id"], "Browser fixture database", "mysql_sql")
capture_only_app = register_capture(api, agent["outpost_id"], "Browser capture-only", "mysql_sql")
token = agent["upload_token"]
server_id = str(uuid4())
target = str(uuid4())
api("restore-targets", {
"id": target, "application_id": app, "outpost_id": agent["outpost_id"],
"name": "Browser staging target", "engine": "mysql",
"identity": {"instance": server_id, "database": "staging"},
}, expected=201)
identity = base64.urlsafe_b64encode(json.dumps({"instance": server_id, "database": "source"}).encode()).decode().rstrip("=")
payload = b"CREATE TABLE browser_fixture(value integer);\nINSERT INTO browser_fixture VALUES (42);\n"
def commit_capture(lease):
job = lease["job_id"]
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{job}/report", {"lease_id": lease["lease_id"], "progress": phase},
token, expected=204)
headers = {"X-Tessera-Lease-Id": lease["lease_id"], "X-Tessera-Sha256": sha256(payload).hexdigest(),
"X-Tessera-Source-Identity": identity}
api(f"wormhole/capture/{job}/payload", payload, token, extra=headers)
capture_only = api(f"capture-profiles/{capture_only_app}/jobs", {}, expected=202)["id"]
commit_capture(api(f"wormhole/capture/{capture_only_app}/claim", {}, token))
document = root / "filesystem.txt"
document.write_text("legacy filesystem fixture")
filesystem = api("orbits", {"name": "Browser filesystem", "provider": "filesystem",
"provider_config": {"paths": [str(document)]}})
api(f"orbits/{filesystem['id']}/run", {}, expected=204)
filesystem_snapshot = next(snap["id"] for snap in api("snapshots") if snap["orbit_id"] == filesystem["id"])
failed = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
failed_lease = api(f"wormhole/capture/{app}/claim", {}, token)
assert failed_lease["job_id"] == failed
for phase in ("dumping", "dump_failed"):
api(f"wormhole/capture/{failed}/report", {"lease_id": failed_lease["lease_id"], "progress": phase},
token, expected=204)
browser = Popen(["node", Path(__file__).with_name("browser.mjs"), url, password, capture_only, filesystem_snapshot])
cleanup.callback(stop, browser)
def claim():
assert browser.poll() is None, "browser failed before queueing capture"
return api(f"wormhole/capture/{app}/claim", {}, token)
lease = wait_until(claim)
job = lease["job_id"]
assert api(f"capture-jobs/{job}")["actor"] == "fixture-browser"
commit_capture(lease)
def claim_restore():
assert browser.poll() is None, "browser failed before queueing restore"
return api(f"wormhole/restore-targets/{target}/claim", {}, token)
restore = wait_until(claim_restore)
restore_id = restore["job"]["id"]
assert restore["job"]["actor"] == "fixture-browser"
scoped = {"X-Tessera-Restore-Token": restore["token"]}
restore_path = f"wormhole/restore/{restore_id}"
api(f"{restore_path}/report", "checking", token, expected=204, extra=scoped)
assert api(f"{restore_path}/payload", token=token, extra=scoped, raw=True) == payload
api(f"{restore_path}/report", "safety", token, expected=204, extra=scoped)
safety = b"CREATE TABLE browser_before_restore(value integer);\n"
safety_id = api(f"{restore_path}/safety", safety, token,
extra={**scoped, "X-Tessera-Sha256": sha256(safety).hexdigest()})["snapshot_id"]
api(f"{restore_path}/apply", {}, token, expected=204, extra=scoped)
api(f"{restore_path}/report", "apply_failed", token, expected=204, extra=scoped)
assert browser.wait(timeout=90) == 0
assert api(f"restore-jobs/{restore_id}")["status"] == "reconciled"
assert api(f"snapshots/{safety_id}/download", raw=True) == safety
with tarfile.open(root / "hub" / "exports" / "filesystem.tar") as archive:
entry = next(member for member in archive.getmembers() if member.name.endswith("filesystem.txt"))
assert archive.extractfile(entry).read() == b"legacy filesystem fixture"
with sqlite3.connect(root / "hub" / "tessera.db") as db:
count = db.execute("SELECT count(*) FROM audit_log WHERE event='snapshot.deleted' AND detail=?",
(f"actor=fixture-browser snapshot={job}",)).fetchone()[0]
assert count == 1
assert {snapshot["id"] for snapshot in api("snapshots")} == {capture_only, filesystem_snapshot, safety_id}
if __name__ == "__main__":
main()

135
tests/mbu/capture-mysql.py Normal file
View File

@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""MySQL direct and pinned SSH capture with view/routine/event fixtures."""
from contextlib import ExitStack
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from uuid import uuid4
from fixture import PASSWORD, bastion, command, mysql_container, pair, start_agent, start_hub, terminal, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-mysql-")))
mysql, defaults, mysql_port = mysql_container(cleanup, root)
password = root / "mysql-password"
password.write_text(PASSWORD + "\n")
password.chmod(0o600)
command(*mysql, "-D", "fixture", "-e",
"CREATE TABLE sample(id INT PRIMARY KEY, label VARCHAR(40)) CHARSET utf8mb4;"
"INSERT INTO sample VALUES(1, 'backup 🛰');"
"CREATE VIEW sample_view AS SELECT label FROM sample;"
"CREATE PROCEDURE sample_routine() SELECT id FROM sample;"
"CREATE EVENT sample_event ON SCHEDULE EVERY 1 DAY DISABLE DO SELECT 1;")
command(*mysql, "-e", """
CREATE DATABASE restored;
CREATE DATABASE managed_target;
CREATE TABLE managed_target.previous(id INT);
INSERT INTO managed_target.previous VALUES (84);
CREATE DATABASE limited_target;
CREATE TABLE limited_target.previous(id INT);
INSERT INTO limited_target.previous VALUES (91);
CREATE USER 'restore_limited'@'%' IDENTIFIED BY 'fixture-limited-password';
GRANT SELECT, SHOW VIEW, EVENT ON limited_target.* TO 'restore_limited'@'%';
GRANT SHOW_ROUTINE ON *.* TO 'restore_limited'@'%';
""")
instance = command(*mysql, "-NB", "-e", "SELECT LOWER(@@server_uuid)",
capture_output=True, text=True).stdout.strip()
limited_password = root / "limited-password"
limited_password.write_text("fixture-limited-password\n")
limited_password.chmod(0o600)
api, hub_url, _, hub_log = start_hub(cleanup, root)
agent = pair(api, "MySQL fixture")
token = agent["upload_token"]
pinned, wrong_key = bastion(cleanup, root)
direct = {"engine": "mysql", "transport": "direct", "host": "127.0.0.1",
"port": mysql_port, "user": "root", "password_file": str(password),
"database": "fixture", "tls": {"mode": "required"}}
remote = {"engine": "mysql", "transport": "ssh", "bastion": pinned,
"defaults_file": str(defaults), "database": "fixture"}
profiles, jobs, targets = {}, {}, {}
for name, source in [
("direct", direct), ("remote", remote),
("engine-error", {**direct, "database": "does_not_exist"}),
("wrong-key", {**remote, "bastion": wrong_key}),
]:
orbit = api("orbits", {"name": name, "provider": "wormhole", "provider_config": {}})
app = str(uuid4())
api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"],
"outpost_id": agent["outpost_id"], "format": "mysql_sql"}, expected=201)
jobs[name] = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
profiles[app] = {"source": source, "timeout_seconds": 45}
if name in ("direct", "remote"):
database = "managed_target" if name == "remote" else "limited_target"
target = str(uuid4())
api("restore-targets", {"id": target, "application_id": app, "outpost_id": agent["outpost_id"],
"name": database, "engine": "mysql", "identity": {"instance": instance, "database": database}},
expected=201)
targets[name] = target
target_connection = {key: value for key, value in source.items() if key != "engine"}
target_connection["database"] = database
if name == "direct":
target_connection.update(user="restore_limited", password_file=str(limited_password))
profiles[app]["targets"] = {target: {
"engine": "mysql", "connection": target_connection,
"recreate_database": True, "use_target_definer": True,
}}
_, agent_log = start_agent(cleanup, root, hub_url, token, profiles)
for name, job in jobs.items():
try:
result = wait_until(lambda: terminal(api, job))
except AssertionError as error:
for log in (hub_log, agent_log):
log.seek(0)
print(log.read().replace(PASSWORD, "<redacted>"))
raise AssertionError((name, api(f"capture-jobs/{job}"))) from error
if name in ("engine-error", "wrong-key"):
assert result["phase"] == "dump_failed" and result["snapshot_id"] is None, result
continue
assert result["status"] == "completed", (name, result)
target = root / f"{name}.sql"
session = api("reconstitute", {"snapshot_id": result["snapshot_id"], "target_path": str(target)})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
sql = target.read_text()
assert all(marker in sql for marker in ("sample_view", "sample_routine", "sample_event", "backup 🛰"))
if name == "remote":
with target.open("rb") as dump:
command(*mysql, "-D", "restored", stdin=dump)
output = command(*mysql, "-NB", "-D", "restored", "-e", "SELECT label FROM sample_view",
capture_output=True, text=True)
assert output.stdout.strip() == "backup 🛰", output.stdout
assert len(api("snapshots")) == 2
for name, target in targets.items():
snap = jobs[name]
job = api("restore-jobs", {"snapshot_id": snap, "target_id": target,
"confirmation": f"RESTORE {snap} TO {target}"}, expected=202)["id"]
def restored_job():
result = api(f"restore-jobs/{job}")
return result if result["status"] in ("completed", "failed", "recovery_required") else None
result = wait_until(restored_job, seconds=65)
if name == "direct":
assert result["status"] == "recovery_required" and result["safety_snapshot_id"], result
output = command(*mysql, "-NB", "-e", "SELECT id FROM limited_target.previous",
capture_output=True, text=True)
assert output.stdout.strip() == "91"
assert b"previous" in api(f"snapshots/{result['safety_snapshot_id']}/download", raw=True)
else:
assert result["status"] == "completed" and result["safety_snapshot_id"], result
output = command(*mysql, "-NB", "-D", "managed_target", "-e",
"SELECT label FROM sample_view; CALL sample_routine();"
"SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA='managed_target';",
capture_output=True, text=True)
assert output.stdout.strip().splitlines() == ["backup 🛰", "1", "sample_event"], output.stdout
assert b"previous" in api(f"snapshots/{result['safety_snapshot_id']}/download", raw=True)
for log in (hub_log, agent_log):
log.seek(0)
assert PASSWORD not in log.read()
print("MySQL direct/SSH capture, SSH apply, utf8mb4, view/routine/event, and limited-role failure with safety verified")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,186 @@
#!/usr/bin/env python3
"""Isolated PostgreSQL TLS → Wormhole → Restic → export → PostgreSQL fixture."""
from contextlib import ExitStack
from hashlib import sha256
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from uuid import uuid4
import json
import os
import socket
import stat
from fixture import BIN, PASSWORD, bastion, command, fixture_env, pair, port, start_agent, start_hub, stop, terminal, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-pg-")))
data = root / "db"
pg_port = port()
password = root / "password"
password.write_text(PASSWORD + "\n")
password.chmod(0o600)
command("initdb", "-D", data, "-U", "fixture", "--auth-local=trust",
"--auth-host=scram-sha-256", "--pwfile", password, stdout=DEVNULL)
ca, key = data / "server.crt", data / "server.key"
command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-noenc",
"-days", "1", "-subj", "/CN=localhost",
"-addext", "subjectAltName=DNS:localhost", "-out", ca,
"-keyout", key, stdout=DEVNULL, stderr=DEVNULL)
key.chmod(0o600)
command("pg_ctl", "-D", data, "-l", root / "postgres.log", "-w", "start",
"-o", f"-h 127.0.0.1 -p {pg_port} -k {root} -c ssl=on", stdout=DEVNULL)
cleanup.callback(command, "pg_ctl", "-D", data, "-m", "immediate", "-w", "stop", stdout=DEVNULL)
pg = ("-h", str(root), "-p", str(pg_port), "-U", "fixture")
for database in ("source_db", "target_db"):
command("createdb", *pg, database)
command("psql", *pg, "-d", "source_db", "-v", "ON_ERROR_STOP=1", "-c",
"CREATE SCHEMA fixture; CREATE TABLE fixture.rows (id integer PRIMARY KEY, value text);"
"INSERT INTO fixture.rows VALUES (1, 'Wormhole ✓');", stdout=DEVNULL)
api, hub_url, hub_port, hub_log = start_hub(cleanup, root)
credentials = root / "wormhole.json"
code = api("wormhole/pairing", {})["code"]
paired = command(BIN / "tessera-agent", "--hub-url", hub_url, "--credentials", credentials,
"pair", code, "--name", "Postgres fixture", env=fixture_env(),
text=True, capture_output=True)
assert stat.S_IMODE(credentials.stat().st_mode) == 0o600
agent = json.loads(credentials.read_text())
token = agent["upload_token"]
assert token not in paired.stdout and token not in paired.stderr
api("wormhole/claim", {"code": code, "outpost_name": "replay"}, expected=410)
wrong_agent = pair(api, "different fixture")
assert {outpost["id"] for outpost in api("wormhole/outposts")} == {
agent["outpost_id"], wrong_agent["outpost_id"],
}
def profile(host, via=None):
orbit = api("orbits", {"name": "fixture", "provider": "wormhole", "provider_config": {}})
app = str(uuid4())
api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"],
"outpost_id": agent["outpost_id"], "format": "postgres_custom"}, expected=201)
source = {"engine": "postgres", "host": host, "port": pg_port, "database": "source_db",
"user": "fixture", "password_file": str(password),
"tls": {"mode": "verify_full_with_ca", "ca_file": str(ca)}}
if via:
source["bastion"] = via
return app, {"source": source, "timeout_seconds": 15}
app, good = profile("localhost")
bad_app, bad = profile("127.0.0.1")
job = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
bad_job = api(f"capture-profiles/{bad_app}/jobs", {}, expected=202)["id"]
assert api(f"wormhole/capture/{app}/claim", {}, wrong_agent["upload_token"]) is None
pinned, wrong_key = bastion(cleanup, root)
tunnel_app, tunnel = profile("localhost", pinned)
wrong_key_app, bad_tunnel = profile("localhost", wrong_key)
tunnel_job = api(f"capture-profiles/{tunnel_app}/jobs", {}, expected=202)["id"]
wrong_key_job = api(f"capture-profiles/{wrong_key_app}/jobs", {}, expected=202)["id"]
stalled = cleanup.enter_context(socket.socket())
stalled.bind(("127.0.0.1", 0))
stalled.listen(1)
stalled.settimeout(5)
timeout_app, stalled_profile = profile("localhost", pinned)
stalled_profile["source"]["port"] = stalled.getsockname()[1]
stalled_profile["timeout_seconds"] = 2
timeout_job = api(f"capture-profiles/{timeout_app}/jobs", {}, expected=202)["id"]
agent_process, agent_log = start_agent(cleanup, root, hub_url, token, {
app: good, bad_app: bad, tunnel_app: tunnel, wrong_key_app: bad_tunnel,
timeout_app: stalled_profile,
}, credentials=credentials)
replica = root / "second-agent"
replica.mkdir()
second, _ = start_agent(cleanup, replica, hub_url, token, {app: good}, credentials=credentials)
partial_dir = root / "partial-client"
partial_dir.mkdir()
partial_client = partial_dir / "pg_dump"
partial_client.write_text("#!/bin/sh\nprintf PGDMPpartial\nexit 1\n")
partial_client.chmod(0o700)
partial_worker = root / "partial-agent"
partial_worker.mkdir()
partial_app, partial_profile = profile("localhost")
partial_job = api(f"capture-profiles/{partial_app}/jobs", {}, expected=202)["id"]
start_agent(cleanup, partial_worker, hub_url, token, {partial_app: partial_profile},
credentials=credentials, settings={"PATH": f"{partial_dir}:{os.environ['PATH']}"})
partial = wait_until(lambda: terminal(api, partial_job))
assert partial["phase"] == "dump_failed" and partial["snapshot_id"] is None
successful = wait_until(lambda: terminal(api, job))
assert sum(event["phase"] == "claimed" for event in api(f"capture-jobs/{job}/events")) == 1
failed = wait_until(lambda: terminal(api, bad_job))
through_bastion = wait_until(lambda: terminal(api, tunnel_job))
assert through_bastion["status"] == "completed", through_bastion
rejected = wait_until(lambda: terminal(api, wrong_key_job))
assert rejected["phase"] == "dump_failed" and rejected["snapshot_id"] is None, rejected
timed_out = wait_until(lambda: terminal(api, timeout_job))
assert timed_out["phase"] == "dump_failed" and timed_out["snapshot_id"] is None
with stalled.accept()[0] as connection:
connection.settimeout(5)
while connection.recv(1024):
pass
assert successful["status"] == "completed", successful
assert failed["status"] == "failed" and failed["phase"] == "dump_failed", failed
assert failed["snapshot_id"] is None
snapshots = api("snapshots")
assert {snap["id"] for snap in snapshots} == {successful["snapshot_id"], through_bastion["snapshot_id"]}
dump = root / "backup.dump"
session = api("reconstitute", {"snapshot_id": successful["snapshot_id"], "target_path": str(dump)})
wait_until(lambda: api(f"reconstitute/{session['session_id']}")["state"] == "completed")
command("pg_restore", *pg, "-d", "target_db", "--exit-on-error", dump)
restored = command("psql", *pg, "-d", "target_db", "-Atc",
"SELECT id, value FROM fixture.rows;", capture_output=True, text=True)
assert restored.stdout.strip() == "1|Wormhole ✓", restored.stdout
# Stage a second capture manually to exercise the commit protocol with a lost reply.
stop(agent_process)
stop(second)
replay = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
lease = api(f"wormhole/capture/{app}/claim", {}, token)
assert lease["job_id"] == replay
api(f"wormhole/capture/{replay}/report",
{"lease_id": lease["lease_id"], "progress": "synthetic-report-secret\x1b"},
token, expected=422)
assert all("synthetic-report-secret" not in json.dumps(value) for value in (
api(f"capture-jobs/{replay}"), api(f"capture-jobs/{replay}/events"), api("capture-jobs"),
))
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{replay}/report", {"lease_id": lease["lease_id"], "progress": phase},
token, expected=204)
payload = dump.read_bytes()
headers = {"X-Tessera-Lease-Id": lease["lease_id"], "X-Tessera-Sha256": sha256(payload).hexdigest()}
path = f"wormhole/capture/{replay}/payload"
api(path, payload, wrong_agent["upload_token"], expected=409, extra=headers)
api(path, payload[:-1], token, expected=422, extra=headers)
assert len(api("snapshots")) == 2
with socket.create_connection(("127.0.0.1", hub_port)) as conn:
request = (f"POST /api/v1/{path} HTTP/1.1\r\nHost: localhost\r\n"
f"X-Tessera-Upload-Token: {token}\r\nX-Tessera-Lease-Id: {lease['lease_id']}\r\n"
f"X-Tessera-Sha256: {headers['X-Tessera-Sha256']}\r\nContent-Length: {len(payload)}\r\n"
"Connection: close\r\n\r\n").encode()
conn.sendall(request + payload[:-1])
assert api(f"capture-jobs/{replay}")["snapshot_id"] is None
with socket.create_connection(("127.0.0.1", hub_port)) as conn:
conn.sendall(request + payload)
committed = wait_until(lambda: terminal(api, replay), seconds=10)
# Drop the connection without reading the acknowledgement.
assert committed["snapshot_id"] == replay
assert api(path, payload, token, extra=headers)["snapshot_id"] == replay
assert len(api("snapshots")) == 3
legacy = api("orbits", {
"name": "legacy-fixture", "provider": "postgres",
"provider_config": {"connection_url": f"postgres://fixture:{PASSWORD}@localhost:{pg_port}/source_db"},
})
assert "provider_config" not in legacy
command(BIN / "tessera", "--hub-url", hub_url, "snap", "--orbit", "legacy-fixture",
env={**fixture_env(), "TESSERA_ADMIN_TOKEN": "fixture-admin"}, stdout=DEVNULL)
assert any(snap["orbit_id"] == legacy["id"] for snap in api("snapshots"))
for log in (hub_log, agent_log):
log.seek(0)
assert PASSWORD not in log.read()
print("PostgreSQL direct and pinned SSH capture, TLS and SSH rejection, Restic restore, and replay verified")
if __name__ == "__main__":
main()

229
tests/mbu/fixture.py Normal file
View File

@@ -0,0 +1,229 @@
from contextlib import ExitStack
from pathlib import Path
from subprocess import DEVNULL, Popen, run
from urllib.error import HTTPError
from urllib.request import Request, urlopen
import getpass
import json
import os
import shutil
import socket
import time
ROOT = Path(__file__).resolve().parents[2]
BIN = ROOT / "target/debug"
PASSWORD = "fixture-database-password"
def command(*args, **kwargs):
return run(args, check=True, **kwargs)
def port():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def wait_until(probe, seconds=45):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
value = probe()
if value:
return value
time.sleep(0.2)
raise AssertionError("fixture timed out")
def stop(process):
if process.poll() is None:
process.terminate()
process.wait(timeout=15)
def fixture_env():
return {name: value for name, value in os.environ.items() if not name.startswith("TESSERA_")}
def start_hub(cleanup: ExitStack, root: Path, settings=None, return_handle=False):
hub_port = port()
env = {**fixture_env(), "TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key",
"TESSERA_LISTEN": f"127.0.0.1:{hub_port}", "TESSERA_DATA_DIR": str(root / "hub"),
"TESSERA_ADMIN_TOKEN": "fixture-admin", **(settings or {})}
hub_url = f"http://127.0.0.1:{hub_port}"
log = cleanup.enter_context((root / "hub.log").open("w+"))
hub = Popen([BIN / "tessera-hub"], env=env, stdout=log, stderr=log)
cleanup.callback(stop, hub)
def api(path, body=None, token=None, expected=200, extra=None, raw=False, method=None):
payload = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None
headers = {"Authorization": "Bearer fixture-admin", "Content-Type": "application/json"}
if token:
headers["X-Tessera-Upload-Token"] = token
headers.update(extra or {})
request = Request(hub_url + "/api/v1/" + path, payload, headers, method=method)
try:
with urlopen(request, timeout=30) as response:
assert response.status == expected, (path, response.status)
data = response.read()
return data if raw else (json.loads(data) if data else None)
except HTTPError as error:
assert error.code == expected, (path, error.code, error.read())
def healthy():
try:
with urlopen(hub_url + "/health", timeout=1) as response:
return response.status == 200
except OSError:
return False
wait_until(healthy)
result = (api, hub_url, hub_port, log)
return (*result, hub) if return_handle else result
def pair(api, name):
pairing = api("wormhole/pairing", {})
return api("wormhole/claim", {"code": pairing["code"], "outpost_name": name})
def start_agent(cleanup, root, hub_url, token, profiles, credentials=None, settings=None):
config = root / "capture.json"
config.write_text(json.dumps(profiles))
config.chmod(0o600)
log = cleanup.enter_context((root / "agent.log").open("w+"))
env = {**fixture_env(), **(settings or {})}
args = [BIN / "tessera-agent", "--capture-profiles", config]
if credentials:
args.extend(["--credentials", credentials])
else:
args.extend(["--hub-url", hub_url])
env["TESSERA_UPLOAD_TOKEN"] = token
agent = Popen([*args, "run"], env=env, stdout=log, stderr=log)
cleanup.callback(stop, agent)
return agent, log
def terminal(api, job_id):
result = api(f"capture-jobs/{job_id}")
return result if result["status"] in ("completed", "failed") else None
def bastion(cleanup, root):
bastion_port = port()
for name in ("host", "client", "wrong_host"):
command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", root / name)
config = root / "sshd_config"
config.write_text(
f"ListenAddress 127.0.0.1\nPort {bastion_port}\nHostKey {root / 'host'}\n"
f"AuthorizedKeysFile {root / 'client.pub'}\nPidFile {root / 'ssh.pid'}\n"
"UsePAM no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nStrictModes no\n"
f"SetEnv PATH={os.environ['PATH']}\n"
)
log = cleanup.enter_context((root / "sshd.log").open("w+"))
ssh = Popen([shutil.which("sshd") or "/usr/sbin/sshd", "-D", "-e", "-f", config],
stdout=log, stderr=log)
cleanup.callback(stop, ssh)
def listening():
try:
with socket.create_connection(("127.0.0.1", bastion_port), timeout=0.25):
return True
except OSError:
return False
wait_until(listening)
endpoint = {"host": "127.0.0.1", "port": bastion_port, "user": getpass.getuser(),
"identity_file": str(root / "client")}
results = []
for key in ("host", "wrong_host"):
known_hosts = root / (key + ".known_hosts")
known_hosts.write_text(f"[127.0.0.1]:{bastion_port} " + (root / (key + ".pub")).read_text())
results.append({**endpoint, "known_hosts_file": str(known_hosts)})
return results
def postgres(cleanup, root, databases):
data = root / "db"
pg_port = port()
password = root / "password"
password.write_text(PASSWORD + "\n")
password.chmod(0o600)
command("initdb", "-D", data, "-U", "fixture", "--auth-local=trust",
"--auth-host=scram-sha-256", "--pwfile", password, stdout=DEVNULL)
ca, key = data / "server.crt", data / "server.key"
command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-noenc",
"-days", "1", "-subj", "/CN=localhost",
"-addext", "subjectAltName=DNS:localhost", "-out", ca,
"-keyout", key, stdout=DEVNULL, stderr=DEVNULL)
key.chmod(0o600)
command("pg_ctl", "-D", data, "-l", root / "postgres.log", "-w", "start",
"-o", f"-h 127.0.0.1 -p {pg_port} -k {root} -c ssl=on", stdout=DEVNULL)
cleanup.callback(command, "pg_ctl", "-D", data, "-m", "immediate", "-w", "stop", stdout=DEVNULL)
pg = ("-h", str(root), "-p", str(pg_port), "-U", "fixture")
for database in databases:
command("createdb", *pg, database)
def connection(database):
return {"host": "localhost", "port": pg_port, "database": database, "user": "fixture",
"password_file": str(password),
"tls": {"mode": "verify_full_with_ca", "ca_file": str(ca)}}
return pg, connection
def register_capture(api, outpost, name, format):
orbit = api("orbits", {"name": name, "provider": "wormhole", "provider_config": {}})
from uuid import uuid4
app = str(uuid4())
api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"],
"outpost_id": outpost, "format": format}, expected=201)
return app
def mysql_container(cleanup, root):
from uuid import uuid4
mysql_port = port()
container = "tessera-mysql-" + uuid4().hex
command("docker", "run", "--rm", "-d", "--name", container,
"-p", f"127.0.0.1:{mysql_port}:3306",
"-e", "MYSQL_ROOT_PASSWORD=" + PASSWORD, "-e", "MYSQL_DATABASE=fixture",
os.environ.get("TESSERA_FIXTURE_MYSQL_IMAGE", "mysql:9.2"), stdout=DEVNULL)
cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL)
defaults = root / "mysql.cnf"
defaults.write_text(f"[client]\nuser=root\npassword={PASSWORD}\n"
f"host=127.0.0.1\nport={mysql_port}\nprotocol=TCP\nssl-mode=REQUIRED\n")
defaults.chmod(0o600)
mysql = ("mysql", f"--defaults-file={defaults}", "--default-character-set=utf8mb4")
def ready():
return run([*mysql, "-e", "SELECT 1"], stdout=DEVNULL, stderr=DEVNULL).returncode == 0
wait_until(ready, seconds=90)
return mysql, defaults, mysql_port
def s3_container(cleanup, bucket):
from uuid import uuid4
endpoint = f"http://127.0.0.1:{port()}"
container = "tessera-s3-" + uuid4().hex
command("docker", "run", "--rm", "-d", "--name", container,
"-p", f"{endpoint.removeprefix('http://')}:5000",
"motoserver/moto:5.1.12", stdout=DEVNULL)
cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL)
def ready():
try:
with urlopen(endpoint, timeout=1) as response:
return response.status == 200
except OSError:
return False
wait_until(ready)
settings = {"AWS_ACCESS_KEY_ID": "fixture-s3-key", "AWS_SECRET_ACCESS_KEY": "fixture-s3-secret",
"AWS_DEFAULT_REGION": "us-east-1", "AWS_EC2_METADATA_DISABLED": "true"}
command("aws", "--endpoint-url", endpoint, "s3api", "create-bucket", "--bucket", bucket,
env={**fixture_env(), **settings}, stdout=DEVNULL)
return endpoint, settings

109
tests/mbu/legacy-import.py Normal file
View File

@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Reconcile legacy archives and a private SQLite history without writing to S3."""
from contextlib import ExitStack
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from urllib.request import urlopen
from uuid import uuid4
import gzip
import json
import sqlite3
from fixture import BIN, command, fixture_env, mysql_container, port, postgres, start_hub, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-legacy-")))
endpoint = f"http://127.0.0.1:{port()}"
container = "tessera-legacy-" + uuid4().hex
command("docker", "run", "--rm", "-d", "--name", container,
"-p", f"{endpoint.removeprefix('http://')}:5000", "motoserver/moto:5.1.12", stdout=DEVNULL)
cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL)
def ready():
try:
with urlopen(endpoint, timeout=1) as response:
return response.status == 200
except OSError:
return False
wait_until(ready)
env = {**fixture_env(), "AWS_ACCESS_KEY_ID": "fixture-legacy-key", "AWS_SECRET_ACCESS_KEY": "fixture-legacy-secret",
"AWS_DEFAULT_REGION": "us-east-1", "AWS_EC2_METADATA_DISABLED": "true",
"TESSERA_VAULT_PASSPHRASE": "fixture-private-vault-key"}
bucket = "legacy-fixture"
aws = ("aws", "--endpoint-url", endpoint, "s3api")
command(*aws, "create-bucket", "--bucket", bucket, env=env, stdout=DEVNULL)
postgres_archive = gzip.compress(b"CREATE TABLE sample(value int);\nINSERT INTO sample VALUES (1);\n")
mysql = gzip.compress(b"CREATE TABLE sample(value INT) ENGINE=InnoDB;\nINSERT INTO sample VALUES (2);\n")
payloads = {"postgres": postgres_archive, "mysql": mysql}
for engine, payload in payloads.items():
file = root / f"{engine}.sql.gz"
file.write_bytes(payload)
command(*aws, "put-object", "--bucket", bucket, "--key", f"{engine}/2026-11-10.sql.gz",
"--body", file, env=env, stdout=DEVNULL)
history = root / "history.sqlite"
with sqlite3.connect(history) as db:
db.executescript("CREATE TABLE jobs(id INTEGER PRIMARY KEY, phase TEXT); INSERT INTO jobs VALUES(42,'archived');")
pg_root = root / "pg"
pg_root.mkdir()
pg, _ = postgres(cleanup, pg_root, ["legacy_fixture"])
mysql_client, _, _ = mysql_container(cleanup, root)
api, _, _, _ = start_hub(cleanup, root)
cli = (BIN / "tessera", "--data-dir", root / "hub")
for engine, payload in payloads.items():
orbit = api("orbits", {"name": engine, "provider": "wormhole", "provider_config": {}})
args = (*cli, "legacy-import", "--bucket", bucket, "--prefix", engine + "/", "--endpoint", endpoint,
"--orbit-id", orbit["id"], "--application", engine, "--engine", engine, "--history", history)
def report(*extra):
result = command(*args, *extra, env=env, capture_output=True)
return json.loads(result.stdout)
inventory = report("--inventory-only")
assert inventory["count"] == 1 and inventory["bytes"] == len(payload)
assert inventory["objects"][0]["status"] == "inventoried"
imported = report()
snapshot = imported["objects"][0]["snapshot_id"]
assert imported["objects"][0]["status"] == "imported"
restored = api(f"snapshots/{snapshot}/download", raw=True)
assert restored == payload
if engine == "postgres":
command("psql", *pg, "-d", "legacy_fixture", "-v", "ON_ERROR_STOP=1",
input=gzip.decompress(restored), stdout=DEVNULL)
value = command("psql", *pg, "-d", "legacy_fixture", "-Atc", "SELECT value FROM sample",
text=True, capture_output=True)
assert value.stdout.strip() == "1"
else:
command(*mysql_client, "-D", "fixture", input=gzip.decompress(restored), stdout=DEVNULL)
value = command(*mysql_client, "-D", "fixture", "-NB", "-e", "SELECT value FROM sample",
text=True, capture_output=True)
assert value.stdout.strip() == "2"
visible = next(entry for entry in api("snapshots") if entry["id"] == snapshot)
assert visible["size_bytes"] == len(payload)
assert visible["taken_at"] == imported["objects"][0]["last_modified"]
repeated = report()
assert repeated["objects"][0]["snapshot_id"] == snapshot
assert repeated["objects"][0]["status"] == "already_imported"
history_id = imported["history_snapshot_id"]
api(f"snapshots/{history_id}/download", expected=404)
exported = root / f"{engine}-history.sqlite"
command(*cli, "legacy-history", history_id, exported, env=env, stdout=DEVNULL)
with sqlite3.connect(exported.as_uri() + "?mode=ro", uri=True) as db:
assert db.execute("SELECT phase FROM jobs WHERE id=42").fetchone()[0] == "archived"
api(f"snapshots/{snapshot}", expected=204, method="DELETE")
command(*cli, "gc", env=env, stdout=DEVNULL)
assert report()["objects"][0]["status"] == "already_imported"
api(f"snapshots/{snapshot}/download", expected=404)
original = command(*aws, "head-object", "--bucket", bucket, "--key", f"{engine}/2026-11-10.sql.gz",
env=env, capture_output=True)
assert json.loads(original.stdout)["ContentLength"] == len(payload)
assert api("snapshots") == []
print("Read-only PostgreSQL/MySQL archive reconciliation, idempotency after GC, and private history verified")
if __name__ == "__main__":
main()

160
tests/mbu/matrix.py Normal file
View File

@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Isolated rehearsal of the ten application shapes, including scheduled capture."""
from contextlib import ExitStack
from datetime import datetime, timedelta, timezone
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
import json
import sqlite3
from fixture import bastion, command, mysql_container, pair, postgres, s3_container, start_agent, start_hub, wait_until
POSTGRES = [
"lti", "presensi", "sso", "helpdesk", "manbu", "daily_checklist",
"odoo_mas", "odoo_fta", "dashboard_management",
]
CAPTURE_ONLY = {"odoo_fta", "dashboard_management"}
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-matrix-")))
pg, connection = postgres(cleanup, root, POSTGRES + [
app + "_staging" for app in POSTGRES if app not in CAPTURE_ONLY
])
pinned, _ = bastion(cleanup, root)
mysql, defaults, _ = mysql_container(cleanup, root)
offsite_password = root / "offsite-password"
offsite_password.write_text("fixture-matrix-s3-vault\n")
offsite_password.chmod(0o600)
endpoint, aws = s3_container(cleanup, "tessera-matrix")
api, url, _, _ = start_hub(cleanup, root, {
**aws, "TESSERA_OFFSITE_REPOSITORY": f"s3:{endpoint}/tessera-matrix/rehearsal",
"TESSERA_OFFSITE_PASSWORD_FILE": str(offsite_password),
})
def pg_sql(database, statement):
return command("psql", *pg, "-d", database, "-Atc", statement,
capture_output=True, text=True).stdout.strip()
def mysql_sql(database, statement):
return command(*mysql, "-NB", "-D", database, "-e", statement,
capture_output=True, text=True).stdout.strip()
pg_id = pg_sql("postgres", "SELECT system_identifier FROM pg_control_system()")
mysql_id = mysql_sql("fixture", "SELECT LOWER(@@server_uuid)")
mysql_sql("fixture", "CREATE DATABASE boiler_staging; CREATE TABLE sample(value VARCHAR(40));"
"INSERT INTO sample VALUES ('boiler'); CREATE VIEW sample_view AS SELECT value FROM sample")
mysql_sql("boiler_staging", "CREATE TABLE sample(value VARCHAR(40)); INSERT INTO sample VALUES ('previous')")
groups = {kind: {"agent": pair(api, f"fixture-{kind}"), "profiles": {}}
for kind in ("direct", "bastion", "mysql")}
applications = {}
for app in POSTGRES + ["boiler"]:
mysql_app = app == "boiler"
group = groups["mysql" if mysql_app else "bastion" if app in ("odoo_mas", "odoo_fta") else "direct"]
node = group["agent"]["outpost_id"]
orbit = api("orbits", {"name": app, "provider": "wormhole", "provider_config": {}})
app_id = str(uuid4())
engine = "mysql" if mysql_app else "postgres"
format = "mysql_sql" if mysql_app else "postgres_sql" if app == "daily_checklist" else "postgres_custom"
api("capture-profiles", {"application_id": app_id, "orbit_id": orbit["id"], "outpost_id": node,
"format": format, "schedule": {"hour": 2, "timezone": "Asia/Jakarta"}}, expected=201)
target_db = app + "_staging"
if mysql_app:
source = {"transport": "ssh", "bastion": pinned, "defaults_file": str(defaults), "database": "fixture"}
target = {"engine": engine, "connection": {**source, "database": target_db},
"recreate_database": True, "use_target_definer": True}
else:
pg_sql(app, "CREATE SCHEMA fixture; CREATE TABLE fixture.sample(value text);"
f"INSERT INTO fixture.sample VALUES ('{app}')")
source = connection(app)
if app in ("odoo_mas", "odoo_fta"):
source["bastion"] = pinned
mode = {"reset": "recreate_database"} if app == "odoo_mas" else {"reset": "schema", "schema": "fixture"}
target = {"engine": engine, "connection": {**source, "database": target_db}, "mode": mode}
if app == "daily_checklist":
post = root / "checklist.sql"
post.write_text("INSERT INTO fixture.sample VALUES ('post-restore');")
target["post_restore_sql"] = str(post)
profile = {"source": {"engine": engine, **source}, "timeout_seconds": 120}
target_id = None
if app not in CAPTURE_ONLY:
target_id = str(uuid4())
api("restore-targets", {"id": target_id, "application_id": app_id, "outpost_id": node,
"name": target_db, "engine": engine, "identity": {
"instance": mysql_id if mysql_app else pg_id, "database": target_db,
}}, expected=201)
profile["targets"] = {target_id: target}
group["profiles"][app_id] = profile
manual = api(f"capture-profiles/{app_id}/jobs", {}, expected=202)["id"]
applications[app] = (app_id, target_id, manual, target_db)
# Backdate registration to just before one elapsed slot, then let the real scheduler tick.
now = datetime.now(timezone.utc)
slot = now.replace(hour=19, minute=0, second=0, microsecond=0)
if slot > now:
slot -= timedelta(days=1)
with sqlite3.connect(root / "hub" / "tessera.db") as db:
db.execute("UPDATE capture_profiles SET registered_at = ?", (int(slot.timestamp()) - 1,))
for kind, group in groups.items():
directory = root / kind
directory.mkdir(mode=0o700)
start_agent(cleanup, directory, url, group["agent"]["upload_token"], group["profiles"])
def completed_captures():
jobs = api("capture-jobs?limit=100")
assert all(job["status"] != "failed" for job in jobs), jobs
return jobs if len(jobs) == 20 and all(job["status"] == "completed" and job["offsite_status"] == "copied" for job in jobs) else None
captures = wait_until(completed_captures, seconds=240)
snapshots = {snap["id"]: snap for snap in api("snapshots")}
stats, restores = {}, {}
for app, (app_id, target, manual, _) in applications.items():
jobs = [job for job in captures if job["profile"]["application_id"] == app_id]
assert {job["actor"] for job in jobs} == {"api-token", "scheduler"}
scheduled = next(job for job in jobs if job["actor"] == "scheduler")
current = next(job for job in jobs if job["id"] == manual)
stats[app] = {
"manual_seconds": current["updated_at"] - current["created_at"],
"scheduled_seconds": scheduled["updated_at"] - scheduled["created_at"],
"freshness_seconds": int(datetime.now(timezone.utc).timestamp()) - scheduled["updated_at"],
"bytes": snapshots[scheduled["snapshot_id"]]["size_bytes"],
"offsite": scheduled["offsite_status"],
}
if target:
restores[app] = api("restore-jobs", {"snapshot_id": manual, "target_id": target,
"confirmation": f"RESTORE {manual} TO {target}"}, expected=202)["id"]
else:
assert api(f"capture-profiles/{app_id}/restore-targets") == []
stats[app]["restore"] = "capture_only"
def restores_done():
results = {app: api(f"restore-jobs/{job}") for app, job in restores.items()}
assert all(job["status"] not in ("failed", "recovery_required") for job in results.values()), results
return results if all(job["status"] == "completed" for job in results.values()) else None
results = wait_until(restores_done, seconds=180)
for app, result in results.items():
_, _, _, database = applications[app]
assert result["safety_snapshot_id"]
if app == "boiler":
assert mysql_sql(database, "SELECT value FROM sample_view") == app
else:
expected = app + "\npost-restore" if app == "daily_checklist" else app
assert pg_sql(database, "SELECT value FROM fixture.sample ORDER BY value") == expected
stats[app]["restore"] = "verified"
archive = applications["lti"][2]
expected = api(f"snapshots/{archive}/download", raw=True)
primary = root / "hub" / "vault" / "restic"
primary.rename(primary.with_name("restic-offline"))
assert api(f"snapshots/{archive}/download", raw=True) == expected
print(json.dumps(stats, indent=2, sort_keys=True))
if __name__ == "__main__":
main()

87
tests/mbu/offsite.py Normal file
View File

@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Verify retry and recovery from a separate S3-compatible Restic repository."""
from contextlib import ExitStack
from hashlib import sha256
from pathlib import Path
from subprocess import DEVNULL
from tempfile import TemporaryDirectory
from urllib.request import urlopen
from uuid import uuid4
import os
from fixture import command, pair, port, start_hub, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-s3-")))
endpoint = f"http://127.0.0.1:{port()}"
container = "tessera-s3-" + uuid4().hex
def ready():
try:
with urlopen(endpoint, timeout=1) as response:
return response.status == 200
except OSError:
return False
password = root / "offsite-password"
password.write_text("fixture-offsite-encryption\n")
password.chmod(0o600)
aws = {"AWS_ACCESS_KEY_ID": "fixture-s3-key", "AWS_SECRET_ACCESS_KEY": "fixture-s3-secret",
"AWS_DEFAULT_REGION": "us-east-1", "AWS_EC2_METADATA_DISABLED": "true"}
api, _, _, hub_log = start_hub(cleanup, root, {
**aws, "TESSERA_OFFSITE_REPOSITORY": f"s3:{endpoint}/tessera-fixture/isolated",
"TESSERA_OFFSITE_PASSWORD_FILE": str(password),
})
agent = pair(api, "offsite fixture")
token = agent["upload_token"]
orbit = api("orbits", {"name": "offsite", "provider": "wormhole", "provider_config": {}})
app = str(uuid4())
api("capture-profiles", {"application_id": app, "orbit_id": orbit["id"],
"outpost_id": agent["outpost_id"], "format": "postgres_sql"}, expected=201)
job = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
lease = api(f"wormhole/capture/{app}/claim", {}, token)
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{job}/report", {"lease_id": lease["lease_id"], "progress": phase},
token, expected=204)
payload = b"CREATE TABLE archived (value INTEGER);\nINSERT INTO archived VALUES (42);\n"
headers = {"X-Tessera-Lease-Id": lease["lease_id"], "X-Tessera-Sha256": sha256(payload).hexdigest()}
assert api(f"wormhole/capture/{job}/payload", payload, token, extra=headers)["snapshot_id"] == job
wait_until(lambda: api(f"capture-jobs/{job}")["offsite_status"] == "failed", seconds=90)
api(f"snapshots/{job}", expected=409, method="DELETE")
command("docker", "run", "--rm", "-d", "--name", container,
"-p", f"{endpoint.removeprefix('http://')}:5000",
"motoserver/moto:5.1.12", stdout=DEVNULL)
cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL)
wait_until(ready)
command("aws", "--endpoint-url", endpoint, "s3api", "create-bucket",
"--bucket", "tessera-fixture", env={**os.environ, **aws}, stdout=DEVNULL)
wait_until(lambda: api(f"capture-jobs/{job}")["offsite_status"] == "copied", seconds=45)
assert len(api("snapshots")) == 1
primary = root / "hub" / "vault" / "restic"
primary.rename(primary.with_name("restic-offline"))
assert api(f"snapshots/{job}/download", raw=True) == payload
api(f"snapshots/{job}", expected=204, method="DELETE")
assert api("snapshots") == []
api(f"snapshots/{job}/download", expected=404)
# Recover using only the S3 URL, Restic password, and the Tessera snapshot UUID.
env = {**os.environ, **aws, "RESTIC_PASSWORD_FILE": str(password)}
repo = f"s3:{endpoint}/tessera-fixture/isolated"
import json
listing = command("restic", "-r", repo, "snapshots", "--json", "--tag", f"tessera-{job}",
env=env, capture_output=True)
copies = json.loads(listing.stdout)
assert len(copies) == 1
recovered = command("restic", "-r", repo, "dump", copies[0]["id"], "/payload",
env=env, capture_output=True)
assert recovered.stdout == payload
hub_log.seek(0)
logs = hub_log.read()
assert all(secret not in logs for secret in (*aws.values(), "fixture-offsite-encryption") if secret.startswith("fixture"))
print("Failed S3 copy, retry, and byte-identical download with the primary repository offline verified")
if __name__ == "__main__":
main()

157
tests/mbu/restic-orbits.py Normal file
View File

@@ -0,0 +1,157 @@
#!/usr/bin/env python3
"""Exercise the orbit source/access matrix with a TLS Rest Server and PostgreSQL."""
from contextlib import ExitStack
from io import BytesIO
from pathlib import Path
from subprocess import DEVNULL, Popen, run
from tempfile import TemporaryDirectory
from uuid import uuid4
from argparse import ArgumentParser
import json
import os
import tarfile
from fixture import PASSWORD, command, mysql_container, pair, port, start_agent, start_hub, stop, terminal, wait_until
def main(with_mysql):
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-restic-orbits-")))
password = root / "password"
password.write_text(PASSWORD + "\n")
password.chmod(0o600)
data = root / "db"
pg_port = port()
command("initdb", "-D", data, "-U", "fixture", "--auth-local=trust",
"--auth-host=scram-sha-256", "--pwfile", password, stdout=DEVNULL)
command("pg_ctl", "-D", data, "-l", root / "postgres.log", "-w", "start",
"-o", f"-h 127.0.0.1 -p {pg_port} -k {root}", stdout=DEVNULL)
cleanup.callback(command, "pg_ctl", "-D", data, "-m", "immediate", "-w", "stop", stdout=DEVNULL)
pg = ("-h", str(root), "-p", str(pg_port), "-U", "fixture")
for database in ("source", "restored"):
command("createdb", *pg, database)
command("psql", *pg, "-d", "source", "-v", "ON_ERROR_STOP=1", "-c",
"CREATE TABLE changes (id int PRIMARY KEY, value text);"
"INSERT INTO changes SELECT i, md5(i::text) FROM generate_series(1, 500000) i;",
stdout=DEVNULL)
db = {"engine": "postgres", "host": "127.0.0.1", "port": pg_port, "user": "fixture",
"database": "source", "password_file": str(password), "tls": {"mode": "disable"}}
folder = root / "source"
folder.mkdir()
original = os.urandom(3 * 1024 * 1024)
(folder / "test.bin").write_bytes(original)
cases = [
("filesystem", "filesystem", "filesystem", {"paths": [str(folder)]}),
("postgres", "database", "postgres_sql", {"source": db}),
]
if with_mysql:
mysql, _, mysql_port = mysql_container(cleanup, root)
command(*mysql, "-D", "fixture", "-e",
"CREATE TABLE changes (id INT PRIMARY KEY, value TEXT);"
"INSERT INTO changes VALUES (1, 'restored MySQL'); CREATE DATABASE restored;")
cases.append(("mysql", "database", "mysql_sql", {"source": {
"engine": "mysql", "transport": "direct", "host": "127.0.0.1", "port": mysql_port,
"user": "root", "database": "fixture", "password_file": str(password), "tls": {"mode": "required"},
}}))
api, url, _, hub_log = start_hub(cleanup, root)
paired = pair(api, "Restic fixture")
vault = root / "hub" / "vault"
repos = vault / "outposts"
repos.mkdir(exist_ok=True)
ca, key = root / "server.crt", root / "server.key"
command("openssl", "req", "-x509", "-newkey", "rsa:2048", "-noenc", "-days", "1",
"-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost",
"-out", ca, "-keyout", key, stdout=DEVNULL, stderr=DEVNULL)
rest_port = port()
auth = root / "htpasswd"
auth.touch()
configs = {}
outposts = {}
for case, source, fmt, config in cases:
hub_config = config if source == "filesystem" else config["source"]
hub = api("orbits", {"name": f"{case} hub", "source": source, "access": "hub",
"provider_config": hub_config})
assert (hub["source"], hub["access"]) == (source, "hub")
api(f"orbits/{hub['id']}/run", {}, expected=204)
orbit = api("orbits", {"name": f"{case} outpost", "source": source, "access": "outpost",
"provider_config": {}, "retention": {
"keep_daily": 1, "keep_weekly": 0, "keep_monthly": 0, "keep_yearly": 0,
}})
assert (orbit["source"], orbit["access"]) == (source, "outpost")
orbit_id = orbit["id"]
application = str(uuid4())
outposts[case] = application
(vault / "keys" / f"outpost-{orbit_id}.json").write_text(json.dumps({
"outpost_id": paired["outpost_id"], "password": PASSWORD,
}))
command("restic", "-r", repos / orbit_id, "--password-file", password, "init", stdout=DEVNULL)
command("htpasswd", "-Bb", auth, orbit_id, PASSWORD, stdout=DEVNULL, stderr=DEVNULL)
other = "postgres_sql" if source == "filesystem" else "filesystem"
profile = {"orbit_id": orbit_id, "application_id": application, "outpost_id": paired["outpost_id"]}
api("capture-profiles", {**profile, "format": other}, expected=409)
api("capture-profiles", {**profile, "format": fmt}, expected=201)
configs[application] = {**config, "restic_repository": f"rest:https://localhost:{rest_port}/{orbit_id}/",
"restic_password_file": str(password), "rest_server_password_file": str(password)}
rest_log = cleanup.enter_context((root / "rest-server.log").open("w+"))
server = Popen(["rest-server", "--listen", f"127.0.0.1:{rest_port}", "--path", repos,
"--tls", "--tls-cert", ca, "--tls-key", key, "--htpasswd-file", auth,
"--append-only", "--private-repos"], stdout=rest_log, stderr=rest_log)
cleanup.callback(stop, server)
wait_until(lambda: run(["curl", "-s", "--cacert", ca, f"https://localhost:{rest_port}/"],
stdout=DEVNULL).returncode == 0)
_, agent_log = start_agent(cleanup, root, url, paired["upload_token"], configs,
settings={"RESTIC_CACERT": str(ca)})
def capture(application):
job = api(f"capture-profiles/{application}/jobs", {}, expected=202)["id"]
result = wait_until(lambda: terminal(api, job))
assert result["status"] == "completed", result
return next(snapshot for snapshot in api("snapshots") if snapshot["id"] == result["snapshot_id"])
try:
for case, application in outposts.items():
first = capture(application)
if case == "filesystem":
(folder / "tiny.txt").write_text("incremental")
elif case == "postgres":
command("psql", *pg, "-d", "source", "-c",
"UPDATE changes SET value = 'incremental' WHERE id = 50000;", stdout=DEVNULL)
second = capture(application)
assert second["stored_bytes"] < first["stored_bytes"], (first, second)
wait_until(lambda: first["id"] not in {snapshot["id"] for snapshot in api("snapshots")})
payload = api(f"snapshots/{second['id']}/download", raw=True)
if case == "filesystem":
with tarfile.open(fileobj=BytesIO(payload)) as archive:
files = {Path(member.name).name: archive.extractfile(member).read()
for member in archive if member.isfile()}
assert files == {"test.bin": original, "tiny.txt": b"incremental"}
elif case == "postgres":
assert second["capture"]["restore_ready"]
command("psql", *pg, "-d", "restored", "-v", "ON_ERROR_STOP=1",
input=payload, stdout=DEVNULL)
restored = command("psql", *pg, "-d", "restored", "-At", "-c",
"SELECT value FROM changes WHERE id = 50000;", capture_output=True)
assert restored.stdout.strip() == b"incremental"
else:
assert second["capture"]["restore_ready"] and second["new_data_chunks"] == 0
command(*mysql, "-D", "restored", input=payload)
restored = command(*mysql, "-NB", "-D", "restored", "-e",
"SELECT value FROM changes WHERE id = 1;", capture_output=True)
assert restored.stdout.strip() == b"restored MySQL"
print(f"{case}: {first['stored_bytes']} → {second['stored_bytes']} packed bytes, restore verified")
except Exception:
for log in (hub_log, agent_log, rest_log):
log.seek(0)
print(log.read())
raise
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("--mysql", action="store_true")
main(parser.parse_args().mysql)

View File

@@ -0,0 +1,260 @@
#!/usr/bin/env python3
"""Restore authorization, target safety, PostgreSQL reset modes, and recovery."""
from contextlib import ExitStack
from hashlib import sha256
from pathlib import Path
from subprocess import CalledProcessError, DEVNULL
from tempfile import TemporaryDirectory
from uuid import uuid4
import base64
import gzip
import json
import sqlite3
from fixture import bastion, command, pair, postgres, register_capture, start_agent, start_hub, stop, terminal, wait_until
def main():
with ExitStack() as cleanup:
root = Path(cleanup.enter_context(TemporaryDirectory(prefix="tessera-restore-pg-")))
pg, connection = postgres(cleanup, root, ["source_db", "schema_target", "recreate_target",
"wrong_target", "manual_target", "recovery_target",
"compressed_target", "corrupt_target", "meta_target"])
def sql(database, statements):
return command("psql", *pg, "-d", database, "-v", "ON_ERROR_STOP=1", "-Atc", statements,
capture_output=True, text=True).stdout.strip()
create = "CREATE SCHEMA fixture; CREATE TABLE fixture.rows(id int PRIMARY KEY, value text);"
for db in ["source_db", "schema_target", "recreate_target", "wrong_target", "manual_target",
"recovery_target", "compressed_target", "corrupt_target", "meta_target"]:
value = "source data" if db == "source_db" else db
sql(db, create + f"INSERT INTO fixture.rows VALUES (1, '{value}');")
instance = sql("postgres", "SELECT system_identifier FROM pg_control_system()")
pinned, _ = bastion(cleanup, root)
api, hub_url, _, _, hub_process = start_hub(cleanup, root, return_handle=True)
agent = pair(api, "restore outpost")
other = pair(api, "foreign outpost")
token = agent["upload_token"]
app = register_capture(api, agent["outpost_id"], "pg-restore", "postgres_custom")
plain_app = register_capture(api, agent["outpost_id"], "pg-plain", "postgres_sql")
foreign_app = register_capture(api, other["outpost_id"], "foreign", "postgres_custom")
def register_target(application, database, instance_id=instance, outpost=agent["outpost_id"]):
target = str(uuid4())
api("restore-targets", {
"id": target, "application_id": application, "outpost_id": outpost, "name": database,
"engine": "postgres", "identity": {"instance": instance_id, "database": database},
}, expected=201)
return target
schema = register_target(app, "schema_target")
recreate = register_target(app, "recreate_target")
wrong = register_target(app, "wrong_target", str(int(instance) - 1))
manual = register_target(app, "manual_target")
recovery = register_target(app, "recovery_target")
corrupt = register_target(app, "corrupt_target")
sql("recovery_target", "GRANT SELECT ON fixture.rows TO PUBLIC")
compressed = register_target(plain_app, "compressed_target")
meta_target = register_target(plain_app, "meta_target")
source_alias = register_target(app, "source_db")
foreign = register_target(foreign_app, "manual_target", str(int(instance) - 2), other["outpost_id"])
post = root / "post.sql"
post.write_text("INSERT INTO fixture.rows VALUES (2, 'post-restore');\n")
broken = root / "broken.sql"
broken.write_text("SELECT pg_sleep(120);\n")
def local(database, reset, **opts):
target = connection(database)
if reset == "recreate_database":
target["bastion"] = pinned
mode = {"reset": reset}
if reset == "schema":
mode["schema"] = "fixture"
return {"engine": "postgres", "connection": target, "mode": mode, **opts}
capture_id = api(f"capture-profiles/{app}/jobs", {}, expected=202)["id"]
profiles = {
app: {"source": {"engine": "postgres", **connection("source_db")}, "timeout_seconds": 45,
"targets": {
schema: local("schema_target", "schema", post_restore_sql=str(post)),
recreate: local("recreate_target", "recreate_database"),
wrong: local("wrong_target", "schema"),
recovery: local("recovery_target", "recreate_database", post_restore_sql=str(broken)),
corrupt: local("corrupt_target", "schema"),
}},
plain_app: {"timeout_seconds": 45, "targets": {
compressed: local("compressed_target", "schema",
omit_transaction_timeout=True, omit_pg_stat_statements=True),
meta_target: local("meta_target", "schema"),
}},
}
agent_process, agent_log = start_agent(cleanup, root, hub_url, token, profiles)
result = wait_until(lambda: terminal(api, capture_id))
assert result["status"] == "completed", result
def enqueue(snapshot, target, expected=202, confirmation=None):
return api("restore-jobs", {"snapshot_id": snapshot, "target_id": target,
"confirmation": confirmation or f"RESTORE {snapshot} TO {target}"}, expected=expected)
def finished(job):
value = api(f"restore-jobs/{job}")
if value["status"] in ("completed", "failed", "recovery_required"):
return value
enqueue(capture_id, schema, expected=400, confirmation="wrong confirmation")
enqueue(capture_id, foreign, expected=422)
enqueue(capture_id, source_alias, expected=422)
enqueue(capture_id, str(uuid4()), expected=422)
api("restore-targets", {"id": str(uuid4()), "application_id": app,
"outpost_id": agent["outpost_id"], "name": "MySQL mismatch", "engine": "mysql",
"identity": {"instance": str(uuid4()), "database": "mismatch"}}, expected=422)
assert api(f"capture-profiles/{foreign_app}/restore-targets")[0]["id"] == foreign
# Check the scoped payload and prove a failed safety write cannot grant apply.
manual_job = enqueue(capture_id, manual)["id"]
api(f"snapshots/{capture_id}", expected=409, method="DELETE")
assert api(f"wormhole/restore-targets/{manual}/claim", {}, other["upload_token"]) is None
lease = api(f"wormhole/restore-targets/{manual}/claim", {}, token)
assert lease["job"]["id"] == manual_job
auth = {"X-Tessera-Restore-Token": lease["token"]}
path = f"wormhole/restore/{manual_job}"
api(f"{path}/report", "checking", token, expected=204, extra=auth)
api(f"{path}/payload", token=token, expected=401)
api(f"{path}/payload", token=other["upload_token"], expected=403, extra=auth)
api(f"wormhole/restore/{uuid4()}/payload", token=token, expected=403, extra=auth)
archive = api(f"{path}/payload", token=token, extra=auth, raw=True)
assert sha256(archive).hexdigest() == lease["artifact"]["sha256"]
api(f"{path}/report", "safety", token, expected=204, extra=auth)
api(f"{path}/safety", archive, token, expected=422, extra={**auth, "X-Tessera-Sha256": "0" * 64})
api(f"{path}/apply", {}, token, expected=409, extra=auth)
assert sql("manual_target", "SELECT value FROM fixture.rows") == "manual_target"
api(f"restore-jobs/{manual_job}", expected=204, method="DELETE")
for target, name, expected_value in [
(schema, "schema_target", "source data\npost-restore"),
(recreate, "recreate_target", "source data"),
]:
job = enqueue(capture_id, target)["id"]
done = wait_until(lambda: finished(job), seconds=65)
if done["status"] != "completed":
agent_log.seek(0)
print(agent_log.read())
assert done["status"] == "completed" and done["safety_snapshot_id"], done
assert sql(name, "SELECT value FROM fixture.rows ORDER BY id") == expected_value
job = enqueue(capture_id, wrong)["id"]
failed = wait_until(lambda: finished(job))
assert failed["phase"] == "wrong_target" and failed["safety_snapshot_id"] is None, failed
assert sql("wrong_target", "SELECT value FROM fixture.rows") == "wrong_target"
# An operator can recover from the pinned safety artifact after an interrupted apply.
job = enqueue(capture_id, recovery)["id"]
def reset_observed():
state = api(f"restore-jobs/{job}")
if state["status"] != "applying":
return False
try:
return sql("recovery_target", "SELECT to_regclass('fixture.rows')") == ""
except CalledProcessError:
return False
wait_until(reset_observed, seconds=45)
stop(agent_process)
stop(hub_process)
# Advance this fixture lease to its deadline before restarting the hub.
with sqlite3.connect(root / "hub" / "tessera.db") as db:
stale_token = db.execute("SELECT lease_token FROM restore_jobs WHERE id = ?", (job,)).fetchone()[0]
db.execute("UPDATE restore_jobs SET lease_until = 0 WHERE id = ?", (job,))
api, hub_url, _, _ = start_hub(cleanup, root)
interrupted = api(f"restore-jobs/{job}")
assert interrupted["status"] == "recovery_required" and interrupted["phase"] == "lease_lost", interrupted
assert interrupted["safety_snapshot_id"]
api(f"wormhole/restore/{job}/apply", {}, token, expected=409, extra={"X-Tessera-Restore-Token": stale_token})
safety = interrupted["safety_snapshot_id"]
api(f"snapshots/{safety}", expected=409, method="DELETE")
api(f"snapshots/{capture_id}", expected=409, method="DELETE")
assert sql("recovery_target", "SELECT to_regclass('fixture.rows')") == ""
saved = root / "safety.dump"
saved.write_bytes(api(f"snapshots/{safety}/download", raw=True))
command("pg_restore", *pg, "-d", "recovery_target", "--exit-on-error", saved, stdout=DEVNULL)
assert sql("recovery_target", "SELECT value FROM fixture.rows") == "recovery_target"
assert "=r/" in sql("recovery_target", "SELECT relacl FROM pg_class WHERE oid = 'fixture.rows'::regclass")
api(f"restore-jobs/{job}/reconcile", {"confirmation": f"RECONCILE {job}"}, expected=204)
assert api(f"restore-jobs/{job}")["status"] == "reconciled"
# Restore a real PostgreSQL 17 dump into the older fixture.
container = "tessera-pg17-" + uuid4().hex
command("docker", "run", "--rm", "-d", "--name", container,
"-e", "POSTGRES_PASSWORD=fixture-pg17", "-e", "POSTGRES_USER=fixture",
"-e", "POSTGRES_DB=source17", "postgres:17", stdout=DEVNULL)
cleanup.callback(command, "docker", "stop", "-t", "3", container, stdout=DEVNULL)
def postgres17_ready():
try:
command("docker", "exec", container, "pg_isready", "-U", "fixture", "-d", "source17",
stdout=DEVNULL, stderr=DEVNULL)
return True
except CalledProcessError:
return False
wait_until(postgres17_ready, seconds=90)
pg17 = ("docker", "exec", container, "psql", "-X", "-U", "fixture", "-d", "source17",
"-v", "ON_ERROR_STOP=1", "-Atc")
command(*pg17, "CREATE EXTENSION pg_stat_statements; CREATE ROLE fixture_dump_owner;"
"CREATE SCHEMA fixture; CREATE TABLE fixture.rows(id int, value text);"
"ALTER TABLE fixture.rows OWNER TO fixture_dump_owner;"
"GRANT SELECT ON fixture.rows TO PUBLIC; INSERT INTO fixture.rows VALUES (1, 'compressed');",
stdout=DEVNULL)
source17_id = command(*pg17, "SELECT system_identifier FROM pg_control_system()",
capture_output=True, text=True).stdout.strip()
text = command("docker", "exec", container, "pg_dump", "-U", "fixture", "-d", "source17",
"--no-owner", "--no-acl", capture_output=True).stdout
assert b"SET transaction_timeout = 0;" in text and b"pg_stat_statements" in text
assert b"OWNER TO fixture_dump_owner" not in text and b"GRANT SELECT" not in text
plain_id = api(f"capture-profiles/{plain_app}/jobs", {}, expected=202)["id"]
claim = api(f"wormhole/capture/{plain_app}/claim", {}, token)
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{plain_id}/report", {"lease_id": claim["lease_id"], "progress": phase},
token, expected=204)
data = gzip.compress(text)
identity = base64.urlsafe_b64encode(json.dumps({"instance": source17_id, "database": "source17"}).encode()).decode().rstrip("=")
api(f"wormhole/capture/{plain_id}/payload", data, token, extra={
"X-Tessera-Lease-Id": claim["lease_id"], "X-Tessera-Sha256": sha256(data).hexdigest(),
"X-Tessera-Source-Identity": identity,
})
corrupted = enqueue(capture_id, corrupt)["id"]
with sqlite3.connect(root / "hub" / "tessera.db") as db:
db.execute("UPDATE restore_jobs SET artifact = json_set(artifact, '$.sha256', ?) WHERE id = ?",
("0" * 64, corrupted))
agent_process, _ = start_agent(cleanup, root, hub_url, token, profiles)
invalid = wait_until(lambda: finished(corrupted))
assert invalid["phase"] == "invalid_payload" and invalid["safety_snapshot_id"] is None, invalid
assert sql("corrupt_target", "SELECT value FROM fixture.rows") == "corrupt_target"
job = enqueue(plain_id, compressed)["id"]
done = wait_until(lambda: finished(job), seconds=65)
assert done["status"] == "completed", done
assert sql("compressed_target", "SELECT value FROM fixture.rows") == "compressed"
marker = root / "unexpected-shell-execution"
bad_archive = f"\\! touch {marker}\n".encode()
bad_id = api(f"capture-profiles/{plain_app}/jobs", {}, expected=202)["id"]
claim = api(f"wormhole/capture/{plain_app}/claim", {}, token)
for phase in ("dumping", "uploading"):
api(f"wormhole/capture/{bad_id}/report", {"lease_id": claim["lease_id"], "progress": phase},
token, expected=204)
api(f"wormhole/capture/{bad_id}/payload", bad_archive, token, extra={
"X-Tessera-Lease-Id": claim["lease_id"], "X-Tessera-Sha256": sha256(bad_archive).hexdigest(),
"X-Tessera-Source-Identity": identity,
})
job = enqueue(bad_id, meta_target)["id"]
guarded = wait_until(lambda: finished(job), seconds=65)
assert guarded["status"] == "recovery_required", guarded
assert not marker.exists() and sql("meta_target", "SELECT value FROM fixture.rows") == "meta_target"
print("PostgreSQL scoped restore, verified safety, schema/recreate, compatibility, restricted client, and recovery verified")
if __name__ == "__main__":
main()

View File

@@ -7,7 +7,7 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"test": "node --experimental-strip-types --test scripts/galaxy.test.mjs",
"test": "node --experimental-strip-types --test scripts/*.test.mjs",
"typecheck": "tsc --noEmit",
"preview": "vite preview"
},

View File

@@ -1,26 +1,179 @@
import assert from "node:assert/strict";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { chromium } from "playwright";
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE ?? "playwright");
const base = process.env.TESSERA_URL ?? "http://127.0.0.1:8787/";
const outFlow = process.env.FLOW_SHOT ?? join(tmpdir(), "tessera-galaxy-flowing.png");
const outLock = process.env.LOCK_SHOT ?? join(tmpdir(), "tessera-galaxy-locked.png");
const browser = await chromium.launch({ headless: true });
const fixture = process.env.TESSERA_GALAXY_FIXTURE === "1";
const verify = fixture && process.env.VERIFY_ANIMATION !== "0";
const throttle = Number(process.env.CPU_THROTTLE ?? 4);
const viewport = {
width: Number(process.env.VIEWPORT_WIDTH ?? 1440),
height: Number(process.env.VIEWPORT_HEIGHT ?? 900),
};
const browser = await chromium.launch({
headless: true,
executablePath: process.env.CHROMIUM_PATH,
});
try {
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const page = await browser.newPage({ viewport });
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
if (fixture) {
const orbits = Array.from({ length: 55 }, (_, index) => ({
id: `orbit-${index}`, name: `Load test orbit ${index + 1}`, provider: "filesystem",
last_status: index === 2 ? "running" : index === 3 ? "failed" : "completed", dry_run: false,
}));
const snapshots = orbits.flatMap(orbit => [1, 2, 3].map(day => ({
id: `${orbit.id}-snapshot-${day}`, orbit_id: orbit.id, orbit_name: orbit.name,
taken_at: `2026-01-0${day}T00:00:00Z`, size_bytes: 4096 * day,
})));
await page.route("**/health", route => route.fulfill({ body: "ok" }));
await page.route("**/api/v1/orbits", route => route.fulfill({ json: orbits }));
await page.route("**/api/v1/snapshots", async route => {
if (snapshots.length > orbits.length * 3) await new Promise(resolve => setTimeout(resolve, 1500));
await route.fulfill({ json: snapshots });
});
await page.route("**/api/v1/orbits/*/run", route => {
const id = new URL(route.request().url()).pathname.split("/").at(-2);
if (id === "orbit-1") return route.fulfill({ status: 500, body: "fixture capture failed" });
const orbit = orbits.find(orbit => orbit.id === id);
const snapshot = {
id: `${id}-captured`, orbit_id: id, orbit_name: orbit.name,
taken_at: new Date().toISOString(), size_bytes: 8192,
};
snapshots.push(snapshot);
return route.fulfill({ status: 204, headers: { "X-Tessera-Snapshot-Id": snapshot.id } });
});
}
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setCPUThrottlingRate", { rate: throttle });
async function frameTimes(mode) {
const stats = await page.evaluate(async () => {
const samples = [];
let previous = await new Promise(requestAnimationFrame);
for (let i = 0; i < 90; i++) {
const now = await new Promise(requestAnimationFrame);
samples.push(now - previous);
previous = now;
}
samples.sort((a, b) => a - b);
return { median: samples[45], p95: samples[85] };
});
console.log(`${mode} at ${viewport.width}×${viewport.height}, ${throttle}× CPU throttle: median ${stats.median.toFixed(1)}ms, p95 ${stats.p95.toFixed(1)}ms`);
const limit = process.env.FRAME_P95_MAX_MS;
if (limit) assert.ok(stats.p95 <= Number(limit), `${mode} p95 exceeded ${limit}ms`);
}
if (verify) {
await page.addInitScript(() => {
const requestFullscreen = Element.prototype.requestFullscreen;
window.fullscreenRequests = 0;
Element.prototype.requestFullscreen = function (...args) {
window.fullscreenRequests++;
return requestFullscreen?.apply(this, args) ?? Promise.reject(new Error("Fullscreen unavailable"));
};
});
}
const [orbitResponse] = await Promise.all([
page.waitForResponse((response) => new URL(response.url()).pathname === "/api/v1/orbits" && response.ok()),
page.goto(base),
]);
await page.getByText("Hub online", { exact: true }).waitFor();
await frameTimes("Workspace flowing");
if (fixture) {
await page.getByRole("button", { name: "Big screen", exact: true }).click();
await page.getByRole("button", { name: "Exit big screen" }).waitFor();
if (verify) {
assert.equal(await page.evaluate(() => window.fullscreenRequests), 0, "Big Screen requested browser fullscreen");
assert.equal(await page.evaluate(() => document.fullscreenElement !== null), false);
}
await frameTimes("Big Screen flowing");
await page.getByRole("button", { name: "Exit big screen" }).click();
}
await page.screenshot({ path: outFlow });
const firstOrbit = page.locator(".register-row").first();
const firstOrbit = fixture ? page.locator("#register-orbit-0") : page.locator(".register-row").first();
if ((await orbitResponse.json()).length) await firstOrbit.click();
else await page.getByRole("button", { name: "Pause motion" }).click();
await page.getByRole("button", { name: "Resume motion" }).waitFor();
if (verify || !fixture) {
await page.waitForFunction(checkSelection => {
const frame = document.querySelector(".galaxy-frame");
return (!checkSelection || frame.querySelector(".scene-labels .is-selected")) &&
Number(getComputedStyle(frame).getPropertyValue("--lock-reveal")) > 0.99;
}, verify);
}
await page.screenshot({ path: outLock });
if (verify) {
const lock = page.getByRole("button", { name: "Pause motion" });
const resume = page.getByRole("button", { name: "Resume motion" });
const frame = page.locator(".galaxy-frame");
// A reversal should reuse the label node and leave no interactive moons in Flowing.
const sameLabel = await page.evaluate(async () => {
const label = document.querySelector(".scene-labels .is-selected");
const button = document.querySelector(".scene-controls button");
button.click();
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
button.click();
return label === document.querySelector(".scene-labels .is-selected");
});
assert.ok(sameLabel);
await resume.waitFor();
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);
await page.waitForFunction(() => Number(
document.querySelector("[data-vault-core]").style.getPropertyValue("--capture-absorption"),
) > 0.2);
await page.waitForFunction(() => {
const flash = document.querySelector("#snapshot-orbit-0-captured .snapshot-row-flash");
const moon = document.querySelector('[data-snapshot-marker="orbit-0-captured"] .snapshot-flash');
return flash && moon && Number(getComputedStyle(flash).opacity) > 0.2 && Number(getComputedStyle(moon).opacity) > 0.2;
});
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");
const workspaceWidth = await frame.evaluate(element => element.getBoundingClientRect().width);
await page.getByRole("button", { name: "Big screen", exact: true }).click();
await page.waitForFunction(width => {
const frame = document.querySelector(".galaxy-frame");
const current = frame.getBoundingClientRect().width;
return current > width + 3 && current < frame.clientWidth - 3;
}, workspaceWidth);
await page.setViewportSize({ width: 1366, height: 820 });
await page.keyboard.press("Escape");
await page.getByRole("button", { name: "Big screen", exact: true }).waitFor();
await page.waitForFunction(() => !document.querySelector(".galaxy-frame").style.transform);
await page.setViewportSize(viewport);
await page.waitForFunction(width =>
Math.abs(document.querySelector(".galaxy-frame").getBoundingClientRect().width - width) < 1, workspaceWidth);
await resume.click();
await lock.waitFor();
assert.equal(await page.locator(".lock-details").getAttribute("pointer-events"), "none");
await page.emulateMedia({ reducedMotion: "reduce" });
await page.getByRole("button", { name: "Reduced motion" }).waitFor();
assert.equal(await frame.getAttribute("data-flowing"), "false");
assert.equal(await page.locator(".scene-labels .is-selected").evaluate(label => getComputedStyle(label).opacity), "1");
await page.getByRole("button", { name: "Big screen", exact: true }).click();
assert.equal(await frame.evaluate(element => element.style.transform), "");
assert.deepEqual(errors, []);
console.log("verified lock reversal, confirmed and failed capture, Big Screen resize, and reduced motion");
}
console.log("saved", outFlow, outLock);
} finally {
await browser.close();

View File

@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { assignOrbitSlots, orbitPose, groupSnapshots, moonPoses } from "../src/lib/galaxyLayout.ts";
import { capturePhases, assignOrbitSlots, orbitPose, groupSnapshots, moonPoses } from "../src/lib/galaxyLayout.ts";
import { placeLabels } from "../src/lib/galaxyLabelLayout.ts";
test("slot identities survive reordering, insertion and removal", () => {
@@ -62,3 +62,25 @@ test("labels respect screen bounds and preserve priority in a crowded scene", ()
assert.deepEqual(labels.map((l) => l.id), ["focused"]);
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);
});

View File

@@ -0,0 +1,38 @@
import assert from "node:assert/strict";
import test from "node:test";
import { formatWhen } from "../src/lib/format.ts";
import { createVaultSearch } from "../src/lib/vaultSearch.ts";
const navigation = [{ id: "orbits", label: "Orbits", icon: "" }];
const orbit = (id, name = "Orbits", provider = "filesystem") => ({ id, name, provider });
const snapshot = (id, taken_at, orbit_name = "Orbits") => ({ id, taken_at, orbit_name });
test("ranks exact, prefix, and substring matches case-insensitively", () => {
const orbits = [orbit("a", "Nightly Vault"), orbit("b", "Vault mirror"), orbit("c", "vault")];
const search = createVaultSearch(navigation, orbits);
const [group] = search(" VAULT ");
assert.deepEqual(group.results.map(({ id }) => id), ["c", "b", "a"]);
assert.equal(search("FILESYSTEM")[0].results.length, 3);
});
test("keeps duplicate names distinguishable and sorts equivalent snapshots newest first", () => {
const orbits = [orbit("alpha"), orbit("beta", "Orbits", "postgres")];
const snapshots = [snapshot("old", "2025-01-01T00:00:00Z"), snapshot("new", "2025-02-01T00:00:00Z")];
const search = createVaultSearch(navigation, orbits, snapshots);
const [, orbitGroup, snapshotGroup] = search("orbits");
assert.equal(new Set(orbitGroup.results.map(({ detail }) => detail)).size, 2);
assert.deepEqual(snapshotGroup.results.map(({ id }) => id), ["new", "old"]);
assert.equal(search(formatWhen(snapshots[0].taken_at))[0].results[0].id, "old");
assert.equal(search("beta")[0].results[0].id, "beta");
});
test("reserves a place for every matching category within the eight-result limit", () => {
const orbits = Array.from({ length: 12 }, (_, index) => orbit(`orbit-${index}`));
const snapshots = [snapshot("snap", "2025-02-01T00:00:00Z")];
const search = createVaultSearch(navigation, orbits, snapshots);
const groups = search("orbits");
assert.deepEqual(groups.map(({ label }) => label), ["Navigation", "Orbits", "Snapshots"]);
assert.equal(groups.flatMap(({ results }) => results).length, 8);
assert.deepEqual(search(" ").map(({ label }) => label), ["Navigation"]);
assert.deepEqual(search("no match"), []);
});

View File

@@ -1,14 +1,15 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence } from "motion/react";
import { AnimatePresence, useMotionValue } from "motion/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute,
runOrbit, startReconstitute, type Orbit,
enqueueCapture, runOrbit, startReconstitute, type Orbit,
} from "./api";
import { DecayView } from "./components/decay/DecayView";
import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD";
import { HUDPanel } from "./components/hud/HUDPanel";
import { HUDRail, type HUDMode } from "./components/hud/HUDRail";
import { SearchIcon, VaultSearch } from "./components/hud/VaultSearch";
import { OperatorGate } from "./components/operator/OperatorGate";
import { OrbitsView } from "./components/orbits/OrbitsView";
import { WormholeView } from "./components/outposts/WormholeView";
import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard";
@@ -20,12 +21,12 @@ import { SnapshotSheet } from "./components/vault/SnapshotSheet";
import { useReducedMotion } from "./hooks/useReducedMotion";
import { orbitStatus } from "./lib/format";
import { groupSnapshots } from "./lib/galaxyLayout";
import type { SearchResult } from "./lib/vaultSearch";
const panelTitles: Record<HUDMode, string> = {
scene: "Vault",
orbits: "Orbit management",
wormhole: "Wormhole uplink",
decay: "Snapshot retention",
reconstitute: "Restore snapshot",
snapshot: "Snapshot detail",
};
@@ -36,10 +37,17 @@ function priority(orbit: Orbit) {
}
export default function App() {
const app = useRef<HTMLDivElement>(null);
return <OperatorGate>{(operator) => <VaultApp {...operator} />}</OperatorGate>;
}
function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promise<void> }) {
const [logoutError, setLogoutError] = useState(false);
const workspaceScroll = useRef<number>(undefined);
const [bigScreen, setBigScreen] = useState(false);
const [mode, setMode] = useState<HUDMode>("scene");
const [searchOpen, setSearchOpen] = useState(false);
const searchTrigger = useRef<HTMLButtonElement>(null);
const searchDestination = useRef<() => HTMLElement | null>(undefined);
const panelOpen = mode !== "scene";
const [orbitId, setOrbitId] = useState<string>();
const [snapshotId, setSnapshotId] = useState<string | null>(null);
@@ -50,18 +58,40 @@ export default function App() {
const reducedMotion = useReducedMotion();
const qc = useQueryClient();
useEffect(() => {
const root = app.current;
if (!root) return;
const syncFullscreen = () => setBigScreen(document.fullscreenElement === root);
root.addEventListener("fullscreenchange", syncFullscreen);
return () => root.removeEventListener("fullscreenchange", syncFullscreen);
}, []);
useLayoutEffect(() => {
function searchKeys(event: KeyboardEvent) {
const composing = event.isComposing || event.keyCode === 229;
if (event.key === "Escape" && searchOpen) {
event.stopPropagation();
if (!composing) {
event.preventDefault();
if (!event.repeat) setSearchOpen(false);
}
} else if (!composing && (event.metaKey || event.ctrlKey) && !event.altKey &&
!event.shiftKey && event.key.toLowerCase() === "k") {
event.preventDefault();
if (!event.repeat) setSearchOpen(true);
}
}
window.addEventListener("keydown", searchKeys, true);
return () => window.removeEventListener("keydown", searchKeys, true);
}, [searchOpen]);
useLayoutEffect(() => {
if (searchOpen) {
searchDestination.current = () => searchTrigger.current;
return;
}
if (!searchDestination.current) return;
const target = searchDestination.current() ?? searchTrigger.current;
searchDestination.current = undefined;
target?.focus();
}, [searchOpen]);
useEffect(() => {
if (!bigScreen || mode !== "scene") return;
const exitOnEscape = (event: KeyboardEvent) => {
if (event.key === "Escape" && !event.defaultPrevented && !document.fullscreenElement) {
if (event.key === "Escape" && !event.defaultPrevented && !event.repeat) {
setBigScreen(false);
}
};
@@ -76,37 +106,32 @@ export default function App() {
}, [bigScreen]);
function toggleBigScreen() {
const root = app.current;
if (bigScreen) {
if (document.fullscreenElement === root) {
void document.exitFullscreen().catch(() => {});
} else {
setBigScreen(false);
}
return;
}
workspaceScroll.current = window.scrollY;
setBigScreen(true);
// The viewport layout also works when the browser declines native fullscreen.
if (document.fullscreenEnabled) void root?.requestFullscreen?.().catch(() => {});
if (!bigScreen) workspaceScroll.current = window.scrollY;
setBigScreen(!bigScreen);
}
const health = useQuery({ queryKey: ["health"], queryFn: fetchHealth, refetchInterval: 15_000, retry: 1 });
const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8_000, retry: 1 });
const orbits = useQuery({ queryKey: ["orbits"], queryFn: fetchOrbits, refetchInterval: 8_000, retry: 1 });
const capture = useMutation({
mutationFn: (target: Orbit) => runOrbit(target.id),
mutationFn: async (target: Orbit) => {
if (target.application_id) {
await enqueueCapture(target.application_id);
return null;
}
return runOrbit(target.id);
},
onSettled: () => {
void qc.invalidateQueries({ queryKey: ["orbits"] });
void qc.invalidateQueries({ queryKey: ["snapshots"] });
void qc.invalidateQueries({ queryKey: ["capture-jobs"] });
},
});
const online = health.isSuccess;
const activeId = capture.isPending ? capture.variables.id : undefined;
const sceneOrbits = useMemo(() => (orbits.data ?? []).map((orbit) =>
orbit.id === activeId ? { ...orbit, last_status: orbit.dry_run ? "rehearsing" : "running" } : orbit,
orbit.id === activeId ? { ...orbit, last_status: orbit.application_id ? "queued" : orbit.dry_run ? "rehearsing" : "running" } : orbit,
), [orbits.data, activeId]);
const register = useMemo(() => [...sceneOrbits].sort((a, b) => priority(a) - priority(b)), [sceneOrbits]);
const grouped = useMemo(() => groupSnapshots(orbits.data ?? [], snaps.data ?? []), [orbits.data, snaps.data]);
@@ -114,10 +139,12 @@ export default function App() {
const selected = sceneOrbits.find(({ id }) => id === orbitId);
const history = (selected && grouped.get(selected.id)) ?? [];
const snapshot = snaps.data?.find(({ id }) => id === snapshotId);
const completedOrbitId = capture.isSuccess ? capture.variables.id : undefined;
const arrival = useMemo(() => !reducedMotion && completedOrbitId && capture.data
? { orbitId: completedOrbitId, snapshotId: capture.data }
: undefined, [reducedMotion, completedOrbitId, capture.data]);
const captureGlow = useMotionValue(0);
const captureOrbitId = capture.variables?.id;
const captureEffect = useMemo(() => captureOrbitId && (capture.isError || capture.data)
? { orbitId: captureOrbitId, key: capture.submittedAt, snapshotId: capture.data ?? undefined }
: undefined, [captureOrbitId, capture.submittedAt, capture.isError, capture.data]);
const captureReady = !!captureEffect?.snapshotId && !!snaps.data?.some(({ id }) => id === captureEffect.snapshotId);
const failedCount = sceneOrbits.filter(({ last_status }) => last_status === "failed").length;
const orbitMessage = orbits.isPending ? "Receiving orbit telemetry…" : orbits.isError
@@ -126,8 +153,9 @@ export default function App() {
const snapshotMessage = snaps.isPending ? "Loading snapshot history…" : snaps.isError
? snaps.data ? "Showing last known snapshots." : "Snapshot history unavailable."
: history.length ? undefined : "This orbit has no snapshots yet.";
const captureLabel = capture.isPending ? capture.variables.dry_run ? "Rehearsing" : "Capturing"
const captureLabel = capture.isPending ? capture.variables.application_id ? "Queueing backup for" : capture.variables.dry_run ? "Rehearsing" : "Capturing"
: capture.isError ? "Capture failed for"
: capture.variables?.application_id ? "Backup queued for"
: capture.variables?.dry_run ? "Rehearsal complete for"
: capture.data ? "Snapshot secured from" : "Capture finished for";
const captureNotice = capture.variables && (
@@ -149,6 +177,7 @@ export default function App() {
}
function runCapture(target: Orbit) {
if (target.access === "outpost" && !target.application_id) return;
selectOrbit(target.id);
capture.mutate(target);
}
@@ -161,9 +190,28 @@ export default function App() {
setMode(next);
}
function selectSearchResult(result: SearchResult) {
if (result.kind === "navigation") openConsole(result.id);
else if (result.kind === "snapshot") openSnapshot(result.id);
else if (result.kind === "orbit") {
selectOrbit(result.id);
openConsole("scene");
}
searchDestination.current = () => {
if (result.kind === "snapshot" || (result.kind === "navigation" && result.id !== "scene")) {
return document.querySelector<HTMLElement>(".vault-dialog .dialog-heading h2");
}
if (bigScreen) return document.querySelector<HTMLElement>(".scene-screen-control");
return result.kind === "orbit" ? document.getElementById(`register-${result.id}`)
: document.querySelector<HTMLElement>(".vault-overview h1");
};
setSearchOpen(false);
}
return (
<div ref={app} className={`vault-app${bigScreen ? " big-screen" : ""}`}>
<header className="vault-topbar">
<div className={`vault-app${bigScreen ? " big-screen" : ""}`}>
<header className="vault-topbar" inert={searchOpen}>
<div className="vault-brand">
<svg viewBox="0 0 38 38" width="34" height="34" aria-hidden="true">
<circle cx="19" cy="19" r="10.5" fill="none" stroke="currentColor" opacity=".5" />
@@ -173,26 +221,40 @@ export default function App() {
<div><strong>Tessera</strong><span>Backup control</span></div>
</div>
<HUDRail active={mode === "snapshot" ? "scene" : mode} floating={bigScreen} panelOpen={panelOpen} reducedMotion={reducedMotion} onSelect={openConsole} />
<p className="hub-link" role="status">
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}
</p>
<div className="vault-topbar-tools">
<p className="hub-link" role="status">
<span className={`register-signal signal-${online ? "green" : "grey"}`} />
{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}
</p>
{onLogout && <button type="button" className="console-control" aria-label="Sign out"
onClick={() => void onLogout().catch(() => setLogoutError(true))}>
Sign out <span className="sr-only">{actor}</span>
</button>}
{logoutError && <p role="alert" className="text-sm text-orbit-red">Could not sign out.</p>}
<button type="button" ref={searchTrigger} className="console-control search-trigger"
aria-label="Search" aria-haspopup="dialog" aria-expanded={searchOpen} aria-keyshortcuts="Meta+K Control+K"
onClick={() => setSearchOpen(true)}>
<SearchIcon />
<span>Search</span>
<kbd aria-hidden="true">⌘K / Ctrl+K</kbd>
</button>
</div>
</header>
<main className="vault-main" inert={panelOpen}>
<main className="vault-main" inert={panelOpen || searchOpen}>
<div className="vault-overview">
<div>
<p className="instrument-label overview-label"><span aria-hidden="true">◈</span> Vault / 01</p>
<h1>Orbital vault</h1>
<h1 tabIndex={-1}>Orbital vault</h1>
<p className="overview-copy">Backup jobs and recovery points</p>
</div>
<TelemetryStrip orbitCount={orbits.data?.length} failedCount={failedCount} snapCount={snaps.data?.length} totalBytes={totalBytes} />
<TelemetryStrip orbitCount={orbits.data?.length} failedCount={failedCount} snapCount={snaps.data?.length} totalBytes={totalBytes} bigScreen={bigScreen} reducedMotion={reducedMotion} />
</div>
<div className="vault-workspace">
<VaultScene
orbits={sceneOrbits} selectedOrbitId={selected?.id} recentSnapshots={history.slice(0, 3)}
flowing={play && !reducedMotion} reducedMotion={reducedMotion} arrival={arrival}
flowing={play && !reducedMotion} reducedMotion={reducedMotion} captureEffect={captureEffect} captureGlow={captureGlow} captureReady={captureReady}
bigScreen={bigScreen} onToggleBigScreen={toggleBigScreen}
onToggleFlow={() => setPlay((value) => !value)}
onSelectOrbit={(id) => {
@@ -202,21 +264,23 @@ export default function App() {
onSelectSnapshot={openSnapshot}
/>
<OrbitRegister
orbits={register} selected={selected?.id} message={orbitMessage}
orbits={register} selected={selected?.id} message={orbitMessage} bigScreen={bigScreen}
onSelect={selectOrbit} onManage={() => setMode("orbits")}
/>
<OrbitInspector
orbit={selected} snapshots={history} snapshotMessage={snapshotMessage}
highlightedId={captureEffect?.snapshotId} captureGlow={captureGlow} bigScreen={bigScreen}
onSelectSnapshot={openSnapshot}
capture={selected && (
<>
<button
type="button" className="console-control capture-button"
onClick={() => runCapture(selected)}
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy}
disabled={!online || capture.isPending || orbitStatus(selected.last_status).busy ||
(selected.access === "outpost" && !selected.application_id)}
>
<span aria-hidden="true">↘</span>
<span>{selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
<span>{selected.application_id ? "Queue backup for" : selected.dry_run ? "Rehearse" : "Capture"} {selected.name}</span>
</button>
{noticeInInspector && mode !== "orbits" && captureNotice}
</>
@@ -231,6 +295,7 @@ export default function App() {
<HUDPanel
open={panelOpen}
inert={searchOpen}
title={panelTitles[mode]}
subtitle={mode === "reconstitute" ? "Review the destination before starting the restore." : undefined}
onClose={() => setMode("scene")}
@@ -239,20 +304,17 @@ export default function App() {
{mode === "orbits" && (
<SpringPane key="orbits">
<QueryGate query={orbits}>
{() => <OrbitsView orbits={sceneOrbits} onRun={runCapture} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
{() => <OrbitsView snapshots={snaps.isSuccess ? snaps.data : undefined} orbits={sceneOrbits} onRun={runCapture} onOpenSnapshot={openSnapshot} captureDisabled={!online || capture.isPending} notice={captureNotice} />}
</QueryGate>
</SpringPane>
)}
{mode === "wormhole" && (
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
)}
{mode === "decay" && (
<SpringPane key="decay"><DecayView orbits={sceneOrbits} /></SpringPane>
)}
{mode === "snapshot" && (
<SpringPane key="snapshot">
{snapshot
? <SnapshotSheet snap={snapshot} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
? <SnapshotSheet snap={snapshot} onDeleted={() => openConsole("scene")} onReconstitute={() => openConsole("reconstitute", snapshot.id)} />
: <EmptyState title="Snapshot unavailable" body="It may have expired under the retention policy." />}
</SpringPane>
)}
@@ -261,7 +323,7 @@ export default function App() {
{restoreTarget && (snaps.data?.length || restoreBusy ? (
<ReconstituteWizard
key={restoreTarget.id ?? "manual"}
snapshots={snaps.data ?? []} selected={restoreTarget.id}
snapshots={snaps.data ?? []} selected={restoreTarget.id} scopedExport={!!actor}
onStart={startReconstitute} onPoll={pollReconstitute} onAbort={abortReconstitute} onBusyChange={setRestoreBusy}
/>
) : (
@@ -271,6 +333,14 @@ export default function App() {
))}
</SpringPane>
</HUDPanel>
<VaultSearch
open={searchOpen} reducedMotion={reducedMotion}
orbits={orbits.data} snapshots={snaps.data}
orbitStatus={orbits.isPending ? "Loading orbits…" : orbits.isError
? orbits.data ? "Showing last known orbits." : "Orbits unavailable." : undefined}
snapshotStatus={snaps.isPending || snaps.isError ? snapshotMessage : undefined}
onClose={() => setSearchOpen(false)} onSelect={selectSearchResult}
/>
</div>
);
}

View File

@@ -4,18 +4,27 @@ export type Snapshot = {
taken_at: string;
orbit_name: string;
size_bytes: number;
capture?: { job_id: string; application_id: string; engine: "postgres" | "mysql"; format: string; restore_ready: boolean } | null;
};
export type BackupSource = "filesystem" | "database";
export type BackupAccess = "hub" | "outpost";
export type Orbit = {
id: string;
name: string;
provider: string;
provider_config?: string;
source: BackupSource | null;
access: BackupAccess;
last_status: string;
dry_run: boolean;
schedule?: string | null;
decay_preset?: string;
retention?: RetentionPolicy | null;
application_id?: string | null;
capture_schedule?: { hour: number; minute: number; timezone: string } | null;
capture_retention?: { mode: "age"; days: number } | { mode: "count"; keep: number } | null;
retention_source?: "orbit" | "profile" | "default";
};
export type RetentionPolicy = {
@@ -29,14 +38,52 @@ export type RetentionSettings = { decay_preset: string } | { retention: Retentio
export type CreateOrbitInput = {
name: string;
provider: "filesystem" | "postgres";
paths: string[];
schedule?: string;
dry_run: boolean;
} & RetentionSettings;
} & RetentionSettings & (
| { source: "filesystem"; access: "hub"; provider_config: { paths: string[] } }
| { source: "database"; access: "hub"; provider_config: {
engine: "postgres" | "mysql"; transport?: "direct"; host: string; port?: number;
database: string; user: string; password_file: string;
tls?: { mode: "verify_full_with_ca" | "verify_identity_with_ca"; ca_file: string };
} }
| { source: BackupSource; access: "outpost"; provider_config: Record<string, never> }
);
export type OperatorSession = {
login_enabled: boolean;
authorized: boolean;
actor: string | null;
csrf: string | null;
};
let csrf: string | null = null;
export async function fetchOperatorSession(signal?: AbortSignal): Promise<OperatorSession> {
const session = await api<OperatorSession>("/api/v1/operator/session", { signal });
csrf = session.csrf;
return session;
}
export async function loginOperator(password: string): Promise<OperatorSession> {
const session = await api<OperatorSession>("/api/v1/operator/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
});
csrf = session.csrf;
return session;
}
export async function logoutOperator(): Promise<void> {
await request("/api/v1/operator/session", { method: "DELETE" });
csrf = null;
}
async function request(path: string, init?: RequestInit): Promise<Response> {
const r = await fetch(path, init);
const headers = new Headers(init?.headers);
if (csrf && init?.method && init.method !== "GET") headers.set("X-Tessera-CSRF", csrf);
const r = await fetch(path, { ...init, headers });
if (!r.ok) {
const text = await r.text().catch(() => "");
throw new Error(text || `${path} failed`);
@@ -68,14 +115,7 @@ export async function createOrbit(input: CreateOrbitInput): Promise<Orbit> {
return api("/api/v1/orbits", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: input.name,
provider: input.provider,
provider_config: { paths: input.paths },
schedule: input.schedule || null,
...("retention" in input ? { retention: input.retention } : { decay_preset: input.decay_preset }),
dry_run: input.dry_run,
}),
body: JSON.stringify(input),
});
}
@@ -120,3 +160,120 @@ export async function pollReconstitute(sessionId: string) {
if (!response.ok) throw new Error("Could not read restore status");
return response.json() as Promise<{ state: string; seconds_remaining: number }>;
}
export type CaptureProfile = {
application_id: string;
orbit_id: string;
outpost_id: string;
format: "postgres_custom" | "postgres_sql" | "mysql_sql" | "filesystem";
schedule?: Orbit["capture_schedule"];
};
export function registerCaptureProfile(profile: CaptureProfile): Promise<CaptureProfile> {
return api("/api/v1/capture-profiles", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(profile),
});
}
export type CaptureJob = {
id: string;
profile: CaptureProfile;
actor: string;
status: "queued" | "running" | "completed" | "failed";
phase: string;
created_at: number;
snapshot_id: string | null;
offsite_status: "pending" | "failed" | "copied" | null;
};
export type CaptureEvent = { at: number; phase: string };
export function fetchCaptureProfiles(): Promise<CaptureProfile[]> {
return api("/api/v1/capture-profiles");
}
export function enqueueCapture(application: string): Promise<CaptureJob> {
return api(`/api/v1/capture-profiles/${application}/jobs`, { method: "POST" });
}
export function fetchCaptureJobs(application: string, status: string): Promise<CaptureJob[]> {
const filter = new URLSearchParams();
if (application) filter.set("application_id", application);
if (status) filter.set("status", status);
return api(`/api/v1/capture-jobs?${filter}`);
}
export function fetchCaptureEvents(job: string): Promise<CaptureEvent[]> {
return api(`/api/v1/capture-jobs/${job}/events`);
}
export function deleteSnapshot(snapshot: string): Promise<void> {
return api(`/api/v1/snapshots/${snapshot}`, { method: "DELETE" });
}
export type Outpost = { id: string; name: string | null; last_seen: string | null; pairing_state: string };
export function fetchOutposts(): Promise<Outpost[]> {
return api("/api/v1/wormhole/outposts");
}
export type RestoreTarget = {
id: string;
name: string;
outpost_id: string;
engine: "postgres" | "mysql";
application_id: string;
identity: { instance: string; database: string };
};
export type SnapshotRestoreTarget = RestoreTarget & { ineligible_reason: string | null };
export function registerRestoreTarget(target: RestoreTarget): Promise<RestoreTarget> {
return api("/api/v1/restore-targets", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(target),
});
}
export type RestoreJob = {
id: string;
snapshot_id: string;
target: RestoreTarget;
status: "queued" | "running" | "applying" | "failed" | "completed" | "recovery_required" | "reconciled" | "cancelled";
phase: string;
safety_snapshot_id: string | null;
};
export function fetchRestoreTargets(snapshot: string): Promise<SnapshotRestoreTarget[]> {
return api(`/api/v1/snapshots/${snapshot}/restore-targets`);
}
export function fetchRestoreJobs(snapshot: string): Promise<RestoreJob[]> {
return api(`/api/v1/snapshots/${snapshot}/restore-jobs`);
}
export function enqueueRestore(snapshot: string, target: string, confirmation: string): Promise<RestoreJob> {
return api("/api/v1/restore-jobs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ snapshot_id: snapshot, target_id: target, confirmation }),
});
}
export function cancelRestore(job: string): Promise<void> {
return api(`/api/v1/restore-jobs/${job}`, { method: "DELETE" });
}
export function reconcileRestore(job: string, confirmation: string): Promise<void> {
return api(`/api/v1/restore-jobs/${job}/reconcile`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ confirmation }),
});
}

View File

@@ -1,68 +0,0 @@
import type { Orbit } from "../../api";
import { DECAY_PRESETS } from "../../lib/format";
import { describeRetention } from "../orbits/RetentionFields";
import { Hint } from "../ui/EmptyState";
import { TelemetryPanel } from "../ui/Telemetry";
export function DecayView({ orbits }: { orbits: Orbit[] }) {
const appliedPresets = new Set(orbits.filter((orbit) => !orbit.retention).map((orbit) => orbit.decay_preset ?? DECAY_PRESETS[0].id));
const custom = orbits.filter((orbit) => orbit.retention);
return (
<div className="h-full overflow-y-auto px-4 py-4 pb-28">
<h2 className="text-2xl font-semibold text-star-100">Decay</h2>
<p className="text-sm text-star-300 mt-1 mb-6">
Choose a preset or set daily, weekly, monthly and yearly counts for each orbit.
</p>
<span className="text-xs text-star-400">Retention presets</span>
<ul className="space-y-3 mt-3">
{DECAY_PRESETS.map((p) => {
const active = appliedPresets.has(p.id);
return (
<li
key={p.id}
className={`rounded-2xl border p-4 ${
active
? "border-orbit-green/35 bg-orbit-green/5"
: "border-space-700 bg-space-800/40"
}`}
>
<div className="flex items-start gap-2 flex-wrap">
<h3 className="font-medium text-star-100">{p.title}</h3>
{active && (
<span className="text-[10px] text-orbit-green border border-orbit-green/30 rounded px-1.5">
In use
</span>
)}
</div>
<p className="text-sm text-star-400 mt-1">{p.blurb}</p>
</li>
);
})}
</ul>
{custom.length > 0 && (
<div className="mt-4 space-y-2">
<h3 className="text-sm font-medium text-star-100">Custom policies</h3>
<ul className="space-y-2">
{custom.map((orbit) => (
<li key={orbit.id} className="rounded-2xl border border-space-700 bg-space-800/40 p-4">
<p className="text-sm font-medium text-star-100">{orbit.name}</p>
<p className="text-sm text-star-400">{describeRetention(orbit)}</p>
</li>
))}
</ul>
</div>
)}
<Hint>
Decay runs after a successful capture — rehearsed orbits never prune the vault.
</Hint>
<TelemetryPanel label="Decay policy IDs">
{JSON.stringify(DECAY_PRESETS.map((p) => p.id), null, 2)}
</TelemetryPanel>
</div>
);
}

View File

@@ -1,34 +1,62 @@
import { AnimatePresence, motion } from "motion/react";
import type { KeyboardEvent, ReactNode } from "react";
import { AnimatePresence, motion, useMotionValue, useSpring, useTransform, type MotionValue } from "motion/react";
import { useLayoutEffect, useRef, type KeyboardEvent, type ReactNode } from "react";
import type { Orbit, Snapshot } from "../../api";
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { gentleSpring } from "../../lib/motion";
import { useReducedMotion } from "../../hooks/useReducedMotion";
import { formatBytes, formatWhen, orbitStatus, schedulePhrase } from "../../lib/format";
import { SpringPane } from "../ui/SpringPane";
function TelemetryValue({ value, bytes = false }: { value?: number; bytes?: boolean }) {
const reducedMotion = useReducedMotion();
const target = useMotionValue(value ?? 0);
const count = useSpring(target, gentleSpring);
const text = useTransform(count, number => bytes ? formatBytes(Math.max(0, number)) : String(Math.round(number)));
useLayoutEffect(() => {
if (reducedMotion || value === undefined) count.jump(value ?? 0);
target.set(value ?? 0);
}, [value, reducedMotion, target, count]);
if (value === undefined) return "—";
return (
<>
<span className="sr-only">{bytes ? formatBytes(value) : value}</span>
<motion.span aria-hidden="true">{text}</motion.span>
</>
);
}
export function TelemetryStrip({
orbitCount, failedCount, snapCount, totalBytes,
orbitCount, failedCount, snapCount, totalBytes, bigScreen, reducedMotion,
}: {
orbitCount?: number;
failedCount: number;
snapCount?: number;
totalBytes: number;
bigScreen: boolean;
reducedMotion: boolean;
}) {
const strip = useRef<HTMLDListElement>(null);
useScreenTransition(strip, bigScreen, reducedMotion, undefined, true);
return (
<dl className="vault-telemetry">
<div><dt>Orbits</dt><dd>{orbitCount ?? "—"}</dd></div>
<div><dt>Failed</dt><dd className={failedCount ? "telemetry-alert" : ""}>{orbitCount === undefined ? "—" : failedCount}</dd></div>
<div><dt>Snapshots</dt><dd>{snapCount ?? "—"}</dd></div>
<div><dt>Payload</dt><dd>{snapCount === undefined ? "—" : formatBytes(totalBytes)}</dd></div>
<dl ref={strip} className="vault-telemetry">
<div><dt>Orbits</dt><dd><TelemetryValue value={orbitCount} /></dd></div>
<div><dt>Failed</dt><dd className={failedCount ? "telemetry-alert" : ""}>
<TelemetryValue value={orbitCount === undefined ? undefined : failedCount} />
</dd></div>
<div><dt>Snapshots</dt><dd><TelemetryValue value={snapCount} /></dd></div>
<div><dt>Payload</dt><dd><TelemetryValue value={snapCount === undefined ? undefined : totalBytes} bytes /></dd></div>
</dl>
);
}
export function OrbitRegister({
orbits, selected, message, onSelect, onManage,
orbits, selected, message, bigScreen, onSelect, onManage,
}: {
orbits: Orbit[];
selected?: string;
message?: string;
bigScreen: boolean;
onSelect: (id: string) => void;
onManage: () => void;
}) {
@@ -45,7 +73,8 @@ export function OrbitRegister({
}
return (
<section className="vault-console orbit-register" aria-labelledby="register-title">
<motion.section className="vault-console orbit-register" aria-labelledby="register-title" inert={bigScreen}
initial={false} animate={{ opacity: bigScreen ? 0 : 1 }}>
<header className="console-heading">
<p className="instrument-label">Flight register</p>
<h2 id="register-title">Orbits</h2>
@@ -56,13 +85,14 @@ export function OrbitRegister({
const status = orbitStatus(orbit.last_status);
return (
<motion.li key={orbit.id} layout={reducedMotion ? false : "position"}>
<button
<motion.button
type="button"
id={`register-${orbit.id}`}
className="register-row"
aria-pressed={selected === orbit.id}
tabIndex={active === orbit.id ? 0 : -1}
onClick={() => onSelect(orbit.id)}
whileHover={{ backgroundColor: selected === orbit.id ? "#28252b" : "#1b1e23" }}
onKeyDown={(event) => moveFocus(event, index)}
>
<span className={`register-signal signal-${status.tone}`} aria-hidden="true" />
@@ -71,7 +101,7 @@ export function OrbitRegister({
<small>{orbit.provider}</small>
</span>
<span className={`register-state tone-${status.tone}`}>{status.label}</span>
</button>
</motion.button>
</motion.li>
);
})}
@@ -81,22 +111,26 @@ export function OrbitRegister({
{orbits.length ? "Manage orbits" : "Set up an orbit"} <span aria-hidden="true">↗</span>
</button>
</div>
</section>
</motion.section>
);
}
export function OrbitInspector({
orbit, snapshots, snapshotMessage, capture, onSelectSnapshot,
orbit, snapshots, snapshotMessage, capture, highlightedId, captureGlow, bigScreen, onSelectSnapshot,
}: {
orbit?: Orbit;
snapshots: Snapshot[];
snapshotMessage?: string;
capture?: ReactNode;
highlightedId?: string;
captureGlow: MotionValue<number>;
bigScreen: boolean;
onSelectSnapshot: (id: string) => void;
}) {
const status = orbitStatus(orbit?.last_status ?? "idle");
return (
<section className="vault-console orbit-inspector" aria-labelledby="inspector-title">
<motion.section className="vault-console orbit-inspector" aria-labelledby="inspector-title" inert={bigScreen}
initial={false} animate={{ opacity: bigScreen ? 0 : 1 }}>
<header className="console-heading">
<p className="instrument-label">Orbit detail</p>
<h2 id="inspector-title">{orbit?.name ?? "Select an orbit"}</h2>
@@ -106,7 +140,7 @@ export function OrbitInspector({
<AnimatePresence initial={false}>
{orbit ? (
<SpringPane key={orbit.id}>
<p className="inspector-schedule">{schedulePhrase(orbit.schedule, orbit.dry_run)}</p>
<p className="inspector-schedule">{schedulePhrase(orbit)}</p>
<div className="inspector-capture">{capture}</div>
<section className="inspector-history" aria-label="Snapshot history">
<header>
@@ -118,6 +152,9 @@ export function OrbitInspector({
{snapshots.map((snapshot, index) => (
<li key={snapshot.id}>
<button id={`snapshot-${snapshot.id}`} type="button" className="snapshot-row" onClick={() => onSelectSnapshot(snapshot.id)}>
{snapshot.id === highlightedId && (
<motion.span className="snapshot-row-flash" aria-hidden="true" style={{ opacity: captureGlow }} />
)}
<span className="snapshot-glyph" aria-hidden="true">◇</span>
<span>
<strong>{formatWhen(snapshot.taken_at)}</strong>
@@ -137,6 +174,6 @@ export function OrbitInspector({
)}
</AnimatePresence>
</div>
</section>
</motion.section>
);
}

View File

@@ -2,13 +2,14 @@ import { motion } from "motion/react";
import { useEffect, useId, useLayoutEffect, useRef, type ReactNode } from "react";
export function HUDPanel({
open, title, subtitle, onClose, children,
open, title, subtitle, onClose, children, inert,
}: {
open: boolean;
title: string;
subtitle?: string;
onClose: () => void;
children: ReactNode;
inert?: boolean;
}) {
const panel = useRef<HTMLElement>(null);
const heading = useRef<HTMLHeadingElement>(null);
@@ -61,7 +62,7 @@ export function HUDPanel({
aria-labelledby={labelId}
aria-describedby={display.subtitle ? descriptionId : undefined}
aria-hidden={!open}
inert={!open}
inert={!open || inert}
initial={false}
animate={{ x: open ? "0%" : "100%" }}
>

View File

@@ -1,14 +1,14 @@
import { animate, motion, useMotionValue, useTransform, useVelocity } from "motion/react";
import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "react";
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { uiSpring } from "../../lib/motion";
export type HUDMode = "scene" | "orbits" | "wormhole" | "decay" | "reconstitute" | "snapshot";
export type HUDMode = "scene" | "orbits" | "wormhole" | "reconstitute" | "snapshot";
const items = [
export const hudItems = [
{ id: "scene", label: "Vault", icon: "M4 9l8-4 8 4v6l-8 4-8-4z M4 9l8 4 8-4 M12 13v6" },
{ id: "orbits", label: "Orbits", icon: "M21 12a9 5 0 1 1-18 0 9 5 0 1 1 18 0z M12 10.5a1.5 1.5 0 1 1 0 3 1.5 1.5 0 1 1 0-3z M18 5h.01" },
{ id: "wormhole", label: "Outposts", icon: "M12 3v3 M4.2 7.5l2.6 1.5 M4.2 16.5 6.8 15 M12 18v3 M17.2 15l2.6 1.5 M17.2 9l2.6-1.5 M15.5 12a3.5 3.5 0 1 1-7 0 3.5 3.5 0 1 1 7 0z" },
{ id: "decay", label: "Retention", icon: "M6 4h12 M6 20h12 M8 4v3l4 5-4 5v3 M16 4v3l-4 5 4 5v3" },
{ id: "reconstitute", label: "Restore", icon: "M4 12a8 8 0 1 1 2.3 5.7 M4 6v6h6 M12 8v4l3 2" },
] as const;
@@ -25,6 +25,7 @@ export function HUDRail({
onSelect: (mode: HUDMode) => void;
}) {
const nav = useRef<HTMLElement>(null);
useScreenTransition(nav, floating, reducedMotion);
const slots = useRef<Slot[]>([]);
const gesture = useRef<Gesture>(undefined);
const suppressClick = useRef(false);
@@ -33,7 +34,7 @@ export function HUDRail({
const velocity = useVelocity(center);
const tail = useTransform(() => center.get() - Math.max(-22, Math.min(22, velocity.get() * 0.032)));
const id = useId();
const activeIndex = Math.max(0, items.findIndex(item => item.id === active));
const activeIndex = Math.max(0, hudItems.findIndex(item => item.id === active));
const snap = useCallback((index: number, immediate = false) => {
const slot = slots.current[index];
@@ -56,11 +57,10 @@ export function HUDRail({
const element = nav.current!;
const buttons = Array.from(element.querySelectorAll("button"));
const measure = () => {
const left = element.getBoundingClientRect().left + element.clientLeft;
const next = buttons.map(button => {
const rect = button.getBoundingClientRect();
return { center: rect.left + rect.width / 2 - left, width: rect.width - 10 };
});
const next = buttons.map(button => ({
center: button.offsetLeft + button.offsetWidth / 2,
width: button.offsetWidth - 10,
}));
const changed = next.some((slot, index) =>
slot.center !== slots.current[index]?.center || slot.width !== slots.current[index]?.width,
);
@@ -115,7 +115,7 @@ export function HUDRail({
Math.abs(slot.center - projected) < Math.abs(slots.current[nearest].center - projected) ? index : nearest,
0);
if (next === activeIndex) snap(activeIndex);
else onSelect(items[next].id);
else onSelect(hudItems[next].id);
}
return (
@@ -144,44 +144,43 @@ export function HUDRail({
}
}}
>
{floating ? (
<svg className="nav-liquid" aria-hidden="true">
<defs>
<filter id={`${id}-goo`} x="-25%" y="-50%" width="150%" height="200%">
<feGaussianBlur in="SourceGraphic" stdDeviation="3.5" result="blur" />
<feColorMatrix in="blur" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -8" result="goo" />
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
<linearGradient id={`${id}-fill`} x2="0%" y2="100%">
<stop stopColor="#724a34" />
<stop offset="100%" stopColor="#38251e" />
</linearGradient>
</defs>
<g filter={`url(#${id}-goo)`} fill={`url(#${id}-fill)`}>
<motion.ellipse cx={reducedMotion ? center : tail} cy="50%" rx="17" ry="13" />
<motion.ellipse cx={center} cy="50%" rx="21" ry="17" />
</g>
</svg>
) : (
<>
<span aria-hidden="true" className="nav-text-dock" />
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }} />
</>
)}
{items.map(({ id, label, icon }) => (
<motion.svg className="nav-liquid" aria-hidden="true" initial={false} animate={{ opacity: floating ? 1 : 0 }}>
<defs>
<filter id={`${id}-goo`} x="-25%" y="-50%" width="150%" height="200%">
<feGaussianBlur in="SourceGraphic" stdDeviation="3.5" result="blur" />
<feColorMatrix in="blur" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -8" result="goo" />
<feComposite in="SourceGraphic" in2="goo" operator="atop" />
</filter>
<linearGradient id={`${id}-fill`} x2="0%" y2="100%">
<stop stopColor="#724a34" />
<stop offset="100%" stopColor="#38251e" />
</linearGradient>
</defs>
<g filter={`url(#${id}-goo)`} fill={`url(#${id}-fill)`}>
<motion.ellipse cx={reducedMotion ? center : tail} cy="50%" rx="17" ry="13" />
<motion.ellipse cx={center} cy="50%" rx="21" ry="17" />
</g>
</motion.svg>
<span aria-hidden="true" className="nav-text-dock" />
<motion.span aria-hidden="true" className="nav-underline" style={{ x: center, width }}
initial={false} animate={{ opacity: floating ? 0 : 1 }} />
{hudItems.map(({ id, label, icon }) => (
<button
key={id}
type="button"
aria-label={floating ? label : undefined}
aria-label={label}
title={floating ? label : undefined}
onClick={() => onSelect(id)}
aria-current={active === id ? "page" : undefined}
>
{floating ? (
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d={icon} />
</svg>
) : label}
<motion.svg className="nav-icon" viewBox="0 0 24 24" width="22" height="22" fill="none"
stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"
initial={false} animate={{ opacity: floating ? 1 : 0 }}>
<path d={icon} />
</motion.svg>
<motion.span className="nav-label" aria-hidden="true" initial={false} animate={{ opacity: floating ? 0 : 1 }}>
{label}
</motion.span>
</button>
))}
</motion.nav>

View File

@@ -0,0 +1,171 @@
import { useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { animate, motion, useMotionValue, useTransform } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
import { gentleSpring, uiSpring } from "../../lib/motion";
import { createVaultSearch, type SearchResult } from "../../lib/vaultSearch";
import { hudItems } from "./HUDRail";
const resultKey = ({ kind, id }: SearchResult) => `${kind}-${id}`;
export function SearchIcon() {
return (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor"
strokeWidth="1.5" strokeLinecap="round" aria-hidden="true">
<circle cx="10.5" cy="10.5" r="5.5" /><path d="m15 15 4 4" />
</svg>
);
}
export function VaultSearch({ open, reducedMotion, orbits, snapshots, orbitStatus, snapshotStatus, onClose, onSelect }: {
open: boolean;
reducedMotion: boolean;
orbits?: Orbit[];
snapshots?: Snapshot[];
orbitStatus?: string;
snapshotStatus?: string;
onClose: () => void;
onSelect: (result: SearchResult) => void;
}) {
const id = useId();
const input = useRef<HTMLInputElement>(null);
const close = useRef<HTMLButtonElement>(null);
const overlay = useRef<HTMLDivElement>(null);
const body = useRef<HTMLDivElement>(null);
const progress = useMotionValue(0);
const y = useTransform(progress, [0, 1], [-12, 0]);
const height = useMotionValue(0);
const [query, setQuery] = useState("");
const [activeId, setActiveId] = useState<string>();
const search = useMemo(() => createVaultSearch(hudItems, orbits, snapshots), [orbits, snapshots]);
const groups = useMemo(() => search(query), [query, search]);
const results = useMemo(() => groups.flatMap(group => group.results), [groups]);
const active = results.find(result => resultKey(result) === activeId) ?? results[0];
const activeKey = active && resultKey(active);
const activeOption = activeKey && `${id}-${encodeURIComponent(activeKey)}`;
useLayoutEffect(() => {
if (!open) return;
setQuery("");
setActiveId(undefined);
input.current?.focus({ preventScroll: true });
const viewport = window.visualViewport;
if (!viewport) return;
const style = overlay.current!.style;
const updateViewport = () => {
style.setProperty("--search-viewport", `${viewport.height}px`);
style.setProperty("--search-viewport-top", `${viewport.offsetTop}px`);
};
updateViewport();
viewport.addEventListener("resize", updateViewport);
viewport.addEventListener("scroll", updateViewport);
return () => {
viewport.removeEventListener("resize", updateViewport);
viewport.removeEventListener("scroll", updateViewport);
};
}, [open]);
useLayoutEffect(() => {
if (reducedMotion) progress.jump(Number(open));
else animate(progress, Number(open), uiSpring);
}, [open, reducedMotion, progress]);
useLayoutEffect(() => {
const element = body.current!;
let target = element.offsetHeight;
height.jump(target);
const observer = new ResizeObserver(() => {
const next = element.offsetHeight;
if (next === target) return;
target = next;
if (reducedMotion) height.jump(next);
else animate(height, next, gentleSpring);
});
observer.observe(element);
return () => observer.disconnect();
}, [height, reducedMotion]);
useLayoutEffect(() => () => {
progress.stop();
height.stop();
}, [progress, height]);
useLayoutEffect(() => {
if (!open) return;
if (activeKey !== activeId) setActiveId(activeKey);
if (activeOption) document.getElementById(activeOption)?.scrollIntoView({ block: "nearest" });
}, [open, activeId, activeKey, activeOption, results]);
function handleKeys(event: KeyboardEvent) {
if (event.key === "Tab") {
event.preventDefault();
(event.target === input.current ? close.current : input.current)?.focus();
return;
}
if (event.target !== input.current || event.nativeEvent.isComposing || event.keyCode === 229) return;
if (event.key === "Enter" && active && !event.repeat) {
event.preventDefault();
onSelect(active);
} else if ((event.key === "ArrowDown" || event.key === "ArrowUp") && results.length) {
event.preventDefault();
const offset = event.key === "ArrowDown" ? 1 : -1;
const next = results[(results.indexOf(active) + offset + results.length) % results.length];
setActiveId(resultKey(next));
}
}
return (
<motion.div ref={overlay} className="search-overlay" inert={!open} style={{ opacity: progress }} onClick={event => {
if (event.target === event.currentTarget) onClose();
}}>
<motion.section className="search-panel" style={{ y }} role="dialog" aria-modal="true" aria-label="Vault search" onKeyDown={handleKeys}>
<div className="search-field">
<SearchIcon />
<input ref={input} type="text" role="combobox" aria-label="Search vault"
aria-autocomplete="list" aria-expanded={!!results.length} aria-controls={`${id}-results`}
aria-activedescendant={activeOption}
autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="Search the vault…"
value={query} onChange={event => {
setQuery(event.currentTarget.value);
setActiveId(undefined);
}} />
<button ref={close} className="console-control search-close" type="button" aria-label="Close search" onClick={onClose}>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor"
strokeWidth="1.5" strokeLinecap="round" aria-hidden="true"><path d="m7 7 10 10M17 7 7 17" /></svg>
</button>
</div>
<motion.div className="search-list-frame" style={{ height }}>
<div ref={body} className="search-body">
<div role="listbox" id={`${id}-results`} aria-label="Search results" hidden={!results.length}>
{groups.map(group => (
<div key={group.label} role="group" aria-label={group.label}>
<p className="instrument-label search-group" aria-hidden="true">{group.label}</p>
{group.results.map(result => {
const key = resultKey(result);
const icon = result.kind === "navigation" ? result.icon
: result.kind === "orbit" ? hudItems[1].icon : "M12 3l8 9-8 9-8-9z M12 9v6";
return (
<div key={key} id={`${id}-${encodeURIComponent(key)}`} role="option" className="search-result"
aria-selected={activeKey === key} onMouseDown={event => event.preventDefault()} onClick={() => onSelect(result)}>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor"
strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={icon} /></svg>
<span className="search-result-text">
<span>{result.label}</span>
{result.detail && <small>{result.detail}</small>}
</span>
</div>
);
})}
</div>
))}
</div>
<p className="search-status" role="status">
<span>{results.length ? `${results.length} ${query.trim() ? "results shown" : "destinations"}` : "No matching results."}</span>
{orbitStatus && <span>{orbitStatus}</span>}
{snapshotStatus && <span>{snapshotStatus}</span>}
</p>
</div>
</motion.div>
</motion.section>
</motion.div>
);
}

View File

@@ -0,0 +1,82 @@
import { useState, type FormEvent, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { fetchOperatorSession, loginOperator, logoutOperator } from "../../api";
import { Button } from "../ui/Button";
export function OperatorGate({
children,
}: {
children: (operator: { actor?: string; onLogout?: () => Promise<void> }) => ReactNode;
}) {
const queryClient = useQueryClient();
const session = useQuery({
queryKey: ["operator-session"],
queryFn: ({ signal }) => fetchOperatorSession(signal),
refetchInterval: 15_000,
retry: false,
});
const [pending, setPending] = useState(false);
const [error, setError] = useState<string>();
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const form = event.currentTarget;
const password = new FormData(form).get("password");
if (pending || typeof password !== "string" || !password) return;
setPending(true);
setError(undefined);
form.reset();
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
try {
const signedIn = await loginOperator(password);
queryClient.setQueryData(["operator-session"], signedIn);
} catch {
setError("Could not sign in. Check the password or try again shortly.");
} finally {
setPending(false);
}
}
if (session.isSuccess && session.data.authorized) {
const actor = session.data.actor ?? undefined;
return children({
actor,
onLogout: actor ? async () => {
await queryClient.cancelQueries({ queryKey: ["operator-session"] });
await logoutOperator();
queryClient.setQueryData(["operator-session"], {
login_enabled: true, authorized: false, actor: null, csrf: null,
});
queryClient.removeQueries({ predicate: (query) => query.queryKey[0] !== "operator-session" });
} : undefined,
});
}
return (
<main className="vault-app flex min-h-screen items-center justify-center p-5">
<section className="w-full max-w-sm rounded-2xl border border-space-700 bg-space-900 p-6 sm:p-8">
<p className="instrument-label mb-3">Tessera / Backup control</p>
<h1 className="text-2xl font-semibold text-star-100">Operator sign-in</h1>
{session.isPending ? <p role="status" className="mt-4 text-star-300">Connecting to the hub…</p>
: session.isError ? (
<div className="mt-4 space-y-3">
<p role="alert" className="text-star-300">Could not reach the hub.</p>
<Button onClick={() => void session.refetch()}>Try again</Button>
</div>
) : session.data.login_enabled ? (
<form onSubmit={submit} className="mt-5 space-y-4">
<label className="block text-sm text-star-300">
Operator password
<input type="password" name="password" autoComplete="current-password" required
maxLength={1024} className="mt-1 block w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100" />
</label>
{error && <p role="alert" className="text-sm text-orbit-red">{error}</p>}
<Button type="submit" variant="primary" className="w-full" disabled={pending}>
{pending ? "Signing in…" : "Sign in"}
</Button>
</form>
) : <p className="mt-4 text-star-300">Browser sign-in is disabled on this hub.</p>}
</section>
</main>
);
}

View File

@@ -0,0 +1,65 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { registerCaptureProfile, type BackupSource, type CaptureProfile } from "../../api";
import { OutpostField } from "../outposts/OutpostField";
import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState";
const field = "mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2";
const uuidPattern = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
export function CaptureProfileForm({ orbitId, source, onClose }: { orbitId: string; source: BackupSource | null; onClose: () => void }) {
const [initialId] = useState(() => globalThis.crypto?.randomUUID?.() ?? "");
const qc = useQueryClient();
const register = useMutation({
mutationFn: registerCaptureProfile,
onSuccess: async () => {
await Promise.all([
qc.invalidateQueries({ queryKey: ["capture-profiles"] }),
qc.invalidateQueries({ queryKey: ["orbits"] }),
]);
onClose();
},
});
return (
<form className="mt-4 space-y-3 border-t border-space-700 pt-3" onSubmit={(event) => {
event.preventDefault();
if (register.isPending) return;
const data = new FormData(event.currentTarget);
const time = String(data.get("time"));
const [hour, minute] = time.split(":").map(Number);
register.mutate({
application_id: String(data.get("application")),
orbit_id: orbitId,
outpost_id: String(data.get("outpost")),
format: source === "filesystem" ? "filesystem" : data.get("format") as CaptureProfile["format"],
schedule: time ? { hour, minute, timezone: "UTC" } : undefined,
});
}}>
<h4 className="font-medium text-star-100">Register Outpost backup profile</h4>
<label className="block text-sm text-star-300">
Application UUID
<input name="application" defaultValue={initialId} required pattern={uuidPattern} className={field} />
</label>
<OutpostField className={field} />
{source !== "filesystem" && <label className="block text-sm text-star-300">
Database engine
<select name="format" className={field}>
<option value="postgres_sql">PostgreSQL</option>
<option value="mysql_sql">MySQL</option>
</select>
</label>}
<label className="block text-sm text-star-300">
Daily backup time (UTC, optional)
<input name="time" type="time" className={field} />
</label>
<Hint>Use the same application UUID in the agent’s local capture configuration. Set the source and Restic repository there before queueing a backup.</Hint>
{register.isError && <p role="alert" className="text-sm text-orbit-red">Could not register the profile. Check that the UUID is unused and the Outpost is paired.</p>}
<div className="flex gap-2">
<Button type="button" disabled={register.isPending} onClick={onClose}>Cancel</Button>
<Button type="submit" variant="primary" disabled={register.isPending}>Register profile</Button>
</div>
</form>
);
}

View File

@@ -0,0 +1,120 @@
import { useId, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { enqueueCapture, fetchCaptureEvents, fetchCaptureJobs, fetchSnapshots, type CaptureProfile, type Orbit } from "../../api";
import { formatWhen } from "../../lib/format";
import { Button } from "../ui/Button";
const labels: Record<string, string> = {
queued: "Waiting for outpost",
claimed: "Assigned to agent",
dumping: "Preparing source",
uploading: "Saving backup",
dump_failed: "Source preparation failed or timed out",
upload_failed: "Backup transfer failed",
completed: "Backup completed",
};
const input = "mt-1 block w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100";
export function JobHistory({
profiles, orbits, snapshots, onOpenSnapshot,
}: {
profiles: CaptureProfile[];
orbits: Orbit[];
snapshots?: ReadonlySet<string>;
onOpenSnapshot: (id: string) => void;
}) {
const filters = useId();
const [application, setApplication] = useState("");
const [status, setStatus] = useState("");
const [selected, setSelected] = useState<string>();
const qc = useQueryClient();
const name = (profile: CaptureProfile) =>
orbits.find((orbit) => orbit.id === profile.orbit_id)?.name ?? profile.application_id;
const jobs = useQuery({
queryKey: ["capture-jobs", application, status],
queryFn: () => fetchCaptureJobs(application, status),
refetchInterval: 3_000,
});
const events = useQuery({
queryKey: ["capture-events", selected],
queryFn: () => fetchCaptureEvents(selected!),
enabled: !!selected,
refetchInterval: 3_000,
});
const enqueue = useMutation({
mutationFn: enqueueCapture,
onSuccess: (job) => {
setStatus("");
setSelected(job.id);
void qc.invalidateQueries({ queryKey: ["capture-jobs"] });
},
});
return (
<section className="mb-6 space-y-4 rounded-2xl border border-space-700 bg-space-800/50 p-4">
<div>
<h3 className="font-semibold text-star-100">Outpost backup jobs</h3>
<p className="mt-1 text-sm text-star-300">Jobs wait for the assigned outpost when it is offline.</p>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<div>
<label className="text-sm text-star-300" htmlFor={`${filters}-application`}>Application</label>
<select id={`${filters}-application`} className={input} value={application} onChange={(event) => setApplication(event.target.value)}>
<option value="">All applications</option>
{profiles.map((profile) => <option key={profile.application_id} value={profile.application_id}>{name(profile)}</option>)}
</select>
</div>
<div>
<label className="text-sm text-star-300" htmlFor={`${filters}-status`}>Job status</label>
<select id={`${filters}-status`} className={input} value={status} onChange={(event) => setStatus(event.target.value)}>
<option value="">Any status</option>
<option value="queued">Queued</option>
<option value="running">Running</option>
<option value="completed">Completed</option>
<option value="failed">Failed</option>
</select>
</div>
</div>
<Button variant="success" disabled={!application || enqueue.isPending}
onClick={() => enqueue.mutate(application)}>
{enqueue.isPending ? "Queueing…" : "Back up selected application"}
</Button>
{enqueue.isError && <p role="alert" className="text-sm text-orbit-red">Could not queue the backup.</p>}
{enqueue.isSuccess && <p role="status" className="text-sm text-star-300">Backup queued.</p>}
{jobs.isPending && <p role="status" className="text-sm text-star-300">Loading jobs…</p>}
{jobs.isError && <p role="alert" className="text-sm text-orbit-red">Job history is unavailable.</p>}
{jobs.data?.length === 0 && <p className="text-sm text-star-300">No jobs match these filters.</p>}
<ul className="space-y-2">
{jobs.data?.map((job) => (
<li key={job.id} className="rounded-xl border border-space-700 px-3 py-2">
<button type="button" aria-expanded={selected === job.id}
className="flex w-full flex-wrap items-center justify-between gap-2 py-1 text-left text-sm text-star-100"
onClick={() => setSelected(selected === job.id ? undefined : job.id)}>
<strong>{name(job.profile)}</strong>
<span className={job.status === "failed" ? "text-orbit-red" : "text-star-300"}>{labels[job.phase] ?? job.status}</span>
</button>
{selected === job.id && (
<div className="mt-2 space-y-2 border-t border-space-700 pt-2 text-xs text-star-300">
<p>Queued by {job.actor} · {formatWhen(new Date(job.created_at * 1000).toISOString())}</p>
{job.offsite_status && <p>Off-site copy {job.offsite_status}</p>}
{events.isError && <p role="alert">Could not load job events.</p>}
<ol className="space-y-1">
{events.data?.map((event, i) => <li key={i}>{labels[event.phase] ?? event.phase}</li>)}
</ol>
{job.snapshot_id && (snapshots?.has(job.snapshot_id) ? (
<Button onClick={async () => {
const catalog = await qc.fetchQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots })
.catch(() => undefined);
const available = catalog?.find(({ id }) => id === job.snapshot_id);
if (available) onOpenSnapshot(available.id);
}}>Open snapshot</Button>
) : <p>{snapshots ? "Snapshot is no longer in the catalog." : "Snapshot availability unknown."}</p>)}
</div>
)}
</li>
))}
</ul>
</section>
);
}

View File

@@ -1,9 +1,11 @@
import { useState, type ReactNode } from "react";
import { AnimatePresence } from "motion/react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Orbit } from "../../api";
import { createOrbit, updateOrbitRetention } from "../../api";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { BackupAccess, BackupSource, Orbit, Snapshot } from "../../api";
import { createOrbit, fetchCaptureProfiles, updateOrbitRetention } from "../../api";
import { orbitStatus, schedulePhrase } from "../../lib/format";
import { CaptureProfileForm } from "./CaptureProfileForm";
import { JobHistory } from "./JobHistory";
import { describeRetention, retentionDraft, RetentionFields, retentionSettings } from "./RetentionFields";
import { Button } from "../ui/Button";
import { OrbitStatusDot } from "../ui/StatusDot";
@@ -12,16 +14,24 @@ import { Hint } from "../ui/EmptyState";
import { SpringPane } from "../ui/SpringPane";
export function OrbitsView({
orbits, onRun, captureDisabled, notice,
orbits, snapshots, onRun, onOpenSnapshot, captureDisabled, notice,
}: {
orbits: Orbit[];
snapshots?: Snapshot[];
onRun: (orbit: Orbit) => void;
onOpenSnapshot: (id: string) => void;
captureDisabled: boolean;
notice?: ReactNode;
}) {
const [editing, setEditing] = useState(false);
const qc = useQueryClient();
const profiles = useQuery({ queryKey: ["capture-profiles"], queryFn: fetchCaptureProfiles });
const [name, setName] = useState("nightly-docs");
const [source, setSource] = useState<BackupSource>("filesystem");
const [access, setAccess] = useState<BackupAccess>("hub");
const [engine, setEngine] = useState<"postgres" | "mysql">("postgres");
const viaOutpost = access === "outpost";
const [profileOrbit, setProfileOrbit] = useState<string>();
const [path, setPath] = useState("./docs");
const [retention, setRetention] = useState(() => retentionDraft());
const [editingRetention, setEditingRetention] = useState<string | null>(null);
@@ -29,20 +39,31 @@ export function OrbitsView({
const [schedule, setSchedule] = useState("0 2 * * *");
const create = useMutation({
mutationFn: () => {
mutationFn: (data: FormData) => {
const settings = retentionSettings(retention);
if (!settings) throw new Error("Invalid retention policy");
return createOrbit({
name,
provider: "filesystem",
paths: [path],
schedule: schedule || undefined,
const orbit = {
name: name.trim(),
schedule: viaOutpost ? undefined : schedule.trim() || undefined,
...settings,
dry_run: rehearse,
});
dry_run: !viaOutpost && rehearse,
};
if (access === "outpost") return createOrbit({ ...orbit, source, access, provider_config: {} });
if (source === "filesystem") {
return createOrbit({ ...orbit, source, access, provider_config: { paths: [path.trim()] } });
}
const field = (key: string) => String(data.get(key) ?? "").trim();
const caFile = field("ca_file");
return createOrbit({ ...orbit, source, access, provider_config: {
engine, ...(engine === "mysql" ? { transport: "direct" } : {}),
host: field("host"), ...(field("port") ? { port: Number(field("port")) } : {}),
database: field("database"), user: field("user"), password_file: field("password_file"),
...(caFile ? { tls: { mode: engine === "postgres" ? "verify_full_with_ca" : "verify_identity_with_ca", ca_file: caFile } } : {}),
} });
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["orbits"] });
onSuccess: (orbit) => {
void qc.invalidateQueries({ queryKey: ["orbits"] });
if (orbit.access === "outpost") setProfileOrbit(orbit.id);
setEditing(false);
},
});
@@ -50,6 +71,12 @@ export function OrbitsView({
return (
<div>
{notice}
{profiles.isError && <p role="alert" className="mb-4 text-sm text-orbit-red">Outpost backup profiles are unavailable.</p>}
<JobHistory profiles={profiles.data ?? []} orbits={orbits}
snapshots={snapshots && new Set(snapshots.map(({ id }) => id))} onOpenSnapshot={onOpenSnapshot} />
{profiles.data?.length === 0 && <p className="mb-4 text-sm text-star-300">
Register an Outpost capture profile to start queueing jobs.
</p>}
<div className="space-y-3 mb-6">
{orbits.map((o) => (
@@ -62,7 +89,10 @@ export function OrbitsView({
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-star-100 truncate">{o.name}</h3>
<p className="text-sm text-star-300">{orbitStatus(o.last_status).label}</p>
<p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o.schedule, o.dry_run)}</p>
<p className="text-xs text-star-400">
{o.source === "filesystem" ? "Filesystem / Folder" : o.source === "database" ? "Database" : "Backup"} · {o.access === "outpost" ? "Via Outpost" : "Via Hub"}
</p>
<p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o)}</p>
<p className="text-xs text-star-400 mt-0.5">{describeRetention(o)}</p>
{o.dry_run && (
<span className="inline-block mt-2 text-[10px] uppercase tracking-wider text-orbit-amber border border-orbit-amber/30 rounded px-2 py-0.5">
@@ -75,17 +105,22 @@ export function OrbitsView({
<Button
variant="success"
className="flex-1 text-xs py-2"
disabled={captureDisabled || orbitStatus(o.last_status).busy}
disabled={(o.access === "outpost" && !o.application_id) || captureDisabled || orbitStatus(o.last_status).busy}
onClick={() => onRun(o)}
>
{o.dry_run ? "Rehearse" : "Capture now"}
{o.application_id ? "Queue backup" : o.access === "outpost" ? "Outpost capture" : o.dry_run ? "Rehearse" : "Capture now"}
</Button>
<Button className="flex-1 text-xs py-2" onClick={() => setEditingRetention(o.id)}
disabled={editingRetention === o.id}>
disabled={editingRetention === o.id || o.retention_source === "profile"}>
Edit retention
</Button>
</div>
{editingRetention === o.id && <OrbitRetentionEditor orbit={o} onClose={() => setEditingRetention(null)} />}
{o.access === "outpost" && !o.dry_run && !o.application_id && (
profileOrbit === o.id
? <CaptureProfileForm key={o.id} orbitId={o.id} source={o.source} onClose={() => setProfileOrbit(undefined)} />
: <Button className="mt-3" onClick={() => setProfileOrbit(o.id)}>Register Outpost backup profile</Button>
)}
<TelemetryPanel>
{JSON.stringify(o, null, 2)}
</TelemetryPanel>
@@ -97,55 +132,94 @@ export function OrbitsView({
<AnimatePresence initial={false}>
{editing ? (
<SpringPane key="form">
<div className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3">
<form className="rounded-2xl border border-wormhole-violet/30 bg-space-900 p-4 space-y-3"
onSubmit={(event) => { event.preventDefault(); if (!create.isPending) create.mutate(new FormData(event.currentTarget)); }}>
<h3 className="font-medium text-star-100">New orbit</h3>
<label className="block text-sm">
<span className="text-star-400">Name</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={name}
required value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<label className="block text-sm">
<span className="text-star-400">Folder path</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
value={path}
onChange={(e) => setPath(e.target.value)}
/>
<span className="text-star-400">Backup source</span>
<select className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={source} onChange={(event) => setSource(event.target.value as BackupSource)}>
<option value="filesystem">Filesystem / Folder</option>
<option value="database">Database</option>
</select>
</label>
<label className="block text-sm">
<span className="text-star-400">Schedule (cron)</span>
<span className="text-star-400">Access</span>
<select className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={access} onChange={(event) => setAccess(event.target.value as BackupAccess)}>
<option value="hub">Via Hub</option>
<option value="outpost">Via Outpost</option>
</select>
</label>
{!viaOutpost && source === "filesystem" && <label className="block text-sm">
<span className="text-star-400">Folder path visible to the hub</span>
<input className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
required value={path} onChange={(e) => setPath(e.target.value)} />
</label>}
{!viaOutpost && source === "database" && <>
<label className="block text-sm text-star-400">
Database engine
<select className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
value={engine} onChange={(event) => setEngine(event.target.value as typeof engine)}>
<option value="postgres">PostgreSQL</option>
<option value="mysql">MySQL</option>
</select>
</label>
{[
["host", "Database host"], ["port", "Port (optional)"], ["database", "Database name"],
["user", "Database user"], ["password_file", "Absolute password file path on hub"],
["ca_file", "CA certificate path on hub (optional)"],
].map(([key, label]) => <label key={key} className="block text-sm text-star-400">
{label}
<input name={key} required={key !== "port" && key !== "ca_file"} type={key === "port" ? "number" : "text"}
min={key === "port" ? 1 : undefined} max={key === "port" ? 65535 : undefined}
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2" />
</label>)}
</>}
{!viaOutpost && <label className="block text-sm">
<span className="text-star-400">Schedule (cron, UTC)</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2 font-mono text-xs"
value={schedule}
onChange={(e) => setSchedule(e.target.value)}
/>
</label>
<RetentionFields draft={retention} onChange={setRetention} />
<label className="flex items-center gap-2 text-sm text-star-300">
<input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} />
Rehearse only (dry run)
</label>
<Hint>
Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”.
</Hint>
{create.isError && <p role="alert" className="text-sm text-orbit-red">The orbit could not be saved.</p>}
<span className="text-xs text-star-400">Leave blank for manual capture. Use weekday names such as MON to avoid ambiguity.</span>
</label>}
{viaOutpost && <Hint>After saving, assign a paired Outpost and schedule. Configure the source and Restic repository on the agent.</Hint>}
<RetentionFields draft={retention} onChange={setRetention} managed={viaOutpost} />
{!viaOutpost && <div className="space-y-1">
<label className="flex items-center gap-2 text-sm text-star-300">
<input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} />
Rehearse only (dry run)
</label>
<p className="text-xs text-star-400">A rehearsal never prunes snapshots.</p>
</div>}
{create.isError && <p role="alert" className="text-sm text-orbit-red">{create.error.message}</p>}
<div className="flex gap-2">
<Button className="flex-1" onClick={() => setEditing(false)}>
<Button type="button" className="flex-1" disabled={create.isPending} onClick={() => {
setEditing(false);
create.reset();
}}>
Cancel
</Button>
<Button
variant="primary"
className="flex-1"
disabled={create.isPending || !retentionSettings(retention)}
onClick={() => create.mutate()}
type="submit"
disabled={create.isPending || !name.trim() || !retentionSettings(retention)}
>
Save orbit
</Button>
</div>
</div>
</form>
</SpringPane>
) : (
<SpringPane key="add">
@@ -176,8 +250,10 @@ function OrbitRetentionEditor({ orbit, onClose }: { orbit: Orbit; onClose: () =>
e.preventDefault();
if (settings && !save.isPending) save.mutate(settings);
}}>
<RetentionFields draft={draft} onChange={setDraft} />
<Hint>Changes apply after the next successful capture.</Hint>
<RetentionFields draft={draft} onChange={setDraft} managed={!!orbit.application_id} />
<Hint>{orbit.application_id
? "Managed backups use custom GFS counts or the managed default. Changes apply after the next successful capture."
: "Changes apply after the next successful capture. A rehearsal never prunes snapshots."}</Hint>
{save.isError && <p role="alert" className="text-sm text-orbit-red">Retention could not be saved.</p>}
<div className="flex gap-2">
<Button type="button" className="flex-1" disabled={save.isPending} onClick={onClose}>Cancel</Button>

View File

@@ -36,25 +36,38 @@ export function retentionSettings({ preset, counts }: Draft): RetentionSettings
}
export function describeRetention(orbit: Orbit): string {
if (orbit.capture_retention) {
const policy = orbit.capture_retention;
const source = orbit.retention_source === "profile" ? "Capture profile" : "Managed default";
const description = policy.mode === "age"
? `Keep ${policy.days} days and always keep the newest`
: `Keep ${policy.keep} most recent`;
return `${description} · ${source}`;
}
if (orbit.retention) {
const policy = orbit.retention;
return tiers.map(([key, label]) => `${policy[key]} ${label.toLowerCase()}`).join(" · ");
return tiers.map(([key, label]) => `${policy[key]} ${label.toLowerCase()}`).join(" · ") + " · Orbit policy";
}
const preset = orbit.decay_preset ?? DECAY_PRESETS[0].id;
return DECAY_PRESETS.find((item) => item.id === preset)?.title ?? preset;
}
export function RetentionFields({ draft, onChange }: { draft: Draft; onChange: (draft: Draft) => void }) {
export function RetentionFields({ draft, onChange, managed = false }: {
draft: Draft; onChange: (draft: Draft) => void; managed?: boolean;
}) {
const invalid = !retentionSettings(draft);
return (
<div className="space-y-3">
<label className="block text-sm">
<span className="text-star-400">Retention</span>
<select className={inputClass} value={draft.preset} onChange={(e) => onChange({ ...draft, preset: e.target.value })}>
{!DECAY_PRESETS.some((item) => item.id === draft.preset) && draft.preset !== "custom" && (
<option value={draft.preset}>{draft.preset}</option>
)}
{DECAY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.title}</option>)}
<select className={inputClass} value={managed && draft.preset !== "custom" ? DECAY_PRESETS[0].id : draft.preset}
onChange={(e) => onChange({ ...draft, preset: e.target.value })}>
{managed ? <option value={DECAY_PRESETS[0].id}>Managed default</option> : <>
{!DECAY_PRESETS.some((item) => item.id === draft.preset) && draft.preset !== "custom" && (
<option value={draft.preset}>{draft.preset}</option>
)}
{DECAY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.title}</option>)}
</>}
<option value="custom">Custom (GFS)</option>
</select>
</label>

View File

@@ -0,0 +1,18 @@
import { useQuery } from "@tanstack/react-query";
import { fetchOutposts } from "../../api";
export function OutpostField({ className }: { className: string }) {
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
const paired = outposts.data?.filter((outpost) => outpost.pairing_state === "active");
return (
<label className="block text-sm text-star-300">
Assigned Outpost
<select name="outpost" required className={className} defaultValue="">
<option value="">Choose a paired Outpost</option>
{paired?.map(({ id, name }) => <option key={id} value={id}>{name || "Outpost"} · {id}</option>)}
</select>
{outposts.isError && <span role="alert">Could not load paired Outposts.</span>}
{paired?.length === 0 && <span>Pair an agent in Outposts first.</span>}
</label>
);
}

View File

@@ -1,6 +1,7 @@
import { useMutation } from "@tanstack/react-query";
import { useMutation, useQuery } from "@tanstack/react-query";
import { motion } from "motion/react";
import { startPairing } from "../../api";
import { fetchOutposts, startPairing } from "../../api";
import { formatWhen } from "../../lib/format";
import { useReducedMotion } from "../../hooks/useReducedMotion";
import { ambientPulse } from "../../lib/motion";
import { Button } from "../ui/Button";
@@ -19,6 +20,7 @@ export function WormholeView({
onSuccess: onPaired,
});
const reducedMotion = useReducedMotion();
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
const expires = pairing ? new Date(pairing.expires_at).toLocaleTimeString() : "";
@@ -44,7 +46,7 @@ export function WormholeView({
<p className="text-sm text-star-400 mt-4">Burns at {expires}</p>
<Hint>
On the outpost:{" "}
<code className="font-mono text-orbit-amber">tessera-agent pair {pairing.code}</code>
<code className="font-mono text-orbit-amber">tessera-agent --hub-url {window.location.origin} --credentials wormhole.json pair {pairing.code}</code>
</Hint>
<Button variant="ghost" className="mt-4 w-full" onClick={() => gen.mutate()}>
Generate fresh code
@@ -57,13 +59,21 @@ export function WormholeView({
<section className="mt-8 space-y-3">
<h3 className="text-sm font-medium text-star-200">Outpost health</h3>
<div className="rounded-xl border border-space-700 bg-space-800/40 p-4 flex items-center gap-3">
<span className="w-2 h-2 rounded-full bg-star-400/50" />
<div>
<p className="text-sm text-star-300">No outposts paired yet</p>
<p className="text-xs text-star-400">Grey dot means offline or waiting.</p>
</div>
</div>
{outposts.isPending && <p role="status" className="text-sm text-star-300">Loading paired outposts…</p>}
{outposts.isError && <p role="alert" className="text-sm text-orbit-red">Could not read outpost health.</p>}
{outposts.data?.length === 0 && <p className="text-sm text-star-300">No outposts paired yet.</p>}
{outposts.data?.map((outpost) => {
const online = outpost.last_seen && Date.now() - Date.parse(outpost.last_seen) < 120_000;
return (
<div key={outpost.id} className="flex items-center gap-3 rounded-xl border border-space-700 bg-space-800/40 p-4">
<span aria-hidden="true" className={`register-signal signal-${online ? "green" : "grey"}`} />
<div className="min-w-0">
<p className="break-words text-sm text-star-100">{outpost.name || "Outpost"}</p>
<p className="text-xs text-star-400">{outpost.last_seen ? `Last activity ${formatWhen(outpost.last_seen)}` : "No agent activity recorded"} · {outpost.id}</p>
</div>
</div>
);
})}
</section>
</div>
);
@@ -77,6 +87,7 @@ function EmptyWormhole({
loading: boolean;
}) {
const reducedMotion = useReducedMotion();
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
return (
<div className="text-center py-8">
<div className="relative mx-auto w-24 h-24 rounded-full border border-wormhole-violet/30 flex items-center justify-center text-3xl">

View File

@@ -0,0 +1,154 @@
import { useId, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { cancelRestore, enqueueRestore, fetchOutposts, fetchRestoreJobs, fetchRestoreTargets, reconcileRestore, type RestoreJob, type RestoreTarget } from "../../api";
import { RestoreTargetForm } from "./RestoreTargetForm";
import { Button } from "../ui/Button";
const field = "mt-1 w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100";
const phases: Record<string, string> = {
queued: "Waiting for outpost",
claimed: "Assigned to agent",
checking: "Verifying archive and target",
safety: "Creating safety backup",
ready: "Safety backup verified",
applying: "Applying restore",
completed: "Restore complete",
wrong_target: "Target identity verification failed",
invalid_payload: "Archive verification failed",
safety_failed: "Safety backup could not be verified",
apply_failed: "Apply failed. Recovery required.",
lease_lost: "Agent disconnected during apply. Recovery required.",
reconciled: "Recovery verified by operator",
cancelled: "Cancelled",
};
export function DatabaseRestore({ snapshot, application, engine }: {
snapshot: string; application: string; engine: RestoreTarget["engine"];
}) {
const fieldId = useId();
const query = useQueryClient();
const [target, setTarget] = useState("");
const [confirmation, setConfirmation] = useState("");
const [registering, setRegistering] = useState(false);
const targets = useQuery({
queryKey: ["restore-targets", snapshot],
queryFn: () => fetchRestoreTargets(snapshot),
refetchInterval: 5_000,
});
const outposts = useQuery({ queryKey: ["outposts"], queryFn: fetchOutposts, refetchInterval: 5_000 });
const targetLabel = (entry: RestoreTarget) => {
const name = outposts.data?.find(({ id }) => id === entry.outpost_id)?.name;
return `${entry.name} · ${entry.identity.database} · ${name || entry.outpost_id}`;
};
const selected = targets.isSuccess
? targets.data.find((entry) => entry.id === target && !entry.ineligible_reason)
: undefined;
const jobs = useQuery({
queryKey: ["restore-jobs", snapshot],
queryFn: () => fetchRestoreJobs(snapshot),
refetchInterval: 2_000,
});
const refresh = () => void query.invalidateQueries({ queryKey: ["restore-jobs", snapshot] });
const submit = useMutation({
mutationFn: () => enqueueRestore(snapshot, target, confirmation),
onSuccess: (job) => {
query.setQueryData<RestoreJob[]>(["restore-jobs", snapshot],
(previous) => [job, ...(previous ?? []).filter(({ id }) => id !== job.id)]);
setConfirmation("");
refresh();
},
});
const required = `RESTORE ${snapshot} TO ${target}`;
return (
<section className="space-y-4 rounded-xl border border-space-700 bg-space-800/50 p-4">
<h3 className="font-semibold text-star-100">Database restore</h3>
{targets.isPending && <p role="status" className="text-sm text-star-300">Loading registered targets…</p>}
{targets.isError && <p role="alert" className="text-sm text-orbit-red">Could not read restore targets.</p>}
{targets.data?.length === 0 && <p className="text-sm text-star-300">This application has no registered restore targets.</p>}
{registering
? <RestoreTargetForm application={application} engine={engine} onClose={() => setRegistering(false)} />
: <Button type="button" onClick={() => setRegistering(true)}>Register restore target</Button>}
{targets.data?.length && !targets.data.some((entry) => !entry.ineligible_reason)
? <p className="text-sm text-star-300">No registered targets are eligible for this snapshot.</p>
: null}
{!!targets.data?.length && (
<form className="space-y-3" onSubmit={(event) => {
event.preventDefault();
if (selected && confirmation === required && !submit.isPending) submit.mutate();
}}>
<label htmlFor={fieldId} className="block text-sm text-star-300">Registered target</label>
<select id={fieldId} className={field} value={target}
onChange={(event) => { setTarget(event.target.value); setConfirmation(""); }}>
<option value="">Choose a target</option>
{targets.data.map((entry) => (
<option key={entry.id} value={entry.id} disabled={!!entry.ineligible_reason}>
{targetLabel(entry)}{entry.ineligible_reason ? ` · ${entry.ineligible_reason}` : ""}
</option>
))}
</select>
{selected && <>
<p className="break-words text-sm text-star-100">
Restore to {selected.identity.database} on {outposts.data?.find(({ id }) => id === selected.outpost_id)?.name || "Outpost"} ({selected.outpost_id})
· {selected.engine} instance {selected.identity.instance}
</p>
<p className="text-sm text-star-300">The agent will verify the target and save a safety backup before applying this snapshot.</p>
<label className="block text-sm text-star-300">
Confirmation
<code className="my-1 block break-all text-xs text-star-100">{required}</code>
<input aria-label="Restore confirmation" className={field} value={confirmation} autoComplete="off"
onChange={(event) => setConfirmation(event.target.value)} />
</label>
</>}
<Button type="submit" variant="warn" disabled={!selected || confirmation !== required || submit.isPending}>
{submit.isPending ? "Queueing…" : "Queue database restore"}
</Button>
{submit.isError && <p role="alert" className="text-sm text-orbit-red">Restore could not be queued. Verify the selected target and confirmation.</p>}
</form>
)}
{jobs.isError && <p role="alert" className="text-sm text-orbit-red">Restore history is unavailable.</p>}
{!!jobs.data?.length && (
<ul className="space-y-2">
{jobs.data.map((job) => <RestoreStatus key={job.id} job={job} destination={targetLabel(job.target)} refresh={refresh} />)}
</ul>
)}
</section>
);
}
function RestoreStatus({ job, destination, refresh }: { job: RestoreJob; destination: string; refresh: () => void }) {
const [acknowledgement, setAcknowledgement] = useState("");
const required = `RECONCILE ${job.id}`;
const cancel = useMutation({ mutationFn: () => cancelRestore(job.id), onSuccess: refresh });
const reconcile = useMutation({
mutationFn: () => reconcileRestore(job.id, acknowledgement), onSuccess: refresh,
});
return (
<li className="space-y-2 rounded-xl border border-space-700 p-3 text-sm">
<strong className="text-star-100">{destination}</strong>
<p role="status" className={job.status === "recovery_required" || job.status === "failed" ? "text-orbit-red" : "text-star-300"}>
{phases[job.phase] ?? job.status}
</p>
{job.safety_snapshot_id && (
<a className="break-all text-orbit-amber underline" href={`/api/v1/snapshots/${job.safety_snapshot_id}/download`} download>
Safety backup {job.safety_snapshot_id}
</a>
)}
{(job.status === "queued" || job.status === "running") && (
<div><Button disabled={cancel.isPending} onClick={() => cancel.mutate()}>Cancel queued restore</Button></div>
)}
{job.status === "recovery_required" && (
<div className="space-y-2">
<label className="block text-star-300">
Verify the target data before releasing its lock.
<code className="my-1 block break-all text-xs text-star-100">{required}</code>
<input aria-label="Reconciliation confirmation" className={field} value={acknowledgement}
onChange={(event) => setAcknowledgement(event.target.value)} />
</label>
<Button variant="warn" disabled={acknowledgement !== required || reconcile.isPending}
onClick={() => reconcile.mutate()}>Mark target recovered</Button>
</div>
)}
{(cancel.isError || reconcile.isError) && <p role="alert" className="text-orbit-red">Action failed. Check the current job state.</p>}
</li>
);
}

View File

@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import { motion } from "motion/react";
import type { Snapshot } from "../../api";
import { DatabaseRestore } from "./DatabaseRestore";
import { formatBytes, formatWhen } from "../../lib/format";
import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState";
@@ -11,6 +12,7 @@ const GRACE = 12;
export function ReconstituteWizard({
snapshots,
selected,
scopedExport,
onStart,
onPoll,
onAbort,
@@ -18,6 +20,7 @@ export function ReconstituteWizard({
}: {
snapshots: Snapshot[];
selected: string | null;
scopedExport?: boolean;
onStart: (snapId: string, target: string) => Promise<{
session_id: string;
session: { seconds_remaining: number; state: string };
@@ -27,7 +30,8 @@ export function ReconstituteWizard({
onBusyChange: (busy: boolean) => void;
}) {
const [snapId, setSnapId] = useState(selected ?? snapshots[0]?.id ?? "");
const [target, setTarget] = useState("./restore/out");
const [databaseMode, setDatabaseMode] = useState(true);
const [target, setTarget] = useState(scopedExport ? "restored.dump" : "./restore/out");
const [sessionId, setSessionId] = useState<string | null>(null);
const [remaining, setRemaining] = useState(GRACE);
const [state, setState] = useState("idle");
@@ -36,6 +40,7 @@ export function ReconstituteWizard({
const [reconnecting, setReconnecting] = useState(false);
const snap = snapshots.find((s) => s.id === snapId);
const managed = snap?.capture?.restore_ready ? snap.capture : undefined;
const inCountdown = state === "countdown" || state === "confirming";
const busy = !!action || inCountdown || state === "restoring";
@@ -72,7 +77,7 @@ export function ReconstituteWizard({
return (
<div className="space-y-4">
<p className="text-sm text-star-300">
Choose a snapshot and a destination on the hub.
Choose a recovery point and a destination.
</p>
{snap && (
@@ -87,7 +92,7 @@ export function ReconstituteWizard({
<select
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5"
value={snapId}
onChange={(e) => setSnapId(e.target.value)}
onChange={(e) => { setSnapId(e.target.value); setDatabaseMode(true); }}
disabled={busy}
>
{snapshots.map((s) => (
@@ -98,8 +103,25 @@ export function ReconstituteWizard({
</select>
</label>
{managed && (
<div className="flex flex-wrap gap-2" aria-label="Recovery destination" role="group">
<Button type="button" aria-pressed={databaseMode} disabled={busy}
variant={databaseMode ? "primary" : "ghost"} onClick={() => setDatabaseMode(true)}>
Restore to database
</Button>
<Button type="button" aria-pressed={!databaseMode} disabled={busy}
variant={databaseMode ? "ghost" : "primary"} onClick={() => setDatabaseMode(false)}>
Export file on hub
</Button>
</div>
)}
{managed && databaseMode ? (
<DatabaseRestore key={snapId} snapshot={snapId} application={managed.application_id}
engine={managed.engine} />
) : <>
<label className="block text-sm">
<span className="text-star-400">Target path</span>
<span className="text-star-400">{scopedExport ? "Export filename on hub" : "Export file path on hub"}</span>
<input
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2.5 font-mono text-xs"
value={target}
@@ -151,7 +173,7 @@ export function ReconstituteWizard({
await onAbort(sessionId);
} catch {
setAction(undefined);
setError("Could not cancel the restore. Check the current session status.");
setError("Could not cancel the file export. Check the current session status.");
}
}}
>
@@ -170,39 +192,40 @@ export function ReconstituteWizard({
setState(res.session.state);
setRemaining(res.session.seconds_remaining);
} catch {
setError("Could not confirm that the hub started the restore.");
setError("Could not confirm that the hub started writing to the destination.");
} finally {
setAction(undefined);
}
}}
>
Begin restore
Begin file export
</Button>
</div>
{error && <p role="alert" className="text-orbit-red text-sm">{error}</p>}
{reconnecting && <p role="status" className="text-orbit-amber text-sm">Reconnecting to the restore session…</p>}
{state === "restoring" && <p role="status" className="text-orbit-amber text-sm">Restoring snapshot…</p>}
{reconnecting && <p role="status" className="text-orbit-amber text-sm">Reconnecting to the export session…</p>}
{state === "restoring" && <p role="status" className="text-orbit-amber text-sm">Exporting snapshot…</p>}
{state === "unavailable" && (
<p role="alert" className="text-orbit-red text-sm">The hub no longer has this restore session. Check the destination before retrying.</p>
<p role="alert" className="text-orbit-red text-sm">The hub no longer has this export session. Check the destination before retrying.</p>
)}
{state === "completed" && (
<p className="text-orbit-green text-sm text-center">Reconstitute complete.</p>
<p className="text-orbit-green text-sm text-center">File export complete.</p>
)}
{state === "aborted" && (
<p className="text-star-300 text-sm text-center">Reconstitute cancelled. Nothing was changed.</p>
<p className="text-star-300 text-sm text-center">File export cancelled.</p>
)}
{state === "failed" && (
<p className="text-orbit-red text-sm text-center">Reconstitute failed — check telemetry.</p>
<p className="text-orbit-red text-sm text-center">File export failed. Check telemetry.</p>
)}
<Hint>The hub writes after the countdown. An existing file at the destination may be overwritten.</Hint>
<Hint>{scopedExport ? "The hub writes to its exports directory after the countdown." : "The hub writes after the countdown. An existing file at the destination may be overwritten."}</Hint>
{sessionId && (
<TelemetryPanel label="Session">
{JSON.stringify({ sessionId, state, remaining }, null, 2)}
</TelemetryPanel>
)}
</>}
</div>
);
}

View File

@@ -0,0 +1,68 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { registerRestoreTarget, type RestoreTarget } from "../../api";
import { OutpostField } from "../outposts/OutpostField";
import { Button } from "../ui/Button";
import { Hint } from "../ui/EmptyState";
const field = "mt-1 w-full rounded-xl border border-space-700 bg-space-950 px-3 py-2 text-star-100";
const uuidPattern = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
export function RestoreTargetForm({ application, engine, onClose }: {
application: string;
engine: RestoreTarget["engine"];
onClose: () => void;
}) {
const [initialId] = useState(() => globalThis.crypto?.randomUUID?.() ?? "");
const qc = useQueryClient();
const register = useMutation({
mutationFn: registerRestoreTarget,
onSuccess: async () => {
await qc.invalidateQueries({ queryKey: ["restore-targets"] });
onClose();
},
});
return (
<form className="space-y-3 rounded-xl border border-space-700 p-3" onSubmit={(event) => {
event.preventDefault();
if (register.isPending) return;
const data = new FormData(event.currentTarget);
register.mutate({
id: String(data.get("id")).toLowerCase(),
application_id: application,
outpost_id: String(data.get("outpost")),
name: String(data.get("name")).trim(),
engine,
identity: {
instance: String(data.get("instance")).trim().toLowerCase(),
database: String(data.get("database")),
},
});
}}>
<h4 className="font-medium text-star-100">Register a {engine === "postgres" ? "PostgreSQL" : "MySQL"} restore target</h4>
<label className="block text-sm text-star-300">
Target name
<input name="name" required maxLength={128} className={field} />
</label>
<label className="block text-sm text-star-300">
Target UUID
<input name="id" defaultValue={initialId} required pattern={uuidPattern} className={field} />
</label>
<OutpostField className={field} />
<label className="block text-sm text-star-300">
{engine === "postgres" ? "Cluster system identifier" : "Server UUID"}
<input name="instance" required pattern={engine === "postgres" ? "[0-9]+" : uuidPattern} className={field} />
</label>
<label className="block text-sm text-star-300">
Database name
<input name="database" required maxLength={255} className={field} />
</label>
<Hint>Configure this target UUID under the application’s targets on the assigned agent. Keep the connection settings and credentials on that agent.</Hint>
{register.isError && <p role="alert" className="text-sm text-orbit-red">Could not register the target. Verify its identity, UUID, and Outpost.</p>}
<div className="flex gap-2">
<Button type="button" disabled={register.isPending} onClick={onClose}>Cancel</Button>
<Button type="submit" variant="primary" disabled={register.isPending}>Register target</Button>
</div>
</form>
);
}

View File

@@ -1,17 +1,18 @@
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import { animate, spring, useMotionValue } from "motion/react";
import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { animate, motion, spring, useMotionValue, useTransform, type MotionStyle, type MotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
import { orbitStatus } from "../../lib/format";
import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout";
import {
assignOrbitSlots, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
assignOrbitSlots, CAPTURE_HIGHLIGHT_START, capturePhases, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, type Vec2,
} from "../../lib/galaxyLayout";
import { useGalaxyMotion } from "../../hooks/useGalaxyMotion";
import { uiSpring } from "../../lib/motion";
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { ambientSpring, gentleSpring, uiSpring } from "../../lib/motion";
import { VaultCore } from "./VaultCore";
export type CaptureArrival = { orbitId: string; snapshotId: string };
export type CaptureEffect = { orbitId: string; key: number; snapshotId?: string };
type Props = {
orbits: Orbit[];
@@ -19,7 +20,10 @@ type Props = {
recentSnapshots: Snapshot[];
flowing: boolean;
reducedMotion: boolean;
arrival?: CaptureArrival;
bigScreen: boolean;
captureEffect?: CaptureEffect;
captureGlow: MotionValue<number>;
captureReady: boolean;
onSelectOrbit: (id: string) => void;
onSelectSnapshot: (id: string) => void;
};
@@ -28,107 +32,198 @@ const HALF_WIDTH = SCENE_WIDTH / 2;
const HALF_HEIGHT = SCENE_HEIGHT / 2;
const labelFont = "500 11px ui-monospace, monospace";
const MAX_LABELS = 12;
const clamp = (value: number) => Math.max(0, Math.min(1, value));
const ACCRETION_SECONDS = 6.4;
const TRAIL_WIDTHS = [0.8, 1.4, 2.3];
export function BlackholeGalaxy({
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival, onSelectOrbit, onSelectSnapshot,
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, captureReady, onSelectOrbit, onSelectSnapshot,
}: Props) {
const frame = useRef<HTMLDivElement>(null);
const bodyNodes = useRef(new Map<SVGGElement, { id: string; far: boolean }>());
const bodyNodes = useRef(new Map<SVGGElement, { id: string; index: number }>());
const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined);
const elapsed = useRef(0);
const entrance = useRef(0);
const core = useRef<SVGGElement>(null);
const meteor = useRef<{ id: string; time: number; source: Vec2; progress: ReturnType<typeof spring> }>(undefined);
const capture = useRef<{ event: CaptureEffect; time: number; source: Vec2; progress: ReturnType<typeof spring>; done: boolean; waiting: boolean }>(undefined);
const skippedCapture = useRef<CaptureEffect>(undefined);
const sourceFlare = useRef<SVGCircleElement>(null);
const busyAngle = useRef(0);
const diskTime = useRef(0);
const hasRunning = orbits.some(orbit => orbitStatus(orbit.last_status).busy);
const trailId = useId();
const trail = useRef<SVGPathElement>(null);
const trailSegments = useRef<(SVGUseElement | null)[]>([]);
const head = useRef<SVGCircleElement>(null);
const effect = useRef<SVGGElement>(null);
const [width, setWidth] = useState(0);
const [coasting, setCoasting] = useState(false);
const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0);
const moving = !reducedMotion && (flowing || coasting);
const [lockedPhase, setLockedPhase] = useState(0);
const reveal = useMotionValue(flowing ? 0 : 1);
const revealStyle = useTransform(reveal, clamp);
const revealVariables: MotionStyle & { "--lock-reveal": MotionValue<number> } = { "--lock-reveal": revealStyle };
const selectionX = useMotionValue(0);
const selectionY = useMotionValue(0);
const selectionPlaced = useRef(false);
useLayoutEffect(() => () => rate.stop(), [rate]);
useLayoutEffect(() => () => {
rate.stop();
reveal.stop();
selectionX.stop();
selectionY.stop();
}, [rate, reveal, selectionX, selectionY]);
useLayoutEffect(() => {
if (reducedMotion) {
rate.jump(0);
reveal.jump(1);
setLockedPhase(elapsed.current);
setCoasting(false);
return;
}
if (flowing) animate(reveal, 0, gentleSpring);
const target = flowing ? 1 : 0;
if (rate.get() === target && !rate.isAnimating()) return;
setCoasting(!flowing);
animate(rate, target, { ...uiSpring, onComplete: () => setCoasting(false) });
}, [flowing, rate, reducedMotion]);
animate(rate, target, {
...uiSpring,
restDelta: 0.025,
restSpeed: 0.25,
onComplete: () => {
if (!flowing) {
setLockedPhase(elapsed.current);
animate(reveal, 1, gentleSpring);
}
setCoasting(false);
},
});
}, [flowing, rate, reducedMotion, reveal]);
const slots = useMemo(
() => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId),
[orbits, selectedOrbitId],
);
useLayoutEffect(() => { slotsBefore.current = slots; }, [slots]);
useLayoutEffect(() => {
const element = frame.current;
if (!element) return;
const measure = () => setWidth(element.clientWidth);
const observer = new ResizeObserver(measure);
observer.observe(element);
measure();
return () => observer.disconnect();
}, []);
useScreenTransition(frame, bigScreen, reducedMotion, setWidth);
const draw = useCallback((delta: number) => {
if (moving && delta > 0) {
elapsed.current += delta * Math.max(0, rate.get());
const phase = (elapsed.current % ACCRETION_SECONDS) / ACCRETION_SECONDS;
const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined;
const selectedPosition = selectedSlot && orbitPose(selectedSlot, lockedPhase);
const selectedX = selectedPosition?.x;
const selectedY = selectedPosition?.y;
useLayoutEffect(() => {
if (selectedX === undefined || selectedY === undefined) {
selectionPlaced.current = false;
} else if (!selectionPlaced.current || reducedMotion) {
selectionX.jump(selectedX);
selectionY.jump(selectedY);
selectionPlaced.current = true;
} else if (!moving) {
animate(selectionX, selectedX, uiSpring);
animate(selectionY, selectedY, uiSpring);
}
}, [moving, reducedMotion, selectedX, selectedY, selectionX, selectionY]);
useGalaxyMotion((delta) => {
const speed = moving ? Math.max(0, rate.get()) : 0;
elapsed.current += delta * speed;
if (hasRunning && !reducedMotion && delta > 0) {
busyAngle.current = (busyAngle.current + 105 * delta) % 360;
frame.current?.style.setProperty("--busy-angle", `${busyAngle.current}deg`);
}
const wasEntering = entrance.current < 0.6;
if (slots.size) entrance.current = reducedMotion ? 0.6 : Math.min(0.6, entrance.current + delta);
const entering = !reducedMotion && slots.size > 0 && entrance.current < 0.6;
if (!delta || moving || (!reducedMotion && wasEntering)) {
for (const [node, { id, index }] of bodyNodes.current) {
const slot = slots.get(id)!;
const { x, y } = orbitPose(slot, elapsed.current);
const depth = y / (slot.radius * ORBIT_TILT);
const appear = entering ? clamp((entrance.current - Math.min(index * 0.013, 0.33)) / 0.23) : 1;
node.setAttribute("transform", `translate(${x} ${y}) scale(${0.95 + depth * 0.08})`);
node.setAttribute("opacity", String(appear * (0.88 + depth * 0.12)));
}
}
if (moving && selectedSlot) {
const point = orbitPose(selectedSlot, elapsed.current);
selectionX.jump(point.x);
selectionY.jump(point.y);
}
if (reducedMotion) skippedCapture.current = captureEffect;
const event = captureEffect === skippedCapture.current ? undefined : captureEffect;
const slot = event && slots.get(event.orbitId);
if (event && slot && capture.current?.event !== event) {
captureGlow.set(0);
effect.current?.setAttribute("opacity", "0");
const source = orbitPose(slot, elapsed.current);
capture.current = {
event, source, time: 0, done: false, waiting: false,
progress: spring({ ...ambientSpring, keyframes: [0, 1], restDelta: 0.002 }),
};
if (event.snapshotId) {
const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35));
trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" "));
}
}
const current = capture.current;
let absorption = 0;
let capturing = false;
if (event && current?.event === event && !current.done) {
// The impact can finish while the snapshot list is still refreshing.
if (!current.waiting || captureReady) current.time += delta * 1000;
const { value, done } = current.progress.next(current.time);
const success = !!event.snapshotId;
current.waiting = success && !captureReady && value >= CAPTURE_HIGHLIGHT_START;
const progress = current.waiting ? CAPTURE_HIGHLIGHT_START : done ? 1 : value;
const phases = capturePhases(progress);
current.done = done && !current.waiting;
const source = slot ? orbitPose(slot, elapsed.current) : current.source;
const pulse = success ? phases.flare : phases.failure;
sourceFlare.current?.setAttribute("cx", String(source.x));
sourceFlare.current?.setAttribute("cy", String(source.y));
sourceFlare.current?.setAttribute("r", String(7 + 13 * clamp(value)));
sourceFlare.current?.setAttribute("stroke", success ? "#ffd3a5" : "#f59183");
sourceFlare.current?.setAttribute("opacity", String(0.75 * pulse));
if (success) {
const { x, y } = spiralPoint(current.source, phases.flight);
head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y));
head.current?.setAttribute("r", String(3.5 * (1 - phases.flight ** 4)));
const segmentLength = Math.min(phases.flight, 0.19) * (1 - phases.flight ** 6) / TRAIL_WIDTHS.length;
trailSegments.current.forEach((segment, index) => {
segment?.setAttribute("stroke-dasharray", `${segmentLength} 1`);
segment?.setAttribute("stroke-dashoffset", String((TRAIL_WIDTHS.length - index) * segmentLength - phases.flight));
});
effect.current?.setAttribute("opacity", String(clamp(phases.flight * 14) * (1 - phases.flight ** 8)));
absorption = phases.absorption;
captureGlow.set(phases.highlight);
}
capturing = !current.done && !current.waiting;
} else {
sourceFlare.current?.setAttribute("opacity", "0");
effect.current?.setAttribute("opacity", "0");
captureGlow.set(0);
}
if (delta > 0 && (speed || absorption)) {
diskTime.current += delta * (speed + 3.2 * absorption);
const phase = (diskTime.current % ACCRETION_SECONDS) / ACCRETION_SECONDS;
core.current?.style.setProperty("--accretion-offset", String(-100 * phase));
}
for (const [node, { id, far }] of bodyNodes.current) {
const slot = slots.get(id);
if (!slot) continue;
const { x, y } = orbitPose(slot, elapsed.current);
const visible = far === (y < 0);
const display = visible ? "" : "none";
if (node.style.display !== display) node.style.display = display;
if (!visible) continue;
node.setAttribute("transform", `translate(${x} ${y})`);
const coreStyle = core.current?.style;
if (coreStyle && (absorption || coreStyle.getPropertyValue("--capture-absorption") !== "0")) {
coreStyle.setProperty("--capture-absorption", String(absorption));
}
if (!arrival || reducedMotion) {
effect.current?.setAttribute("opacity", "0");
return moving;
}
const slot = slots.get(arrival.orbitId);
if (meteor.current?.id !== arrival.snapshotId && slot) {
const source = orbitPose(slot, elapsed.current);
meteor.current = {
id: arrival.snapshotId,
time: 0,
source,
progress: spring({ ...uiSpring, stiffness: 36, damping: 12, keyframes: [0, 1], restDelta: 0.002 }),
};
const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35));
trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" "));
}
const current = meteor.current;
if (!current || current.id !== arrival.snapshotId) return moving;
current.time += delta * 1000;
const { value: progress, done } = current.progress.next(current.time);
const { x, y } = spiralPoint(current.source, progress);
head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y));
trail.current?.setAttribute("stroke-dashoffset", String(0.2 - progress));
effect.current?.setAttribute("opacity", String(progress >= 1 ? 0 : Math.min(1, (1 - progress) * 6)));
return moving || !done;
}, [arrival, moving, rate, reducedMotion, slots]);
useGalaxyMotion(moving || (!reducedMotion && !!arrival), draw);
return moving || entering || capturing || (hasRunning && !reducedMotion);
});
const scale = width / SCENE_WIDTH;
const height = SCENE_HEIGHT * scale;
const hitRadius = Math.max(12, scale ? 12 / scale : 12);
const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined;
const selectedPosition = !moving && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined;
const positions = !moving ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : [];
const positions = [...slots.values()].map((slot) => orbitPose(slot, lockedPhase));
const moons = selectedPosition
? moonPoses(selectedPosition, recentSnapshots.length, 2 * hitRadius + 3, positions)
: [];
@@ -146,87 +241,100 @@ export function BlackholeGalaxy({
};
let labels: ReturnType<typeof placeLabels> = [];
if (!moving && width && labelCandidates.length) {
if (width && labelCandidates.length) {
const measure = document.createElement("canvas").getContext("2d");
if (measure) measure.font = labelFont;
const markers = positions.map((point) => box(point, 7));
const core = box({ x: 0, y: 0 }, 65 * scale);
labels = placeLabels(labelCandidates.map(({ id, name }) => {
const point = screen(orbitPose(slots.get(id)!, elapsed.current));
const point = screen(orbitPose(slots.get(id)!, lockedPhase));
return { id, ...point, width: Math.min(146, Math.ceil(measure?.measureText(name).width ?? name.length * 7) + 16) };
}), width, height, [core, ...markers, ...moons.map((moon) => box(moon, 12))]);
}), width, height, [core, ...markers, ...moons.map((moon) => box(moon, 12))], selectedOrbitId);
}
const focusLabel = labels.find(({ id }) => id === selectedOrbitId);
const renderOrbits = (far: boolean) => visible.map((orbit) => {
const point = orbitPose(slots.get(orbit.id)!, elapsed.current);
// Each marker switches layers when it crosses the orbital plane.
const renderOrbits = visible.map((orbit, index) => {
const selected = orbit.id === selectedOrbitId;
const status = orbitStatus(orbit.last_status);
return (
<g
<motion.g
key={orbit.id}
ref={(node) => {
if (!node) return;
bodyNodes.current.set(node, { id: orbit.id, far });
bodyNodes.current.set(node, { id: orbit.id, index });
return () => { bodyNodes.current.delete(node); };
}}
transform={`translate(${point.x} ${point.y})`}
style={{ display: far === (point.y < 0) ? "" : "none" }}
initial={false}
animate="idle"
whileHover="hover"
data-orbit-marker={orbit.id}
className={`orbit-marker orbit-marker--${status.tone}${selected ? " orbit-marker--selected" : ""}`}
>
<circle className="orbit-halo" r={selected ? 16 : 10} />
<motion.circle className="orbit-halo" r={selected ? 16 : 10}
variants={{ idle: { opacity: 0.08 }, hover: { opacity: 0.3 } }} />
{status.tone === "red" && <path className="orbit-alert" d="M0 -8 8 0 0 8 -8 0Z" />}
{status.busy && <circle className="orbit-busy" r="8.5" />}
{selected && <circle className="orbit-selection" r="13" />}
<circle className="orbit-light" r="4.6" />
<circle className="orbit-hit" r={hitRadius} onClick={() => onSelectOrbit(orbit.id)} />
</g>
</motion.g>
);
});
return (
<div ref={frame} className="galaxy-frame" data-flowing={flowing}>
<motion.div ref={frame} className="galaxy-frame" data-flowing={flowing} style={revealVariables}>
<svg viewBox={`${-HALF_WIDTH} ${-HALF_HEIGHT} ${SCENE_WIDTH} ${SCENE_HEIGHT}`} aria-hidden="true">
<g className="orbit-tracks" pointerEvents="none">
{orbitRadii.map((radius) => (
<ellipse key={radius} rx={radius} ry={radius * ORBIT_TILT} className={selectedSlot?.radius === radius ? "is-selected" : ""} />
))}
</g>
<g className="orbit-layer orbit-layer--far">{renderOrbits(true)}</g>
<VaultCore ref={core} />
<g className="orbit-layer orbit-layer--near">{renderOrbits(false)}</g>
{selectedPosition && moons.map(({ x, y }, index) => {
const snapshot = recentSnapshots[index];
return (
<g key={snapshot.id} data-snapshot-marker={snapshot.id} className="snapshot-marker">
<line x1={selectedPosition.x} y1={selectedPosition.y} x2={x} y2={y} />
<rect className="snapshot-light" x={x - 4} y={y - 4} width="8" height="8" rx="1" transform={`rotate(45 ${x} ${y})`} />
<circle className="orbit-hit" cx={x} cy={y} r={hitRadius} onClick={() => onSelectSnapshot(snapshot.id)} />
</g>
);
})}
{selectedPosition && focusLabel && (
<line className="focus-leader"
x1={selectedPosition.x} y1={selectedPosition.y}
x2={(focusLabel.x + focusLabel.width / 2) / scale - HALF_WIDTH}
y2={(focusLabel.y + LABEL_HEIGHT / 2) / scale - HALF_HEIGHT}
/>
)}
<g className="orbit-layer">{renderOrbits}</g>
{selectedPosition && <motion.circle className="orbit-selection" cx={selectionX} cy={selectionY} r="13" />}
<g className="lock-details" pointerEvents={moving ? "none" : undefined}>
{selectedPosition && moons.map(({ x, y }, index) => {
const snapshot = recentSnapshots[index];
return (
<g key={index} data-snapshot-marker={snapshot.id} className="snapshot-marker">
<motion.line x1={selectionX} y1={selectionY} initial={false} animate={{ x2: x, y2: y }} />
<motion.g initial={false} animate={{ x, y }}>
<rect className="snapshot-light" x="-4" y="-4" width="8" height="8" rx="1" transform="rotate(45)" />
{snapshot.id === captureEffect?.snapshotId && (
<motion.circle className="snapshot-flash" r="9" style={{ opacity: captureGlow }} />
)}
<circle className="orbit-hit" r={hitRadius} onClick={() => onSelectSnapshot(snapshot.id)} />
</motion.g>
</g>
);
})}
{selectedPosition && focusLabel && (
<motion.line className="focus-leader"
x1={selectionX} y1={selectionY} initial={false}
animate={{
x2: (focusLabel.x + focusLabel.width / 2) / scale - HALF_WIDTH,
y2: (focusLabel.y + LABEL_HEIGHT / 2) / scale - HALF_HEIGHT,
}}
/>
)}
</g>
<circle ref={sourceFlare} className="capture-flare" opacity="0" pointerEvents="none" fill="none" />
<g ref={effect} className="capture-arrival" opacity="0" pointerEvents="none">
<path ref={trail} pathLength="1" strokeDasharray=".2 1" fill="none" />
<defs><path id={trailId} ref={trail} pathLength="1" /></defs>
{TRAIL_WIDTHS.map((strokeWidth, index) => (
<use key={strokeWidth} ref={node => { trailSegments.current[index] = node; }}
href={`#${trailId}`} fill="none" strokeWidth={strokeWidth} opacity={0.35 + index * 0.3} />
))}
<circle ref={head} r="3.5" />
</g>
</svg>
<div aria-hidden="true" className="scene-labels" style={{ font: labelFont }}>
{labels.map(({ id, x, y, width: labelWidth }) => (
<span key={id} style={{ left: x, top: y, width: labelWidth }} className={id === selectedOrbitId ? "is-selected" : ""}>
{labels.map(({ id, x, y, width: labelWidth }, index) => (
<span key={id} style={{ left: `${100 * x / width}%`, top: `${100 * y / height}%`, width: labelWidth, opacity: reducedMotion ? 1 : `clamp(0, (var(--lock-reveal) - ${index * 0.035}) * 1.8, 1)` }} className={id === selectedOrbitId ? "is-selected" : ""}>
{labelCandidates.find((orbit) => orbit.id === id)?.name}
</span>
))}
</div>
{orbits.length >= orbitCapacity && <p className="scene-density">Select an orbit in the list to inspect it</p>}
</div>
</motion.div>
);
}

View File

@@ -44,6 +44,7 @@ export const VaultCore = memo(function VaultCore({ ref }: { ref: Ref<SVGGElement
</filter>
</defs>
<ellipse rx="162" ry="81" cy="6" fill={paint("halo")} />
<ellipse className="core-absorption" rx="178" ry="89" cy="6" fill={paint("halo")} />
<g transform="rotate(-11)">
<path
d={`${LENS_ARC} M-114 13 C-62 38 -28 53 13 51 C54 48 89 27 111 6`}

View File

@@ -1,9 +1,10 @@
import { BlackholeGalaxy, type CaptureArrival } from "./BlackholeGalaxy";
import { BlackholeGalaxy, type CaptureEffect } from "./BlackholeGalaxy";
import { SpaceBackdrop } from "./SpaceBackdrop";
import { motion, type MotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
export function VaultScene({
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival,
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, captureEffect, captureGlow, captureReady,
bigScreen, onToggleBigScreen, onToggleFlow, onSelectOrbit, onSelectSnapshot,
}: {
orbits: Orbit[];
@@ -11,7 +12,9 @@ export function VaultScene({
recentSnapshots: Snapshot[];
flowing: boolean;
reducedMotion: boolean;
arrival?: CaptureArrival;
captureEffect?: CaptureEffect;
captureGlow: MotionValue<number>;
captureReady: boolean;
bigScreen: boolean;
onToggleBigScreen: () => void;
onToggleFlow: () => void;
@@ -27,7 +30,11 @@ export function VaultScene({
<div>
<p className="instrument-label">Vault map</p>
<p className="scene-mode">
<span className={`mode-signal${flowing ? " is-live" : ""}`} />
<motion.span className="mode-signal" initial={false} animate={{
rotate: flowing ? 0 : 45,
borderRadius: flowing ? 3 : 1,
backgroundColor: flowing ? "var(--color-orbit-green)" : "var(--accent)",
}} />
{flowing ? "Flowing" : "Locked"}
{!flowing && selected && <span className="scene-focus" title={selected.name}>· {selected.name}</span>}
</p>
@@ -64,7 +71,10 @@ export function VaultScene({
recentSnapshots={recentSnapshots}
flowing={flowing}
reducedMotion={reducedMotion}
arrival={arrival}
bigScreen={bigScreen}
captureEffect={captureEffect}
captureGlow={captureGlow}
captureReady={captureReady}
onSelectOrbit={onSelectOrbit}
onSelectSnapshot={onSelectSnapshot}
/>

View File

@@ -1,4 +1,6 @@
import type { Snapshot } from "../../api";
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { deleteSnapshot, type Snapshot } from "../../api";
import { formatBytes, formatWhen } from "../../lib/format";
import { Button } from "../ui/Button";
import { TelemetryPanel } from "../ui/Telemetry";
@@ -6,10 +8,21 @@ import { TelemetryPanel } from "../ui/Telemetry";
export function SnapshotSheet({
snap,
onReconstitute,
onDeleted,
}: {
snap: Snapshot;
onReconstitute: () => void;
onDeleted: () => void;
}) {
const [confirmDelete, setConfirmDelete] = useState(false);
const qc = useQueryClient();
const deletion = useMutation({
mutationFn: () => deleteSnapshot(snap.id),
onSuccess: () => {
void qc.invalidateQueries({ queryKey: ["snapshots"] });
onDeleted();
},
});
return (
<div className="space-y-4">
<p className="text-sm text-star-300">
@@ -22,8 +35,20 @@ export function SnapshotSheet({
<p className="text-star-100">{formatBytes(snap.size_bytes)}</p>
</div>
<Button variant="warn" className="w-full" onClick={onReconstitute}>
Restore this snapshot
{snap.capture?.restore_ready ? "Database recovery options" : "Export file on hub"}
</Button>
<a href={`/api/v1/snapshots/${snap.id}/download`} download
className="console-control block w-full text-center">Download snapshot</a>
{confirmDelete ? (
<div className="space-y-2 rounded-xl border border-orbit-red/40 p-3">
<p className="text-sm text-star-300">Remove this recovery point from the hub catalogue?</p>
{deletion.isError && <p role="alert" className="text-sm text-orbit-red">Snapshot could not be removed. It may be in use.</p>}
<div className="flex gap-2">
<Button disabled={deletion.isPending} onClick={() => setConfirmDelete(false)}>Cancel</Button>
<Button variant="warn" disabled={deletion.isPending} onClick={() => deletion.mutate()}>Confirm deletion</Button>
</div>
</div>
) : <Button className="w-full" onClick={() => setConfirmDelete(true)}>Delete snapshot</Button>}
<TelemetryPanel label="Snapshot ID">{snap.id}</TelemetryPanel>
</div>
);

View File

@@ -1,25 +1,40 @@
import { useLayoutEffect } from "react";
import { useLayoutEffect, useRef } from "react";
export function useGalaxyMotion(draw: (elapsed: number) => boolean) {
const latest = useRef(draw);
const wake = useRef<() => void>(undefined);
export function useGalaxyMotion(active: boolean, draw: (elapsed: number) => boolean) {
useLayoutEffect(() => {
let frame = 0;
let previous: number | undefined;
const tick = (now: number) => {
const keepDrawing = draw(previous === undefined ? 0 : (now - previous) / 1000);
previous = now;
if (keepDrawing) frame = requestAnimationFrame(tick);
frame = 0;
const keepDrawing = latest.current(previous === undefined ? 0 : (now - previous) / 1000);
previous = keepDrawing ? now : undefined;
if (keepDrawing) schedule();
};
const sync = () => {
const schedule = () => {
if (!frame && !document.hidden) frame = requestAnimationFrame(tick);
};
const visibilityChanged = () => {
cancelAnimationFrame(frame);
frame = 0;
previous = undefined;
if (!document.hidden && active) frame = requestAnimationFrame(tick);
if (!document.hidden && latest.current(0)) schedule();
};
draw(0);
sync();
document.addEventListener("visibilitychange", sync);
wake.current = schedule;
document.addEventListener("visibilitychange", visibilityChanged);
return () => {
cancelAnimationFrame(frame);
document.removeEventListener("visibilitychange", sync);
wake.current = undefined;
document.removeEventListener("visibilitychange", visibilityChanged);
};
}, [active, draw]);
}, []);
useLayoutEffect(() => {
latest.current = draw;
if (draw(0)) wake.current?.();
});
}

View File

@@ -0,0 +1,97 @@
import { animate, useMotionValue } from "motion/react";
import { useLayoutEffect, useRef, type RefObject } from "react";
import { gentleSpring } from "../lib/motion";
export function useScreenTransition(
ref: RefObject<HTMLElement | null>,
bigScreen: boolean,
reducedMotion: boolean,
onSettled?: (width: number) => void,
fade = false,
) {
const centerX = useMotionValue(0);
const centerY = useMotionValue(0);
const width = useMotionValue(0);
const height = useMotionValue(0);
const target = useRef<DOMRect>(undefined);
const lastMode = useRef(bigScreen);
useLayoutEffect(() => {
if (!ref.current) return;
const element = ref.current;
const values = [centerX, centerY, width, height];
const changedMode = lastMode.current !== bigScreen;
lastMode.current = bigScreen;
let revision = 0;
function paint() {
const rect = target.current;
if (!rect?.width || !rect.height) return;
const x = centerX.get() - rect.left - rect.width / 2;
const y = centerY.get() - rect.top - rect.height / 2;
const sx = width.get() / rect.width;
const sy = height.get() / rect.height;
element.style.transform = `translate(${x}px, ${y}px) scale(${sx}, ${sy})`;
if (fade) element.style.opacity = String(1 - Math.min(0.35, Math.hypot(x, y) / 300));
}
function measure(transition = false) {
const previous = target.current;
element.style.transform = "";
const next = element.getBoundingClientRect();
target.current = next;
const destination = [next.left + next.width / 2, next.top + next.height / 2, next.width, next.height];
const animating = values.some(value => value.isAnimating());
if (previous && next.x === previous.x && next.y === previous.y &&
next.width === previous.width && next.height === previous.height && !reducedMotion && !transition) {
if (animating) paint();
return;
}
const version = ++revision;
const finish = () => {
element.style.transform = "";
if (fade) element.style.opacity = "";
onSettled?.(element.clientWidth);
};
if (reducedMotion || !previous?.width || !previous.height || (!transition && !animating)) {
values.forEach((value, index) => value.jump(destination[index]));
finish();
return;
}
let remaining = values.length;
paint();
values.forEach((value, index) => animate(value, destination[index], {
...gentleSpring,
restDelta: 0.25,
restSpeed: 2,
onComplete: () => {
if (version === revision && --remaining === 0) finish();
},
}));
}
const unsubscribes = values.map(value => value.on("change", paint));
const resize = () => measure();
const observer = new ResizeObserver(resize);
observer.observe(element);
window.addEventListener("resize", resize);
window.addEventListener("scroll", resize, { passive: true });
measure(changedMode);
return () => {
revision++;
unsubscribes.forEach(unsubscribe => unsubscribe());
observer.disconnect();
window.removeEventListener("resize", resize);
window.removeEventListener("scroll", resize);
};
}, [ref, bigScreen, reducedMotion, onSettled, fade, centerX, centerY, width, height]);
useLayoutEffect(() => () => {
centerX.stop();
centerY.stop();
width.stop();
height.stop();
}, [centerX, centerY, width, height]);
}

View File

@@ -83,6 +83,7 @@ button:disabled { cursor: default; }
touch-action: pan-y;
user-select: none;
}
.nav-icon { position: absolute; inset: 0; margin: auto; }
.vault-nav button:hover, .vault-nav button[aria-current] { color: var(--color-star-100); }
.vault-nav button[aria-current] { cursor: grab; }
.vault-nav:active button[aria-current] { cursor: grabbing; }
@@ -125,6 +126,87 @@ button:disabled { cursor: default; }
}
.hub-link { justify-self: end; display: flex; align-items: center; gap: 8px; color: var(--color-star-300); font: 500 11px var(--font-mono); white-space: nowrap; }
.vault-topbar-tools { justify-self: end; display: flex; align-items: center; gap: clamp(8px, 1.5vw, 20px); }
.search-trigger kbd { color: var(--quiet); font: 10px var(--font-mono); }
.big-screen .vault-topbar-tools {
position: absolute;
z-index: 30;
bottom: var(--screen-bottom);
right: max(var(--screen-gutter), env(safe-area-inset-right));
}
.search-overlay {
--search-viewport: 100dvh;
--search-top: clamp(12px, calc(var(--search-viewport) * .09), 84px);
--search-body-limit: max(0px, calc(var(--search-viewport) - var(--search-top) - 74px));
position: fixed;
inset: var(--search-viewport-top, 0px) 0 auto;
height: var(--search-viewport);
z-index: 50;
display: grid;
justify-items: center;
align-items: start;
padding: var(--search-top) 12px 12px;
background: #030508a6;
}
.search-overlay[inert] { pointer-events: none; }
.search-panel {
width: min(100%, 560px);
min-width: 0;
overflow: clip;
border: 1px solid #44434a;
border-radius: 12px;
background: #15181cf5;
backdrop-filter: blur(16px);
box-shadow: 0 18px 64px #0009;
}
.search-field {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 10px 8px 16px;
height: 60px;
border-bottom: 1px solid var(--line);
color: var(--accent);
}
.search-field > svg { flex: none; }
.search-field input { flex: 1; min-width: 0; padding: 6px; font-size: 16px; color: var(--color-star-100); }
.search-field input::placeholder { color: var(--quiet); }
.search-field .search-close { justify-content: center; width: 44px; height: 44px; padding: 0; }
.search-list-frame, .search-body { max-height: var(--search-body-limit); }
.search-list-frame { overflow: clip; }
.search-body { overflow: auto; overscroll-behavior: contain; }
.search-group { padding: 10px 14px 4px; }
.search-result {
display: flex;
align-items: center;
gap: 10px;
margin-inline: 6px;
min-height: 44px;
padding: 6px 8px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
}
.search-result > svg { flex: none; color: var(--accent); }
.search-result[aria-selected="true"] { background: #493329; box-shadow: inset 2px 0 var(--accent); }
.search-result:hover { background: #352c29; }
.search-result-text { min-width: 0; }
.search-result-text > * { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.search-result-text small, .search-status { font: 11px/1.5 var(--font-mono); color: var(--quiet); }
.search-status { display: flex; flex-wrap: wrap; gap: 4px 12px; padding: 10px 14px; }
@media (max-width: 840px) {
.vault-topbar-tools .search-trigger { justify-content: center; width: 44px; min-height: 44px; padding: 0; }
.search-trigger span { display: none; }
}
@media (max-width: 1120px) {
.search-trigger kbd { display: none; }
}
@media (max-width: 420px) {
.big-screen .vault-topbar-tools { bottom: auto; top: var(--screen-top); }
.big-screen .vault-overlay .vault-dialog { top: calc(var(--screen-top) + 52px); }
}
.vault-main { max-width: 1720px; padding: 30px clamp(16px, 3vw, 44px) 10px; margin-inline: auto; }
.vault-overview { display: flex; align-items: end; justify-content: space-between; gap: 18px; margin-bottom: 25px; }
.overview-label span { color: var(--accent); margin-right: 5px; }
@@ -168,7 +250,7 @@ button:disabled { cursor: default; }
padding: 7px 10px;
text-align: left;
}
.register-row:hover, .snapshot-row:hover { background: #1b1e23; }
.snapshot-row:hover { background: #1b1e23; }
.register-row[aria-pressed="true"] { background: #222025; box-shadow: inset 2px 0 var(--accent); }
.register-content { min-width: 0; }
.register-content span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; }
@@ -214,10 +296,11 @@ button:disabled { cursor: default; }
.inspector-history h3 { font-size: 12px; font-weight: 550; }
.inspector-history header span { color: var(--quiet); font: 11px var(--font-mono); }
.inspector-history .console-empty { padding-top: 10px; }
.snapshot-row { width: 100%; min-height: 52px; display: grid; grid-template-columns: 17px minmax(0, 1fr) 12px; align-items: center; gap: 8px; padding: 7px 13px; text-align: left; }
.snapshot-row { position: relative; width: 100%; min-height: 52px; display: grid; grid-template-columns: 17px minmax(0, 1fr) 12px; align-items: center; gap: 8px; padding: 7px 13px; text-align: left; }
.snapshot-row strong { display: block; font-size: 12px; font-weight: 550; }
.snapshot-row small { display: block; margin-top: 3px; font: 10px/1.3 var(--font-mono); color: var(--quiet); }
.snapshot-glyph { color: #c6d2e6; font-size: 18px; }
.snapshot-row-flash { position: absolute; inset: 0; background: #ffb9752b; box-shadow: inset 2px 0 var(--accent); pointer-events: none; }
.snapshot-arrow { color: var(--quiet); }
.vault-scene {
@@ -242,8 +325,7 @@ button:disabled { cursor: default; }
.scene-controls { display: flex; align-items: center; gap: 6px; }
.scene-toolbar button { flex: none; }
.scene-mode { display: flex; align-items: center; gap: 7px; margin-top: 3px; font-size: 13px; }
.mode-signal { flex: none; width: 6px; height: 6px; background: var(--accent); transform: rotate(45deg); border-radius: 1px; }
.mode-signal.is-live { background: var(--color-orbit-green); border-radius: 50%; transform: none; }
.mode-signal { flex: none; width: 6px; height: 6px; background: var(--accent); border-radius: 1px; }
.scene-focus { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: var(--quiet); }
.scene-footer { border-top: 1px solid #24282c; background: #0a0c10bb; }
.scene-footer > p span { color: var(--accent); }
@@ -265,17 +347,19 @@ button:disabled { cursor: default; }
.orbit-halo { opacity: .08; }
.orbit-alert, .orbit-selection, .orbit-busy { fill: none; stroke: currentColor; stroke-width: 1.15; pointer-events: none; }
.orbit-selection { stroke: #f8eadc; stroke-width: 1; }
.orbit-busy { stroke-dasharray: 3 3; }
.orbit-layer--far .orbit-marker:not(.orbit-marker--red, .orbit-marker--selected) { opacity: .76; }
.orbit-busy { stroke-dasharray: 3 3; transform: rotate(var(--busy-angle, 0deg)); }
.orbit-hit { fill: transparent; cursor: pointer; }
.orbit-marker:hover .orbit-halo { opacity: .3; }
.lock-details { opacity: var(--lock-reveal, 0); }
.snapshot-marker line { stroke: #bdc4ce; opacity: .58; stroke-dasharray: 2 3; pointer-events: none; }
.snapshot-light { fill: #dce5f7; stroke: #272c35; stroke-width: 1.1; pointer-events: none; }
.snapshot-marker:hover .snapshot-light { fill: #fff; }
.focus-leader { stroke: var(--accent); opacity: .65; pointer-events: none; }
.accretion-flow { stroke-dashoffset: var(--accretion-offset, 0); }
.accretion-flow--inner { stroke-dashoffset: calc(32 + 2 * var(--accretion-offset, 0)); }
.capture-arrival path { stroke: #ffce9b; stroke-width: 2.3; stroke-linecap: round; }
.core-absorption { opacity: var(--capture-absorption, 0); }
.capture-flare, .snapshot-flash { stroke-width: 1.5; }
.snapshot-flash { fill: none; stroke: #ffce9b; pointer-events: none; }
.capture-arrival use { stroke: #ffce9b; stroke-linecap: round; }
.capture-arrival circle { fill: #fff0d9; }
.scene-labels { position: absolute; inset: 0; pointer-events: none; }
.scene-labels span { display: block; position: absolute; height: 24px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; line-height: 22px; color: #dde0e6; background: #111519ed; border: 1px solid #353c46; border-radius: 4px; padding-inline: 7px; }
@@ -327,8 +411,18 @@ button:disabled { cursor: default; }
.big-screen .vault-topbar { display: contents; }
.big-screen .vault-dialog { top: var(--screen-top); bottom: calc(var(--screen-bottom) + 64px); }
.big-screen :is(.vault-brand, .hub-link, .vault-console, .vault-footer, .scene-footer) { display: none; }
.big-screen :is(.vault-brand, .hub-link, .vault-footer, .scene-footer) { display: none; }
.big-screen .vault-main { padding: 0; }
.big-screen .vault-console {
position: absolute;
z-index: 1;
top: 185px;
bottom: 70px;
width: clamp(190px, 16%, 260px);
pointer-events: none;
}
.big-screen .orbit-register { left: clamp(16px, 3vw, 44px); }
.big-screen .orbit-inspector { right: clamp(16px, 3vw, 44px); }
.big-screen .vault-workspace,
.big-screen .vault-scene { position: absolute; inset: 0; display: grid; }
.big-screen .vault-workspace { grid-template: 1fr / 1fr; height: auto; }
@@ -371,11 +465,11 @@ button:disabled { cursor: default; }
position: absolute;
z-index: 30;
bottom: var(--screen-bottom);
left: 50%;
transform: translateX(-50%);
inset-inline: 0;
width: max-content;
gap: 4px;
max-width: calc(100% - 2 * var(--screen-gutter));
margin: 0;
margin: 0 auto;
padding: 5px 7px;
border-radius: 999px;
box-shadow: inset 0 1px #ffffff12, 0 8px 30px #0008;
@@ -387,6 +481,7 @@ button:disabled { cursor: default; }
border-radius: 999px;
padding: 0;
}
.big-screen .nav-label { position: absolute; }
.big-screen .vault-nav button[aria-current] { color: #ffe2c9; }
@media (max-width: 1060px) {

View File

@@ -12,12 +12,18 @@ export function formatWhen(iso: string): string {
});
}
export function schedulePhrase(cron?: string | null, dryRun?: boolean): string {
if (dryRun) return "Rehearse — no vault write";
if (!cron) return "On your command";
if (cron.includes("0 2")) return "Every night at 2am";
if (cron.includes("0 */6")) return "Every six hours";
return cron;
export function schedulePhrase(orbit: import("../api").Orbit): string {
if (orbit.access === "outpost") {
const schedule = orbit.capture_schedule;
if (!schedule) return orbit.application_id ? "On your command" : "Started by the Outpost";
const time = [schedule.hour, schedule.minute].map((part) => String(part).padStart(2, "0")).join(":");
return `Daily at ${time} ${schedule.timezone}`;
}
const cron = orbit.schedule?.trim().replace(/\s+/g, " ");
if (!cron) return orbit.dry_run ? "Rehearse on command" : "On your command";
if (cron === "0 2 * * *" || cron === "0 0 2 * * *") return "Daily at 02:00 UTC";
if (cron === "0 */6 * * *" || cron === "0 0 */6 * * *") return "Every six hours (UTC)";
return `${cron} (UTC)`;
}
export type VaultStatus = "green" | "amber" | "grey" | "red";
@@ -25,6 +31,7 @@ export type VaultStatus = "green" | "amber" | "grey" | "red";
export function orbitStatus(status: string): { label: string; tone: VaultStatus; busy?: boolean } {
switch (status) {
case "failed": return { label: "Failed", tone: "red" };
case "queued": return { label: "Queued", tone: "amber", busy: true };
case "running": return { label: "Running", tone: "amber", busy: true };
case "rehearsing": return { label: "Rehearsing", tone: "amber", busy: true };
case "rehearsed": return { label: "Rehearsed", tone: "amber" };

View File

@@ -13,12 +13,14 @@ export function placeLabels(
width: number,
height: number,
obstacles: Rect[],
selectedId?: string,
): Label[] {
const occupied = [...obstacles];
const placed: Label[] = [];
for (const label of candidates) {
const { x, y, width: w } = label;
const offsets = [12, 28, 44].flatMap((gap) => [
const gaps = label.id === selectedId ? [12, 28, 44, 64, 88, 112, 144, 180] : [12, 28, 44];
const offsets = gaps.flatMap((gap) => [
[gap, -LABEL_HEIGHT / 2], [-w - gap, -LABEL_HEIGHT / 2],
[-w / 2, -LABEL_HEIGHT - gap], [-w / 2, gap],
[gap, -LABEL_HEIGHT - gap / 2], [-w - gap, gap / 2],

View File

@@ -103,3 +103,16 @@ export function spiralPoint(source: Vec2, progress: number): Vec2 {
const radius = Math.hypot(source.x, source.y) * (1 - u ** 1.4);
return { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };
}
export const CAPTURE_HIGHLIGHT_START = 0.94;
export function capturePhases(progress: number) {
const stage = (start: number, end: number) => Math.min(1, Math.max(0, (progress - start) / (end - start)));
return {
flare: stage(0, 0.06) * (1 - stage(0.08, 0.24)),
flight: stage(0.09, 0.79),
absorption: stage(0.76, 0.84) * (1 - stage(0.85, CAPTURE_HIGHLIGHT_START)),
highlight: stage(CAPTURE_HIGHLIGHT_START, 0.97) * (1 - stage(0.97, 0.998)),
failure: stage(0, 0.15) * (1 - stage(0.17, 0.9)),
};
}

View File

@@ -5,12 +5,24 @@ export const uiSpring = {
stiffness: 320,
damping: 36,
mass: 1,
restDelta: 0.01,
restSpeed: 0.05,
} as const satisfies Transition;
export const ambientPulse = {
export const gentleSpring = {
...uiSpring,
stiffness: 180,
damping: 28,
} as const satisfies Transition;
export const ambientSpring = {
...uiSpring,
stiffness: 40,
damping: 13,
} as const satisfies Transition;
export const ambientPulse = {
...ambientSpring,
repeat: Infinity,
repeatType: "mirror",
} as const satisfies Transition;

View File

@@ -0,0 +1,65 @@
import type { Orbit, Snapshot } from "../api";
import type { HUDMode } from "../components/hud/HUDRail";
import { formatWhen } from "./format.ts";
type Navigation = { id: Exclude<HUDMode, "snapshot">; label: string; icon: string };
export type SearchResult =
| (Navigation & { kind: "navigation"; detail?: undefined })
| { kind: "orbit" | "snapshot"; id: string; label: string; detail: string };
type Candidate = { result: SearchResult; fields: string[]; timestamp?: number };
function matchRank(fields: string[], term: string) {
return Math.min(...fields.map(value => {
const field = value.toLowerCase();
if (field === term) return 0;
if (field.startsWith(term)) return 1;
if (field.includes(term)) return 2;
return Infinity;
}));
}
export function createVaultSearch(
navigation: readonly Navigation[],
orbits: readonly Pick<Orbit, "id" | "name" | "provider">[] = [],
snapshots: readonly Snapshot[] = [],
) {
const destinations = navigation.map(item => ({ ...item, kind: "navigation" as const }));
const categories: [string, Candidate[]][] = [
["Navigation", destinations.map(result => ({ result, fields: [result.label] }))],
["Orbits", orbits.map(({ id, name, provider }) => ({
result: { kind: "orbit", id, label: name, detail: `${provider} · ${id}` },
fields: [name, id, provider],
}))],
["Snapshots", snapshots.map(({ id, orbit_id, orbit_name, taken_at }) => {
const date = formatWhen(taken_at);
return {
result: { kind: "snapshot", id, label: orbit_name, detail: `${date} · ${id}` },
fields: [orbit_name, id, orbit_id ?? "", date],
timestamp: Date.parse(taken_at) || 0,
};
})],
];
return (query: string): { label: string; results: SearchResult[] }[] => {
const term = query.trim().toLowerCase();
if (!term) return [{ label: "Navigation", results: destinations.slice(0, 8) }];
const groups = categories.map(([label, candidates]) => ({
label,
results: candidates
.map(candidate => ({ ...candidate, rank: matchRank(candidate.fields, term) }))
.filter(({ rank }) => Number.isFinite(rank))
.sort((a, b) => a.rank - b.rank || (b.timestamp ?? 0) - (a.timestamp ?? 0) ||
a.result.id.localeCompare(b.result.id))
.map(({ result }) => result),
})).filter(({ results }) => results.length);
let remaining = 8;
return groups.map(({ label, results }, index) => {
// Leave at least one slot for each later category with matches.
const visible = results.slice(0, remaining - (groups.length - index - 1));
remaining -= visible.length;
return { label, results: visible };
});
};
}