diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a2c66f9 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +.git +target +data +graft +node_modules +web/node_modules +web/dist +**/.DS_Store +*.db +*.part +.env +.env.* diff --git a/.gitignore b/.gitignore index 279c4da..593d467 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ web/dist/ *.db *.part .DS_Store + +# graft's local graph cache — regenerable, not committed (run `graft build`). +/graft/ diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..615e581 --- /dev/null +++ b/.ignore @@ -0,0 +1,5 @@ +# graft's cards are gitignored but should stay greppable: ripgrep reads +# .ignore before .gitignore, so this re-admits the tree to search only. +!graft/ +graft/.cache/ +graft/.graph/ diff --git a/Cargo.lock b/Cargo.lock index 275b97d..6c8790e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,30 +19,30 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aead" -version = "0.4.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b613b8e1e3cf911a086f53f03bf286f52fd7a7258e4fa606f0ef220d39d8877" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ + "crypto-common", "generic-array", ] [[package]] name = "aes" -version = "0.7.5" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e8b47f52ea9bae42228d07ec09eb676433d7c4ed1ebdf0f1d1c29ed446f1ab8" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", "cpufeatures", - "opaque-debug", ] [[package]] name = "aes-gcm" -version = "0.9.4" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df5f85a83a7d8b0442b6aa7b504b8212c1733da07b98aae43d4bc21b2cb3cdf6" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" dependencies = [ "aead", "aes", @@ -138,6 +138,18 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -161,6 +173,29 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "axum" version = "0.7.9" @@ -250,6 +285,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -278,6 +322,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -303,11 +349,12 @@ dependencies = [ [[package]] name = "cipher" -version = "0.3.0" +version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ee52072ec15386f770805afd189a01c8841be8696bed250fa2f13c4c0d6dfb7" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "generic-array", + "crypto-common", + "inout", ] [[package]] @@ -350,6 +397,15 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -395,18 +451,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] [[package]] name = "ctr" -version = "0.8.0" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "049bb91fb4aaf0e3c7efa6cd5ef877dbbbd15b39dad06d9948de4ec8a75761ea" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ "cipher", ] +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + [[package]] name = "digest" version = "0.10.7" @@ -418,6 +481,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "encoding_rs" version = "0.8.44" @@ -481,6 +550,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futures-core" version = "0.3.34" @@ -545,9 +620,9 @@ dependencies = [ [[package]] name = "ghash" -version = "0.4.4" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1583cc1656d7839fd3732b80cf4f38850336cdb9b8ded1cd399ca62958de3c99" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" dependencies = [ "opaque-debug", "polyval", @@ -737,6 +812,15 @@ dependencies = [ "serde", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -749,6 +833,16 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -909,6 +1003,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-traits" version = "0.2.19" @@ -970,9 +1070,9 @@ dependencies = [ [[package]] name = "password-hash" -version = "0.3.2" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d791538a6dcc1e7cb7fe6f6b58aca40e7f79403c45b2bc274008b5e647af1d8" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" dependencies = [ "base64ct", "rand_core", @@ -980,15 +1080,13 @@ dependencies = [ ] [[package]] -name = "pbkdf2" -version = "0.10.1" +name = "pem" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "271779f35b581956db91a3e55737327a03aa051e90b1c47aeb189508533adfd7" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" dependencies = [ - "digest", - "hmac", - "password-hash", - "sha2", + "base64", + "serde_core", ] [[package]] @@ -1011,9 +1109,9 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "polyval" -version = "0.5.3" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8419d2b623c7c0896ff2d5d96e2cb4ede590fed28fcc34934f4c33c036e620a1" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" dependencies = [ "cfg-if", "cpufeatures", @@ -1021,6 +1119,12 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1108,6 +1212,19 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rcgen" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "yasna", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1146,6 +1263,20 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rusqlite" version = "0.31.0" @@ -1179,6 +1310,52 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47796c98c480fce5406ef69d1c76378375492c3b0a0de587be0c1d9feb12f395" +dependencies = [ + "aws-lc-rs", + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.102.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -1356,9 +1533,9 @@ checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] name = "subtle" -version = "2.4.1" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" @@ -1418,6 +1595,8 @@ dependencies = [ "anyhow", "base64", "clap", + "rustls", + "rustls-pemfile", "serde", "serde_json", "tessera-core", @@ -1483,17 +1662,25 @@ dependencies = [ "chrono", "cron", "hex", + "hyper", + "hyper-util", "include_dir", "indexmap", "rand", + "rcgen", "rusqlite", + "rustls", + "rustls-pemfile", "serde", "serde_json", + "tempfile", "tessera-core", "tessera-demo", "tessera-providers", "tessera-store", "tokio", + "tokio-rustls", + "tower", "tower-http", "tracing", "tracing-subscriber", @@ -1521,10 +1708,10 @@ version = "0.1.0" dependencies = [ "aes-gcm", "anyhow", + "argon2", "chrono", "hex", "hmac", - "pbkdf2", "rand", "serde", "serde_json", @@ -1567,6 +1754,25 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + [[package]] name = "tokio" version = "1.40.0" @@ -1596,6 +1802,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tokio-rustls" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e727b36a1a0e8b74c376ac2211e40c2c8af09fb4013c60d910495810f008e9b" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.17" @@ -1745,14 +1961,20 @@ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "universal-hash" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f214e8f697e925001e66ec2c6e37a4ef93f0f78c2eed7814394e10c62025b05" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "generic-array", + "crypto-common", "subtle", ] +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "utf8parse" version = "0.2.2" @@ -2023,6 +2245,15 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -2043,6 +2274,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 4098d4f..8ad3212 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,8 +39,8 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } utoipa = { version = "4.2", features = ["axum_extras", "chrono"] } uuid = { version = "=1.10.0", features = ["v4", "serde"] } -aes-gcm = "=0.9.4" -pbkdf2 = { version = "=0.10.1", features = ["simple"] } +aes-gcm = "=0.10.3" +argon2 = "=0.5.3" hmac = "0.12" tempfile = "3.12" walkdir = "2.5" diff --git a/Dockerfile b/Dockerfile index 9590023..722afe0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM node:22-bookworm AS web WORKDIR /build COPY web/package.json web/package-lock.json* ./ -RUN npm ci 2>/dev/null || npm install +RUN npm ci COPY web/ ./ RUN npm run build @@ -13,7 +13,7 @@ COPY --from=web /build/dist ./web/dist RUN cargo build --release -p tessera-hub FROM debian:bookworm-slim -RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/* +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates postgresql-client && rm -rf /var/lib/apt/lists/* COPY --from=rust /build/target/release/tessera-hub /usr/local/bin/ ENV TESSERA_LISTEN=0.0.0.0:8787 ENV TESSERA_DATA_DIR=/data diff --git a/README.md b/README.md index 8b3187b..f7f4f1c 100644 --- a/README.md +++ b/README.md @@ -10,24 +10,28 @@ cd web && npm ci && npm run build && cd .. cargo build --release -p tessera-hub export TESSERA_DATA_DIR=./data -export TESSERA_VAULT_PASSPHRASE=dev-vault-key +export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase' ./target/release/tessera-hub ``` -Open [http://127.0.0.1:8787](http://127.0.0.1:8787) — API docs at `/swagger-ui`. +The hub listens on **127.0.0.1:8787** unless `TESSERA_LISTEN` is set. Open [http://127.0.0.1:8787](http://127.0.0.1:8787). The OpenAPI document is at `/api-doc/openapi.json`. 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 ` 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. ### Docker Compose ```bash +export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase' docker compose up --build ``` -Hub listens on **8787**. +Compose publishes **127.0.0.1:8787** only. The process inside the container listens on `0.0.0.0:8787` so that published port can reach it. The image includes `pg_dump` via `postgresql-client`. ### CLI ```bash cargo build --release -p tessera-cli +export TESSERA_VAULT_PASSPHRASE='choose a long private passphrase' ./target/release/tessera init ./target/release/tessera orbit nightly --path ./docs --dry-run ./target/release/tessera snap @@ -41,9 +45,12 @@ See [docs/SPEC.md](docs/SPEC.md). Rust workspace crates: `tessera-core`, `tesser ## Limitations (v1) - Vault engine uses a **restic-compatible directory layout** with Tessera’s own chunk encryption (Rust 1.83 cannot yet depend on `rustic_core` 0.13+). Emergency tooling may use external `rustic`/`restic` as formats converge. -- Wormhole uploads are **token-authenticated**; mTLS is optional via env hook (`TESSERA_WORMHOLE_MTLS`) without bundled CA generation. -- Postgres provider requires `pg_dump` on `PATH`. -- OIDC admin auth is stubbed; v1 uses open local API when hub is bound to localhost. +- New vaults derive the key with Argon2id (19 MiB, 2 iterations, parallelism 1) and record `keys/kdf.json`. A vault that already has a salt and no `kdf.json` still opens with PBKDF2-HMAC-SHA256, 100,000 iterations. New snapshot metadata is written as `{id}.json.enc`. Existing `{id}.json` files still list and restore. +- Wormhole pairing codes and upload tokens are stored in SQLite and survive a hub restart. Chunks are written at the given offset. When the bytes cover `total_bytes`, the hub seals them into the vault and deletes the `.part` file. `total_bytes` is required. +- Set `TESSERA_WORMHOLE_MTLS` to `1` or `true` to open a client-certificate listener. It also needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is up, plain HTTP upload routes answer 403. An agent that uses `https://` needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`. +- Postgres capture shells out to `pg_dump`. The connection URL is parsed and the password is written to a mode `0600` pgpass file (`PGPASSFILE`); it is not placed on the process argument list. The release image installs `pg_dump`; a hub built from source 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`. ## License diff --git a/compose.yaml b/compose.yaml index d0dec38..a769ecf 100644 --- a/compose.yaml +++ b/compose.yaml @@ -2,11 +2,11 @@ services: tessera-hub: build: . ports: - - "8787:8787" + - "127.0.0.1:8787:8787" environment: TESSERA_LISTEN: "0.0.0.0:8787" TESSERA_DATA_DIR: /data - TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:-dev-vault-key} + TESSERA_VAULT_PASSPHRASE: ${TESSERA_VAULT_PASSPHRASE:?Set TESSERA_VAULT_PASSPHRASE} RUST_LOG: tessera_hub=info volumes: - tessera-data:/data diff --git a/crates/tessera-agent/Cargo.toml b/crates/tessera-agent/Cargo.toml index 7b18590..4dfa547 100644 --- a/crates/tessera-agent/Cargo.toml +++ b/crates/tessera-agent/Cargo.toml @@ -20,3 +20,5 @@ tracing.workspace = true tracing-subscriber.workspace = true uuid.workspace = true base64 = "0.22" +rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] } +rustls-pemfile = "=2.2.0" diff --git a/crates/tessera-agent/src/http.rs b/crates/tessera-agent/src/http.rs index 0ef139a..085273e 100644 --- a/crates/tessera-agent/src/http.rs +++ b/crates/tessera-agent/src/http.rs @@ -1,7 +1,11 @@ use anyhow::{Context, Result}; +use rustls::pki_types::ServerName; +use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned}; use std::collections::HashMap; -use std::io::{Read, Write}; +use std::fs::File; +use std::io::{BufReader, Read, Write}; use std::net::TcpStream; +use std::sync::Arc; pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result { let payload = serde_json::to_string(body)?; @@ -15,8 +19,12 @@ fn request( content_type: Option<&str>, headers: &[(&str, &str)], ) -> Result { - let (host, port, path) = parse_url(url)?; - let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?; + let (https, host, port, path) = parse_url(url)?; + let mut stream: Box = if https { + Box::new(connect_mtls(&host, port)?) + } else { + Box::new(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"); for (k, v) in headers { req.push_str(&format!("{k}: {v}\r\n")); @@ -38,20 +46,65 @@ fn request( Ok(buf[body_start..].trim().to_string()) } -fn parse_url(url: &str) -> Result<(String, u16, String)> { - let url = url.strip_prefix("http://").context("only http supported")?; - let (host_port, path) = url.split_once('/').unwrap_or((url, "")); +trait ReadWrite: Read + Write {} +impl ReadWrite for T {} + +fn parse_url(url: &str) -> Result<(bool, String, u16, String)> { + let (https, rest) = if let Some(rest) = url.strip_prefix("https://") { + (true, rest) + } else if let Some(rest) = url.strip_prefix("http://") { + (false, rest) + } else { + anyhow::bail!("hub url must start with http:// or https://"); + }; + let (host_port, path) = rest.split_once('/').unwrap_or((rest, "")); let path = if path.is_empty() { "/".to_string() } else { format!("/{path}") }; - let (host, port) = if let Some((h, p)) = host_port.split_once(':') { - (h.to_string(), p.parse()?) + let (host, port) = if let Some((host, port)) = host_port.split_once(':') { + (host.to_string(), port.parse()?) } else { - (host_port.to_string(), 80) + (host_port.to_string(), if https { 443 } else { 80 }) }; - Ok((host, port, path)) + Ok((https, host, port, path)) +} + +fn connect_mtls(host: &str, port: u16) -> Result> { + 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}"))?; + } + 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}"))?; + 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")?; + Ok(StreamOwned::new(connection, tcp)) +} + +fn load_certs(path: &str) -> Result>> { + let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?); + rustls_pemfile::certs(&mut reader) + .collect::, _>>() + .context("parse certificate") +} + +fn load_key(path: &str) -> Result> { + let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?); + rustls_pemfile::private_key(&mut reader) + .context("parse private key")? + .context("no private key in client key file") } #[allow(dead_code)] diff --git a/crates/tessera-cli/src/main.rs b/crates/tessera-cli/src/main.rs index da30543..cd01d03 100644 --- a/crates/tessera-cli/src/main.rs +++ b/crates/tessera-cli/src/main.rs @@ -12,8 +12,9 @@ struct Cli { command: Commands, #[arg(long, env = "TESSERA_DATA_DIR", default_value = "./data")] data_dir: String, - #[arg(long, env = "TESSERA_VAULT_PASSPHRASE", default_value = "dev-vault-key")] - vault_pass: String, + /// Required for vault commands. No default; the published example passphrase is rejected for new vaults. + #[arg(long, env = "TESSERA_VAULT_PASSPHRASE")] + vault_pass: Option, #[arg(long, env = "TESSERA_HUB_URL", default_value = "http://127.0.0.1:8787")] hub_url: String, } @@ -98,14 +99,24 @@ fn main() -> Result<()> { Ok(()) } +fn require_passphrase(cli: &Cli) -> Result<&str> { + match cli.vault_pass.as_deref() { + Some(pass) if !pass.is_empty() => Ok(pass), + _ => anyhow::bail!( + "Set TESSERA_VAULT_PASSPHRASE or pass --vault-pass. Tessera does not ship a default passphrase." + ), + } +} + fn cmd_seed_demo(cli: &Cli, force: bool, reset: bool) -> Result<()> { let data = std::path::Path::new(&cli.data_dir); + let vault_pass = require_passphrase(cli)?; if reset { - tessera_demo::clear_demo(data, &cli.vault_pass)?; + tessera_demo::clear_demo(data, vault_pass)?; println!("Demo seed cleared."); return Ok(()); } - let report = tessera_demo::apply(data, &cli.vault_pass, force)?; + let report = tessera_demo::apply(data, vault_pass, force)?; if report.skipped { println!( "Demo seed already applied ({} orbits, {} snapshots). Use --force to re-seed.", @@ -130,7 +141,7 @@ fn cmd_init(cli: &Cli) -> Result<()> { println!("Vault already initialized."); return Ok(()); } - Vault::init(&vp, &cli.vault_pass).context("init vault")?; + Vault::init(&vp, require_passphrase(cli)?).context("init vault")?; println!("Vault initialized at {}", vp.display()); Ok(()) } @@ -142,7 +153,7 @@ fn cmd_status(cli: &Cli) -> Result<()> { } let vp = vault_path(&cli.data_dir); if vp.join("config").exists() { - let vault = Vault::open(&vp, &cli.vault_pass)?; + let vault = Vault::open(&vp, require_passphrase(cli)?)?; let n = vault.list_snapshots()?.len(); println!("Vault: online — {n} snapshots"); } else { @@ -197,7 +208,7 @@ fn cmd_snap(cli: &Cli, orbit_name: Option) -> Result<()> { } fn cmd_list(cli: &Cli) -> Result<()> { - let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?; + let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; for s in vault.list_snapshots()? { println!( "{} {} {} bytes orbit={}", @@ -211,14 +222,14 @@ fn cmd_list(cli: &Cli) -> Result<()> { } fn cmd_reconstitute(cli: &Cli, snapshot_id: Uuid, target: String) -> Result<()> { - let vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?; + let vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; let n = vault.restore_snapshot(snapshot_id, std::path::Path::new(&target))?; println!("Reconstituted {n} bytes to {target}"); Ok(()) } fn cmd_decay(cli: &Cli, preset: &str) -> Result<()> { - let mut vault = Vault::open(&vault_path(&cli.data_dir), &cli.vault_pass)?; + let mut vault = Vault::open(&vault_path(&cli.data_dir), require_passphrase(cli)?)?; let pruned = vault.prune_with_decay(preset)?; println!("{} snapshots decayed.", pruned.len()); Ok(()) diff --git a/crates/tessera-core/src/config.rs b/crates/tessera-core/src/config.rs index 5257fee..d1b7754 100644 --- a/crates/tessera-core/src/config.rs +++ b/crates/tessera-core/src/config.rs @@ -18,7 +18,7 @@ pub struct HubConfig { impl Default for HubConfig { fn default() -> Self { Self { - listen: "0.0.0.0:8787".into(), + listen: "127.0.0.1:8787".into(), data_dir: "./data".into(), admin_password_hash: None, } diff --git a/crates/tessera-hub/Cargo.toml b/crates/tessera-hub/Cargo.toml index c512def..7965971 100644 --- a/crates/tessera-hub/Cargo.toml +++ b/crates/tessera-hub/Cargo.toml @@ -31,3 +31,14 @@ uuid.workspace = true hex.workspace = true base64 = "0.22" indexmap = "=2.2.6" +hyper = { version = "=1.12.0", features = ["server", "http1"] } +hyper-util = { version = "=0.1.21", features = ["tokio"] } +rustls = { version = "=0.23.23", default-features = false, features = ["ring", "std"] } +rustls-pemfile = "=2.2.0" +tokio-rustls = "=0.26.2" +tower = { workspace = true } + +[dev-dependencies] +rcgen = "=0.13.2" +tempfile.workspace = true +tokio.workspace = true diff --git a/crates/tessera-hub/src/admin.rs b/crates/tessera-hub/src/admin.rs new file mode 100644 index 0000000..aafa07f --- /dev/null +++ b/crates/tessera-hub/src/admin.rs @@ -0,0 +1,135 @@ +use axum::http::{HeaderMap, StatusCode}; +use std::net::SocketAddr; + +#[derive(Clone, Debug)] +pub struct AdminGate { + pub token: Option, +} + +impl AdminGate { + pub fn from_env() -> Self { + let token = std::env::var("TESSERA_ADMIN_TOKEN") + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()); + Self { token } + } + + pub fn log_policy(&self) { + if self.token.is_none() { + tracing::warn!( + "TESSERA_ADMIN_TOKEN is unset; snapshot, orbit, reconstitute, and pairing APIs are open to loopback clients only" + ); + } else { + tracing::info!( + "TESSERA_ADMIN_TOKEN is set; backup APIs require that token from every client" + ); + } + } + + pub fn authorize(&self, peer: SocketAddr, headers: &HeaderMap) -> Result<(), StatusCode> { + let presented = presented_token(headers); + match &self.token { + Some(expected) => { + if presented.is_some_and(|value| tokens_match(expected, value)) { + Ok(()) + } else { + Err(StatusCode::UNAUTHORIZED) + } + } + None if peer.ip().is_loopback() => Ok(()), + None => Err(StatusCode::UNAUTHORIZED), + } + } +} + +fn presented_token(headers: &HeaderMap) -> Option<&str> { + if let Some(value) = headers + .get("x-tessera-admin-token") + .and_then(|value| value.to_str().ok()) + { + let value = value.trim(); + if !value.is_empty() { + return Some(value); + } + } + let header = headers.get("authorization")?.to_str().ok()?; + let token = header + .strip_prefix("Bearer ") + .or_else(|| header.strip_prefix("bearer "))? + .trim(); + if token.is_empty() { + None + } else { + Some(token) + } +} + +fn tokens_match(expected: &str, presented: &str) -> bool { + let expected = expected.as_bytes(); + let presented = presented.as_bytes(); + let mut diff = expected.len() ^ presented.len(); + for (left, right) in expected.iter().zip(presented.iter()) { + diff |= (*left ^ *right) as usize; + } + diff == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::http::HeaderValue; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + + fn peer(ip: IpAddr) -> SocketAddr { + SocketAddr::new(ip, 9) + } + + #[test] + fn loopback_without_a_token_is_the_only_open_path() { + let gate = AdminGate { token: None }; + let headers = HeaderMap::new(); + assert!(gate + .authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers) + .is_ok()); + assert!(gate + .authorize(peer(IpAddr::V6(Ipv6Addr::LOCALHOST)), &headers) + .is_ok()); + assert!(gate + .authorize(peer(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 4))), &headers) + .is_err()); + } + + #[test] + fn a_configured_token_is_required_on_loopback() { + let gate = AdminGate { + token: Some("secret-token".into()), + }; + let mut headers = HeaderMap::new(); + assert!(gate + .authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers) + .is_err()); + headers.insert( + "authorization", + HeaderValue::from_static("Bearer secret-token"), + ); + assert!(gate + .authorize(peer(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 8))), &headers) + .is_ok()); + headers.remove("authorization"); + headers.insert( + "x-tessera-admin-token", + HeaderValue::from_static("secret-token"), + ); + assert!(gate + .authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers) + .is_ok()); + headers.insert( + "x-tessera-admin-token", + HeaderValue::from_static("secret-tokem"), + ); + assert!(gate + .authorize(peer(IpAddr::V4(Ipv4Addr::LOCALHOST)), &headers) + .is_err()); + } +} diff --git a/crates/tessera-hub/src/api/orbit.rs b/crates/tessera-hub/src/api/orbit.rs index b54a3c3..6a56565 100644 --- a/crates/tessera-hub/src/api/orbit.rs +++ b/crates/tessera-hub/src/api/orbit.rs @@ -37,7 +37,8 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result let provider_kind = match orbit.provider.as_str() { "filesystem" => ProviderKind::Filesystem, "postgres" => ProviderKind::Postgres, - _ => ProviderKind::Command, + "command" => ProviderKind::Command, + other => anyhow::bail!("unknown provider '{other}'"), }; let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?; let provider = provider_from_config(&provider_kind, &config)?; diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index 9c1d1ce..16df2ce 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -1,7 +1,8 @@ use crate::db::OrbitRow; -use crate::state::{HubState, PairingEntry}; +use crate::state::HubState; +use crate::upload::write_at; use axum::{ - extract::{Path, State}, + extract::{ConnectInfo, Path, State}, http::{header, HeaderMap, HeaderValue, StatusCode, Uri}, response::IntoResponse, routing::{get, post}, @@ -9,8 +10,11 @@ use axum::{ }; use base64::Engine; use include_dir::{include_dir, Dir}; +use std::fs::OpenOptions; +use std::io::{Read, Seek, SeekFrom}; +use std::net::SocketAddr; +use tessera_core::manifest::SnapshotManifest; use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS}; -use tessera_core::wormhole::PairingState; use tower_http::trace::TraceLayer; use utoipa::OpenApi; use uuid::Uuid; @@ -109,6 +113,14 @@ struct ReconstituteStartResponse { session: ReconstituteSession, } +fn require_admin( + state: &HubState, + peer: SocketAddr, + headers: &HeaderMap, +) -> Result<(), StatusCode> { + state.admin.authorize(peer, headers) +} + pub fn router(state: HubState) -> Router { let api = Router::new() .route("/health", get(health)) @@ -141,7 +153,12 @@ async fn health() -> &'static str { } #[utoipa::path(get, path = "/api/v1/snapshots", responses((status = 200, body = [SnapshotSummary])))] -async fn list_snapshots(State(state): State) -> Result>, StatusCode> { +async fn list_snapshots( + ConnectInfo(peer): ConnectInfo, + State(state): State, + headers: HeaderMap, +) -> Result>, StatusCode> { + require_admin(&state, peer, &headers)?; let vault = state.vault.read().await; let snaps = vault.list_snapshots().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; let out = snaps @@ -158,7 +175,12 @@ async fn list_snapshots(State(state): State) -> Result) -> Result>, StatusCode> { +async fn list_orbits( + ConnectInfo(peer): ConnectInfo, + State(state): State, + headers: HeaderMap, +) -> Result>, StatusCode> { + require_admin(&state, peer, &headers)?; state .db .list_orbits() @@ -169,9 +191,12 @@ async fn list_orbits(State(state): State) -> Result #[utoipa::path(post, path = "/api/v1/orbits", request_body = CreateOrbitRequest, responses((status = 200, body = OrbitRow)))] async fn create_orbit( + ConnectInfo(peer): ConnectInfo, State(state): State, + headers: HeaderMap, Json(req): Json, ) -> Result, StatusCode> { + require_admin(&state, peer, &headers)?; let row = OrbitRow { id: Uuid::new_v4(), name: req.name, @@ -190,19 +215,26 @@ async fn create_orbit( #[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")))))] async fn trigger_orbit( + ConnectInfo(peer): ConnectInfo, State(state): State, + headers: HeaderMap, Path(id): Path, -) -> Result<(StatusCode, HeaderMap), StatusCode> { +) -> 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) .await .map_err(|error| { tracing::warn!(orbit_id = %id, %error, "capture did not complete"); - StatusCode::INTERNAL_SERVER_ERROR + (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()) })?; let mut headers = HeaderMap::new(); if let Some(snapshot_id) = snapshot_id { - let value = HeaderValue::from_str(&snapshot_id.to_string()) - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let value = HeaderValue::from_str(&snapshot_id.to_string()).map_err(|_| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + "snapshot id header".into(), + ) + })?; headers.insert("x-tessera-snapshot-id", value); } Ok((StatusCode::NO_CONTENT, headers)) @@ -210,9 +242,12 @@ async fn trigger_orbit( #[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))] async fn start_reconstitute( + ConnectInfo(peer): ConnectInfo, State(state): State, + headers: HeaderMap, Json(req): Json, ) -> Result, StatusCode> { + require_admin(&state, peer, &headers)?; let session_id = Uuid::new_v4(); let session = ReconstituteSession { snapshot_id: req.snapshot_id, @@ -273,17 +308,23 @@ async fn start_reconstitute( } async fn reconstitute_status( + ConnectInfo(peer): ConnectInfo, State(state): State, + headers: HeaderMap, Path(id): Path, ) -> Result, StatusCode> { + require_admin(&state, peer, &headers)?; let map = state.reconstitute_sessions.read().await; map.get(&id).cloned().map(Json).ok_or(StatusCode::NOT_FOUND) } async fn abort_reconstitute( + ConnectInfo(peer): ConnectInfo, State(state): State, + headers: HeaderMap, Path(id): Path, ) -> Result { + require_admin(&state, peer, &headers)?; let mut map = state.reconstitute_sessions.write().await; if let Some(s) = map.get_mut(&id) { if matches!( @@ -298,7 +339,12 @@ async fn abort_reconstitute( } #[utoipa::path(post, path = "/api/v1/wormhole/pairing", responses((status = 200, body = PairingResponse)))] -async fn pairing_start(State(state): State) -> Json { +async fn pairing_start( + ConnectInfo(peer): ConnectInfo, + State(state): State, + headers: HeaderMap, +) -> Result, StatusCode> { + require_admin(&state, peer, &headers)?; let code: String = (0..6) .map(|_| { let n = rand::random::() % 36; @@ -312,14 +358,16 @@ async fn pairing_start(State(state): State) -> Json { 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()); - state.pairing_codes.write().await.push(PairingEntry { - code: code.clone(), - expires_at: expires, - state: PairingState::CodeShown, - outpost_id, - upload_token: upload_token.clone(), - }); - Json(PairingResponse { code, expires_at: expires }) + state + .db + .insert_wormhole_token( + &upload_token, + &outpost_id.to_string(), + &code, + &expires.to_rfc3339(), + ) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok(Json(PairingResponse { code, expires_at: expires })) } #[utoipa::path(post, path = "/api/v1/wormhole/claim", request_body = ClaimRequest, responses((status = 200, body = ClaimResponse)))] @@ -327,23 +375,28 @@ async fn pairing_claim( State(state): State, Json(req): Json, ) -> Result, StatusCode> { - let mut codes = state.pairing_codes.write().await; - let now = chrono::Utc::now(); - let entry = codes - .iter_mut() - .find(|c| c.code == req.code && c.expires_at > now) + let now = chrono::Utc::now().to_rfc3339(); + let claimed = state + .db + .claim_wormhole_code(&req.code, &req.outpost_name, &now) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .ok_or(StatusCode::GONE)?; - entry.state = PairingState::Active; - let hub_url = - std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8787".into()); + let hub_url = std::env::var("TESSERA_PUBLIC_URL").unwrap_or_else(|_| { + if state.wormhole_mtls { + "https://127.0.0.1:8788".into() + } else { + "http://127.0.0.1:8787".into() + } + }); state .db .audit("wormhole.paired", &req.outpost_name) .await .ok(); + let outpost_id = Uuid::parse_str(&claimed.1).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; Ok(Json(ClaimResponse { - outpost_id: entry.outpost_id, - upload_token: entry.upload_token.clone(), + outpost_id, + upload_token: claimed.0, hub_url, })) } @@ -354,16 +407,26 @@ async fn wormhole_upload_init( headers: axum::http::HeaderMap, Json(body): Json, ) -> Result, StatusCode> { - verify_upload_token(&state, &headers).await?; + verify_upload_token(&state, &headers)?; + let total = body.total_bytes.ok_or(StatusCode::BAD_REQUEST)?; let session_id = Uuid::new_v4(); state .db .insert_upload_session( &session_id.to_string(), &body.orbit_id.to_string(), - body.total_bytes.map(|t| t as i64), + Some(i64::try_from(total).map_err(|_| StatusCode::BAD_REQUEST)?), ) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if total == 0 { + let seal = state + .db + .record_range(&session_id.to_string(), 0, 0, 0) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if seal { + seal_upload(&state, session_id, body.orbit_id, Vec::new()).await?; + } + } Ok(Json(serde_json::json!({ "session_id": session_id }))) } @@ -373,39 +436,141 @@ async fn wormhole_upload_chunk( headers: axum::http::HeaderMap, Json(body): Json, ) -> Result { - verify_upload_token(&state, &headers).await?; + verify_upload_token(&state, &headers)?; + let session = state + .db + .upload_session(&body.session_id.to_string()) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + if session.sealed { + return Err(StatusCode::CONFLICT); + } let data = base64::engine::general_purpose::STANDARD .decode(&body.data_b64) .map_err(|_| StatusCode::BAD_REQUEST)?; - let tmp = state.data_dir.join("wormhole").join(format!("{}.part", body.session_id)); - if let Some(parent) = tmp.parent() { - std::fs::create_dir_all(parent).ok(); + let path = upload_part_path(&state, body.session_id); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; } - use std::io::Write; - let mut file = std::fs::OpenOptions::new() + let mut file = OpenOptions::new() .create(true) - .append(true) - .open(&tmp) + .read(true) + .write(true) + .open(&path) .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - file.write_all(&data).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + restrict_part(&path); + let range = write_at(&mut file, body.offset, &data, session.total).map_err(|error| { + if error.kind() == std::io::ErrorKind::InvalidInput { + StatusCode::BAD_REQUEST + } else { + StatusCode::INTERNAL_SERVER_ERROR + } + })?; + let seal = state + .db + .record_range( + &body.session_id.to_string(), + range.start, + range.end, + session.total, + ) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if seal { + let mut bytes = Vec::new(); + file.seek(SeekFrom::Start(0)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + file.read_to_end(&mut bytes) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if (bytes.len() as u64) < session.total { + let _ = state.db.mark_upload_unsealed(&body.session_id.to_string()); + return Err(StatusCode::INTERNAL_SERVER_ERROR); + } + bytes.truncate(session.total as usize); + if let Err(status) = seal_upload(&state, body.session_id, session.orbit_id, bytes).await { + let _ = state.db.mark_upload_unsealed(&body.session_id.to_string()); + return Err(status); + } + let _ = std::fs::remove_file(&path); + } Ok(StatusCode::NO_CONTENT) } -async fn verify_upload_token( - state: &HubState, - headers: &axum::http::HeaderMap, -) -> Result<(), StatusCode> { +fn upload_part_path(state: &HubState, session_id: Uuid) -> std::path::PathBuf { + state + .data_dir + .join("wormhole") + .join(format!("{session_id}.part")) +} + +fn restrict_part(path: &std::path::Path) { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); + } + #[cfg(not(unix))] + let _ = path; +} + +fn verify_upload_token(state: &HubState, headers: &HeaderMap) -> Result<(), StatusCode> { + if !state.accept_plain_upload { + return Err(StatusCode::FORBIDDEN); + } let token = headers .get("x-tessera-upload-token") .and_then(|v| v.to_str().ok()) .ok_or(StatusCode::UNAUTHORIZED)?; - if state.upload_token_valid(token).await { + if state.upload_token_valid(token) { Ok(()) } else { Err(StatusCode::UNAUTHORIZED) } } +async fn seal_upload( + state: &HubState, + session_id: Uuid, + orbit_id: Uuid, + bytes: Vec, +) -> Result<(), StatusCode> { + let orbits = state + .db + .list_orbits() + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let orbit = orbits.into_iter().find(|orbit| orbit.id == orbit_id); + let orbit_name = orbit + .as_ref() + .map(|orbit| orbit.name.clone()) + .unwrap_or_else(|| orbit_id.to_string()); + let decay = orbit + .as_ref() + .map(|orbit| orbit.decay_preset.clone()) + .unwrap_or_else(|| "week-of-dailies".into()); + let manifest = SnapshotManifest { + snapshot_id: Uuid::new_v4(), + orbit_id, + orbit_name, + labels: vec!["wormhole".into()], + provider: "wormhole".into(), + paths: vec![], + restore_hints: serde_json::json!({ "session_id": session_id }), + }; + let snap_id = { + let mut vault = state.vault.write().await; + let snap = vault + .snapshot(manifest, &bytes, false) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let _ = vault.prune_orbit_with_decay(orbit_id, &decay); + snap.id + }; + let _ = state + .db + .audit("wormhole.sealed", &format!("snapshot={snap_id}")) + .await; + Ok(()) +} + async fn spa_fallback(uri: Uri) -> impl IntoResponse { let mut path = uri.path().trim_start_matches('/').to_string(); if path.is_empty() { diff --git a/crates/tessera-hub/src/db.rs b/crates/tessera-hub/src/db.rs index eba0e7e..5db590c 100644 --- a/crates/tessera-hub/src/db.rs +++ b/crates/tessera-hub/src/db.rs @@ -66,8 +66,22 @@ impl Db { total INTEGER, created_at TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS wormhole_tokens ( + token TEXT PRIMARY KEY, + outpost_id TEXT NOT NULL, + code TEXT NOT NULL, + state TEXT NOT NULL, + expires_at TEXT NOT NULL, + outpost_name TEXT + ); + CREATE TABLE IF NOT EXISTS upload_ranges ( + session_id TEXT NOT NULL, + start_off INTEGER NOT NULL, + end_off INTEGER NOT NULL + ); "#, )?; + ensure_column(&conn, "upload_sessions", "sealed", "INTEGER NOT NULL DEFAULT 0")?; Ok(()) } @@ -137,9 +151,156 @@ impl Db { ) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( - "INSERT INTO upload_sessions (id, orbit_id, offset, total, created_at) VALUES (?1, ?2, 0, ?3, datetime('now'))", + "INSERT INTO upload_sessions (id, orbit_id, offset, total, sealed, created_at) VALUES (?1, ?2, 0, ?3, 0, datetime('now'))", params![id, orbit_id, total], )?; Ok(()) } + + pub fn insert_wormhole_token( + &self, + token: &str, + outpost_id: &str, + code: &str, + expires_at: &str, + ) -> Result<()> { + let conn = self.conn.lock().unwrap(); + conn.execute( + "INSERT INTO wormhole_tokens (token, outpost_id, code, state, expires_at) VALUES (?1, ?2, ?3, 'code_shown', ?4)", + params![token, outpost_id, code, expires_at], + )?; + Ok(()) + } + + pub fn claim_wormhole_code( + &self, + code: &str, + outpost_name: &str, + now: &str, + ) -> Result> { + 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", + params![code, outpost_name, now], + )?; + if changed != 1 { + return Ok(None); + } + 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)?))) + } + + pub fn upload_token_active(&self, token: &str) -> Result { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT 1 FROM wormhole_tokens WHERE token = ?1 AND state = 'active' LIMIT 1", + )?; + Ok(stmt.query_row(params![token], |_| Ok(())).is_ok()) + } + + pub fn upload_session(&self, id: &str) -> Result> { + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare( + "SELECT orbit_id, total, sealed FROM upload_sessions WHERE id = ?1", + )?; + let mut rows = stmt.query(params![id])?; + let Some(row) = rows.next()? else { + return Ok(None); + }; + let orbit_id: String = row.get(0)?; + let total: Option = row.get(1)?; + let sealed: i64 = row.get(2)?; + Ok(Some(UploadSession { + orbit_id: Uuid::parse_str(&orbit_id).map_err(|e| anyhow::anyhow!(e))?, + total: total.unwrap_or(0).max(0) as u64, + sealed: sealed != 0, + })) + } + + /// Records a received range. Returns whether this call won the right to seal. + pub fn record_range(&self, session_id: &str, start: u64, end: u64, total: u64) -> Result { + let conn = self.conn.lock().unwrap(); + conn.execute_batch("BEGIN IMMEDIATE")?; + let outcome = (|| -> Result { + let sealed: i64 = conn.query_row( + "SELECT sealed FROM upload_sessions WHERE id = ?1", + params![session_id], + |row| row.get(0), + )?; + if sealed != 0 { + return Ok(false); + } + conn.execute( + "INSERT INTO upload_ranges (session_id, start_off, end_off) VALUES (?1, ?2, ?3)", + params![session_id, start as i64, end as i64], + )?; + let mut stmt = + conn.prepare("SELECT start_off, end_off FROM upload_ranges WHERE session_id = ?1")?; + let ranges = stmt + .query_map(params![session_id], |row| { + Ok(crate::upload::ByteRange { + start: row.get::<_, i64>(0)? as u64, + end: row.get::<_, i64>(1)? as u64, + }) + })? + .collect::, _>>()?; + let covered = crate::upload::contiguous_from_zero(&ranges); + conn.execute( + "UPDATE upload_sessions SET offset = ?2 WHERE id = ?1", + params![session_id, covered as i64], + )?; + if covered >= total { + conn.execute( + "UPDATE upload_sessions SET sealed = 1 WHERE id = ?1 AND sealed = 0", + params![session_id], + )?; + return Ok(true); + } + Ok(false) + })(); + match outcome { + Ok(value) => { + conn.execute_batch("COMMIT")?; + Ok(value) + } + Err(error) => { + let _ = conn.execute_batch("ROLLBACK"); + Err(error) + } + } + } + + pub fn mark_upload_unsealed(&self, session_id: &str) -> Result<()> { + let conn = self.conn.lock().unwrap(); + conn.execute( + "UPDATE upload_sessions SET sealed = 0 WHERE id = ?1", + params![session_id], + )?; + Ok(()) + } +} + +#[derive(Debug, Clone)] +pub struct UploadSession { + pub orbit_id: Uuid, + pub total: u64, + pub sealed: bool, +} + +fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Result<()> { + let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?; + let names = stmt.query_map([], |row| row.get::<_, String>(1))?; + for name in names { + if name? == column { + return Ok(()); + } + } + conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?; + Ok(()) } diff --git a/crates/tessera-hub/src/main.rs b/crates/tessera-hub/src/main.rs index 384f1d4..789fa60 100644 --- a/crates/tessera-hub/src/main.rs +++ b/crates/tessera-hub/src/main.rs @@ -1,7 +1,10 @@ +mod admin; mod api; mod db; +mod mtls; mod scheduler; mod state; +mod upload; use anyhow::Result; use state::HubState; @@ -15,10 +18,22 @@ async fn main() -> Result<()> { .init(); let data_dir = std::env::var("TESSERA_DATA_DIR").unwrap_or_else(|_| "./data".into()); - let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "0.0.0.0:8787".into()); - let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE").unwrap_or_else(|_| "dev-vault-key".into()); + let listen = std::env::var("TESSERA_LISTEN").unwrap_or_else(|_| "127.0.0.1:8787".into()); + let vault_pass = std::env::var("TESSERA_VAULT_PASSPHRASE") + .ok() + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + anyhow::anyhow!( + "TESSERA_VAULT_PASSPHRASE is required and must be non-empty. Tessera does not ship a default passphrase." + ) + })?; + if vault_pass == "dev-vault-key" { + tracing::warn!( + "TESSERA_VAULT_PASSPHRASE is the old published example. New vaults refuse it; set a private passphrase." + ); + } - let state = HubState::bootstrap(&data_dir, &vault_pass).await?; + let mut state = HubState::bootstrap(&data_dir, &vault_pass).await?; if std::env::var("TESSERA_SEED_DEMO") .map(|v| v == "1" || v == "true") @@ -26,8 +41,9 @@ async fn main() -> Result<()> { { match tessera_demo::apply(std::path::Path::new(&data_dir), &vault_pass, false) { Ok(r) if !r.skipped => { - tracing::info!( - "demo seed: {} orbits, {} snapshots", + tracing::warn!( + "TESSERA_SEED_DEMO wrote demo backup history into {}: {} orbits, {} snapshots", + data_dir, r.orbits, r.snapshots ); @@ -41,11 +57,37 @@ async fn main() -> Result<()> { } scheduler::start_orbit_scheduler(state.clone()).await?; + state.admin.log_policy(); + if let Some(wormhole) = mtls::from_env()? { + state.wormhole_mtls = true; + state.accept_plain_upload = false; + let mut tls_state = state.clone(); + tls_state.accept_plain_upload = true; + let listen_addr = wormhole.listen; + let tls_app = api::router(tls_state); + tokio::spawn(async move { + if let Err(error) = mtls::serve(wormhole, tls_app).await { + tracing::error!("wormhole mTLS stopped: {error:#}"); + } + }); + tracing::info!("plain HTTP uploads are closed; wormhole clients use {listen_addr}"); + } + + let admin_token_unset = state.admin.token.is_none(); let app = api::router(state); let addr: SocketAddr = listen.parse()?; + if addr.ip().is_unspecified() && admin_token_unset { + tracing::warn!( + "listening on {addr}; backup APIs reject non-loopback clients until TESSERA_ADMIN_TOKEN is set" + ); + } tracing::info!("Tessera hub listening on {addr}"); let listener = tokio::net::TcpListener::bind(addr).await?; - axum::serve(listener, app).await?; + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await?; Ok(()) } diff --git a/crates/tessera-hub/src/mtls.rs b/crates/tessera-hub/src/mtls.rs new file mode 100644 index 0000000..1725b78 --- /dev/null +++ b/crates/tessera-hub/src/mtls.rs @@ -0,0 +1,145 @@ +use anyhow::{Context, Result}; +use axum::body::Body; +use axum::extract::Request; +use axum::response::Response; +use axum::Router; +use hyper::body::Incoming; +use hyper_util::rt::TokioIo; +use hyper_util::service::TowerToHyperService; +use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use rustls::server::WebPkiClientVerifier; +use rustls::RootCertStore; +use rustls::ServerConfig; +use std::convert::Infallible; +use std::fs::File; +use std::future::Future; +use std::io::BufReader; +use std::net::SocketAddr; +use std::path::Path; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context as TaskContext, Poll}; +use tokio::net::TcpListener; +use tokio_rustls::TlsAcceptor; +use tower::{Service, ServiceExt}; + +pub struct WormholeMtls { + pub listen: SocketAddr, + cert: Vec>, + key: PrivateKeyDer<'static>, + client_ca: RootCertStore, +} + +pub fn from_env() -> Result> { + let raw = std::env::var("TESSERA_WORMHOLE_MTLS").unwrap_or_default(); + let enabled = raw == "1" || raw.eq_ignore_ascii_case("true"); + if !enabled { + return Ok(None); + } + let cert = std::env::var("TESSERA_WORMHOLE_CERT").context( + "TESSERA_WORMHOLE_CERT is required when TESSERA_WORMHOLE_MTLS is enabled", + )?; + let key = std::env::var("TESSERA_WORMHOLE_KEY").context( + "TESSERA_WORMHOLE_KEY is required when TESSERA_WORMHOLE_MTLS is enabled", + )?; + let ca = std::env::var("TESSERA_WORMHOLE_CLIENT_CA").context( + "TESSERA_WORMHOLE_CLIENT_CA is required when TESSERA_WORMHOLE_MTLS is enabled", + )?; + let listen = std::env::var("TESSERA_WORMHOLE_LISTEN") + .unwrap_or_else(|_| "127.0.0.1:8788".into()) + .parse() + .context("TESSERA_WORMHOLE_LISTEN")?; + install_provider(); + Ok(Some(WormholeMtls { + listen, + cert: load_certs(Path::new(&cert))?, + key: load_key(Path::new(&key))?, + client_ca: load_ca(Path::new(&ca))?, + })) +} + +pub fn install_provider() { + let _ = rustls::crypto::ring::default_provider().install_default(); +} + +pub async fn serve(mtls: WormholeMtls, app: Router) -> Result<()> { + install_provider(); + let verifier = WebPkiClientVerifier::builder(Arc::new(mtls.client_ca)) + .build() + .map_err(|error| anyhow::anyhow!("wormhole client CA: {error}"))?; + let server = ServerConfig::builder() + .with_client_cert_verifier(verifier) + .with_single_cert(mtls.cert, mtls.key) + .map_err(|error| anyhow::anyhow!("wormhole certificate: {error}"))?; + let acceptor = TlsAcceptor::from(Arc::new(server)); + let listener = TcpListener::bind(mtls.listen) + .await + .with_context(|| format!("bind wormhole mTLS {}", mtls.listen))?; + tracing::info!( + "wormhole mTLS listening on {}; a client certificate is required", + mtls.listen + ); + loop { + let (tcp, _) = listener.accept().await.context("accept wormhole mTLS")?; + let acceptor = acceptor.clone(); + let app = app.clone(); + tokio::spawn(async move { + let Ok(tls) = acceptor.accept(tcp).await else { + return; + }; + let io = TokioIo::new(tls); + let service = TowerToHyperService::new(HyperApp(app)); + let _ = hyper::server::conn::http1::Builder::new() + .serve_connection(io, service) + .await; + }); + } +} + +#[derive(Clone)] +struct HyperApp(Router); + +impl Service> for HyperApp { + type Response = Response; + type Error = Infallible; + type Future = Pin> + Send>>; + + fn poll_ready(&mut self, _cx: &mut TaskContext<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, request: Request) -> Self::Future { + let app = self.0.clone(); + Box::pin(async move { + Ok(app + .oneshot(request.map(Body::new)) + .await + .unwrap_or_else(|error| match error {})) + }) + } +} + +pub fn load_certs(path: &Path) -> Result>> { + let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?); + rustls_pemfile::certs(&mut reader) + .collect::, _>>() + .context("parse certificate") +} + +pub fn load_key(path: &Path) -> Result> { + let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {}", path.display()))?); + rustls_pemfile::private_key(&mut reader) + .context("parse private key")? + .context("certificate file has no private key") +} + +pub fn load_ca(path: &Path) -> Result { + let mut roots = RootCertStore::empty(); + for cert in load_certs(path)? { + roots.add(cert).map_err(|error| anyhow::anyhow!("client CA: {error}"))?; + } + if roots.is_empty() { + anyhow::bail!("client CA file contained no certificates"); + } + Ok(roots) +} diff --git a/crates/tessera-hub/src/state.rs b/crates/tessera-hub/src/state.rs index 14501dc..743f0d6 100644 --- a/crates/tessera-hub/src/state.rs +++ b/crates/tessera-hub/src/state.rs @@ -1,10 +1,10 @@ +use crate::admin::AdminGate; 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_core::wormhole::PairingState; use tessera_store::Vault; use tokio::sync::{Mutex, RwLock}; use uuid::Uuid; @@ -15,18 +15,13 @@ pub struct HubState { pub data_dir: PathBuf, pub vault_passphrase: String, pub vault: Arc>, - pub pairing_codes: Arc>>, pub reconstitute_sessions: Arc>>, pub active_orbits: Arc>>, -} - -#[derive(Clone)] -pub struct PairingEntry { - pub code: String, - pub expires_at: chrono::DateTime, - pub state: PairingState, - pub outpost_id: Uuid, - pub upload_token: String, + pub admin: AdminGate, + pub wormhole_mtls: bool, + /// Token uploads are accepted on this listener. Plain HTTP turns this off + /// when wormhole mTLS is required, so those routes are not a bypass. + pub accept_plain_upload: bool, } impl HubState { @@ -49,14 +44,15 @@ impl HubState { data_dir, vault_passphrase: vault_pass.to_string(), vault: Arc::new(RwLock::new(vault)), - pairing_codes: Arc::new(RwLock::new(Vec::new())), reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())), active_orbits: Arc::new(Mutex::new(HashSet::new())), + admin: AdminGate::from_env(), + wormhole_mtls: false, + accept_plain_upload: true, }) } - pub async fn upload_token_valid(&self, token: &str) -> bool { - let codes = self.pairing_codes.read().await; - codes.iter().any(|c| c.upload_token == token && c.state == PairingState::Active) + pub fn upload_token_valid(&self, token: &str) -> bool { + self.db.upload_token_active(token).unwrap_or(false) } } diff --git a/crates/tessera-hub/src/upload.rs b/crates/tessera-hub/src/upload.rs new file mode 100644 index 0000000..883378f --- /dev/null +++ b/crates/tessera-hub/src/upload.rs @@ -0,0 +1,79 @@ +use std::fs::File; +use std::io::{self, Seek, SeekFrom, Write}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ByteRange { + pub start: u64, + pub end: u64, +} + +/// Bytes covered from offset 0 with no gap. Overlaps are merged. +pub fn contiguous_from_zero(ranges: &[ByteRange]) -> u64 { + let mut ordered: Vec = ranges + .iter() + .copied() + .filter(|range| range.end > range.start) + .collect(); + ordered.sort_by_key(|range| (range.start, range.end)); + let mut covered = 0u64; + for range in ordered { + if range.start > covered { + break; + } + covered = covered.max(range.end); + } + covered +} + +pub fn write_at(file: &mut File, offset: u64, data: &[u8], total: u64) -> io::Result { + let end = offset.checked_add(data.len() as u64).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows") + })?; + if end > total { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "chunk exceeds the declared upload size", + )); + } + file.seek(SeekFrom::Start(offset))?; + file.write_all(data)?; + Ok(ByteRange { start: offset, end }) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::NamedTempFile; + + #[test] + fn out_of_order_chunks_cover_the_object() { + assert_eq!( + contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]), + 0 + ); + assert_eq!( + contiguous_from_zero(&[ + ByteRange { start: 4, end: 8 }, + ByteRange { start: 0, end: 4 }, + ]), + 8 + ); + assert_eq!( + contiguous_from_zero(&[ + ByteRange { start: 0, end: 3 }, + ByteRange { start: 2, end: 5 }, + ]), + 5 + ); + } + + #[test] + fn writes_honor_offset() { + let mut file = NamedTempFile::new().unwrap(); + write_at(file.as_file_mut(), 3, b"def", 6).unwrap(); + write_at(file.as_file_mut(), 0, b"abc", 6).unwrap(); + assert!(write_at(file.as_file_mut(), 4, b"xyz", 6).is_err()); + let bytes = std::fs::read(file.path()).unwrap(); + assert_eq!(&bytes[..6], b"abcdef"); + } +} diff --git a/crates/tessera-providers/src/lib.rs b/crates/tessera-providers/src/lib.rs index b1da922..e872a50 100644 --- a/crates/tessera-providers/src/lib.rs +++ b/crates/tessera-providers/src/lib.rs @@ -26,6 +26,8 @@ pub fn provider_from_config(kind: &ProviderKind, config: &Value) -> Result Ok(Box::new(FilesystemProvider::from_config(config)?)), ProviderKind::Postgres => Ok(Box::new(PostgresProvider::from_config(config)?)), - ProviderKind::Command => anyhow::bail!("command provider not implemented in v1"), + ProviderKind::Command => anyhow::bail!( + "command provider is outside this release; use filesystem or postgres" + ), } } diff --git a/crates/tessera-providers/src/postgres.rs b/crates/tessera-providers/src/postgres.rs index 578a566..63b08e1 100644 --- a/crates/tessera-providers/src/postgres.rs +++ b/crates/tessera-providers/src/postgres.rs @@ -3,6 +3,9 @@ use anyhow::{Context, Result}; use async_trait::async_trait; use serde::Deserialize; use serde_json::json; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; use std::process::Stdio; use tessera_core::config::ProviderKind; use tokio::process::Command; @@ -22,6 +25,25 @@ pub struct PostgresProvider { config: PostgresConfig, } +#[derive(Debug)] +struct PgTarget { + host: String, + port: String, + user: String, + password: String, + dbname: String, +} + +struct PgpassFile { + path: PathBuf, +} + +impl Drop for PgpassFile { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + impl PostgresProvider { pub fn from_config(config: &serde_json::Value) -> Result { let config: PostgresConfig = serde_json::from_value(config.clone())?; @@ -29,6 +51,110 @@ impl PostgresProvider { } } +fn percent_decode(input: &str) -> Result { + let bytes = input.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + if bytes[index] == b'%' && index + 2 < bytes.len() { + let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).ok(); + if let Some(hex) = hex { + if let Ok(value) = u8::from_str_radix(hex, 16) { + out.push(value); + index += 3; + continue; + } + } + } + out.push(bytes[index]); + index += 1; + } + String::from_utf8(out).context("connection url is not utf-8") +} + +fn parse_postgres_url(url: &str) -> Result { + let rest = url + .strip_prefix("postgres://") + .or_else(|| url.strip_prefix("postgresql://")) + .context("postgres connection_url must start with postgres:// or postgresql://")?; + let (userinfo, hostpart) = rest.split_once('@').context("connection url is missing userinfo")?; + let (user, password) = userinfo + .split_once(':') + .context("connection url is missing a password")?; + let (hostport, dbpath) = hostpart.split_once('/').context("connection url is missing a database")?; + let dbname = dbpath.split('?').next().unwrap_or(dbpath); + let (host, port) = if let Some(host) = hostport.strip_prefix('[') { + let (host, port) = host + .split_once("]:") + .context("ipv6 connection url is missing a port")?; + (host.to_string(), port.to_string()) + } else if let Some((host, port)) = hostport.split_once(':') { + (host.to_string(), port.to_string()) + } else { + (hostport.to_string(), "5432".into()) + }; + if host.is_empty() || dbname.is_empty() { + anyhow::bail!("connection url is missing a host or database"); + } + Ok(PgTarget { + host, + port, + user: percent_decode(user)?, + password: percent_decode(password)?, + dbname: percent_decode(dbname)?, + }) +} + +fn escape_pgpass(value: &str) -> String { + value.replace('\\', "\\\\").replace(':', "\\:") +} + +fn write_pgpass(target: &PgTarget) -> Result { + 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 }) +} + +fn restrict_secret_file(path: &Path) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + } + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + +fn dump_args(format: &str) -> Result> { + match format { + "custom" => Ok(vec!["-Fc".into(), "-w".into()]), + "plain" => Ok(vec!["-w".into()]), + other => anyhow::bail!("unknown pg format: {other}"), + } +} + #[async_trait] impl BackupProvider for PostgresProvider { fn kind(&self) -> ProviderKind { @@ -36,17 +162,20 @@ impl BackupProvider for PostgresProvider { } async fn capture(&self) -> Result { + 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"); - cmd.arg(&self.config.connection_url); - match self.config.format.as_str() { - "custom" => { - cmd.arg("-Fc"); - } - "plain" => {} - other => anyhow::bail!("unknown pg format: {other}"), - } + cmd.args(&args); + cmd.env("PGPASSFILE", &pgpass.path); + cmd.env("PGHOST", &target.host); + cmd.env("PGPORT", &target.port); + cmd.env("PGUSER", &target.user); + cmd.env("PGDATABASE", &target.dbname); + cmd.env_remove("PGPASSWORD"); cmd.stdout(Stdio::piped()).stderr(Stdio::piped()); let output = cmd.output().await.context("pg_dump failed to start")?; + drop(pgpass); if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); anyhow::bail!("pg_dump failed: {stderr}"); @@ -56,8 +185,30 @@ impl BackupProvider for PostgresProvider { labels: vec!["postgres".into()], restore_hints: json!({ "format": self.config.format, - "restore_command_hint": "pg_restore -d $DATABASE_URL dump.file" + "restore_command_hint": "pg_restore -d \"$DATABASE_URL\" dump.file" }), }) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn pg_dump_keeps_the_url_out_of_argv() { + let target = parse_postgres_url("postgres://migrator:s%3Acret@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(); + assert!(rendered.contains("s\\:cret")); + assert!(!args.iter().any(|arg| arg.contains("s:cret") || arg.contains("postgres://"))); + let mode = fs::metadata(&pgpass.path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let joined = args.join(" "); + assert!(!joined.contains(&target.password)); + assert!(!joined.contains(&target.user)); + } +} diff --git a/crates/tessera-store/Cargo.toml b/crates/tessera-store/Cargo.toml index 13fcdfd..ffcb9e1 100644 --- a/crates/tessera-store/Cargo.toml +++ b/crates/tessera-store/Cargo.toml @@ -8,7 +8,7 @@ license.workspace = true tessera-core = { path = "../tessera-core" } anyhow.workspace = true aes-gcm.workspace = true -pbkdf2.workspace = true +argon2.workspace = true hmac.workspace = true sha2.workspace = true chrono.workspace = true diff --git a/crates/tessera-store/src/crypto.rs b/crates/tessera-store/src/crypto.rs index 18940f9..e44354c 100644 --- a/crates/tessera-store/src/crypto.rs +++ b/crates/tessera-store/src/crypto.rs @@ -1,10 +1,11 @@ use aes_gcm::aead::generic_array::GenericArray; -use aes_gcm::aead::{Aead, NewAead}; -use aes_gcm::Aes256Gcm; +use aes_gcm::aead::Aead; +use aes_gcm::{Aes256Gcm, KeyInit}; use anyhow::{anyhow, Result}; -use hmac::Hmac; -use pbkdf2::pbkdf2; +use argon2::{Algorithm, Argon2, Params, Version}; +use hmac::{Hmac, Mac}; use rand::RngCore; +use serde::{Deserialize, Serialize}; use sha2::Sha256; use std::fs; use std::path::Path; @@ -17,25 +18,37 @@ pub struct VaultKey { } impl VaultKey { + /// Opens an existing key or creates one. A salt with no `kdf.json` stays + /// PBKDF2 so vaults created before Argon2id still open. A missing salt is a + /// new vault and uses Argon2id. pub fn derive_from_passphrase(passphrase: &str, salt_path: &Path) -> Result { - let salt = if salt_path.exists() { - fs::read(salt_path)? - } else { - let mut salt = [0u8; SALT_LEN]; - rand::thread_rng().fill_bytes(&mut salt); - if let Some(parent) = salt_path.parent() { - fs::create_dir_all(parent)?; - } - fs::write(salt_path, &salt)?; - salt.to_vec() - }; + if passphrase.is_empty() { + anyhow::bail!("vault passphrase is required"); + } + let marker = salt_path.with_file_name("kdf.json"); + if marker.exists() { + let spec: KdfSpec = serde_json::from_slice(&fs::read(&marker)?)?; + let salt = fs::read(salt_path)?; + restrict_secret_file(salt_path)?; + return derive_marked(passphrase, &salt, &spec); + } + if salt_path.exists() { + restrict_secret_file(salt_path)?; + let salt = fs::read(salt_path)?; + return cipher_from_key(&pbkdf2_key(passphrase, &salt)); + } - let mut key = [0u8; 32]; - pbkdf2::>(passphrase.as_bytes(), &salt, 100_000, &mut key); - - let cipher = - Aes256Gcm::new_from_slice(&key).map_err(|e| anyhow!("cipher key: {e}"))?; - Ok(Self { cipher }) + let mut salt = [0u8; SALT_LEN]; + rand::thread_rng().fill_bytes(&mut salt); + if let Some(parent) = salt_path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(salt_path, &salt)?; + restrict_secret_file(salt_path)?; + let spec = KdfSpec::argon2id(); + fs::write(&marker, serde_json::to_vec_pretty(&spec)?)?; + restrict_secret_file(&marker)?; + derive_marked(passphrase, &salt, &spec) } pub fn encrypt(&self, plaintext: &[u8]) -> Result> { @@ -63,6 +76,100 @@ impl VaultKey { } } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +struct KdfSpec { + kdf: String, + #[serde(default = "default_m_kib")] + m_kib: u32, + #[serde(default = "default_t")] + t: u32, + #[serde(default = "default_p")] + p: u32, +} + +fn default_m_kib() -> u32 { + 19_456 +} +fn default_t() -> u32 { + 2 +} +fn default_p() -> u32 { + 1 +} + +impl KdfSpec { + fn argon2id() -> Self { + Self { + kdf: "argon2id".into(), + m_kib: default_m_kib(), + t: default_t(), + p: default_p(), + } + } +} + +fn pbkdf2_key(passphrase: &str, salt: &[u8]) -> [u8; 32] { + pbkdf2_hmac_sha256(passphrase.as_bytes(), salt, 100_000) +} + +fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], iterations: u32) -> [u8; 32] { + // RFC 8018 PBKDF2-HMAC-SHA256, one block (dkLen = 32). This is the historical + // vault KDF, so existing salt files still open. + type HmacSha256 = Hmac; + let mut block = { + let mut mac = + ::new_from_slice(password).expect("hmac accepts any key length"); + mac.update(salt); + mac.update(&1u32.to_be_bytes()); + mac.finalize().into_bytes() + }; + let mut derived = block; + for _ in 1..iterations { + let mut mac = + ::new_from_slice(password).expect("hmac accepts any key length"); + mac.update(&block); + block = mac.finalize().into_bytes(); + for (slot, byte) in derived.iter_mut().zip(block.iter()) { + *slot ^= *byte; + } + } + derived.into() +} + +fn derive_marked(passphrase: &str, salt: &[u8], spec: &KdfSpec) -> Result { + let key = match spec.kdf.as_str() { + "argon2id" => { + let params = Params::new(spec.m_kib, spec.t, spec.p, Some(32)) + .map_err(|e| anyhow!("argon2 params: {e}"))?; + let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); + let mut key = [0u8; 32]; + argon + .hash_password_into(passphrase.as_bytes(), salt, &mut key) + .map_err(|e| anyhow!("argon2id: {e}"))?; + key + } + "pbkdf2" => pbkdf2_key(passphrase, salt), + other => anyhow::bail!("unknown vault kdf: {other}"), + }; + cipher_from_key(&key) +} + +fn cipher_from_key(key: &[u8; 32]) -> Result { + let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| anyhow!("cipher key: {e}"))?; + Ok(VaultKey { cipher }) +} + +fn restrict_secret_file(path: &Path) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + } + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + pub fn content_id(data: &[u8]) -> String { use sha2::Digest; hex::encode(Sha256::digest(data)) @@ -76,6 +183,9 @@ pub fn pack_path(data_dir: &Path, id: &str) -> std::path::PathBuf { #[cfg(test)] mod tests { use super::*; + use aes_gcm::aead::generic_array::GenericArray; + use aes_gcm::aead::Aead; + use aes_gcm::{Aes256Gcm, KeyInit}; use tempfile::tempdir; #[test] @@ -87,4 +197,63 @@ mod tests { let plain = key.decrypt(&enc).unwrap(); assert_eq!(plain, b"stardust"); } + + #[test] + fn rejects_empty_passphrase() { + let dir = tempdir().unwrap(); + let err = VaultKey::derive_from_passphrase("", &dir.path().join("salt")); + assert!(err.is_err()); + } + + #[cfg(unix)] + #[test] + fn salt_file_is_owner_only() { + use std::os::unix::fs::PermissionsExt; + let dir = tempdir().unwrap(); + let salt = dir.path().join("salt"); + VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); + let mode = fs::metadata(&salt).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + } + + #[test] + fn new_vault_uses_argon2id() { + let dir = tempdir().unwrap(); + let salt = dir.path().join("tessera.salt"); + let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); + let marker: serde_json::Value = + serde_json::from_slice(&fs::read(dir.path().join("kdf.json")).unwrap()).unwrap(); + assert_eq!(marker["kdf"], "argon2id"); + let enc = key.encrypt(b"stardust").unwrap(); + let raw_salt = fs::read(&salt).unwrap(); + let legacy = pbkdf2_key("test-vault", &raw_salt); + let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap(); + let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]); + assert!(legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).is_err()); + assert_eq!(key.decrypt(&enc).unwrap(), b"stardust"); + } + + #[test] + fn pbkdf2_matches_the_rfc_vector() { + let key = super::pbkdf2_hmac_sha256(b"password", b"salt", 4096); + assert_eq!( + hex::encode(key), + "c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a" + ); + } + + #[test] + fn existing_pbkdf2_salt_still_opens() { + let dir = tempdir().unwrap(); + let salt = dir.path().join("tessera.salt"); + fs::write(&salt, b"0123456789abcdef").unwrap(); + let key = VaultKey::derive_from_passphrase("test-vault", &salt).unwrap(); + assert!(!dir.path().join("kdf.json").exists()); + let enc = key.encrypt(b"legacy").unwrap(); + let legacy = pbkdf2_key("test-vault", b"0123456789abcdef"); + let legacy_cipher = Aes256Gcm::new_from_slice(&legacy).unwrap(); + let nonce = GenericArray::from_slice(&enc[..NONCE_LEN]); + let plain = legacy_cipher.decrypt(nonce, &enc[NONCE_LEN..]).unwrap(); + assert_eq!(plain, b"legacy"); + } } diff --git a/crates/tessera-store/src/vault.rs b/crates/tessera-store/src/vault.rs index 17d00bd..25301b0 100644 --- a/crates/tessera-store/src/vault.rs +++ b/crates/tessera-store/src/vault.rs @@ -28,11 +28,17 @@ pub struct Vault { impl Vault { pub fn init(root: impl AsRef, passphrase: &str) -> Result { + if passphrase == "dev-vault-key" { + anyhow::bail!( + "refusing to initialize a vault with the published dev passphrase; choose a private passphrase" + ); + } let root = root.as_ref().to_path_buf(); fs::create_dir_all(root.join("data"))?; fs::create_dir_all(root.join("snapshots"))?; fs::create_dir_all(root.join("index"))?; fs::create_dir_all(root.join("keys"))?; + restrict_dir(&root.join("keys"))?; let config_path = root.join("config"); if !config_path.exists() { @@ -56,6 +62,7 @@ impl Vault { if !root.join("config").exists() { anyhow::bail!("vault not initialized"); } + restrict_dir(&root.join("keys"))?; let salt = root.join("keys/tessera.salt"); let key = VaultKey::derive_from_passphrase(passphrase, &salt)?; let index = Self::load_index(&root)?; @@ -150,14 +157,28 @@ impl Vault { tree_root: chunk_id, }; + let plain = serde_json::to_vec(&snap)?; + let enc = self.key.encrypt(&plain)?; let path = self .root .join("snapshots") - .join(format!("{}.json", snap.id)); - fs::write(&path, serde_json::to_string_pretty(&snap)?)?; + .join(format!("{}.json.enc", snap.id)); + fs::write(&path, &enc)?; Ok(snap) } + fn read_snapshot_file(&self, path: &Path) -> Result { + let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); + if name.ends_with(".json.enc") { + let plain = self.key.decrypt(&fs::read(path)?)?; + Ok(serde_json::from_slice(&plain)?) + } else if name.ends_with(".json") { + Ok(serde_json::from_str(&fs::read_to_string(path)?)?) + } else { + anyhow::bail!("not a snapshot file"); + } + } + pub fn list_snapshots(&self) -> Result> { let dir = self.root.join("snapshots"); if !dir.exists() { @@ -166,21 +187,21 @@ impl Vault { let mut out = Vec::new(); for entry in fs::read_dir(&dir)? { let path = entry?.path(); - if path.extension().and_then(|e| e.to_str()) != Some("json") { + let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); + if !(name.ends_with(".json") || name.ends_with(".json.enc")) { continue; } - let data = fs::read_to_string(&path)?; - let snap: StoredSnapshot = serde_json::from_str(&data)?; - out.push(snap); + out.push(self.read_snapshot_file(&path)?); } out.sort_by(|a, b| b.taken_at.cmp(&a.taken_at)); Ok(out) } pub fn restore_snapshot(&self, id: Uuid, dest: &Path) -> Result { - let path = self.root.join("snapshots").join(format!("{id}.json")); - let data = fs::read_to_string(&path).context("snapshot metadata")?; - let snap: StoredSnapshot = serde_json::from_str(&data)?; + let 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 bytes = self.read_chunk(&snap.tree_root)?; if let Some(parent) = dest.parent() { fs::create_dir_all(parent)?; @@ -192,9 +213,15 @@ impl Vault { pub fn forget(&mut self, ids: &[Uuid]) -> Result { let mut removed = 0; for id in ids { - let path = self.root.join("snapshots").join(format!("{id}.json")); - if path.exists() { - fs::remove_file(&path)?; + let mut gone = false; + for suffix in [".json.enc", ".json"] { + let path = self.root.join("snapshots").join(format!("{id}{suffix}")); + if path.exists() { + fs::remove_file(&path)?; + gone = true; + } + } + if gone { removed += 1; } } @@ -236,6 +263,19 @@ impl Vault { } } +fn restrict_dir(path: &Path) -> Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if path.exists() { + fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; + } + } + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -315,4 +355,69 @@ mod tests { .iter() .any(|s| s.manifest.orbit_id == other_id)); } + + #[test] + fn new_snapshots_are_encrypted_and_legacy_json_still_reads() { + let dir = tempdir().unwrap(); + let mut vault = Vault::init(dir.path(), "secret").unwrap(); + let legacy_id = Uuid::new_v4(); + let legacy = StoredSnapshot { + id: legacy_id, + taken_at: DateTime::from_timestamp(1_700_000_000, 0).unwrap(), + manifest: SnapshotManifest { + snapshot_id: legacy_id, + orbit_id: Uuid::new_v4(), + orbit_name: "legacy".into(), + labels: vec![], + provider: "filesystem".into(), + paths: vec![], + restore_hints: serde_json::json!({}), + }, + size_bytes: 4, + tree_root: "missing".into(), + }; + fs::write( + dir.path().join("snapshots").join(format!("{legacy_id}.json")), + serde_json::to_string(&legacy).unwrap(), + ) + .unwrap(); + + let manifest = SnapshotManifest { + snapshot_id: Uuid::new_v4(), + orbit_id: Uuid::new_v4(), + orbit_name: "new".into(), + labels: vec![], + provider: "filesystem".into(), + paths: vec![], + restore_hints: serde_json::json!({}), + }; + let snap = vault.snapshot(manifest, b"cipher", false).unwrap(); + assert!(dir + .path() + .join("snapshots") + .join(format!("{}.json.enc", snap.id)) + .exists()); + assert!(!dir + .path() + .join("snapshots") + .join(format!("{}.json", snap.id)) + .exists()); + let names: Vec<_> = vault + .list_snapshots() + .unwrap() + .into_iter() + .map(|s| s.manifest.orbit_name) + .collect(); + assert!(names.contains(&"legacy".to_string())); + assert!(names.contains(&"new".to_string())); + let out = dir.path().join("restored.bin"); + assert_eq!(vault.restore_snapshot(snap.id, &out).unwrap(), 6); + } + + #[test] + fn init_rejects_published_dev_passphrase() { + let dir = tempdir().unwrap(); + assert!(Vault::init(dir.path(), "dev-vault-key").is_err()); + assert!(Vault::init(dir.path(), "").is_err()); + } } diff --git a/docs/SPEC.md b/docs/SPEC.md index d841308..0758007 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -112,7 +112,7 @@ Tessera is a self-hosted backup vault. This document is the contract for metapho │ issue device token + id │ │───────────────────────────────►│ │ │ - │ mTLS or Bearer on upload API │ + │ Bearer upload token on upload API │ │◄───────────────────────────────│ ``` @@ -139,12 +139,13 @@ Tone: short sentences, metaphor in headings, facts in telemetry panels. ## Security baseline -1. **Vault key:** Argon2id-derived key from passphrase; key file `keys/tessera.key` (mode 0600). Never logged. -2. **Hub auth (v1):** Local admin password → HTTP-only session cookie; hook point for OIDC later. -3. **Agents:** No vault master key. Hub issues **scoped upload tokens** per outpost/orbit after pairing. -4. **Wormhole:** v1 token-based HTTPS upload; mTLS optional when `TESSERA_WORMHOLE_MTLS=1` and certs present. -5. **Control plane:** SQLite (`data/tessera.db`) holds metadata only—no backup payloads. -6. **Audit:** Pairing, reconstitute start/complete, decay prune logged to `audit_log` table. +1. **Vault key:** New vaults use Argon2id (19 MiB, time cost 2, parallelism 1). The salt is `keys/tessera.salt` (mode 0600) and the parameters are `keys/kdf.json`. A salt with no `kdf.json` stays PBKDF2-HMAC-SHA256, 100,000 iterations, so vaults created before Argon2id still open. The derived key is not stored. Never log the passphrase. New vaults refuse the published passphrase `dev-vault-key`. New snapshot metadata is AES-GCM ciphertext in `{id}.json.enc`. Existing plaintext `{id}.json` files still list and restore. Chunk index JSON stays plaintext. +2. **Hub auth:** `TESSERA_ADMIN_TOKEN` is optional and local. When it is unset, the hub logs that snapshot, orbit list/create/run, reconstitute, and pairing routes are open to loopback peers only; every other peer gets 401. When it is set, every peer, including loopback, must send `Authorization: Bearer ` or `X-Tessera-Admin-Token`. The compare is constant time. `/health`, OpenAPI, wormhole claim, and wormhole upload are not on this gate. The default listen address is `127.0.0.1:8787`. The canvas does not send the token, so a token-protected hub and a Docker-published port (the peer inside the container is not loopback) will 401 those routes from the page. OIDC is not implemented. +3. **Agents:** No vault master key. After pairing, the hub issues an upload token stored in SQLite. The token survives a hub restart. Claim is an atomic update of a pairing code that has not expired. +4. **Wormhole:** Uploads require `total_bytes`. Chunks are written at `offset` into a mode `0600` `.part` file. When the recorded ranges cover the object from byte 0, the hub seals the bytes with `Vault::snapshot` (encrypted metadata), prunes decay, and deletes the `.part`. A later chunk on a sealed session is 409. `TESSERA_WORMHOLE_MTLS=1` (or `true`) starts a separate rustls listener that requires a client certificate. It needs `TESSERA_WORMHOLE_CERT`, `TESSERA_WORMHOLE_KEY`, and `TESSERA_WORMHOLE_CLIENT_CA`. `TESSERA_WORMHOLE_LISTEN` defaults to `127.0.0.1:8788`. While that listener is running, the plain HTTP upload routes return 403. An `https://` agent needs `TESSERA_WORMHOLE_CA`, `TESSERA_WORMHOLE_CLIENT_CERT`, and `TESSERA_WORMHOLE_CLIENT_KEY`. +5. **Providers:** Filesystem and Postgres are in this release. The command provider is rejected with `command provider is outside this release; use filesystem or postgres`. Postgres parses `postgres://` or `postgresql://`, writes the password to a mode `0600` pgpass file, and passes `PGPASSFILE`, `PGHOST`, `PGPORT`, `PGUSER`, and `PGDATABASE`. The URL and password are not process arguments. +6. **Control plane:** SQLite (`data/tessera.db`) holds metadata, pairing codes, upload tokens, and upload ranges — no backup payloads. +7. **Audit:** Pairing, wormhole seal, reconstitute start/complete, and decay prune are logged to `audit_log`. --- diff --git a/docs/UI.md b/docs/UI.md index fa000d9..58f22b4 100644 --- a/docs/UI.md +++ b/docs/UI.md @@ -4,12 +4,14 @@ 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. **Locked** freezes their motion and prioritizes labels for the selected, failed, and running orbits. Pause or resume from the map toolbar. Selecting an orbit locks the map. Reduced motion starts in Locked mode. +- **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. - 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. - 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. +- 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. ## Data and rendering @@ -18,6 +20,14 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep - Successful capture preserves HTTP 204 and supplies `X-Tessera-Snapshot-Id` when it retained a new snapshot. Automatic decay applies to that orbit's history. - The scene uses SVG with static artwork and one animation clock. The clock pauses when the tab is hidden. Labels are laid out in screen coordinates. +## 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. +- 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. +- Honor live changes to `prefers-reduced-motion`. The app applies declarative targets immediately. Imperative effects must stop and jump to the appropriate static state themselves. Verify reversals before settling, the final target, and reduced motion in a browser. + ## Local verification Build the web UI before building the hub, which embeds the generated assets. diff --git a/web/AGENTS.md b/web/AGENTS.md new file mode 100644 index 0000000..bdeb3b3 --- /dev/null +++ b/web/AGENTS.md @@ -0,0 +1,3 @@ +# Web animation + +Follow the [animation guideline](../docs/UI.md#animation-guideline) for component transitions and scene motion. Use the shared Framer Motion physics spring and retarget the same element or MotionValue so interruption preserves velocity. diff --git a/web/package.json b/web/package.json index 736bcc5..560419f 100644 --- a/web/package.json +++ b/web/package.json @@ -2,6 +2,7 @@ "name": "tessera-web", "private": true, "version": "0.1.0", + "license": "AGPL-3.0-or-later", "type": "module", "scripts": { "dev": "vite", diff --git a/web/src/App.tsx b/web/src/App.tsx index 18c0862..8ecd3fd 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1,4 +1,5 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { AnimatePresence } from "motion/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute, @@ -14,6 +15,7 @@ import { ReconstituteWizard } from "./components/reconstitute/ReconstituteWizard import { VaultScene } from "./components/scene/VaultScene"; import { EmptyState } from "./components/ui/EmptyState"; import { QueryGate } from "./components/ui/QueryGate"; +import { SpringPane } from "./components/ui/SpringPane"; import { SnapshotSheet } from "./components/vault/SnapshotSheet"; import { useReducedMotion } from "./hooks/useReducedMotion"; import { orbitStatus } from "./lib/format"; @@ -38,6 +40,7 @@ export default function App() { const workspaceScroll = useRef(undefined); const [bigScreen, setBigScreen] = useState(false); const [mode, setMode] = useState("scene"); + const panelOpen = mode !== "scene"; const [orbitId, setOrbitId] = useState(); const [snapshotId, setSnapshotId] = useState(null); const [pairing, setPairing] = useState<{ code: string; expires_at: string } | null>(null); @@ -169,14 +172,14 @@ export default function App() {
TesseraBackup control
- +

