mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Ending the work of another connection.
//!
//! Three refusals stand in front of the server, and all three are decided
//! before anything is sent:
//!
//! 1. this invocation's own connection is never ended, because that would
//!    break the call carrying the request;
//! 2. nothing happens without the confirmation every destructive operation
//!    needs;
//! 3. work belonging to another user needs a mark of its own on top of that
//!    confirmation, because taking away somebody else's work is a different
//!    act from taking away your own. Only this third refusal can be turned
//!    off, and only by the host, from `server.kill_foreign_requires_yes`.
//!
//! The owner is read before the decision, never guessed from the identifier.

use super::{cell, fetch, text_of, ServerSettings};
use crate::cli::server::KillArgs;
use crate::error::{Failure, Result};
use crate::output::{Envelope, Row};
use mysql_async::{params, Conn, Params};
use serde_json::json;

/// Who owns a connection and how it relates to this invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
    /// The identifier the server knows the connection by.
    pub id: u64,
    /// The user the connection belongs to.
    pub owner: String,
    /// Whether this is the connection carrying the request.
    pub is_own_connection: bool,
}

/// What was decided about a request to end work.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decision {
    /// The statement to send.
    pub statement: String,
    /// Whether the work belongs to somebody other than the caller.
    pub belongs_to_another_user: bool,
    /// The warning the caller is told alongside the result.
    pub warning: String,
}

/// Ends the running statement of a connection, or the connection itself.
///
/// # Errors
///
/// Returns a validation failure when the confirmation is missing, when the
/// connection belongs to another user and the mark allowing that is absent, or
/// when the identifier names this invocation's own connection; an absence
/// failure when no connection carries that identifier; and the mapped driver
/// failure when the server refuses the request.
pub async fn run(
    connection: &mut Conn,
    args: &KillArgs,
    own_connection_id: u64,
    settings: &ServerSettings,
) -> Result<Envelope> {
    let own_user = read_own_user(connection).await?;
    let target = look_up(connection, args.id, own_connection_id).await?;
    let decision = decide(&target, &own_user, args, settings)?;

    fetch(connection, &decision.statement, Params::Empty).await?;
    let still_open = look_up(connection, args.id, own_connection_id)
        .await
        .is_ok();

    Ok(Envelope::new(
        "server kill",
        json!({
            "id": target.id,
            "owner": target.owner,
            "belongs_to_another_user": decision.belongs_to_another_user,
            "statement_only": args.query_only,
            "still_open": still_open,
            "warning": decision.warning,
        }),
    ))
}

/// Decides whether the request may be sent, and what to send.
///
/// Kept apart from the round trips so every refusal is provable without a
/// server, since it is the rule and not the network that refuses.
///
/// # Errors
///
/// Returns a validation failure for each of the three refusals this module
/// stands on.
pub fn decide(
    target: &Target,
    own_user: &str,
    args: &KillArgs,
    settings: &ServerSettings,
) -> Result<Decision> {
    if target.is_own_connection {
        return Err(Failure::validation(
            "validation.own_connection",
            "that identifier is the connection carrying this request",
        )
        .with_hint("end another connection; ending this one would break the call in progress"));
    }

    if !settings.confirmed {
        return Err(Failure::validation(
            "validation.confirmation_missing",
            "ending the work of a connection needs confirmation",
        )
        .with_hint("repeat the call with --yes"));
    }

    // The ordinary confirmation was already demanded above. This is the extra
    // one, and it is extra because the work belongs to somebody who never knew
    // this tool ran; a host that does not want that distinction drops it from
    // the setting rather than from the code.
    let belongs_to_another_user = target.owner != own_user;
    if belongs_to_another_user && settings.kill_foreign_requires_yes && !args.kill_other {
        return Err(Failure::validation(
            "validation.other_user_not_allowed",
            "that connection belongs to another user",
        )
        .with_hint("repeat the call with --kill-other to end work that is not yours"));
    }

    Ok(Decision {
        statement: statement_for(target.id, args.query_only),
        belongs_to_another_user,
        warning: warning_for(&target.owner, belongs_to_another_user, args.query_only),
    })
}

/// The statement that ends the work.
///
/// The identifier is a whole number the argument layer already parsed, so it
/// carries no text of the caller's and cannot change what the statement means.
#[must_use]
pub fn statement_for(id: u64, statement_only: bool) -> String {
    if statement_only {
        format!("KILL QUERY {id}")
    } else {
        format!("KILL CONNECTION {id}")
    }
}

/// The warning that names the owner of the work being taken away.
#[must_use]
pub fn warning_for(owner: &str, belongs_to_another_user: bool, statement_only: bool) -> String {
    let what = if statement_only {
        "the running statement"
    } else {
        "the whole connection"
    };
    if belongs_to_another_user {
        format!("{what} of another user, `{owner}`, was ended on request")
    } else {
        format!("{what} of `{owner}`, your own user, was ended on request")
    }
}

/// The user this invocation is connected as.
async fn read_own_user(connection: &mut Conn) -> Result<String> {
    let rows = fetch(
        connection,
        "SELECT SUBSTRING_INDEX(USER(), '@', 1)",
        Params::Empty,
    )
    .await?;
    Ok(rows
        .first()
        .and_then(|row| row.values().next())
        .map(|value| text_of(Some(value)))
        .unwrap_or_default())
}

