use crate::output::envelope::Row;
use serde_json::{Map, Value};
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),
}
}
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
}
pub(super) fn lookup<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
path.split('.')
.try_fold(value, |current, segment| current.get(segment))
}
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()),
}
}
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),
_ => scalar_text(left).cmp(&scalar_text(right)),
}
}
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)
}
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
}
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,
}
}
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
}
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,
}
}
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()
}
fn serialised_len(element: &Value) -> Option<usize> {
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;
#[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}"
);
}
#[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"));
}
#[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"));
}
}