lib

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

workspace.rs (13676B)


      1 //! Scoped workspace authentication primitives. These are storage operations,
      2 //! not an application-owned command, stock or recovery engine.
      3 
      4 use core::fmt;
      5 use radroots_domain::{
      6     ActorRef, AuthorityRef, CheckpointRef, GrantId, PublicKey, RouteDigest, Sequence, UnixSeconds,
      7     WorkspaceId,
      8 };
      9 use radroots_transport::{BoxFuture, host::HostBound};
     10 use zeroize::Zeroizing;
     11 
     12 /// Bounded grant metadata shared by qualified workspace hosts.
     13 #[cfg(feature = "protected_outbox")]
     14 pub mod grant;
     15 #[cfg(feature = "protected_outbox")]
     16 pub mod local_outbox;
     17 #[cfg(feature = "protected_outbox")]
     18 pub mod seller_stock;
     19 
     20 /// A fixed workspace boundary error; no path, credential, SQL or caller prose.
     21 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     22 #[non_exhaustive]
     23 pub enum WorkspaceError {
     24     /// Descriptor representation is invalid.
     25     InvalidInput,
     26     /// The selected protected provider or host is unavailable.
     27     Unavailable,
     28     /// The explicit private namespace cannot be safely opened.
     29     NamespaceUnavailable,
     30     /// Another writer retains this exact namespace.
     31     WriterActive,
     32     /// Namespace identity does not match the selected workspace.
     33     WrongNamespace,
     34     /// Protected state or creation evidence requires explicit recovery.
     35     RecoveryRequired,
     36     /// The presented protected credential does not authenticate its grant.
     37     Unauthorized,
     38     /// The current grant has expired.
     39     GrantExpired,
     40     /// The current grant has been revoked.
     41     GrantRevoked,
     42     /// The selected authority no longer matches.
     43     StaleAuthority,
     44     /// The required checkpoint does not match retained state.
     45     StaleCheckpoint,
     46     /// Admission is permanently closed.
     47     Closed,
     48     /// The bounded host queue or close-observer budget is exhausted.
     49     Capacity,
     50     /// Storage reports a known failure before confirmed completion.
     51     StorageFailure,
     52     /// Transaction completion is uncertain and must be reconciled.
     53     CommitUnknown,
     54 }
     55 impl WorkspaceError {
     56     /// Returns the stable source-redacted diagnostic code.
     57     pub const fn code(self) -> &'static str {
     58         match self {
     59             Self::InvalidInput => "invalid_input",
     60             Self::Unavailable => "workspace_unavailable",
     61             Self::NamespaceUnavailable => "namespace_unavailable",
     62             Self::WriterActive => "writer_active",
     63             Self::WrongNamespace => "wrong_workspace",
     64             Self::RecoveryRequired => "recovery_required",
     65             Self::Unauthorized => "unauthorized",
     66             Self::GrantExpired => "grant_expired",
     67             Self::GrantRevoked => "grant_revoked",
     68             Self::StaleAuthority => "stale_authority",
     69             Self::StaleCheckpoint => "stale_checkpoint",
     70             Self::Closed => "closed",
     71             Self::Capacity => "capacity_exhausted",
     72             Self::StorageFailure => "storage_failure",
     73             Self::CommitUnknown => "commit_unknown",
     74         }
     75     }
     76 }
     77 impl fmt::Display for WorkspaceError {
     78     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     79         f.write_str(self.code())
     80     }
     81 }
     82 impl core::error::Error for WorkspaceError {}
     83 
     84 /// An opaque protected bearer credential, independent of signer keys and grant
     85 /// selectors. No automatic serialization, cloning or secret diagnostics exist.
     86 pub struct AttachmentProof(Zeroizing<[u8; 32]>);
     87 impl AttachmentProof {
     88     /// Copies one qualified protected-channel value into a zeroizing owner.
     89     /// This checks only width; the persisted grant must authenticate it.
     90     pub fn from_protected_input(value: &[u8]) -> Result<Self, WorkspaceError> {
     91         let bytes = <[u8; 32]>::try_from(value).map_err(|_| WorkspaceError::InvalidInput)?;
     92         Ok(Self(Zeroizing::new(bytes)))
     93     }
     94     /// Exposes the fixed secret only for explicit backend authentication.
     95     pub fn with_secret<T>(&self, use_secret: impl FnOnce(&[u8; 32]) -> T) -> T {
     96         use_secret(&self.0)
     97     }
     98 }
     99 impl fmt::Debug for AttachmentProof {
    100     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    101         f.write_str("AttachmentProof(<redacted>)")
    102     }
    103 }
    104 
    105 /// Explicit selected endpoint, participant, grant and checkpoint data. This is
    106 /// never itself proof that the actor or endpoint is trusted.
    107 #[derive(Clone, Eq, PartialEq)]
    108 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    109 pub struct AttachmentInput {
    110     workspace_id: WorkspaceId,
    111     authority: AuthorityRef,
    112     participant: PublicKey,
    113     endpoint: Box<str>,
    114     endpoint_identity: PublicKey,
    115     grant_id: GrantId,
    116     checkpoint: CheckpointRef,
    117     route_digest: RouteDigest,
    118 }
    119 impl AttachmentInput {
    120     /// Captures explicit selected input; it performs no authentication or I/O.
    121     #[allow(clippy::too_many_arguments)]
    122     pub fn new(
    123         workspace_id: WorkspaceId,
    124         authority: AuthorityRef,
    125         participant: PublicKey,
    126         endpoint: impl Into<String>,
    127         endpoint_identity: PublicKey,
    128         grant_id: GrantId,
    129         checkpoint: CheckpointRef,
    130         route_digest: RouteDigest,
    131     ) -> Result<Self, WorkspaceError> {
    132         let endpoint = endpoint.into();
    133         if endpoint.is_empty() || endpoint.len() > 2048 || endpoint.chars().any(char::is_control) {
    134             return Err(WorkspaceError::InvalidInput);
    135         }
    136         Ok(Self {
    137             workspace_id,
    138             authority,
    139             participant,
    140             endpoint: endpoint.into_boxed_str(),
    141             endpoint_identity,
    142             grant_id,
    143             checkpoint,
    144             route_digest,
    145         })
    146     }
    147     /// Returns the selected workspace, independent of a cache generation.
    148     pub const fn workspace_id(&self) -> WorkspaceId {
    149         self.workspace_id
    150     }
    151     /// Returns the selected executor/epoch.
    152     pub const fn authority(&self) -> AuthorityRef {
    153         self.authority
    154     }
    155     /// Returns the claimed participant.
    156     pub const fn participant(&self) -> PublicKey {
    157         self.participant
    158     }
    159     /// Borrows the explicit selected endpoint.
    160     pub fn endpoint(&self) -> &str {
    161         &self.endpoint
    162     }
    163     /// Returns its pinned application identity.
    164     pub const fn endpoint_identity(&self) -> PublicKey {
    165         self.endpoint_identity
    166     }
    167     /// Returns the requested grant selector, never its credential.
    168     pub const fn grant_id(&self) -> GrantId {
    169         self.grant_id
    170     }
    171     /// Borrows the required checkpoint.
    172     pub const fn checkpoint(&self) -> &CheckpointRef {
    173         &self.checkpoint
    174     }
    175     /// Returns the exact selected route commitment.
    176     pub const fn route_digest(&self) -> RouteDigest {
    177         self.route_digest
    178     }
    179 }
    180 impl fmt::Debug for AttachmentInput {
    181     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    182         f.write_str("AttachmentInput(<untrusted descriptor>)")
    183     }
    184 }
    185 
    186 #[cfg(feature = "serde")]
    187 impl<'de> serde::Deserialize<'de> for AttachmentInput {
    188     fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
    189         #[derive(serde::Deserialize)]
    190         #[serde(deny_unknown_fields)]
    191         struct Raw {
    192             workspace_id: WorkspaceId,
    193             authority: AuthorityRef,
    194             participant: PublicKey,
    195             endpoint: String,
    196             endpoint_identity: PublicKey,
    197             grant_id: GrantId,
    198             checkpoint: CheckpointRef,
    199             route_digest: RouteDigest,
    200         }
    201         let raw = Raw::deserialize(deserializer)?;
    202         Self::new(
    203             raw.workspace_id,
    204             raw.authority,
    205             raw.participant,
    206             raw.endpoint,
    207             raw.endpoint_identity,
    208             raw.grant_id,
    209             raw.checkpoint,
    210             raw.route_digest,
    211         )
    212         .map_err(serde::de::Error::custom)
    213     }
    214 }
    215 
    216 /// A declared workspace permission scope. Metadata alone authenticates none
    217 /// of these permissions; the concrete selected host must qualify its grant.
    218 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    219 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    220 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    221 pub enum WorkspaceScope {
    222     /// New buyer inquiry and request outbox; no existing order history.
    223     NewBuyerOutbox,
    224     /// New seller public authoring and private communication outbox; no stock.
    225     NewSellerOutbox,
    226     /// Owner scope requiring the separate qualified seller stock namespace.
    227     /// Ordinary local outbox enrollment and opening must refuse this scope.
    228     SellerStockOwner,
    229 }
    230 impl WorkspaceScope {
    231     pub(crate) const fn actor_role(self) -> radroots_domain::ActorRole {
    232         match self {
    233             Self::NewBuyerOutbox => radroots_domain::ActorRole::Buyer,
    234             Self::NewSellerOutbox | Self::SellerStockOwner => radroots_domain::ActorRole::Seller,
    235         }
    236     }
    237 }
    238 
    239 /// A native/remote adapter's authenticated grant observation. It does not
    240 /// replace transaction-time checks and contains no bearer credential.
    241 #[derive(Clone, Eq, PartialEq)]
    242 pub struct WorkspaceBinding {
    243     input: AttachmentInput,
    244     scope: WorkspaceScope,
    245     actor: ActorRef,
    246     principal_id: Box<str>,
    247     grant_revision: Sequence,
    248     expires_at: UnixSeconds,
    249     observed_at: UnixSeconds,
    250     #[cfg(feature = "protected_outbox")]
    251     stock_authorization: Option<seller_stock::StockAuthorizationRef>,
    252 }
    253 impl WorkspaceBinding {
    254     /// Checks the internal binding of a trusted storage adapter's observation.
    255     /// Host implementations require actual authentication qualification; this
    256     /// constructor does not turn public metadata into an authenticated context.
    257     pub fn from_authenticated_host(
    258         input: AttachmentInput,
    259         scope: WorkspaceScope,
    260         actor: ActorRef,
    261         principal_id: impl Into<String>,
    262         grant_revision: Sequence,
    263         expires_at: UnixSeconds,
    264         observed_at: UnixSeconds,
    265     ) -> Result<Self, WorkspaceError> {
    266         let principal_id = principal_id.into();
    267         if actor.role() != scope.actor_role()
    268             || actor.organization().is_some()
    269             || actor.participant() != input.participant()
    270             || actor.grant_id() != Some(input.grant_id())
    271             || principal_id.is_empty()
    272             || principal_id.len() > 128
    273             || principal_id.chars().any(char::is_control)
    274             || grant_revision.get() == 0
    275             || expires_at.get() == 0
    276             || observed_at.get() == 0
    277             || expires_at <= observed_at
    278         {
    279             return Err(WorkspaceError::InvalidInput);
    280         }
    281         Ok(Self {
    282             input,
    283             scope,
    284             actor,
    285             principal_id: principal_id.into_boxed_str(),
    286             grant_revision,
    287             expires_at,
    288             observed_at,
    289             #[cfg(feature = "protected_outbox")]
    290             stock_authorization: None,
    291         })
    292     }
    293     /// Adds qualified stock-host observation metadata, never credential authority.
    294     #[cfg(feature = "protected_outbox")]
    295     pub fn with_stock_authorization(
    296         mut self,
    297         value: seller_stock::StockAuthorizationRef,
    298     ) -> Result<Self, WorkspaceError> {
    299         if self.scope != WorkspaceScope::SellerStockOwner {
    300             return Err(WorkspaceError::InvalidInput);
    301         }
    302         self.stock_authorization = Some(value);
    303         Ok(self)
    304     }
    305     #[cfg(feature = "protected_outbox")]
    306     pub const fn stock_authorization(&self) -> Option<seller_stock::StockAuthorizationRef> {
    307         self.stock_authorization
    308     }
    309     /// Borrows the exact authenticated selection.
    310     pub const fn input(&self) -> &AttachmentInput {
    311         &self.input
    312     }
    313     /// Returns the observed scope; signing custody adds no workspace permission.
    314     pub const fn scope(&self) -> WorkspaceScope {
    315         self.scope
    316     }
    317     /// Returns actor data from the persisted authenticated grant.
    318     pub const fn actor(&self) -> ActorRef {
    319         self.actor
    320     }
    321     /// Borrows the authenticated local device/principal audit identity.
    322     pub fn principal_id(&self) -> &str {
    323         &self.principal_id
    324     }
    325     /// Returns the observed revocation-sensitive grant revision.
    326     pub const fn grant_revision(&self) -> Sequence {
    327         self.grant_revision
    328     }
    329     /// Returns the observed grant expiry, without reading an ambient clock.
    330     pub const fn expires_at(&self) -> UnixSeconds {
    331         self.expires_at
    332     }
    333     /// Returns the actual adapter clock observation used to validate expiry.
    334     pub const fn observed_at(&self) -> UnixSeconds {
    335         self.observed_at
    336     }
    337 }
    338 impl fmt::Debug for WorkspaceBinding {
    339     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    340         f.write_str("WorkspaceBinding(<redacted>)")
    341     }
    342 }
    343 
    344 /// Backend-neutral current workspace authentication. Applications consume the
    345 /// concrete shared implementation; they do not supply command/stock semantics.
    346 pub trait WorkspaceStore: HostBound {
    347     /// Authenticates protected input against current persisted scope. The
    348     /// returned observation is rechecked at each authoritative transaction.
    349     /// The adapter owns its request credential through its safe completion;
    350     /// observers must not retain an attachment's credential root across await.
    351     fn authenticate(
    352         &self,
    353         input: AttachmentInput,
    354         proof: AttachmentProof,
    355     ) -> BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>>;
    356     /// Stops storage admission and observes actual backend closure.
    357     fn close_workspace(&self) -> BoxFuture<'_, Result<(), WorkspaceError>>;
    358 }
    359 
    360 /// The backend's explicit time source. Failure cannot become a valid timestamp.
    361 pub trait WorkspaceClock: HostBound {
    362     /// Returns a checked, positive current wall time or an unavailable result.
    363     fn now(&self) -> Result<UnixSeconds, WorkspaceError>;
    364 }