mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! What the connected credential is actually allowed to do.
//!
//! This is how a caller proves that a restriction lives on the server rather
//! than in this tool. A tool that decides what it will not do can be argued
//! with; a credential that cannot write is the only answer that holds.
//!
//! The server states a permission as one line of its own grammar, and that
//! line may also carry authentication material. Nothing here ever publishes
//! the line: only the parts that were understood leave, so a secret in the
//! tail of a line cannot travel with the answer.

use crate::conn::OrFailure;
use crate::error::Result;
use mysql_async::prelude::Queryable;
use mysql_async::Conn;
use serde_json::{json, Value};

/// One permission, as it was understood.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Permission {
    /// The abilities the line confers.
    pub abilities: Vec<String>,
    /// What the abilities reach, as the server writes it.
    pub scope: String,
    /// Whether the credential may pass these abilities on.
    pub may_delegate: bool,
}

impl Permission {
    /// The abilities that let the holder change stored data or structure.
    #[must_use]
    pub fn writes(&self) -> Vec<&str> {
        self.abilities
            .iter()
            .map(String::as_str)
            .filter(|ability| WRITING.contains(ability))
            .collect()
    }

    /// The abilities that reach beyond the data, and are worth pointing at.
    #[must_use]
    pub fn far_reaching(&self) -> Vec<&str> {
        let mut found: Vec<&str> = self
            .abilities
            .iter()
            .map(String::as_str)
            .filter(|ability| FAR_REACHING.contains(ability))
            .collect();
        if self.may_delegate {
            found.push(DELEGATION);
        }
        found
    }

    /// This permission as it is published.
    #[must_use]
    pub fn as_value(&self) -> Value {
        json!({
            "abilities": self.abilities,
            "scope": self.scope,
            "may_delegate": self.may_delegate,
            "writes": self.writes(),
            "far_reaching": self.far_reaching(),
        })
    }
}

/// Abilities that change stored data or structure.
static WRITING: &[&str] = &[
    "ALL PRIVILEGES",
    "ALTER",
    "ALTER ROUTINE",
    "CREATE",
    "CREATE ROUTINE",
    "CREATE TEMPORARY TABLES",
    "CREATE VIEW",
    "DELETE",
    "DELETE HISTORY",
    "DROP",
    "EVENT",
    "INDEX",
    "INSERT",
    "REFERENCES",
    "TRIGGER",
    "UPDATE",
];

/// Abilities that reach past the data of one database.
static FAR_REACHING: &[&str] = &[
    "ALL PRIVILEGES",
    "BINLOG ADMIN",
    "CREATE USER",
    "FEDERATED ADMIN",
    "FILE",
    "PROCESS",
    "RELOAD",
    "REPLICATION CLIENT",
    "REPLICATION SLAVE",
    "SET USER",
    "SHUTDOWN",
    "SUPER",
];

/// The name given to the ability to pass permissions on.
const DELEGATION: &str = "GRANT OPTION";

/// Reads who is connected and what that credential may do.
///
/// # Errors
///
/// Returns the mapped driver failure when the credential may not read its own
/// permissions, which the server reports as a refusal rather than as an empty
/// answer.
pub async fn effective(connection: &mut Conn) -> Result<Value> {
    let identity: Option<(String, String)> = connection
        .query_first("SELECT CURRENT_USER(), USER()")
        .await
        .or_failure()?;
    let lines: Vec<String> = connection.query("SHOW GRANTS").await.or_failure()?;

    let permissions: Vec<Permission> = lines.iter().filter_map(|line| parse(line)).collect();
    let understood = permissions.len();
    let (authenticated_as, connected_as) = identity.unwrap_or_default();

    Ok(json!({
        "authenticated_as": authenticated_as,
        "connected_as": connected_as,
        "rows": permissions.iter().map(Permission::as_value).collect::<Vec<_>>(),
        "can_write": permissions.iter().any(|entry| !entry.writes().is_empty()),
        "far_reaching": permissions
            .iter()
            .flat_map(|entry| entry.far_reaching().into_iter().map(ToOwned::to_owned))
            .collect::<Vec<String>>(),
        "lines_read": lines.len(),
        "lines_understood": understood,
    }))
}

/// Reads one permission line, keeping only the parts that were understood.
///
/// A line this release cannot read produces nothing rather than a guess, and
/// the count of read against understood lines in the answer makes that
/// visible instead of hiding it.
#[must_use]
pub fn parse(line: &str) -> Option<Permission> {
    let body = line.strip_prefix("GRANT ")?;
    // Anything from the authentication clause onward may carry a secret and is
    // dropped before the line is read any further.
    let body = cut_at(body, " IDENTIFIED");
    let (abilities, rest) = body.split_once(" ON ")?;
    let (scope, tail) = rest.split_once(" TO ").unwrap_or((rest, ""));

    Some(Permission {
        abilities: split_abilities(abilities),
        scope: scope.trim().to_owned(),
        may_delegate: tail.contains("WITH GRANT OPTION"),
    })
}

