lib.rs (12708B)
1 //! Synthetic native host for actual generated-language qualification. 2 #![forbid(unsafe_code)] 3 mod relay; 4 mod signer; 5 6 use radroots::{Client, NativeConfig}; 7 use radroots_domain::{PublicKey, UnixSeconds}; 8 use radroots_ffi::{NativeClient, SessionState, Workspace}; 9 use radroots_secrets::{ 10 SecretId, SecretRef, 11 envelope::Nonce, 12 file::{FileOpenMode, FileProvider}, 13 id::{BackendKind, KeyVersion}, 14 provider::AccessPolicy, 15 wrapping::SecretMaterial, 16 }; 17 use radroots_signing::{ 18 provider::{ProviderError, SignerCallbacks, SignerHandle}, 19 signer::BoxFuture, 20 }; 21 use radroots_storage::{ 22 event::SourceGeneration, 23 workspace::{AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceError}, 24 }; 25 use radroots_storage_sqlite::{ 26 OpenMode, OpenOptions, Paths, 27 workspace::{LocalOutboxConfig, NativeWorkspace, WorkspaceCrypto}, 28 }; 29 use std::{ 30 path::PathBuf, 31 sync::{ 32 Arc, Mutex, 33 atomic::{AtomicU64, Ordering}, 34 }, 35 time::{Duration, SystemTime, UNIX_EPOCH}, 36 }; 37 38 uniffi::setup_scaffolding!(); 39 radroots_ffi::uniffi_reexport_scaffolding!(); 40 41 #[derive(Debug, thiserror::Error, uniffi::Error)] 42 pub enum FixtureError { 43 #[error("native fixture unavailable")] 44 Unavailable, 45 #[error("native fixture still owns an open client")] 46 Busy, 47 } 48 pub(crate) fn now() -> Result<u64, FixtureError> { 49 SystemTime::now() 50 .duration_since(UNIX_EPOCH) 51 .map(|v| v.as_secs()) 52 .map_err(|_| FixtureError::Unavailable) 53 } 54 struct Clock; 55 impl WorkspaceClock for Clock { 56 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 57 UnixSeconds::new(now().map_err(|_| WorkspaceError::Unavailable)?) 58 .map_err(|_| WorkspaceError::Unavailable) 59 } 60 } 61 struct Callbacks { 62 closed: Arc<AtomicU64>, 63 } 64 impl SignerCallbacks for Callbacks { 65 fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 66 Box::pin(async { Ok(()) }) 67 } 68 fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> { 69 self.closed.fetch_add(1, Ordering::SeqCst); 70 Box::pin(async { Ok(()) }) 71 } 72 } 73 74 #[derive(Clone, uniffi::Record)] 75 pub struct Session { 76 pub client: Arc<NativeClient>, 77 pub workspace: Arc<Workspace>, 78 } 79 #[derive(Clone, uniffi::Record)] 80 pub struct Measurements { 81 pub signing_calls: String, 82 pub legacy_signing_calls: String, 83 pub relay_reads: String, 84 pub closed_callbacks: String, 85 pub original_signed_events: Vec<String>, 86 } 87 88 /// Explicit test-host assembly choices; evaluation remains in shared Rust. 89 #[derive(Clone, Copy, uniffi::Enum)] 90 pub enum FixturePolicy { 91 All, 92 Any, 93 Quorum, 94 Required, 95 } 96 97 #[derive(Clone, Copy, uniffi::Enum)] 98 pub enum FixtureRejection { 99 Malformed, 100 Oversized, 101 Foreign, 102 } 103 104 /// Test resources and counters. The shared client owns every command effect. 105 #[derive(uniffi::Object)] 106 pub struct Host { 107 root: PathBuf, 108 provider: Arc<FileProvider>, 109 clock: Arc<Clock>, 110 selected: AttachmentInput, 111 proof: AttachmentProof, 112 signer: Arc<signer::MeasuredSigner>, 113 closed: Arc<AtomicU64>, 114 relay: relay::Relay, 115 initial: Session, 116 clients: Mutex<Vec<Arc<NativeClient>>>, 117 lifecycle: tokio::sync::Mutex<()>, 118 } 119 #[uniffi::export(async_runtime = "tokio")] 120 impl Host { 121 /// Explicit test setup, with real protected grant creation and no commands. 122 #[uniffi::constructor] 123 pub async fn open( 124 seller: bool, 125 unknown_signing: bool, 126 pause_after_signing: bool, 127 ) -> Result<Arc<Self>, FixtureError> { 128 Self::open_with_policy( 129 seller, 130 unknown_signing, 131 pause_after_signing, 132 FixturePolicy::All, 133 ) 134 .await 135 } 136 #[uniffi::constructor] 137 pub async fn open_with_policy( 138 seller: bool, 139 unknown_signing: bool, 140 pause_after_signing: bool, 141 policy: FixturePolicy, 142 ) -> Result<Arc<Self>, FixtureError> { 143 let directory = tempfile::Builder::new() 144 .prefix("radroots_native_binding_fixture_") 145 .tempdir() 146 .map_err(|_| FixtureError::Unavailable)?; 147 // Keep failed or observer-lost fixtures recoverable. Only explicit 148 // cleanup after confirmed client closure removes this owned namespace. 149 let root = directory 150 .keep() 151 .canonicalize() 152 .map_err(|_| FixtureError::Unavailable)?; 153 let provider = Arc::new( 154 FileProvider::open(root.join("vault"), FileOpenMode::CreateNew, material(0xa5)?) 155 .map_err(|_| FixtureError::Unavailable)?, 156 ); 157 provider 158 .provision(&reference()?, &material(0x41)?, Nonce::new([0x11; 24])) 159 .map_err(|_| FixtureError::Unavailable)?; 160 let clock = Arc::new(Clock); 161 let expiry = UnixSeconds::new(now()? + 600).map_err(|_| FixtureError::Unavailable)?; 162 let config = if seller { 163 LocalOutboxConfig::seller(key()?, key()?, "native-binding-fixture", expiry) 164 } else { 165 LocalOutboxConfig::new(key()?, key()?, "native-binding-fixture", expiry) 166 } 167 .map_err(|_| FixtureError::Unavailable)?; 168 let (store, selected, proof) = NativeWorkspace::initialize_local_outbox( 169 &root.join("outbox"), 170 config, 171 crypto(provider.clone())?, 172 clock.clone(), 173 ) 174 .await 175 .map_err(|_| FixtureError::Unavailable)?; 176 let relay = relay::Relay::new(policy).await?; 177 let signer = signer::MeasuredSigner::new(unknown_signing, pause_after_signing); 178 let closed = Arc::new(AtomicU64::new(0)); 179 let initial = open_client( 180 &root.join("cache0"), 181 store, 182 &selected, 183 &proof, 184 signer.clone(), 185 closed.clone(), 186 &relay, 187 ) 188 .await?; 189 Ok(Arc::new(Self { 190 root, 191 provider, 192 clock, 193 selected, 194 proof, 195 signer, 196 closed, 197 relay, 198 clients: Mutex::new(vec![initial.client.clone()]), 199 initial, 200 lifecycle: tokio::sync::Mutex::new(()), 201 })) 202 } 203 pub fn session(&self) -> Session { 204 self.initial.clone() 205 } 206 pub fn unix_seconds(&self) -> Result<String, FixtureError> { 207 now().map(|v| v.to_string()) 208 } 209 pub fn set_accepting(&self, accepting: bool) { 210 self.relay.accepting.store(accepting, Ordering::SeqCst); 211 } 212 pub fn set_unknown_signing(&self, unknown: bool) { 213 self.signer.unknown.store(unknown, Ordering::SeqCst); 214 } 215 pub fn set_rejected_signing(&self, mode: FixtureRejection) { 216 self.signer.rejection.store( 217 match mode { 218 FixtureRejection::Malformed => 1, 219 FixtureRejection::Oversized => 2, 220 FixtureRejection::Foreign => 3, 221 }, 222 Ordering::SeqCst, 223 ); 224 } 225 pub fn release_signer(&self) { 226 self.signer.release(); 227 } 228 pub async fn wait_until_signer_paused(&self) -> Result<(), FixtureError> { 229 tokio::time::timeout(Duration::from_secs(5), async { 230 while !self.signer.paused.load(Ordering::SeqCst) { 231 tokio::time::sleep(Duration::from_millis(5)).await; 232 } 233 }) 234 .await 235 .map_err(|_| FixtureError::Unavailable) 236 } 237 /// Opens the same real namespace only after every previous client closed. 238 /// No start, query, signature or outbox continuation is performed here. 239 pub async fn reopen(&self) -> Result<Session, FixtureError> { 240 let _lifecycle = self.lifecycle.lock().await; 241 let index = { 242 let clients = self.clients.lock().map_err(|_| FixtureError::Unavailable)?; 243 if clients.len() >= 16 || clients.iter().any(|v| v.state() != SessionState::Closed) { 244 return Err(FixtureError::Busy); 245 } 246 clients.len() 247 }; 248 let store = NativeWorkspace::open_existing( 249 &self.root.join("outbox"), 250 self.selected.clone(), 251 crypto(self.provider.clone())?, 252 self.clock.clone(), 253 ) 254 .await 255 .map_err(|_| FixtureError::Unavailable)?; 256 let session = open_client( 257 &self.root.join(format!("cache{index}")), 258 store, 259 &self.selected, 260 &self.proof, 261 self.signer.clone(), 262 self.closed.clone(), 263 &self.relay, 264 ) 265 .await?; 266 self.clients 267 .lock() 268 .map_err(|_| FixtureError::Unavailable)? 269 .push(session.client.clone()); 270 Ok(session) 271 } 272 pub fn measurements(&self) -> Result<Measurements, FixtureError> { 273 Ok(Measurements { 274 signing_calls: self.signer.calls.load(Ordering::SeqCst).to_string(), 275 legacy_signing_calls: self.signer.legacy_calls.load(Ordering::SeqCst).to_string(), 276 relay_reads: self.relay.reads.load(Ordering::SeqCst).to_string(), 277 closed_callbacks: self.closed.load(Ordering::SeqCst).to_string(), 278 original_signed_events: self 279 .relay 280 .events 281 .lock() 282 .map_err(|_| FixtureError::Unavailable)? 283 .clone(), 284 }) 285 } 286 pub async fn cleanup(&self) -> Result<(), FixtureError> { 287 let _lifecycle = self.lifecycle.lock().await; 288 if self 289 .clients 290 .lock() 291 .map_err(|_| FixtureError::Unavailable)? 292 .iter() 293 .any(|v| v.state() != SessionState::Closed) 294 { 295 return Err(FixtureError::Busy); 296 } 297 self.relay.stop().await?; 298 std::fs::remove_dir_all(&self.root).map_err(|_| FixtureError::Unavailable) 299 } 300 } 301 302 async fn open_client( 303 cache: &std::path::Path, 304 store: NativeWorkspace, 305 selected: &AttachmentInput, 306 proof: &AttachmentProof, 307 signer: Arc<signer::MeasuredSigner>, 308 closed: Arc<AtomicU64>, 309 relay: &relay::Relay, 310 ) -> Result<Session, FixtureError> { 311 std::fs::create_dir(cache).map_err(|_| FixtureError::Unavailable)?; 312 let options = OpenOptions::new( 313 Paths::from_directory(cache).map_err(|_| FixtureError::Unavailable)?, 314 OpenMode::Create, 315 ) 316 .with_source_generation( 317 SourceGeneration::new([43; 32]).map_err(|_| FixtureError::Unavailable)?, 318 1, 319 ) 320 .map_err(|_| FixtureError::Unavailable)?; 321 let config = NativeConfig::public_read(options) 322 .with_workspace(store) 323 .with_nostr(relay.config()?, relay.policy.clone()) 324 .map_err(|_| FixtureError::Unavailable)?; 325 let client = Client::open(config) 326 .await 327 .map_err(|_| FixtureError::Unavailable)?; 328 let scope = client 329 .attach( 330 selected.clone(), 331 proof 332 .with_secret(|v| AttachmentProof::from_protected_input(v)) 333 .map_err(|_| FixtureError::Unavailable)?, 334 ) 335 .await 336 .map_err(|_| FixtureError::Unavailable)?; 337 client 338 .attach_signer(SignerHandle::new(signer, Arc::new(Callbacks { closed }))) 339 .await 340 .map_err(|_| FixtureError::Unavailable)?; 341 Ok(Session { 342 client: NativeClient::from_native(client), 343 workspace: Workspace::from_session(scope), 344 }) 345 } 346 fn reference() -> Result<SecretRef, FixtureError> { 347 Ok(SecretRef::new( 348 SecretId::parse("workspace-key").map_err(|_| FixtureError::Unavailable)?, 349 BackendKind::File, 350 KeyVersion::new(1).map_err(|_| FixtureError::Unavailable)?, 351 )) 352 } 353 fn key() -> Result<PublicKey, FixtureError> { 354 PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798") 355 .map_err(|_| FixtureError::Unavailable) 356 } 357 fn material(byte: u8) -> Result<SecretMaterial, FixtureError> { 358 SecretMaterial::from_slice(&[byte; 32]).map_err(|_| FixtureError::Unavailable) 359 } 360 fn crypto(provider: Arc<FileProvider>) -> Result<WorkspaceCrypto, FixtureError> { 361 WorkspaceCrypto::new( 362 provider, 363 reference()?, 364 material(0x41)?, 365 AccessPolicy::standard(), 366 ) 367 .map_err(|_| FixtureError::Unavailable) 368 } 369 370 /// This probe belongs only to this test library, never to product bindings. 371 #[uniffi::export] 372 pub fn fixture_panic_probe() -> String { 373 panic!("synthetic native binding panic probe") 374 } 375 376 /// Exercises unexpected panic conversion on the same Result-shaped boundary 377 /// used by the production command methods. This is fixture-only code. 378 #[uniffi::export] 379 pub fn fixture_result_panic_probe() -> Result<String, FixtureError> { 380 panic!("synthetic native binding Result panic probe") 381 }