lib

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

workspace.rs (13475B)


      1 #![cfg(feature = "workspace_session")]
      2 // Port-model tests for captured context invariants. Concrete native credential,
      3 // persistence and cancellation qualification belongs to its actual backend.
      4 use futures::{executor::block_on, task::AtomicWaker};
      5 use radroots_domain::*;
      6 use radroots_execution::session::{ClientSession, HostFuture, SessionHost};
      7 use radroots_execution::workspace::WorkspaceSession;
      8 use radroots_storage::workspace::{
      9     AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceStore,
     10 };
     11 #[cfg(target_arch = "wasm32")]
     12 use std::rc::Rc as Shared;
     13 #[cfg(not(target_arch = "wasm32"))]
     14 use std::sync::Arc as Shared;
     15 use std::{
     16     future::poll_fn,
     17     sync::{
     18         Mutex,
     19         atomic::{AtomicBool, Ordering},
     20     },
     21     task::Poll,
     22 };
     23 
     24 struct Model {
     25     binding: Mutex<WorkspaceBinding>,
     26     error: Mutex<Option<WorkspaceError>>,
     27     pending: AtomicBool,
     28     waker: AtomicWaker,
     29 }
     30 impl WorkspaceStore for Model {
     31     fn authenticate(
     32         &self,
     33         _input: AttachmentInput,
     34         _proof: AttachmentProof,
     35     ) -> radroots_storage::event::BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>> {
     36         Box::pin(async move {
     37             poll_fn(|cx| {
     38                 self.waker.register(cx.waker());
     39                 if self.pending.load(Ordering::Acquire) {
     40                     Poll::Pending
     41                 } else {
     42                     Poll::Ready(())
     43                 }
     44             })
     45             .await;
     46             if let Some(error) = *self.error.lock().unwrap() {
     47                 return Err(error);
     48             }
     49             Ok(self.binding.lock().unwrap().clone())
     50         })
     51     }
     52     fn close_workspace(
     53         &self,
     54     ) -> radroots_storage::event::BoxFuture<'_, Result<(), WorkspaceError>> {
     55         Box::pin(async { Ok(()) })
     56     }
     57 }
     58 fn key() -> PublicKey {
     59     PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap()
     60 }
     61 fn input(route: u8) -> AttachmentInput {
     62     AttachmentInput::new(
     63         WorkspaceId::from_bytes([1; 32]),
     64         AuthorityRef::new(ExecutorId::from_bytes([2; 32]), Generation::new(1).unwrap()),
     65         key(),
     66         "local://model",
     67         key(),
     68         GrantId::from_bytes([3; 32]),
     69         CheckpointRef::new(
     70             CheckpointDigest::from_bytes([4; 32]),
     71             Sequence::new(0).unwrap(),
     72             Coverage::Partial,
     73             vec![],
     74         )
     75         .unwrap(),
     76         RouteDigest::from_bytes([route; 32]),
     77     )
     78     .unwrap()
     79 }
     80 fn binding(change: u8, observed: u64) -> WorkspaceBinding {
     81     let input = input(if change == 1 { 9 } else { 5 });
     82     WorkspaceBinding::from_authenticated_host(
     83         input.clone(),
     84         if change == 2 {
     85             radroots_storage::workspace::WorkspaceScope::NewSellerOutbox
     86         } else {
     87             radroots_storage::workspace::WorkspaceScope::NewBuyerOutbox
     88         },
     89         ActorRef::new(
     90             key(),
     91             if change == 2 {
     92                 ActorRole::Seller
     93             } else {
     94                 ActorRole::Buyer
     95             },
     96             None,
     97             Some(input.grant_id()),
     98         ),
     99         if change == 3 {
    100             "other-device"
    101         } else {
    102             "device"
    103         },
    104         Sequence::new(if change == 4 { 2 } else { 1 }).unwrap(),
    105         UnixSeconds::new(if change == 5 { 201 } else { 200 }).unwrap(),
    106         UnixSeconds::new(observed).unwrap(),
    107     )
    108     .unwrap()
    109 }
    110 fn new_model() -> Shared<Model> {
    111     Shared::new(Model {
    112         binding: Mutex::new(binding(0, 100)),
    113         error: Mutex::new(None),
    114         pending: AtomicBool::new(false),
    115         waker: AtomicWaker::new(),
    116     })
    117 }
    118 fn proof() -> AttachmentProof {
    119     AttachmentProof::from_protected_input(&[7; 32]).unwrap()
    120 }
    121 
    122 struct Host;
    123 impl SessionHost for Host {
    124     fn start(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
    125         Box::pin(async { Ok(()) })
    126     }
    127     fn quiesce(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
    128         Box::pin(async { Ok(()) })
    129     }
    130     fn disconnect(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
    131         Box::pin(async { Ok(()) })
    132     }
    133     fn dispose_callbacks(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
    134         Box::pin(async { Ok(()) })
    135     }
    136     fn close_storage(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
    137         Box::pin(async { Ok(()) })
    138     }
    139 }
    140 #[test]
    141 fn client_bounds_and_retires_scopes_and_refuses_attachment_finishing_after_quiesce() {
    142     block_on(async {
    143         let model = new_model();
    144         let client = ClientSession::new(Host, core::num::NonZeroU16::MIN);
    145         let mut scopes = Vec::new();
    146         for _ in 0..16 {
    147             scopes.push(
    148                 client
    149                     .attach_workspace(model.clone(), input(5), proof())
    150                     .await
    151                     .unwrap(),
    152             );
    153         }
    154         assert_eq!(
    155             client
    156                 .attach_workspace(model.clone(), input(5), proof())
    157                 .await
    158                 .unwrap_err()
    159                 .code(),
    160             radroots_execution::Code::CapabilityUnavailable
    161         );
    162         scopes[0].close();
    163         scopes.push(
    164             client
    165                 .attach_workspace(model.clone(), input(5), proof())
    166                 .await
    167                 .unwrap(),
    168         );
    169         model.pending.store(true, Ordering::Release);
    170         let mut attachment = Box::pin(client.attach_workspace(model.clone(), input(5), proof()));
    171         assert!(futures::poll!(attachment.as_mut()).is_pending());
    172         let mut closing = Box::pin(client.close());
    173         assert!(futures::poll!(closing.as_mut()).is_pending());
    174         for scope in &scopes {
    175             assert!(
    176                 scope
    177                     .command_context(
    178                         OperationId::from_bytes([10; 32]),
    179                         None,
    180                         None,
    181                         UnixSeconds::new(150).unwrap()
    182                     )
    183                     .is_err()
    184             );
    185         }
    186         model.pending.store(false, Ordering::Release);
    187         model.waker.wake();
    188         assert_eq!(
    189             attachment.await.unwrap_err().code(),
    190             radroots_execution::Code::CapabilityUnavailable
    191         );
    192         closing.await.unwrap();
    193         assert!(
    194             client
    195                 .attach_workspace(model, input(5), proof())
    196                 .await
    197                 .is_err()
    198         );
    199     })
    200 }
    201 #[test]
    202 fn captured_context_retains_all_fields_and_refuses_each_semantic_grant_change() {
    203     block_on(async {
    204         let model = new_model();
    205         let session = WorkspaceSession::attach(model.clone(), input(5), proof())
    206             .await
    207             .unwrap();
    208         let expected = ExpectedOrder::new(
    209             OrderId::from_bytes([8; 32]),
    210             None,
    211             Sequence::new(0).unwrap(),
    212             None,
    213             input(5).checkpoint().clone(),
    214         );
    215         let approval = Approval::new(
    216             ApprovalIntentDigest::from_bytes([9; 32]),
    217             "scope",
    218             UnixSeconds::new(160).unwrap(),
    219         )
    220         .unwrap();
    221         let context = session
    222             .command_context_with_correlation(
    223                 OperationId::from_bytes([10; 32]),
    224                 Some(expected.clone()),
    225                 Some(approval.clone()),
    226                 UnixSeconds::new(150).unwrap(),
    227                 Some(CorrelationId::new("diagnostic").unwrap()),
    228             )
    229             .unwrap();
    230         assert_eq!(context.data().expected(), Some(&expected));
    231         assert_eq!(context.data().approval(), Some(&approval));
    232         assert_eq!(context.data().actor(), session.binding().actor());
    233         assert_eq!(format!("{session:?}"), "WorkspaceSession(<redacted>)");
    234         assert_eq!(format!("{context:?}"), "CommandContext(<redacted>)");
    235         context.revalidate().await.unwrap();
    236         for change in 1..=5 {
    237             *model.binding.lock().unwrap() = binding(change, 100);
    238             assert_eq!(
    239                 context.revalidate().await.unwrap_err().code(),
    240                 radroots_execution::Code::GrantRevoked
    241             );
    242         }
    243         *model.binding.lock().unwrap() = binding(0, 150);
    244         assert_eq!(
    245             context.revalidate().await.unwrap_err().code(),
    246             radroots_execution::Code::Unauthorized
    247         );
    248         *model.binding.lock().unwrap() = binding(0, 100);
    249         for deadline in [0, 100, 201] {
    250             assert!(
    251                 session
    252                     .command_context(
    253                         OperationId::from_bytes([10; 32]),
    254                         None,
    255                         None,
    256                         UnixSeconds::new(deadline).unwrap()
    257                     )
    258                     .is_err()
    259             );
    260         }
    261         *model.error.lock().unwrap() = Some(WorkspaceError::Unavailable);
    262         // Construction is pure even while the host is unavailable; admission must
    263         // perform the separate current-rights check and refuse this unavailable host.
    264         session
    265             .command_context(
    266                 OperationId::from_bytes([10; 32]),
    267                 None,
    268                 None,
    269                 UnixSeconds::new(150).unwrap(),
    270             )
    271             .unwrap();
    272         assert_eq!(
    273             context.revalidate().await.unwrap_err().code(),
    274             radroots_execution::Code::CapabilityUnavailable
    275         );
    276     })
    277 }
    278 
    279 #[test]
    280 fn pre_admission_workspace_errors_retain_proposed_identity_and_typed_uncertainty() {
    281     block_on(async {
    282         use WorkspaceError as W;
    283         use radroots_execution::{Admission, Code as C, RetryClass};
    284         let model = new_model();
    285         let session = WorkspaceSession::attach(model.clone(), input(5), proof())
    286             .await
    287             .unwrap();
    288         let operation = OperationId::from_bytes([10; 32]);
    289         let context = session
    290             .command_context(operation, None, None, UnixSeconds::new(150).unwrap())
    291             .unwrap();
    292         for (source, code) in [
    293             (W::InvalidInput, C::InvalidInput),
    294             (W::Unauthorized, C::Unauthorized),
    295             (W::GrantExpired, C::Unauthorized),
    296             (W::GrantRevoked, C::GrantRevoked),
    297             (W::WriterActive, C::MissingAuthority),
    298             (W::WrongNamespace, C::Unauthorized),
    299             (W::StaleAuthority, C::StaleState),
    300             (W::StaleCheckpoint, C::StaleState),
    301             (W::Unavailable, C::CapabilityUnavailable),
    302             (W::Closed, C::CapabilityUnavailable),
    303             (W::StorageFailure, C::StorageFailure),
    304             (W::NamespaceUnavailable, C::RecoveryRequired),
    305             (W::RecoveryRequired, C::RecoveryRequired),
    306             (W::CommitUnknown, C::RecoveryRequired),
    307         ] {
    308             *model.error.lock().unwrap() = Some(source);
    309             let error = context.revalidate().await.unwrap_err();
    310             assert_eq!(error.code(), code);
    311             assert_eq!(error.context().operation_id(), Some(operation));
    312             assert_eq!(error.context().admission(), Admission::NotAdmitted);
    313             assert!(error.detail().is_some());
    314             if source == W::CommitUnknown {
    315                 assert_eq!(error.retry(), RetryClass::ManualReconciliation);
    316             }
    317         }
    318     })
    319 }
    320 #[test]
    321 fn attachment_never_trusts_an_adapter_result_for_another_selection() {
    322     block_on(async {
    323         let model = new_model();
    324         *model.binding.lock().unwrap() = binding(1, 100);
    325         assert_eq!(
    326             WorkspaceSession::attach(model, input(5), proof())
    327                 .await
    328                 .unwrap_err()
    329                 .code(),
    330             radroots_execution::Code::Unauthorized
    331         );
    332         let model = new_model();
    333         *model.error.lock().unwrap() = Some(WorkspaceError::Unauthorized);
    334         assert_eq!(
    335             WorkspaceSession::attach(model, input(5), proof())
    336                 .await
    337                 .unwrap_err()
    338                 .code(),
    339             radroots_execution::Code::Unauthorized
    340         );
    341     })
    342 }
    343 #[test]
    344 fn close_invalidates_clones_and_an_already_pending_context_revalidation() {
    345     block_on(async {
    346         let model = new_model();
    347         let session = WorkspaceSession::attach(model.clone(), input(5), proof())
    348             .await
    349             .unwrap();
    350         let context = session
    351             .command_context(
    352                 OperationId::from_bytes([10; 32]),
    353                 None,
    354                 None,
    355                 UnixSeconds::new(150).unwrap(),
    356             )
    357             .unwrap();
    358         model.pending.store(true, Ordering::Release);
    359         let mut pending = Box::pin(context.revalidate());
    360         assert!(futures::poll!(pending.as_mut()).is_pending());
    361         session.clone().close();
    362         model.pending.store(false, Ordering::Release);
    363         model.waker.wake();
    364         assert_eq!(
    365             pending.await.unwrap_err().code(),
    366             radroots_execution::Code::CapabilityUnavailable
    367         );
    368         assert_eq!(
    369             context.revalidate().await.unwrap_err().code(),
    370             radroots_execution::Code::CapabilityUnavailable
    371         );
    372         assert!(
    373             session
    374                 .command_context(
    375                     OperationId::from_bytes([10; 32]),
    376                     None,
    377                     None,
    378                     UnixSeconds::new(150).unwrap()
    379                 )
    380                 .is_err()
    381         );
    382     })
    383 }
    384 
    385 #[path = "support/workspace_commands.rs"]
    386 mod commands;
    387 
    388 #[path = "support/workspace_inventory.rs"]
    389 mod inventory;