/// Reads who owns one connection, refusing to guess when it is gone.
async fn look_up(connection: &mut Conn, id: u64, own_connection_id: u64) -> Result<Target> {
    let rows = fetch(
        connection,
        "SELECT ID, USER FROM information_schema.PROCESSLIST WHERE ID = :id",
        params! { "id" => id },
    )
    .await
    .map_err(|failure| super::observation_failure(failure, "PROCESS", "other-connections"))?;

    let row: &Row = rows.first().ok_or_else(|| {
        Failure::absence(
            "absence.unknown_connection",
            "no connection on this server carries that identifier",
        )
        .with_hint("list the open connections first to confirm the identifier")
    })?;

    Ok(Target {
        id,
        owner: text_of(cell(row, "USER")),
        is_own_connection: id == own_connection_id,
    })
}

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

    fn args(query_only: bool, kill_other: bool) -> KillArgs {
        KillArgs {
            id: 4711,
            query_only,
            kill_other,
        }
    }

    /// The published defaults, with the confirmation the caller gave.
    fn settings(confirmed: bool) -> ServerSettings {
        ServerSettings {
            status_interval_secs: 1,
            default_top: 100,
            confirmed,
            observability_visible: true,
            kill_foreign_requires_yes: true,
        }
    }

    fn target(owner: &str, is_own: bool) -> Target {
        Target {
            id: 4711,
            owner: owner.to_owned(),
            is_own_connection: is_own,
        }
    }

    /// Work of another user is refused without the mark allowing it, and the
    /// refusal names the mark, so the caller is never left guessing.
    #[test]
    fn another_users_work_is_refused_without_the_mark() {
        let failure = decide(
            &target("reporting", false),
            "app",
            &args(true, false),
            &settings(true),
        )
        .expect_err("another user's work must be refused");
        assert_eq!(failure.code(), "validation.other_user_not_allowed");
        assert_eq!(failure.exit_number().code(), 3);
        assert!(failure
            .hint()
            .is_some_and(|hint| hint.contains("--kill-other")));
    }

    /// With the mark, the same request goes through and the answer names the
    /// owner whose work was taken away.
    #[test]
    fn another_users_work_goes_through_with_the_mark_and_names_the_owner() {
        let decision = decide(
            &target("reporting", false),
            "app",
            &args(true, true),
            &settings(true),
        )
        .expect("the mark allows it");
        assert!(decision.belongs_to_another_user);
        assert!(decision.warning.contains("reporting"));
        assert!(decision.warning.contains("another user"));
    }

    /// Work of the caller's own user needs only the ordinary confirmation.
    #[test]
    fn your_own_work_needs_only_the_ordinary_confirmation() {
        let decision = decide(
            &target("app", false),
            "app",
            &args(true, false),
            &settings(true),
        )
        .expect("own work");
        assert!(!decision.belongs_to_another_user);
        assert_eq!(decision.statement, "KILL QUERY 4711");
    }

    /// Nothing reaches the server without the confirmation.
    #[test]
    fn nothing_is_sent_without_the_confirmation() {
        let failure = decide(
            &target("app", false),
            "app",
            &args(true, false),
            &settings(false),
        )
        .expect_err("confirmation is required");
        assert_eq!(failure.code(), "validation.confirmation_missing");
        assert!(failure.hint().is_some_and(|hint| hint.contains("--yes")));
    }

    /// The connection carrying the request is never ended, whatever marks the
    /// caller passes.
    #[test]
    fn this_invocations_own_connection_is_never_ended() {
        let failure = decide(
            &target("app", true),
            "app",
            &args(false, true),
            &settings(true),
        )
        .expect_err("our own connection must be refused");
        assert_eq!(failure.code(), "validation.own_connection");
    }

    /// A host that does not want the extra mark drops it from the setting, and
    /// then the ordinary confirmation is the whole gate for another user's
    /// work. The confirmation itself is never dropped with it.
    #[test]
    fn the_extra_mark_for_another_users_work_can_be_turned_off() {
        let without_the_extra_mark = ServerSettings {
            kill_foreign_requires_yes: false,
            ..settings(true)
        };
        let decision = decide(
            &target("reporting", false),
            "app",
            &args(true, false),
            &without_the_extra_mark,
        )
        .expect("the ordinary confirmation is enough now");
        assert!(decision.belongs_to_another_user);
        assert!(decision.warning.contains("reporting"));

        let unconfirmed = ServerSettings {
            kill_foreign_requires_yes: false,
            ..settings(false)
        };
        assert_eq!(
            decide(
                &target("reporting", false),
                "app",
                &args(true, false),
                &unconfirmed
            )
            .expect_err("the ordinary confirmation still stands")
            .code(),
            "validation.confirmation_missing"
        );
    }

    /// The two shapes of the request are told apart in the statement and in
    /// the warning.
    #[test]
    fn ending_a_statement_differs_from_ending_a_connection() {
        assert_eq!(statement_for(9, true), "KILL QUERY 9");
        assert_eq!(statement_for(9, false), "KILL CONNECTION 9");
        assert!(warning_for("app", false, true).contains("statement"));
        assert!(warning_for("app", false, false).contains("connection"));
    }
}