secure_gate/cloneable/vec.rs
1use crate::Dynamic;
2use zeroize::Zeroize;
3
4/// Inner wrapper for a vector of bytes that can be safely cloned as a secret.
5///
6/// This struct wraps a `Vec<u8>` and implements the necessary traits for secure
7/// secret handling: `Clone` for duplication and `Zeroize` for secure memory wiping.
8/// The `zeroize(drop)` attribute ensures the vector contents are zeroized when
9/// this struct is dropped.
10#[derive(Clone, Zeroize)]
11#[zeroize(drop)]
12pub struct CloneableVecInner(pub Vec<u8>);
13
14impl crate::CloneSafe for CloneableVecInner {}
15
16/// A dynamically-sized vector of bytes wrapped as a cloneable secret.
17///
18/// This type provides a secure wrapper around a `Vec<u8>` that can be safely cloned
19/// while ensuring the underlying data is properly zeroized when no longer needed.
20/// Use this for variable-length secret data like encrypted payloads or keys.
21///
22/// # Examples
23///
24/// ```
25/// # #[cfg(feature = "zeroize")]
26/// # {
27/// use secure_gate::{CloneableVec, ExposeSecret};
28///
29/// // Create from a vector
30/// let data: CloneableVec = vec![1, 2, 3, 4].into();
31///
32/// // Create from a slice
33/// let data2: CloneableVec = b"hello world".as_slice().into();
34///
35/// // Access the inner vector
36/// let inner = &data.expose_secret().0;
37/// assert_eq!(inner.len(), 4);
38/// # }
39/// ```
40pub type CloneableVec = Dynamic<CloneableVecInner>;
41
42impl CloneableVec {
43 /// Construct a cloneable vec secret by building it in a closure.
44 ///
45 /// Same stack-minimization benefits as `CloneableString::init_with`.
46 ///
47 /// # Example
48 ///
49 /// ```
50 /// # #[cfg(feature = "zeroize")]
51 /// # {
52 /// use secure_gate::CloneableVec;
53 ///
54 /// let seed = CloneableVec::init_with(|| {
55 /// let mut v = vec![0u8; 32];
56 /// // Fill from some source...
57 /// v
58 /// });
59 /// # }
60 /// ```
61 #[must_use]
62 pub fn init_with<F>(constructor: F) -> Self
63 where
64 F: FnOnce() -> Vec<u8>,
65 {
66 let mut tmp = constructor();
67 let secret = Self::from(tmp.clone());
68 tmp.zeroize();
69 secret
70 }
71
72 /// Fallible version of `init_with`.
73 ///
74 /// Same stack-minimization benefits as `init_with`, but allows for construction
75 /// that may fail with an error. Useful when reading secrets from fallible sources
76 /// like files or network connections.
77 pub fn try_init_with<F, E>(constructor: F) -> Result<Self, E>
78 where
79 F: FnOnce() -> Result<Vec<u8>, E>,
80 {
81 let mut tmp = constructor()?;
82 let secret = Self::from(tmp.clone());
83 tmp.zeroize();
84 Ok(secret)
85 }
86}
87
88/// Wrap a `Vec<u8>` in a `CloneableVec`.
89impl From<Vec<u8>> for CloneableVec {
90 fn from(value: Vec<u8>) -> Self {
91 Dynamic::new(CloneableVecInner(value))
92 }
93}
94
95/// Wrap a byte slice in a `CloneableVec`.
96impl From<&[u8]> for CloneableVec {
97 fn from(value: &[u8]) -> Self {
98 Self::from(value.to_vec())
99 }
100}