From aea9ccf930cb3ba2ca84e76091478393a6fef358 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Wed, 9 Oct 2024 12:25:26 -0600 Subject: [PATCH] secrecy: make integer primitive `SecretSlice`s cloneable Impls `Clone` for `SecretSlice` when the `S` generic type is `CloneableSecret + Zeroize`. As originally requested in #1070, also marks the integer primitive types as `CloneableSecret`, which makes it possible to clone a `SecretSlice`. Closes #1233 --- secrecy/src/lib.rs | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/secrecy/src/lib.rs b/secrecy/src/lib.rs index dc1d18a8..97e4ecb2 100644 --- a/secrecy/src/lib.rs +++ b/secrecy/src/lib.rs @@ -184,6 +184,28 @@ where } } +impl Clone for SecretSlice +where + S: CloneableSecret + Zeroize, + [S]: Zeroize, +{ + fn clone(&self) -> Self { + SecretBox { + inner_secret: Vec::from(&*self.inner_secret).into_boxed_slice() + } + } +} + +impl Default for SecretSlice +where + S: Zeroize, + [S]: Zeroize, +{ + fn default() -> Self { + Vec::new().into() + } +} + /// Secret string type. /// /// This is a type alias for [`SecretBox`] which supports some helpful trait impls. @@ -206,7 +228,7 @@ impl Clone for SecretString { } impl Default for SecretString { - fn default() -> SecretString { + fn default() -> Self { String::default().into() } } @@ -214,6 +236,22 @@ impl Default for SecretString { /// Marker trait for secrets which are allowed to be cloned pub trait CloneableSecret: Clone + Zeroize {} +// Mark integer primitives as cloneable secrets + +impl CloneableSecret for i8 {} +impl CloneableSecret for i16 {} +impl CloneableSecret for i32 {} +impl CloneableSecret for i64 {} +impl CloneableSecret for i128 {} +impl CloneableSecret for isize {} + +impl CloneableSecret for u8 {} +impl CloneableSecret for u16 {} +impl CloneableSecret for u32 {} +impl CloneableSecret for u64 {} +impl CloneableSecret for u128 {} +impl CloneableSecret for usize {} + /// Expose a reference to an inner secret pub trait ExposeSecret { /// Expose secret: this is the only method providing access to a secret.