Skip to content

Commit c576645

Browse files
authored
feat: serde::redacted convenience serialize_with - serialize without exposing (#46)
* feat: `serde::redacted` convenience `serialize_with` - serialize without exposing # Todo - [ ] Document function with rustdoc - [ ] Update serde section in `README.md` * Update documentation * Rename `redacted` -> `redact_secret`
1 parent e06604f commit c576645

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ struct Payment {
6666
}
6767
```
6868

69+
If you would like to implement `Serialize` without exposing the `Secret` see [serde::redact_secret].
70+
6971
## Comparison with alternatives
7072

7173
### [secrecy](https://docs.rs/secrecy/latest/secrecy/)

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ mod error;
99
mod fake;
1010
mod ops;
1111
#[cfg(feature = "serde")]
12-
mod serde;
12+
pub mod serde;
1313

1414
#[cfg(feature = "serde")]
1515
pub use crate::serde::expose_secret;

src/serde.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,14 @@ impl<T: Serialize> SerializableSecret<T> for Option<Secret<T>> {
4242
}
4343
}
4444

45-
#[cfg(feature = "serde")]
4645
/// Exposes a [Secret] for serialization.
4746
///
4847
/// For general-purpose secret exposing see [Secret::expose_secret].
4948
///
5049
/// See [module level documentation][crate] for usage example.
5150
///
5251
/// *This API requires the following crate features to be activated: `serde`*
52+
#[cfg(feature = "serde")]
5353
#[inline]
5454
pub fn expose_secret<S: Serializer, T: Serialize>(
5555
secret: &impl SerializableSecret<T>,
@@ -60,6 +60,24 @@ pub fn expose_secret<S: Serializer, T: Serialize>(
6060
.serialize(serializer)
6161
}
6262

63+
/// Serialize a redacted [Secret] without exposing the contained data.
64+
///
65+
/// The secret will be serialized as its [`Debug`] output.
66+
/// Since the data is redacted, it is not possible to deserialize data serialized in this way.
67+
///
68+
/// This function is designed to be used with `#[serde(serialize_with)]` in the same way as
69+
/// [serde::expose_secret][crate::serde::expose_secret].
70+
///
71+
/// *This API requires the following crate features to be activated: `serde`*
72+
#[cfg(feature = "serde")]
73+
#[inline]
74+
pub fn redact_secret<S: Serializer, T>(
75+
secret: &Secret<T>,
76+
serializer: S,
77+
) -> Result<S::Ok, S::Error> {
78+
format!("{secret:?}").serialize(serializer)
79+
}
80+
6381
#[cfg(test)]
6482
mod tests {
6583
use super::*;

0 commit comments

Comments
 (0)