lib

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

permissions.rs (10079B)


      1 //! Bounded inventory permission claims. A qualified host must authenticate the
      2 //! protected grant and its current principal, expiry and revocation separately.
      3 use crate::workspace::WorkspaceError;
      4 use radroots_domain::PoolId;
      5 
      6 /// One explicit inventory capability; no signer or grant-administration right.
      7 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
      8 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
      9 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
     10 pub enum StockAction {
     11     ReadPools,
     12     ReadOperations,
     13     CreatePool,
     14     AddStock,
     15     RemoveStock,
     16     SpoilStock,
     17 }
     18 impl StockAction {
     19     const ALL: [Self; 6] = [
     20         Self::ReadPools,
     21         Self::ReadOperations,
     22         Self::CreatePool,
     23         Self::AddStock,
     24         Self::RemoveStock,
     25         Self::SpoilStock,
     26     ];
     27     const fn bit(self) -> u8 {
     28         match self {
     29             Self::ReadPools => 1,
     30             Self::ReadOperations => 2,
     31             Self::CreatePool => 4,
     32             Self::AddStock => 8,
     33             Self::RemoveStock => 16,
     34             Self::SpoilStock => 32,
     35         }
     36     }
     37 }
     38 /// Explicit all-pool selection or at most64 sorted unique private pool IDs.
     39 #[derive(Clone, Eq, PartialEq)]
     40 pub struct StockResources(Option<Box<[PoolId]>>);
     41 impl StockResources {
     42     /// Claims every pool in this selected seller namespace, without authority.
     43     pub const fn all_pools() -> Self {
     44         Self(None)
     45     }
     46     /// Requires canonical ascending unique IDs; empty never means all pools.
     47     pub fn pools(pools: Vec<PoolId>) -> Result<Self, WorkspaceError> {
     48         if pools.is_empty() || pools.len() > 64 || pools.windows(2).any(|v| v[0] >= v[1]) {
     49             return Err(WorkspaceError::InvalidInput);
     50         }
     51         Ok(Self(Some(pools.into_boxed_slice())))
     52     }
     53     /// Tests only the declared resource set, never authenticated permission.
     54     pub fn contains(&self, pool: PoolId) -> bool {
     55         self.0
     56             .as_ref()
     57             .is_none_or(|ids| ids.binary_search(&pool).is_ok())
     58     }
     59     /// None denotes the explicit all-pools variant; a selected set is nonempty.
     60     pub fn selected_pools(&self) -> Option<&[PoolId]> {
     61         self.0.as_deref()
     62     }
     63 }
     64 impl core::fmt::Debug for StockResources {
     65     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
     66         f.write_str("StockResources(<redacted>)")
     67     }
     68 }
     69 /// Action/resource claims for one namespace. Write scopes explicitly include
     70 /// pool and operation reads needed for checked effects and original recovery.
     71 /// This constructor grants no permission and cannot create or update a grant.
     72 #[derive(Clone, Eq, PartialEq)]
     73 pub struct StockGrantScope {
     74     resources: StockResources,
     75     mask: u8,
     76 }
     77 impl StockGrantScope {
     78     /// Requires nonempty actions in the declared enum order, without duplicates.
     79     pub fn new(
     80         resources: StockResources,
     81         actions: Vec<StockAction>,
     82     ) -> Result<Self, WorkspaceError> {
     83         if actions.is_empty()
     84             || actions.len() > 6
     85             || actions.windows(2).any(|v| v[0].bit() >= v[1].bit())
     86         {
     87             return Err(WorkspaceError::InvalidInput);
     88         }
     89         let mask = actions
     90             .into_iter()
     91             .fold(0, |mask, action| mask | action.bit());
     92         if mask & !3 != 0 && mask & 3 != 3 {
     93             return Err(WorkspaceError::InvalidInput);
     94         }
     95         Ok(Self { resources, mask })
     96     }
     97     /// Explicit full inventory claim; it includes no grant control or signing.
     98     pub const fn full_inventory() -> Self {
     99         Self {
    100             resources: StockResources::all_pools(),
    101             mask: 63,
    102         }
    103     }
    104     /// Canonical bounded declared actions.
    105     pub fn actions(&self) -> Vec<StockAction> {
    106         StockAction::ALL
    107             .into_iter()
    108             .filter(|action| self.allows_action(*action))
    109             .collect()
    110     }
    111     pub fn resources(&self) -> &StockResources {
    112         &self.resources
    113     }
    114     /// Evaluates only a declared action, without grant authentication.
    115     pub const fn allows_action(&self, action: StockAction) -> bool {
    116         self.mask & action.bit() != 0
    117     }
    118     /// Evaluates the complete declared action/resource pair.
    119     pub fn allows(&self, action: StockAction, pool: PoolId) -> bool {
    120         self.allows_action(action) && self.resources.contains(pool)
    121     }
    122 }
    123 impl core::fmt::Debug for StockGrantScope {
    124     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    125         f.write_str("StockGrantScope(<untrusted descriptor>)")
    126     }
    127 }
    128 
    129 #[cfg(feature = "serde")]
    130 mod serialization {
    131     use super::*;
    132     use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser::SerializeStruct};
    133     impl<'de> Deserialize<'de> for StockAction {
    134         fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
    135             struct Visitor;
    136             impl de::Visitor<'_> for Visitor {
    137                 type Value = StockAction;
    138                 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    139                     f.write_str("one exact stock action string")
    140                 }
    141                 fn visit_str<E: de::Error>(self, v: &str) -> Result<StockAction, E> {
    142                     match v {
    143                         "read_pools" => Ok(StockAction::ReadPools),
    144                         "read_operations" => Ok(StockAction::ReadOperations),
    145                         "create_pool" => Ok(StockAction::CreatePool),
    146                         "add_stock" => Ok(StockAction::AddStock),
    147                         "remove_stock" => Ok(StockAction::RemoveStock),
    148                         "spoil_stock" => Ok(StockAction::SpoilStock),
    149                         _ => Err(E::custom("invalid stock action")),
    150                     }
    151                 }
    152             }
    153             d.deserialize_str(Visitor)
    154         }
    155     }
    156     fn bounded<'de, D: Deserializer<'de>, T: Deserialize<'de>, const N: usize>(
    157         d: D,
    158     ) -> Result<Vec<T>, D::Error> {
    159         struct Visitor<T, const N: usize>(core::marker::PhantomData<T>);
    160         impl<'de, T: Deserialize<'de>, const N: usize> de::Visitor<'de> for Visitor<T, N> {
    161             type Value = Vec<T>;
    162             fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    163                 f.write_str("a bounded scope array")
    164             }
    165             fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<T>, A::Error> {
    166                 let mut values = Vec::new();
    167                 while let Some(value) = seq.next_element()? {
    168                     if values.len() == N {
    169                         return Err(de::Error::custom("scope array limit exceeded"));
    170                     }
    171                     values.push(value);
    172                 }
    173                 Ok(values)
    174             }
    175         }
    176         d.deserialize_seq(Visitor::<T, N>(core::marker::PhantomData))
    177     }
    178     fn object<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> {
    179         struct Visitor<T>(core::marker::PhantomData<T>);
    180         impl<'de, T: Deserialize<'de>> de::Visitor<'de> for Visitor<T> {
    181             type Value = T;
    182             fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    183                 f.write_str("a closed stock scope object")
    184             }
    185             fn visit_map<A: de::MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
    186                 T::deserialize(de::value::MapAccessDeserializer::new(map))
    187             }
    188         }
    189         d.deserialize_map(Visitor(core::marker::PhantomData))
    190     }
    191     impl Serialize for StockResources {
    192         fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    193             let mut wire =
    194                 s.serialize_struct("StockResources", if self.0.is_some() { 2 } else { 1 })?;
    195             if let Some(ids) = &self.0 {
    196                 wire.serialize_field("ids", ids)?;
    197             }
    198             wire.serialize_field(
    199                 "type",
    200                 if self.0.is_some() {
    201                     "pools"
    202                 } else {
    203                     "all_pools"
    204                 },
    205             )?;
    206             wire.end()
    207         }
    208     }
    209     impl<'de> Deserialize<'de> for StockResources {
    210         fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
    211             fn ids<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<PoolId>>, D::Error> {
    212                 bounded::<D, PoolId, 64>(d).map(Some)
    213             }
    214             #[derive(Deserialize)]
    215             #[serde(deny_unknown_fields)]
    216             struct Wire {
    217                 #[serde(rename = "type")]
    218                 kind: String,
    219                 #[serde(default, deserialize_with = "ids")]
    220                 ids: Option<Vec<PoolId>>,
    221             }
    222             let wire: Wire = object(d)?;
    223             match (wire.kind.as_str(), wire.ids) {
    224                 ("all_pools", None) => Ok(Self::all_pools()),
    225                 ("pools", Some(ids)) => Self::pools(ids).map_err(de::Error::custom),
    226                 _ => Err(de::Error::custom("invalid stock resources")),
    227             }
    228         }
    229     }
    230     impl Serialize for StockGrantScope {
    231         fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
    232             let mut wire = s.serialize_struct("StockGrantScope", 2)?;
    233             wire.serialize_field("actions", &self.actions())?;
    234             wire.serialize_field("resources", &self.resources)?;
    235             wire.end()
    236         }
    237     }
    238     impl<'de> Deserialize<'de> for StockGrantScope {
    239         fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
    240             fn actions<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<StockAction>, D::Error> {
    241                 bounded::<D, StockAction, 6>(d)
    242             }
    243             #[derive(Deserialize)]
    244             #[serde(deny_unknown_fields)]
    245             struct Wire {
    246                 resources: StockResources,
    247                 #[serde(deserialize_with = "actions")]
    248                 actions: Vec<StockAction>,
    249             }
    250             let wire: Wire = object(d)?;
    251             Self::new(wire.resources, wire.actions).map_err(de::Error::custom)
    252         }
    253     }
    254 }