lib

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

grant.rs (9143B)


      1 //! Shared bounded workspace grant codec; concrete host admission remains separate.
      2 use super::{AttachmentInput, AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceScope};
      3 use radroots_domain::{ActorRef, GrantId, Sequence, UnixSeconds, WorkspaceId};
      4 use serde::{Deserialize, Serialize};
      5 use sha2::{Digest, Sha256};
      6 use subtle::ConstantTimeEq;
      7 use zeroize::{Zeroize, Zeroizing};
      8 /// Maximum cleartext grant record, checked before decoding.
      9 pub const GRANT_BYTES_MAX: usize = 16 * 1024;
     10 /// Retained protected outbox context. A stock host needs its own qualified context.
     11 pub const GRANT_ENVELOPE_PURPOSE: &str = "radroots.workspace.grant";
     12 pub const GRANT_PAYLOAD_SCHEMA: &str = "radroots.workspace.grant.v1";
     13 pub fn grant_envelope_subject(workspace: WorkspaceId, grant: GrantId) -> String {
     14     // Both IDs have fixed-width canonical hexadecimal representations.
     15     format!("{workspace}{grant}")
     16 }
     17 /// Validated shared grant metadata and current credential/authorization rules.
     18 /// Hosts authenticate its envelope before decoding; this value alone is no authority.
     19 /// Raw Serde construction cannot bypass the bounded validating codec.
     20 pub struct WorkspaceGrant {
     21     wire: GrantWire,
     22 }
     23 #[derive(Serialize, Deserialize)]
     24 #[serde(deny_unknown_fields)]
     25 struct GrantWire {
     26     version: u8,
     27     scope: WorkspaceScope,
     28     input: AttachmentInput,
     29     actor: ActorRef,
     30     principal: String,
     31     revision: Sequence,
     32     expires_at: UnixSeconds,
     33     revoked: bool,
     34     verifier: [u8; 32],
     35 }
     36 impl Drop for WorkspaceGrant {
     37     fn drop(&mut self) {
     38         self.wire.verifier.zeroize();
     39     }
     40 }
     41 impl WorkspaceGrant {
     42     pub(super) const fn is_revoked(&self) -> bool {
     43         self.wire.revoked
     44     }
     45     pub(super) fn expires_at(&self) -> UnixSeconds {
     46         self.wire.expires_at
     47     }
     48     pub(super) fn input(&self) -> &AttachmentInput {
     49         &self.wire.input
     50     }
     51     pub fn new(
     52         input: AttachmentInput,
     53         actor: ActorRef,
     54         principal: String,
     55         expires_at: UnixSeconds,
     56         proof: &AttachmentProof,
     57     ) -> Result<Self, WorkspaceError> {
     58         Self::with_scope(
     59             input,
     60             WorkspaceScope::NewBuyerOutbox,
     61             actor,
     62             principal,
     63             expires_at,
     64             proof,
     65         )
     66     }
     67     pub(super) fn with_scope(
     68         input: AttachmentInput,
     69         scope: WorkspaceScope,
     70         actor: ActorRef,
     71         principal: String,
     72         expires_at: UnixSeconds,
     73         proof: &AttachmentProof,
     74     ) -> Result<Self, WorkspaceError> {
     75         let verifier = verifier(&input, scope, proof);
     76         let record = Self {
     77             wire: GrantWire {
     78                 version: 1,
     79                 scope,
     80                 input,
     81                 actor,
     82                 principal,
     83                 revision: Sequence::new(1).map_err(|_| WorkspaceError::InvalidInput)?,
     84                 expires_at,
     85                 revoked: false,
     86                 verifier,
     87             },
     88         };
     89         record.validate()?;
     90         Ok(record)
     91     }
     92     /// Decodes bounded metadata only, without authenticating an envelope or
     93     /// qualifying a host's supported scopes. Outbox hosts use `decode_outbox`.
     94     pub fn decode(bytes: &[u8]) -> Result<Self, WorkspaceError> {
     95         if bytes.len() > GRANT_BYTES_MAX {
     96             return Err(WorkspaceError::RecoveryRequired);
     97         }
     98         let record = Self {
     99             wire: serde_json::from_slice(bytes).map_err(|_| WorkspaceError::RecoveryRequired)?,
    100         };
    101         record
    102             .validate()
    103             .map_err(|_| WorkspaceError::RecoveryRequired)?;
    104         Ok(record)
    105     }
    106     /// Admits only the retained outbox scopes after envelope authentication.
    107     /// A structurally valid stock-owner claim cannot upgrade an outbox host.
    108     pub fn decode_outbox(bytes: &[u8]) -> Result<Self, WorkspaceError> {
    109         let record = Self::decode(bytes)?;
    110         if record.wire.scope == WorkspaceScope::SellerStockOwner {
    111             return Err(WorkspaceError::RecoveryRequired);
    112         }
    113         Ok(record)
    114     }
    115     /// Declared authenticated metadata; the concrete host still qualifies its scope.
    116     pub const fn scope(&self) -> WorkspaceScope {
    117         self.wire.scope
    118     }
    119     pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>, WorkspaceError> {
    120         self.validate()?;
    121         let bytes = Zeroizing::new(
    122             serde_json::to_vec(&self.wire).map_err(|_| WorkspaceError::StorageFailure)?,
    123         );
    124         if bytes.len() > GRANT_BYTES_MAX {
    125             return Err(WorkspaceError::InvalidInput);
    126         }
    127         Ok(bytes)
    128     }
    129     fn validate(&self) -> Result<(), WorkspaceError> {
    130         if self.wire.version != 1
    131             || self.wire.actor.role() != self.wire.scope.actor_role()
    132             || self.wire.actor.organization().is_some()
    133             || self.wire.actor.participant() != self.wire.input.participant()
    134             || self.wire.actor.grant_id() != Some(self.wire.input.grant_id())
    135             || self.wire.principal.is_empty()
    136             || self.wire.principal.len() > 128
    137             || self.wire.principal.chars().any(char::is_control)
    138             || self.wire.revision.get() == 0
    139             || self.wire.expires_at.get() == 0
    140         {
    141             return Err(WorkspaceError::InvalidInput);
    142         }
    143         Ok(())
    144     }
    145     pub fn authenticate(
    146         &self,
    147         input: &AttachmentInput,
    148         proof: &AttachmentProof,
    149         now: UnixSeconds,
    150     ) -> Result<WorkspaceBinding, WorkspaceError> {
    151         self.authenticate_retained_capture(input, proof)?;
    152         if self.wire.revoked {
    153             return Err(WorkspaceError::GrantRevoked);
    154         }
    155         if now.get() == 0 {
    156             return Err(WorkspaceError::Unavailable);
    157         }
    158         if self.wire.expires_at <= now {
    159             return Err(WorkspaceError::GrantExpired);
    160         }
    161         self.validate()?;
    162         WorkspaceBinding::from_authenticated_host(
    163             self.wire.input.clone(),
    164             self.wire.scope,
    165             self.wire.actor,
    166             self.wire.principal.clone(),
    167             self.wire.revision,
    168             self.wire.expires_at,
    169             now,
    170         )
    171     }
    172     /// Checks only the original protected credential and exact namespace scope.
    173     /// This path is exclusively for appending a matching already obtained
    174     /// artifact to an actual existing claim, never for new issuance or reads.
    175     pub fn authenticate_retained_capture(
    176         &self,
    177         input: &AttachmentInput,
    178         proof: &AttachmentProof,
    179     ) -> Result<(), WorkspaceError> {
    180         // Check the complete secret commitment before projecting detailed state.
    181         let observed = Zeroizing::new(verifier(&self.wire.input, self.wire.scope, proof));
    182         if !bool::from(observed.as_ref().ct_eq(&self.wire.verifier)) {
    183             return Err(WorkspaceError::Unauthorized);
    184         }
    185         if self.wire.input.workspace_id() != input.workspace_id() {
    186             return Err(WorkspaceError::WrongNamespace);
    187         }
    188         if self.wire.input.authority() != input.authority() {
    189             return Err(WorkspaceError::StaleAuthority);
    190         }
    191         if self.wire.input.checkpoint() != input.checkpoint() {
    192             return Err(WorkspaceError::StaleCheckpoint);
    193         }
    194         if &self.wire.input != input {
    195             return Err(WorkspaceError::Unauthorized);
    196         }
    197         self.validate()
    198     }
    199     pub fn revoke(&mut self) -> Result<(), WorkspaceError> {
    200         self.wire.revoked = true;
    201         self.wire.revision = Sequence::new(
    202             self.wire
    203                 .revision
    204                 .get()
    205                 .checked_add(1)
    206                 .ok_or(WorkspaceError::RecoveryRequired)?,
    207         )
    208         .map_err(|_| WorkspaceError::RecoveryRequired)?;
    209         Ok(())
    210     }
    211 }
    212 impl WorkspaceScope {
    213     pub(super) fn route_domain(self) -> &'static [u8] {
    214         match self {
    215             Self::NewBuyerOutbox => b"radroots.local_buyer_outbox.route.v1\0",
    216             Self::NewSellerOutbox => b"radroots.local_seller_outbox.route.v1\0",
    217             Self::SellerStockOwner => b"radroots.seller_stock.route.v1\0",
    218         }
    219     }
    220     pub(super) fn genesis_domain(self) -> &'static [u8] {
    221         match self {
    222             Self::NewBuyerOutbox => b"radroots.local_buyer_outbox.genesis.v1\0",
    223             Self::NewSellerOutbox => b"radroots.local_seller_outbox.genesis.v1\0",
    224             Self::SellerStockOwner => b"radroots.seller_stock.genesis.v1\0",
    225         }
    226     }
    227     fn credential_domain(self) -> &'static [u8] {
    228         match self {
    229             Self::NewBuyerOutbox => b"radroots.local_buyer_outbox.credential.v1\0",
    230             Self::NewSellerOutbox => b"radroots.local_seller_outbox.credential.v1\0",
    231             Self::SellerStockOwner => b"radroots.seller_stock.credential.v1\0",
    232         }
    233     }
    234 }
    235 fn verifier(input: &AttachmentInput, scope: WorkspaceScope, proof: &AttachmentProof) -> [u8; 32] {
    236     let mut digest = Sha256::new();
    237     digest.update(scope.credential_domain());
    238     digest.update(input.workspace_id().as_bytes());
    239     digest.update(input.grant_id().as_bytes());
    240     proof.with_secret(|secret| digest.update(secret));
    241     digest.finalize().into()
    242 }