mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Which destination an answer came from, and who chose it.
//!
//! # Why these proofs exist
//!
//! An answer used to describe everything the product decided except the one
//! decision it made on the caller's behalf. A call naming no profile is served
//! by whichever destination the stored default points at, and nothing in the
//! answer said which that was. Someone reading the result had to go and read
//! the configuration to learn where their own change had landed.
//!
//! The two requirements below close that from opposite ends. One makes every
//! answer name its destination and say where the choice came from. The other
//! stops a change being served at all when the choice came from the stored
//! default rather than from the call.

// Each file here uses the part of the shared module that it needs, so a helper
// unused by this one is not dead code.
#[allow(dead_code)]
mod support;

use support::server::{destination_or_skip, on_server};
use support::Sandbox;

/// The profile name every stored-destination proof here writes.
const STORED: &str = "declarado";

/// Writes a stored profile pointing at the declared destination.
///
/// The secret travels on the standard input, which is the only way this product
/// accepts one, so the proof cannot be written without going through it.
fn store_profile(sandbox: &Sandbox, dsn: &str) {
    let parsed = url_parts(dsn);
    let written = sandbox.run_with_input(
        &[
            "conn",
            "add",
            STORED,
            "--host",
            &parsed.host,
            "--port",
            &parsed.port,
            "--user",
            &parsed.user,
            "--database",
            &parsed.database,
            "--password-stdin",
            "--ca",
            &parsed.authority_file,
        ],
        &parsed.secret,
    );
    assert_eq!(
        written.code, 0,
        "the profile must be stored: {}",
        written.err
    );
}

/// The profile that points somewhere the product will never reach.
const ELSEWHERE: &str = "desviado";

/// Writes a stored profile pointing where nothing answers, and returns nothing.
///
/// # Why the address is the loopback and the port is one
///
/// The two proofs of the displaced token need two destinations that can be told
/// apart by what happens, not by reading a field back: a field can be reported
/// from one place while the work goes to another, and that is precisely the
/// failure being looked for. A refusal is not reportable that way.
///
/// Port one on the loopback refuses at once and never leaves the machine, so
/// the proof costs no waiting and reaches nobody else's server. An unroutable
/// address would do the same job and would do it by timing out, which would
/// make the suite slower for no gain in what is shown.
fn store_unreachable_profile(sandbox: &Sandbox) {
    let written = sandbox.run_with_input(
        &[
            "conn",
            "add",
            ELSEWHERE,
            "--host",
            "127.0.0.1",
            "--port",
            "1",
            "--user",
            "ninguem",
            "--database",
            "nenhum",
            "--password-stdin",
        ],
        "nada",
    );
    assert_eq!(
        written.code, 0,
        "the second profile must be stored: {}",
        written.err
    );
}

/// Makes one stored profile the one a call with no destination inherits.
fn make_default(sandbox: &Sandbox, profile: &str) {
    let chosen = sandbox.run(&["conn", "default", profile]);
    assert_eq!(
        chosen.code, 0,
        "the default must be settable: {}",
        chosen.err
    );
}

/// The pieces of a destination text this file needs.
struct Parts {
    host: String,
    port: String,
    user: String,
    secret: String,
    database: String,
    /// The trust anchor the destination text names, so the stored profile can
    /// keep the same certificate check the text was written to pass.
    authority_file: String,
}

/// Takes a destination text apart without pulling in a parser for it.
///
/// The text is written by this suite in `tests/destination.toml`, so its shape
/// is known and a full parser would be more machinery than the proof needs.
fn url_parts(dsn: &str) -> Parts {
    let body = dsn.trim_start_matches("mariadb://");
    let (credential, rest) = body
        .split_once('@')
        .expect("a destination carries a credential");
    let (user, secret) = credential
        .split_once(':')
        .expect("a credential carries a secret");
    let (authority, tail) = rest
        .split_once('/')
        .expect("a destination names a database");
    let (host, port) = authority.split_once(':').unwrap_or((authority, "3306"));
    let database = tail.split('?').next().unwrap_or(tail);
    let authority_file = tail
        .split_once("ca=")
        .map(|(_, path)| path.split('&').next().unwrap_or(path))
        .expect("the declared destination names a trust anchor");

    Parts {
        host: host.to_owned(),
        port: port.to_owned(),
        user: user.to_owned(),
        secret: secret.to_owned(),
        database: database.to_owned(),
        authority_file: authority_file.to_owned(),
    }
}

