Skip to content

Commit

Permalink
feat: serde::redacted convenience serialize_with - serialize with…
Browse files Browse the repository at this point in the history
…out 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`
  • Loading branch information
eopb authored Jan 25, 2024
1 parent e06604f commit c576645
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ struct Payment {
}
```

If you would like to implement `Serialize` without exposing the `Secret` see [serde::redact_secret].

## Comparison with alternatives

### [secrecy](https://docs.rs/secrecy/latest/secrecy/)
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod error;
mod fake;
mod ops;
#[cfg(feature = "serde")]
mod serde;
pub mod serde;

#[cfg(feature = "serde")]
pub use crate::serde::expose_secret;
Expand Down
20 changes: 19 additions & 1 deletion src/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ impl<T: Serialize> SerializableSecret<T> for Option<Secret<T>> {
}
}

#[cfg(feature = "serde")]
/// Exposes a [Secret] for serialization.
///
/// For general-purpose secret exposing see [Secret::expose_secret].
///
/// See [module level documentation][crate] for usage example.
///
/// *This API requires the following crate features to be activated: `serde`*
#[cfg(feature = "serde")]
#[inline]
pub fn expose_secret<S: Serializer, T: Serialize>(
secret: &impl SerializableSecret<T>,
Expand All @@ -60,6 +60,24 @@ pub fn expose_secret<S: Serializer, T: Serialize>(
.serialize(serializer)
}

/// Serialize a redacted [Secret] without exposing the contained data.
///
/// The secret will be serialized as its [`Debug`] output.
/// Since the data is redacted, it is not possible to deserialize data serialized in this way.
///
/// This function is designed to be used with `#[serde(serialize_with)]` in the same way as
/// [serde::expose_secret][crate::serde::expose_secret].
///
/// *This API requires the following crate features to be activated: `serde`*
#[cfg(feature = "serde")]
#[inline]
pub fn redact_secret<S: Serializer, T>(
secret: &Secret<T>,
serializer: S,
) -> Result<S::Ok, S::Error> {
format!("{secret:?}").serialize(serializer)
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit c576645

Please sign in to comment.