From 5f05ce3a83b7810d4baa2770a4fc7ba29c1689f1 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Fri, 30 Oct 2026 22:24:10 -0400 Subject: [PATCH 1/5] app: close the store nits and add the device keystore Store::open no longer takes an index directory. Config is the vault and the inbox; the store picks the index in app-private storage itself, so a caller cannot hand it a symlink. The engine's own confinement still runs. The Android no_backup check now passes only the no_backup directory directly in the app's data directory. A decoy component elsewhere fails, and the comment says it is hygiene, not getNoBackupFilesDir(). Captured.index_error carries the kind of failure, never the engine's message, which can name vault paths. The backup-exclusion unsafe call has a SAFETY comment. app/src/platform/keystore.rs makes the device key: P-256 in the Secure Enclave via the Keychain, biometric per signature, this device only. The bridge format is a SEC1 public key and a DER ECDSA-SHA256 signature. Android returns Unsupported until an app shell owns Keystore and BiometricPrompt. Co-Authored-By: Claude Opus 5.5 --- app/src/notes/store.rs | 308 +++++++++++++++--- app/src/platform/keystore.rs | 604 +++++++++++++++++++++++++++++++++++ 2 files changed, 866 insertions(+), 46 deletions(-) create mode 100644 app/src/platform/keystore.rs 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(_)))); + } +} From c2cdfccf4747ee8ce7fd11f54f4ffdd0535723f4 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Fri, 30 Oct 2026 22:24:10 -0400 Subject: [PATCH 2/5] Add pairing routes and close the open bridge nits. PENDANT_BIND now accepts only loopback, Serve origin and scratch-path checks are pinned, and prompt, keys, approve, and worktree create require a phone-supplied signature plus an open grant. The app workspace is included in cargo deny. Co-authored-by: Cursor --- .github/workflows/ci.yml | 3 + Cargo.lock | 175 +++++++- README.md | 6 +- crates/pendant-bridge/Cargo.toml | 3 + crates/pendant-bridge/src/bind.rs | 15 +- crates/pendant-bridge/src/config.rs | 7 + crates/pendant-bridge/src/error.rs | 2 + crates/pendant-bridge/src/lib.rs | 15 +- crates/pendant-bridge/src/pairing.rs | 294 ++++++++++++++ crates/pendant-bridge/src/routes.rs | 577 ++++++++++++++++++++++++++- crates/pendant-bridge/src/session.rs | 32 +- deny.toml | 2 + 12 files changed, 1108 insertions(+), 23 deletions(-) create mode 100644 crates/pendant-bridge/src/pairing.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 872c576..966d53c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,9 @@ 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@cargo-deny + - name: cargo deny check (app) + run: cargo deny --manifest-path app/Cargo.toml check banned-names: runs-on: ubuntu-latest diff --git a/Cargo.lock b/Cargo.lock index 78be8b0..1ab6612 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -84,6 +84,12 @@ 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,6 +126,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -163,12 +175,49 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "data-encoding" version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" @@ -186,10 +235,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", ] +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "rand_core 0.6.4", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "errno" version = "0.3.14" @@ -206,6 +280,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -277,6 +357,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -498,10 +589,13 @@ name = "pendant-bridge" version = "0.0.1" dependencies = [ "axum", + "base64", + "ed25519-dalek", "futures-util", "mime_guess", "pendant-herdr", "pendant-web", + "rand_core 0.6.4", "serde", "serde_json", "tempfile", @@ -544,6 +638,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -590,7 +694,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 +704,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", ] [[package]] @@ -660,10 +773,19 @@ version = "8.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ffa149f6aa81b58a5b3011d01a857c4ed12c7a732d2c51947a4c7c692185f0" dependencies = [ - "sha2", + "sha2 0.11.0", "walkdir", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.5" @@ -692,6 +814,12 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -769,6 +897,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha2" version = "0.11.0" @@ -799,6 +938,12 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" + [[package]] name = "slab" version = "0.4.12" @@ -821,6 +966,22 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +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" @@ -1168,6 +1329,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/crates/pendant-bridge/Cargo.toml b/crates/pendant-bridge/Cargo.toml index 9243f9a..5ec0500 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" +ed25519-dalek = { version = "2.1", default-features = false, features = ["alloc", "rand_core"] } +rand_core = { version = "0.6", features = ["getrandom"] } 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..6d65dac --- /dev/null +++ b/crates/pendant-bridge/src/pairing.rs @@ -0,0 +1,294 @@ +//! Device pairing for the phone. The phone creates the key. This crate verifies +//! it. No key or token is minted here, and there is no relay. +//! +//! 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 ed25519_dalek::{Signature, Verifier, VerifyingKey}; + +/// Session takeover is not implemented. +pub const TAKEOVER: bool = false; + +const GRANT_TTL: Duration = Duration::from_secs(30); + +#[derive(Clone)] +pub struct Pairing { + inner: std::sync::Arc>, +} + +struct Inner { + ttl: Duration, + nonces: Vec, + devices: HashMap, + grants: HashMap, +} + +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, + nonces: Vec::new(), + devices: HashMap::new(), + grants: HashMap::new(), + })), + } + } + + /// 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 mut bytes = [0u8; 16]; + rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut bytes); + let nonce = bytes.iter().map(|b| format!("{b:02x}")).collect::(); + self.inner + .lock() + .expect("pairing") + .nonces + .push(nonce.clone()); + nonce + } + + pub fn qr_payload(nonce: &str) -> String { + format!("pendant-pair:v1:{nonce}") + } + + pub fn pair( + &self, + device_id: &str, + public_b64: &str, + nonce: &str, + sig_b64: &str, + takeover: bool, + ) -> Result<(), AuthError> { + if takeover || self.other_device_active(device_id) { + if self.other_device_active(device_id) { + return Err(AuthError::TakeoverOff); + } + } + let public = decode_key(public_b64).map_err(|_| AuthError::BadSignature)?; + let msg = pair_message(nonce); + if !verify(&public, &msg, sig_b64) { + return Err(AuthError::BadSignature); + } + let mut inner = self.inner.lock().expect("pairing"); + let Some(pos) = inner.nonces.iter().position(|n| n == nonce) else { + return Err(AuthError::BadSignature); + }; + inner.nonces.remove(pos); + inner.devices.insert( + device_id.to_string(), + Device { + public, + revoked: false, + }, + ); + Ok(()) + } + + pub fn revoke(&self, device_id: &str) { + let mut inner = self.inner.lock().expect("pairing"); + if let Some(device) = inner.devices.get_mut(device_id) { + device.revoked = true; + } else { + inner.devices.insert( + device_id.to_string(), + Device { + public: dummy_key(), + revoked: true, + }, + ); + } + if let Some(grant) = inner.grants.get_mut(device_id) { + grant.released = true; + } + } + + pub fn open_grant(&self, device_id: &str, sig_b64: &str) -> Result<(), AuthError> { + let msg = grant_message(device_id); + self.verify_device(device_id, &msg, sig_b64)?; + 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, + ) -> Result<(), AuthError> { + self.verify_device(device_id, message, sig_b64)?; + 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>) -> bool { + let Some(sig_b64) = sig_b64 else { + return false; + }; + let msg = attach_message(device_id); + if self.authorize(device_id, &msg, sig_b64).is_err() { + return false; + } + true + } + + 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_device( + &self, + device_id: &str, + message: &[u8], + sig_b64: &str, + ) -> Result<(), AuthError> { + let inner = self.inner.lock().expect("pairing"); + let Some(device) = inner.devices.get(device_id) else { + return Err(AuthError::BadSignature); + }; + if device.revoked { + return Err(AuthError::Revoked); + } + if verify(&device.public, message, sig_b64) { + Ok(()) + } else { + Err(AuthError::BadSignature) + } + } + + fn other_device_active(&self, device_id: &str) -> bool { + let inner = self.inner.lock().expect("pairing"); + inner + .devices + .iter() + .any(|(id, device)| id != device_id && !device.revoked) + } +} + +#[derive(Debug, PartialEq, Eq)] +pub enum AuthError { + BadSignature, + GrantRequired, + GrantReleased, + Revoked, + TakeoverOff, + Unpaired, +} + +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, canonical: &str) -> Vec { + format!("pendant-sign:v1\n{device_id}\n{method}\n{path}\n{canonical}").into_bytes() +} + +pub fn pair_message(nonce: &str) -> Vec { + format!("pendant-pair:v1:{nonce}").into_bytes() +} + +pub fn grant_message(device_id: &str) -> Vec { + format!("pendant-grant:v1\n{device_id}\nforeground").into_bytes() +} + +pub fn attach_message(device_id: &str) -> Vec { + format!("pendant-attach:v1\n{device_id}").into_bytes() +} + +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_slice(&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(|_| ())?; + let bytes: [u8; 32] = bytes.try_into().map_err(|_| ())?; + VerifyingKey::from_bytes(&bytes).map_err(|_| ()) +} + +fn dummy_key() -> VerifyingKey { + ed25519_dalek::SigningKey::from_bytes(&[1u8; 32]).verifying_key() +} + +#[cfg(test)] +pub struct TestDevice { + pub id: String, + signing: ed25519_dalek::SigningKey, +} + +#[cfg(test)] +impl TestDevice { + pub fn generate(id: &str) -> Self { + Self { + id: id.to_string(), + signing: ed25519_dalek::SigningKey::generate(&mut rand_core::OsRng), + } + } + + pub fn public_b64(&self) -> String { + STANDARD.encode(self.signing.verifying_key().as_bytes()) + } + + pub fn sign_b64(&self, message: &[u8]) -> String { + use ed25519_dalek::Signer; + STANDARD.encode(self.signing.sign(message).to_bytes()) + } +} diff --git a/crates/pendant-bridge/src/routes.rs b/crates/pendant-bridge/src/routes.rs index 6146276..800d960 100644 --- a/crates/pendant-bridge/src/routes.rs +++ b/crates/pendant-bridge/src/routes.rs @@ -15,6 +15,7 @@ use pendant_herdr::{CreateWorktree, HerdrError}; use serde::Deserialize; use serde_json::json; +use crate::pairing::{self, unpaired_log, AuthError}; use crate::session::{approve_key, scratch_socket}; use crate::static_files; use crate::AppState; @@ -27,6 +28,11 @@ 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/pair", post(pair_device)) + .route("/v1/grant", post(open_grant)) + .route("/v1/devices/{id}/revoke", post(revoke_device)) .route("/v1/events", get(events_inbox)) .route("/v1/events/stream", get(events_sse)) .route("/v1/ws", get(ws_upgrade)) @@ -234,11 +240,17 @@ fn refuse_write() -> Response { async fn create_worktree( State(state): State, + headers: HeaderMap, Json(body): Json, ) -> Response { if !scratch_socket(state.herdr.socket_path()) { 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 { Ok(value) => Json(value).into_response(), Err(err) => herdr_error(err), @@ -274,6 +286,7 @@ 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()) { @@ -286,6 +299,11 @@ async fn agent_prompt( ) .into_response(); } + 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 state.herdr.agent_prompt(&id, &body.prompt).await { Ok(value) => Json(value).into_response(), Err(err) => herdr_error(err), @@ -295,6 +313,7 @@ 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()) { @@ -307,6 +326,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, @@ -325,6 +350,166 @@ async fn agent_keys( } } +#[derive(Deserialize)] +struct ApproveBody { + decision: String, +} + +async fn agent_approve( + State(state): State, + Path(id): Path, + headers: HeaderMap, + Json(body): Json, +) -> Response { + if !scratch_socket(state.herdr.socket_path()) { + 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 state.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) -> impl IntoResponse { + let nonce = state.pairing.issue_nonce(); + Json(json!({ + "v": 1, + "nonce": nonce, + "payload": pairing::Pairing::qr_payload(&nonce), + })) +} + +#[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, + biometric: String, +} + +async fn open_grant(State(state): State, Json(body): Json) -> Response { + if body.biometric != "foreground" { + return auth_error(AuthError::GrantRequired); + } + match state.pairing.open_grant(&body.device_id, &body.sig) { + Ok(()) => Json(json!({"ok": true, "biometric": "foreground"})).into_response(), + Err(err) => auth_error(err), + } +} + +async fn revoke_device(State(state): State, Path(id): Path) -> impl IntoResponse { + state.pairing.revoke(&id); + Json(json!({"ok": true, "revoked": id, "real_pairings": state.pairing.real_pairings()})) +} + +fn signed_message(headers: &HeaderMap, method: &str, path: &str, canonical: &str) -> Vec { + let device = header_value(headers, "x-pendant-device").unwrap_or(""); + pairing::sign_message(device, method, path, 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"); + 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) { + 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 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"), + }; + 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 +578,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 +593,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 +625,72 @@ 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 sig = phone.sign_b64(&pairing::pair_message(nonce)); + let pair_body = serde_json::json!({ + "device_id": phone.id, + "public_key": phone.public_b64(), + "nonce": nonce, + "sig": sig, + }) + .to_string(); + let (status, _) = http(port, "POST", "/v1/pair", &pair_body).await; + assert_eq!(status, 200); + phone + } + + async fn enroll(port: u16) -> pairing::TestDevice { + let phone = pair_only(port).await; + let grant_sig = phone.sign_b64(&pairing::grant_message(&phone.id)); + let grant_body = serde_json::json!({ + "device_id": phone.id, + "sig": grant_sig, + "biometric": "foreground", + }) + .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 sig = phone.sign_b64(&pairing::sign_message(&phone.id, method, path, 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()), + ], + ) + .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 +738,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 +803,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 +869,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 +889,254 @@ 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 sig = phone.sign_b64(&pairing::attach_message(&phone.id)); + let attach = serde_json::json!({ + "v": 1, + "pane": "w1:p1", + "type": "attach", + "device_id": phone.id, + "sig": sig, + }) + .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 sig = other.sign_b64(&pairing::pair_message(&nonce)); + let body = serde_json::json!({ + "device_id": other.id, + "public_key": other.public_b64(), + "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 (status, raw) = http( + port, + "POST", + &format!("/v1/devices/{}/revoke", phone.id), + "", + ) + .await; + assert_eq!(status, 200); + let body = response_json(&raw); + assert_eq!(body["real_pairings"], 0); + let grant_sig = phone.sign_b64(&pairing::grant_message(&phone.id)); + let grant_body = serde_json::json!({ + "device_id": phone.id, + "sig": grant_sig, + "biometric": "foreground", + }) + .to_string(); + let (status, raw) = http(port, "POST", "/v1/grant", &grant_body).await; + assert_eq!(status, 403); + assert!(raw.contains("revoked")); + } } diff --git a/crates/pendant-bridge/src/session.rs b/crates/pendant-bridge/src/session.rs index 172108f..192d65d 100644 --- a/crates/pendant-bridge/src/session.rs +++ b/crates/pendant-bridge/src/session.rs @@ -99,9 +99,11 @@ 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, } pub async fn run_socket(socket: WebSocket, state: AppState) { @@ -116,6 +118,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 +133,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 +177,13 @@ 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()) { + attached = Some(id); + } + } + } "input" | "resize" | "scroll" => { let _ = tx .send( @@ -194,6 +203,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(); } @@ -414,6 +426,21 @@ mod tests { assert!(!scratch_socket(live)); } + #[test] + fn scratch_socket_allows_a_missing_path_and_still_rejects_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] fn scratch_socket_rejects_parent_dir_and_a_symlink_that_walks_out() { let walked = std::path::Path::new("/tmp/work/.config/herdr/sessions/g1/../../herdr.sock"); @@ -531,6 +558,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/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"] From 35bff6c21c8cc3eb4da0279e10caf9adb76e40f8 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Sat, 31 Oct 2026 07:01:27 -0400 Subject: [PATCH 3/5] Close the pairing review on one head. The QR nonce and revoke stay on the host, pairing signatures bind the device id and public key, revoked ids stay tombstoned, and the bridge verifies the phone P-256 signature with a one-time challenge. Co-authored-by: Cursor --- .github/workflows/ci.yml | 24 ++- Cargo.lock | 311 +++++++++++++++++++-------- crates/pendant-bridge/Cargo.toml | 4 +- crates/pendant-bridge/src/pairing.rs | 220 +++++++++++++------ crates/pendant-bridge/src/routes.rs | 199 +++++++++++++++-- crates/pendant-bridge/src/session.rs | 26 ++- 6 files changed, 581 insertions(+), 203 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 966d53c..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,14 +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@cargo-deny + - 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 @@ -42,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 1ab6612..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,6 +84,12 @@ 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" @@ -127,10 +139,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] -name = "const-oid" -version = "0.9.6" +name = "cmov" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" [[package]] name = "const-oid" @@ -138,6 +150,12 @@ 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" @@ -156,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" @@ -172,34 +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 = "curve25519-dalek" -version = "4.1.3" +name = "ctutils" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a" dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "curve25519-dalek-derive", - "digest 0.10.7", - "fiat-crypto", - "rustc_version", + "cmov", "subtle", - "zeroize", -] - -[[package]] -name = "curve25519-dalek-derive" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", ] [[package]] @@ -210,11 +229,12 @@ checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" [[package]] name = "der" -version = "0.7.10" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ - "const-oid 0.9.6", + "const-oid", + "pem-rfc7468", "zeroize", ] @@ -235,31 +255,43 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid 0.10.2", + "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] -name = "ed25519" -version = "2.2.3" +name = "ecdsa" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" dependencies = [ - "pkcs8", + "der", + "digest 0.11.3", + "elliptic-curve", + "rfc6979", "signature", + "spki", + "zeroize", ] [[package]] -name = "ed25519-dalek" -version = "2.2.0" +name = "elliptic-curve" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +checksum = "900f37e7e18d74a2347389af6cd69e3a30d5cc9e697f40004865679aa75e9c7c" dependencies = [ - "curve25519-dalek", - "ed25519", - "rand_core 0.6.4", - "serde", - "sha2 0.10.9", + "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", ] @@ -281,10 +313,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] -name = "fiat-crypto" -version = "0.2.9" +name = "ff" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] [[package]] name = "form_urlencoded" @@ -357,17 +393,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - [[package]] name = "getrandom" version = "0.3.4" @@ -389,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]] @@ -442,7 +488,9 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] @@ -567,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" @@ -590,12 +669,12 @@ version = "0.0.1" dependencies = [ "axum", "base64", - "ed25519-dalek", "futures-util", + "getrandom 0.3.4", "mime_guess", + "p256", "pendant-herdr", "pendant-web", - "rand_core 0.6.4", "serde", "serde_json", "tempfile", @@ -640,9 +719,9 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "pkcs8" -version = "0.10.2" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" dependencies = [ "der", "spki", @@ -657,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" @@ -709,21 +815,18 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.6.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [ - "getrandom 0.2.17", + "getrandom 0.3.4", ] [[package]] name = "rand_core" -version = "0.9.5" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] name = "regex-automata" @@ -742,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" @@ -773,19 +886,10 @@ version = "8.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ffa149f6aa81b58a5b3011d01a857c4ed12c7a732d2c51947a4c7c692185f0" dependencies = [ - "sha2 0.11.0", + "sha2", "walkdir", ] -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - [[package]] name = "rustix" version = "1.1.5" @@ -815,10 +919,18 @@ dependencies = [ ] [[package]] -name = "semver" -version = "1.0.28" +name = "sec1" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der", + "hybrid-array", + "subtle", + "zeroize", +] [[package]] name = "serde" @@ -887,21 +999,20 @@ dependencies = [ ] [[package]] -name = "sha1" -version = "0.10.7" +name = "serdect" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", + "base16ct", + "serde", ] [[package]] -name = "sha2" -version = "0.10.9" +name = "sha1" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", @@ -940,9 +1051,13 @@ dependencies = [ [[package]] name = "signature" -version = "2.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] [[package]] name = "slab" @@ -968,9 +1083,9 @@ dependencies = [ [[package]] name = "spki" -version = "0.7.3" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" dependencies = [ "base64ct", "der", @@ -1309,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" diff --git a/crates/pendant-bridge/Cargo.toml b/crates/pendant-bridge/Cargo.toml index 5ec0500..c437100 100644 --- a/crates/pendant-bridge/Cargo.toml +++ b/crates/pendant-bridge/Cargo.toml @@ -11,8 +11,8 @@ description = "Loopback HTTP bridge from Pendant to herdr" [dependencies] axum = { workspace = true, features = ["ws"] } base64 = "0.22" -ed25519-dalek = { version = "2.1", default-features = false, features = ["alloc", "rand_core"] } -rand_core = { version = "0.6", features = ["getrandom"] } +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/pairing.rs b/crates/pendant-bridge/src/pairing.rs index 6d65dac..78d596e 100644 --- a/crates/pendant-bridge/src/pairing.rs +++ b/crates/pendant-bridge/src/pairing.rs @@ -1,5 +1,8 @@ -//! Device pairing for the phone. The phone creates the key. This crate verifies -//! it. No key or token is minted here, and there is no relay. +//! 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. @@ -10,12 +13,17 @@ use std::time::{Duration, Instant}; use base64::engine::general_purpose::STANDARD; use base64::Engine; -use ed25519_dalek::{Signature, Verifier, VerifyingKey}; +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 { @@ -25,6 +33,7 @@ pub struct Pairing { struct Inner { ttl: Duration, nonces: Vec, + challenges: Vec, devices: HashMap, grants: HashMap, } @@ -49,6 +58,7 @@ impl Pairing { inner: std::sync::Arc::new(Mutex::new(Inner { ttl, nonces: Vec::new(), + challenges: Vec::new(), devices: HashMap::new(), grants: HashMap::new(), })), @@ -69,21 +79,24 @@ impl Pairing { } pub fn issue_nonce(&self) -> String { - let mut bytes = [0u8; 16]; - rand_core::RngCore::fill_bytes(&mut rand_core::OsRng, &mut bytes); - let nonce = bytes.iter().map(|b| format!("{b:02x}")).collect::(); - self.inner - .lock() - .expect("pairing") - .nonces - .push(nonce.clone()); + 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) -> String { + let challenge = random_token(); + let mut inner = self.inner.lock().expect("pairing"); + push_capped(&mut inner.challenges, challenge.clone()); + 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, @@ -92,17 +105,26 @@ impl Pairing { sig_b64: &str, takeover: bool, ) -> Result<(), AuthError> { - if takeover || self.other_device_active(device_id) { - if self.other_device_active(device_id) { - return Err(AuthError::TakeoverOff); - } - } let public = decode_key(public_b64).map_err(|_| AuthError::BadSignature)?; - let msg = pair_message(nonce); + 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); + } let Some(pos) = inner.nonces.iter().position(|n| n == nonce) else { return Err(AuthError::BadSignature); }; @@ -117,27 +139,48 @@ impl Pairing { Ok(()) } - pub fn revoke(&self, device_id: &str) { + /// 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 let Some(device) = inner.devices.get_mut(device_id) { - device.revoked = true; - } else { - inner.devices.insert( - device_id.to_string(), - Device { - public: dummy_key(), - revoked: true, - }, - ); + if !take_challenge(&mut inner.challenges, challenge) { + return Err(AuthError::BadSignature); } - if let Some(grant) = inner.grants.get_mut(device_id) { + 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(()) } - pub fn open_grant(&self, device_id: &str, sig_b64: &str) -> Result<(), AuthError> { - let msg = grant_message(device_id); - self.verify_device(device_id, &msg, sig_b64)?; + 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(), @@ -154,8 +197,9 @@ impl Pairing { device_id: &str, message: &[u8], sig_b64: &str, + challenge: &str, ) -> Result<(), AuthError> { - self.verify_device(device_id, message, sig_b64)?; + 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 { @@ -171,15 +215,12 @@ impl Pairing { Ok(()) } - pub fn attach(&self, device_id: &str, sig_b64: Option<&str>) -> bool { - let Some(sig_b64) = sig_b64 else { + 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); - if self.authorize(device_id, &msg, sig_b64).is_err() { - return false; - } - true + let msg = attach_message(device_id, challenge); + self.authorize(device_id, &msg, sig_b64, challenge).is_ok() } pub fn release(&self, device_id: &str) { @@ -189,33 +230,31 @@ impl Pairing { } } - fn verify_device( + fn verify_fresh( &self, device_id: &str, message: &[u8], sig_b64: &str, + challenge: &str, ) -> Result<(), AuthError> { - let inner = self.inner.lock().expect("pairing"); + let mut inner = self.inner.lock().expect("pairing"); + if !take_challenge(&mut inner.challenges, 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); } - if verify(&device.public, message, sig_b64) { + let public = device.public.clone(); + drop(inner); + if verify(&public, message, sig_b64) { Ok(()) } else { Err(AuthError::BadSignature) } } - - fn other_device_active(&self, device_id: &str) -> bool { - let inner = self.inner.lock().expect("pairing"); - inner - .devices - .iter() - .any(|(id, device)| id != device_id && !device.revoked) - } } #[derive(Debug, PartialEq, Eq)] @@ -232,27 +271,58 @@ 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, canonical: &str) -> Vec { - format!("pendant-sign:v1\n{device_id}\n{method}\n{path}\n{canonical}").into_bytes() +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 pair_message(nonce: &str) -> Vec { - format!("pendant-pair:v1:{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 grant_message(device_id: &str) -> Vec { - format!("pendant-grant:v1\n{device_id}\nforeground").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 attach_message(device_id: &str) -> Vec { - format!("pendant-attach:v1\n{device_id}").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 take_challenge(challenges: &mut Vec, challenge: &str) -> bool { + let Some(pos) = challenges.iter().position(|item| item == challenge) else { + return false; + }; + challenges.remove(pos); + true } 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_slice(&bytes) else { + let Ok(sig) = Signature::from_der(&bytes) else { return false; }; key.verify(message, &sig).is_ok() @@ -260,18 +330,24 @@ fn verify(key: &VerifyingKey, message: &[u8], sig_b64: &str) -> bool { fn decode_key(public_b64: &str) -> Result { let bytes = STANDARD.decode(public_b64.trim()).map_err(|_| ())?; - let bytes: [u8; 32] = bytes.try_into().map_err(|_| ())?; - VerifyingKey::from_bytes(&bytes).map_err(|_| ()) -} - -fn dummy_key() -> VerifyingKey { - ed25519_dalek::SigningKey::from_bytes(&[1u8; 32]).verifying_key() + VerifyingKey::from_sec1_bytes(&bytes).map_err(|_| ()) } #[cfg(test)] pub struct TestDevice { pub id: String, - signing: ed25519_dalek::SigningKey, + 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)] @@ -279,16 +355,18 @@ impl TestDevice { pub fn generate(id: &str) -> Self { Self { id: id.to_string(), - signing: ed25519_dalek::SigningKey::generate(&mut rand_core::OsRng), + signing: random_signing_key(), } } pub fn public_b64(&self) -> String { - STANDARD.encode(self.signing.verifying_key().as_bytes()) + let point = self.signing.verifying_key().to_sec1_point(false); + STANDARD.encode(point.as_bytes()) } pub fn sign_b64(&self, message: &[u8]) -> String { - use ed25519_dalek::Signer; - STANDARD.encode(self.signing.sign(message).to_bytes()) + 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 800d960..e8469a1 100644 --- a/crates/pendant-bridge/src/routes.rs +++ b/crates/pendant-bridge/src/routes.rs @@ -30,6 +30,7 @@ pub fn router(state: AppState) -> Router { .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)) @@ -385,12 +386,23 @@ async fn agent_approve( } } -async fn pair_qr(State(state): State) -> impl IntoResponse { +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) -> impl IntoResponse { + Json(json!({ + "challenge": state.pairing.issue_challenge(), })) } @@ -421,33 +433,58 @@ async fn pair_device(State(state): State, Json(body): Json) struct GrantBody { device_id: String, sig: String, - biometric: String, + challenge: String, } async fn open_grant(State(state): State, Json(body): Json) -> Response { - if body.biometric != "foreground" { - return auth_error(AuthError::GrantRequired); - } - match state.pairing.open_grant(&body.device_id, &body.sig) { - Ok(()) => Json(json!({"ok": true, "biometric": "foreground"})).into_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) -> impl IntoResponse { - state.pairing.revoke(&id); - Json(json!({"ok": true, "revoked": id, "real_pairings": state.pairing.real_pairings()})) +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), + } } fn signed_message(headers: &HeaderMap, method: &str, path: &str, canonical: &str) -> Vec { let device = header_value(headers, "x-pendant-device").unwrap_or(""); - pairing::sign_message(device, method, path, canonical) + 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)) { @@ -461,7 +498,7 @@ fn gate_write(state: &AppState, headers: &HeaderMap, message: &[u8]) -> Result<( "device signature is missing or wrong", )); }; - match state.pairing.authorize(device, message, sig) { + match state.pairing.authorize(device, message, sig, challenge) { Ok(()) => Ok(()), Err(err) => Err(auth_error(err)), } @@ -482,6 +519,15 @@ fn via_serve(host: Option<&str>, serve_origin: Option<&str>) -> bool { || (host.eq_ignore_ascii_case(&origin.host) && (origin.port == 80 || origin.port == 443)) } +fn local_only(state: &AppState, headers: &HeaderMap) -> Result<(), Response> { + let host = headers.get(HOST).and_then(|value| value.to_str().ok()); + if via_serve(host, state.serve_origin.as_deref()) { + Err(forbid("local_only", "this route is only on the host")) + } else { + Ok(()) + } +} + fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { headers .get(name) @@ -641,10 +687,11 @@ mod tests { .starts_with("pendant-pair:v1:")); assert!(!raw.contains("private_key")); let phone = pairing::TestDevice::generate("phone-1"); - let sig = phone.sign_b64(&pairing::pair_message(nonce)); + 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": phone.public_b64(), + "public_key": public, "nonce": nonce, "sig": sig, }) @@ -654,13 +701,23 @@ mod tests { 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 grant_sig = phone.sign_b64(&pairing::grant_message(&phone.id)); + 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, - "biometric": "foreground", + "challenge": challenge, }) .to_string(); let (status, _) = http(port, "POST", "/v1/grant", &grant_body).await; @@ -676,7 +733,10 @@ mod tests { canonical: &str, body: &str, ) -> (u16, String) { - let sig = phone.sign_b64(&pairing::sign_message(&phone.id, method, path, canonical)); + let challenge = fresh_challenge(port).await; + let sig = phone.sign_b64(&pairing::sign_message( + &phone.id, method, path, &challenge, canonical, + )); http_headers( port, method, @@ -686,6 +746,7 @@ mod tests { &[ ("x-pendant-device", phone.id.as_str()), ("x-pendant-signature", sig.as_str()), + ("x-pendant-challenge", challenge.as_str()), ], ) .await @@ -1057,13 +1118,15 @@ mod tests { format!("http://127.0.0.1:{port}").parse().unwrap(), ); let (mut ws, _) = tokio_tungstenite::connect_async(req).await.unwrap(); - let sig = phone.sign_b64(&pairing::attach_message(&phone.id)); + 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; @@ -1097,10 +1160,11 @@ mod tests { assert_eq!(status, 200); let nonce = response_json(&raw)["nonce"].as_str().unwrap().to_string(); let other = pairing::TestDevice::generate("phone-2"); - let sig = other.sign_b64(&pairing::pair_message(&nonce)); + 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": other.public_b64(), + "public_key": public, "nonce": nonce, "sig": sig, "takeover": true, @@ -1118,25 +1182,114 @@ mod tests { spawn_mock(&scratch, Arc::new(Mutex::new(Vec::new()))); let port = serve_on(&scratch).await; let phone = pair_only(port).await; - let (status, raw) = http( + 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_sig = phone.sign_b64(&pairing::grant_message(&phone.id)); + 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, - "biometric": "foreground", + "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")); + let _ = status; + } } diff --git a/crates/pendant-bridge/src/session.rs b/crates/pendant-bridge/src/session.rs index 192d65d..27682aa 100644 --- a/crates/pendant-bridge/src/session.rs +++ b/crates/pendant-bridge/src/session.rs @@ -104,6 +104,8 @@ struct Up { sig: Option, #[serde(default)] device_id: Option, + #[serde(default)] + challenge: Option, } pub async fn run_socket(socket: WebSocket, state: AppState) { @@ -179,7 +181,10 @@ pub async fn run_socket(socket: WebSocket, state: AppState) { } "attach" => { if let Some(id) = up.device_id.clone() { - if state.pairing.attach(&id, up.sig.as_deref()) { + if state + .pairing + .attach(&id, up.sig.as_deref(), up.challenge.as_deref()) + { attached = Some(id); } } @@ -327,7 +332,7 @@ pub fn scratch_socket(path: &std::path::Path) -> bool { } match std::fs::canonicalize(path) { Ok(canonical) => socket_shape(&canonical), - Err(_) => socket_shape(path), + Err(_) => false, } } @@ -420,19 +425,24 @@ 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_allows_a_missing_path_and_still_rejects_dotdot() { + 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)); + assert!(!scratch_socket(&missing)); let walked = dir .path() From 3d5488a658717a01a1e9bb8005bf97ef0d766e69 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Sat, 31 Oct 2026 09:32:17 -0400 Subject: [PATCH 4/5] Refuse a proxied pairing nonce and close the remaining pairing nits. A loopback Host with a forwarding header is not local, so it cannot obtain a QR nonce or use host revoke. Writes dial the canonical scratch socket, and challenges expire and are rate limited. Co-authored-by: Cursor --- crates/pendant-bridge/src/client.rs | 427 +++++++++++++++++++++++++++ crates/pendant-bridge/src/pairing.rs | 126 +++++++- crates/pendant-bridge/src/routes.rs | 202 +++++++++++-- crates/pendant-bridge/src/session.rs | 31 +- crates/pendant-herdr/src/client.rs | 14 +- 5 files changed, 760 insertions(+), 40 deletions(-) create mode 100644 crates/pendant-bridge/src/client.rs diff --git a/crates/pendant-bridge/src/client.rs b/crates/pendant-bridge/src/client.rs new file mode 100644 index 0000000..6b9ff22 --- /dev/null +++ b/crates/pendant-bridge/src/client.rs @@ -0,0 +1,427 @@ +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use tokio::io::{AsyncWriteExt, BufReader}; + +use tokio::net::UnixStream; + +use crate::cli; +use crate::error::HerdrError; +use crate::line::{read_limited_line, MAX_HERDR_LINE}; +use crate::paths::expand_path; +use crate::protocol::{RpcRequest, RpcResponse}; +use crate::snapshot::{InboxItem, Snapshot}; +use crate::via::{stamp, Via}; + +const RPC_TIMEOUT: Duration = Duration::from_secs(8); + +#[derive(Clone, Debug)] +pub struct HerdrClient { + socket_path: PathBuf, + pub(crate) herdr_bin: PathBuf, + pub(crate) ack_timeout: Duration, + next_id: Arc, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +pub struct CreateWorktree { + #[serde(default)] + pub workspace_id: Option, + #[serde(default)] + pub cwd: Option, + #[serde(default)] + pub branch: Option, + #[serde(default)] + pub base: Option, + #[serde(default)] + pub path: Option, + #[serde(default)] + pub label: Option, + #[serde(default)] + pub focus: bool, +} + +impl HerdrClient { + pub fn new(socket_path: impl AsRef) -> Self { + Self { + socket_path: socket_path.as_ref().to_path_buf(), + herdr_bin: resolve_executable(PathBuf::from("herdr")), + ack_timeout: Duration::from_secs(8), + next_id: Arc::new(AtomicU64::new(1)), + } + } + + /// `bin` is the herdr executable. An absolute path is used as given. + /// A name is resolved on `PATH` at startup. Transcript tests pass a + /// binary whose file name is not `herdr`. + pub fn with_herdr_bin(socket_path: impl AsRef, bin: impl Into) -> Self { + let mut client = Self::new(socket_path); + client.herdr_bin = resolve_executable(bin.into()); + client + } + + pub fn with_ack_timeout(mut self, timeout: Duration) -> Self { + self.ack_timeout = timeout; + self + } + + pub(crate) fn herdr_bin_path(&self) -> &Path { + &self.herdr_bin + } + + pub(crate) fn alloc_id(&self) -> String { + format!("p-{}", self.next_id.fetch_add(1, Ordering::Relaxed)) + } + + pub fn from_env_path(raw: &str) -> Self { + Self::new(expand_path(raw)) + } + + pub fn socket_path(&self) -> &Path { + &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)) + } + + pub async fn inbox(&self) -> Result, HerdrError> { + Ok(self.snapshot().await?.inbox()) + } + + pub async fn worktree_list(&self, workspace_id: Option<&str>) -> Result { + let mut params = json!({}); + if let Some(id) = workspace_id { + params["workspace_id"] = json!(id); + } + self.rpc("worktree.list", params).await + } + + pub async fn worktree_create(&self, create: &CreateWorktree) -> Result { + self.rpc("worktree.create", serde_json::to_value(create)?) + .await + } + + pub async fn agent_prompt(&self, target: &str, text: &str) -> Result { + self.rpc("agent.prompt", json!({ "target": target, "text": text })) + .await + } + + pub async fn agent_send_keys( + &self, + target: &str, + keys: &[String], + ) -> Result { + self.rpc("agent.send_keys", json!({ "target": target, "keys": keys })) + .await + } + + pub async fn agent_read(&self, target: &str) -> Result { + self.rpc( + "agent.read", + json!({ "target": target, "source": "recent", "lines": 80 }), + ) + .await + } + + pub async fn agent_get(&self, target: &str) -> Result { + self.rpc("agent.get", json!({ "target": target })).await + } + + pub async fn ping(&self) -> Result { + self.rpc("ping", json!({})).await + } + + pub async fn health(&self) -> bool { + match tokio::time::timeout(Duration::from_secs(2), self.ping()).await { + Ok(Ok(_)) => true, + _ => self.snapshot().await.is_ok(), + } + } + + /// Acknowledgement only. The open stream is [`Self::subscribe_events`]. + /// This drops the connection after the ack. It does not poll. + pub async fn subscribe_ack(&self) -> Result { + let sub = self + .subscribe_events(&[json!({ "type": "pane.agent_status_changed" })]) + .await?; + Ok(sub.ack) + } + + pub async fn rpc(&self, method: &str, params: Value) -> Result { + match self.rpc_socket(method, params.clone()).await { + Ok(value) => Ok(stamp(value, Via::Socket)), + Err(sock_err) if self.cli_fallback(&sock_err) => { + tracing::debug!(error = %sock_err, method, "herdr socket connect failed; trying CLI"); + match cli::rpc_cli(&self.herdr_bin, &self.socket_path, method, params).await { + Ok(value) => Ok(stamp(value, Via::Cli)), + Err(HerdrError::UnsupportedMethod(method)) => { + Err(HerdrError::UnsupportedMethod(method)) + } + Err(cli_err) => Err(HerdrError::Unavailable { + path: self.socket_path.clone(), + socket: sock_err.to_string(), + cli: cli_err.to_string(), + }), + } + } + Err(err) => Err(err), + } + } + + /// CLI only when the path is already a socket inode and connect fails. + /// A missing path or a regular file is a wrong path: return before `rpc_cli`. + fn cli_fallback(&self, err: &HerdrError) -> bool { + match err { + HerdrError::Connect { path, .. } => path_is_socket(path), + _ => false, + } + } + + pub(crate) async fn connect_socket(&self) -> Result { + let connect = UnixStream::connect(&self.socket_path); + match tokio::time::timeout(RPC_TIMEOUT, connect).await { + Ok(Ok(stream)) => Ok(stream), + Ok(Err(source)) => Err(HerdrError::Connect { + path: self.socket_path.clone(), + source, + }), + Err(_) => Err(HerdrError::Connect { + path: self.socket_path.clone(), + source: std::io::Error::new( + std::io::ErrorKind::TimedOut, + "timed out connecting to herdr socket", + ), + }), + } + } + + async fn rpc_socket(&self, method: &str, params: Value) -> Result { + let id = self.alloc_id(); + let request = RpcRequest::new(id.clone(), method, params); + let line = request.to_line()?; + let stream = self.connect_socket().await?; + + let exchange = async { + let mut stream = stream; + stream.write_all(line.as_bytes()).await?; + stream.flush().await?; + let mut reader = BufReader::new(stream); + let response_line = read_limited_line(&mut reader, MAX_HERDR_LINE).await?; + let parsed: RpcResponse = serde_json::from_str(response_line.trim())?; + if let Some(err) = parsed.error { + return Err(HerdrError::from_rpc(err)); + } + Ok(parsed.result.unwrap_or(Value::Null)) + }; + + match tokio::time::timeout(RPC_TIMEOUT, exchange).await { + Ok(result) => result, + Err(_) => Err(HerdrError::Timeout), + } + } +} + +/// An absolute path is kept. A bare name is the first match on `PATH`. +pub(crate) fn resolve_executable(bin: PathBuf) -> PathBuf { + if bin.is_absolute() { + return bin; + } + let Some(path_var) = std::env::var_os("PATH") else { + return bin; + }; + for dir in std::env::split_paths(&path_var) { + let candidate = dir.join(&bin); + if candidate.is_file() { + return candidate; + } + } + bin +} + +fn path_is_socket(path: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::FileTypeExt; + std::fs::metadata(path) + .map(|meta| meta.file_type().is_socket()) + .unwrap_or(false) + } + #[cfg(not(unix))] + { + let _ = path; + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::line::MAX_HERDR_LINE; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + use tokio::net::UnixListener; + + #[tokio::test] + async fn socket_snapshot_roundtrip() { + let dir = tempfile::tempdir().unwrap(); + let sock = dir.path().join("herdr.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + reader.read_line(&mut line).await.unwrap(); + let req: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(req["method"], "session.snapshot"); + assert!(req["id"].as_str().unwrap().starts_with("p-")); + let resp = json!({ + "id": req["id"], + "result": { + "type": "session_snapshot", + "agents": [{ + "pane_id": "w1:p1", + "agent": "codex", + "agent_status": "idle", + "workspace_id": "w1", + "tab_id": "w1:t1" + }] + } + }); + let mut stream = reader.into_inner(); + stream + .write_all(format!("{resp}\n").as_bytes()) + .await + .unwrap(); + }); + + let client = HerdrClient::new(&sock); + let snap = client.snapshot().await.unwrap(); + assert_eq!(snap.via, "socket"); + assert_eq!(snap.raw["via"], "socket"); + assert_eq!(snap.agents.len(), 1); + assert_eq!(snap.agents[0].pane_id, "w1:p1"); + assert_eq!(snap.agents[0].status, "idle"); + server.await.unwrap(); + } + + #[tokio::test] + async fn missing_socket_is_transport_error() { + let client = HerdrClient::new("/tmp/pendant-definitely-missing.sock"); + let err = client.rpc_socket("ping", json!({})).await.unwrap_err(); + assert!(err.is_transport()); + } + + /// Wrong path: the socket file is not there. A fake herdr that would + /// succeed must not run. The error is returned before `rpc_cli`. + #[tokio::test] + async fn wrong_socket_path_fails_before_rpc_cli() { + let dir = tempfile::tempdir().unwrap(); + let marker = dir.path().join("cli-was-called"); + let bin = write_fake_herdr(dir.path(), &marker); + let missing = dir.path().join("no-such-herdr.sock"); + let client = HerdrClient::with_herdr_bin(&missing, &bin); + let err = client.rpc("session.snapshot", json!({})).await.unwrap_err(); + assert!(matches!(err, HerdrError::Connect { .. })); + assert!(!marker.exists(), "rpc_cli ran for a wrong socket path"); + } + + /// `via: cli` only when connect to an existing socket inode fails. + #[tokio::test] + async fn cli_fallback_only_when_socket_connect_fails() { + let dir = tempfile::tempdir().unwrap(); + let marker = dir.path().join("cli-was-called"); + let bin = write_fake_herdr(dir.path(), &marker); + let sock = dir.path().join("refused.sock"); + let _inode = std::os::unix::net::UnixDatagram::bind(&sock).unwrap(); + let client = HerdrClient::with_herdr_bin(&sock, &bin); + let value = client.rpc("ping", json!({})).await.unwrap(); + assert_eq!(value["via"], "cli"); + assert_eq!(value["from"], "cli"); + assert!(marker.exists()); + } + + /// A socket that answers an RPC error must not be rewritten by the CLI. + #[tokio::test] + async fn socket_rpc_error_does_not_fall_through_to_cli() { + let dir = tempfile::tempdir().unwrap(); + let marker = dir.path().join("cli-was-called"); + let bin = write_fake_herdr(dir.path(), &marker); + let sock = dir.path().join("herdr.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + reader.read_line(&mut line).await.unwrap(); + let req: Value = serde_json::from_str(&line).unwrap(); + let resp = json!({ + "id": req["id"], + "error": { "code": "nope", "message": "socket said no" } + }); + stream = reader.into_inner(); + stream + .write_all(format!("{resp}\n").as_bytes()) + .await + .unwrap(); + }); + let client = HerdrClient::with_herdr_bin(&sock, &bin); + let err = client.rpc("ping", json!({})).await.unwrap_err(); + match err { + HerdrError::Rpc { code, .. } => assert_eq!(code, "nope"), + other => panic!("expected socket RPC error, got {other}"), + } + assert!(!marker.exists()); + server.await.unwrap(); + } + + #[tokio::test] + async fn rpc_reply_longer_than_the_cap_is_an_error() { + let dir = tempfile::tempdir().unwrap(); + let marker = dir.path().join("cli-was-called"); + let bin = write_fake_herdr(dir.path(), &marker); + let sock = dir.path().join("herdr.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut reader = BufReader::new(stream); + let mut line = String::new(); + reader.read_line(&mut line).await.unwrap(); + let mut huge = vec![b'x'; MAX_HERDR_LINE + 1]; + huge.push(b'\n'); + let mut stream = reader.into_inner(); + stream.write_all(&huge).await.unwrap(); + }); + 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!(!marker.exists()); + server.await.unwrap(); + } + + fn write_fake_herdr(dir: &std::path::Path, marker: &std::path::Path) -> PathBuf { + let path = dir.join("fake-herdr"); + let marker_q = marker.to_string_lossy().replace('\'', "'\\''"); + let body = format!( + "#!/bin/sh\ntouch '{marker_q}'\nprintf '%s\\n' '{{\"ok\":true,\"from\":\"cli\"}}'\n" + ); + std::fs::write(&path, body).unwrap(); + use std::os::unix::fs::PermissionsExt; + let mut perms = std::fs::metadata(&path).unwrap().permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(&path, perms).unwrap(); + path + } +} diff --git a/crates/pendant-bridge/src/pairing.rs b/crates/pendant-bridge/src/pairing.rs index 78d596e..ce45ba7 100644 --- a/crates/pendant-bridge/src/pairing.rs +++ b/crates/pendant-bridge/src/pairing.rs @@ -32,12 +32,21 @@ pub struct Pairing { struct Inner { ttl: Duration, + challenge_ttl: Duration, + challenge_rate: usize, + challenge_window: Duration, nonces: Vec, - challenges: Vec, + challenges: Vec, + recent: Vec, devices: HashMap, grants: HashMap, } +struct Ticket { + token: String, + issued: Instant, +} + struct Device { public: VerifyingKey, revoked: bool, @@ -57,14 +66,27 @@ impl Pairing { 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 @@ -85,11 +107,31 @@ impl Pairing { nonce } - pub fn issue_challenge(&self) -> String { - let challenge = random_token(); + pub fn issue_challenge(&self) -> Result { let mut inner = self.inner.lock().expect("pairing"); - push_capped(&mut inner.challenges, challenge.clone()); - challenge + 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 { @@ -125,10 +167,9 @@ impl Pairing { if other && (takeover || !TAKEOVER) { return Err(AuthError::TakeoverOff); } - let Some(pos) = inner.nonces.iter().position(|n| n == nonce) else { + if !take_token(&mut inner.nonces, nonce) { return Err(AuthError::BadSignature); - }; - inner.nonces.remove(pos); + } inner.devices.insert( device_id.to_string(), Device { @@ -150,7 +191,7 @@ impl Pairing { ) -> Result<(), AuthError> { let msg = revoke_message(target_id, challenge); let mut inner = self.inner.lock().expect("pairing"); - if !take_challenge(&mut inner.challenges, challenge) { + if !take_ticket(&mut inner, challenge) { return Err(AuthError::BadSignature); } let Some(signer) = inner.devices.get(signer_id) else { @@ -173,6 +214,18 @@ impl Pairing { 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, @@ -238,7 +291,7 @@ impl Pairing { challenge: &str, ) -> Result<(), AuthError> { let mut inner = self.inner.lock().expect("pairing"); - if !take_challenge(&mut inner.challenges, challenge) { + if !take_ticket(&mut inner, challenge) { return Err(AuthError::BadSignature); } let Some(device) = inner.devices.get(device_id) else { @@ -265,6 +318,7 @@ pub enum AuthError { Revoked, TakeoverOff, Unpaired, + RateLimited, } pub fn unpaired_log(host: &str) -> String { @@ -310,12 +364,54 @@ fn push_capped(items: &mut Vec, item: String) { items.push(item); } -fn take_challenge(challenges: &mut Vec, challenge: &str) -> bool { - let Some(pos) = challenges.iter().position(|item| item == challenge) else { +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; - }; - challenges.remove(pos); - true + } + 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 { diff --git a/crates/pendant-bridge/src/routes.rs b/crates/pendant-bridge/src/routes.rs index e8469a1..062b794 100644 --- a/crates/pendant-bridge/src/routes.rs +++ b/crates/pendant-bridge/src/routes.rs @@ -16,7 +16,7 @@ use serde::Deserialize; use serde_json::json; use crate::pairing::{self, unpaired_log, AuthError}; -use crate::session::{approve_key, scratch_socket}; +use crate::session::{approve_key, canonical_scratch}; use crate::static_files; use crate::AppState; @@ -34,6 +34,7 @@ pub fn router(state: AppState) -> Router { .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)) @@ -244,15 +245,15 @@ async fn create_worktree( 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), } @@ -290,9 +291,9 @@ async fn agent_prompt( 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, @@ -305,7 +306,7 @@ async fn agent_prompt( if let Err(response) = gate_write(&state, &headers, &message) { return response; } - match state.herdr.agent_prompt(&id, &body.prompt).await { + match herdr.agent_prompt(&id, &body.prompt).await { Ok(value) => Json(value).into_response(), Err(err) => herdr_error(err), } @@ -317,9 +318,9 @@ async fn agent_keys( 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, @@ -345,7 +346,7 @@ 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), } @@ -362,9 +363,9 @@ async fn agent_approve( headers: HeaderMap, Json(body): Json, ) -> Response { - if !scratch_socket(state.herdr.socket_path()) { + 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) { @@ -380,7 +381,7 @@ async fn agent_approve( ) .into_response(); } - match state.herdr.agent_send_keys(&id, &[decision]).await { + match herdr.agent_send_keys(&id, &[decision]).await { Ok(value) => Json(value).into_response(), Err(err) => herdr_error(err), } @@ -400,10 +401,16 @@ async fn pair_qr(State(state): State, headers: HeaderMap) -> Response .into_response() } -async fn issue_challenge(State(state): State) -> impl IntoResponse { - Json(json!({ - "challenge": state.pairing.issue_challenge(), - })) +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)] @@ -474,6 +481,28 @@ async fn revoke_device( } } +#[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(""); @@ -519,15 +548,26 @@ fn via_serve(host: Option<&str>, serve_origin: Option<&str>) -> bool { || (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()); - if via_serve(host, state.serve_origin.as_deref()) { + // 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) @@ -552,6 +592,7 @@ fn auth_error(err: AuthError) -> Response { 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) } @@ -1290,6 +1331,129 @@ mod tests { let (status, raw) = http(port, "POST", "/v1/pair", &body).await; assert_eq!(status, 403); assert!(raw.contains("revoked")); - let _ = status; + } + + #[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 27682aa..a286ba7 100644 --- a/crates/pendant-bridge/src/session.rs +++ b/crates/pendant-bridge/src/session.rs @@ -326,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(_) => false, + 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 @@ -469,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()); 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(); } From 72fcdd4c678d23aec272476d495d519bec071525 Mon Sep 17 00:00:00 2001 From: VirtualMachinist Date: Sat, 31 Oct 2026 09:32:33 -0400 Subject: [PATCH 5/5] Remove a herdr client copy that landed in the bridge crate. Co-authored-by: Cursor --- crates/pendant-bridge/src/client.rs | 427 ---------------------------- 1 file changed, 427 deletions(-) delete mode 100644 crates/pendant-bridge/src/client.rs diff --git a/crates/pendant-bridge/src/client.rs b/crates/pendant-bridge/src/client.rs deleted file mode 100644 index 6b9ff22..0000000 --- a/crates/pendant-bridge/src/client.rs +++ /dev/null @@ -1,427 +0,0 @@ -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Arc; -use std::time::Duration; - -use serde::{Deserialize, Serialize}; -use serde_json::{json, Value}; -use tokio::io::{AsyncWriteExt, BufReader}; - -use tokio::net::UnixStream; - -use crate::cli; -use crate::error::HerdrError; -use crate::line::{read_limited_line, MAX_HERDR_LINE}; -use crate::paths::expand_path; -use crate::protocol::{RpcRequest, RpcResponse}; -use crate::snapshot::{InboxItem, Snapshot}; -use crate::via::{stamp, Via}; - -const RPC_TIMEOUT: Duration = Duration::from_secs(8); - -#[derive(Clone, Debug)] -pub struct HerdrClient { - socket_path: PathBuf, - pub(crate) herdr_bin: PathBuf, - pub(crate) ack_timeout: Duration, - next_id: Arc, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -pub struct CreateWorktree { - #[serde(default)] - pub workspace_id: Option, - #[serde(default)] - pub cwd: Option, - #[serde(default)] - pub branch: Option, - #[serde(default)] - pub base: Option, - #[serde(default)] - pub path: Option, - #[serde(default)] - pub label: Option, - #[serde(default)] - pub focus: bool, -} - -impl HerdrClient { - pub fn new(socket_path: impl AsRef) -> Self { - Self { - socket_path: socket_path.as_ref().to_path_buf(), - herdr_bin: resolve_executable(PathBuf::from("herdr")), - ack_timeout: Duration::from_secs(8), - next_id: Arc::new(AtomicU64::new(1)), - } - } - - /// `bin` is the herdr executable. An absolute path is used as given. - /// A name is resolved on `PATH` at startup. Transcript tests pass a - /// binary whose file name is not `herdr`. - pub fn with_herdr_bin(socket_path: impl AsRef, bin: impl Into) -> Self { - let mut client = Self::new(socket_path); - client.herdr_bin = resolve_executable(bin.into()); - client - } - - pub fn with_ack_timeout(mut self, timeout: Duration) -> Self { - self.ack_timeout = timeout; - self - } - - pub(crate) fn herdr_bin_path(&self) -> &Path { - &self.herdr_bin - } - - pub(crate) fn alloc_id(&self) -> String { - format!("p-{}", self.next_id.fetch_add(1, Ordering::Relaxed)) - } - - pub fn from_env_path(raw: &str) -> Self { - Self::new(expand_path(raw)) - } - - pub fn socket_path(&self) -> &Path { - &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)) - } - - pub async fn inbox(&self) -> Result, HerdrError> { - Ok(self.snapshot().await?.inbox()) - } - - pub async fn worktree_list(&self, workspace_id: Option<&str>) -> Result { - let mut params = json!({}); - if let Some(id) = workspace_id { - params["workspace_id"] = json!(id); - } - self.rpc("worktree.list", params).await - } - - pub async fn worktree_create(&self, create: &CreateWorktree) -> Result { - self.rpc("worktree.create", serde_json::to_value(create)?) - .await - } - - pub async fn agent_prompt(&self, target: &str, text: &str) -> Result { - self.rpc("agent.prompt", json!({ "target": target, "text": text })) - .await - } - - pub async fn agent_send_keys( - &self, - target: &str, - keys: &[String], - ) -> Result { - self.rpc("agent.send_keys", json!({ "target": target, "keys": keys })) - .await - } - - pub async fn agent_read(&self, target: &str) -> Result { - self.rpc( - "agent.read", - json!({ "target": target, "source": "recent", "lines": 80 }), - ) - .await - } - - pub async fn agent_get(&self, target: &str) -> Result { - self.rpc("agent.get", json!({ "target": target })).await - } - - pub async fn ping(&self) -> Result { - self.rpc("ping", json!({})).await - } - - pub async fn health(&self) -> bool { - match tokio::time::timeout(Duration::from_secs(2), self.ping()).await { - Ok(Ok(_)) => true, - _ => self.snapshot().await.is_ok(), - } - } - - /// Acknowledgement only. The open stream is [`Self::subscribe_events`]. - /// This drops the connection after the ack. It does not poll. - pub async fn subscribe_ack(&self) -> Result { - let sub = self - .subscribe_events(&[json!({ "type": "pane.agent_status_changed" })]) - .await?; - Ok(sub.ack) - } - - pub async fn rpc(&self, method: &str, params: Value) -> Result { - match self.rpc_socket(method, params.clone()).await { - Ok(value) => Ok(stamp(value, Via::Socket)), - Err(sock_err) if self.cli_fallback(&sock_err) => { - tracing::debug!(error = %sock_err, method, "herdr socket connect failed; trying CLI"); - match cli::rpc_cli(&self.herdr_bin, &self.socket_path, method, params).await { - Ok(value) => Ok(stamp(value, Via::Cli)), - Err(HerdrError::UnsupportedMethod(method)) => { - Err(HerdrError::UnsupportedMethod(method)) - } - Err(cli_err) => Err(HerdrError::Unavailable { - path: self.socket_path.clone(), - socket: sock_err.to_string(), - cli: cli_err.to_string(), - }), - } - } - Err(err) => Err(err), - } - } - - /// CLI only when the path is already a socket inode and connect fails. - /// A missing path or a regular file is a wrong path: return before `rpc_cli`. - fn cli_fallback(&self, err: &HerdrError) -> bool { - match err { - HerdrError::Connect { path, .. } => path_is_socket(path), - _ => false, - } - } - - pub(crate) async fn connect_socket(&self) -> Result { - let connect = UnixStream::connect(&self.socket_path); - match tokio::time::timeout(RPC_TIMEOUT, connect).await { - Ok(Ok(stream)) => Ok(stream), - Ok(Err(source)) => Err(HerdrError::Connect { - path: self.socket_path.clone(), - source, - }), - Err(_) => Err(HerdrError::Connect { - path: self.socket_path.clone(), - source: std::io::Error::new( - std::io::ErrorKind::TimedOut, - "timed out connecting to herdr socket", - ), - }), - } - } - - async fn rpc_socket(&self, method: &str, params: Value) -> Result { - let id = self.alloc_id(); - let request = RpcRequest::new(id.clone(), method, params); - let line = request.to_line()?; - let stream = self.connect_socket().await?; - - let exchange = async { - let mut stream = stream; - stream.write_all(line.as_bytes()).await?; - stream.flush().await?; - let mut reader = BufReader::new(stream); - let response_line = read_limited_line(&mut reader, MAX_HERDR_LINE).await?; - let parsed: RpcResponse = serde_json::from_str(response_line.trim())?; - if let Some(err) = parsed.error { - return Err(HerdrError::from_rpc(err)); - } - Ok(parsed.result.unwrap_or(Value::Null)) - }; - - match tokio::time::timeout(RPC_TIMEOUT, exchange).await { - Ok(result) => result, - Err(_) => Err(HerdrError::Timeout), - } - } -} - -/// An absolute path is kept. A bare name is the first match on `PATH`. -pub(crate) fn resolve_executable(bin: PathBuf) -> PathBuf { - if bin.is_absolute() { - return bin; - } - let Some(path_var) = std::env::var_os("PATH") else { - return bin; - }; - for dir in std::env::split_paths(&path_var) { - let candidate = dir.join(&bin); - if candidate.is_file() { - return candidate; - } - } - bin -} - -fn path_is_socket(path: &Path) -> bool { - #[cfg(unix)] - { - use std::os::unix::fs::FileTypeExt; - std::fs::metadata(path) - .map(|meta| meta.file_type().is_socket()) - .unwrap_or(false) - } - #[cfg(not(unix))] - { - let _ = path; - false - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::line::MAX_HERDR_LINE; - use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; - use tokio::net::UnixListener; - - #[tokio::test] - async fn socket_snapshot_roundtrip() { - let dir = tempfile::tempdir().unwrap(); - let sock = dir.path().join("herdr.sock"); - let listener = UnixListener::bind(&sock).unwrap(); - - let server = tokio::spawn(async move { - let (stream, _) = listener.accept().await.unwrap(); - let mut reader = BufReader::new(stream); - let mut line = String::new(); - reader.read_line(&mut line).await.unwrap(); - let req: Value = serde_json::from_str(&line).unwrap(); - assert_eq!(req["method"], "session.snapshot"); - assert!(req["id"].as_str().unwrap().starts_with("p-")); - let resp = json!({ - "id": req["id"], - "result": { - "type": "session_snapshot", - "agents": [{ - "pane_id": "w1:p1", - "agent": "codex", - "agent_status": "idle", - "workspace_id": "w1", - "tab_id": "w1:t1" - }] - } - }); - let mut stream = reader.into_inner(); - stream - .write_all(format!("{resp}\n").as_bytes()) - .await - .unwrap(); - }); - - let client = HerdrClient::new(&sock); - let snap = client.snapshot().await.unwrap(); - assert_eq!(snap.via, "socket"); - assert_eq!(snap.raw["via"], "socket"); - assert_eq!(snap.agents.len(), 1); - assert_eq!(snap.agents[0].pane_id, "w1:p1"); - assert_eq!(snap.agents[0].status, "idle"); - server.await.unwrap(); - } - - #[tokio::test] - async fn missing_socket_is_transport_error() { - let client = HerdrClient::new("/tmp/pendant-definitely-missing.sock"); - let err = client.rpc_socket("ping", json!({})).await.unwrap_err(); - assert!(err.is_transport()); - } - - /// Wrong path: the socket file is not there. A fake herdr that would - /// succeed must not run. The error is returned before `rpc_cli`. - #[tokio::test] - async fn wrong_socket_path_fails_before_rpc_cli() { - let dir = tempfile::tempdir().unwrap(); - let marker = dir.path().join("cli-was-called"); - let bin = write_fake_herdr(dir.path(), &marker); - let missing = dir.path().join("no-such-herdr.sock"); - let client = HerdrClient::with_herdr_bin(&missing, &bin); - let err = client.rpc("session.snapshot", json!({})).await.unwrap_err(); - assert!(matches!(err, HerdrError::Connect { .. })); - assert!(!marker.exists(), "rpc_cli ran for a wrong socket path"); - } - - /// `via: cli` only when connect to an existing socket inode fails. - #[tokio::test] - async fn cli_fallback_only_when_socket_connect_fails() { - let dir = tempfile::tempdir().unwrap(); - let marker = dir.path().join("cli-was-called"); - let bin = write_fake_herdr(dir.path(), &marker); - let sock = dir.path().join("refused.sock"); - let _inode = std::os::unix::net::UnixDatagram::bind(&sock).unwrap(); - let client = HerdrClient::with_herdr_bin(&sock, &bin); - let value = client.rpc("ping", json!({})).await.unwrap(); - assert_eq!(value["via"], "cli"); - assert_eq!(value["from"], "cli"); - assert!(marker.exists()); - } - - /// A socket that answers an RPC error must not be rewritten by the CLI. - #[tokio::test] - async fn socket_rpc_error_does_not_fall_through_to_cli() { - let dir = tempfile::tempdir().unwrap(); - let marker = dir.path().join("cli-was-called"); - let bin = write_fake_herdr(dir.path(), &marker); - let sock = dir.path().join("herdr.sock"); - let listener = UnixListener::bind(&sock).unwrap(); - let server = tokio::spawn(async move { - let (mut stream, _) = listener.accept().await.unwrap(); - let mut reader = BufReader::new(stream); - let mut line = String::new(); - reader.read_line(&mut line).await.unwrap(); - let req: Value = serde_json::from_str(&line).unwrap(); - let resp = json!({ - "id": req["id"], - "error": { "code": "nope", "message": "socket said no" } - }); - stream = reader.into_inner(); - stream - .write_all(format!("{resp}\n").as_bytes()) - .await - .unwrap(); - }); - let client = HerdrClient::with_herdr_bin(&sock, &bin); - let err = client.rpc("ping", json!({})).await.unwrap_err(); - match err { - HerdrError::Rpc { code, .. } => assert_eq!(code, "nope"), - other => panic!("expected socket RPC error, got {other}"), - } - assert!(!marker.exists()); - server.await.unwrap(); - } - - #[tokio::test] - async fn rpc_reply_longer_than_the_cap_is_an_error() { - let dir = tempfile::tempdir().unwrap(); - let marker = dir.path().join("cli-was-called"); - let bin = write_fake_herdr(dir.path(), &marker); - let sock = dir.path().join("herdr.sock"); - let listener = UnixListener::bind(&sock).unwrap(); - let server = tokio::spawn(async move { - let (stream, _) = listener.accept().await.unwrap(); - let mut reader = BufReader::new(stream); - let mut line = String::new(); - reader.read_line(&mut line).await.unwrap(); - let mut huge = vec![b'x'; MAX_HERDR_LINE + 1]; - huge.push(b'\n'); - let mut stream = reader.into_inner(); - stream.write_all(&huge).await.unwrap(); - }); - 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!(!marker.exists()); - server.await.unwrap(); - } - - fn write_fake_herdr(dir: &std::path::Path, marker: &std::path::Path) -> PathBuf { - let path = dir.join("fake-herdr"); - let marker_q = marker.to_string_lossy().replace('\'', "'\\''"); - let body = format!( - "#!/bin/sh\ntouch '{marker_q}'\nprintf '%s\\n' '{{\"ok\":true,\"from\":\"cli\"}}'\n" - ); - std::fs::write(&path, body).unwrap(); - use std::os::unix::fs::PermissionsExt; - let mut perms = std::fs::metadata(&path).unwrap().permissions(); - perms.set_mode(0o755); - std::fs::set_permissions(&path, perms).unwrap(); - path - } -}