/// Everything before the given marker, or the whole text when it is absent.
fn cut_at<'a>(text: &'a str, marker: &str) -> &'a str {
    text.find(marker).map_or(text, |offset| &text[..offset])
}

/// Splits the ability list, keeping any column list attached to its ability.
///
/// The server writes a column-restricted ability as the ability followed by
/// its columns in brackets, and the comma inside those brackets must not be
/// mistaken for the separator between two abilities.
fn split_abilities(text: &str) -> Vec<String> {
    let mut abilities = Vec::new();
    let mut current = String::new();
    let mut depth = 0_usize;
    for character in text.chars() {
        match character {
            '(' => {
                depth += 1;
                current.push(character);
            }
            ')' => {
                depth = depth.saturating_sub(1);
                current.push(character);
            }
            ',' if depth == 0 => {
                push_ability(&mut abilities, &current);
                current.clear();
            }
            _ => current.push(character),
        }
    }
    push_ability(&mut abilities, &current);
    abilities
}

/// Records one ability, in the upper case the server itself uses.
fn push_ability(abilities: &mut Vec<String>, current: &str) {
    let trimmed = current.trim();
    if !trimmed.is_empty() {
        abilities.push(trimmed.to_uppercase());
    }
}

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

    /// A plain read-only permission is understood, and says it cannot write.
    #[test]
    fn a_read_only_permission_says_it_cannot_write() {
        let permission = parse("GRANT SELECT ON `shop`.* TO `reader`@`%`").expect("understood");
        assert_eq!(permission.abilities, vec!["SELECT".to_owned()]);
        assert_eq!(permission.scope, "`shop`.*");
        assert!(permission.writes().is_empty());
        assert!(permission.far_reaching().is_empty());
        assert!(!permission.may_delegate);
    }

    /// Every writing ability is named, so a credential that can change data
    /// cannot pass for a read-only one.
    #[test]
    fn every_writing_ability_is_named() {
        let permission = parse("GRANT SELECT, INSERT, UPDATE, DELETE ON `shop`.* TO `app`@`%`")
            .expect("understood");
        assert_eq!(permission.writes(), vec!["INSERT", "UPDATE", "DELETE"]);
    }

    /// An ability that reaches past the data is pointed at.
    #[test]
    fn an_ability_that_reaches_past_the_data_is_pointed_at() {
        let permission =
            parse("GRANT SELECT, FILE, SUPER ON *.* TO `admin`@`localhost`").expect("understood");
        assert_eq!(permission.far_reaching(), vec!["FILE", "SUPER"]);
    }

    /// The ability to pass permissions on is itself far-reaching.
    #[test]
    fn the_ability_to_pass_permissions_on_is_far_reaching() {
        let permission =
            parse("GRANT SELECT ON *.* TO `owner`@`%` WITH GRANT OPTION").expect("understood");
        assert!(permission.may_delegate);
        assert_eq!(permission.far_reaching(), vec!["GRANT OPTION"]);
    }

    /// A permission over every ability counts as both writing and far-reaching.
    #[test]
    fn a_permission_over_everything_counts_as_both() {
        let permission =
            parse("GRANT ALL PRIVILEGES ON *.* TO `root`@`localhost`").expect("understood");
        assert_eq!(permission.writes(), vec!["ALL PRIVILEGES"]);
        assert_eq!(permission.far_reaching(), vec!["ALL PRIVILEGES"]);
    }

    /// Authentication material in the tail of a line never survives reading,
    /// so it cannot travel with the answer.
    #[test]
    fn authentication_material_never_survives_reading() {
        let permission =
            parse("GRANT USAGE ON *.* TO `app`@`%` IDENTIFIED BY PASSWORD '*ABCDEF0123456789'")
                .expect("understood");
        let published = serde_json::to_string(&permission.as_value()).expect("serialises");
        assert!(!published.contains("ABCDEF"), "{published}");
        assert!(!published.contains("IDENTIFIED"), "{published}");
        assert_eq!(permission.scope, "*.*");
    }

    /// A comma inside a column list is not a separator between abilities.
    #[test]
    fn a_column_list_stays_attached_to_its_ability() {
        let permission =
            parse("GRANT SELECT (id, name), UPDATE (name) ON `shop`.`users` TO `app`@`%`")
                .expect("understood");
        assert_eq!(
            permission.abilities,
            vec!["SELECT (ID, NAME)".to_owned(), "UPDATE (NAME)".to_owned()]
        );
    }

    /// A line this release cannot read produces nothing rather than a guess.
    #[test]
    fn an_unreadable_line_produces_nothing_rather_than_a_guess() {
        assert_eq!(parse("REVOKE SELECT ON `shop`.* FROM `x`@`%`"), None);
        assert_eq!(parse("GRANT `role_reader` TO `app`@`%`"), None);
        assert_eq!(parse(""), None);
    }

    /// A role granted with no scope is not mistaken for a permission over
    /// everything.
    #[test]
    fn a_role_is_not_mistaken_for_a_permission_over_everything() {
        assert!(parse("GRANT `analyst` TO `app`@`%`").is_none());
    }
}