stock_authority.rs (21406B)
1 use super::*; 2 use radroots_storage::workspace::WorkspaceScope; 3 use radroots_storage_sqlite::workspace::{SellerStockConfig, StockEnrollment}; 4 use sqlx::Connection; 5 fn enrollment(f: &Fixture) -> StockEnrollment { 6 StockEnrollment::prepare( 7 SellerStockConfig::new( 8 key(), 9 key(), 10 "stock-owner-device", 11 UnixSeconds::new(200).unwrap(), 12 ) 13 .unwrap(), 14 f.clock.as_ref(), 15 ) 16 .unwrap() 17 } 18 async fn create(f: &Fixture, e: &StockEnrollment) -> NativeWorkspace { 19 NativeWorkspace::initialize_seller_stock(&f.path, e, f.crypto(), f.clock.clone()) 20 .await 21 .unwrap() 22 } 23 async fn reopen(f: &Fixture, e: &StockEnrollment) -> NativeWorkspace { 24 NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) 25 .await 26 .unwrap() 27 } 28 // Prepared outside the future under test so observer loss cannot discard a 29 // not-yet-submitted revocation. Production callers retain its actual receipt. 30 struct PreparedRevocation { 31 binding: radroots_storage::workspace::WorkspaceBinding, 32 minimum: radroots_storage::inventory::InventoryCheckpointRef, 33 transaction: radroots_domain::TransactionId, 34 } 35 impl PreparedRevocation { 36 async fn new(store: &NativeWorkspace, e: &StockEnrollment) -> Self { 37 Self { 38 binding: store 39 .authenticate(e.input().clone(), e.proof()) 40 .await 41 .unwrap(), 42 minimum: store 43 .stock_authority(e.input().clone(), e.proof()) 44 .await 45 .unwrap() 46 .inventory_checkpoint() 47 .unwrap(), 48 transaction: radroots_domain::TransactionId::from_bytes([0xAD; 32]), 49 } 50 } 51 async fn run( 52 &self, 53 store: &NativeWorkspace, 54 e: &StockEnrollment, 55 ) -> Result<(), WorkspaceError> { 56 match store 57 .revoke_stock_grant( 58 self.binding.clone(), 59 self.minimum, 60 e.proof(), 61 self.transaction, 62 e.input().grant_id(), 63 ) 64 .await? 65 { 66 radroots_storage_sqlite::workspace::StockGrantOutcome::Committed(_) => Ok(()), 67 radroots_storage_sqlite::workspace::StockGrantOutcome::Unknown(_) => { 68 Err(WorkspaceError::CommitUnknown) 69 } 70 } 71 } 72 } 73 #[tokio::test] 74 async fn explicit_stock_creation_has_retained_receipt_and_reopens() { 75 let f = Fixture::new(); 76 let e = enrollment(&f); 77 assert!(!f.path.exists()); 78 let store = create(&f, &e).await; 79 let binding = store 80 .authenticate(e.input().clone(), e.proof()) 81 .await 82 .unwrap(); 83 assert_eq!(binding.scope(), WorkspaceScope::SellerStockOwner); 84 assert_eq!(binding.actor().role(), radroots_domain::ActorRole::Seller); 85 let receipt = store 86 .stock_authority(e.input().clone(), e.proof()) 87 .await 88 .unwrap(); 89 assert_eq!(receipt.input(), e.input()); 90 assert_eq!(receipt.transaction_id(), e.transaction_id()); 91 assert_eq!(receipt.revocation_generation().get(), 1); 92 assert!(f.path.join("stock_execution_v1.sqlite").exists()); 93 assert!(!f.path.join("execution_v1.sqlite").exists()); 94 store.close().await.unwrap(); 95 let store = reopen(&f, &e).await; 96 assert_eq!( 97 store 98 .stock_authority(e.input().clone(), e.proof()) 99 .await 100 .unwrap(), 101 receipt 102 ); 103 store.close().await.unwrap(); 104 } 105 #[tokio::test] 106 async fn proof_expiry_revocation_and_wrong_selection_are_current() { 107 let f = Fixture::new(); 108 let e = enrollment(&f); 109 let store = create(&f, &e).await; 110 let prepared_revocation = PreparedRevocation::new(&store, &e).await; 111 let wrong = AttachmentProof::from_protected_input(&[0xAB; 32]).unwrap(); 112 assert_eq!( 113 store.authenticate(e.input().clone(), &wrong).await, 114 Err(WorkspaceError::Unauthorized) 115 ); 116 for field in 0..9 { 117 assert!( 118 store 119 .authenticate(altered(e.input(), field), e.proof()) 120 .await 121 .is_err() 122 ); 123 } 124 f.clock.0.store(200, Ordering::SeqCst); 125 assert_eq!( 126 store.authenticate(e.input().clone(), e.proof()).await, 127 Err(WorkspaceError::GrantExpired) 128 ); 129 f.clock.0.store(100, Ordering::SeqCst); 130 prepared_revocation.run(&store, &e).await.unwrap(); 131 assert_eq!( 132 store.authenticate(e.input().clone(), e.proof()).await, 133 Err(WorkspaceError::GrantRevoked) 134 ); 135 store.close().await.unwrap(); 136 let store = reopen(&f, &e).await; 137 assert_eq!( 138 store.authenticate(e.input().clone(), e.proof()).await, 139 Err(WorkspaceError::GrantRevoked) 140 ); 141 store.close().await.unwrap(); 142 } 143 #[tokio::test] 144 async fn stock_and_outbox_factories_never_adopt_or_reset_one_another() { 145 let f = Fixture::new(); 146 let e = enrollment(&f); 147 let store = create(&f, &e).await; 148 assert!(matches!( 149 NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) 150 .await, 151 Err(WorkspaceError::WriterActive) 152 )); 153 store.close().await.unwrap(); 154 let database = f.path.join("stock_execution_v1.sqlite"); 155 let before = std::fs::read(&database).unwrap(); 156 assert!( 157 NativeWorkspace::open_existing(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) 158 .await 159 .is_err() 160 ); 161 assert!( 162 NativeWorkspace::initialize_local_outbox(&f.path, f.config(), f.crypto(), f.clock.clone()) 163 .await 164 .is_err() 165 ); 166 assert!( 167 NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), f.clock.clone()) 168 .await 169 .is_err() 170 ); 171 assert_eq!(std::fs::read(&database).unwrap(), before); 172 let g = Fixture::new(); 173 let (outbox, input, _) = g.create().await; 174 outbox.close().await.unwrap(); 175 let database = g.path.join("execution_v1.sqlite"); 176 let before = std::fs::read(&database).unwrap(); 177 assert!( 178 NativeWorkspace::open_seller_stock(&g.path, input, g.crypto(), g.clock.clone()) 179 .await 180 .is_err() 181 ); 182 assert_eq!(std::fs::read(&database).unwrap(), before); 183 } 184 #[tokio::test] 185 async fn protected_key_and_every_selection_field_refuse_without_writes() { 186 let f = Fixture::new(); 187 let e = enrollment(&f); 188 let store = create(&f, &e).await; 189 store.close().await.unwrap(); 190 let database = f.path.join("stock_execution_v1.sqlite"); 191 let before = std::fs::read(&database).unwrap(); 192 assert!( 193 NativeWorkspace::open_seller_stock( 194 &f.path, 195 e.input().clone(), 196 f.crypto_with([0x99; 32]), 197 f.clock.clone() 198 ) 199 .await 200 .is_err() 201 ); 202 for field in 0..9 { 203 assert!( 204 NativeWorkspace::open_seller_stock( 205 &f.path, 206 altered(e.input(), field), 207 f.crypto(), 208 f.clock.clone() 209 ) 210 .await 211 .is_err() 212 ); 213 } 214 assert_eq!(std::fs::read(&database).unwrap(), before); 215 } 216 #[tokio::test] 217 async fn stock_catalog_and_protected_record_corruption_are_never_repaired() { 218 for sql in [ 219 "PRAGMA user_version=99", 220 "CREATE TABLE unexpected(value INTEGER)", 221 "CREATE TRIGGER foreign_trigger BEFORE INSERT ON stock_grants BEGIN SELECT RAISE(ABORT,'fault'); END", 222 "UPDATE stock_authority SET protected=zeroblob(64)", 223 "UPDATE stock_grants SET protected=zeroblob(64)", 224 "DELETE FROM stock_grants", 225 ] { 226 let f = Fixture::new(); 227 let e = enrollment(&f); 228 let store = create(&f, &e).await; 229 store.close().await.unwrap(); 230 let database = f.path.join("stock_execution_v1.sqlite"); 231 let mut connection = sqlx::SqliteConnection::connect_with( 232 &sqlx::sqlite::SqliteConnectOptions::new().filename(&database), 233 ) 234 .await 235 .unwrap(); 236 sqlx::raw_sql(sql).execute(&mut connection).await.unwrap(); 237 connection.close().await.unwrap(); 238 let before = std::fs::read(&database).unwrap(); 239 assert!( 240 NativeWorkspace::open_seller_stock( 241 &f.path, 242 e.input().clone(), 243 f.crypto(), 244 f.clock.clone() 245 ) 246 .await 247 .is_err(), 248 "{sql}" 249 ); 250 assert_eq!(std::fs::read(&database).unwrap(), before); 251 } 252 } 253 #[tokio::test] 254 async fn cancelled_stock_revocation_drains_then_remains_revoked() { 255 let f = Fixture::new(); 256 let e = enrollment(&f); 257 let clock = Arc::new(PausedClock { 258 state: std::sync::Mutex::new((false, false, false)), 259 changed: std::sync::Condvar::new(), 260 }); 261 let store = NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) 262 .await 263 .unwrap(); 264 let prepared_revocation = PreparedRevocation::new(&store, &e).await; 265 clock.arm(); 266 let mut revoked = Box::pin(prepared_revocation.run(&store, &e)); 267 assert!(futures::poll!(revoked.as_mut()).is_pending()); 268 clock.entered(); 269 drop(revoked); 270 let mut closing = Box::pin(store.close()); 271 assert!(futures::poll!(closing.as_mut()).is_pending()); 272 drop(closing); 273 assert!(matches!( 274 NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) 275 .await, 276 Err(WorkspaceError::WriterActive) 277 )); 278 clock.release(); 279 store.close().await.unwrap(); 280 let store = reopen(&f, &e).await; 281 assert_eq!( 282 store.authenticate(e.input().clone(), e.proof()).await, 283 Err(WorkspaceError::GrantRevoked) 284 ); 285 store.close().await.unwrap(); 286 } 287 288 #[tokio::test] 289 async fn actual_commit_error_fences_the_owner_until_original_state_reopens() { 290 let f = Fixture::new(); 291 let e = enrollment(&f); 292 let store = create(&f, &e).await; 293 let prepared_revocation = PreparedRevocation::new(&store, &e).await; 294 let database = f.path.join("stock_execution_v1.sqlite"); 295 let mut connection = sqlx::SqliteConnection::connect_with( 296 &sqlx::sqlite::SqliteConnectOptions::new().filename(&database), 297 ) 298 .await 299 .unwrap(); 300 sqlx::raw_sql("CREATE TABLE deferred_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_commit AFTER UPDATE ON stock_grants BEGIN INSERT INTO deferred_fault VALUES(2); END").execute(&mut connection).await.unwrap(); 301 assert_eq!( 302 prepared_revocation.run(&store, &e).await, 303 Err(WorkspaceError::CommitUnknown) 304 ); 305 assert_eq!( 306 store.authenticate(e.input().clone(), e.proof()).await, 307 Err(WorkspaceError::RecoveryRequired) 308 ); 309 assert_eq!( 310 store.stock_authority(e.input().clone(), e.proof()).await, 311 Err(WorkspaceError::RecoveryRequired) 312 ); 313 store.close().await.unwrap(); 314 sqlx::raw_sql("DROP TRIGGER fail_commit; DROP TABLE deferred_fault") 315 .execute(&mut connection) 316 .await 317 .unwrap(); 318 connection.close().await.unwrap(); 319 let store = reopen(&f, &e).await; 320 let receipt = store 321 .stock_authority(e.input().clone(), e.proof()) 322 .await 323 .unwrap(); 324 assert_eq!(receipt.transaction_id(), e.transaction_id()); 325 assert_eq!(receipt.revocation_generation().get(), 1); 326 store 327 .authenticate(e.input().clone(), e.proof()) 328 .await 329 .unwrap(); 330 store.close().await.unwrap(); 331 } 332 struct CreationClock { 333 calls: AtomicU64, 334 paused: PausedClock, 335 } 336 impl WorkspaceClock for CreationClock { 337 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 338 if self.calls.fetch_add(1, Ordering::SeqCst) == 1 { 339 self.paused.arm(); 340 self.paused.now() 341 } else { 342 Ok(UnixSeconds::new(100).unwrap()) 343 } 344 } 345 } 346 #[tokio::test] 347 async fn lost_creation_observer_recovers_original_prepared_identity() { 348 let f = Fixture::new(); 349 let e = enrollment(&f); 350 let clock = Arc::new(CreationClock { 351 calls: AtomicU64::new(0), 352 paused: PausedClock { 353 state: std::sync::Mutex::new((false, false, false)), 354 changed: std::sync::Condvar::new(), 355 }, 356 }); 357 let mut creation = Box::pin(NativeWorkspace::initialize_seller_stock( 358 &f.path, 359 &e, 360 f.crypto(), 361 clock.clone(), 362 )); 363 assert!(futures::poll!(creation.as_mut()).is_pending()); 364 clock.paused.entered(); 365 drop(creation); 366 assert!(matches!( 367 NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) 368 .await, 369 Err(WorkspaceError::WriterActive) 370 )); 371 clock.paused.release(); 372 // The first observer owns no handle after cancellation. The worker still 373 // commits and explicitly closes its connection before releasing authority. 374 // Observe the actual persistent writer-ownership transition. Attempt counts 375 // cannot establish completion on a slower scheduler or emulated target. 376 let lock = std::fs::OpenOptions::new() 377 .read(true) 378 .write(true) 379 .open(f.path.join(".stock_execution_v1.lock")) 380 .unwrap(); 381 fs2::FileExt::lock_exclusive(&lock).unwrap(); 382 fs2::FileExt::unlock(&lock).unwrap(); 383 drop(lock); 384 let store = reopen(&f, &e).await; 385 let receipt = store 386 .stock_authority(e.input().clone(), e.proof()) 387 .await 388 .unwrap(); 389 assert_eq!(receipt.transaction_id(), e.transaction_id()); 390 assert_eq!(receipt.input(), e.input()); 391 store.close().await.unwrap(); 392 } 393 394 #[tokio::test] 395 async fn ordinary_journal_is_not_a_stock_transaction_path() { 396 use radroots_storage::command::{OperationError, OperationJournal}; 397 let f = Fixture::new(); 398 let e = enrollment(&f); 399 let store = create(&f, &e).await; 400 let binding = store 401 .authenticate(e.input().clone(), e.proof()) 402 .await 403 .unwrap(); 404 let proof = e 405 .proof() 406 .with_secret(|bytes| AttachmentProof::from_protected_input(bytes)) 407 .unwrap(); 408 assert!(matches!( 409 store 410 .operation( 411 binding, 412 radroots_domain::OperationId::from_bytes([1; 32]), 413 None, 414 proof 415 ) 416 .await, 417 Err(OperationError::RecoveryRequired) 418 )); 419 store.close().await.unwrap(); 420 } 421 422 #[tokio::test] 423 async fn changed_protected_grant_after_decryption_is_refused_before_binding() { 424 let f = Fixture::new(); 425 let e = enrollment(&f); 426 let clock = Arc::new(PausedClock { 427 state: std::sync::Mutex::new((false, false, false)), 428 changed: std::sync::Condvar::new(), 429 }); 430 let store = NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) 431 .await 432 .unwrap(); 433 clock.arm(); 434 let mut auth = Box::pin(store.authenticate(e.input().clone(), e.proof())); 435 assert!(futures::poll!(auth.as_mut()).is_pending()); 436 clock.entered(); 437 let mut connection = sqlx::SqliteConnection::connect_with( 438 &sqlx::sqlite::SqliteConnectOptions::new() 439 .filename(f.path.join("stock_execution_v1.sqlite")), 440 ) 441 .await 442 .unwrap(); 443 sqlx::query("UPDATE stock_grants SET protected=zeroblob(64)") 444 .execute(&mut connection) 445 .await 446 .unwrap(); 447 connection.close().await.unwrap(); 448 clock.release(); 449 assert_eq!(auth.await, Err(WorkspaceError::RecoveryRequired)); 450 store.close().await.unwrap(); 451 } 452 #[tokio::test] 453 async fn statement_failure_rolls_back_both_revocation_records() { 454 let f = Fixture::new(); 455 let e = enrollment(&f); 456 let store = create(&f, &e).await; 457 let prepared_revocation = PreparedRevocation::new(&store, &e).await; 458 let mut connection = sqlx::SqliteConnection::connect_with( 459 &sqlx::sqlite::SqliteConnectOptions::new() 460 .filename(f.path.join("stock_execution_v1.sqlite")), 461 ) 462 .await 463 .unwrap(); 464 sqlx::raw_sql("CREATE TRIGGER fail_revocation BEFORE UPDATE ON stock_grants BEGIN SELECT RAISE(ABORT,'fault'); END").execute(&mut connection).await.unwrap(); 465 assert_eq!( 466 prepared_revocation.run(&store, &e).await, 467 Err(WorkspaceError::StorageFailure) 468 ); 469 let receipt = store 470 .stock_authority(e.input().clone(), e.proof()) 471 .await 472 .unwrap(); 473 assert_eq!(receipt.revocation_generation().get(), 1); 474 sqlx::raw_sql("DROP TRIGGER fail_revocation") 475 .execute(&mut connection) 476 .await 477 .unwrap(); 478 connection.close().await.unwrap(); 479 store.close().await.unwrap(); 480 let store = reopen(&f, &e).await; 481 store 482 .authenticate(e.input().clone(), e.proof()) 483 .await 484 .unwrap(); 485 store.close().await.unwrap(); 486 } 487 488 struct ExpiringCreationClock(AtomicU64); 489 impl WorkspaceClock for ExpiringCreationClock { 490 fn now(&self) -> Result<UnixSeconds, WorkspaceError> { 491 Ok( 492 UnixSeconds::new(if self.0.fetch_add(1, Ordering::SeqCst) < 2 { 493 100 494 } else { 495 200 496 }) 497 .unwrap(), 498 ) 499 } 500 } 501 #[tokio::test] 502 async fn expiry_is_rechecked_inside_actual_creation_transaction() { 503 let f = Fixture::new(); 504 let e = enrollment(&f); 505 assert!(matches!( 506 NativeWorkspace::initialize_seller_stock( 507 &f.path, 508 &e, 509 f.crypto(), 510 Arc::new(ExpiringCreationClock(AtomicU64::new(0))) 511 ) 512 .await, 513 Err(WorkspaceError::GrantExpired) 514 )); 515 let mut connection = sqlx::SqliteConnection::connect_with( 516 &sqlx::sqlite::SqliteConnectOptions::new() 517 .filename(f.path.join("stock_execution_v1.sqlite")) 518 .read_only(true), 519 ) 520 .await 521 .unwrap(); 522 let count: i64 = sqlx::query_scalar("SELECT count(*) FROM sqlite_schema") 523 .fetch_one(&mut connection) 524 .await 525 .unwrap(); 526 assert_eq!(count, 0); 527 connection.close().await.unwrap(); 528 assert!( 529 NativeWorkspace::open_seller_stock(&f.path, e.input().clone(), f.crypto(), f.clock.clone()) 530 .await 531 .is_err() 532 ); 533 } 534 535 #[tokio::test] 536 async fn prepared_enrollment_cannot_create_a_second_authority_namespace() { 537 let f = Fixture::new(); 538 let e = enrollment(&f); 539 let store = create(&f, &e).await; 540 let other = f.path.parent().unwrap().join("second-authority"); 541 assert!(matches!( 542 NativeWorkspace::initialize_seller_stock(&other, &e, f.crypto(), f.clock.clone()).await, 543 Err(WorkspaceError::RecoveryRequired) 544 )); 545 assert!(!other.exists()); 546 store.close().await.unwrap(); 547 assert!(matches!( 548 NativeWorkspace::initialize_seller_stock(&other, &e, f.crypto(), f.clock.clone()).await, 549 Err(WorkspaceError::RecoveryRequired) 550 )); 551 let store = reopen(&f, &e).await; 552 assert_eq!( 553 store 554 .stock_authority(e.input().clone(), e.proof()) 555 .await 556 .unwrap() 557 .transaction_id(), 558 e.transaction_id() 559 ); 560 store.close().await.unwrap(); 561 } 562 563 #[tokio::test] 564 async fn changed_catalog_after_protected_reads_is_refused_before_authenticated_completion() { 565 for revocation in [false, true] { 566 let f = Fixture::new(); 567 let e = enrollment(&f); 568 let clock = Arc::new(PausedClock { 569 state: std::sync::Mutex::new((false, false, false)), 570 changed: std::sync::Condvar::new(), 571 }); 572 let store = 573 NativeWorkspace::initialize_seller_stock(&f.path, &e, f.crypto(), clock.clone()) 574 .await 575 .unwrap(); 576 let prepared_revocation = PreparedRevocation::new(&store, &e).await; 577 clock.arm(); 578 let mut operation: std::pin::Pin< 579 Box<dyn std::future::Future<Output = Result<(), WorkspaceError>> + '_>, 580 > = if revocation { 581 Box::pin(prepared_revocation.run(&store, &e)) 582 } else { 583 Box::pin(async { 584 store 585 .authenticate(e.input().clone(), e.proof()) 586 .await 587 .map(|_| ()) 588 }) 589 }; 590 assert!(futures::poll!(operation.as_mut()).is_pending()); 591 clock.entered(); 592 let mut connection = sqlx::SqliteConnection::connect_with( 593 &sqlx::sqlite::SqliteConnectOptions::new() 594 .filename(f.path.join("stock_execution_v1.sqlite")), 595 ) 596 .await 597 .unwrap(); 598 sqlx::query("PRAGMA user_version=2") 599 .execute(&mut connection) 600 .await 601 .unwrap(); 602 clock.release(); 603 assert_eq!(operation.await, Err(WorkspaceError::RecoveryRequired)); 604 store.close().await.unwrap(); 605 sqlx::query("PRAGMA user_version=17") 606 .execute(&mut connection) 607 .await 608 .unwrap(); 609 connection.close().await.unwrap(); 610 let reopened = reopen(&f, &e).await; 611 assert_eq!( 612 reopened 613 .stock_authority(e.input().clone(), e.proof()) 614 .await 615 .unwrap() 616 .revocation_generation() 617 .get(), 618 1 619 ); 620 reopened.close().await.unwrap(); 621 } 622 }