lib

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

protected.rs (14388B)


      1 //! Bounded protected Prepared representation and pure scope checks shared by
      2 //! concrete transaction hosts. Decoding supplies no current access or commit.
      3 use super::{AdmissionRequest, OperationError, PreparedOperation};
      4 use crate::workspace::{AttachmentInput, WorkspaceBinding, WorkspaceScope};
      5 use radroots_domain::{
      6     CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, UnixSeconds,
      7 };
      8 use serde::{Deserialize, Serialize};
      9 use zeroize::Zeroizing;
     10 
     11 pub mod issuance;
     12 pub mod plan;
     13 
     14 /// Maximum complete preparation, before a host splits private records.
     15 pub const PREPARED_BYTES_MAX: usize = 65_536;
     16 
     17 #[derive(Serialize)]
     18 struct Encoded<'a> {
     19     version: u8,
     20     selection: &'a AttachmentInput,
     21     scope: WorkspaceScope,
     22     principal: &'a str,
     23     grant_revision: Sequence,
     24     grant_expires_at: UnixSeconds,
     25     captured_observed_at: UnixSeconds,
     26     transaction_id: TransactionId,
     27     revision: Sequence,
     28     prepared_at: UnixSeconds,
     29     first_issue_not_after: UnixSeconds,
     30     command: &'a serde_json::value::RawValue,
     31 }
     32 #[derive(Deserialize)]
     33 #[serde(deny_unknown_fields)]
     34 struct Decoded<'a> {
     35     version: u8,
     36     selection: AttachmentInput,
     37     #[serde(default, deserialize_with = "present_scope")]
     38     scope: Option<WorkspaceScope>,
     39     principal: String,
     40     grant_revision: Sequence,
     41     grant_expires_at: UnixSeconds,
     42     captured_observed_at: UnixSeconds,
     43     transaction_id: TransactionId,
     44     revision: Sequence,
     45     prepared_at: UnixSeconds,
     46     first_issue_not_after: UnixSeconds,
     47     #[serde(borrow)]
     48     command: &'a serde_json::value::RawValue,
     49 }
     50 
     51 fn present_scope<'de, D: serde::Deserializer<'de>>(
     52     deserializer: D,
     53 ) -> Result<Option<WorkspaceScope>, D::Error> {
     54     WorkspaceScope::deserialize(deserializer).map(Some)
     55 }
     56 
     57 /// Encodes the original immutable preparation before encryption. A host must
     58 /// independently commit it and enforce its smaller private record limit.
     59 pub fn encode(
     60     request: &AdmissionRequest,
     61     transaction_id: TransactionId,
     62     window: IssuanceWindow,
     63 ) -> Result<Zeroizing<Vec<u8>>, OperationError> {
     64     let binding = request.binding();
     65     let encoded = Encoded {
     66         version: 3,
     67         selection: binding.input(),
     68         scope: binding.scope(),
     69         principal: binding.principal_id(),
     70         grant_revision: binding.grant_revision(),
     71         grant_expires_at: binding.expires_at(),
     72         captured_observed_at: binding.observed_at(),
     73         transaction_id,
     74         revision: Sequence::new(1).map_err(|_| OperationError::RecoveryRequired)?,
     75         prepared_at: window.prepared_at(),
     76         first_issue_not_after: window.first_issue_not_after(),
     77         command: serde_json::from_slice(request.command().protected_wire())
     78             .map_err(|_| OperationError::InvalidCommand)?,
     79     };
     80     let plaintext =
     81         Zeroizing::new(serde_json::to_vec(&encoded).map_err(|_| OperationError::InvalidCommand)?);
     82     if plaintext.len() > PREPARED_BYTES_MAX {
     83         return Err(OperationError::InvalidCommand);
     84     }
     85     Ok(plaintext)
     86 }
     87 
     88 /// Validates bounded decrypted retained bytes against the independently selected
     89 /// namespace/operation. This is a historical observation, never current authority.
     90 pub fn decode(
     91     bytes: &[u8],
     92     selected: &AttachmentInput,
     93     operation_id: OperationId,
     94 ) -> Result<PreparedOperation, OperationError> {
     95     if bytes.len() > PREPARED_BYTES_MAX {
     96         return Err(OperationError::RecoveryRequired);
     97     }
     98     let decoded: Decoded<'_> =
     99         serde_json::from_slice(bytes).map_err(|_| OperationError::RecoveryRequired)?;
    100     let scope = match (decoded.version, decoded.scope) {
    101         // The historical profile could only enroll buyer outboxes. It must
    102         // never infer seller authority from a substituted retained actor.
    103         (2, None) => WorkspaceScope::NewBuyerOutbox,
    104         (3, Some(scope)) => scope,
    105         _ => return Err(OperationError::RecoveryRequired),
    106     };
    107     if decoded.revision.get() != 1 {
    108         return Err(OperationError::RecoveryRequired);
    109     }
    110     let command_context: radroots_domain::CommandContextData = {
    111         #[derive(Deserialize)]
    112         struct ContextOnly {
    113             context: radroots_domain::CommandContextData,
    114         }
    115         serde_json::from_str::<ContextOnly>(decoded.command.get())
    116             .map_err(|_| OperationError::RecoveryRequired)?
    117             .context
    118     };
    119     let binding = WorkspaceBinding::from_authenticated_host(
    120         decoded.selection,
    121         scope,
    122         command_context.actor(),
    123         decoded.principal,
    124         decoded.grant_revision,
    125         decoded.grant_expires_at,
    126         decoded.captured_observed_at,
    127     )
    128     .map_err(|_| OperationError::RecoveryRequired)?;
    129     if binding.input() != selected {
    130         return Err(OperationError::RecoveryRequired);
    131     }
    132     let request = AdmissionRequest::from_protected_wire(binding, decoded.command.get().as_bytes())
    133         .map_err(|_| OperationError::RecoveryRequired)?;
    134     let context = request.command().context();
    135     if context.workspace_id() != selected.workspace_id() || context.operation_id() != operation_id {
    136         return Err(OperationError::RecoveryRequired);
    137     }
    138     let snapshot = PreparedOperation::from_committed_store(
    139         request,
    140         decoded.transaction_id,
    141         decoded.revision,
    142         IssuanceWindow::new(decoded.prepared_at, decoded.first_issue_not_after)
    143             .map_err(|_| OperationError::RecoveryRequired)?,
    144     )?;
    145     Ok::<_, OperationError>(snapshot)
    146 }
    147 
    148 /// Checks the actor and optional exact original commitment without fresh issuance.
    149 pub fn check_digest(
    150     snapshot: &PreparedOperation,
    151     actor: radroots_domain::ActorRef,
    152     expected: Option<CommandDigest>,
    153 ) -> Result<(), OperationError> {
    154     if snapshot.request().command().context().actor().participant() != actor.participant() {
    155         return Err(OperationError::Unauthorized);
    156     }
    157     if expected.is_some_and(|digest| digest != snapshot.request().command().digest()) {
    158         return Err(OperationError::IdempotencyConflict);
    159     }
    160     Ok(())
    161 }
    162 
    163 /// Compares the retained scope and current grant revision; observation times may differ.
    164 pub fn same_binding(
    165     captured: &WorkspaceBinding,
    166     current: &WorkspaceBinding,
    167 ) -> Result<(), OperationError> {
    168     if captured.input() != current.input()
    169         || captured.scope() != current.scope()
    170         || captured.actor() != current.actor()
    171         || captured.principal_id() != current.principal_id()
    172         || captured.grant_revision() != current.grant_revision()
    173         || captured.expires_at() != current.expires_at()
    174     {
    175         return Err(OperationError::Unauthorized);
    176     }
    177     Ok(())
    178 }
    179 
    180 #[cfg(test)]
    181 mod tests {
    182     use super::*;
    183     use crate::workspace::{AttachmentProof, local_outbox::LocalOutboxConfig};
    184     use radroots_domain::{CommandContextData, ExecutorId, GrantId, PublicKey, WorkspaceId};
    185     use serde_json::json;
    186 
    187     pub(super) fn request() -> AdmissionRequest {
    188         let participant =
    189             PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798")
    190                 .unwrap();
    191         let now = UnixSeconds::new(100).unwrap();
    192         let (input, proof, grant) = LocalOutboxConfig::new(
    193             participant,
    194             participant,
    195             "synthetic-codec",
    196             UnixSeconds::new(200).unwrap(),
    197         )
    198         .unwrap()
    199         .enroll(
    200             now,
    201             WorkspaceId::from_bytes([1; 32]),
    202             ExecutorId::from_bytes([2; 32]),
    203             GrantId::from_bytes([3; 32]),
    204             AttachmentProof::from_protected_input(&[4; 32]).unwrap(),
    205         )
    206         .unwrap();
    207         let binding = grant.authenticate(&input, &proof, now).unwrap();
    208         let context = CommandContextData::new(
    209             OperationId::from_bytes([5; 32]),
    210             binding.actor(),
    211             input.workspace_id(),
    212             input.authority(),
    213             input.route_digest(),
    214             None,
    215             None,
    216             UnixSeconds::new(150).unwrap(),
    217             None,
    218         )
    219         .unwrap();
    220         let wire = serde_json::to_vec(&json!({"type":"inbox.inquire","context":context,
    221             "input":{"thread_id":"66".repeat(32),"peer":participant,"source":null,"text":"synthetic retained preparation"}})).unwrap();
    222         AdmissionRequest::from_protected_wire(binding, &wire).unwrap()
    223     }
    224     #[test]
    225     fn retained_scope_is_explicit_and_legacy_preparation_never_infers_seller_authority() {
    226         let request = request();
    227         let operation = request.command().context().operation_id();
    228         let bytes = encode(
    229             &request,
    230             TransactionId::from_bytes([7; 32]),
    231             IssuanceWindow::capture(
    232                 UnixSeconds::new(100).unwrap(),
    233                 UnixSeconds::new(150).unwrap(),
    234             )
    235             .unwrap(),
    236         )
    237         .unwrap();
    238         let original: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    239         assert_eq!(original["version"], 3);
    240         assert_eq!(original["scope"], "new_buyer_outbox");
    241         let read = |wire: &serde_json::Value| {
    242             decode(
    243                 &serde_json::to_vec(wire).unwrap(),
    244                 request.binding().input(),
    245                 operation,
    246             )
    247         };
    248         let mut legacy = original.clone();
    249         legacy["version"] = json!(2);
    250         assert!(read(&legacy).is_err());
    251         legacy.as_object_mut().unwrap().remove("scope");
    252         assert_eq!(
    253             read(&legacy).unwrap().request().binding().scope(),
    254             WorkspaceScope::NewBuyerOutbox
    255         );
    256         legacy["command"]["context"]["actor"]["role"] = json!("seller");
    257         assert!(read(&legacy).is_err());
    258         for version in [2, 3] {
    259             let mut null = original.clone();
    260             null["version"] = json!(version);
    261             null["scope"] = serde_json::Value::Null;
    262             assert!(read(&null).is_err());
    263         }
    264         let mut missing = original.clone();
    265         missing.as_object_mut().unwrap().remove("scope");
    266         assert!(read(&missing).is_err());
    267         let mut mismatched = original.clone();
    268         mismatched["scope"] = json!("new_seller_outbox");
    269         assert!(read(&mismatched).is_err());
    270         mismatched["command"]["context"]["actor"]["role"] = json!("seller");
    271         let decoded = read(&mismatched).unwrap();
    272         assert_eq!(
    273             decoded.request().binding().scope(),
    274             WorkspaceScope::NewSellerOutbox
    275         );
    276         assert!(same_binding(request.binding(), decoded.request().binding()).is_err());
    277     }
    278     #[test]
    279     fn original_preparation_round_trip_and_scope_are_checked_without_current_authority() {
    280         let request = request();
    281         let operation = request.command().context().operation_id();
    282         let transaction = TransactionId::from_bytes([7; 32]);
    283         let window = IssuanceWindow::capture(
    284             UnixSeconds::new(100).unwrap(),
    285             UnixSeconds::new(150).unwrap(),
    286         )
    287         .unwrap();
    288         let bytes = encode(&request, transaction, window).unwrap();
    289         let decoded = decode(&bytes, request.binding().input(), operation).unwrap();
    290         assert_eq!(decoded.transaction_id(), transaction);
    291         assert_eq!(decoded.issuance_window(), window);
    292         assert_eq!(
    293             decoded.request().command().protected_wire(),
    294             request.command().protected_wire()
    295         );
    296         assert!(same_binding(request.binding(), decoded.request().binding()).is_ok());
    297         assert!(check_digest(&decoded, request.binding().actor(), None).is_ok());
    298         assert!(
    299             check_digest(
    300                 &decoded,
    301                 request.binding().actor(),
    302                 Some(request.command().digest())
    303             )
    304             .is_ok()
    305         );
    306         assert_eq!(
    307             check_digest(
    308                 &decoded,
    309                 request.binding().actor(),
    310                 Some(CommandDigest::from_bytes([8; 32]))
    311             ),
    312             Err(OperationError::IdempotencyConflict)
    313         );
    314         assert!(
    315             decode(
    316                 &bytes,
    317                 request.binding().input(),
    318                 OperationId::from_bytes([9; 32])
    319             )
    320             .is_err()
    321         );
    322         assert!(
    323             decode(
    324                 &vec![0; PREPARED_BYTES_MAX + 1],
    325                 request.binding().input(),
    326                 operation
    327             )
    328             .is_err()
    329         );
    330         assert!(decode(b"{}", request.binding().input(), operation).is_err());
    331         let original: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    332         for (pointer, value) in [
    333             ("/version", json!(1)),
    334             ("/revision", json!("0")),
    335             ("/revision", json!("2")),
    336             ("/selection/workspace_id", json!("88".repeat(32))),
    337             ("/principal", json!("")),
    338             ("/prepared_at", json!("0")),
    339             ("/prepared_at", json!("99")),
    340             ("/first_issue_not_after", json!("100")),
    341             ("/first_issue_not_after", json!("151")),
    342             ("/command/type", json!("unknown")),
    343             ("/command/context", json!({})),
    344         ] {
    345             let mut damaged = original.clone();
    346             *damaged.pointer_mut(pointer).unwrap() = value;
    347             let wire = serde_json::to_vec(&damaged).unwrap();
    348             assert!(
    349                 decode(&wire, request.binding().input(), operation).is_err(),
    350                 "{pointer}"
    351             );
    352         }
    353         let binding = request.binding();
    354         let other = WorkspaceBinding::from_authenticated_host(
    355             binding.input().clone(),
    356             binding.scope(),
    357             binding.actor(),
    358             "foreign-principal",
    359             binding.grant_revision(),
    360             binding.expires_at(),
    361             binding.observed_at(),
    362         )
    363         .unwrap();
    364         assert_eq!(
    365             same_binding(binding, &other),
    366             Err(OperationError::Unauthorized)
    367         );
    368         let foreign =
    369             PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5")
    370                 .unwrap();
    371         let actor = radroots_domain::ActorRef::new(
    372             foreign,
    373             binding.actor().role(),
    374             None,
    375             binding.actor().grant_id(),
    376         );
    377         assert_eq!(
    378             check_digest(&decoded, actor, None),
    379             Err(OperationError::Unauthorized)
    380         );
    381     }
    382 }