lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

stock_grants.rs (26395B)


      1 use super::*;
      2 use radroots_domain::TransactionId;
      3 use radroots_storage::workspace::seller_stock::{
      4     SellerAuthoritySelection, StockAction, StockGrantScope, StockResources,
      5 };
      6 use radroots_storage_sqlite::workspace::{StockGrantEnrollment, StockGrantOutcome};
      7 
      8 #[tokio::test]
      9 async fn cancelled_enrollment_drains_and_recovers_the_original_grant_transaction() {
     10     let f = Fixture::new();
     11     let enrollment = StockEnrollment::prepare(
     12         SellerStockConfig::new(key(), key(), "owner", UnixSeconds::new(200).unwrap()).unwrap(),
     13         f.clock.as_ref(),
     14     )
     15     .unwrap();
     16     let clock = Arc::new(PausedClock {
     17         state: std::sync::Mutex::new((false, false, false)),
     18         changed: std::sync::Condvar::new(),
     19     });
     20     let store =
     21         NativeWorkspace::initialize_seller_stock(&f.path, &enrollment, f.crypto(), clock.clone())
     22             .await
     23             .unwrap();
     24     let owner = store
     25         .authenticate(enrollment.input().clone(), enrollment.proof())
     26         .await
     27         .unwrap();
     28     let current = minimum(&owner);
     29     let delegated = StockGrantEnrollment::prepare(
     30         &SellerAuthoritySelection::from_attachment(owner.input()),
     31         "cancelled-device".into(),
     32         UnixSeconds::new(200).unwrap(),
     33         StockGrantScope::full_inventory(),
     34     )
     35     .unwrap();
     36     clock.arm();
     37     let mut operation =
     38         Box::pin(store.enroll_stock_grant(owner.clone(), current, enrollment.proof(), &delegated));
     39     assert!(futures::poll!(operation.as_mut()).is_pending());
     40     clock.entered();
     41     drop(operation);
     42     let mut closing = Box::pin(store.close());
     43     assert!(futures::poll!(closing.as_mut()).is_pending());
     44     drop(closing);
     45     assert!(matches!(
     46         NativeWorkspace::open_seller_stock(
     47             &f.path,
     48             enrollment.input().clone(),
     49             f.crypto(),
     50             f.clock.clone()
     51         )
     52         .await,
     53         Err(WorkspaceError::WriterActive)
     54     ));
     55     clock.release();
     56     store.close().await.unwrap();
     57     let reopened = NativeWorkspace::open_seller_stock(
     58         &f.path,
     59         delegated.input().clone(),
     60         f.crypto(),
     61         f.clock.clone(),
     62     )
     63     .await
     64     .unwrap();
     65     assert!(
     66         reopened
     67             .authenticate(delegated.input().clone(), delegated.proof())
     68             .await
     69             .is_ok()
     70     );
     71     let original = grant_committed(
     72         reopened
     73             .enroll_stock_grant(owner, current, enrollment.proof(), &delegated)
     74             .await
     75             .unwrap(),
     76     );
     77     assert_eq!(original.transaction_id(), delegated.transaction_id());
     78     reopened.close().await.unwrap();
     79 }
     80 
     81 #[tokio::test]
     82 async fn grant_capacity_is_explicit_and_revoked_credentials_are_never_evicted_to_admit_new_grants()
     83 {
     84     let f = Fixture::new();
     85     let (store, enrollment, owner) = create(&f).await;
     86     let namespace = SellerAuthoritySelection::from_attachment(owner.input());
     87     let mut current = minimum(&owner);
     88     let mut first = None;
     89     for index in 0..63 {
     90         let grant = StockGrantEnrollment::prepare(
     91             &namespace,
     92             format!("bounded-device-{index}"),
     93             UnixSeconds::new(200).unwrap(),
     94             StockGrantScope::full_inventory(),
     95         )
     96         .unwrap();
     97         let receipt = grant_committed(
     98             store
     99                 .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &grant)
    100                 .await
    101                 .unwrap(),
    102         );
    103         current = current.with_authorization(receipt.authorization());
    104         if index == 0 {
    105             first = Some(grant);
    106         }
    107     }
    108     let first = first.unwrap();
    109     let receipt = grant_committed(
    110         store
    111             .revoke_stock_grant(
    112                 owner.clone(),
    113                 current,
    114                 enrollment.proof(),
    115                 TransactionId::from_bytes([111; 32]),
    116                 first.input().grant_id(),
    117             )
    118             .await
    119             .unwrap(),
    120     );
    121     current = current.with_authorization(receipt.authorization());
    122     let over = StockGrantEnrollment::prepare(
    123         &namespace,
    124         "over-capacity".into(),
    125         UnixSeconds::new(200).unwrap(),
    126         StockGrantScope::full_inventory(),
    127     )
    128     .unwrap();
    129     assert_eq!(
    130         store
    131             .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &over)
    132             .await,
    133         Err(WorkspaceError::Capacity)
    134     );
    135     assert_eq!(
    136         store
    137             .authenticate(first.input().clone(), first.proof())
    138             .await,
    139         Err(WorkspaceError::GrantRevoked)
    140     );
    141     assert_eq!(
    142         checkpoint(&store, owner.input(), enrollment.proof()).await,
    143         current
    144     );
    145     store.close().await.unwrap();
    146 }
    147 
    148 struct RegressingClock {
    149     calls: std::sync::atomic::AtomicUsize,
    150     regress_at: std::sync::atomic::AtomicUsize,
    151 }
    152 impl RegressingClock {
    153     fn new() -> Self {
    154         Self {
    155             calls: std::sync::atomic::AtomicUsize::new(0),
    156             regress_at: std::sync::atomic::AtomicUsize::new(usize::MAX),
    157         }
    158     }
    159     fn arm(&self, at: usize) {
    160         self.calls.store(0, Ordering::SeqCst);
    161         self.regress_at.store(at, Ordering::SeqCst);
    162     }
    163 }
    164 impl WorkspaceClock for RegressingClock {
    165     fn now(&self) -> Result<UnixSeconds, WorkspaceError> {
    166         let count = self.calls.fetch_add(1, Ordering::SeqCst) + 1;
    167         Ok(
    168             UnixSeconds::new(if count >= self.regress_at.load(Ordering::SeqCst) {
    169                 50
    170             } else {
    171                 100
    172             })
    173             .unwrap(),
    174         )
    175     }
    176 }
    177 #[tokio::test]
    178 async fn current_grant_clock_regression_refuses_fresh_and_retained_administrative_completion() {
    179     for regress_at in [1, 3] {
    180         let f = Fixture::new();
    181         let clock = Arc::new(RegressingClock::new());
    182         let enrollment = StockEnrollment::prepare(
    183             SellerStockConfig::new(key(), key(), "owner", UnixSeconds::new(200).unwrap()).unwrap(),
    184             clock.as_ref(),
    185         )
    186         .unwrap();
    187         let store = NativeWorkspace::initialize_seller_stock(
    188             &f.path,
    189             &enrollment,
    190             f.crypto(),
    191             clock.clone(),
    192         )
    193         .await
    194         .unwrap();
    195         let owner = store
    196             .authenticate(enrollment.input().clone(), enrollment.proof())
    197             .await
    198             .unwrap();
    199         let current = minimum(&owner);
    200         let grant = StockGrantEnrollment::prepare(
    201             &SellerAuthoritySelection::from_attachment(owner.input()),
    202             "clock-device".into(),
    203             UnixSeconds::new(200).unwrap(),
    204             StockGrantScope::full_inventory(),
    205         )
    206         .unwrap();
    207         clock.arm(regress_at);
    208         assert_eq!(
    209             store
    210                 .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &grant)
    211                 .await,
    212             Err(WorkspaceError::Unavailable)
    213         );
    214         clock.arm(usize::MAX);
    215         assert_eq!(
    216             checkpoint(&store, owner.input(), enrollment.proof()).await,
    217             current
    218         );
    219         let first = grant_committed(
    220             store
    221                 .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &grant)
    222                 .await
    223                 .unwrap(),
    224         );
    225         clock.arm(2);
    226         assert_eq!(
    227             store
    228                 .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &grant)
    229                 .await,
    230             Err(WorkspaceError::Unavailable)
    231         );
    232         clock.arm(usize::MAX);
    233         assert_eq!(
    234             grant_committed(
    235                 store
    236                     .enroll_stock_grant(owner, current, enrollment.proof(), &grant)
    237                     .await
    238                     .unwrap()
    239             ),
    240             first
    241         );
    242         store.close().await.unwrap();
    243     }
    244 }
    245 
    246 fn grant_committed(
    247     value: StockGrantOutcome,
    248 ) -> radroots_storage_sqlite::workspace::StockGrantReceipt {
    249     match value {
    250         StockGrantOutcome::Committed(v) => v,
    251         StockGrantOutcome::Unknown(_) => panic!("expected confirmed grant mutation"),
    252     }
    253 }
    254 async fn checkpoint(
    255     store: &NativeWorkspace,
    256     input: &radroots_storage::workspace::AttachmentInput,
    257     proof: &AttachmentProof,
    258 ) -> InventoryCheckpointRef {
    259     store
    260         .stock_authority(input.clone(), proof)
    261         .await
    262         .unwrap()
    263         .inventory_checkpoint()
    264         .unwrap()
    265 }
    266 #[tokio::test]
    267 async fn scoped_grants_execute_and_replay_original_inventory_without_reallocation_and_revoke_current_access()
    268  {
    269     let f = Fixture::new();
    270     let (store, enrollment, owner) = create(&f).await;
    271     let initial = minimum(&owner);
    272     let original = request(&owner, 91, 92, "scoped original");
    273     let digest = original.command().digest();
    274     let captured = original.command().protected_wire().to_vec();
    275     let effect = committed(
    276         store
    277             .execute_inventory(original, proof(enrollment.proof()))
    278             .await
    279             .unwrap(),
    280     );
    281     let namespace = SellerAuthoritySelection::from_attachment(owner.input());
    282     let delegated = StockGrantEnrollment::prepare(
    283         &namespace,
    284         "scoped-device".to_owned(),
    285         UnixSeconds::new(200).unwrap(),
    286         StockGrantScope::new(
    287             StockResources::pools(vec![PoolId::from_bytes([92; 32])]).unwrap(),
    288             vec![
    289                 StockAction::ReadPools,
    290                 StockAction::ReadOperations,
    291                 StockAction::AddStock,
    292             ],
    293         )
    294         .unwrap(),
    295     )
    296     .unwrap();
    297     let added = grant_committed(
    298         store
    299             .enroll_stock_grant(
    300                 owner.clone(),
    301                 effect.checkpoint(),
    302                 enrollment.proof(),
    303                 &delegated,
    304             )
    305             .await
    306             .unwrap(),
    307     );
    308     assert_eq!(added.transaction_id(), delegated.transaction_id());
    309     assert_eq!(added.authorization().generation().get(), 2);
    310     let current = checkpoint(&store, owner.input(), enrollment.proof()).await;
    311     assert_eq!(current.authorization(), Some(added.authorization()));
    312     let device = store
    313         .authenticate(delegated.input().clone(), delegated.proof())
    314         .await
    315         .unwrap();
    316     // Old acknowledged grant state cannot be reused after mutation.
    317     assert_eq!(
    318         store
    319             .pool(
    320                 owner.clone(),
    321                 initial,
    322                 PoolId::from_bytes([92; 32]),
    323                 proof(enrollment.proof())
    324             )
    325             .await,
    326         Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint))
    327     );
    328     assert!(
    329         store
    330             .pool(
    331                 device.clone(),
    332                 current,
    333                 PoolId::from_bytes([92; 32]),
    334                 proof(delegated.proof())
    335             )
    336             .await
    337             .unwrap()
    338             .is_some()
    339     );
    340     assert_eq!(
    341         store
    342             .pool(
    343                 device.clone(),
    344                 current,
    345                 PoolId::from_bytes([93; 32]),
    346                 proof(delegated.proof())
    347             )
    348             .await,
    349         Err(OperationError::Unauthorized)
    350     );
    351     let retained = store
    352         .inventory_operation(
    353             device.clone(),
    354             current,
    355             OperationId::from_bytes([91; 32]),
    356             Some(digest),
    357             proof(delegated.proof()),
    358         )
    359         .await
    360         .unwrap()
    361         .unwrap();
    362     assert_eq!(retained, effect);
    363     let replay =
    364         InventoryRequest::replay_from_protected_wire(device.clone(), current, &captured).unwrap();
    365     assert!(InventoryRequest::from_protected_wire(device.clone(), current, &captured).is_err());
    366     let unseen = request(&owner, 99, 92, "missing retained command");
    367     let unseen = InventoryRequest::replay_from_protected_wire(
    368         device.clone(),
    369         current,
    370         unseen.command().protected_wire(),
    371     )
    372     .unwrap();
    373     assert_eq!(
    374         store
    375             .execute_inventory(unseen, proof(delegated.proof()))
    376             .await,
    377         Err(OperationError::RecoveryRequired)
    378     );
    379     assert_eq!(
    380         committed(
    381             store
    382                 .execute_inventory(replay, proof(delegated.proof()))
    383                 .await
    384                 .unwrap()
    385         ),
    386         effect
    387     );
    388     // Reusing the same operation with another grant creates a different exact
    389     // command digest and cannot acquire a second stock effect.
    390     let conflict = request(&device, 91, 92, "scoped original");
    391     let conflict = InventoryRequest::from_protected_wire(
    392         device.clone(),
    393         current,
    394         conflict.command().protected_wire(),
    395     )
    396     .unwrap();
    397     assert_eq!(
    398         store
    399             .execute_inventory(conflict, proof(delegated.proof()))
    400             .await,
    401         Err(OperationError::IdempotencyConflict)
    402     );
    403     let forbidden = request(&device, 94, 92, "cannot create");
    404     let forbidden = InventoryRequest::from_protected_wire(
    405         device.clone(),
    406         current,
    407         forbidden.command().protected_wire(),
    408     )
    409     .unwrap();
    410     assert_eq!(
    411         store
    412             .execute_inventory(forbidden, proof(delegated.proof()))
    413             .await,
    414         Err(OperationError::Unauthorized)
    415     );
    416     let another = StockGrantEnrollment::prepare(
    417         &namespace,
    418         "no-admin".into(),
    419         UnixSeconds::new(200).unwrap(),
    420         StockGrantScope::full_inventory(),
    421     )
    422     .unwrap();
    423     assert_eq!(
    424         store
    425             .enroll_stock_grant(device.clone(), current, delegated.proof(), &another)
    426             .await,
    427         Err(WorkspaceError::Unauthorized)
    428     );
    429     let context = CommandContextData::new(
    430         OperationId::from_bytes([96; 32]),
    431         device.actor(),
    432         device.input().workspace_id(),
    433         device.input().authority(),
    434         device.input().route_digest(),
    435         None,
    436         None,
    437         UnixSeconds::new(150).unwrap(),
    438         None,
    439     )
    440     .unwrap();
    441     let mut wire = serde_json::json!({"type":"stock.adjust","context":context,"input":{"pool_id":PoolId::from_bytes([92;32]),"expected_version":"1","direction":"add","amount":"0.125","reason":"delegated harvest"}});
    442     let add = InventoryRequest::from_protected_wire(
    443         device.clone(),
    444         current,
    445         &serde_json::to_vec(&wire).unwrap(),
    446     )
    447     .unwrap();
    448     let added_stock = committed(
    449         store
    450             .execute_inventory(add, proof(delegated.proof()))
    451             .await
    452             .unwrap(),
    453     );
    454     assert_eq!(
    455         added_stock.pool().balances().physical().available.get(),
    456         375
    457     );
    458     wire["context"]["operation_id"] = serde_json::json!(OperationId::from_bytes([97; 32]));
    459     wire["input"]["expected_version"] = serde_json::json!("2");
    460     wire["input"]["direction"] = serde_json::json!("remove");
    461     let remove = InventoryRequest::from_protected_wire(
    462         device.clone(),
    463         added_stock.checkpoint(),
    464         &serde_json::to_vec(&wire).unwrap(),
    465     )
    466     .unwrap();
    467     assert_eq!(
    468         store
    469             .execute_inventory(remove, proof(delegated.proof()))
    470             .await,
    471         Err(OperationError::Unauthorized)
    472     );
    473     let current = added_stock.checkpoint();
    474     let revoked = grant_committed(
    475         store
    476             .revoke_stock_grant(
    477                 owner.clone(),
    478                 current,
    479                 enrollment.proof(),
    480                 TransactionId::from_bytes([95; 32]),
    481                 delegated.input().grant_id(),
    482             )
    483             .await
    484             .unwrap(),
    485     );
    486     assert_eq!(revoked.authorization().generation().get(), 3);
    487     assert_eq!(
    488         store
    489             .authenticate(delegated.input().clone(), delegated.proof())
    490             .await,
    491         Err(WorkspaceError::GrantRevoked)
    492     );
    493     let next = current.with_authorization(revoked.authorization());
    494     assert_eq!(
    495         store
    496             .inventory_operation(
    497                 device,
    498                 next,
    499                 OperationId::from_bytes([91; 32]),
    500                 Some(digest),
    501                 proof(delegated.proof())
    502             )
    503             .await,
    504         Err(OperationError::Workspace(WorkspaceError::GrantRevoked))
    505     );
    506     let mut connection = database(&f).await;
    507     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_operations")
    508         .fetch_one(&mut connection)
    509         .await
    510         .unwrap();
    511     assert_eq!(count, 2);
    512     let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_grant_changes")
    513         .fetch_one(&mut connection)
    514         .await
    515         .unwrap();
    516     assert_eq!(count, 2);
    517     connection.close().await.unwrap();
    518     store.close().await.unwrap();
    519     let reopened = NativeWorkspace::open_seller_stock(
    520         &f.path,
    521         delegated.input().clone(),
    522         f.crypto(),
    523         f.clock.clone(),
    524     )
    525     .await
    526     .unwrap();
    527     assert_eq!(
    528         reopened
    529             .authenticate(delegated.input().clone(), delegated.proof())
    530             .await,
    531         Err(WorkspaceError::GrantRevoked)
    532     );
    533     let owner = reopened
    534         .authenticate(enrollment.input().clone(), enrollment.proof())
    535         .await
    536         .unwrap();
    537     assert!(
    538         reopened
    539             .pool(
    540                 owner,
    541                 next,
    542                 PoolId::from_bytes([92; 32]),
    543                 proof(enrollment.proof())
    544             )
    545             .await
    546             .unwrap()
    547             .is_some()
    548     );
    549     reopened.close().await.unwrap();
    550 }
    551 
    552 #[tokio::test]
    553 async fn acknowledged_revocation_refuses_a_complete_older_database_and_partial_grant_restore() {
    554     let f = Fixture::new();
    555     let (store, enrollment, owner) = create(&f).await;
    556     let pool = committed(
    557         store
    558             .execute_inventory(
    559                 request(&owner, 101, 102, "restore stock"),
    560                 proof(enrollment.proof()),
    561             )
    562             .await
    563             .unwrap(),
    564     );
    565     let delegated = StockGrantEnrollment::prepare(
    566         &SellerAuthoritySelection::from_attachment(owner.input()),
    567         "restore-device".into(),
    568         UnixSeconds::new(200).unwrap(),
    569         StockGrantScope::full_inventory(),
    570     )
    571     .unwrap();
    572     grant_committed(
    573         store
    574             .enroll_stock_grant(
    575                 owner.clone(),
    576                 pool.checkpoint(),
    577                 enrollment.proof(),
    578                 &delegated,
    579             )
    580             .await
    581             .unwrap(),
    582     );
    583     let before = checkpoint(&store, owner.input(), enrollment.proof()).await;
    584     store.close().await.unwrap();
    585     let original = f.path.join("stock_execution_v1.sqlite");
    586     let backup = f
    587         .path
    588         .parent()
    589         .unwrap()
    590         .join("synthetic-before-revocation.sqlite");
    591     std::fs::copy(&original, &backup).unwrap();
    592     let store = NativeWorkspace::open_seller_stock(
    593         &f.path,
    594         enrollment.input().clone(),
    595         f.crypto(),
    596         f.clock.clone(),
    597     )
    598     .await
    599     .unwrap();
    600     let owner = store
    601         .authenticate(enrollment.input().clone(), enrollment.proof())
    602         .await
    603         .unwrap();
    604     let mut connection = database(&f).await;
    605     let old_grant: Vec<u8> =
    606         sqlx::query_scalar("SELECT protected FROM stock_grants WHERE grant_id=?")
    607             .bind(delegated.input().grant_id().as_bytes().as_slice())
    608             .fetch_one(&mut connection)
    609             .await
    610             .unwrap();
    611     let receipt = grant_committed(
    612         store
    613             .revoke_stock_grant(
    614                 owner.clone(),
    615                 before,
    616                 enrollment.proof(),
    617                 TransactionId::from_bytes([103; 32]),
    618                 delegated.input().grant_id(),
    619             )
    620             .await
    621             .unwrap(),
    622     );
    623     let minimum = before.with_authorization(receipt.authorization());
    624     // Restoring just the old encrypted grant is caught by the protected root's
    625     // grant-set digest, even with a syntactically valid authentic envelope.
    626     sqlx::query("UPDATE stock_grants SET protected=? WHERE grant_id=?")
    627         .bind(old_grant)
    628         .bind(delegated.input().grant_id().as_bytes().as_slice())
    629         .execute(&mut connection)
    630         .await
    631         .unwrap();
    632     assert_eq!(
    633         store
    634             .authenticate(enrollment.input().clone(), enrollment.proof())
    635             .await,
    636         Err(WorkspaceError::RecoveryRequired)
    637     );
    638     connection.close().await.unwrap();
    639     store.close().await.unwrap();
    640     std::fs::copy(&backup, &original).unwrap();
    641     let restored = NativeWorkspace::open_seller_stock(
    642         &f.path,
    643         enrollment.input().clone(),
    644         f.crypto(),
    645         f.clock.clone(),
    646     )
    647     .await
    648     .unwrap();
    649     let binding = restored
    650         .authenticate(enrollment.input().clone(), enrollment.proof())
    651         .await
    652         .unwrap();
    653     assert_eq!(
    654         restored
    655             .pool(
    656                 binding,
    657                 minimum,
    658                 PoolId::from_bytes([102; 32]),
    659                 proof(enrollment.proof())
    660             )
    661             .await,
    662         Err(OperationError::Workspace(WorkspaceError::StaleCheckpoint))
    663     );
    664     restored.close().await.unwrap();
    665 }
    666 
    667 #[tokio::test]
    668 async fn grant_mutation_faults_roll_back_all_rows_and_original_transaction_replays() {
    669     for table in ["stock_grants", "stock_grant_changes", "stock_authority"] {
    670         let f = Fixture::new();
    671         let (store, enrollment, owner) = create(&f).await;
    672         let current = minimum(&owner);
    673         let delegated = StockGrantEnrollment::prepare(
    674             &SellerAuthoritySelection::from_attachment(owner.input()),
    675             "fault-device".into(),
    676             UnixSeconds::new(200).unwrap(),
    677             StockGrantScope::full_inventory(),
    678         )
    679         .unwrap();
    680         let mut connection = database(&f).await;
    681         let sql = match table {
    682             "stock_grants" => {
    683                 "CREATE TRIGGER grant_fault BEFORE INSERT ON stock_grants BEGIN SELECT RAISE(ABORT,'synthetic grant failure'); END"
    684             }
    685             "stock_grant_changes" => {
    686                 "CREATE TRIGGER grant_fault BEFORE INSERT ON stock_grant_changes BEGIN SELECT RAISE(ABORT,'synthetic grant failure'); END"
    687             }
    688             "stock_authority" => {
    689                 "CREATE TRIGGER grant_fault BEFORE UPDATE ON stock_authority BEGIN SELECT RAISE(ABORT,'synthetic grant failure'); END"
    690             }
    691             _ => unreachable!(),
    692         };
    693         sqlx::raw_sql(sql).execute(&mut connection).await.unwrap();
    694         assert_eq!(
    695             store
    696                 .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &delegated)
    697                 .await,
    698             Err(WorkspaceError::StorageFailure)
    699         );
    700         let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_grants")
    701             .fetch_one(&mut connection)
    702             .await
    703             .unwrap();
    704         assert_eq!(count, 1);
    705         let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_grant_changes")
    706             .fetch_one(&mut connection)
    707             .await
    708             .unwrap();
    709         assert_eq!(count, 0);
    710         assert_eq!(
    711             checkpoint(&store, owner.input(), enrollment.proof()).await,
    712             current
    713         );
    714         sqlx::raw_sql("DROP TRIGGER grant_fault")
    715             .execute(&mut connection)
    716             .await
    717             .unwrap();
    718         let first = grant_committed(
    719             store
    720                 .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &delegated)
    721                 .await
    722                 .unwrap(),
    723         );
    724         // Exact original identity and pre-state recover a successful attempt,
    725         // including a lost response, without installing another grant or row.
    726         let second = grant_committed(
    727             store
    728                 .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &delegated)
    729                 .await
    730                 .unwrap(),
    731         );
    732         assert_eq!(first, second);
    733         assert_eq!(first.transaction_id(), delegated.transaction_id());
    734         let count: i64 = sqlx::query_scalar("SELECT count(*) FROM stock_grant_changes")
    735             .fetch_one(&mut connection)
    736             .await
    737             .unwrap();
    738         assert_eq!(count, 1);
    739         connection.close().await.unwrap();
    740         store.close().await.unwrap();
    741     }
    742 }
    743 
    744 #[tokio::test]
    745 async fn unknown_grant_commit_fences_the_worker_and_reopen_recovers_the_original_prepared_identity()
    746 {
    747     let f = Fixture::new();
    748     let (store, enrollment, owner) = create(&f).await;
    749     let current = minimum(&owner);
    750     let delegated = StockGrantEnrollment::prepare(
    751         &SellerAuthoritySelection::from_attachment(owner.input()),
    752         "unknown-device".into(),
    753         UnixSeconds::new(200).unwrap(),
    754         StockGrantScope::full_inventory(),
    755     )
    756     .unwrap();
    757     let mut connection = database(&f).await;
    758     sqlx::raw_sql("CREATE TABLE grant_commit_fault(value INTEGER REFERENCES stock_authority(singleton) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER grant_commit_failure AFTER INSERT ON stock_grant_changes BEGIN INSERT INTO grant_commit_fault VALUES(2); END").execute(&mut connection).await.unwrap();
    759     assert_eq!(
    760         store
    761             .enroll_stock_grant(owner.clone(), current, enrollment.proof(), &delegated)
    762             .await
    763             .unwrap(),
    764         StockGrantOutcome::Unknown(delegated.transaction_id())
    765     );
    766     assert_eq!(
    767         store
    768             .authenticate(enrollment.input().clone(), enrollment.proof())
    769             .await,
    770         Err(WorkspaceError::RecoveryRequired)
    771     );
    772     store.close().await.unwrap();
    773     sqlx::raw_sql("DROP TRIGGER grant_commit_failure; DROP TABLE grant_commit_fault")
    774         .execute(&mut connection)
    775         .await
    776         .unwrap();
    777     connection.close().await.unwrap();
    778     let reopened = NativeWorkspace::open_seller_stock(
    779         &f.path,
    780         enrollment.input().clone(),
    781         f.crypto(),
    782         f.clock.clone(),
    783     )
    784     .await
    785     .unwrap();
    786     let binding = reopened
    787         .authenticate(enrollment.input().clone(), enrollment.proof())
    788         .await
    789         .unwrap();
    790     assert_eq!(
    791         checkpoint(&reopened, binding.input(), enrollment.proof()).await,
    792         current
    793     );
    794     let result = grant_committed(
    795         reopened
    796             .enroll_stock_grant(binding, current, enrollment.proof(), &delegated)
    797             .await
    798             .unwrap(),
    799     );
    800     assert_eq!(result.transaction_id(), delegated.transaction_id());
    801     reopened.close().await.unwrap();
    802 }