helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! Hiding or decoding Secret values (`diff/diff.go` `redactSecrets`, `decodeSecrets`).

use std::collections::BTreeMap;

use base64::{Engine, engine::general_purpose::STANDARD};
use serde_json::{Map, Value};

use super::object::View;
use super::{
    FieldChange, FieldPath, MaskedValue, ObjectId, PathSegment, SecretMasker, SecretMode,
    SecretSide,
};
use crate::manifest::Error;

/// The Secret's values after the API server's `stringData` merge (`preHandleSecrets`): `data`
/// base64 decoded, then `stringData` on top. A value that is not valid base64 counts as its own
/// text, and anything that is not a string as its JSON, so that comparing and measuring never
/// fail; the bytes are only compared and counted, never shown.
fn secret_data(value: &Value) -> BTreeMap<String, Vec<u8>> {
    let mut data = BTreeMap::new();

    if let Some(Value::Object(entries)) = value.get("data") {
        for (key, entry) in entries {
            let bytes = entry.as_str().map_or_else(
                || entry.to_string().into_bytes(),
                |text| {
                    STANDARD
                        .decode(text)
                        .unwrap_or_else(|_| text.as_bytes().to_vec())
                },
            );

            data.insert(key.clone(), bytes);
        }
    }

    if let Some(Value::Object(entries)) = value.get("stringData") {
        for (key, entry) in entries {
            let bytes = entry.as_str().map_or_else(
                || entry.to_string().into_bytes(),
                |text| text.as_bytes().to_vec(),
            );

            data.insert(key.clone(), bytes);
        }
    }

    data
}

/// The top-level keys of a typed Secret in the order Kubernetes serialises them (`v1.Secret`).
const SECRET_ORDER: [&str; 7] = [
    "apiVersion",
    "kind",
    "metadata",
    "immutable",
    "data",
    "stringData",
    "type",
];
/// The `metadata` keys in the order Kubernetes serialises them (`metav1.ObjectMeta`).
const METADATA_ORDER: [&str; 14] = [
    "name",
    "generateName",
    "namespace",
    "uid",
    "resourceVersion",
    "generation",
    "creationTimestamp",
    "deletionTimestamp",
    "deletionGracePeriodSeconds",
    "labels",
    "annotations",
    "ownerReferences",
    "finalizers",
    "managedFields",
];

/// The Secret as a YAML mapping with its keys in the order the plugin prints them, which is
/// the typed Secret's, not alphabetical (the plugin re-encodes a `v1.Secret`); keys outside that
/// order follow sorted.
fn ordered(value: &Value) -> Result<serde_norway::Value, Error> {
    let to_yaml = |value: &Value| {
        serde_norway::to_value(value).map_err(|error| Error::Serialize(error.to_string()))
    };
    let Value::Object(top) = value else {
        return to_yaml(value);
    };
    let mut mapping = serde_norway::Mapping::new();
    let keys = SECRET_ORDER.iter().copied().chain(
        top.keys()
            .map(String::as_str)
            .filter(|key| !SECRET_ORDER.contains(key)),
    );

    for key in keys.filter(|key| top.contains_key(*key)) {
        let entry = if let (Some(Value::Object(metadata)), "metadata") = (top.get(key), key) {
            let mut inner = serde_norway::Mapping::new();
            let names = METADATA_ORDER.iter().copied().chain(
                metadata
                    .keys()
                    .map(String::as_str)
                    .filter(|name| !METADATA_ORDER.contains(name)),
            );

            for name in names.filter(|name| metadata.contains_key(*name)) {
                inner.insert(name.into(), to_yaml(&metadata[name])?);
            }

            serde_norway::Value::Mapping(inner)
        } else {
            to_yaml(&top[key])?
        };

        mapping.insert(key.into(), entry);
    }

    Ok(serde_norway::Value::Mapping(mapping))
}

/// The marker for `data` or `stringData` that is not a mapping.
const MALFORMED: &str = "[malformed secret data]";

/// Whether `data` or `stringData` is present but not a mapping.
fn is_malformed(value: &Value) -> bool {
    ["data", "stringData"].iter().any(|key| {
        value
            .get(key)
            .is_some_and(|entry| !entry.is_object() && !entry.is_null())
    })
}

