use crate::cli::query::QueryCommand;
use crate::cli::{Cli, Command};
use crate::commands::query::Context;
use crate::error::Result;
use crate::sql::ParseLimits;
pub fn refuse_early(cli: &Cli, config: &crate::config::Config, context: &Context) -> Result<()> {
refuse_an_unsound_statement(cli, config, context)?;
refuse_a_named_query_that_cannot_run(cli, context)?;
refuse_an_unwritten_target(cli, config)
}
fn refuse_a_named_query_that_cannot_run(cli: &Cli, context: &Context) -> Result<()> {
let Command::Query(QueryCommand::Named(args)) = &cli.command else {
return Ok(());
};
let crate::cli::query::NamedAction::Run { name, args: given } = &args.action else {
return Ok(());
};
let catalogue = crate::exec::named::Catalogue::open(&context.config_dir)?;
let stored = catalogue.get(name)?;
crate::exec::named::arguments(stored, given).map(|_| ())
}
fn refuse_an_unsound_statement(
cli: &Cli,
config: &crate::config::Config,
context: &Context,
) -> Result<()> {
let Command::Query(command) = &cli.command else {
return Ok(());
};
let statement = match command {
QueryCommand::Run(args) => &args.statement,
QueryCommand::Explain(args) => &args.statement,
QueryCommand::Analyze(args) | QueryCommand::Lineage(args) => args,
_ => return Ok(()),
};
if statement.statement.is_none() {
return Ok(());
}
let text = crate::commands::query::statement_text(
statement,
crate::settings::no_input(&cli.globals),
context.policy.max_input_bytes,
)?;
let gated = crate::exec::gate(&text, &statement.params, &context.policy)?;
if !gated.classification().is_read() {
context.policy.admit_read_only(gated.kind())?;
refuse_a_change_a_profile_forbids(cli, config, context, gated.kind())?;
}
Ok(())
}
fn refuse_a_change_a_profile_forbids(
cli: &Cli,
config: &crate::config::Config,
context: &Context,
what: &str,
) -> Result<()> {
if cli.globals.destination.dsn.is_some() {
return Ok(());
}
let store = crate::conn::store::ProfileStore::open(&context.config_dir)?;
let stored_default = super::context::stored_default(config)?;
let Ok(profile) = store.resolve(
cli.globals.destination.profile.as_deref(),
stored_default.as_deref(),
) else {
return Ok(());
};
if profile.read_only {
return Err(crate::error::Failure::validation(
"safety.read_only",
format!(
"the profile `{}` refuses every change, and `{what}` is one",
profile.name
),
)
.with_detail("detail", what)
.with_hint("use a profile that carries changes, or clear the policy with `conn edit`"));
}
Ok(())
}
fn refuse_an_unwritten_target(cli: &Cli, config: &crate::config::Config) -> Result<()> {
use crate::output::envelope::TargetSource;
if cli.globals.destination.source() != TargetSource::Config {
return Ok(());
}
if !crate::settings::boolean(config, "conn.require_explicit_target")? {
return Ok(());
}
let limits = ParseLimits::from_server(config)?;
if !can_change_the_server(cli, limits) {
return Ok(());
}
Err(crate::error::Failure::validation(
"validation.target_not_written",
"this command can change the server and no destination was named on the call",
)
.with_hint(
"name the destination with --profile or --dsn, or turn off conn.require_explicit_target",
))
}
fn can_change_the_server(cli: &Cli, limits: ParseLimits) -> bool {
match &cli.command {
Command::Query(command) => match command {
QueryCommand::Sample(_)
| QueryCommand::Explain(_)
| QueryCommand::Lineage(_)
| QueryCommand::Plan(_) => false,
QueryCommand::Run(args) => args
.statement
.statement
.as_deref()
.and_then(|text| crate::sql::classify::classify(text, limits).ok())
.is_none_or(|kind| !kind.is_read()),
QueryCommand::Named(args) => {
matches!(args.action, crate::cli::query::NamedAction::Run { .. })
}
_ => true,
},
Command::Data(_) => true,
Command::Server(command) => matches!(command, crate::cli::server::ServerCommand::Kill(_)),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
fn parse(args: &[&str]) -> Cli {
let command_line: Vec<String> = std::iter::once("mariadb-cli")
.chain(args.iter().copied())
.map(ToOwned::to_owned)
.collect();
Cli::try_parse_from(command_line).expect("the sample invocation parses")
}
fn context() -> Context {
let scratch = tempfile::tempdir().expect("scratch directory");
let config = crate::config::Config::load(Some(scratch.path())).expect("loads");
super::super::context::query_context(
&config,
&parse(&["query", "run", "SELECT 1"]),
tokio_util::sync::CancellationToken::new(),
)
.expect("builds")
}
fn settings() -> crate::config::Config {
let scratch = tempfile::tempdir().expect("scratch directory");
crate::config::Config::load(Some(scratch.path())).expect("loads")
}
#[test]
fn the_bounds_handed_in_decide_the_judgement_and_not_the_defaults() {
let call = parse(&["query", "run", "SELECT 'a long reading' AS note"]);
assert!(
!can_change_the_server(&call, ParseLimits::default()),
"a reading under generous bounds is a reading"
);
assert!(
can_change_the_server(
&call,
ParseLimits::new(8, crate::sql::parse::DEFAULT_PARSER_STACK_BYTES)
),
"the same reading above the configured ceiling does not parse, and \
what cannot be read is treated as a change"
);
}
#[test]
fn a_rule_that_names_several_destinations_is_a_destination_written() {
let context = context();
let config = settings();
refuse_early(
&parse(&[
"--all-profiles",
"query",
"run",
"DELETE FROM t WHERE id = 1",
]),
&config,
&context,
)
.expect("the call named which destinations it wanted");
}
#[test]
fn a_change_with_no_destination_written_is_refused() {
let context = context();
let config = settings();
let failure = refuse_early(
&parse(&["query", "run", "DELETE FROM t WHERE id = 1"]),
&config,
&context,
)
.expect_err("an unwritten destination must be refused");
assert_eq!(failure.category(), crate::error::Category::Validation);
assert!(
refuse_early(
&parse(&[
"--profile",
"producao",
"query",
"run",
"DELETE FROM t WHERE id = 1"
]),
&config,
&context,
)
.is_ok(),
"the same change passes once the call names where it goes"
);
}
#[test]
fn a_statement_that_condemns_itself_is_named_before_the_missing_destination() {
let context = context();
let config = settings();
let failure = refuse_early(
&parse(&[
"query",
"run",
"DELETE FROM t WHERE id = 1; DELETE FROM u WHERE id = 1",
]),
&config,
&context,
)
.expect_err("two commands carried in one text must be refused");
assert_eq!(
failure.code(),
"sql.multiple_statements",
"the statement's own refusal must answer first; \
`validation.target_not_written` here would send the caller after \
the wrong problem, and would mean the guards had been reordered"
);
}
#[test]
fn a_kept_statement_nobody_kept_is_named_before_the_missing_destination() {
let context = context();
let config = settings();
let failure = refuse_early(
&parse(&["query", "named", "run", "relatorio-do-mes"]),
&config,
&context,
)
.expect_err("a name that was never kept must be refused");
assert_eq!(
failure.code(),
"absence.unknown_named_statement",
"the catalogue's own refusal must answer first; \
`validation.target_not_written` here would send the caller after \
the wrong problem, and would mean the guards had been reordered"
);
}
#[test]
fn a_read_still_inherits_the_stored_default() {
assert!(
refuse_early(
&parse(&["query", "run", "SELECT 1"]),
&settings(),
&context()
)
.is_ok(),
"reading is allowed to inherit"
);
assert!(
refuse_early(&parse(&["schema", "tables"]), &settings(), &context()).is_ok(),
"a structure listing changes nothing and may inherit"
);
}
#[test]
fn a_statement_nobody_can_read_yet_is_treated_as_a_change() {
let failure = refuse_early(
&parse(&["query", "run", "--stdin"]),
&settings(),
&context(),
)
.expect_err("an unreadable statement must not inherit its destination");
assert_eq!(failure.category(), crate::error::Category::Validation);
}
#[test]
fn a_refused_statement_never_reaches_the_network() {
let context = context();
for statement in [
"SELECT 1; SELECT 2;",
"SELECT LOAD_FILE('/etc/passwd')",
"SELEC 1",
] {
let failure = refuse_early(&parse(&["query", "run", statement]), &settings(), &context)
.expect_err("must refuse before connecting");
assert_eq!(
failure.category(),
crate::error::Category::Validation,
"`{statement}` must be refused by analysis, not by the network",
);
}
}
#[test]
fn a_sound_statement_passes_through_untouched() {
assert!(refuse_early(
&parse(&["query", "run", "SELECT 1"]),
&settings(),
&context()
)
.is_ok());
}
#[test]
fn a_command_without_statement_text_is_left_to_the_server() {
let context = context();
assert!(refuse_early(&parse(&["schema", "tables"]), &settings(), &context).is_ok());
assert!(refuse_early(&parse(&["server", "status"]), &settings(), &context).is_ok());
assert!(
refuse_early(
&parse(&["query", "sample", "--table", "t"]),
&settings(),
&context
)
.is_ok(),
"naming a table is not statement text"
);
}
#[test]
fn a_statement_still_on_the_input_stream_is_not_consumed() {
assert!(refuse_early(
&parse(&["--profile", "producao", "query", "run", "--stdin"]),
&settings(),
&context()
)
.is_ok());
}
}