helm-rs 0.1.1

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! How a Secret's values are masked in a diff: the hook ([`SecretMasker`]) and its presets.

use std::fmt;
use std::sync::Arc;

use super::ObjectId;

/// Which side of the diff a masked value is on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretSide {
    /// The value in the old manifest, which differs from the new one or has no counterpart there.
    Before,
    /// The value in the new manifest, which differs from the old one or has no counterpart there.
    After,
    /// The value is the same on both sides. A key that is absent on one side counts as an empty
    /// value there, as in the plugin, so an empty value without a counterpart is also `Both`.
    Both,
}

/// One value of a Secret about to be masked, with everything a masking policy can use.
///
/// `bytes` is the **plaintext**: the base64-decoded `data` entry, or the `stringData` entry, after
/// the API server's `stringData` merge.
#[derive(Debug, Clone, Copy)]
pub struct MaskedValue<'a> {
    /// The Secret.
    pub id: &'a ObjectId,
    /// The key under `data` or `stringData`.
    pub key: &'a str,
    /// Which side this value is on.
    pub side: SecretSide,
    /// The plaintext of this side's value.
    pub bytes: &'a [u8],
}

/// The policy that turns one Secret value into the text a diff shows.
///
/// The closure receives the plaintext (see [`MaskedValue`]), and whatever it returns appears
/// verbatim in the text diff and in [`FieldChange::before`](super::FieldChange) and `after`, so
/// it must not contain the value unless that is the intent. It is called once per value per
/// side; a value that is equal on both sides is masked once and the result used on both. It is
/// never asked whether a value changed: that is decided on the real values, so a policy that
/// returns the same text for different values still yields a changed field (with equal
/// `before` and `after`, and no changed line in the text).
///
/// ```
/// use helm_rs::manifest::{DiffOptions, SecretMasker, SecretSide};
///
/// let options = DiffOptions::builder()
///     .mask_secrets(|value| match value.side {
///         SecretSide::Both => "unchanged".to_owned(),
///         _ => format!("{} bytes", value.bytes.len()),
///     })
///     .build();
/// let _ = SecretMasker::opaque();
/// # let _ = options;
/// ```
#[derive(Clone)]
pub struct SecretMasker(Arc<dyn Fn(&MaskedValue<'_>) -> String + Send + Sync>);

impl SecretMasker {
    /// A masker from a closure.
    pub fn new(mask: impl Fn(&MaskedValue<'_>) -> String + Send + Sync + 'static) -> Self {
        Self(Arc::new(mask))
    }

    /// The helm-diff plugin's markers (`redactSecrets`, the default): `REDACTED # (n bytes)` for
    /// a value equal on both sides, `-------- # (n bytes)` before and `++++++++ # (n bytes)`
    /// after. They reveal the length.
    #[must_use]
    pub fn helm_diff() -> Self {
        Self::new(|value| {
            let prefix = match value.side {
                SecretSide::Both => "REDACTED",
                SecretSide::Before => "--------",
                SecretSide::After => "++++++++",
            };

            format!("{prefix} # ({} bytes)", value.bytes.len())
        })
    }

    /// Markers that reveal neither content nor length: `[secret]` for a value equal on both
    /// sides, `[secret, old]` and `[secret, new]` for one that differs. The side in the marker is
    /// what keeps a change visible in the text diff, and it says nothing else.
    #[must_use]
    pub fn opaque() -> Self {
        Self::new(|value| {
            match value.side {
                SecretSide::Both => "[secret]",
                SecretSide::Before => "[secret, old]",
                SecretSide::After => "[secret, new]",
            }
            .to_owned()
        })
    }

    /// Masks one value.
    pub(super) fn mask(&self, value: &MaskedValue<'_>) -> String {
        (self.0)(value)
    }
}

impl fmt::Debug for SecretMasker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("SecretMasker(..)")
    }
}

impl PartialEq for SecretMasker {
    /// Two maskers are equal when they are the same closure (clones of one another).
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Eq for SecretMasker {}