lib

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

wrapping.rs (9348B)


      1 //! Data-key wrapping contracts.
      2 
      3 use crate::SecretRef;
      4 use crate::context::EnvelopeContext;
      5 use crate::envelope::LegacyV1ResealAuthority;
      6 use crate::error::Error;
      7 use alloc::boxed::Box;
      8 use alloc::vec::Vec;
      9 use core::fmt;
     10 use core::future::Future;
     11 use core::pin::Pin;
     12 use zeroize::Zeroizing;
     13 
     14 /// Maximum plaintext accepted by the generic wrapping boundary.
     15 pub const SECRET_MATERIAL_MAX_BYTES: usize = 64 * 1024;
     16 /// Maximum protected value accepted by the generic wrapping boundary.
     17 pub const WRAPPED_SECRET_MAX_BYTES: usize = 128 * 1024;
     18 
     19 /// Native providers retain thread-safe ownership; browser providers may retain
     20 /// local objects. This marker grants no residency or security capability.
     21 #[cfg(not(target_arch = "wasm32"))]
     22 pub trait HostBound: Send + Sync {}
     23 #[cfg(not(target_arch = "wasm32"))]
     24 impl<T: Send + Sync + ?Sized> HostBound for T {}
     25 /// Native providers retain thread-safe ownership; browser providers may retain
     26 /// local objects. This marker grants no residency or security capability.
     27 #[cfg(target_arch = "wasm32")]
     28 pub trait HostBound {}
     29 #[cfg(target_arch = "wasm32")]
     30 impl<T: ?Sized> HostBound for T {}
     31 
     32 /// Native provider future without a prescribed executor.
     33 #[cfg(not(target_arch = "wasm32"))]
     34 pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
     35 /// Browser-local provider future without a prescribed executor.
     36 #[cfg(target_arch = "wasm32")]
     37 pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
     38 
     39 /// Opaque, single-owner plaintext material that zeroizes on drop.
     40 ///
     41 /// This type never implements `Clone` or `Serialize`, and its diagnostics are
     42 /// always redacted. Callers must opt in to the narrow [`Self::expose_secret`]
     43 /// scope when invoking cryptographic code.
     44 ///
     45 /// ```compile_fail
     46 /// use radroots_secrets::wrapping::SecretMaterial;
     47 ///
     48 /// let material = SecretMaterial::from_slice(b"secret")?;
     49 /// let _duplicate = material.clone();
     50 /// # Ok::<(), radroots_secrets::Error>(())
     51 /// ```
     52 ///
     53 /// ```compile_fail
     54 /// use radroots_secrets::wrapping::SecretMaterial;
     55 ///
     56 /// let material = SecretMaterial::from_slice(b"secret")?;
     57 /// let _json = serde_json::to_string(&material)?;
     58 /// # Ok::<(), Box<dyn std::error::Error>>(())
     59 /// ```
     60 pub struct SecretMaterial(Zeroizing<Box<[u8]>>);
     61 
     62 impl SecretMaterial {
     63     /// Copies caller-supplied material into a zeroizing owner.
     64     pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
     65         if bytes.is_empty() || bytes.len() > SECRET_MATERIAL_MAX_BYTES {
     66             return Err(Error::InvalidSecretLength {
     67                 actual_bytes: bytes.len(),
     68                 max_bytes: SECRET_MATERIAL_MAX_BYTES,
     69             });
     70         }
     71         Ok(Self(Zeroizing::new(Box::from(bytes))))
     72     }
     73 
     74     pub(crate) fn from_owned(bytes: Vec<u8>) -> Result<Self, Error> {
     75         let bytes = Zeroizing::new(bytes);
     76         Self::from_slice(bytes.as_slice())
     77     }
     78 
     79     /// Exposes plaintext only for the lifetime of an explicit closure call.
     80     pub fn expose_secret<T>(&self, use_secret: impl FnOnce(&[u8]) -> T) -> T {
     81         use_secret(&self.0[..])
     82     }
     83 
     84     /// Returns the plaintext length without exposing its contents.
     85     #[must_use]
     86     pub fn len(&self) -> usize {
     87         self.0.len()
     88     }
     89 
     90     /// Returns whether the value is empty.
     91     #[must_use]
     92     pub fn is_empty(&self) -> bool {
     93         self.0.is_empty()
     94     }
     95 }
     96 
     97 impl fmt::Debug for SecretMaterial {
     98     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     99         formatter.write_str("SecretMaterial(<redacted>)")
    100     }
    101 }
    102 
    103 /// Opaque provider-wrapped material safe for persistence but not diagnostics.
    104 #[derive(Clone, PartialEq, Eq)]
    105 pub struct WrappedSecret(Vec<u8>);
    106 
    107 impl WrappedSecret {
    108     /// Validates and owns provider-wrapped material.
    109     pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self, Error> {
    110         let bytes = bytes.into();
    111         if bytes.is_empty() || bytes.len() > WRAPPED_SECRET_MAX_BYTES {
    112             return Err(Error::InvalidWrappedLength {
    113                 actual_bytes: bytes.len(),
    114                 max_bytes: WRAPPED_SECRET_MAX_BYTES,
    115             });
    116         }
    117         Ok(Self(bytes))
    118     }
    119 
    120     /// Returns the wrapped representation for envelope persistence.
    121     #[must_use]
    122     pub fn as_bytes(&self) -> &[u8] {
    123         self.0.as_slice()
    124     }
    125 }
    126 
    127 impl fmt::Debug for WrappedSecret {
    128     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    129         formatter.write_str("WrappedSecret(<redacted>)")
    130     }
    131 }
    132 
    133 /// Borrowed input for one key-wrapping operation.
    134 #[derive(Debug, Clone, Copy)]
    135 pub struct WrapRequest<'a> {
    136     reference: &'a SecretRef,
    137     context: &'a EnvelopeContext,
    138     plaintext: &'a SecretMaterial,
    139 }
    140 
    141 impl<'a> WrapRequest<'a> {
    142     /// Creates an explicit wrapping request.
    143     #[must_use]
    144     pub const fn new(
    145         reference: &'a SecretRef,
    146         context: &'a EnvelopeContext,
    147         plaintext: &'a SecretMaterial,
    148     ) -> Self {
    149         Self {
    150             reference,
    151             context,
    152             plaintext,
    153         }
    154     }
    155 
    156     /// Returns the provider capability reference.
    157     #[must_use]
    158     pub const fn reference(&self) -> &'a SecretRef {
    159         self.reference
    160     }
    161 
    162     /// Returns the independently validated semantic wrapping authority.
    163     #[must_use]
    164     pub const fn context(&self) -> &'a EnvelopeContext {
    165         self.context
    166     }
    167 
    168     /// Returns the single-owner plaintext wrapper.
    169     #[must_use]
    170     pub const fn plaintext(&self) -> &'a SecretMaterial {
    171         self.plaintext
    172     }
    173 }
    174 
    175 /// Borrowed input for one key-unwrapping operation.
    176 #[derive(Debug, Clone, Copy)]
    177 pub struct UnwrapRequest<'a> {
    178     reference: &'a SecretRef,
    179     context: &'a EnvelopeContext,
    180     wrapped: &'a WrappedSecret,
    181 }
    182 
    183 /// Capability-gated input for migration-only v1 key unwrapping.
    184 pub struct LegacyV1UnwrapRequest<'a> {
    185     reference: &'a SecretRef,
    186     wrapped: &'a WrappedSecret,
    187     _authority: &'a LegacyV1ResealAuthority,
    188 }
    189 
    190 impl<'a> LegacyV1UnwrapRequest<'a> {
    191     pub(crate) const fn new(
    192         reference: &'a SecretRef,
    193         wrapped: &'a WrappedSecret,
    194         authority: &'a LegacyV1ResealAuthority,
    195     ) -> Self {
    196         Self {
    197             reference,
    198             wrapped,
    199             _authority: authority,
    200         }
    201     }
    202 
    203     /// Returns the exact legacy provider capability reference.
    204     #[must_use]
    205     pub const fn reference(&self) -> &'a SecretRef {
    206         self.reference
    207     }
    208 
    209     /// Returns the exact provider-wrapped v1 value.
    210     #[must_use]
    211     pub const fn wrapped(&self) -> &'a WrappedSecret {
    212         self.wrapped
    213     }
    214 }
    215 
    216 impl fmt::Debug for LegacyV1UnwrapRequest<'_> {
    217     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    218         formatter.write_str("LegacyV1UnwrapRequest(<redacted>)")
    219     }
    220 }
    221 
    222 impl<'a> UnwrapRequest<'a> {
    223     /// Creates an explicit unwrapping request.
    224     #[must_use]
    225     pub const fn new(
    226         reference: &'a SecretRef,
    227         context: &'a EnvelopeContext,
    228         wrapped: &'a WrappedSecret,
    229     ) -> Self {
    230         Self {
    231             reference,
    232             context,
    233             wrapped,
    234         }
    235     }
    236 
    237     /// Returns the provider capability reference.
    238     #[must_use]
    239     pub const fn reference(&self) -> &'a SecretRef {
    240         self.reference
    241     }
    242 
    243     /// Returns the independently validated semantic unwrapping authority.
    244     #[must_use]
    245     pub const fn context(&self) -> &'a EnvelopeContext {
    246         self.context
    247     }
    248 
    249     /// Returns the provider-wrapped value.
    250     #[must_use]
    251     pub const fn wrapped(&self) -> &'a WrappedSecret {
    252         self.wrapped
    253     }
    254 }
    255 
    256 /// Executor-neutral, dyn-compatible data-key wrapping.
    257 pub trait KeyWrapping: HostBound {
    258     /// Wraps explicit caller-owned plaintext for the selected reference.
    259     fn wrap<'a>(&'a self, request: WrapRequest<'a>) -> BoxFuture<'a, Result<WrappedSecret, Error>>;
    260 
    261     /// Unwraps provider-owned protected material into a zeroizing owner.
    262     fn unwrap<'a>(
    263         &'a self,
    264         request: UnwrapRequest<'a>,
    265     ) -> BoxFuture<'a, Result<SecretMaterial, Error>>;
    266 
    267     /// Unwraps v1 material only when the envelope migration boundary grants authority.
    268     fn unwrap_legacy_v1<'a>(
    269         &'a self,
    270         _request: LegacyV1UnwrapRequest<'a>,
    271     ) -> BoxFuture<'a, Result<SecretMaterial, Error>> {
    272         Box::pin(async { Err(Error::LegacyEnvelopeDenied) })
    273     }
    274 }
    275 
    276 #[cfg(test)]
    277 mod tests {
    278     use super::{
    279         SECRET_MATERIAL_MAX_BYTES, SecretMaterial, WRAPPED_SECRET_MAX_BYTES, WrappedSecret,
    280     };
    281     use alloc::vec;
    282     use alloc::vec::Vec;
    283     use zeroize::Zeroize;
    284 
    285     #[test]
    286     fn owned_plaintext_buffer_zeroizes_in_place() {
    287         let mut material =
    288             SecretMaterial::from_slice(b"owned plaintext sentinel").expect("valid secret material");
    289         let original_len = material.len();
    290         material.0.zeroize();
    291         assert_eq!(material.len(), original_len);
    292         material.expose_secret(|bytes| assert!(bytes.iter().all(|byte| *byte == 0)));
    293     }
    294 
    295     #[test]
    296     fn rejected_owned_plaintext_is_wrapped_before_validation() {
    297         assert!(SecretMaterial::from_owned(Vec::new()).is_err());
    298         assert!(SecretMaterial::from_slice(&vec![0; SECRET_MATERIAL_MAX_BYTES + 1]).is_err());
    299         assert!(WrappedSecret::from_bytes(Vec::new()).is_err());
    300         assert!(WrappedSecret::from_bytes(vec![0; WRAPPED_SECRET_MAX_BYTES + 1]).is_err());
    301     }
    302 }