lib

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

workspace.rs (8352B)


      1 #![cfg(all(feature = "native", unix))]
      2 use radroots::{Client, NativeConfig, OperationId, StartMode};
      3 use radroots_domain::{
      4     Approval, ApprovalIntentDigest, CorrelationId, ExpectedOrder, OrderId, PublicKey, RecordId,
      5     Sequence, UnixSeconds,
      6 };
      7 use radroots_secrets::{
      8     SecretId, SecretRef,
      9     envelope::Nonce,
     10     file::{FileOpenMode, FileProvider},
     11     id::{BackendKind, KeyVersion},
     12     provider::AccessPolicy,
     13     wrapping::SecretMaterial,
     14 };
     15 use radroots_storage::{
     16     event::SourceGeneration,
     17     workspace::{AttachmentProof, WorkspaceClock, WorkspaceError},
     18 };
     19 use radroots_storage_sqlite::{
     20     OpenMode, OpenOptions, Paths,
     21     workspace::{LocalOutboxConfig, NativeWorkspace, WorkspaceCrypto},
     22 };
     23 use std::sync::{
     24     Arc,
     25     atomic::{AtomicU64, Ordering},
     26 };
     27 struct Clock(AtomicU64);
     28 impl WorkspaceClock for Clock {
     29     fn now(&self) -> Result<UnixSeconds, WorkspaceError> {
     30         UnixSeconds::new(self.0.load(Ordering::SeqCst)).map_err(|_| WorkspaceError::Unavailable)
     31     }
     32 }
     33 fn key() -> PublicKey {
     34     PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap()
     35 }
     36 #[tokio::test]
     37 async fn ordinary_client_authenticates_context_and_closes_actual_workspace() {
     38     let temp = tempfile::tempdir().unwrap();
     39     let root = temp.path().canonicalize().unwrap();
     40     let provider = Arc::new(
     41         FileProvider::open(
     42             root.join("vault"),
     43             FileOpenMode::CreateNew,
     44             SecretMaterial::from_slice(&[0xA5; 32]).unwrap(),
     45         )
     46         .unwrap(),
     47     );
     48     let reference = || {
     49         SecretRef::new(
     50             SecretId::parse("workspace-key").unwrap(),
     51             BackendKind::File,
     52             KeyVersion::new(1).unwrap(),
     53         )
     54     };
     55     provider
     56         .provision(
     57             &reference(),
     58             &SecretMaterial::from_slice(&[0x41; 32]).unwrap(),
     59             Nonce::new([0x11; 24]),
     60         )
     61         .unwrap();
     62     let crypto = || {
     63         WorkspaceCrypto::new(
     64             provider.clone(),
     65             reference(),
     66             SecretMaterial::from_slice(&[0x41; 32]).unwrap(),
     67             AccessPolicy::standard(),
     68         )
     69         .unwrap()
     70     };
     71     let clock = Arc::new(Clock(AtomicU64::new(100)));
     72     let config = LocalOutboxConfig::new(
     73         key(),
     74         key(),
     75         "synthetic-device",
     76         UnixSeconds::new(200).unwrap(),
     77     )
     78     .unwrap();
     79     let (workspace, input, proof) = NativeWorkspace::initialize_local_outbox(
     80         &root.join("outbox"),
     81         config,
     82         crypto(),
     83         clock.clone(),
     84     )
     85     .await
     86     .unwrap();
     87     let workspace_copy = workspace.clone();
     88     let options = OpenOptions::new(
     89         Paths::from_directory(root.join("cache")).unwrap(),
     90         OpenMode::Create,
     91     )
     92     .with_source_generation(SourceGeneration::new([17; 32]).unwrap(), 1)
     93     .unwrap();
     94     // The existing public cache adapter requires its explicit directory to exist.
     95     std::fs::create_dir(root.join("cache")).unwrap();
     96     let client = Client::open(NativeConfig::public_read(options).with_workspace(workspace))
     97         .await
     98         .unwrap();
     99     let wrong = AttachmentProof::from_protected_input(&[0; 32]).unwrap();
    100     assert_eq!(
    101         client
    102             .attach(input.clone(), wrong)
    103             .await
    104             .unwrap_err()
    105             .code(),
    106         radroots_execution::Code::Unauthorized
    107     );
    108     let duplicate = proof
    109         .with_secret(|secret| AttachmentProof::from_protected_input(secret))
    110         .unwrap();
    111     let other_proof = proof
    112         .with_secret(|secret| AttachmentProof::from_protected_input(secret))
    113         .unwrap();
    114     let session = client.attach(input.clone(), proof).await.unwrap();
    115     assert_eq!(session.binding().actor().participant(), key());
    116     let op = OperationId::from_bytes([7; 32]);
    117     let approval = Approval::new(
    118         ApprovalIntentDigest::from_bytes([8; 32]),
    119         "known-kind",
    120         UnixSeconds::new(160).unwrap(),
    121     )
    122     .unwrap();
    123     let expected = ExpectedOrder::new(
    124         OrderId::from_bytes([9; 32]),
    125         Some(RecordId::from_bytes([10; 32])),
    126         Sequence::new(11).unwrap(),
    127         Some(RecordId::from_bytes([12; 32])),
    128         input.checkpoint().clone(),
    129     );
    130     let context = session
    131         .command_context_with_correlation(
    132             op,
    133             Some(expected.clone()),
    134             Some(approval.clone()),
    135             UnixSeconds::new(150).unwrap(),
    136             Some(CorrelationId::new("diagnostic").unwrap()),
    137         )
    138         .unwrap();
    139     let data = context.data();
    140     assert_eq!(data.operation_id(), op);
    141     assert_eq!(data.actor(), session.binding().actor());
    142     assert_eq!(data.workspace_id(), input.workspace_id());
    143     assert_eq!(data.authority(), input.authority());
    144     assert_eq!(data.route_digest(), input.route_digest());
    145     assert_eq!(data.approval(), Some(&approval));
    146     assert_eq!(data.expected(), Some(&expected));
    147     assert_eq!(data.not_after().get(), 150);
    148     assert_eq!(data.correlation_id().unwrap().as_str(), "diagnostic");
    149     context.revalidate().await.unwrap();
    150     assert_eq!(format!("{context:?}"), "CommandContext(<redacted>)");
    151     assert_eq!(format!("{session:?}"), "WorkspaceSession(<redacted>)");
    152     assert!(
    153         session
    154             .command_context(op, None, None, UnixSeconds::new(100).unwrap())
    155             .is_err()
    156     );
    157     assert!(
    158         session
    159             .command_context(op, None, None, UnixSeconds::new(201).unwrap())
    160             .is_err()
    161     );
    162     clock.0.store(150, Ordering::SeqCst);
    163     assert_eq!(
    164         context.revalidate().await.unwrap_err().code(),
    165         radroots_execution::Code::Unauthorized
    166     );
    167     clock.0.store(101, Ordering::SeqCst);
    168     let other = client.attach(input.clone(), other_proof).await.unwrap();
    169     let other_context = other
    170         .command_context(op, None, None, UnixSeconds::new(150).unwrap())
    171         .unwrap();
    172     other.close();
    173     assert_eq!(
    174         other_context.revalidate().await.unwrap_err().code(),
    175         radroots_execution::Code::CapabilityUnavailable
    176     );
    177     assert!(
    178         other
    179             .command_context(op, None, None, UnixSeconds::new(150).unwrap())
    180             .is_err()
    181     );
    182     context.revalidate().await.unwrap();
    183     workspace_copy
    184         .revoke(input.clone(), &duplicate)
    185         .await
    186         .unwrap();
    187     assert_eq!(
    188         context.revalidate().await.unwrap_err().code(),
    189         radroots_execution::Code::GrantRevoked
    190     );
    191     client.start(StartMode::LocalOnly).await.unwrap();
    192     client.close().await.unwrap();
    193     assert!(
    194         session
    195             .command_context(op, None, None, UnixSeconds::new(150).unwrap())
    196             .is_err()
    197     );
    198     assert_eq!(
    199         context.revalidate().await.unwrap_err().code(),
    200         radroots_execution::Code::CapabilityUnavailable
    201     );
    202     assert!(
    203         client
    204             .attach(
    205                 input.clone(),
    206                 AttachmentProof::from_protected_input(&[0; 32]).unwrap()
    207             )
    208             .await
    209             .is_err()
    210     );
    211     workspace_copy.close().await.unwrap();
    212     let reopened = NativeWorkspace::open_existing(&root.join("outbox"), input, crypto(), clock)
    213         .await
    214         .unwrap();
    215     reopened.close().await.unwrap();
    216 }
    217 
    218 #[tokio::test]
    219 async fn preview_cannot_authenticate_a_caller_supplied_workspace_descriptor() {
    220     let client = Client::preview();
    221     let input = radroots_storage::workspace::AttachmentInput::new(
    222         radroots_domain::WorkspaceId::from_bytes([1; 32]),
    223         radroots_domain::AuthorityRef::new(
    224             radroots_domain::ExecutorId::from_bytes([2; 32]),
    225             radroots_domain::Generation::new(1).unwrap(),
    226         ),
    227         key(),
    228         "local://workspace/untrusted",
    229         key(),
    230         radroots_domain::GrantId::from_bytes([3; 32]),
    231         radroots_domain::CheckpointRef::new(
    232             radroots_domain::CheckpointDigest::from_bytes([4; 32]),
    233             Sequence::new(0).unwrap(),
    234             radroots_domain::Coverage::Partial,
    235             vec![],
    236         )
    237         .unwrap(),
    238         radroots_domain::RouteDigest::from_bytes([5; 32]),
    239     )
    240     .unwrap();
    241     let proof = AttachmentProof::from_protected_input(&[0; 32]).unwrap();
    242     assert_eq!(
    243         client.attach(input, proof).await.unwrap_err().code(),
    244         radroots_execution::Code::MissingAuthority
    245     );
    246     client.close().await.unwrap();
    247 }