apollo-redaction 0.2.0

Redaction utility for sensitive data in error messages, debug logs, etc.
Documentation
//! Serde serialization helpers.

use crate::Redacted;
use crate::RedactionStrategy;

/// A helper for serializing the [`Redacted`] representation of a value with [serde].
///
/// [`Redacted`] types themselves are not serializable. To serialize a struct containing
/// [`Redacted`] field types, the fields must be annotated with `#[serde(serialize_with)]`.
///
/// Use this one to use the _redacted_ representation for serialization.
///
/// ## Warning
///
/// By serializing the redacted representation, serialization and deserialization do **not**
/// round-trip. This can be unexpected depending on your use case. This is a soft recommendation to
/// only use this feature if you're not expecting to deserialize a struct that you previously
/// serialized.
///
/// ## Example
///
/// ```rust
/// use apollo_redaction::Redacted;
///
/// #[derive(serde::Serialize)]
/// struct DisplayRedacted {
///     #[serde(serialize_with = "apollo_redaction::ser::display_redacted")]
///     value: Redacted<String>,
/// }
///
/// let s = DisplayRedacted {
///     value: "top secret".to_string().into(),
/// };
/// assert_eq!(
///     serde_json::to_string(&s).unwrap(),
///     r#"{"value":"[REDACTED]"}"#,
/// );
/// ```
pub fn display_redacted<T, R, S>(value: &Redacted<T, R>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
    R: RedactionStrategy<T>,
{
    let redacted = value.to_string();
    serializer.serialize_str(&redacted)
}

/// A helper for serializing the underlying value of a [`Redacted`] value with [serde].
///
/// [`Redacted`] types themselves are not serializable. To serialize a struct containing
/// [`Redacted`] field types, the fields must be annotated with `#[serde(serialize_with)]`.
///
/// Use this one to use the _underlying_ representation for serialization.
///
/// ## Example
///
/// ```rust
/// use apollo_redaction::Redacted;
///
/// #[derive(serde::Serialize)]
/// struct DisplayRedacted {
///     #[serde(serialize_with = "apollo_redaction::ser::unredacted")]
///     value: Redacted<String>,
/// }
///
/// let s = DisplayRedacted {
///     value: "top secret".to_string().into(),
/// };
/// assert_eq!(
///     serde_json::to_string(&s).unwrap(),
///     r#"{"value":"top secret"}"#,
/// );
/// ```
pub fn unredacted<T, R, S>(value: &Redacted<T, R>, serializer: S) -> Result<S::Ok, S::Error>
where
    T: serde::Serialize,
    S: serde::Serializer,
{
    value.unredact().serialize(serializer)
}