mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The connections open on the server and what each one is doing.
//!
//! The statement text of another connection may carry a value from somebody
//! else's application, so it never travels out as it arrived: every literal is
//! blanked first, by the same pass that guards statements on the way in.
//!
//! A credential without the right to observe other connections sees only its
//! own. The server says nothing about that narrowing, so the answer says it,
//! because a caller who believes a one-row listing is the whole server draws
//! the wrong conclusion from it.

use super::{cell, fetch, number_of, text_of, ServerSettings};
use crate::cli::server::ProcessesArgs;
use crate::error::Result;
use crate::output::{Envelope, Gap, Row};
use crate::sql::strip;
use mysql_async::{params, Conn};
use serde_json::{json, Value};

/// The listing, narrowed on the server so unwanted rows never travel.
const LISTING: &str = "SELECT ID, USER, HOST, DB, COMMAND, TIME, STATE, INFO \
     FROM information_schema.PROCESSLIST \
     WHERE (:user IS NULL OR USER = :user) \
       AND (:min_seconds IS NULL OR TIME >= :min_seconds) \
       AND (:command IS NULL OR COMMAND = :command) \
     ORDER BY TIME DESC, ID ASC";

/// Lists the connections open on the server.
///
/// # Errors
///
/// Returns a permission failure naming the right that is missing when the
/// server refuses the listing outright, and the mapped driver failure for any
/// other condition.
pub async fn run(
    connection: &mut Conn,
    args: &ProcessesArgs,
    own_connection_id: u64,
    _settings: &ServerSettings,
) -> Result<Envelope> {
    let source = fetch(
        connection,
        LISTING,
        params! {
            "user" => args.user.clone(),
            "min_seconds" => args.min_seconds,
            "command" => args.state.map(crate::cli::server::ConnectionState::command_word),
        },
    )
    .await
    .map_err(|failure| super::observation_failure(failure, "PROCESS", "other-connections"))?;

    let rows = shape_all(&source);
    let envelope = Envelope::new(
        "server processes",
        json!({
            "own_connection_id": own_connection_id,
            "rows": rows,
        }),
    );

    Ok(match narrowing(&source, own_connection_id) {
        Some(gap) => envelope.with_gap(gap),
        None => envelope,
    })
}

/// Shapes every listed connection, redacting the statement text.
#[must_use]
pub fn shape_all(source: &[Row]) -> Vec<Row> {
    source.iter().map(shape_one).collect()
}

/// Shapes one listed connection.
fn shape_one(row: &Row) -> Row {
    let mut shaped = Row::new();
    shaped.insert(
        "id".to_owned(),
        cell(row, "ID").cloned().unwrap_or(Value::Null),
    );
    shaped.insert(
        "user".to_owned(),
        cell(row, "USER").cloned().unwrap_or(Value::Null),
    );
    shaped.insert(
        "host".to_owned(),
        cell(row, "HOST").cloned().unwrap_or(Value::Null),
    );
    shaped.insert(
        "database".to_owned(),
        cell(row, "DB").cloned().unwrap_or(Value::Null),
    );
    shaped.insert(
        "command".to_owned(),
        cell(row, "COMMAND").cloned().unwrap_or(Value::Null),
    );
    shaped.insert(
        "seconds".to_owned(),
        cell(row, "TIME").cloned().unwrap_or(Value::Null),
    );
    shaped.insert(
        "state".to_owned(),
        cell(row, "STATE").cloned().unwrap_or(Value::Null),
    );
    shaped.insert("statement".to_owned(), redact(cell(row, "INFO")));
    shaped
}

/// Blanks every literal in a statement observed on another connection.
///
/// The shape of the statement is what makes the listing useful, and the values
/// inside it are what makes the listing dangerous, so the shape stays and the
/// values go.
#[must_use]
pub fn redact(statement: Option<&Value>) -> Value {
    match statement {
        None | Some(Value::Null) => Value::Null,
        Some(other) => json!(strip::strip(&text_of(Some(other))).text().to_owned()),
    }
}

/// The gap a narrowed listing deserves, when it looks narrowed.
///
/// Every listed connection belonging to the same user as this one is the sign
/// the server showed only what this credential owns. It is a sign and not a
/// proof, and the gap says so, because asking the server for the credential's
/// rights would cost a round trip on every single call.
#[must_use]
pub fn narrowing(source: &[Row], own_connection_id: u64) -> Option<Gap> {
    let own_id = i64::try_from(own_connection_id).ok()?;
    let own_user = source
        .iter()
        .find(|row| number_of(cell(row, "ID")) == Some(own_id))
        .map(|row| text_of(cell(row, "USER")))?;

    let all_ours = source
        .iter()
        .all(|row| text_of(cell(row, "USER")) == own_user);

    all_ours.then(|| {
        Gap::new(
            "other_connections",
            "possibly_restricted",
            format!(
                "every listed connection belongs to `{own_user}`, which is what a credential \
                 without the right to observe other connections would see"
            ),
        )
    })
}

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

    fn listed(id: i64, user: &str, statement: Value) -> Row {
        let mut row = Row::new();
        row.insert("ID".to_owned(), json!(id));
        row.insert("USER".to_owned(), json!(user));
        row.insert("HOST".to_owned(), json!("localhost"));
        row.insert("DB".to_owned(), json!("sales"));
        row.insert("COMMAND".to_owned(), json!("Query"));
        row.insert("TIME".to_owned(), json!(12));
        row.insert("STATE".to_owned(), json!("Sending data"));
        row.insert("INFO".to_owned(), statement);
        row
    }

    /// A value inside an observed statement never leaves the tool, while the
    /// shape of the statement survives so the listing stays useful.
    #[test]
    fn an_observed_statement_keeps_its_shape_and_loses_its_values() {
        let redacted = redact(Some(&json!("SELECT * FROM users WHERE token = 'sekret'")));
        let text = text_of(Some(&redacted));
        assert!(
            !text.contains("sekret"),
            "a literal must not survive: {text}"
        );
        assert!(text.contains("SELECT"), "the shape must survive: {text}");
        assert!(text.contains("users"), "the object must survive: {text}");
    }

    /// A connection running nothing has no statement to redact.
    #[test]
    fn an_idle_connection_carries_no_statement() {
        assert_eq!(redact(Some(&Value::Null)), Value::Null);
        assert_eq!(redact(None), Value::Null);
    }

    /// Every column the caller needs survives the shaping, under the published
    /// name rather than the server's own.
    #[test]
    fn the_shaped_row_carries_every_published_field() {
        let rows = shape_all(&[listed(7, "app", json!("SELECT 1"))]);
        for field in [
            "id",
            "user",
            "host",
            "database",
            "command",
            "seconds",
            "state",
            "statement",
        ] {
            assert!(rows[0].contains_key(field), "{field} is missing");
        }
    }

    /// A listing showing only this credential's own connections declares the
    /// narrowing, because a caller must not read it as the whole server.
    #[test]
    fn a_listing_of_only_our_own_connections_declares_the_narrowing() {
        let source = vec![listed(7, "app", Value::Null), listed(9, "app", Value::Null)];
        let gap = narrowing(&source, 7).expect("the narrowing must be declared");
        assert_eq!(gap.object, "other_connections");
        assert!(gap.detail.contains("app"));
    }

    /// A listing carrying somebody else's connection is the whole server, so
    /// nothing is declared.
    #[test]
    fn a_listing_carrying_another_user_declares_nothing() {
        let source = vec![
            listed(7, "app", Value::Null),
            listed(9, "reporting", Value::Null),
        ];
        assert!(narrowing(&source, 7).is_none());
    }
}