/// Replaces the Secret's `data` and `stringData` in `view`, then renders its text again with
/// the leading `# Source:` comment kept. `entries` are the new `data` (or `stringData` when
/// `decoded`); with none, malformed data leaves its marker and anything else leaves neither key.
fn rewrite(view: &mut View, entries: Map<String, Value>, decoded: bool) -> Result<(), Error> {
    let key = if decoded { "stringData" } else { "data" };
    let malformed = is_malformed(&view.value);

    if let Value::Object(object) = &mut view.value {
        object.remove("data");
        object.remove("stringData");

        if !entries.is_empty() {
            object.insert(key.to_owned(), Value::Object(entries));
        } else if malformed {
            object.insert(key.to_owned(), Value::String(MALFORMED.to_owned()));
        }
    }

    view.render(&ordered(&view.value)?)
}

/// Applies `mode` to the two sides of one Secret, either of which may be missing. Nothing
/// secret is kept in the views. Returns the keys present on both sides whose real values differ:
/// the caller reports them as changed even when the mask makes them look equal.
pub(super) fn apply(
    mode: &SecretMode,
    id: &ObjectId,
    old: Option<&mut View>,
    new: Option<&mut View>,
) -> Result<Vec<String>, Error> {
    let old_data = old.as_deref().map(|view| secret_data(&view.value));
    let new_data = new.as_deref().map(|view| secret_data(&view.value));
    let differing = match (&old_data, &new_data) {
        (Some(old), Some(new)) => old
            .iter()
            .filter(|(key, bytes)| new.get(*key).is_some_and(|other| other != *bytes))
            .map(|(key, _)| key.clone())
            .collect(),
        _ => Vec::new(),
    };
    let helm_diff;
    let masker = match mode {
        SecretMode::Show => return Ok(Vec::new()),
        SecretMode::Mask(masker) => Some(masker),
        SecretMode::Redact => {
            helm_diff = SecretMasker::helm_diff();

            Some(&helm_diff)
        }
        SecretMode::Decode => None,
    };
    let mut both = BTreeMap::new();

    for (view, own, other, side) in [
        (old, &old_data, &new_data, SecretSide::Before),
        (new, &new_data, &old_data, SecretSide::After),
    ] {
        let (Some(view), Some(own)) = (view, own) else {
            continue;
        };
        let entries = own
            .iter()
            .map(|(key, bytes)| {
                let same = other.as_ref().is_some_and(|other| {
                    other.get(key).map_or(&[][..], Vec::as_slice) == bytes.as_slice()
                });
                let text = match masker {
                    None => String::from_utf8_lossy(bytes).into_owned(),
                    Some(masker) => {
                        let value = |side| MaskedValue {
                            id,
                            key,
                            side,
                            bytes,
                        };

                        if same {
                            both.entry(key.clone())
                                .or_insert_with(|| masker.mask(&value(SecretSide::Both)))
                                .clone()
                        } else {
                            masker.mask(&value(side))
                        }
                    }
                };

                (key.clone(), Value::String(text))
            })
            .collect();

        rewrite(view, entries, masker.is_none())?;
    }

    Ok(differing)
}

/// Adds a field change for every key in `keys` that the diff of the masked values did not
/// report, with the masked values (which are equal), and puts the fields in path order.
pub(super) fn add_forced(
    fields: &mut Vec<FieldChange>,
    keys: &[String],
    mode: &SecretMode,
    before: &Value,
    after: &Value,
) {
    let heading = if *mode == SecretMode::Decode {
        "stringData"
    } else {
        "data"
    };

    for key in keys {
        let path = FieldPath(vec![
            PathSegment::Key(heading.to_owned()),
            PathSegment::Key(key.clone()),
        ]);

        if fields.iter().all(|field| field.path != path) {
            fields.push(FieldChange {
                path,
                before: before.get(heading).and_then(|map| map.get(key)).cloned(),
                after: after.get(heading).and_then(|map| map.get(key)).cloned(),
            });
        }
    }

    fields.sort_by(|a, b| a.path.0.cmp(&b.path.0));
}