mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Reading, ordering, projecting and shortening one value.
//!
//! The gathered path and the flow share these helpers on purpose: a row must
//! not mean one thing gathered and another in flight.

use crate::output::envelope::Row;
use serde_json::{Map, Value};

/// Follows a dotted path into a row, whose first segment is a column name.
///
/// A row is a column map and not a document, so the first segment is looked up
/// in the map and the rest, if any, inside the value found there.
pub(super) fn lookup_row<'a>(row: &'a Row, path: &str) -> Option<&'a Value> {
    let (head, rest) = path
        .split_once('.')
        .map_or((path, None), |(a, b)| (a, Some(b)));
    let found = row.get(head)?;
    match rest {
        Some(rest) => lookup(found, rest),
        None => Some(found),
    }
}

/// Keeps only the requested dotted paths of one row, skipping absent ones.
///
/// Absent paths are skipped rather than emitted empty, exactly as the gathered
/// path does, so the two never disagree about what a projection means.
pub(super) fn project_row(row: &Row, paths: &[String]) -> Row {
    let mut kept = Row::with_capacity(paths.len());
    for path in paths {
        if let Some(found) = lookup_row(row, path) {
            kept.insert(path.clone(), found.clone());
        }
    }
    kept
}

/// Follows a dotted path into a value.
pub(super) fn lookup<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
    path.split('.')
        .try_fold(value, |current, segment| current.get(segment))
}

/// Renders a scalar for comparison, without the quotes JSON would add.
///
/// Borrowed where there is nothing to build. A JSON string already IS the text
/// this returns, so the previous form cloned it only to hand back a copy the
/// caller usually just read and dropped. Everything else is genuinely rendered
/// and is owned.
///
/// The distinction is not decoration: `compare` calls this twice per comparison
/// and is the comparator `sort_by` runs, so the owning form cost two allocations
/// for every pair examined while ordering rows by a text field.
pub(super) fn scalar_text(value: &Value) -> std::borrow::Cow<'_, str> {
    match value {
        Value::String(text) => std::borrow::Cow::Borrowed(text),
        other => std::borrow::Cow::Owned(other.to_string()),
    }
}

/// Orders two values, comparing numbers numerically and the rest as text.
pub(super) fn compare(left: &Value, right: &Value) -> std::cmp::Ordering {
    match (left.as_f64(), right.as_f64()) {
        (Some(a), Some(b)) => a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Equal),
        // Two string values now compare with no allocation at all, which is the
        // ordinary case when a caller orders by a name.
        _ => scalar_text(left).cmp(&scalar_text(right)),
    }
}

/// Keeps only the requested dotted paths, skipping the ones that are absent.
///
/// An absent path is skipped rather than emitted as an empty value, so the
/// caller never has to tell "missing" from "present but empty".
pub(super) fn project(element: &Value, paths: &[String]) -> Value {
    let mut kept = Map::new();
    for path in paths {
        if let Some(found) = lookup(element, path) {
            kept.insert(path.clone(), found.clone());
        }
    }
    Value::Object(kept)
}

/// Replaces credential-shaped text inside every string with the fixed mark.
///
/// Returns whether anything was replaced.
///
/// # Why this runs before the shortening and not after
///
/// Shortening first would cut a credential in half and leave the half that fits
/// standing in the answer. The mark this puts in its place is short, so
/// shortening it afterwards costs nothing and removes nothing.
///
/// # What it recognises, and what it therefore does not
///
/// The same shapes the auxiliary channel already refuses to carry, read from
/// `obs::redact`: a certificate or key block, a destination carrying a
/// password, and an assignment naming one. It is shape-based, so a password
/// stored as a bare word in a column called `senha` looks exactly like every
/// other word and is not touched. That limit is stated here rather than left
/// for a caller to discover, because a guard believed to be complete is worse
/// than one known to be partial.
pub(super) fn redact_in_place(value: &mut Value) -> bool {
    match value {
        Value::String(text) => {
            let scrubbed = crate::obs::redact::scrub(text);
            if scrubbed == *text {
                return false;
            }
            *text = scrubbed;
            true
        }
        // Every branch is visited, for the reason given below: stopping at the
        // first replacement would leave every later cell untouched.
        Value::Array(elements) => {
            let mut any = false;
            for element in elements {
                any |= redact_in_place(element);
            }
            any
        }
        Value::Object(fields) => {
            let mut any = false;
            for (_, field) in fields {
                any |= redact_in_place(field);
            }
            any
        }
        _ => false,
    }
}

