receipts.rs (7514B)
1 #![cfg(all(unix, feature = "native"))] 2 3 #[path = "support/receipt_plans.rs"] 4 mod plans; 5 6 #[path = "support/receipt_client.rs"] 7 mod ordinary; 8 9 #[path = "support/receipt_workflow.rs"] 10 mod workflow; 11 12 #[path = "support/receipt_public_delivery.rs"] 13 mod public_delivery; 14 15 use radroots_domain::{ 16 CommandContextData, CommandDigest, CorrelationId, OperationId, PublicKey, UnixSeconds, 17 }; 18 use radroots_secrets::{ 19 SecretId, SecretRef, 20 envelope::Nonce, 21 file::{FileOpenMode, FileProvider}, 22 id::{BackendKind, KeyVersion}, 23 provider::AccessPolicy, 24 wrapping::SecretMaterial, 25 }; 26 use radroots_storage::{ 27 command::{ 28 AdmissionOutcome, AdmissionRequest, OperationError, OperationJournal, PreparedOperation, 29 }, 30 workspace::{ 31 AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceClock, WorkspaceError, 32 }, 33 }; 34 use radroots_storage_sqlite::workspace::{LocalOutboxConfig, NativeWorkspace, WorkspaceCrypto}; 35 use serde_json::json; 36 use sqlx::{Connection, SqliteConnection}; 37 use std::{ 38 path::PathBuf, 39 sync::{ 40 Arc, Mutex, 41 atomic::{AtomicBool, AtomicU64, Ordering}, 42 mpsc, 43 }, 44 time::Duration, 45 }; 46 47 struct Pause { 48 skip: usize, 49 reached: mpsc::SyncSender<()>, 50 resume: mpsc::Receiver<()>, 51 } 52 struct Clock { 53 now: AtomicU64, 54 live: AtomicBool, 55 pause: Mutex<Option<Pause>>, 56 } 57 impl Clock { 58 fn arm(&self, skip: usize) -> (mpsc::Receiver<()>, mpsc::SyncSender<()>) { 59 let (reached, receive) = mpsc::sync_channel(1); 60 let (resume, released) = mpsc::sync_channel(1); 61 *self.pause.lock().unwrap() = Some(Pause { 62 skip, 63 reached, 64 resume: released, 65 }); 66 (receive, resume) 67 } 68 } 69 impl WorkspaceClock for Clock { 70 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 71 let pause = { 72 let mut selected = self.pause.lock().unwrap(); 73 if let Some(pause) = selected.as_mut() { 74 if pause.skip == 0 { 75 selected.take() 76 } else { 77 pause.skip -= 1; 78 None 79 } 80 } else { 81 None 82 } 83 }; 84 if let Some(pause) = pause { 85 pause 86 .reached 87 .send(()) 88 .map_err(|_| WorkspaceError::Unavailable)?; 89 pause 90 .resume 91 .recv_timeout(Duration::from_secs(10)) 92 .map_err(|_| WorkspaceError::Unavailable)?; 93 } 94 let now = if self.live.load(Ordering::SeqCst) { 95 std::time::SystemTime::now() 96 .duration_since(std::time::UNIX_EPOCH) 97 .map_err(|_| WorkspaceError::Unavailable)? 98 .as_secs() 99 } else { 100 self.now.load(Ordering::SeqCst) 101 }; 102 UnixSeconds::new(now).map_err(|_| WorkspaceError::Unavailable) 103 } 104 } 105 struct Fixture { 106 _root: tempfile::TempDir, 107 path: PathBuf, 108 provider: Arc<FileProvider>, 109 clock: Arc<Clock>, 110 } 111 impl Fixture { 112 fn new() -> Self { 113 let root = tempfile::tempdir().unwrap(); 114 let base = root.path().canonicalize().unwrap(); 115 let provider = Arc::new( 116 FileProvider::open( 117 base.join("vault"), 118 FileOpenMode::CreateNew, 119 SecretMaterial::from_slice(&[0xa5; 32]).unwrap(), 120 ) 121 .unwrap(), 122 ); 123 provider 124 .provision( 125 &reference(), 126 &SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 127 Nonce::new([0x11; 24]), 128 ) 129 .unwrap(); 130 Self { 131 _root: root, 132 path: base.join("outbox"), 133 provider, 134 clock: Arc::new(Clock { 135 now: AtomicU64::new(100), 136 live: AtomicBool::new(false), 137 pause: Mutex::new(None), 138 }), 139 } 140 } 141 fn crypto(&self) -> WorkspaceCrypto { 142 WorkspaceCrypto::new( 143 self.provider.clone(), 144 reference(), 145 SecretMaterial::from_slice(&[0x41; 32]).unwrap(), 146 AccessPolicy::standard(), 147 ) 148 .unwrap() 149 } 150 async fn create( 151 &self, 152 ) -> ( 153 Arc<NativeWorkspace>, 154 AttachmentInput, 155 AttachmentProof, 156 WorkspaceBinding, 157 ) { 158 self.create_with_expiry(200).await 159 } 160 async fn create_with_expiry( 161 &self, 162 expiry: u64, 163 ) -> ( 164 Arc<NativeWorkspace>, 165 AttachmentInput, 166 AttachmentProof, 167 WorkspaceBinding, 168 ) { 169 let (store, input, proof) = NativeWorkspace::initialize_local_outbox( 170 &self.path, 171 LocalOutboxConfig::new( 172 key(), 173 key(), 174 "synthetic-device", 175 UnixSeconds::new(expiry).unwrap(), 176 ) 177 .unwrap(), 178 self.crypto(), 179 self.clock.clone(), 180 ) 181 .await 182 .unwrap(); 183 let binding = store.authenticate(input.clone(), &proof).await.unwrap(); 184 (Arc::new(store), input, proof, binding) 185 } 186 async fn database(&self) -> SqliteConnection { 187 SqliteConnection::connect_with( 188 &sqlx::sqlite::SqliteConnectOptions::new() 189 .filename(self.path.join("execution_v1.sqlite")) 190 .create_if_missing(false), 191 ) 192 .await 193 .unwrap() 194 } 195 async fn reopen(&self, input: AttachmentInput) -> NativeWorkspace { 196 NativeWorkspace::open_existing(&self.path, input, self.crypto(), self.clock.clone()) 197 .await 198 .unwrap() 199 } 200 } 201 fn reference() -> SecretRef { 202 SecretRef::new( 203 SecretId::parse("workspace-key").unwrap(), 204 BackendKind::File, 205 KeyVersion::new(1).unwrap(), 206 ) 207 } 208 fn key() -> PublicKey { 209 PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() 210 } 211 fn copy(proof: &AttachmentProof) -> AttachmentProof { 212 proof.with_secret(|secret| AttachmentProof::from_protected_input(secret).unwrap()) 213 } 214 fn request(binding: &WorkspaceBinding, id: u8, text: &str, correlation: &str) -> AdmissionRequest { 215 request_until(binding, id, text, correlation, 150) 216 } 217 fn request_until( 218 binding: &WorkspaceBinding, 219 id: u8, 220 text: &str, 221 correlation: &str, 222 not_after: u64, 223 ) -> AdmissionRequest { 224 let input = binding.input(); 225 let context = CommandContextData::new( 226 OperationId::from_bytes([id; 32]), 227 binding.actor(), 228 input.workspace_id(), 229 input.authority(), 230 input.route_digest(), 231 None, 232 None, 233 UnixSeconds::new(not_after).unwrap(), 234 Some(CorrelationId::new(correlation).unwrap()), 235 ) 236 .unwrap(); 237 let bytes = serde_json::to_vec(&json!({"type": "inbox.inquire", "context": context, 238 "input": {"thread_id": "66".repeat(32), "peer": key(), "source": null, "text": text}})) 239 .unwrap(); 240 AdmissionRequest::from_protected_wire(binding.clone(), &bytes).unwrap() 241 } 242 fn committed(outcome: AdmissionOutcome) -> PreparedOperation { 243 match outcome { 244 AdmissionOutcome::Committed(result) => result, 245 AdmissionOutcome::Unknown(_) => panic!("unexpected unknown completion"), 246 } 247 } 248 async fn reached(receiver: mpsc::Receiver<()>) { 249 tokio::task::spawn_blocking(move || receiver.recv_timeout(Duration::from_secs(10))) 250 .await 251 .unwrap() 252 .unwrap(); 253 }