{online ? "Hub online" : health.isPending ? "Connecting" : "Hub offline"}

-
+

Vault / 01

@@ -227,22 +230,34 @@ export default function App() {
setMode("scene")} > - {mode === "orbits" && ( - - {() => } - - )} - {mode === "wormhole" && } - {mode === "decay" && orbit.decay_preset ?? "week-of-dailies")} />} - {mode === "snapshot" && (snapshot ? ( - openConsole("reconstitute", snapshot.id)} /> - ) : )} - + ); diff --git a/web/src/components/hud/DiegeticHUD.tsx b/web/src/components/hud/DiegeticHUD.tsx index b4355a5..7d275d1 100644 --- a/web/src/components/hud/DiegeticHUD.tsx +++ b/web/src/components/hud/DiegeticHUD.tsx @@ -1,6 +1,9 @@ +import { AnimatePresence, motion } from "motion/react"; import type { KeyboardEvent, ReactNode } from "react"; import type { Orbit, Snapshot } from "../../api"; +import { useReducedMotion } from "../../hooks/useReducedMotion"; import { formatBytes, formatWhen, orbitStatus, schedulePhrase } from "../../lib/format"; +import { SpringPane } from "../ui/SpringPane"; export function TelemetryStrip({ orbitCount, failedCount, snapCount, totalBytes, @@ -29,6 +32,7 @@ export function OrbitRegister({ onSelect: (id: string) => void; onManage: () => void; }) { + const reducedMotion = useReducedMotion(); const active = orbits.some(({ id }) => id === selected) ? selected : orbits[0]?.id; function moveFocus(event: KeyboardEvent, index: number) { @@ -47,11 +51,11 @@ export function OrbitRegister({

Orbits

{message &&

{message}

} -
    + {orbits.map((orbit, index) => { const status = orbitStatus(orbit.last_status); return ( -
  • + -
  • + ); })} -
+
- - ))} - - - - ) : ( -

Choose a star on the map or an orbit in the register to inspect its status and recovery points.

- )} +
+ + {orbit ? ( + +

{schedulePhrase(orbit.schedule, orbit.dry_run)}

+
{capture}
+
+
+

Snapshot history

+ {snapshots.length.toString().padStart(2, "0")} +
+ {snapshotMessage &&

{snapshotMessage}

} +
    + {snapshots.map((snapshot, index) => ( +
  • + +
  • + ))} +
+
+
+ ) : ( + +

Choose a star on the map or an orbit in the register to inspect its status and recovery points.

+
+ )} +
+
); } diff --git a/web/src/components/hud/HUDPanel.tsx b/web/src/components/hud/HUDPanel.tsx index 4e5ba08..9cd63eb 100644 --- a/web/src/components/hud/HUDPanel.tsx +++ b/web/src/components/hud/HUDPanel.tsx @@ -1,4 +1,5 @@ -import { useId, useLayoutEffect, useRef, type ReactNode } from "react"; +import { motion } from "motion/react"; +import { useEffect, useId, useLayoutEffect, useRef, type ReactNode } from "react"; export function HUDPanel({ open, title, subtitle, onClose, children, @@ -9,46 +10,73 @@ export function HUDPanel({ onClose: () => void; children: ReactNode; }) { - const dialog = useRef(null); + const panel = useRef(null); const heading = useRef(null); + const returnFocus = useRef(null); + const lastHeading = useRef({ title, subtitle }); const labelId = useId(); const descriptionId = useId(); useLayoutEffect(() => { - const panel = dialog.current; - if (!open || !panel) return; - panel.showModal(); - return () => panel.close(); + const focused = document.activeElement; + if (open) { + returnFocus.current = focused instanceof HTMLElement ? focused : null; + if (!focused?.closest(".vault-nav")) heading.current?.focus({ preventScroll: true }); + } else if (returnFocus.current && (panel.current?.contains(focused) || focused === document.body)) { + const previous = returnFocus.current; + const target = previous.isConnected && previous !== document.body + ? previous + : document.querySelector(".vault-nav button[aria-current]"); + target?.focus({ preventScroll: true }); + } }, [open]); useLayoutEffect(() => { - if (open) heading.current?.focus(); - }, [open, title]); + if (open) { + lastHeading.current = { title, subtitle }; + panel.current?.scrollTo(0, 0); + } + }, [open, title, subtitle]); + + useEffect(() => { + if (!open) return; + const closeOnEscape = (event: KeyboardEvent) => { + if (event.key !== "Escape" || event.defaultPrevented || event.repeat) return; + event.preventDefault(); + onClose(); + }; + window.addEventListener("keydown", closeOnEscape); + return () => window.removeEventListener("keydown", closeOnEscape); + }, [open, onClose]); + + const display = open ? { title, subtitle } : lastHeading.current; return ( - { - event.preventDefault(); - onClose(); - }} - > - {open && ( +
+
+
{children}
+ +
); } diff --git a/web/src/components/hud/HUDRail.tsx b/web/src/components/hud/HUDRail.tsx index c935784..230ca7c 100644 --- a/web/src/components/hud/HUDRail.tsx +++ b/web/src/components/hud/HUDRail.tsx @@ -1,31 +1,189 @@ +import { animate, motion, useMotionValue, useTransform, useVelocity } from "motion/react"; +import { useCallback, useId, useLayoutEffect, useRef, type PointerEvent } from "react"; +import { uiSpring } from "../../lib/motion"; + export type HUDMode = "scene" | "orbits" | "wormhole" | "decay" | "reconstitute" | "snapshot"; const items = [ - { id: "scene", label: "Vault" }, - { id: "orbits", label: "Orbits" }, - { id: "wormhole", label: "Outposts" }, - { id: "decay", label: "Retention" }, - { id: "reconstitute", label: "Restore" }, + { 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; +type Slot = { center: number; width: number }; +type Gesture = { pointer: number; x: number; y: number; origin?: number }; + export function HUDRail({ - active, onSelect, + active, floating, panelOpen, reducedMotion, onSelect, }: { active: HUDMode; + floating: boolean; + panelOpen: boolean; + reducedMotion: boolean; onSelect: (mode: HUDMode) => void; }) { + const nav = useRef(null); + const slots = useRef([]); + const gesture = useRef(undefined); + const suppressClick = useRef(false); + const center = useMotionValue(0); + const width = useMotionValue(0); + 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 snap = useCallback((index: number, immediate = false) => { + const slot = slots.current[index]; + if (!slot) return; + if (immediate || reducedMotion) { + center.jump(slot.center); + width.jump(slot.width); + } else { + animate(center, slot.center, uiSpring); + animate(width, slot.width, uiSpring); + } + }, [center, reducedMotion, width]); + + useLayoutEffect(() => () => { + center.stop(); + width.stop(); + }, [center, width]); + + useLayoutEffect(() => { + 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 changed = next.some((slot, index) => + slot.center !== slots.current[index]?.center || slot.width !== slots.current[index]?.width, + ); + slots.current = next; + if (changed) gesture.current = undefined; + return changed; + }; + snap(activeIndex, measure()); + const observer = new ResizeObserver(() => { + if (measure()) snap(activeIndex, true); + }); + observer.observe(element); + buttons.forEach(button => observer.observe(button)); + return () => observer.disconnect(); + }, [activeIndex, floating, snap]); + + function start(event: PointerEvent) { + if (!event.isPrimary || event.button !== 0) return; + suppressClick.current = false; + const button = (event.target as Element).closest("button"); + if (button?.hasAttribute("aria-current")) { + gesture.current = { pointer: event.pointerId, x: event.clientX, y: event.clientY }; + } + } + + function move(event: PointerEvent) { + const drag = gesture.current; + if (drag?.pointer !== event.pointerId) return; + const dx = event.clientX - drag.x; + if (drag.origin === undefined) { + if (Math.abs(dx) < 5 || Math.abs(dx) < Math.abs(event.clientY - drag.y)) return; + center.stop(); + drag.origin = center.get(); + suppressClick.current = true; + event.currentTarget.setPointerCapture(event.pointerId); + } + center.set(Math.max(slots.current[0].center, Math.min(slots.current.at(-1)!.center, drag.origin + dx))); + } + + function finish(event: PointerEvent) { + const drag = gesture.current; + if (drag?.pointer !== event.pointerId) return; + gesture.current = undefined; + if (drag.origin === undefined) return; + if (event.type !== "pointerup") { + snap(activeIndex); + return; + } + + const projected = center.get() + Math.max(-18, Math.min(18, center.getVelocity() * 0.1)); + const next = slots.current.reduce((nearest, slot, index) => + 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); + } + return ( - + ); } diff --git a/web/src/components/orbits/OrbitsView.tsx b/web/src/components/orbits/OrbitsView.tsx index c07e525..8d5bb5a 100644 --- a/web/src/components/orbits/OrbitsView.tsx +++ b/web/src/components/orbits/OrbitsView.tsx @@ -1,4 +1,5 @@ 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 } from "../../api"; @@ -7,6 +8,7 @@ import { Button } from "../ui/Button"; import { OrbitStatusDot } from "../ui/StatusDot"; import { TelemetryPanel } from "../ui/Telemetry"; import { Hint } from "../ui/EmptyState"; +import { SpringPane } from "../ui/SpringPane"; export function OrbitsView({ orbits, onRun, captureDisabled, notice, @@ -80,74 +82,82 @@ export function OrbitsView({ ))} - {editing ? ( -
-

New orbit

- - - - - - - Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”. - - {create.isError &&

The orbit could not be saved.

} -
- - -
-
- ) : ( - - )} +
+ + {editing ? ( + +
+

New orbit

+ + + + + + + Rehearse orbits prove the path without writing to the vault — status shows amber “rehearsed”. + + {create.isError &&

The orbit could not be saved.

} +
+ + +
+
+
+ ) : ( + + + + )} +
+
); } diff --git a/web/src/components/outposts/WormholeView.tsx b/web/src/components/outposts/WormholeView.tsx index 162dd72..ee01780 100644 --- a/web/src/components/outposts/WormholeView.tsx +++ b/web/src/components/outposts/WormholeView.tsx @@ -1,6 +1,8 @@ import { useMutation } from "@tanstack/react-query"; import { motion } from "motion/react"; import { startPairing } from "../../api"; +import { useReducedMotion } from "../../hooks/useReducedMotion"; +import { ambientPulse } from "../../lib/motion"; import { Button } from "../ui/Button"; import { Hint } from "../ui/EmptyState"; import { TelemetryPanel } from "../ui/Telemetry"; @@ -16,6 +18,7 @@ export function WormholeView({ mutationFn: startPairing, onSuccess: onPaired, }); + const reducedMotion = useReducedMotion(); const expires = pairing ? new Date(pairing.expires_at).toLocaleTimeString() : ""; @@ -31,7 +34,7 @@ export function WormholeView({ ) : (

@@ -73,15 +76,19 @@ function EmptyWormhole({ onGenerate: () => void; loading: boolean; }) { + const reducedMotion = useReducedMotion(); return (

- +
+

Open a wormhole when you're ready to claim an outpost.

diff --git a/web/src/components/reconstitute/ReconstituteWizard.tsx b/web/src/components/reconstitute/ReconstituteWizard.tsx index 2da9d1c..0d1a8da 100644 --- a/web/src/components/reconstitute/ReconstituteWizard.tsx +++ b/web/src/components/reconstitute/ReconstituteWizard.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from "react"; +import { motion } from "motion/react"; import type { Snapshot } from "../../api"; import { formatBytes, formatWhen } from "../../lib/format"; import { Button } from "../ui/Button"; @@ -108,21 +109,23 @@ export function ReconstituteWizard({ {inCountdown && ( -
- @@ -132,7 +135,7 @@ export function ReconstituteWizard({

Reconstituting in {remaining}s — abort restores nothing.

-
+ )}
diff --git a/web/src/components/scene/BlackholeGalaxy.tsx b/web/src/components/scene/BlackholeGalaxy.tsx index 82433bb..da33eec 100644 --- a/web/src/components/scene/BlackholeGalaxy.tsx +++ b/web/src/components/scene/BlackholeGalaxy.tsx @@ -1,4 +1,5 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { animate, spring, useMotionValue } from "motion/react"; import type { Orbit, Snapshot } from "../../api"; import { orbitStatus } from "../../lib/format"; import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout"; @@ -7,6 +8,7 @@ import { SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, type Vec2, } from "../../lib/galaxyLayout"; import { useGalaxyMotion } from "../../hooks/useGalaxyMotion"; +import { uiSpring } from "../../lib/motion"; import { VaultCore } from "./VaultCore"; export type CaptureArrival = { orbitId: string; snapshotId: string }; @@ -16,6 +18,7 @@ type Props = { selectedOrbitId?: string; recentSnapshots: Snapshot[]; flowing: boolean; + reducedMotion: boolean; arrival?: CaptureArrival; onSelectOrbit: (id: string) => void; onSelectSnapshot: (id: string) => void; @@ -25,22 +28,38 @@ const HALF_WIDTH = SCENE_WIDTH / 2; const HALF_HEIGHT = SCENE_HEIGHT / 2; const labelFont = "500 11px ui-monospace, monospace"; const MAX_LABELS = 12; -const METEOR_SECONDS = 1.4; const ACCRETION_SECONDS = 6.4; export function BlackholeGalaxy({ - orbits, selectedOrbitId, recentSnapshots, flowing, arrival, onSelectOrbit, onSelectSnapshot, + orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, arrival, onSelectOrbit, onSelectSnapshot, }: Props) { const frame = useRef(null); const bodyNodes = useRef(new Map()); const slotsBefore = useRef>(undefined); const elapsed = useRef(0); const core = useRef(null); - const meteor = useRef<{ id: string; time: number; source: Vec2 }>(undefined); + const meteor = useRef<{ id: string; time: number; source: Vec2; progress: ReturnType }>(undefined); const trail = useRef(null); const head = useRef(null); const effect = useRef(null); const [width, setWidth] = useState(0); + const [coasting, setCoasting] = useState(false); + const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0); + const moving = !reducedMotion && (flowing || coasting); + + useLayoutEffect(() => () => rate.stop(), [rate]); + useLayoutEffect(() => { + if (reducedMotion) { + rate.jump(0); + setCoasting(false); + return; + } + + const target = flowing ? 1 : 0; + if (rate.get() === target && !rate.isAnimating()) return; + setCoasting(!flowing); + animate(rate, target, { ...uiSpring, onComplete: () => setCoasting(false) }); + }, [flowing, rate, reducedMotion]); const slots = useMemo( () => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId), @@ -58,8 +77,8 @@ export function BlackholeGalaxy({ }, []); const draw = useCallback((delta: number) => { - if (flowing && delta > 0) { - elapsed.current += delta; + if (moving && delta > 0) { + elapsed.current += delta * Math.max(0, rate.get()); const phase = (elapsed.current % ACCRETION_SECONDS) / ACCRETION_SECONDS; core.current?.style.setProperty("--accretion-offset", String(-100 * phase)); } @@ -74,37 +93,42 @@ export function BlackholeGalaxy({ node.setAttribute("transform", `translate(${x} ${y})`); } - if (!arrival) { + if (!arrival || reducedMotion) { effect.current?.setAttribute("opacity", "0"); - return flowing; + 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 }; + 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 flowing; - current.time += delta; - const progress = Math.min(1, current.time / METEOR_SECONDS); + 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 flowing || progress < 1; - }, [arrival, flowing, slots]); + return moving || !done; + }, [arrival, moving, rate, reducedMotion, slots]); - useGalaxyMotion(flowing || !!arrival, draw); + useGalaxyMotion(moving || (!reducedMotion && !!arrival), draw); 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 = !flowing && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined; - const positions = !flowing ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : []; + const selectedPosition = !moving && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined; + const positions = !moving ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : []; const moons = selectedPosition ? moonPoses(selectedPosition, recentSnapshots.length, 2 * hitRadius + 3, positions) : []; @@ -122,7 +146,7 @@ export function BlackholeGalaxy({ }; let labels: ReturnType = []; - if (!flowing && width && labelCandidates.length) { + if (!moving && width && labelCandidates.length) { const measure = document.createElement("canvas").getContext("2d"); if (measure) measure.font = labelFont; const markers = positions.map((point) => box(point, 7)); diff --git a/web/src/components/scene/VaultScene.tsx b/web/src/components/scene/VaultScene.tsx index 4ad34d5..03172f2 100644 --- a/web/src/components/scene/VaultScene.tsx +++ b/web/src/components/scene/VaultScene.tsx @@ -63,6 +63,7 @@ export function VaultScene({ selectedOrbitId={selectedOrbitId} recentSnapshots={recentSnapshots} flowing={flowing} + reducedMotion={reducedMotion} arrival={arrival} onSelectOrbit={onSelectOrbit} onSelectSnapshot={onSelectSnapshot} diff --git a/web/src/components/ui/Button.tsx b/web/src/components/ui/Button.tsx index 0683fb3..12e2b87 100644 --- a/web/src/components/ui/Button.tsx +++ b/web/src/components/ui/Button.tsx @@ -1,25 +1,28 @@ -import type { ButtonHTMLAttributes } from "react"; +import { motion, type HTMLMotionProps } from "motion/react"; const variants = { primary: - "bg-wormhole-violet/25 text-star-100 border-wormhole-violet/40 hover:bg-wormhole-violet/35", - ghost: "bg-space-800/60 text-star-200 border-space-700 hover:bg-space-800", - danger: "bg-orbit-red/15 text-orbit-red border-orbit-red/35 hover:bg-orbit-red/25", - success: "bg-orbit-green/15 text-orbit-green border-orbit-green/35 hover:bg-orbit-green/25", - warn: "bg-orbit-amber/15 text-orbit-amber border-orbit-amber/40 hover:bg-orbit-amber/25", + "text-star-100 border-wormhole-violet/40 [--button-color:var(--color-wormhole-violet)] [--button-rest:25%] [--button-hover:35%]", + ghost: "text-star-200 border-space-700 [--button-color:var(--color-space-800)] [--button-rest:60%] [--button-hover:100%]", + danger: "text-orbit-red border-orbit-red/35 [--button-color:var(--color-orbit-red)]", + success: "text-orbit-green border-orbit-green/35 [--button-color:var(--color-orbit-green)]", + warn: "text-orbit-amber border-orbit-amber/40 [--button-color:var(--color-orbit-amber)]", }; export function Button({ variant = "ghost", className = "", ...props -}: ButtonHTMLAttributes & { +}: HTMLMotionProps<"button"> & { variant?: keyof typeof variants; }) { return ( -