/// The same read names the same destination whoever chose it.
///
/// FR-143. The read is run twice against one server: once with the destination
/// written on the call, once with it inherited from the stored default. The
/// address is asserted to be the same both times and the declared origin to
/// differ, which is exactly the pair the requirement asks for. Asserting only
/// the first would pass for a product that hard-coded the word `argv`.
#[test]
fn the_same_destination_is_named_whether_it_was_written_or_inherited() {
    let Some(dsn) = destination_or_skip("the declared destination") else {
        return;
    };
    let sandbox = Sandbox::new();
    store_profile(&sandbox, &dsn);

    let written = on_server(&sandbox, &dsn, &["query", "run", "SELECT 1 AS a"]);
    assert_eq!(written.code, 0, "the read must succeed: {}", written.err);
    let by_text = written.answer();

    let inherited = sandbox.run(&["query", "run", "SELECT 1 AS a"]);
    assert_eq!(
        inherited.code, 0,
        "the read must succeed: {}",
        inherited.err
    );
    let by_default = inherited.answer();

    assert_eq!(
        by_text["target_resolved"]["host"], by_default["target_resolved"]["host"],
        "both calls reached the same server, so both must name it"
    );
    assert_eq!(by_text["target_source"], "dsn");
    assert_eq!(
        by_default["target_source"], "config",
        "a destination nobody wrote on the call is declared as inherited"
    );
    assert_eq!(
        by_default["target_resolved"]["profile"], STORED,
        "the inherited destination names the profile that served it"
    );
}

/// Naming the profile on the call is declared as having been named there.
///
/// FR-143. The third origin of the closed domain, which the pair above cannot
/// reach: a profile written on the call is neither a destination text nor an
/// inheritance, and a product that only told those two apart would pass there
/// and fail here.
#[test]
fn a_profile_written_on_the_call_is_declared_as_written_there() {
    let Some(dsn) = destination_or_skip("the declared destination") else {
        return;
    };
    let sandbox = Sandbox::new();
    store_profile(&sandbox, &dsn);

    let named = sandbox.run(&["--profile", STORED, "query", "run", "SELECT 1 AS a"]);
    assert_eq!(named.code, 0, "the read must succeed: {}", named.err);

    let answer = named.answer();
    assert_eq!(answer["target_source"], "argv");
    assert_eq!(answer["target_resolved"]["profile"], STORED);
}

/// A change with no destination on the call is refused, and never sent.
///
/// FR-144. The refusal is asserted to carry the number the annex gives a
/// refused command, and the same change is then run with the destination
/// written and asserted to reach the server. Without the second half this
/// would pass for a product that had simply stopped serving changes.
#[test]
fn a_change_names_its_destination_or_is_refused_before_the_server_is_reached() {
    let Some(dsn) = destination_or_skip("the declared destination") else {
        return;
    };
    let sandbox = Sandbox::new();
    store_profile(&sandbox, &dsn);

    let inherited = sandbox.run(&[
        "query",
        "run",
        "UPDATE orders SET total = total WHERE id = 1",
        "--yes",
    ]);
    assert_eq!(
        inherited.code, 3,
        "a change with an unwritten destination must be refused: {}",
        inherited.err
    );
    assert_eq!(inherited.code(), "validation.target_not_written");

    let written = on_server(
        &sandbox,
        &dsn,
        &[
            "query",
            "run",
            "UPDATE orders SET total = total WHERE id = 1",
            "--yes",
        ],
    );
    assert_eq!(
        written.code, 0,
        "the same change must pass once the call names where it goes: {}",
        written.err
    );
}

