workspace_plans.rs (17235B)
1 //! Native storage tests use real synthetic NIP-44 data, never host custody. 2 #[path = "workspace_issuance.rs"] 3 mod issuance; 4 use super::*; 5 use nostr::{JsonUtil, nips::nip44}; 6 use radroots_domain::EnvelopeEventId; 7 use radroots_protocol::chat::{ChatRumor, ChatSeal, ChatSigningPlan}; 8 use radroots_protocol::intent::SigningReplay; 9 use radroots_protocol::nip59::CapturedDmRoute; 10 use radroots_storage::command::{BoundSigningPlan, PlanBindingOutcome}; 11 fn keys(last: u8) -> nostr::Keys { 12 let mut bytes = [0; 32]; 13 bytes[31] = last; 14 nostr::Keys::new(nostr::SecretKey::from_slice(&bytes).unwrap()) 15 } 16 fn peer_request(binding: &WorkspaceBinding, id: u8) -> AdmissionRequest { 17 let request = request(binding, id, "protected complete private plan", "original"); 18 let mut value: serde_json::Value = 19 serde_json::from_slice(request.command().protected_wire()).unwrap(); 20 value["input"]["peer"] = keys(2).public_key().to_hex().into(); 21 AdmissionRequest::from_protected_wire(binding.clone(), &serde_json::to_vec(&value).unwrap()) 22 .unwrap() 23 } 24 fn plan( 25 command: &radroots_protocol::command::CapturedChatCommand, 26 created: u64, 27 suffix: &str, 28 ) -> ChatSigningPlan { 29 let rumor = ChatRumor::from_command(command, UnixSeconds::new(created).unwrap()).unwrap(); 30 let author = keys(1); 31 let mut seals = Vec::new(); 32 let mut routes = Vec::new(); 33 for recipient in rumor.recipients() { 34 let target = nostr::PublicKey::from_slice(recipient.as_bytes()).unwrap(); 35 let ciphertext = nip44::encrypt( 36 author.secret_key(), 37 &target, 38 rumor.json(), 39 nip44::Version::V2, 40 ) 41 .unwrap(); 42 seals.push( 43 ChatSeal::new( 44 &rumor, 45 *recipient, 46 UnixSeconds::new(created - 1).unwrap(), 47 &ciphertext, 48 ) 49 .unwrap(), 50 ); 51 let signer = if recipient == &key() { 52 keys(1) 53 } else { 54 keys(2) 55 }; 56 let url = format!("wss://relay.example/{suffix}"); 57 let source = nostr::UnsignedEvent { 58 id: None, 59 pubkey: signer.public_key(), 60 created_at: nostr::Timestamp::from_secs(created - 1), 61 kind: nostr::Kind::Custom(10050), 62 tags: nostr::Tags::from_list(vec![nostr::Tag::parse(["relay", &url]).unwrap()]), 63 content: "public signed route provenance ".repeat(1000), 64 } 65 .sign_with_keys(&signer) 66 .unwrap(); 67 source.verify().unwrap(); 68 routes.push( 69 CapturedDmRoute::from_observed_descriptor( 70 *recipient, 71 EnvelopeEventId::from_bytes(*source.id.as_bytes()), 72 &source.as_json(), 73 &[url], 74 ) 75 .unwrap(), 76 ); 77 } 78 ChatSigningPlan::new( 79 command, 80 UnixSeconds::new(created).unwrap(), 81 seals, 82 routes, 83 SigningReplay::NonReplayable, 84 ) 85 .unwrap() 86 } 87 fn bound(outcome: PlanBindingOutcome) -> BoundSigningPlan { 88 match outcome { 89 PlanBindingOutcome::Committed(bound) => bound, 90 PlanBindingOutcome::Unknown(_) => panic!("fixture must confirm T1"), 91 } 92 } 93 #[tokio::test] 94 async fn complete_private_plan_commits_reopens_and_replays_exact_original_bytes_after_expiry() { 95 let fixture = Fixture::new(); 96 let (store, input, proof, binding) = fixture.create().await; 97 let prepared = committed( 98 store 99 .admit_command_and_hold(peer_request(&binding, 90), copy(&proof)) 100 .await 101 .unwrap(), 102 ); 103 let original = plan(prepared.request().chat_command().unwrap(), 100, "original"); 104 let wire = original.protected_wire().to_vec(); 105 let digest = prepared.identity().command_digest(); 106 let operation = prepared.identity().operation_id(); 107 assert!( 108 store 109 .signing_plan(binding.clone(), operation, digest, copy(&proof)) 110 .await 111 .unwrap() 112 .is_none() 113 ); 114 let retained = bound( 115 store 116 .bind_signing_intents(binding.clone(), (original).into(), copy(&proof)) 117 .await 118 .unwrap(), 119 ); 120 assert_eq!(retained.chat_plan().unwrap().seals().len(), 2); 121 assert_eq!(retained.plan().protected_wire(), wire); 122 assert_eq!( 123 retained.prepared().transaction_id(), 124 prepared.transaction_id() 125 ); 126 let transaction = retained.transaction_id(); 127 let altered = plan(prepared.request().chat_command().unwrap(), 100, "changed"); 128 assert!(matches!( 129 store 130 .bind_signing_intents(binding.clone(), (altered).into(), copy(&proof)) 131 .await, 132 Err(OperationError::IdempotencyConflict) 133 )); 134 fixture.clock.now.store(151, Ordering::SeqCst); 135 let replay = ChatSigningPlan::parse(prepared.request().chat_command().unwrap(), &wire).unwrap(); 136 assert_eq!( 137 bound( 138 store 139 .bind_signing_intents(binding.clone(), (replay).into(), copy(&proof)) 140 .await 141 .unwrap() 142 ) 143 .transaction_id(), 144 transaction 145 ); 146 store.close().await.unwrap(); 147 let database_bytes = std::fs::read(fixture.path.join("execution_v1.sqlite")).unwrap(); 148 assert!( 149 !database_bytes 150 .windows(wire.len()) 151 .any(|bytes| bytes == wire) 152 ); 153 assert!( 154 !database_bytes 155 .windows(31) 156 .any(|bytes| bytes == b"protected complete private plan") 157 ); 158 let reopened = fixture.reopen(input).await; 159 let recovered = reopened 160 .signing_plan(binding.clone(), operation, digest, copy(&proof)) 161 .await 162 .unwrap() 163 .unwrap(); 164 assert_eq!(recovered.plan().protected_wire(), wire); 165 assert_eq!(recovered.transaction_id(), transaction); 166 assert_eq!(recovered.bound_at().get(), 100); 167 assert!(matches!( 168 reopened 169 .signing_plan( 170 binding, 171 operation, 172 CommandDigest::from_bytes([0; 32]), 173 copy(&proof) 174 ) 175 .await, 176 Err(OperationError::IdempotencyConflict) 177 )); 178 reopened.close().await.unwrap(); 179 } 180 #[tokio::test] 181 async fn no_new_plan_commits_after_window_or_after_current_grant_revocation() { 182 for revoked in [false, true] { 183 let fixture = Fixture::new(); 184 let (store, input, proof, binding) = fixture.create().await; 185 let prepared = committed( 186 store 187 .admit_command_and_hold(peer_request(&binding, 91), copy(&proof)) 188 .await 189 .unwrap(), 190 ); 191 let supplied = plan(prepared.request().chat_command().unwrap(), 100, "one"); 192 if revoked { 193 store.revoke(input, &proof).await.unwrap(); 194 } else { 195 fixture.clock.now.store(150, Ordering::SeqCst); 196 } 197 let result = store 198 .bind_signing_intents(binding, (supplied).into(), copy(&proof)) 199 .await; 200 assert!(if revoked { 201 matches!( 202 result, 203 Err(OperationError::Workspace(WorkspaceError::GrantRevoked)) 204 ) 205 } else { 206 matches!(result, Err(OperationError::DeadlineExceeded)) 207 }); 208 store.close().await.unwrap(); 209 let mut database = fixture.database().await; 210 let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans") 211 .fetch_one(&mut database) 212 .await 213 .unwrap(); 214 assert_eq!(count, 0); 215 database.close().await.unwrap(); 216 } 217 } 218 #[tokio::test] 219 async fn admitted_plan_outlives_its_observer_and_byte_budget_refuses_unadmitted_work() { 220 let fixture = Fixture::new(); 221 let (store, _, proof, binding) = fixture.create().await; 222 let mut preparations = Vec::new(); 223 for id in 100..105 { 224 preparations.push(committed( 225 store 226 .admit_command_and_hold(peer_request(&binding, id), copy(&proof)) 227 .await 228 .unwrap(), 229 )); 230 } 231 let (arrived, resume) = fixture.clock.arm(0); 232 let mut first = store.bind_signing_intents( 233 binding.clone(), 234 (plan( 235 preparations[0].request().chat_command().unwrap(), 236 100, 237 "one", 238 )) 239 .into(), 240 copy(&proof), 241 ); 242 assert!(futures::poll!(first.as_mut()).is_pending()); 243 reached(arrived).await; 244 drop(first); 245 let mut accepted = Vec::new(); 246 for prepared in &preparations[1..4] { 247 let mut next = store.bind_signing_intents( 248 binding.clone(), 249 (plan(prepared.request().chat_command().unwrap(), 100, "one")).into(), 250 copy(&proof), 251 ); 252 assert!(futures::poll!(next.as_mut()).is_pending()); 253 accepted.push(next); 254 } 255 assert!(matches!( 256 store 257 .bind_signing_intents( 258 binding.clone(), 259 (plan( 260 preparations[4].request().chat_command().unwrap(), 261 100, 262 "one" 263 )) 264 .into(), 265 copy(&proof) 266 ) 267 .await, 268 Err(OperationError::Workspace(WorkspaceError::Unavailable)) 269 )); 270 resume.send(()).unwrap(); 271 for next in accepted { 272 bound(next.await.unwrap()); 273 } 274 let recovered = store 275 .signing_plan( 276 binding.clone(), 277 preparations[0].identity().operation_id(), 278 preparations[0].identity().command_digest(), 279 copy(&proof), 280 ) 281 .await 282 .unwrap() 283 .unwrap(); 284 assert_eq!( 285 recovered.plan().operation_id(), 286 preparations[0].identity().operation_id() 287 ); 288 assert!( 289 store 290 .signing_plan( 291 binding, 292 preparations[4].identity().operation_id(), 293 preparations[4].identity().command_digest(), 294 copy(&proof) 295 ) 296 .await 297 .unwrap() 298 .is_none() 299 ); 300 store.close().await.unwrap(); 301 } 302 #[tokio::test] 303 async fn expiry_during_protection_and_known_sql_rollback_preserve_unbound_preparation() { 304 for expire in [false, true] { 305 let fixture = Fixture::new(); 306 let (store, _, proof, binding) = fixture.create().await; 307 let prepared = committed( 308 store 309 .admit_command_and_hold(peer_request(&binding, 110), copy(&proof)) 310 .await 311 .unwrap(), 312 ); 313 let supplied = plan(prepared.request().chat_command().unwrap(), 100, "one"); 314 let mut database = fixture.database().await; 315 if !expire { 316 sqlx::raw_sql("CREATE TRIGGER reject_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ABORT,'synthetic storage failure'); END").execute(&mut database).await.unwrap(); 317 } 318 let (arrived, resume) = fixture.clock.arm(1); 319 let mut call = store.bind_signing_intents(binding.clone(), (supplied).into(), copy(&proof)); 320 assert!(futures::poll!(call.as_mut()).is_pending()); 321 reached(arrived).await; 322 if expire { 323 fixture.clock.now.store(150, Ordering::SeqCst); 324 } 325 resume.send(()).unwrap(); 326 let result = call.await; 327 assert!(if expire { 328 matches!(result, Err(OperationError::DeadlineExceeded)) 329 } else { 330 matches!(result, Err(OperationError::StorageFailure)) 331 }); 332 let count: i64 = sqlx::query_scalar("SELECT count(*) FROM signing_plans") 333 .fetch_one(&mut database) 334 .await 335 .unwrap(); 336 assert_eq!(count, 0); 337 if !expire { 338 sqlx::raw_sql("DROP TRIGGER reject_plan") 339 .execute(&mut database) 340 .await 341 .unwrap(); 342 } 343 database.close().await.unwrap(); 344 assert!( 345 store 346 .signing_plan( 347 binding, 348 prepared.identity().operation_id(), 349 prepared.identity().command_digest(), 350 copy(&proof) 351 ) 352 .await 353 .unwrap() 354 .is_none() 355 ); 356 store.close().await.unwrap(); 357 } 358 } 359 360 #[tokio::test] 361 async fn unknown_plan_completion_latches_until_reopen_and_preserves_original_operation_anchor() { 362 let fixture = Fixture::new(); 363 let (store, input, proof, binding) = fixture.create().await; 364 let prepared = committed( 365 store 366 .admit_command_and_hold(peer_request(&binding, 120), copy(&proof)) 367 .await 368 .unwrap(), 369 ); 370 let supplied = plan(prepared.request().chat_command().unwrap(), 100, "one"); 371 let mut database = fixture.database().await; 372 sqlx::raw_sql("CREATE TRIGGER unknown_plan BEFORE INSERT ON signing_plan_parts WHEN NEW.part=2 BEGIN SELECT RAISE(ROLLBACK,'synthetic unknown completion'); END").execute(&mut database).await.unwrap(); 373 let outcome = store 374 .bind_signing_intents(binding.clone(), (supplied).into(), copy(&proof)) 375 .await 376 .unwrap(); 377 match outcome { 378 PlanBindingOutcome::Unknown(anchor) => { 379 assert_eq!(anchor.workspace_id(), prepared.identity().workspace_id()); 380 assert_eq!(anchor.operation_id(), prepared.identity().operation_id()); 381 assert_eq!( 382 anchor.command_digest(), 383 prepared.identity().command_digest() 384 ); 385 assert!(anchor.transaction_id().is_some()); 386 } 387 _ => panic!("uncertain rollback must remain unknown"), 388 } 389 assert!(matches!( 390 store 391 .signing_plan( 392 binding.clone(), 393 prepared.identity().operation_id(), 394 prepared.identity().command_digest(), 395 copy(&proof) 396 ) 397 .await, 398 Err(OperationError::RecoveryRequired) 399 )); 400 sqlx::raw_sql("DROP TRIGGER unknown_plan") 401 .execute(&mut database) 402 .await 403 .unwrap(); 404 database.close().await.unwrap(); 405 store.close().await.unwrap(); 406 let reopened = fixture.reopen(input).await; 407 assert!( 408 reopened 409 .signing_plan( 410 binding, 411 prepared.identity().operation_id(), 412 prepared.identity().command_digest(), 413 copy(&proof) 414 ) 415 .await 416 .unwrap() 417 .is_none() 418 ); 419 reopened.close().await.unwrap(); 420 } 421 #[tokio::test] 422 async fn retained_plan_refuses_index_manifest_and_part_substitution_without_repair() { 423 let fixture = Fixture::new(); 424 let (store, _, proof, binding) = fixture.create().await; 425 let prepared = committed( 426 store 427 .admit_command_and_hold(peer_request(&binding, 121), copy(&proof)) 428 .await 429 .unwrap(), 430 ); 431 bound( 432 store 433 .bind_signing_intents( 434 binding.clone(), 435 (plan(prepared.request().chat_command().unwrap(), 100, "one")).into(), 436 copy(&proof), 437 ) 438 .await 439 .unwrap(), 440 ); 441 let mut database = fixture.database().await; 442 sqlx::query("PRAGMA ignore_check_constraints=ON") 443 .execute(&mut database) 444 .await 445 .unwrap(); 446 let header: (Vec<u8>, Vec<u8>, i64, i64, Vec<u8>) = sqlx::query_as( 447 "SELECT plan_digest,transaction_id,part_count,byte_count,protected FROM signing_plans", 448 ) 449 .fetch_one(&mut database) 450 .await 451 .unwrap(); 452 let part: Vec<u8> = sqlx::query_scalar("SELECT protected FROM signing_plan_parts WHERE part=1") 453 .fetch_one(&mut database) 454 .await 455 .unwrap(); 456 for change in [ 457 "UPDATE signing_plans SET plan_digest=zeroblob(32)", 458 "UPDATE signing_plans SET transaction_id=zeroblob(32)", 459 "UPDATE signing_plans SET part_count=25", 460 "UPDATE signing_plans SET byte_count=393217", 461 "UPDATE signing_plans SET protected=zeroblob(262145)", 462 "UPDATE signing_plan_parts SET protected=zeroblob(262145) WHERE part=1", 463 "UPDATE signing_plan_parts SET protected=zeroblob(64) WHERE part=1", 464 ] { 465 sqlx::query("UPDATE signing_plans SET plan_digest=?,transaction_id=?,part_count=?,byte_count=?,protected=?").bind(&header.0).bind(&header.1).bind(header.2).bind(header.3).bind(&header.4).execute(&mut database).await.unwrap(); 466 sqlx::query("UPDATE signing_plan_parts SET protected=? WHERE part=1") 467 .bind(&part) 468 .execute(&mut database) 469 .await 470 .unwrap(); 471 sqlx::query(change).execute(&mut database).await.unwrap(); 472 let error = store 473 .signing_plan( 474 binding.clone(), 475 prepared.identity().operation_id(), 476 prepared.identity().command_digest(), 477 copy(&proof), 478 ) 479 .await 480 .unwrap_err(); 481 assert_eq!(error.code(), "recovery_required", "{change}: {error:?}"); 482 } 483 database.close().await.unwrap(); 484 store.close().await.unwrap(); 485 }