diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 872c576..f86a1b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,8 +12,10 @@ jobs: check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec - name: cargo check run: cargo check --workspace --all-targets - name: cargo test @@ -23,11 +25,18 @@ jobs: run: cargo check --manifest-path app/Cargo.toml --all-targets --locked - name: cargo test (app) run: cargo test --manifest-path app/Cargo.toml --locked + - uses: taiki-e/install-action@718993db25d12d67fe704d6aa97369e03d3803c8 + with: + tool: cargo-deny + - name: cargo deny check (app) + run: cargo deny --manifest-path app/Cargo.toml check banned-names: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false - name: fixture run: scripts/banned-names-fixture.sh - name: banned names @@ -39,8 +48,12 @@ jobs: cargo-deny: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - - uses: taiki-e/install-action@cargo-deny + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec + - uses: taiki-e/install-action@718993db25d12d67fe704d6aa97369e03d3803c8 + with: + tool: cargo-deny - name: cargo deny check run: cargo deny check diff --git a/Cargo.lock b/Cargo.lock index 78be8b0..4b4751e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,6 +23,12 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "axum" version = "0.8.9" @@ -78,12 +84,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" @@ -120,12 +138,24 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "const-oid" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -144,6 +174,22 @@ dependencies = [ "libc", ] +[[package]] +name = "crypto-bigint" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -160,7 +206,19 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "ctutils" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a" +dependencies = [ + "cmov", + "subtle", ] [[package]] @@ -169,6 +227,17 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -188,6 +257,43 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der", + "digest 0.11.3", + "elliptic-curve", + "rfc6979", + "signature", + "spki", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" +dependencies = [ + "base16ct", + "crypto-bigint", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff", + "group", + "hybrid-array", + "pem-rfc7468", + "pkcs8", + "rand_core 0.10.1", + "sec1", + "subtle", + "zeroize", ] [[package]] @@ -206,6 +312,16 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -298,6 +414,27 @@ dependencies = [ "cfg-if", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff", + "rand_core 0.10.1", + "subtle", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", ] [[package]] @@ -351,7 +488,9 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] @@ -476,12 +615,43 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primefield", + "primeorder", + "sha2", +] + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "pendant" version = "0.0.1" @@ -498,8 +668,11 @@ name = "pendant-bridge" version = "0.0.1" dependencies = [ "axum", + "base64", "futures-util", + "getrandom 0.3.4", "mime_guess", + "p256", "pendant-herdr", "pendant-web", "serde", @@ -544,6 +717,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -553,6 +736,33 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.2", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -590,7 +800,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha", - "rand_core", + "rand_core 0.9.5", ] [[package]] @@ -600,7 +810,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.9.5", ] [[package]] @@ -612,6 +822,12 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "regex-automata" version = "0.4.18" @@ -629,6 +845,16 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint", + "hmac", +] + [[package]] name = "rust-embed" version = "8.12.0" @@ -692,6 +918,20 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der", + "hybrid-array", + "subtle", + "zeroize", +] + [[package]] name = "serde" version = "1.0.229" @@ -758,6 +998,16 @@ dependencies = [ "serde", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "sha1" version = "0.10.7" @@ -799,6 +1049,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "slab" version = "0.4.12" @@ -821,6 +1081,22 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -1148,6 +1424,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -1168,6 +1456,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/README.md b/README.md index 6ff6f2f..4bcfb27 100644 --- a/README.md +++ b/README.md @@ -19,17 +19,17 @@ Then open [http://127.0.0.1:8780](http://127.0.0.1:8780). | `PENDANT_BIND` | `127.0.0.1:8780` | | `PENDANT_HERDR_SOCK` | `~/.config/herdr/herdr.sock` | -The process refuses unspecified bind addresses such as `0.0.0.0` or `::`. +The process refuses `PENDANT_BIND` unless the address is loopback. `0.0.0.0`, `::`, and any other non-loopback address are refused. ## Phone access (Tailscale Serve) On the machine running herdr and Pendant, publish the loopback bridge on your tailnet: ```bash -tailscale serve --bg 8780 +tailscale serve --bg --https=8443 http://127.0.0.1:8780 ``` -Flags vary by `tailscale` version; this is a placeholder. Open the Serve HTTPS URL from a phone on the same tailnet. +Pendant HTTPS is port `8443`, proxying `http://127.0.0.1:8780`. Port `443` is not the Pendant route. Set `PENDANT_SERVE_ORIGIN` to the exact origin a browser sends on that route. Leaving it unset makes those requests `403`. ## Security diff --git a/app/src/notes/store.rs b/app/src/notes/store.rs index 6bf89a1..641dd93 100644 --- a/app/src/notes/store.rs +++ b/app/src/notes/store.rs @@ -2,7 +2,7 @@ //! //! One worker thread owns the [`Engine`]. The UI thread only hands it jobs, so //! opening the index, refreshing it, searching and capturing never run on the -//! UI thread. The index lives in a caller-chosen directory in app-private +//! UI thread. The index lives in a directory the store picks in app-private //! storage, never in the vault, and is excluded from backups. Search is //! keyword (FTS5); the embedder is `None`. Capture goes through //! [`lapis_notes::create_new`], which writes a new file and never overwrites. @@ -16,19 +16,24 @@ use std::thread::{self, JoinHandle}; use lapis_lattice::{Engine, Hit, RefreshReport}; use lapis_notes::{CreateRequest, WrittenNote}; +// Until app/src/lib.rs lands this file is the library root (see Cargo.toml), +// so the platform keystore mounts here. +#[path = "../platform/keystore.rs"] +pub mod keystore; + /// Name of the store's worker thread. pub const WORKER: &str = "pendant-notes"; -/// Where the store reads the vault and keeps its index. +/// The index directory's name inside the app's private storage. +const INDEX: &str = "notes-index"; + +/// Where the store reads the vault. There is no index directory here: the +/// store picks it in app-private storage (see [`Store::open`]), so a caller +/// cannot name one, a symlink included. #[derive(Debug, Clone)] pub struct Config { /// The vault root. The store writes nothing in it except a new capture. pub vault: PathBuf, - /// The index directory, in app-private storage. On iOS, a directory under - /// Application Support; the store marks it excluded from backups. On - /// Android, a directory under `Context.getNoBackupFilesDir()`, which the - /// OS already leaves out of Auto Backup; anything else is refused. - pub index_dir: PathBuf, /// The inbox bucket captures land in. Always passed to `create_new`, so /// the vault's `.lapis/vault.json` is never consulted. pub inbox: String, @@ -50,7 +55,8 @@ pub type OnRefresh = Box) + Se pub struct Captured { pub note: WrittenNote, /// Why the new note is not searchable yet. The file is on disk either - /// way, and the next refresh indexes it. + /// way, and the next refresh indexes it. Never carries a path, so a UI + /// may log it. pub index_error: Option, } @@ -105,16 +111,50 @@ pub struct Store { } impl Store { - /// Start the worker and open the index there. Returns once the index is - /// open, or with the refusal: an index directory that is the vault, inside - /// it, reached through `..`, or through a symlink into it is refused - /// before anything is written. + /// Start the worker and open the index in the app's private storage: + /// `Library/Application Support/Pendant/notes-index` under the app's home + /// on iOS, `no_backup/notes-index` in the app's data directory on Android. + /// Returns once the index is open, or with the refusal. Nothing the caller + /// passes names that directory: + /// + /// ```no_run + /// use pendant_app::{Config, Store}; + /// let config = Config { vault: "/vault".into(), inbox: "inbox".into() }; + /// let store = Store::open(config, Box::new(|_, _| {})); + /// ``` + /// + /// ```compile_fail,E0560 + /// use pendant_app::{Config, Store}; + /// let config = Config { + /// vault: "/vault".into(), + /// index_dir: "/tmp/link-to-anywhere".into(), + /// inbox: "inbox".into(), + /// }; + /// let store = Store::open(config, Box::new(|_, _| {})); + /// ``` + /// + /// ```compile_fail,E0061 + /// use pendant_app::{Config, Store}; + /// let config = Config { vault: "/vault".into(), inbox: "inbox".into() }; + /// let store = Store::open(config, "/tmp/link-to-anywhere", Box::new(|_, _| {})); + /// ``` pub fn open(config: Config, on_refresh: OnRefresh) -> Result { + Store::open_in(config, app_index_dir()?, on_refresh) + } + + /// The engine still refuses an index directory that is the vault, inside + /// it, reached through `..`, or through a symlink into it, before anything + /// is written. Not public: only [`app_index_dir`] and tests choose `index_dir`. + fn open_in( + config: Config, + index_dir: PathBuf, + on_refresh: OnRefresh, + ) -> Result { let (jobs, queue) = mpsc::channel(); let (opened, open_result) = mpsc::channel(); let worker = thread::Builder::new() .name(WORKER.into()) - .spawn(move || match open_engine(&config) { + .spawn(move || match open_engine(&config, &index_dir) { Ok(engine) => { let _ = opened.send(Ok(engine.db_path())); run(engine, &config, queue, on_refresh); @@ -204,12 +244,11 @@ impl Drop for Store { } } -fn open_engine(config: &Config) -> Result { - check_backup_location(&config.index_dir)?; +fn open_engine(config: &Config, index_dir: &Path) -> Result { + check_backup_location(index_dir)?; // Confinement is the engine's: it resolves the directory, refuses `..`, // the vault and anything inside it, and writes nothing when it refuses. - let engine = - Engine::open_in(&config.vault, &config.index_dir, None).map_err(StoreError::Index)?; + let engine = Engine::open_in(&config.vault, index_dir, None).map_err(StoreError::Index)?; if let Some(dir) = engine.db_path().parent() { exclude_from_backup(dir)?; } @@ -256,10 +295,28 @@ fn capture( ..Default::default() }; let note = lapis_notes::create_new(&config.vault, &req, None).map_err(StoreError::Capture)?; - let index_error = engine.reindex_path(¬e.path).err().map(|e| e.to_string()); + let index_error = engine + .reindex_path(¬e.path) + .err() + .map(|e| index_failure(&e)); Ok(Captured { note, index_error }) } +/// The engine's own messages can carry vault paths (an I/O error, a refused +/// note, a SQLite message), so only the kind of failure goes out. +fn index_failure(e: &lapis_lattice::Error) -> String { + match e { + lapis_lattice::Error::Usage(_) => "the index refused the note".into(), + lapis_lattice::Error::Io(e) => { + format!("the index could not read the note ({:?})", e.kind()) + } + lapis_lattice::Error::Sqlite(e) => match e.sqlite_error_code() { + Some(code) => format!("the index could not store the note (SQLite {code:?})"), + None => "the index could not store the note (SQLite)".into(), + }, + } +} + fn check_date(created: &str) -> Result<(), StoreError> { let b = created.as_bytes(); let digits = |r: std::ops::Range| b[r].iter().all(u8::is_ascii_digit); @@ -278,20 +335,83 @@ fn check_date(created: &str) -> Result<(), StoreError> { } } -/// Android leaves `getNoBackupFilesDir()` out of Auto Backup and device -/// transfer. The index must sit under it. +/// The index directory in the app's private storage. It comes from the +/// platform, never from a caller. +fn app_index_dir() -> Result { + #[cfg(target_os = "android")] + let dir = android_data_dir()?.join("no_backup").join(INDEX); + // iOS sets HOME to the app's sandbox container. macOS dev hosts use the + // user's own Library. + #[cfg(target_vendor = "apple")] + let dir = home()? + .join("Library/Application Support/Pendant") + .join(INDEX); + #[cfg(not(any(target_os = "android", target_vendor = "apple")))] + let dir = home()?.join(".local/share/pendant").join(INDEX); + Ok(dir) +} + +#[cfg(not(target_os = "android"))] +fn home() -> Result { + std::env::var_os("HOME") + .map(PathBuf::from) + .filter(|h| h.is_absolute()) + .ok_or_else(|| StoreError::Backup("HOME is not set to an absolute path".into())) +} + +/// This app's data directory on internal storage, laid out the way Android +/// lays out `Context.getDataDir()`: `/data/user//`. The user is +/// the process uid over 100000; the package is the process name up to `:`. +#[cfg(target_os = "android")] +fn android_data_dir() -> Result { + use std::os::unix::fs::MetadataExt; + let proc_err = |e: std::io::Error| StoreError::Backup(format!("/proc/self: {e}")); + let uid = std::fs::metadata("/proc/self").map_err(proc_err)?.uid(); + let cmdline = std::fs::read("/proc/self/cmdline").map_err(proc_err)?; + data_dir_for(uid, &cmdline) + .ok_or_else(|| StoreError::Backup("the process name is not an app package".into())) +} + +#[cfg_attr(not(any(target_os = "android", test)), allow(dead_code))] +fn data_dir_for(uid: u32, cmdline: &[u8]) -> Option { + let name = cmdline.split(|b| *b == 0).next()?; + let package = std::str::from_utf8(name).ok()?.split(':').next()?; + let segment_ok = |s: &str| { + s.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) + && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') + }; + if !package.contains('.') || !package.split('.').all(segment_ok) { + return None; + } + Some(PathBuf::from(format!( + "/data/user/{}/{package}", + uid / 100_000 + ))) +} + +/// Backup hygiene, not the platform no-backup API. This is not +/// `Context.getNoBackupFilesDir()`: nothing here calls into Android, and no +/// symlink is resolved. It checks the path's shape only: the index must sit +/// in the `no_backup` directory directly inside `data_dir`, the app's own +/// data directory, which Auto Backup and device transfer leave out. A +/// `no_backup` component anywhere else is a decoy and fails, and so does any +/// `..`. It is not a security boundary. #[cfg_attr(not(any(target_os = "android", test)), allow(dead_code))] -fn under_no_backup(index_dir: &Path) -> bool { - index_dir.components().any(|c| c.as_os_str() == "no_backup") +fn in_no_backup(index_dir: &Path, data_dir: &Path) -> bool { + use std::path::Component; + let Ok(rest) = index_dir.strip_prefix(data_dir.join("no_backup")) else { + return false; + }; + rest.components().next().is_some() + && rest.components().all(|c| matches!(c, Component::Normal(_))) } fn check_backup_location(index_dir: &Path) -> Result<(), StoreError> { #[cfg(target_os = "android")] - if !under_no_backup(index_dir) { - return Err(StoreError::Backup(format!( - "{} is not under the app's no_backup directory", - index_dir.display() - ))); + if !in_no_backup(index_dir, &android_data_dir()?) { + return Err(StoreError::Backup( + "the index is not in the app's no_backup directory".into(), + )); } let _ = index_dir; Ok(()) @@ -305,8 +425,14 @@ fn exclude_from_backup(dir: &Path) -> Result<(), StoreError> { .ok_or_else(|| StoreError::Backup(format!("{} is not UTF-8", dir.display())))?; let url = NSURL::fileURLWithPath_isDirectory(&NSString::from_str(path), true); let yes = NSNumber::new_bool(true); - unsafe { url.setResourceValue_forKey_error(Some(&yes), NSURLIsExcludedFromBackupKey) } - .map_err(|e| StoreError::Backup(e.localizedDescription().to_string())) + // SAFETY: `url` is a typed file NSURL built from a UTF-8 path above, and + // `yes` is an NSNumber, the value type NSURLIsExcludedFromBackupKey takes. + // The key is a Foundation constant read only here. objc2 turns the + // NSError out-parameter into the `Err` that is mapped below, so a failure + // is returned, not dropped. + let set = + unsafe { url.setResourceValue_forKey_error(Some(&yes), NSURLIsExcludedFromBackupKey) }; + set.map_err(|e| StoreError::Backup(e.localizedDescription().to_string())) } /// Android: the location is the exclusion, checked before the index opened. @@ -382,18 +508,20 @@ mod tests { id: ThreadId, } - fn config(vault: &Path, index_dir: &Path) -> Config { + fn config(vault: &Path) -> Config { Config { vault: vault.to_path_buf(), - index_dir: index_dir.to_path_buf(), inbox: "inbox".into(), } } - fn open(config: Config) -> (Store, Receiver) { + /// Tests pick a scratch index directory through the crate-private + /// `open_in`; the public `open` takes none. + fn open(config: Config, index_dir: &Path) -> (Store, Receiver) { let (tx, rx) = mpsc::channel(); - let store = Store::open( + let store = Store::open_in( config, + index_dir.to_path_buf(), Box::new(move |trigger, result| { let me = thread::current(); let _ = tx.send(Refreshed { @@ -449,6 +577,8 @@ mod tests { let url = NSURL::fileURLWithPath_isDirectory(&NSString::from_str(dir.to_str().unwrap()), true); let mut value = None; + // SAFETY: a typed file NSURL, a Foundation key constant, and an + // out-slot objc2 types as Option>. unsafe { url.getResourceValue_forKey_error(&mut value, NSURLIsExcludedFromBackupKey) } .unwrap(); value @@ -464,7 +594,7 @@ mod tests { let before = tree(&v); let app = dir("app"); let index = app.join("Library/Application Support/notes-index"); - let (store, done) = open(config(&v, &index)); + let (store, done) = open(config(&v), &index); assert_eq!(store.index_dir(), index.canonicalize().unwrap()); assert!(store.index_dir().join("lattice.sqlite").is_file()); @@ -500,7 +630,7 @@ mod tests { outside.join("in-vault/deeper"), ]; for index in cases { - let err = Store::open(config(&v, &index), Box::new(|_, _| {})) + let err = Store::open_in(config(&v), index.clone(), Box::new(|_, _| {})) .err() .expect("refused"); assert!( @@ -534,7 +664,7 @@ mod tests { fn refresh_runs_off_the_calling_thread() { let v = vault(); let app = dir("app"); - let (store, done) = open(config(&v, &app.join("index"))); + let (store, done) = open(config(&v), &app.join("index")); let ui = thread::current().id(); store.launched().unwrap(); @@ -557,7 +687,7 @@ mod tests { fn a_no_change_refresh_writes_nothing() { let v = vault(); let app = dir("app"); - let (store, done) = open(config(&v, &app.join("index"))); + let (store, done) = open(config(&v), &app.join("index")); store.launched().unwrap(); assert_eq!(counts(&next(&done).result.unwrap()), (2, 0, 0)); @@ -590,7 +720,7 @@ mod tests { fn a_failed_refresh_rolls_back() { let v = vault(); let app = dir("app"); - let (store, done) = open(config(&v, &app.join("index"))); + let (store, done) = open(config(&v), &app.join("index")); store.launched().unwrap(); assert_eq!(counts(&next(&done).result.unwrap()), (2, 0, 0)); @@ -659,7 +789,7 @@ mod tests { ) .unwrap(); let app = dir("app"); - let (store, done) = open(config(&v, &app.join("index"))); + let (store, done) = open(config(&v), &app.join("index")); store.launched().unwrap(); next(&done).result.unwrap(); @@ -703,7 +833,7 @@ mod tests { fn capture_refuses_a_date_that_is_not_iso() { let v = vault(); let app = dir("app"); - let (store, _done) = open(config(&v, &app.join("index"))); + let (store, _done) = open(config(&v), &app.join("index")); for bad in [ "30/10/2026", "2026-13-01", @@ -721,13 +851,99 @@ mod tests { let _ = std::fs::remove_dir_all(&app); } + /// G0d: a reindex failure whose engine message carries the vault's path + /// comes back on `index_error` with no path in it, and the note is still + /// written. #[test] - fn android_index_must_sit_under_no_backup() { - assert!(under_no_backup(Path::new( + fn a_reindex_failure_carries_no_vault_path() { + let v = vault(); + let app = dir("app"); + let (store, done) = open(config(&v), &app.join("index")); + store.launched().unwrap(); + next(&done).result.unwrap(); + + let leak = v.canonicalize().unwrap().join("inbox/Leak.md"); + let probe = rusqlite::Connection::open(store.index_dir().join("lattice.sqlite")).unwrap(); + probe + .execute_batch(&format!( + "CREATE TRIGGER leak BEFORE INSERT ON documents WHEN NEW.path LIKE 'inbox/%' \ + BEGIN SELECT RAISE(ABORT, '{}'); END;", + leak.display() + )) + .unwrap(); + + let captured = store + .capture("Leak", Some("Body.\n"), "2026-10-30") + .unwrap(); + assert!(v.join(&captured.note.path).is_file(), "the note is written"); + let message = captured.index_error.expect("the reindex failed"); + assert!(!message.contains('/'), "{message}"); + assert!(!message.contains(v.to_str().unwrap()), "{message}"); + assert!(!message.contains("Leak"), "{message}"); + drop(probe); + drop(store); + let _ = std::fs::remove_dir_all(&v); + let _ = std::fs::remove_dir_all(&app); + } + + /// G0b: only the `no_backup` directly inside the app's data directory + /// passes. A decoy `no_backup` anywhere else fails, and so does `..`. + #[test] + fn a_decoy_no_backup_component_fails_the_hygiene_check() { + let data = Path::new("/data/user/0/com.hedronite.pendant"); + let ok = |p: &str| in_no_backup(Path::new(p), data); + assert!(ok( "/data/user/0/com.hedronite.pendant/no_backup/notes-index" - ))); - assert!(!under_no_backup(Path::new( - "/data/user/0/com.hedronite.pendant/files/notes-index" - ))); + )); + for decoy in [ + "/data/user/0/com.hedronite.pendant/files/no_backup/notes-index", + "/data/user/0/com.hedronite.pendant/cache/no_backup", + "/sdcard/no_backup/notes-index", + "/storage/emulated/0/Android/data/com.hedronite.pendant/no_backup/notes-index", + "/data/user/0/com.other.app/no_backup/notes-index", + "/data/user/10/com.hedronite.pendant/no_backup/notes-index", + "/data/user/0/com.hedronite.pendant/no_backup/../files/notes-index", + "/data/user/0/com.hedronite.pendant/no_backup/./notes-index/..", + "/data/user/0/com.hedronite.pendant/no_backup", + "/data/user/0/com.hedronite.pendant/files/notes-index", + ] { + assert!(!ok(decoy), "{decoy}"); + } + } + + /// The data directory comes from the process uid and name, never from a + /// caller, and a process name that is not a package gives none. + #[test] + fn the_android_data_dir_is_derived_from_the_process() { + let d = |uid, cmd: &[u8]| data_dir_for(uid, cmd).map(|p| p.display().to_string()); + assert_eq!( + d(10_123, b"com.hedronite.pendant\0"), + Some("/data/user/0/com.hedronite.pendant".into()) + ); + assert_eq!( + d(1_010_123, b"com.hedronite.pendant:sync\0"), + Some("/data/user/10/com.hedronite.pendant".into()) + ); + for bad in [ + &b"sh\0"[..], + b"../../tmp\0", + b"com.x/../y\0", + b"com..x\0", + b"\0", + b"", + ] { + assert_eq!(d(10_123, bad), None, "{:?}", String::from_utf8_lossy(bad)); + } + } + + /// G0c: the public `open` names its own index directory in app-private + /// storage; `Config` has no field to name another (see the compile_fail + /// examples on `Store::open`). + #[cfg(not(target_os = "android"))] + #[test] + fn the_index_directory_is_the_apps_own() { + let dir = app_index_dir().unwrap(); + assert!(dir.starts_with(home().unwrap()), "{}", dir.display()); + assert!(dir.ends_with(INDEX), "{}", dir.display()); } } diff --git a/app/src/platform/keystore.rs b/app/src/platform/keystore.rs new file mode 100644 index 0000000..e7fe6c3 --- /dev/null +++ b/app/src/platform/keystore.rs @@ -0,0 +1,604 @@ +//! The phone's device key for pairing. +//! +//! The key is made on the phone and never leaves it. On iOS it is a P-256 key +//! in the Secure Enclave, stored in the Keychain under [`TAG`], usable only +//! while the device is unlocked, never synced or backed up, and each signature +//! needs a biometric match from the currently enrolled set. Nothing here +//! writes the key to a file, and nothing ships one: the repo holds no key. +//! +//! The wire format the bridge verifies is [`ALGORITHM`]: +//! - public key: the SEC1 uncompressed point, 65 bytes, `0x04 || X || Y`; +//! - signature: ECDSA over SHA-256 of the message, ASN.1 DER (X9.62). +//! +//! Android Keystore is not reachable from here. Its key generation and +//! `BiometricPrompt` are Java APIs that need the app's `Context` and a +//! foreground `Activity`, and there is no app shell yet to own them, so every +//! call on Android returns [`KeyError::Unsupported`]. + +use std::fmt; + +/// The algorithm a device signature uses, as the bridge names it. +pub const ALGORITHM: &str = "ecdsa-p256-sha256"; + +/// The Keychain application tag the device key is stored under. +pub const TAG: &str = "com.hedronite.pendant.device-key"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyError { + /// A device key already exists. It is not replaced: delete it first. + Exists, + /// No device key is stored. + NotFound, + /// The person dismissed the biometric prompt. + Cancelled, + /// The biometric did not match, or none is enrolled. + AuthFailed, + /// The platform refused, with its status code. + Os(i64), + /// This platform has no device key here. + Unsupported(&'static str), +} + +impl fmt::Display for KeyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + KeyError::Exists => write!(f, "a device key already exists"), + KeyError::NotFound => write!(f, "no device key"), + KeyError::Cancelled => write!(f, "biometric cancelled"), + KeyError::AuthFailed => write!(f, "biometric failed"), + KeyError::Os(code) => write!(f, "keystore status {code}"), + KeyError::Unsupported(why) => write!(f, "no device key on this platform: {why}"), + } + } +} + +impl std::error::Error for KeyError {} + +/// The device key, by reference. The private half stays in the platform. +pub struct DeviceKey { + public_key: Vec, + key: imp::Key, +} + +impl DeviceKey { + /// Make the device key and store it. Refuses with [`KeyError::Exists`] + /// when one is already stored, so a paired key is never swapped silently. + pub fn create() -> Result { + if imp::Key::stored(None)?.is_some() { + return Err(KeyError::Exists); + } + DeviceKey::wrap(imp::Key::generate(imp::Protection::Device)?) + } + + /// The stored device key, if there is one. Reading it needs no biometric. + pub fn load() -> Result, KeyError> { + imp::Key::stored(None)?.map(DeviceKey::wrap).transpose() + } + + /// Remove the stored device key. A key that is not there is not an error. + pub fn delete() -> Result<(), KeyError> { + imp::Key::delete() + } + + /// The public key to pair with, in the SEC1 uncompressed form. + pub fn public_key(&self) -> &[u8] { + &self.public_key + } + + /// Sign `message`. The platform shows the biometric prompt with `reason` + /// and signs only on a match, on the phone, while the app is in front. + pub fn sign(&self, message: &[u8], reason: &str) -> Result, KeyError> { + self.key.sign(message, reason) + } + + fn wrap(key: imp::Key) -> Result { + Ok(DeviceKey { + public_key: key.public_key()?, + key, + }) + } +} + +#[cfg(target_vendor = "apple")] +mod imp { + //! Security.framework through its C API. Every CoreFoundation object + //! that a `Create` or `Copy` call returns is owned by a [`Cf`], which + //! releases it once. + + use super::{KeyError, TAG}; + use std::ffi::c_void; + use std::ptr; + + type CFTypeRef = *const c_void; + type CFIndex = isize; + type OSStatus = i32; + + #[repr(C)] + struct Opaque { + _private: [u8; 0], + } + + const UTF8: u32 = 0x0800_0100; + const SINT32: CFIndex = 3; + const BIOMETRY_CURRENT_SET: usize = 1 << 3; + const PRIVATE_KEY_USAGE: usize = 1 << 30; + const ERR_ITEM_NOT_FOUND: OSStatus = -25300; + const ERR_USER_CANCELED: i64 = -128; + const ERR_AUTH_FAILED: i64 = -25293; + + #[link(name = "CoreFoundation", kind = "framework")] + extern "C" { + static kCFTypeDictionaryKeyCallBacks: Opaque; + static kCFTypeDictionaryValueCallBacks: Opaque; + static kCFBooleanTrue: CFTypeRef; + fn CFDictionaryCreateMutable( + alloc: CFTypeRef, + capacity: CFIndex, + keys: *const Opaque, + values: *const Opaque, + ) -> CFTypeRef; + fn CFDictionarySetValue(dict: CFTypeRef, key: CFTypeRef, value: CFTypeRef); + fn CFDataCreate(alloc: CFTypeRef, bytes: *const u8, len: CFIndex) -> CFTypeRef; + fn CFDataGetBytePtr(data: CFTypeRef) -> *const u8; + fn CFDataGetLength(data: CFTypeRef) -> CFIndex; + fn CFStringCreateWithBytes( + alloc: CFTypeRef, + bytes: *const u8, + len: CFIndex, + encoding: u32, + external: u8, + ) -> CFTypeRef; + fn CFNumberCreate(alloc: CFTypeRef, kind: CFIndex, value: *const c_void) -> CFTypeRef; + fn CFErrorGetCode(err: CFTypeRef) -> CFIndex; + fn CFRetain(cf: CFTypeRef) -> CFTypeRef; + fn CFRelease(cf: CFTypeRef); + } + + #[link(name = "Security", kind = "framework")] + extern "C" { + static kSecClass: CFTypeRef; + static kSecClassKey: CFTypeRef; + static kSecAttrKeyType: CFTypeRef; + static kSecAttrKeyTypeECSECPrimeRandom: CFTypeRef; + static kSecAttrKeySizeInBits: CFTypeRef; + static kSecAttrKeyClass: CFTypeRef; + static kSecAttrKeyClassPrivate: CFTypeRef; + static kSecAttrTokenID: CFTypeRef; + static kSecAttrTokenIDSecureEnclave: CFTypeRef; + static kSecAttrIsPermanent: CFTypeRef; + static kSecAttrApplicationTag: CFTypeRef; + static kSecAttrAccessControl: CFTypeRef; + static kSecAttrAccessibleWhenUnlockedThisDeviceOnly: CFTypeRef; + static kSecPrivateKeyAttrs: CFTypeRef; + static kSecReturnRef: CFTypeRef; + static kSecUseOperationPrompt: CFTypeRef; + static kSecUseDataProtectionKeychain: CFTypeRef; + static kSecKeyAlgorithmECDSASignatureMessageX962SHA256: CFTypeRef; + fn SecAccessControlCreateWithFlags( + alloc: CFTypeRef, + protection: CFTypeRef, + flags: usize, + error: *mut CFTypeRef, + ) -> CFTypeRef; + fn SecKeyCreateRandomKey(params: CFTypeRef, error: *mut CFTypeRef) -> CFTypeRef; + fn SecKeyCopyPublicKey(key: CFTypeRef) -> CFTypeRef; + fn SecKeyCopyExternalRepresentation(key: CFTypeRef, error: *mut CFTypeRef) -> CFTypeRef; + fn SecKeyCreateSignature( + key: CFTypeRef, + algorithm: CFTypeRef, + data: CFTypeRef, + error: *mut CFTypeRef, + ) -> CFTypeRef; + fn SecItemCopyMatching(query: CFTypeRef, result: *mut CFTypeRef) -> OSStatus; + fn SecItemDelete(query: CFTypeRef) -> OSStatus; + } + + #[cfg(test)] + #[link(name = "CoreFoundation", kind = "framework")] + extern "C" { + static kCFBooleanFalse: CFTypeRef; + } + + #[cfg(test)] + #[link(name = "Security", kind = "framework")] + extern "C" { + static kSecAttrKeyClassPublic: CFTypeRef; + fn SecKeyCreateWithData( + data: CFTypeRef, + attrs: CFTypeRef, + error: *mut CFTypeRef, + ) -> CFTypeRef; + fn SecKeyVerifySignature( + key: CFTypeRef, + algorithm: CFTypeRef, + data: CFTypeRef, + signature: CFTypeRef, + error: *mut CFTypeRef, + ) -> u8; + } + + /// An owned CoreFoundation object. + pub(super) struct Cf(CFTypeRef); + + impl Cf { + /// Owns `p`, the result of a `Create` or `Copy` call; null is `None`. + fn owned(p: CFTypeRef) -> Option { + (!p.is_null()).then_some(Cf(p)) + } + + fn as_ptr(&self) -> CFTypeRef { + self.0 + } + + fn bytes(&self) -> Vec { + // SAFETY: `self` owns a CFData (every caller builds it from a + // `Copy`/`Create` call that returns CFData), so the pointer and + // length describe one live buffer for as long as `self` lives. + unsafe { + let len = CFDataGetLength(self.0); + std::slice::from_raw_parts(CFDataGetBytePtr(self.0), len as usize).to_vec() + } + } + } + + impl Drop for Cf { + fn drop(&mut self) { + // SAFETY: `Cf` is only built from a non-null owned reference, and + // it is released exactly once, here. + unsafe { CFRelease(self.0) } + } + } + + // SAFETY: CoreFoundation and Security objects are reference counted with + // atomic counts and are immutable once made, so a reference can move to + // another thread. + unsafe impl Send for Cf {} + + fn data(bytes: &[u8]) -> Cf { + // SAFETY: `bytes` is a live slice; CFDataCreate copies it. + Cf::owned(unsafe { CFDataCreate(ptr::null(), bytes.as_ptr(), bytes.len() as CFIndex) }) + .expect("CFDataCreate") + } + + fn string(s: &str) -> Cf { + // SAFETY: `s` is live UTF-8 and is copied, not borrowed (external = 0). + Cf::owned(unsafe { + CFStringCreateWithBytes(ptr::null(), s.as_ptr(), s.len() as CFIndex, UTF8, 0) + }) + .expect("CFStringCreateWithBytes") + } + + fn number(n: i32) -> Cf { + // SAFETY: `n` is a live i32, read once as kCFNumberSInt32Type. + Cf::owned(unsafe { CFNumberCreate(ptr::null(), SINT32, (&n as *const i32).cast()) }) + .expect("CFNumberCreate") + } + + /// A CFDictionary that retains its keys and values. + fn dict(pairs: &[(CFTypeRef, CFTypeRef)]) -> Cf { + // SAFETY: the callbacks are CoreFoundation's own CFType callbacks, so + // the dictionary retains what it is given. Every key and value is a + // live CF object: a Security constant or one owned by the caller. + unsafe { + let d = Cf::owned(CFDictionaryCreateMutable( + ptr::null(), + pairs.len() as CFIndex, + &raw const kCFTypeDictionaryKeyCallBacks, + &raw const kCFTypeDictionaryValueCallBacks, + )) + .expect("CFDictionaryCreateMutable"); + for (k, v) in pairs { + CFDictionarySetValue(d.as_ptr(), *k, *v); + } + d + } + } + + /// The code of an owned CFError, which is then released. + fn error(err: CFTypeRef) -> KeyError { + let Some(err) = Cf::owned(err) else { + return KeyError::Os(0); + }; + // SAFETY: `err` is a live CFError that `err` owns. + match unsafe { CFErrorGetCode(err.as_ptr()) } as i64 { + ERR_USER_CANCELED => KeyError::Cancelled, + ERR_AUTH_FAILED => KeyError::AuthFailed, + code => KeyError::Os(code), + } + } + + pub(super) enum Protection { + /// Secure Enclave, stored in the Keychain, biometric to sign. + Device, + /// A software key held in memory only, so the FFI can run on a host + /// without a Secure Enclave entitlement. Never shipped. + #[cfg(test)] + Memory, + } + + impl Protection { + fn held(&self) -> bool { + match self { + Protection::Device => false, + #[cfg(test)] + Protection::Memory => true, + } + } + } + + pub(super) struct Key { + /// Held for a memory key. A stored key is fetched again on each + /// signature, so the prompt carries that signature's reason. + held: Option, + } + + impl Key { + pub(super) fn generate(protection: Protection) -> Result { + let tag = data(TAG.as_bytes()); + let bits = number(256); + let mut err: CFTypeRef = ptr::null(); + // SAFETY: the Security constants are read-only CFStrings that live + // for the process. Every dictionary entry is a live CF object; + // `err` is a valid out slot and, when set, is owned by `error`. + unsafe { + let params = match protection { + Protection::Device => { + let access = Cf::owned(SecAccessControlCreateWithFlags( + ptr::null(), + kSecAttrAccessibleWhenUnlockedThisDeviceOnly, + PRIVATE_KEY_USAGE | BIOMETRY_CURRENT_SET, + &mut err, + )) + .ok_or_else(|| error(err))?; + let private = dict(&[ + (kSecAttrIsPermanent, kCFBooleanTrue), + (kSecAttrApplicationTag, tag.as_ptr()), + (kSecAttrAccessControl, access.as_ptr()), + ]); + dict(&[ + (kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom), + (kSecAttrKeySizeInBits, bits.as_ptr()), + (kSecAttrTokenID, kSecAttrTokenIDSecureEnclave), + (kSecUseDataProtectionKeychain, kCFBooleanTrue), + (kSecPrivateKeyAttrs, private.as_ptr()), + ]) + } + #[cfg(test)] + Protection::Memory => { + let private = dict(&[(kSecAttrIsPermanent, kCFBooleanFalse)]); + dict(&[ + (kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom), + (kSecAttrKeySizeInBits, bits.as_ptr()), + (kSecPrivateKeyAttrs, private.as_ptr()), + ]) + } + }; + let key = Cf::owned(SecKeyCreateRandomKey(params.as_ptr(), &mut err)) + .ok_or_else(|| error(err))?; + Ok(Key { + held: protection.held().then_some(key), + }) + } + } + + /// The stored private key. With a `reason`, a signature made with the + /// returned reference prompts with it. + fn copy_stored(reason: Option<&str>) -> Result, KeyError> { + let tag = data(TAG.as_bytes()); + let reason = reason.map(string); + // SAFETY: as in `generate`; `found` is a valid out slot that + // SecItemCopyMatching fills with an owned SecKey on success. + unsafe { + let mut pairs = vec![ + (kSecClass, kSecClassKey), + (kSecAttrApplicationTag, tag.as_ptr()), + (kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom), + (kSecAttrKeyClass, kSecAttrKeyClassPrivate), + (kSecUseDataProtectionKeychain, kCFBooleanTrue), + (kSecReturnRef, kCFBooleanTrue), + ]; + if let Some(r) = &reason { + pairs.push((kSecUseOperationPrompt, r.as_ptr())); + } + let query = dict(&pairs); + let mut found: CFTypeRef = ptr::null(); + match SecItemCopyMatching(query.as_ptr(), &mut found) { + 0 => Ok(Cf::owned(found)), + ERR_ITEM_NOT_FOUND => Ok(None), + status => Err(KeyError::Os(status.into())), + } + } + } + + pub(super) fn stored(reason: Option<&str>) -> Result, KeyError> { + Ok(Key::copy_stored(reason)?.map(|_| Key { held: None })) + } + + pub(super) fn delete() -> Result<(), KeyError> { + let tag = data(TAG.as_bytes()); + // SAFETY: as in `generate`. + let status = unsafe { + let query = dict(&[ + (kSecClass, kSecClassKey), + (kSecAttrApplicationTag, tag.as_ptr()), + (kSecUseDataProtectionKeychain, kCFBooleanTrue), + ]); + SecItemDelete(query.as_ptr()) + }; + match status { + 0 | ERR_ITEM_NOT_FOUND => Ok(()), + status => Err(KeyError::Os(status.into())), + } + } + + fn private(&self, reason: Option<&str>) -> Result { + match &self.held { + // SAFETY: retaining a live SecKey before a second owner + // takes it; the copy below is a fresh owned reference. + Some(key) => Ok(Cf(unsafe { CFRetain(key.as_ptr()) })), + None => Key::copy_stored(reason)?.ok_or(KeyError::NotFound), + } + } + + pub(super) fn public_key(&self) -> Result, KeyError> { + let private = self.private(None)?; + let mut err: CFTypeRef = ptr::null(); + // SAFETY: `private` is a live SecKey. Copying its public half + // needs no biometric; both results are owned here. + unsafe { + let public = + Cf::owned(SecKeyCopyPublicKey(private.as_ptr())).ok_or(KeyError::Os(0))?; + let bytes = Cf::owned(SecKeyCopyExternalRepresentation(public.as_ptr(), &mut err)) + .ok_or_else(|| error(err))?; + Ok(bytes.bytes()) + } + } + + pub(super) fn sign(&self, message: &[u8], reason: &str) -> Result, KeyError> { + let private = self.private(Some(reason))?; + let message = data(message); + let mut err: CFTypeRef = ptr::null(); + // SAFETY: a live SecKey, a Security algorithm constant and a live + // CFData. For a stored key the platform shows the biometric prompt + // and returns null with an owned CFError when it is not met. + unsafe { + let signature = Cf::owned(SecKeyCreateSignature( + private.as_ptr(), + kSecKeyAlgorithmECDSASignatureMessageX962SHA256, + message.as_ptr(), + &mut err, + )) + .ok_or_else(|| error(err))?; + Ok(signature.bytes()) + } + } + } + + /// Whether `signature` over `message` verifies under the SEC1 + /// `public_key`, checked by Security itself. + #[cfg(test)] + pub(super) fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> bool { + let (key_data, message, signature) = (data(public_key), data(message), data(signature)); + let bits = number(256); + let mut err: CFTypeRef = ptr::null(); + // SAFETY: as in `generate`; every argument is a live CF object. + unsafe { + let attrs = dict(&[ + (kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom), + (kSecAttrKeyClass, kSecAttrKeyClassPublic), + (kSecAttrKeySizeInBits, bits.as_ptr()), + ]); + let Some(public) = Cf::owned(SecKeyCreateWithData( + key_data.as_ptr(), + attrs.as_ptr(), + &mut err, + )) else { + let _ = error(err); + return false; + }; + let ok = SecKeyVerifySignature( + public.as_ptr(), + kSecKeyAlgorithmECDSASignatureMessageX962SHA256, + message.as_ptr(), + signature.as_ptr(), + &mut err, + ) != 0; + if !ok { + let _ = error(err); + } + ok + } + } +} + +#[cfg(not(target_vendor = "apple"))] +mod imp { + use super::KeyError; + + #[cfg(target_os = "android")] + const WHY: &str = "Android Keystore and BiometricPrompt need the app shell"; + #[cfg(not(target_os = "android"))] + const WHY: &str = "not a phone"; + + pub(super) enum Protection { + Device, + } + + pub(super) struct Key; + + impl Key { + pub(super) fn generate(_: Protection) -> Result { + Err(KeyError::Unsupported(WHY)) + } + + pub(super) fn stored(_: Option<&str>) -> Result, KeyError> { + Err(KeyError::Unsupported(WHY)) + } + + pub(super) fn delete() -> Result<(), KeyError> { + Err(KeyError::Unsupported(WHY)) + } + + pub(super) fn public_key(&self) -> Result, KeyError> { + Err(KeyError::Unsupported(WHY)) + } + + pub(super) fn sign(&self, _: &[u8], _: &str) -> Result, KeyError> { + Err(KeyError::Unsupported(WHY)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The wire format the bridge verifies: a 65-byte SEC1 point and a DER + /// ECDSA signature that Security accepts for the message and refuses for + /// any other. A memory key, since a host test has no Secure Enclave. + #[cfg(target_vendor = "apple")] + #[test] + fn a_signature_verifies_under_the_exported_public_key() { + let key = DeviceKey::wrap(imp::Key::generate(imp::Protection::Memory).unwrap()).unwrap(); + let public = key.public_key(); + assert_eq!(public.len(), 65); + assert_eq!(public[0], 0x04, "uncompressed point"); + + let message = b"POST /v1/agents/a1/prompt\n2026-10-30T12:00:00Z\nnonce"; + let signature = key.sign(message, "Approve the prompt").unwrap(); + assert_eq!(signature[0], 0x30, "DER SEQUENCE"); + assert!(imp::verify(public, message, &signature)); + assert!(!imp::verify( + public, + b"POST /v1/agents/a2/prompt", + &signature + )); + + let other = DeviceKey::wrap(imp::Key::generate(imp::Protection::Memory).unwrap()).unwrap(); + assert_ne!(other.public_key(), public, "each key is new"); + assert!(!imp::verify(other.public_key(), message, &signature)); + } + + /// The device protection reaches the Secure Enclave on a phone. Run on + /// the device with `--ignored`; a host without the Keychain entitlement + /// gets a status code back, not a key and not a crash. + #[test] + #[ignore = "needs a phone with a Secure Enclave and an enrolled biometric"] + fn a_device_key_is_made_in_the_keychain() { + DeviceKey::delete().unwrap(); + let key = DeviceKey::create().unwrap(); + assert_eq!(key.public_key().len(), 65); + assert!(matches!(DeviceKey::create(), Err(KeyError::Exists))); + let loaded = DeviceKey::load().unwrap().expect("stored"); + assert_eq!(loaded.public_key(), key.public_key()); + DeviceKey::delete().unwrap(); + assert!(DeviceKey::load().unwrap().is_none()); + } + + #[cfg(not(target_vendor = "apple"))] + #[test] + fn other_platforms_say_unsupported() { + assert!(matches!(DeviceKey::create(), Err(KeyError::Unsupported(_)))); + assert!(matches!(DeviceKey::load(), Err(KeyError::Unsupported(_)))); + } +} diff --git a/crates/pendant-bridge/Cargo.toml b/crates/pendant-bridge/Cargo.toml index 9243f9a..c437100 100644 --- a/crates/pendant-bridge/Cargo.toml +++ b/crates/pendant-bridge/Cargo.toml @@ -10,6 +10,9 @@ description = "Loopback HTTP bridge from Pendant to herdr" [dependencies] axum = { workspace = true, features = ["ws"] } +base64 = "0.22" +getrandom = "0.3" +p256 = { version = "0.14", features = ["ecdsa"] } futures-util.workspace = true mime_guess.workspace = true pendant-herdr = { path = "../pendant-herdr" } diff --git a/crates/pendant-bridge/src/bind.rs b/crates/pendant-bridge/src/bind.rs index 28710d8..0d603f5 100644 --- a/crates/pendant-bridge/src/bind.rs +++ b/crates/pendant-bridge/src/bind.rs @@ -10,9 +10,11 @@ pub enum BindError { Invalid { input: String, message: String }, #[error("refusing unspecified bind address {addr} (no 0.0.0.0 / ::)")] Unspecified { addr: SocketAddr }, + #[error("refusing non-loopback bind address {addr}")] + NonLoopback { addr: SocketAddr }, } -/// Parse `host:port` and reject unspecified IPs (`0.0.0.0`, `::`). +/// Parse `host:port` and accept only a loopback address. pub fn parse_bind(input: &str) -> Result { let trimmed = input.trim(); let addr: SocketAddr = trimmed @@ -24,6 +26,9 @@ pub fn parse_bind(input: &str) -> Result { if addr.ip().is_unspecified() { return Err(BindError::Unspecified { addr }); } + if !addr.ip().is_loopback() { + return Err(BindError::NonLoopback { addr }); + } Ok(addr) } @@ -58,6 +63,14 @@ mod tests { assert!(matches!(err, BindError::Unspecified { .. })); } + #[test] + fn reject_non_loopback() { + let v4 = parse_bind("192.0.2.10:8780").unwrap_err(); + assert!(matches!(v4, BindError::NonLoopback { .. })); + let v6 = parse_bind("[2001:db8::1]:8780").unwrap_err(); + assert!(matches!(v6, BindError::NonLoopback { .. })); + } + #[test] fn reject_garbage() { assert!(matches!( diff --git a/crates/pendant-bridge/src/config.rs b/crates/pendant-bridge/src/config.rs index f71306c..02d183b 100644 --- a/crates/pendant-bridge/src/config.rs +++ b/crates/pendant-bridge/src/config.rs @@ -33,6 +33,7 @@ impl From for BridgeError { match value { BindError::Invalid { input, message } => BridgeError::InvalidBind { input, message }, BindError::Unspecified { addr } => BridgeError::UnspecifiedBind(addr), + BindError::NonLoopback { addr } => BridgeError::NonLoopbackBind(addr), } } } @@ -55,4 +56,10 @@ mod tests { assert_eq!(cfg.bind.port(), 9000); assert_eq!(cfg.herdr_sock, PathBuf::from("/tmp/custom.sock")); } + + #[test] + fn non_loopback_pendant_bind_is_refused() { + let err = Config::from_raw("192.0.2.10:8780", "/tmp/custom.sock").unwrap_err(); + assert!(matches!(err, BridgeError::NonLoopbackBind(_))); + } } diff --git a/crates/pendant-bridge/src/error.rs b/crates/pendant-bridge/src/error.rs index 33cf719..342bd45 100644 --- a/crates/pendant-bridge/src/error.rs +++ b/crates/pendant-bridge/src/error.rs @@ -8,6 +8,8 @@ pub enum BridgeError { InvalidBind { input: String, message: String }, #[error("refusing unspecified bind address {0} (no 0.0.0.0 / ::)")] UnspecifiedBind(SocketAddr), + #[error("refusing non-loopback bind address {0}")] + NonLoopbackBind(SocketAddr), #[error("listen failed: {0}")] Listen(#[from] std::io::Error), } diff --git a/crates/pendant-bridge/src/lib.rs b/crates/pendant-bridge/src/lib.rs index f197b41..425199a 100644 --- a/crates/pendant-bridge/src/lib.rs +++ b/crates/pendant-bridge/src/lib.rs @@ -1,8 +1,9 @@ -//! Loopback HTTP bridge. Never bind `0.0.0.0` / `::`. +//! Loopback HTTP bridge. Never bind a non-loopback address. mod bind; mod config; mod error; +mod pairing; mod routes; mod session; mod static_files; @@ -26,6 +27,7 @@ pub struct AppState { pub bind: SocketAddr, /// Optional Serve origin, such as `https://name.example`. Not a hard-coded name. pub serve_origin: Option, + pub pairing: pairing::Pairing, } pub fn app(state: AppState) -> Router { @@ -33,15 +35,11 @@ pub fn app(state: AppState) -> Router { } pub async fn serve(config: Config) -> Result<(), BridgeError> { - if config.bind.ip().is_unspecified() { - return Err(BridgeError::UnspecifiedBind(config.bind)); - } + assert_loopback_only(config.bind)?; let listener = TcpListener::bind(config.bind).await?; let local = listener.local_addr()?; - if local.ip().is_unspecified() { - return Err(BridgeError::UnspecifiedBind(local)); - } + assert_loopback_only(local)?; let state = AppState { herdr: HerdrClient::new(&config.herdr_sock), @@ -50,6 +48,7 @@ pub async fn serve(config: Config) -> Result<(), BridgeError> { serve_origin: std::env::var("PENDANT_SERVE_ORIGIN") .ok() .filter(|value| !value.is_empty()), + pairing: pairing::Pairing::new(), }; tracing::info!( @@ -72,6 +71,8 @@ async fn shutdown_signal() { pub fn assert_loopback_only(addr: SocketAddr) -> Result<(), BridgeError> { if addr.ip().is_unspecified() { Err(BridgeError::UnspecifiedBind(addr)) + } else if !addr.ip().is_loopback() { + Err(BridgeError::NonLoopbackBind(addr)) } else { Ok(()) } diff --git a/crates/pendant-bridge/src/pairing.rs b/crates/pendant-bridge/src/pairing.rs new file mode 100644 index 0000000..ce45ba7 --- /dev/null +++ b/crates/pendant-bridge/src/pairing.rs @@ -0,0 +1,468 @@ +//! Device pairing for the phone. The phone creates the P-256 key. This crate +//! verifies it. No key or token is minted here, and there is no relay. +//! +//! The wire format is `ecdsa-p256-sha256`: a SEC1 uncompressed public key +//! (`0x04 || X || Y`) and an ASN.1 DER signature over SHA-256 of the message. +//! +//! A real phone is not paired by these tests. Lost-phone revoke is covered +//! first, while `real_pairings` stays zero. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use base64::engine::general_purpose::STANDARD; +use base64::Engine; +use p256::ecdsa::signature::Verifier; +use p256::ecdsa::{Signature, VerifyingKey}; + +/// Session takeover is not implemented. +pub const TAKEOVER: bool = false; + +/// Name of the phone signature algorithm. +pub const DEVICE_SIGNATURE: &str = "ecdsa-p256-sha256"; + +const GRANT_TTL: Duration = Duration::from_secs(30); +const MAX_CHALLENGES: usize = 64; + +#[derive(Clone)] +pub struct Pairing { + inner: std::sync::Arc>, +} + +struct Inner { + ttl: Duration, + challenge_ttl: Duration, + challenge_rate: usize, + challenge_window: Duration, + nonces: Vec, + challenges: Vec, + recent: Vec, + devices: HashMap, + grants: HashMap, +} + +struct Ticket { + token: String, + issued: Instant, +} + +struct Device { + public: VerifyingKey, + revoked: bool, +} + +struct Grant { + opened: Instant, + released: bool, +} + +impl Pairing { + pub fn new() -> Self { + Self::with_ttl(GRANT_TTL) + } + + pub fn with_ttl(ttl: Duration) -> Self { + Self { + inner: std::sync::Arc::new(Mutex::new(Inner { + ttl, + challenge_ttl: GRANT_TTL, + challenge_rate: 32, + challenge_window: Duration::from_secs(1), + nonces: Vec::new(), + challenges: Vec::new(), + recent: Vec::new(), + devices: HashMap::new(), + grants: HashMap::new(), + })), + } + } + + pub fn with_challenge_limit(rate: usize, challenge_ttl: Duration) -> Self { + let pairing = Self::new(); + let mut inner = pairing.inner.lock().expect("pairing"); + inner.challenge_rate = rate.max(1); + inner.challenge_ttl = challenge_ttl; + drop(inner); + pairing + } + + /// No real phone has been paired. Tests assert this stays zero. + pub fn real_pairings(&self) -> u64 { + 0 + } + + pub fn is_paired(&self, device_id: &str) -> bool { + let inner = self.inner.lock().expect("pairing"); + inner + .devices + .get(device_id) + .is_some_and(|device| !device.revoked) + } + + pub fn issue_nonce(&self) -> String { + let nonce = random_token(); + let mut inner = self.inner.lock().expect("pairing"); + push_capped(&mut inner.nonces, nonce.clone()); + nonce + } + + pub fn issue_challenge(&self) -> Result { + let mut inner = self.inner.lock().expect("pairing"); + let now = Instant::now(); + let ttl = inner.challenge_ttl; + let window = inner.challenge_window; + let rate = inner.challenge_rate; + inner + .challenges + .retain(|ticket| now.saturating_duration_since(ticket.issued) <= ttl); + inner + .recent + .retain(|issued| now.saturating_duration_since(*issued) <= window); + if inner.recent.len() >= rate { + return Err(AuthError::RateLimited); + } + let challenge = random_token(); + inner.recent.push(now); + if inner.challenges.len() >= MAX_CHALLENGES { + inner.challenges.remove(0); + } + inner.challenges.push(Ticket { + token: challenge.clone(), + issued: now, + }); + Ok(challenge) + } + + pub fn qr_payload(nonce: &str) -> String { + format!("pendant-pair:v1:{nonce}") + } + + /// The check and the insert share one lock. A revoked id is not overwritten. + pub fn pair( + &self, + device_id: &str, + public_b64: &str, + nonce: &str, + sig_b64: &str, + takeover: bool, + ) -> Result<(), AuthError> { + let public = decode_key(public_b64).map_err(|_| AuthError::BadSignature)?; + let msg = pair_message(device_id, public_b64, nonce); + if !verify(&public, &msg, sig_b64) { + return Err(AuthError::BadSignature); + } + let mut inner = self.inner.lock().expect("pairing"); + if inner + .devices + .get(device_id) + .is_some_and(|device| device.revoked) + { + return Err(AuthError::Revoked); + } + let other = inner + .devices + .iter() + .any(|(id, device)| id != device_id && !device.revoked); + if other && (takeover || !TAKEOVER) { + return Err(AuthError::TakeoverOff); + } + if !take_token(&mut inner.nonces, nonce) { + return Err(AuthError::BadSignature); + } + inner.devices.insert( + device_id.to_string(), + Device { + public, + revoked: false, + }, + ); + Ok(()) + } + + /// Auth is a signature from an already paired device over a fresh challenge. + /// Unknown ids are not stored. + pub fn revoke( + &self, + target_id: &str, + signer_id: &str, + sig_b64: &str, + challenge: &str, + ) -> Result<(), AuthError> { + let msg = revoke_message(target_id, challenge); + let mut inner = self.inner.lock().expect("pairing"); + if !take_ticket(&mut inner, challenge) { + return Err(AuthError::BadSignature); + } + let Some(signer) = inner.devices.get(signer_id) else { + return Err(AuthError::BadSignature); + }; + if signer.revoked { + return Err(AuthError::Revoked); + } + let public = signer.public.clone(); + if !verify(&public, &msg, sig_b64) { + return Err(AuthError::BadSignature); + } + let Some(target) = inner.devices.get_mut(target_id) else { + return Ok(()); + }; + target.revoked = true; + if let Some(grant) = inner.grants.get_mut(target_id) { + grant.released = true; + } + Ok(()) + } + + /// Host operator revoke. No phone signature. The route is local-only. + pub fn host_revoke(&self, target_id: &str) { + let mut inner = self.inner.lock().expect("pairing"); + let Some(target) = inner.devices.get_mut(target_id) else { + return; + }; + target.revoked = true; + if let Some(grant) = inner.grants.get_mut(target_id) { + grant.released = true; + } + } + + pub fn open_grant( + &self, + device_id: &str, + sig_b64: &str, + challenge: &str, + ) -> Result<(), AuthError> { + let msg = grant_message(device_id, challenge); + self.verify_fresh(device_id, &msg, sig_b64, challenge)?; + let mut inner = self.inner.lock().expect("pairing"); + inner.grants.insert( + device_id.to_string(), + Grant { + opened: Instant::now(), + released: false, + }, + ); + Ok(()) + } + + pub fn authorize( + &self, + device_id: &str, + message: &[u8], + sig_b64: &str, + challenge: &str, + ) -> Result<(), AuthError> { + self.verify_fresh(device_id, message, sig_b64, challenge)?; + let mut inner = self.inner.lock().expect("pairing"); + let ttl = inner.ttl; + let Some(grant) = inner.grants.get_mut(device_id) else { + return Err(AuthError::GrantRequired); + }; + if grant.released { + return Err(AuthError::GrantReleased); + } + if grant.opened.elapsed() > ttl { + grant.released = true; + return Err(AuthError::GrantReleased); + } + Ok(()) + } + + pub fn attach(&self, device_id: &str, sig_b64: Option<&str>, challenge: Option<&str>) -> bool { + let (Some(sig_b64), Some(challenge)) = (sig_b64, challenge) else { + return false; + }; + let msg = attach_message(device_id, challenge); + self.authorize(device_id, &msg, sig_b64, challenge).is_ok() + } + + pub fn release(&self, device_id: &str) { + let mut inner = self.inner.lock().expect("pairing"); + if let Some(grant) = inner.grants.get_mut(device_id) { + grant.released = true; + } + } + + fn verify_fresh( + &self, + device_id: &str, + message: &[u8], + sig_b64: &str, + challenge: &str, + ) -> Result<(), AuthError> { + let mut inner = self.inner.lock().expect("pairing"); + if !take_ticket(&mut inner, challenge) { + return Err(AuthError::BadSignature); + } + let Some(device) = inner.devices.get(device_id) else { + return Err(AuthError::BadSignature); + }; + if device.revoked { + return Err(AuthError::Revoked); + } + let public = device.public.clone(); + drop(inner); + if verify(&public, message, sig_b64) { + Ok(()) + } else { + Err(AuthError::BadSignature) + } + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum AuthError { + BadSignature, + GrantRequired, + GrantReleased, + Revoked, + TakeoverOff, + Unpaired, + RateLimited, +} + +pub fn unpaired_log(host: &str) -> String { + format!("unpaired device refused via=serve host={host}") +} + +pub fn sign_message( + device_id: &str, + method: &str, + path: &str, + challenge: &str, + canonical: &str, +) -> Vec { + format!("pendant-sign:v1\n{device_id}\n{method}\n{path}\n{challenge}\n{canonical}").into_bytes() +} + +pub fn pair_message(device_id: &str, public_b64: &str, nonce: &str) -> Vec { + format!("pendant-pair:v1\n{device_id}\n{public_b64}\n{nonce}").into_bytes() +} + +pub fn grant_message(device_id: &str, challenge: &str) -> Vec { + format!("pendant-grant:v1\n{device_id}\n{challenge}").into_bytes() +} + +pub fn attach_message(device_id: &str, challenge: &str) -> Vec { + format!("pendant-attach:v1\n{device_id}\n{challenge}").into_bytes() +} + +pub fn revoke_message(target_id: &str, challenge: &str) -> Vec { + format!("pendant-revoke:v1\n{target_id}\n{challenge}").into_bytes() +} + +fn random_token() -> String { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).expect("random"); + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn push_capped(items: &mut Vec, item: String) { + if items.len() >= MAX_CHALLENGES { + items.remove(0); + } + items.push(item); +} + +fn ct_eq(left: &str, right: &str) -> bool { + let left = left.as_bytes(); + let right = right.as_bytes(); + if left.len() != right.len() { + return false; + } + let mut diff = 0u8; + for (a, b) in left.iter().zip(right.iter()) { + diff |= a ^ b; + } + diff == 0 +} + +fn take_token(items: &mut Vec, token: &str) -> bool { + let mut found = None; + for (index, item) in items.iter().enumerate() { + if ct_eq(item, token) { + found = Some(index); + } + } + if let Some(index) = found { + items.remove(index); + true + } else { + false + } +} + +fn take_ticket(inner: &mut Inner, token: &str) -> bool { + let now = Instant::now(); + let ttl = inner.challenge_ttl; + let mut found = None; + for (index, ticket) in inner.challenges.iter().enumerate() { + let fresh = now.saturating_duration_since(ticket.issued) <= ttl; + if fresh && ct_eq(&ticket.token, token) { + found = Some(index); + } + } + inner + .challenges + .retain(|ticket| now.saturating_duration_since(ticket.issued) <= ttl || found.is_some()); + if let Some(index) = found { + if index < inner.challenges.len() && ct_eq(&inner.challenges[index].token, token) { + inner.challenges.remove(index); + return true; + } + } + false +} + +fn verify(key: &VerifyingKey, message: &[u8], sig_b64: &str) -> bool { + let Ok(bytes) = STANDARD.decode(sig_b64.trim()) else { + return false; + }; + let Ok(sig) = Signature::from_der(&bytes) else { + return false; + }; + key.verify(message, &sig).is_ok() +} + +fn decode_key(public_b64: &str) -> Result { + let bytes = STANDARD.decode(public_b64.trim()).map_err(|_| ())?; + VerifyingKey::from_sec1_bytes(&bytes).map_err(|_| ()) +} + +#[cfg(test)] +pub struct TestDevice { + pub id: String, + signing: p256::ecdsa::SigningKey, +} + +#[cfg(test)] +fn random_signing_key() -> p256::ecdsa::SigningKey { + loop { + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).expect("random"); + if let Ok(key) = p256::ecdsa::SigningKey::from_slice(&bytes) { + return key; + } + } +} + +#[cfg(test)] +impl TestDevice { + pub fn generate(id: &str) -> Self { + Self { + id: id.to_string(), + signing: random_signing_key(), + } + } + + pub fn public_b64(&self) -> String { + let point = self.signing.verifying_key().to_sec1_point(false); + STANDARD.encode(point.as_bytes()) + } + + pub fn sign_b64(&self, message: &[u8]) -> String { + use p256::ecdsa::signature::Signer; + let sig: Signature = self.signing.sign(message); + STANDARD.encode(sig.to_der().as_bytes()) + } +} diff --git a/crates/pendant-bridge/src/routes.rs b/crates/pendant-bridge/src/routes.rs index 6146276..062b794 100644 --- a/crates/pendant-bridge/src/routes.rs +++ b/crates/pendant-bridge/src/routes.rs @@ -15,7 +15,8 @@ use pendant_herdr::{CreateWorktree, HerdrError}; use serde::Deserialize; use serde_json::json; -use crate::session::{approve_key, scratch_socket}; +use crate::pairing::{self, unpaired_log, AuthError}; +use crate::session::{approve_key, canonical_scratch}; use crate::static_files; use crate::AppState; @@ -27,6 +28,13 @@ pub fn router(state: AppState) -> Router { .route("/v1/agents/{id}", get(agent_detail)) .route("/v1/agents/{id}/prompt", post(agent_prompt)) .route("/v1/agents/{id}/keys", post(agent_keys)) + .route("/v1/agents/{id}/approve", post(agent_approve)) + .route("/v1/pair/qr", get(pair_qr)) + .route("/v1/challenge", get(issue_challenge)) + .route("/v1/pair", post(pair_device)) + .route("/v1/grant", post(open_grant)) + .route("/v1/devices/{id}/revoke", post(revoke_device)) + .route("/v1/host/revoke", post(host_revoke)) .route("/v1/events", get(events_inbox)) .route("/v1/events/stream", get(events_sse)) .route("/v1/ws", get(ws_upgrade)) @@ -234,12 +242,18 @@ fn refuse_write() -> Response { async fn create_worktree( State(state): State, + headers: HeaderMap, Json(body): Json, ) -> Response { - if !scratch_socket(state.herdr.socket_path()) { + let Some(herdr) = scratch_client(&state) else { return refuse_write(); + }; + let canonical = serde_json::to_string(&body).unwrap_or_default(); + let message = signed_message(&headers, "POST", "/v1/worktrees", &canonical); + if let Err(response) = gate_write(&state, &headers, &message) { + return response; } - match state.herdr.worktree_create(&body).await { + match herdr.worktree_create(&body).await { Ok(value) => Json(value).into_response(), Err(err) => herdr_error(err), } @@ -274,11 +288,12 @@ async fn agent_detail(State(state): State, Path(id): Path) -> async fn agent_prompt( State(state): State, Path(id): Path, + headers: HeaderMap, Json(body): Json, ) -> Response { - if !scratch_socket(state.herdr.socket_path()) { + let Some(herdr) = scratch_client(&state) else { return refuse_write(); - } + }; if body.prompt.trim().is_empty() { return ( StatusCode::BAD_REQUEST, @@ -286,7 +301,12 @@ async fn agent_prompt( ) .into_response(); } - match state.herdr.agent_prompt(&id, &body.prompt).await { + let path = format!("/v1/agents/{id}/prompt"); + let message = signed_message(&headers, "POST", &path, body.prompt.trim()); + if let Err(response) = gate_write(&state, &headers, &message) { + return response; + } + match herdr.agent_prompt(&id, &body.prompt).await { Ok(value) => Json(value).into_response(), Err(err) => herdr_error(err), } @@ -295,11 +315,12 @@ async fn agent_prompt( async fn agent_keys( State(state): State, Path(id): Path, + headers: HeaderMap, Json(body): Json, ) -> Response { - if !scratch_socket(state.herdr.socket_path()) { + let Some(herdr) = scratch_client(&state) else { return refuse_write(); - } + }; if body.keys.is_empty() { return ( StatusCode::BAD_REQUEST, @@ -307,6 +328,12 @@ async fn agent_keys( ) .into_response(); } + let path = format!("/v1/agents/{id}/keys"); + let canonical = body.keys.join("\n"); + let message = signed_message(&headers, "POST", &path, &canonical); + if let Err(response) = gate_write(&state, &headers, &message) { + return response; + } if body.keys.iter().any(|key| !approve_key(key)) { return ( StatusCode::FORBIDDEN, @@ -319,12 +346,257 @@ async fn agent_keys( ) .into_response(); } - match state.herdr.agent_send_keys(&id, &body.keys).await { + match herdr.agent_send_keys(&id, &body.keys).await { Ok(value) => Json(value).into_response(), Err(err) => herdr_error(err), } } +#[derive(Deserialize)] +struct ApproveBody { + decision: String, +} + +async fn agent_approve( + State(state): State, + Path(id): Path, + headers: HeaderMap, + Json(body): Json, +) -> Response { + let Some(herdr) = scratch_client(&state) else { + return refuse_write(); + }; + let path = format!("/v1/agents/{id}/approve"); + let message = signed_message(&headers, "POST", &path, body.decision.trim()); + if let Err(response) = gate_write(&state, &headers, &message) { + return response; + } + let decision = body.decision.trim().to_string(); + if !approve_key(&decision) { + return ( + StatusCode::FORBIDDEN, + Json(json!({ + "error": { "code": "key_refused", "message": "key is outside the approve bar" } + })), + ) + .into_response(); + } + match herdr.agent_send_keys(&id, &[decision]).await { + Ok(value) => Json(value).into_response(), + Err(err) => herdr_error(err), + } +} + +async fn pair_qr(State(state): State, headers: HeaderMap) -> Response { + if let Err(response) = local_only(&state, &headers) { + return response; + } + let nonce = state.pairing.issue_nonce(); + Json(json!({ + "v": 1, + "nonce": nonce, + "payload": pairing::Pairing::qr_payload(&nonce), + "algorithm": pairing::DEVICE_SIGNATURE, + })) + .into_response() +} + +async fn issue_challenge(State(state): State) -> Response { + match state.pairing.issue_challenge() { + Ok(challenge) => Json(json!({ "challenge": challenge })).into_response(), + Err(AuthError::RateLimited) => ( + StatusCode::TOO_MANY_REQUESTS, + Json(json!({"error": {"code": "rate_limited", "message": "too many challenges"}})), + ) + .into_response(), + Err(err) => auth_error(err), + } +} + +#[derive(Deserialize)] +struct PairBody { + device_id: String, + public_key: String, + nonce: String, + sig: String, + #[serde(default)] + takeover: bool, +} + +async fn pair_device(State(state): State, Json(body): Json) -> Response { + match state.pairing.pair( + &body.device_id, + &body.public_key, + &body.nonce, + &body.sig, + body.takeover, + ) { + Ok(()) => Json(json!({"ok": true, "takeover": pairing::TAKEOVER})).into_response(), + Err(err) => auth_error(err), + } +} + +#[derive(Deserialize)] +struct GrantBody { + device_id: String, + sig: String, + challenge: String, +} + +async fn open_grant(State(state): State, Json(body): Json) -> Response { + match state + .pairing + .open_grant(&body.device_id, &body.sig, &body.challenge) + { + Ok(()) => Json(json!({"ok": true})).into_response(), + Err(err) => auth_error(err), + } +} + +async fn revoke_device( + State(state): State, + Path(id): Path, + headers: HeaderMap, +) -> Response { + if let Err(response) = local_only(&state, &headers) { + return response; + } + let Some(signer) = header_value(&headers, "x-pendant-device") else { + return auth_error(AuthError::BadSignature); + }; + let Some(sig) = header_value(&headers, "x-pendant-signature") else { + return auth_error(AuthError::BadSignature); + }; + let Some(challenge) = header_value(&headers, "x-pendant-challenge") else { + return auth_error(AuthError::BadSignature); + }; + match state.pairing.revoke(&id, signer, sig, challenge) { + Ok(()) => Json(json!({ + "ok": true, + "revoked": id, + "real_pairings": state.pairing.real_pairings(), + })) + .into_response(), + Err(err) => auth_error(err), + } +} + +#[derive(Deserialize)] +struct HostRevokeBody { + device_id: String, +} + +async fn host_revoke( + State(state): State, + headers: HeaderMap, + Json(body): Json, +) -> Response { + if let Err(response) = local_only(&state, &headers) { + return response; + } + state.pairing.host_revoke(&body.device_id); + Json(json!({ + "ok": true, + "revoked": body.device_id, + "real_pairings": state.pairing.real_pairings(), + })) + .into_response() +} + +fn signed_message(headers: &HeaderMap, method: &str, path: &str, canonical: &str) -> Vec { + let device = header_value(headers, "x-pendant-device").unwrap_or(""); + let challenge = header_value(headers, "x-pendant-challenge").unwrap_or(""); + pairing::sign_message(device, method, path, challenge, canonical) +} + +fn gate_write(state: &AppState, headers: &HeaderMap, message: &[u8]) -> Result<(), Response> { + let host = headers.get(HOST).and_then(|value| value.to_str().ok()); + let device = header_value(headers, "x-pendant-device"); + let sig = header_value(headers, "x-pendant-signature"); + let challenge = header_value(headers, "x-pendant-challenge").unwrap_or(""); + if via_serve(host, state.serve_origin.as_deref()) + && !device.is_some_and(|id| state.pairing.is_paired(id)) + { + let line = unpaired_log(host.unwrap_or("serve")); + tracing::warn!("{line}"); + return Err(forbid("unpaired", &line)); + } + let (Some(device), Some(sig)) = (device, sig) else { + return Err(forbid( + "bad_signature", + "device signature is missing or wrong", + )); + }; + match state.pairing.authorize(device, message, sig, challenge) { + Ok(()) => Ok(()), + Err(err) => Err(auth_error(err)), + } +} + +fn via_serve(host: Option<&str>, serve_origin: Option<&str>) -> bool { + let Some(host) = host.map(str::trim).filter(|value| !value.is_empty()) else { + return false; + }; + if host.starts_with("127.0.0.1") || host.starts_with("localhost") || host.starts_with("[::1]") { + return false; + } + let Some(origin) = serve_origin.and_then(parse_origin) else { + return false; + }; + let with_port = format!("{}:{}", origin.host, origin.port); + host.eq_ignore_ascii_case(&with_port) + || (host.eq_ignore_ascii_case(&origin.host) && (origin.port == 80 || origin.port == 443)) +} + +fn proxy_forwarded(headers: &HeaderMap) -> bool { + headers.get("forwarded").is_some() || headers.get("x-forwarded-for").is_some() +} + +fn local_only(state: &AppState, headers: &HeaderMap) -> Result<(), Response> { + let host = headers.get(HOST).and_then(|value| value.to_str().ok()); + // A loopback Host is not enough: the proxy dials 127.0.0.1 and can forward that Host. + // Forwarding headers are client-visible proof the request was proxied. The TCP peer is not. + if proxy_forwarded(headers) || via_serve(host, state.serve_origin.as_deref()) { + Err(forbid("local_only", "this route is only on the host")) + } else { + Ok(()) + } +} + +fn scratch_client(state: &AppState) -> Option { + let path = canonical_scratch(state.herdr.socket_path())?; + Some(state.herdr.with_socket_path(path)) +} + +fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(str::trim) + .filter(|value| !value.is_empty()) +} + +fn forbid(code: &str, message: &str) -> Response { + ( + StatusCode::FORBIDDEN, + Json(json!({"error": {"code": code, "message": message}})), + ) + .into_response() +} + +fn auth_error(err: AuthError) -> Response { + let (code, message) = match err { + AuthError::BadSignature => ("bad_signature", "device signature is missing or wrong"), + AuthError::GrantRequired => ("grant_required", "biometric grant is not open"), + AuthError::GrantReleased => ("grant_released", "biometric grant released"), + AuthError::Revoked => ("revoked", "device is revoked"), + AuthError::TakeoverOff => ("takeover_off", "takeover is off"), + AuthError::Unpaired => ("unpaired", "unpaired device"), + AuthError::RateLimited => ("rate_limited", "too many challenges"), + }; + forbid(code, message) +} + async fn events_inbox(State(state): State) -> Response { match state.herdr.inbox().await { Ok(items) => Json(json!({ "items": items })).into_response(), @@ -393,8 +665,11 @@ mod tests { use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::net::{TcpListener, TcpStream, UnixListener}; + use crate::pairing; use crate::AppState; + static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + async fn http(port: u16, method: &str, path: &str, body: &str) -> (u16, String) { http_host(port, method, path, body, &format!("127.0.0.1:{port}")).await } @@ -405,10 +680,28 @@ mod tests { path: &str, body: &str, host: &str, + ) -> (u16, String) { + http_headers(port, method, path, body, host, &[]).await + } + + async fn http_headers( + port: u16, + method: &str, + path: &str, + body: &str, + host: &str, + extra: &[(&str, &str)], ) -> (u16, String) { let mut stream = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + let mut headers = String::new(); + for (name, value) in extra { + headers.push_str(name); + headers.push_str(": "); + headers.push_str(value); + headers.push_str("\r\n"); + } let req = format!( - "{method} {path} HTTP/1.1\r\nHost: {host}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + "{method} {path} HTTP/1.1\r\nHost: {host}\r\n{headers}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len() ); stream.write_all(req.as_bytes()).await.unwrap(); @@ -419,6 +712,87 @@ mod tests { (status, text) } + fn response_json(raw: &str) -> serde_json::Value { + let body = raw.split("\r\n\r\n").nth(1).unwrap_or(""); + serde_json::from_str(body).unwrap_or(serde_json::json!({})) + } + + async fn pair_only(port: u16) -> pairing::TestDevice { + let (status, raw) = http(port, "GET", "/v1/pair/qr", "").await; + assert_eq!(status, 200); + let qr = response_json(&raw); + let nonce = qr["nonce"].as_str().unwrap(); + assert!(qr["payload"] + .as_str() + .unwrap() + .starts_with("pendant-pair:v1:")); + assert!(!raw.contains("private_key")); + let phone = pairing::TestDevice::generate("phone-1"); + let public = phone.public_b64(); + let sig = phone.sign_b64(&pairing::pair_message(&phone.id, &public, nonce)); + let pair_body = serde_json::json!({ + "device_id": phone.id, + "public_key": public, + "nonce": nonce, + "sig": sig, + }) + .to_string(); + let (status, _) = http(port, "POST", "/v1/pair", &pair_body).await; + assert_eq!(status, 200); + phone + } + + async fn fresh_challenge(port: u16) -> String { + let (status, raw) = http(port, "GET", "/v1/challenge", "").await; + assert_eq!(status, 200); + response_json(&raw)["challenge"] + .as_str() + .unwrap() + .to_string() + } + + async fn enroll(port: u16) -> pairing::TestDevice { + let phone = pair_only(port).await; + let challenge = fresh_challenge(port).await; + let grant_sig = phone.sign_b64(&pairing::grant_message(&phone.id, &challenge)); + let grant_body = serde_json::json!({ + "device_id": phone.id, + "sig": grant_sig, + "challenge": challenge, + }) + .to_string(); + let (status, _) = http(port, "POST", "/v1/grant", &grant_body).await; + assert_eq!(status, 200); + phone + } + + async fn signed( + port: u16, + phone: &pairing::TestDevice, + method: &str, + path: &str, + canonical: &str, + body: &str, + ) -> (u16, String) { + let challenge = fresh_challenge(port).await; + let sig = phone.sign_b64(&pairing::sign_message( + &phone.id, method, path, &challenge, canonical, + )); + http_headers( + port, + method, + path, + body, + &format!("127.0.0.1:{port}"), + &[ + ("x-pendant-device", phone.id.as_str()), + ("x-pendant-signature", sig.as_str()), + ("x-pendant-challenge", challenge.as_str()), + ], + ) + .await + } + fn spawn_mock(path: &std::path::Path, seen: Arc>>) { let path = path.to_path_buf(); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); @@ -466,13 +840,35 @@ mod tests { async fn serve_on(path: &std::path::Path) -> u16 { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); - let port = addr.port(); let state = AppState { herdr: HerdrClient::new(path), queue_cap: 8, bind: addr, serve_origin: None, + pairing: pairing::Pairing::new(), + }; + serve_state(listener, state).await + } + + async fn serve_with( + path: &std::path::Path, + pairing: pairing::Pairing, + serve_origin: Option, + ) -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let state = AppState { + herdr: HerdrClient::new(path), + queue_cap: 8, + bind: addr, + serve_origin, + pairing, }; + serve_state(listener, state).await + } + + async fn serve_state(listener: TcpListener, state: AppState) -> u16 { + let port = state.bind.port(); tokio::spawn(async move { let _ = axum::serve(listener, crate::app(state)).await; }); @@ -509,19 +905,39 @@ mod tests { let seen = Arc::new(Mutex::new(Vec::new())); spawn_mock(&scratch, seen.clone()); let port = serve_on(&scratch).await; - let (status, _) = http( + let phone = enroll(port).await; + let (status, _) = signed( port, + &phone, "POST", "/v1/agents/w1:p1/prompt", + "hello", r#"{"prompt":"hello"}"#, ) .await; assert_eq!(status, 200); assert!(seen.lock().unwrap().iter().any(|m| m == "agent.prompt")); - let (status, _) = http(port, "POST", "/v1/worktrees", "{}").await; + let tree: pendant_herdr::CreateWorktree = serde_json::from_str("{}").unwrap(); + let tree_body = serde_json::to_string(&tree).unwrap(); + let (status, _) = signed( + port, + &phone, + "POST", + "/v1/worktrees", + &tree_body, + &tree_body, + ) + .await; assert_eq!(status, 200); - let (status, body) = - http(port, "POST", "/v1/agents/w1:p1/keys", r#"{"keys":["rm"]}"#).await; + let (status, body) = signed( + port, + &phone, + "POST", + "/v1/agents/w1:p1/keys", + "rm", + r#"{"keys":["rm"]}"#, + ) + .await; assert_eq!(status, 403); assert!(body.contains("key_refused")); assert!(!seen.lock().unwrap().iter().any(|m| m == "agent.send_keys")); @@ -555,6 +971,7 @@ mod tests { queue_cap: 4, bind: addr, serve_origin: Some("https://serve.invalid".into()), + pairing: pairing::Pairing::new(), }; tokio::spawn(async move { let _ = axum::serve(listener, crate::app(state)).await; @@ -574,4 +991,469 @@ mod tests { .insert("Origin", "http://foreign.invalid".parse().unwrap()); assert!(tokio_tungstenite::connect_async(foreign).await.is_err()); } + + #[tokio::test] + async fn websocket_accepts_configured_serve_origin() { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let _guard = ENV_LOCK.lock().unwrap(); + std::env::set_var("PENDANT_SERVE_ORIGIN", "https://serve.invalid"); + let origin = std::env::var("PENDANT_SERVE_ORIGIN").unwrap(); + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let sock = dir.path().join(".config/herdr/herdr.sock"); + spawn_mock(&sock, Arc::new(Mutex::new(Vec::new()))); + let port = serve_with(&sock, pairing::Pairing::new(), Some(origin.clone())).await; + let mut req = format!("ws://127.0.0.1:{port}/v1/ws") + .into_client_request() + .unwrap(); + req.headers_mut().insert("Origin", origin.parse().unwrap()); + tokio_tungstenite::connect_async(req).await.unwrap(); + std::env::remove_var("PENDANT_SERVE_ORIGIN"); + } + + #[tokio::test] + async fn websocket_refuses_a_missing_origin() { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let sock = dir.path().join(".config/herdr/herdr.sock"); + spawn_mock(&sock, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&sock).await; + let req = format!("ws://127.0.0.1:{port}/v1/ws") + .into_client_request() + .unwrap(); + let err = tokio_tungstenite::connect_async(req).await.unwrap_err(); + match err { + tokio_tungstenite::tungstenite::Error::Http(response) => { + assert_eq!(response.status(), 403); + } + other => panic!("expected an http refusal, got {other}"), + } + } + + #[tokio::test] + async fn unpaired_device_is_refused_through_serve() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_with( + &scratch, + pairing::Pairing::new(), + Some("https://serve.invalid".into()), + ) + .await; + let (status, body) = http_headers( + port, + "POST", + "/v1/agents/w1:p1/prompt", + r#"{"prompt":"hello"}"#, + "serve.invalid", + &[("x-pendant-device", "phone-x")], + ) + .await; + assert_eq!(status, 403); + assert!(body.contains("unpaired device refused via=serve host=serve.invalid")); + let line = body + .lines() + .find(|line| line.contains("unpaired device refused")) + .unwrap(); + assert!(!line.contains("127.0.0.1")); + } + + #[tokio::test] + async fn write_routes_refuse_a_missing_or_wrong_signature() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&scratch).await; + let tree: pendant_herdr::CreateWorktree = serde_json::from_str("{}").unwrap(); + let tree_body = serde_json::to_string(&tree).unwrap(); + let calls = [ + ("/v1/agents/w1:p1/prompt", "hello", r#"{"prompt":"hello"}"#), + ("/v1/agents/w1:p1/keys", "y", r#"{"keys":["y"]}"#), + ("/v1/agents/w1:p1/approve", "y", r#"{"decision":"y"}"#), + ("/v1/worktrees", tree_body.as_str(), tree_body.as_str()), + ]; + for (path, canonical, body) in calls { + let (status, raw) = http(port, "POST", path, body).await; + assert_eq!(status, 403, "{path}"); + assert!(raw.contains("bad_signature"), "{path}"); + let phone = pairing::TestDevice::generate("phone-1"); + let sig = phone.sign_b64(b"wrong"); + let (status, raw) = http_headers( + port, + "POST", + path, + body, + &format!("127.0.0.1:{port}"), + &[ + ("x-pendant-device", "phone-1"), + ("x-pendant-signature", sig.as_str()), + ], + ) + .await; + assert_eq!(status, 403, "{path} {canonical}"); + assert!(raw.contains("bad_signature"), "{path}"); + } + } + + #[tokio::test] + async fn write_routes_refuse_a_signature_without_a_grant() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&scratch).await; + let phone = pair_only(port).await; + let tree: pendant_herdr::CreateWorktree = serde_json::from_str("{}").unwrap(); + let tree_body = serde_json::to_string(&tree).unwrap(); + let calls = [ + ("/v1/agents/w1:p1/prompt", "hello", r#"{"prompt":"hello"}"#), + ("/v1/agents/w1:p1/keys", "y", r#"{"keys":["y"]}"#), + ("/v1/agents/w1:p1/approve", "y", r#"{"decision":"y"}"#), + ("/v1/worktrees", tree_body.as_str(), tree_body.as_str()), + ]; + for (path, canonical, body) in calls { + let (status, raw) = signed(port, &phone, "POST", path, canonical, body).await; + assert_eq!(status, 403, "{path}"); + assert!(raw.contains("grant_required"), "{path}"); + } + } + + #[tokio::test] + async fn grant_releases_on_timeout() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_with( + &scratch, + pairing::Pairing::with_ttl(std::time::Duration::from_millis(30)), + None, + ) + .await; + let phone = enroll(port).await; + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + let (status, raw) = signed( + port, + &phone, + "POST", + "/v1/agents/w1:p1/prompt", + "hello", + r#"{"prompt":"hello"}"#, + ) + .await; + assert_eq!(status, 403); + assert!(raw.contains("grant_released")); + } + + #[tokio::test] + async fn grant_releases_when_the_connection_drops() { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&scratch).await; + let phone = enroll(port).await; + let mut req = format!("ws://127.0.0.1:{port}/v1/ws") + .into_client_request() + .unwrap(); + req.headers_mut().insert( + "Origin", + format!("http://127.0.0.1:{port}").parse().unwrap(), + ); + let (mut ws, _) = tokio_tungstenite::connect_async(req).await.unwrap(); + let challenge = fresh_challenge(port).await; + let sig = phone.sign_b64(&pairing::attach_message(&phone.id, &challenge)); + let attach = serde_json::json!({ + "v": 1, + "pane": "w1:p1", + "type": "attach", + "device_id": phone.id, + "sig": sig, + "challenge": challenge, + }) + .to_string(); + use futures_util::SinkExt; + ws.send(tokio_tungstenite::tungstenite::Message::Text(attach.into())) + .await + .unwrap(); + drop(ws); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + let (status, raw) = signed( + port, + &phone, + "POST", + "/v1/agents/w1:p1/prompt", + "hello", + r#"{"prompt":"hello"}"#, + ) + .await; + assert_eq!(status, 403); + assert!(raw.contains("grant_released")); + } + + #[tokio::test] + async fn takeover_stays_off() { + assert!(!pairing::TAKEOVER); + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&scratch).await; + let _first = pair_only(port).await; + let (status, raw) = http(port, "GET", "/v1/pair/qr", "").await; + assert_eq!(status, 200); + let nonce = response_json(&raw)["nonce"].as_str().unwrap().to_string(); + let other = pairing::TestDevice::generate("phone-2"); + let public = other.public_b64(); + let sig = other.sign_b64(&pairing::pair_message(&other.id, &public, &nonce)); + let body = serde_json::json!({ + "device_id": other.id, + "public_key": public, + "nonce": nonce, + "sig": sig, + "takeover": true, + }) + .to_string(); + let (status, raw) = http(port, "POST", "/v1/pair", &body).await; + assert_eq!(status, 403); + assert!(raw.contains("takeover_off")); + } + + #[tokio::test] + async fn lost_phone_revoke_is_refused_before_any_real_pairing() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&scratch).await; + let phone = pair_only(port).await; + let challenge = fresh_challenge(port).await; + let sig = phone.sign_b64(&pairing::revoke_message(&phone.id, &challenge)); + let (status, raw) = http_headers( + port, + "POST", + &format!("/v1/devices/{}/revoke", phone.id), + "", + &format!("127.0.0.1:{port}"), + &[ + ("x-pendant-device", phone.id.as_str()), + ("x-pendant-signature", sig.as_str()), + ("x-pendant-challenge", challenge.as_str()), + ], + ) + .await; + assert_eq!(status, 200); + let body = response_json(&raw); + assert_eq!(body["real_pairings"], 0); + let grant_challenge = fresh_challenge(port).await; + let grant_sig = phone.sign_b64(&pairing::grant_message(&phone.id, &grant_challenge)); + let grant_body = serde_json::json!({ + "device_id": phone.id, + "sig": grant_sig, + "challenge": grant_challenge, + }) + .to_string(); + let (status, raw) = http(port, "POST", "/v1/grant", &grant_body).await; + assert_eq!(status, 403); + assert!(raw.contains("revoked")); + } + + #[tokio::test] + async fn qr_and_revoke_are_local_only_and_a_revoked_id_stays_tombstoned() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_with( + &scratch, + pairing::Pairing::new(), + Some("https://serve.invalid".into()), + ) + .await; + let (status, raw) = http_host(port, "GET", "/v1/pair/qr", "", "serve.invalid").await; + assert_eq!(status, 403); + assert!(raw.contains("local_only")); + let phone = pair_only(port).await; + let challenge = fresh_challenge(port).await; + let sig = phone.sign_b64(&pairing::revoke_message(&phone.id, &challenge)); + let (status, raw) = http_headers( + port, + "POST", + &format!("/v1/devices/{}/revoke", phone.id), + "", + "serve.invalid", + &[ + ("x-pendant-device", phone.id.as_str()), + ("x-pendant-signature", sig.as_str()), + ("x-pendant-challenge", challenge.as_str()), + ], + ) + .await; + assert_eq!(status, 403); + assert!(raw.contains("local_only")); + let (status, raw) = http(port, "GET", "/v1/pair/qr", "").await; + assert_eq!(status, 200); + let nonce = response_json(&raw)["nonce"].as_str().unwrap().to_string(); + let only_nonce = phone.sign_b64(format!("pendant-pair:v1:{nonce}").as_bytes()); + let public = phone.public_b64(); + let weak = serde_json::json!({ + "device_id": "phone-2", + "public_key": public, + "nonce": nonce, + "sig": only_nonce, + }) + .to_string(); + let (status, raw) = http(port, "POST", "/v1/pair", &weak).await; + assert_eq!(status, 403); + assert!(raw.contains("bad_signature")); + let local_challenge = fresh_challenge(port).await; + let local_sig = phone.sign_b64(&pairing::revoke_message(&phone.id, &local_challenge)); + let (status, _) = http_headers( + port, + "POST", + &format!("/v1/devices/{}/revoke", phone.id), + "", + &format!("127.0.0.1:{port}"), + &[ + ("x-pendant-device", phone.id.as_str()), + ("x-pendant-signature", local_sig.as_str()), + ("x-pendant-challenge", local_challenge.as_str()), + ], + ) + .await; + assert_eq!(status, 200); + let (status, raw) = http(port, "GET", "/v1/pair/qr", "").await; + assert_eq!(status, 200); + let nonce = response_json(&raw)["nonce"].as_str().unwrap().to_string(); + let again = phone.sign_b64(&pairing::pair_message(&phone.id, &public, &nonce)); + let body = serde_json::json!({ + "device_id": phone.id, + "public_key": public, + "nonce": nonce, + "sig": again, + }) + .to_string(); + let (status, raw) = http(port, "POST", "/v1/pair", &body).await; + assert_eq!(status, 403); + assert!(raw.contains("revoked")); + } + + #[tokio::test] + async fn loopback_host_with_forwarding_headers_gets_no_pairing_nonce() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_on(&scratch).await; + let host = format!("127.0.0.1:{port}"); + for extra in [ + ("x-forwarded-for", "203.0.113.5"), + ("forwarded", "for=203.0.113.5"), + ] { + let (status, raw) = http_headers(port, "GET", "/v1/pair/qr", "", &host, &[extra]).await; + assert_eq!(status, 403); + assert!(raw.contains("local_only")); + assert!(!raw.contains("pendant-pair:v1:")); + let phone = pairing::TestDevice::generate("phone-x"); + let public = phone.public_b64(); + let nonce = "0123456789abcdef0123456789abcdef"; + let sig = phone.sign_b64(&pairing::pair_message(&phone.id, &public, nonce)); + let body = serde_json::json!({ + "device_id": phone.id, + "public_key": public, + "nonce": nonce, + "sig": sig, + }) + .to_string(); + let (status, raw) = http(port, "POST", "/v1/pair", &body).await; + assert_eq!(status, 403); + assert!(raw.contains("bad_signature")); + } + let (status, raw) = http(port, "GET", "/v1/pair/qr", "").await; + assert_eq!(status, 200); + assert!(raw.contains("pendant-pair:v1:")); + } + + #[tokio::test] + async fn host_revoke_is_refused_to_a_serve_caller() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let port = serve_with( + &scratch, + pairing::Pairing::new(), + Some("https://serve.invalid".into()), + ) + .await; + let phone = pair_only(port).await; + let body = serde_json::json!({"device_id": phone.id}).to_string(); + let (status, raw) = http_headers( + port, + "POST", + "/v1/host/revoke", + &body, + "serve.invalid", + &[("x-forwarded-for", "203.0.113.5")], + ) + .await; + assert_eq!(status, 403); + assert!(raw.contains("local_only")); + let (status, raw) = http_headers( + port, + "POST", + "/v1/host/revoke", + &body, + &format!("127.0.0.1:{port}"), + &[("forwarded", "for=203.0.113.5")], + ) + .await; + assert_eq!(status, 403); + assert!(raw.contains("local_only")); + let (status, raw) = http(port, "POST", "/v1/host/revoke", &body).await; + assert_eq!(status, 200); + assert_eq!(response_json(&raw)["real_pairings"], 0); + let grant_challenge = fresh_challenge(port).await; + let grant_sig = phone.sign_b64(&pairing::grant_message(&phone.id, &grant_challenge)); + let grant_body = serde_json::json!({ + "device_id": phone.id, + "sig": grant_sig, + "challenge": grant_challenge, + }) + .to_string(); + let (status, raw) = http(port, "POST", "/v1/grant", &grant_body).await; + assert_eq!(status, 403); + assert!(raw.contains("revoked")); + } + + #[tokio::test] + async fn challenge_is_rate_limited_and_expires() { + let dir = tempfile::tempdir_in("/tmp").unwrap(); + let scratch = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); + let limited = serve_with( + &scratch, + pairing::Pairing::with_challenge_limit(2, std::time::Duration::from_secs(30)), + None, + ) + .await; + assert_eq!(http(limited, "GET", "/v1/challenge", "").await.0, 200); + assert_eq!(http(limited, "GET", "/v1/challenge", "").await.0, 200); + let (status, raw) = http(limited, "GET", "/v1/challenge", "").await; + assert_eq!(status, 429); + assert!(raw.contains("rate_limited")); + + let expiring = serve_with( + &scratch, + pairing::Pairing::with_challenge_limit(8, std::time::Duration::from_millis(30)), + None, + ) + .await; + let phone = pair_only(expiring).await; + let stale = fresh_challenge(expiring).await; + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + let grant_sig = phone.sign_b64(&pairing::grant_message(&phone.id, &stale)); + let grant_body = serde_json::json!({ + "device_id": phone.id, + "sig": grant_sig, + "challenge": stale, + }) + .to_string(); + let (status, raw) = http(expiring, "POST", "/v1/grant", &grant_body).await; + assert_eq!(status, 403); + assert!(raw.contains("bad_signature")); + } } diff --git a/crates/pendant-bridge/src/session.rs b/crates/pendant-bridge/src/session.rs index 172108f..a286ba7 100644 --- a/crates/pendant-bridge/src/session.rs +++ b/crates/pendant-bridge/src/session.rs @@ -99,9 +99,13 @@ struct Up { kind: String, cols: Option, rows: Option, - /// Accepted and ignored. Reserved verbs stay refused. + /// Accepted and ignored on reserved verbs. `attach` verifies it. #[serde(default)] sig: Option, + #[serde(default)] + device_id: Option, + #[serde(default)] + challenge: Option, } pub async fn run_socket(socket: WebSocket, state: AppState) { @@ -116,6 +120,7 @@ pub async fn run_socket(socket: WebSocket, state: AppState) { }); let mut watches: HashMap = HashMap::new(); + let mut attached: Option = None; let fulls: std::sync::Arc>> = std::sync::Arc::new(std::sync::Mutex::new(HashMap::new())); @@ -130,7 +135,6 @@ pub async fn run_socket(socket: WebSocket, state: AppState) { if up.v != ENVELOPE_VERSION { continue; } - let _ignored_sig = up.sig; match up.kind.as_str() { "watch" => { let already = watches.contains_key(&up.pane); @@ -175,6 +179,16 @@ pub async fn run_socket(socket: WebSocket, state: AppState) { let _ = tx.send(frame_json(&up.pane, &full)).await; } } + "attach" => { + if let Some(id) = up.device_id.clone() { + if state + .pairing + .attach(&id, up.sig.as_deref(), up.challenge.as_deref()) + { + attached = Some(id); + } + } + } "input" | "resize" | "scroll" => { let _ = tx .send( @@ -194,6 +208,9 @@ pub async fn run_socket(socket: WebSocket, state: AppState) { for handle in watches.into_values() { handle.abort(); } + if let Some(device) = attached { + state.pairing.release(&device); + } writer.abort(); } @@ -309,16 +326,22 @@ pub fn admit_watch(open: usize, already: bool, pane: &str) -> Result<(), ()> { /// Writes are allowed only for `…/.config/herdr/sessions//herdr.sock`. /// `.` and `..` components are refused, including after symlink resolution. -pub fn scratch_socket(path: &std::path::Path) -> bool { +pub fn canonical_scratch(path: &std::path::Path) -> Option { if has_dot_components(path) { - return false; + return None; } - match std::fs::canonicalize(path) { - Ok(canonical) => socket_shape(&canonical), - Err(_) => socket_shape(path), + let canonical = std::fs::canonicalize(path).ok()?; + if socket_shape(&canonical) { + Some(canonical) + } else { + None } } +pub fn scratch_socket(path: &std::path::Path) -> bool { + canonical_scratch(path).is_some() +} + fn has_dot_components(path: &std::path::Path) -> bool { use std::path::Component; // `Path::components` drops a `.` in the middle of an absolute path, so the @@ -408,10 +431,30 @@ mod tests { #[test] fn scratch_socket_is_a_named_session_path() { - let ok = std::path::Path::new("/tmp/work/.config/herdr/sessions/g1/herdr.sock"); - let live = std::path::Path::new("/tmp/work/.config/herdr/herdr.sock"); - assert!(scratch_socket(ok)); - assert!(!scratch_socket(live)); + let dir = tempfile::tempdir().unwrap(); + let ok = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + std::fs::create_dir_all(ok.parent().unwrap()).unwrap(); + std::fs::write(&ok, b"").unwrap(); + assert!(scratch_socket(&ok)); + let live = dir.path().join(".config/herdr/herdr.sock"); + std::fs::create_dir_all(live.parent().unwrap()).unwrap(); + std::fs::write(&live, b"").unwrap(); + assert!(!scratch_socket(&live)); + } + + #[test] + fn scratch_socket_rejects_a_missing_path_and_dotdot() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join(".config/herdr/sessions/g1/herdr.sock"); + assert!(!missing.exists()); + assert!(std::fs::canonicalize(&missing).is_err()); + assert!(!scratch_socket(&missing)); + + let walked = dir + .path() + .join(".config/herdr/sessions/g1/../../herdr.sock"); + assert!(std::fs::canonicalize(&walked).is_err()); + assert!(!scratch_socket(&walked)); } #[test] @@ -432,6 +475,21 @@ mod tests { assert!(!scratch_socket(&linked)); } + #[test] + fn canonical_scratch_follows_a_symlink_that_stays_inside_the_session() { + let dir = tempfile::tempdir().unwrap(); + let real = dir.path().join("real/.config/herdr/sessions/g1/herdr.sock"); + std::fs::create_dir_all(real.parent().unwrap()).unwrap(); + std::fs::write(&real, b"").unwrap(); + let link_dir = dir.path().join("link/.config/herdr/sessions/g1"); + std::fs::create_dir_all(&link_dir).unwrap(); + let link = link_dir.join("herdr.sock"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let resolved = canonical_scratch(&link).unwrap(); + assert_eq!(resolved, std::fs::canonicalize(&real).unwrap()); + assert_ne!(resolved, link); + } + #[test] fn one_connection_watches_at_most_eight_panes_and_long_ids_are_refused() { assert!(admit_watch(7, false, "w1:p1").is_ok()); @@ -531,6 +589,7 @@ mod dial { queue_cap: 8, bind: addr, serve_origin: None, + pairing: crate::pairing::Pairing::new(), }; tokio::spawn(async move { let _ = axum::serve(tcp, crate::app(state)).await; diff --git a/crates/pendant-herdr/src/client.rs b/crates/pendant-herdr/src/client.rs index b2aed14..092b33f 100644 --- a/crates/pendant-herdr/src/client.rs +++ b/crates/pendant-herdr/src/client.rs @@ -85,6 +85,13 @@ impl HerdrClient { &self.socket_path } + /// A client that dials `path` instead of the configured path. + pub fn with_socket_path(&self, path: impl AsRef) -> Self { + let mut next = self.clone(); + next.socket_path = path.as_ref().to_path_buf(); + next + } + pub async fn snapshot(&self) -> Result { let raw = self.rpc("session.snapshot", json!({})).await?; Ok(Snapshot::from_raw(raw)) @@ -399,7 +406,12 @@ mod tests { }); let client = HerdrClient::with_herdr_bin(&sock, &bin); let err = client.rpc("ping", json!({})).await.unwrap_err(); - assert!(matches!(err, HerdrError::LineTooLong { limit: MAX_HERDR_LINE })); + assert!(matches!( + err, + HerdrError::LineTooLong { + limit: MAX_HERDR_LINE + } + )); assert!(!marker.exists()); server.await.unwrap(); } diff --git a/deny.toml b/deny.toml index 478e9e6..79d20d4 100644 --- a/deny.toml +++ b/deny.toml @@ -10,6 +10,7 @@ allow = [ "Apache-2.0 WITH LLVM-exception", "BSD-3-Clause", "Unicode-3.0", + "Zlib", ] confidence-threshold = 0.8 @@ -23,3 +24,4 @@ highlight = "all" unknown-registry = "deny" unknown-git = "deny" allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-git = ["https://github.com/Hedronite/lapis-lattice"]