/// Shortens every string above the ceiling, counting characters and never bytes.
///
/// Returns whether anything was shortened. A multi-byte character is never
/// split in half.
pub(super) fn truncate_in_place(value: &mut Value, ceiling: usize) -> bool {
    match value {
        Value::String(text) => {
            if text.chars().count() <= ceiling {
                return false;
            }
            let kept: String = text.chars().take(ceiling).collect();
            *text = kept;
            true
        }
        // Every branch is visited: short-circuiting here would leave later
        // cells above the ceiling, which is the opposite of what was asked.
        Value::Array(elements) => {
            let mut any = false;
            for element in elements {
                any |= truncate_in_place(element, ceiling);
            }
            any
        }
        Value::Object(fields) => {
            let mut any = false;
            for (_, field) in fields {
                any |= truncate_in_place(field, ceiling);
            }
            any
        }
        _ => false,
    }
}

/// How many leading elements fit within the volume ceiling.
///
/// Whole elements are dropped from the end; the serialised text is never cut
/// mid-way, so the answer stays parseable.
pub(super) fn fit_within(elements: &[Value], ceiling: usize) -> usize {
    let mut used = 0usize;
    for (index, element) in elements.iter().enumerate() {
        let size = serialised_len(element).map_or(0, |len| len + 1);
        if used + size > ceiling {
            return index;
        }
        used += size;
    }
    elements.len()
}

/// How many bytes an element would take, without building those bytes.
///
/// The question here is only how LARGE the serialisation is, and the previous
/// form answered it by producing the whole serialisation and then dropping it.
/// Over a set of rows that is one full copy of every row allocated and thrown
/// away, purely to read its length.
fn serialised_len(element: &Value) -> Option<usize> {
    /// A writer that keeps the count and none of the bytes.
    struct Tally(usize);

    impl std::io::Write for Tally {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0 += buf.len();
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    let mut tally = Tally(0);
    serde_json::to_writer(&mut tally, element).ok()?;
    Some(tally.0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// A destination carrying a password loses the password and nothing else.
    ///
    /// The redaction this product already performed covered the diagnostic
    /// channel and the statement text of `server processes`. It never reached a
    /// cell, so reading a table that stores destinations put every password in
    /// it onto the channel documented as carrying data and nothing else.
    #[test]
    fn a_destination_in_a_cell_loses_its_credential_and_keeps_its_address() {
        let mut cell = json!("mariadb://leitor:hunter2@db.local:3306/loja");

        assert!(redact_in_place(&mut cell));

        let text = cell.as_str().expect("text");
        assert!(!text.contains("hunter2"), "the credential survived: {text}");
        assert!(
            text.contains("db.local") && text.contains("leitor"),
            "only the credential is replaced, not the destination around it: {text}"
        );
    }

    /// Ordinary text is left exactly as it arrived, and says so.
    ///
    /// The answer to a query is what this product exists to deliver, so a cell
    /// carrying no credential must be indistinguishable from one this operation
    /// never saw.
    #[test]
    fn a_cell_carrying_no_credential_travels_untouched() {
        let mut cell = json!("nothing secret here");
        assert!(!redact_in_place(&mut cell));
        assert_eq!(cell, json!("nothing secret here"));
    }

    /// Every cell is visited, not merely the first one that matched.
    ///
    /// Stopping at the first replacement would leave every later cell standing,
    /// which is the shape the shortening beside this one had to answer for too.
    #[test]
    fn every_cell_beneath_a_row_is_visited_and_not_only_the_first() {
        let mut row = json!({
            "first": "mariadb://a:senha1@h1/d",
            "second": "plain",
            "nested": ["mariadb://b:senha2@h2/d"]
        });

        assert!(redact_in_place(&mut row));

        let written = row.to_string();
        assert!(
            !written.contains("senha1") && !written.contains("senha2"),
            "a later cell kept its credential: {written}"
        );
        assert!(written.contains("plain"));
    }
}