bitwarden_crypto/safe/
high_entropy_secret.rs1use std::str::FromStr;
10
11use bitwarden_encoding::{B64, FromStrVisitor};
12use bitwarden_sensitive_value::{ExposeSensitive, Sensitive, SensitiveSlice};
13use rand::Rng;
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16use zeroize::Zeroizing;
17
18const MIN_SECRET_LENGTH: usize = 16;
21
22pub trait HighEntropySecretSource {
34 fn provide_high_entropy_bytes(&self) -> SensitiveSlice<'_>;
36}
37
38#[derive(Clone)]
41pub struct HighEntropySecret {
42 secret: Zeroizing<Vec<u8>>,
43}
44
45impl HighEntropySecret {
46 pub fn from<T: HighEntropySecretSource>(secret: T) -> Self {
49 Self::from_internal(secret.provide_high_entropy_bytes().expose_owned())
52 }
53
54 pub(crate) fn from_internal(secret: &[u8]) -> Self {
58 Self {
59 secret: Zeroizing::new(secret.to_vec()),
60 }
61 }
62
63 pub fn make(desired_size: usize) -> Result<Self, HighEntropySecretError> {
68 if desired_size < MIN_SECRET_LENGTH {
69 return Err(HighEntropySecretError::TooShort);
70 }
71
72 let mut secret = Zeroizing::new(vec![0u8; desired_size]);
73 bitwarden_random::rng().fill_bytes(secret.as_mut_slice());
74 Ok(Self { secret })
75 }
76
77 #[allow(dead_code)]
81 pub(crate) fn as_bytes(&self) -> SensitiveSlice<'_> {
82 Sensitive::from(self.secret.as_slice())
83 }
84}
85
86impl FromStr for HighEntropySecret {
87 type Err = HighEntropySecretError;
88
89 fn from_str(s: &str) -> Result<Self, Self::Err> {
90 let bytes = B64::try_from(s).map_err(|_| HighEntropySecretError::Malformed)?;
91 if bytes.as_bytes().len() < MIN_SECRET_LENGTH {
92 return Err(HighEntropySecretError::TooShort);
93 }
94 Ok(Self::from_internal(bytes.as_bytes()))
95 }
96}
97
98impl From<HighEntropySecret> for String {
99 fn from(val: HighEntropySecret) -> Self {
100 B64::from(val.secret.as_slice()).to_string()
101 }
102}
103
104impl<'de> Deserialize<'de> for HighEntropySecret {
105 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106 where
107 D: serde::Deserializer<'de>,
108 {
109 deserializer.deserialize_str(FromStrVisitor::new())
110 }
111}
112
113impl Serialize for HighEntropySecret {
114 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
115 where
116 S: serde::Serializer,
117 {
118 serializer.serialize_str(&B64::from(self.secret.as_slice()).to_string())
119 }
120}
121
122impl std::fmt::Debug for HighEntropySecret {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 f.debug_struct("HighEntropySecret").finish()
126 }
127}
128
129#[derive(Debug, Error)]
131pub enum HighEntropySecretError {
132 #[error("Secret is too short")]
134 TooShort,
135 #[error("Secret is not valid base64")]
137 Malformed,
138}
139
140#[cfg(feature = "wasm")]
141#[wasm_bindgen::prelude::wasm_bindgen(typescript_custom_section)]
142const TS_CUSTOM_TYPES: &'static str = r#"
143export type HighEntropySecret = Tagged<string, "HighEntropySecret">;
144"#;
145
146bitwarden_ffi::impl_wire_string!(
147 HighEntropySecret,
148 parse = |wire: String| wire.parse(),
149 format = |secret: HighEntropySecret| B64::from(secret.secret.as_slice()).to_string(),
150);
151
152#[cfg(test)]
153mod tests {
154 use bitwarden_sensitive_value::ExposeSensitive;
155
156 use super::*;
157
158 #[test]
159 fn test_debug_does_not_leak_secret() {
160 let secret = HighEntropySecret::make(32).unwrap();
161 let debug = format!("{secret:?}");
162 assert_eq!(debug, "HighEntropySecret");
163 }
164
165 #[test]
166 fn test_make_rejects_secret_below_minimum_length() {
167 for size in 0..MIN_SECRET_LENGTH {
168 assert!(
169 matches!(
170 HighEntropySecret::make(size),
171 Err(HighEntropySecretError::TooShort)
172 ),
173 "expected size {size} to be rejected as too short"
174 );
175 }
176 }
177
178 #[test]
179 fn test_make_accepts_secret_at_minimum_length() {
180 let secret = HighEntropySecret::make(MIN_SECRET_LENGTH).unwrap();
181 assert_eq!(secret.as_bytes().expose_owned().len(), MIN_SECRET_LENGTH);
182 }
183
184 #[test]
185 fn test_make_produces_secret_of_requested_length() {
186 for size in [16, 32, 64, 128] {
187 let secret = HighEntropySecret::make(size).unwrap();
188 assert_eq!(secret.as_bytes().expose_owned().len(), size);
189 }
190 }
191
192 #[test]
193 fn test_make_produces_distinct_secrets() {
194 let first = HighEntropySecret::make(32).unwrap();
195 let second = HighEntropySecret::make(32).unwrap();
196 assert_ne!(
198 first.as_bytes().expose_owned(),
199 second.as_bytes().expose_owned()
200 );
201 }
202
203 #[test]
204 fn test_from_bytes_preserves_secret() {
205 let bytes = vec![7u8; 32];
206 let secret = HighEntropySecret::from_internal(bytes.as_slice());
207 assert_eq!(secret.as_bytes().expose_owned(), bytes.as_slice());
208 }
209
210 #[test]
211 fn test_from_bytes_accepts_secret_at_minimum_length() {
212 let secret = HighEntropySecret::from_internal(vec![1u8; MIN_SECRET_LENGTH].as_slice());
213 assert_eq!(secret.as_bytes().expose_owned().len(), MIN_SECRET_LENGTH);
214 }
215
216 #[test]
217 fn test_clone_preserves_secret_bytes() {
218 let secret = HighEntropySecret::make(32).unwrap();
219 let cloned = secret.clone();
220 assert_eq!(
221 secret.as_bytes().expose_owned(),
222 cloned.as_bytes().expose_owned()
223 );
224 }
225
226 #[test]
227 fn test_base64_round_trip_preserves_bytes() {
228 let secret = HighEntropySecret::make(32).unwrap();
229 let bytes = secret.as_bytes().expose_owned().to_vec();
230 let encoded = String::from(secret);
231 let decoded: HighEntropySecret = encoded.parse().unwrap();
232 assert_eq!(decoded.as_bytes().expose_owned(), bytes.as_slice());
233 }
234
235 #[test]
236 fn test_from_str_rejects_malformed_input() {
237 assert!(matches!(
238 "!!!not-base64!!!".parse::<HighEntropySecret>(),
239 Err(HighEntropySecretError::Malformed)
240 ));
241 }
242
243 #[test]
244 fn test_from_str_rejects_below_minimum_length() {
245 for byte_len in 0..MIN_SECRET_LENGTH {
248 let bytes = vec![0u8; byte_len];
249 let encoded = B64::from(bytes.as_slice()).to_string();
250 assert!(
251 matches!(
252 encoded.parse::<HighEntropySecret>(),
253 Err(HighEntropySecretError::TooShort)
254 ),
255 "expected decoded length {byte_len} to be rejected as too short"
256 );
257 }
258 }
259
260 #[test]
261 fn test_from_str_accepts_input_at_minimum_length() {
262 let bytes = vec![7u8; MIN_SECRET_LENGTH];
263 let encoded = B64::from(bytes.as_slice()).to_string();
264 let secret: HighEntropySecret = encoded
265 .parse()
266 .expect("input at minimum length is accepted");
267 assert_eq!(secret.as_bytes().expose_owned().len(), MIN_SECRET_LENGTH);
268 }
269
270 #[test]
271 fn test_serde_json_round_trip_preserves_bytes() {
272 let secret = HighEntropySecret::make(32).unwrap();
275 let bytes = secret.as_bytes().expose_owned().to_vec();
276 let json = serde_json::to_string(&secret).expect("serialize");
277 let round_tripped: HighEntropySecret = serde_json::from_str(&json).expect("deserialize");
278 assert_eq!(round_tripped.as_bytes().expose_owned(), bytes.as_slice());
279 }
280}