/// A read is still served from the stored default, as FR-001 designed it.
///
/// FR-144. The requirement declares this limit in its own text, so a proof that
/// only showed the refusal would leave half of it unmeasured and would let a
/// later change tighten the guard onto reads without anything objecting.
#[test]
fn a_read_is_still_served_from_the_stored_default() {
    let Some(dsn) = destination_or_skip("the declared destination") else {
        return;
    };
    let sandbox = Sandbox::new();
    store_profile(&sandbox, &dsn);

    let inherited = sandbox.run(&["schema", "tables"]);
    assert_eq!(
        inherited.code, 0,
        "a listing changes nothing and may inherit its destination: {}",
        inherited.err
    );
}

/// A destination on the call is obeyed over a different one already in force.
///
/// # Why the proofs above do not already show this
///
/// FR-143. Every one of them runs with the written destination and the inherited one
/// pointing at the same server. That is the arrangement under which the two can
/// never be told apart: a product that read the call and a product that ignored
/// it would reach the same place and report the same address, and both would
/// pass. What is measured here is the case those proofs cannot reach, which is
/// the one the requirement is actually about — the two disagreeing.
///
/// The second half is not decoration. On its own, the first half would pass for
/// a product that ignored `--profile` entirely and was saved by the stored
/// default happening to be usable. Showing that the very same call with nothing
/// written fails is what rules that out.
#[test]
fn a_destination_written_on_the_call_outranks_a_different_one_in_the_settings() {
    let Some(dsn) = destination_or_skip("the declared destination") else {
        return;
    };
    let sandbox = Sandbox::new();
    store_profile(&sandbox, &dsn);
    store_unreachable_profile(&sandbox);
    make_default(&sandbox, ELSEWHERE);

    let written = sandbox.run(&["--profile", STORED, "query", "run", "SELECT 1 AS a"]);
    assert_eq!(
        written.code, 0,
        "the destination written on the call must be the one used: {}",
        written.err
    );
    let answer = written.answer();
    assert_eq!(answer["target_source"], "argv");
    assert_eq!(answer["target_resolved"]["profile"], STORED);

    let inherited = sandbox.run(&["query", "run", "SELECT 1 AS a"]);
    assert_eq!(
        inherited.code, 5,
        "the default really does point elsewhere, so the same read without a \
         written destination must fail to reach anything: {}",
        inherited.err
    );
}

/// A destination on the call is never quietly swapped for the usable one.
///
/// # Why this runs the exchange the other way round
///
/// FR-143. The proof above shows the call being obeyed when obeying it is what works.
/// This one shows it being obeyed when obeying it is what fails: the stored
/// default points at a server that answers, and the call names one that does
/// not. A product that treated the written destination as a preference, or that
/// fell back to the default on a first refusal, would succeed here — and
/// succeeding here is the defect.
#[test]
fn a_destination_written_on_the_call_is_never_traded_for_the_one_in_force() {
    let Some(dsn) = destination_or_skip("the declared destination") else {
        return;
    };
    let sandbox = Sandbox::new();
    store_profile(&sandbox, &dsn);
    store_unreachable_profile(&sandbox);
    make_default(&sandbox, STORED);

    let served = sandbox.run(&["query", "run", "SELECT 1 AS a"]);
    assert_eq!(
        served.code, 0,
        "the default must be the usable one, or this proof shows nothing: {}",
        served.err
    );

    let displaced = sandbox.run(&["--profile", ELSEWHERE, "query", "run", "SELECT 1 AS a"]);
    assert_eq!(
        displaced.code, 5,
        "a call naming a destination that answers nothing must fail there \
         rather than be served from the one in force: {}",
        displaced.err
    );
    assert_eq!(displaced.code(), "network.unreachable");
}