starmap-cli 0.4.4

The starmap command, which checks, explains, compares and runs an application's declared environment
Documentation
//! The masking of secret references in the text of a `starmap.toml` that
//! does not parse, so the excerpt that `starmap check` prints under a
//! problem, in text and in JSON, never shows a reference.

use std::ops::Range;

#[cfg(test)]
mod tests;

/// Returns `text` with each byte of each span in `spans` replaced by `*`,
/// and then each run from `op://` to the end of its line replaced the same
/// way. Line breaks are kept, so every problem's span and line still point
/// at the same text.
///
/// `spans` come from the parser, which finds each value of a bind that may
/// hold a reference, such as one without the `op://` prefix. The scan for
/// `op://` catches a reference that the parser never reached, such as one
/// beside a TOML syntax error. It masks to the end of the line rather than
/// to a closing quote, because a reference may hold its own quote
/// character, so the rest of that line is lost from the excerpt. A
/// reference outside a bind without the prefix, after a syntax error, is
/// missed.
///
/// Returns `None`, so the caller prints no excerpt rather than an unmasked
/// one, when a span does not lie on character boundaries of `text`, or
/// when a multi-line string (`"""` or `'''`) still holds `op:` after
/// masking. A multi-line string can carry a reference onto lines that hold
/// no `op://`, or split `op:` from `//` with a line-ending backslash, and
/// this scan does not parse strings.
pub(super) fn masked(text: String, spans: &[Range<usize>]) -> Option<String> {
    let mut bytes = text.into_bytes();
    for span in spans {
        mask(&mut bytes, span.clone())?;
    }
    if multi_line_holds_op(&bytes) {
        return None;
    }
    let mut from = 0;
    while let Some(start) = find(&bytes, b"op://", from) {
        let end = find(&bytes, b"\n", start).unwrap_or(bytes.len());
        mask(&mut bytes, start..end)?;
        from = end;
    }
    String::from_utf8(bytes).ok()
}

/// Returns whether a run from `"""` or `'''` to the next of the same three
/// quotes, or to the end of the text when none follows, holds `op:`. The
/// scan does not parse TOML, so three quotes in a comment or in a one-line
/// string also open a run, which can only drop an excerpt.
fn multi_line_holds_op(bytes: &[u8]) -> bool {
    let mut from = 0;
    loop {
        let opened = [b"\"\"\"", b"'''"]
            .into_iter()
            .filter_map(|quotes| find(bytes, quotes, from).map(|at| (at, quotes)))
            .min();
        let Some((start, quotes)) = opened else {
            return false;
        };
        let body = start + quotes.len();
        let end = find(bytes, quotes, body).unwrap_or(bytes.len());
        if find(bytes.get(body..end).unwrap_or_default(), b"op:", 0).is_some() {
            return true;
        }
        from = end + quotes.len();
    }
}

/// Replaces each byte of `bytes` in `span` other than a line break with
/// `*`, or returns `None` when `span` does not lie on character
/// boundaries of the text `bytes` holds.
fn mask(bytes: &mut [u8], span: Range<usize>) -> Option<()> {
    let text = std::str::from_utf8(bytes).ok()?;
    if !text.is_char_boundary(span.start) || !text.is_char_boundary(span.end) {
        return None;
    }
    for byte in bytes.get_mut(span)? {
        if !matches!(byte, b'\n' | b'\r') {
            *byte = b'*';
        }
    }
    Some(())
}

/// Returns the offset of the first `needle` in `bytes` at or after
/// `from`.
fn find(bytes: &[u8], needle: &[u8], from: usize) -> Option<usize> {
    bytes
        .get(from..)?
        .windows(needle.len())
        .position(|window| window == needle)
        .map(|at| at + from)
}