2024-04-26 00:30:32 +02:00
|
|
|
use anyhow::{anyhow, Context};
|
2024-04-21 06:03:25 +02:00
|
|
|
use clap::Parser;
|
2024-08-07 16:43:26 +02:00
|
|
|
use dialoguer::Editor;
|
2024-04-26 00:30:32 +02:00
|
|
|
use indoc::indoc;
|
|
|
|
use itertools::Itertools;
|
2024-04-21 06:03:25 +02:00
|
|
|
use prettytable::{Cell, Row, Table};
|
2024-08-07 16:54:26 +02:00
|
|
|
use sqlx::{Connection, MySqlConnection};
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-04-26 00:30:32 +02:00
|
|
|
use crate::core::{
|
2024-08-07 20:50:39 +02:00
|
|
|
common::{close_database_connection, get_current_unix_user, yn},
|
|
|
|
database_operations::*,
|
|
|
|
database_privilege_operations::*,
|
2024-08-06 23:48:31 +02:00
|
|
|
user_operations::user_exists,
|
2024-04-26 00:30:32 +02:00
|
|
|
};
|
2024-04-21 06:03:25 +02:00
|
|
|
|
|
|
|
#[derive(Parser)]
|
2024-07-09 19:54:27 +02:00
|
|
|
// #[command(next_help_heading = Some(DATABASE_COMMAND_HEADER))]
|
|
|
|
pub enum DatabaseCommand {
|
|
|
|
/// Create one or more databases
|
|
|
|
#[command()]
|
|
|
|
CreateDb(DatabaseCreateArgs),
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-07-09 19:54:27 +02:00
|
|
|
/// Delete one or more databases
|
|
|
|
#[command()]
|
|
|
|
DropDb(DatabaseDropArgs),
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-07-09 19:54:27 +02:00
|
|
|
/// List all databases you have access to
|
2024-04-21 06:03:25 +02:00
|
|
|
#[command()]
|
2024-07-09 19:54:27 +02:00
|
|
|
ListDb(DatabaseListArgs),
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-07-09 19:54:27 +02:00
|
|
|
/// List user permissions for one or more databases
|
2024-04-21 06:03:25 +02:00
|
|
|
///
|
2024-07-09 19:54:27 +02:00
|
|
|
/// If no database names are provided, it will show permissions for all databases you have access to.
|
|
|
|
#[command()]
|
|
|
|
ShowDbPerm(DatabaseShowPermArgs),
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-07-09 19:54:27 +02:00
|
|
|
/// Change user permissions for one or more databases. See `edit-db-perm --help` for details.
|
2024-04-21 06:03:25 +02:00
|
|
|
///
|
|
|
|
/// This command has two modes of operation:
|
2024-07-09 19:54:27 +02:00
|
|
|
///
|
2024-04-26 00:30:32 +02:00
|
|
|
/// 1. Interactive mode: If nothing else is specified, the user will be prompted to edit the permissions using a text editor.
|
|
|
|
///
|
2024-07-09 19:54:27 +02:00
|
|
|
/// You can configure your preferred text editor by setting the `VISUAL` or `EDITOR` environment variables.
|
|
|
|
///
|
2024-04-26 00:30:32 +02:00
|
|
|
/// Follow the instructions inside the editor for more information.
|
2024-04-21 06:03:25 +02:00
|
|
|
///
|
2024-04-26 00:30:32 +02:00
|
|
|
/// 2. Non-interactive mode: If the `-p` flag is specified, the user can write permissions using arguments.
|
2024-04-21 06:03:25 +02:00
|
|
|
///
|
2024-04-26 00:30:32 +02:00
|
|
|
/// The permission arguments should be formatted as `<db>:<user>:<privileges>`
|
|
|
|
/// where the privileges are a string of characters, each representing a single permissions.
|
|
|
|
/// The character `A` is an exception, because it represents all permissions.
|
2024-04-21 06:03:25 +02:00
|
|
|
///
|
2024-07-09 19:54:27 +02:00
|
|
|
/// The character to permission mapping is declared as follows:
|
2024-04-21 06:03:25 +02:00
|
|
|
///
|
2024-04-26 00:30:32 +02:00
|
|
|
/// - `s` - SELECT
|
|
|
|
/// - `i` - INSERT
|
|
|
|
/// - `u` - UPDATE
|
|
|
|
/// - `d` - DELETE
|
|
|
|
/// - `c` - CREATE
|
|
|
|
/// - `D` - DROP
|
|
|
|
/// - `a` - ALTER
|
|
|
|
/// - `I` - INDEX
|
|
|
|
/// - `t` - CREATE TEMPORARY TABLES
|
|
|
|
/// - `l` - LOCK TABLES
|
|
|
|
/// - `r` - REFERENCES
|
|
|
|
/// - `A` - ALL PRIVILEGES
|
2024-04-21 06:03:25 +02:00
|
|
|
///
|
2024-07-09 19:54:27 +02:00
|
|
|
/// If you provide a database name, you can omit it from the permission arguments.
|
|
|
|
///
|
|
|
|
/// Example usage of non-interactive mode:
|
|
|
|
///
|
|
|
|
/// Set permissions `SELECT`, `INSERT`, and `UPDATE` for user `my_user` on database `my_db`:
|
|
|
|
///
|
|
|
|
/// mysqladm edit-db-perm -p my_db:my_user:siu
|
|
|
|
///
|
|
|
|
/// Set all permissions for user `my_other_user` on database `my_other_db`:
|
|
|
|
///
|
|
|
|
/// mysqladm edit-db-perm -p my_other_db:my_other_user:A
|
|
|
|
///
|
|
|
|
/// Set miscellaneous permissions for multiple users on database `my_db`:
|
|
|
|
///
|
|
|
|
/// mysqladm edit-db-perm my_db -p my_user:siu my_other_user:ct
|
|
|
|
///
|
|
|
|
#[command(verbatim_doc_comment)]
|
|
|
|
EditDbPerm(DatabaseEditPermArgs),
|
2024-04-21 06:03:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Parser)]
|
2024-07-09 19:54:27 +02:00
|
|
|
pub struct DatabaseCreateArgs {
|
2024-04-21 06:03:25 +02:00
|
|
|
/// The name of the database(s) to create.
|
|
|
|
#[arg(num_args = 1..)]
|
|
|
|
name: Vec<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Parser)]
|
2024-07-09 19:54:27 +02:00
|
|
|
pub struct DatabaseDropArgs {
|
2024-04-21 06:03:25 +02:00
|
|
|
/// The name of the database(s) to drop.
|
|
|
|
#[arg(num_args = 1..)]
|
|
|
|
name: Vec<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Parser)]
|
2024-07-09 19:54:27 +02:00
|
|
|
pub struct DatabaseListArgs {
|
2024-04-21 06:03:25 +02:00
|
|
|
/// Whether to output the information in JSON format.
|
|
|
|
#[arg(short, long)]
|
|
|
|
json: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Parser)]
|
2024-07-09 19:54:27 +02:00
|
|
|
pub struct DatabaseShowPermArgs {
|
2024-04-21 06:03:25 +02:00
|
|
|
/// The name of the database(s) to show.
|
|
|
|
#[arg(num_args = 0..)]
|
|
|
|
name: Vec<String>,
|
|
|
|
|
|
|
|
/// Whether to output the information in JSON format.
|
|
|
|
#[arg(short, long)]
|
|
|
|
json: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Parser)]
|
2024-07-09 19:54:27 +02:00
|
|
|
pub struct DatabaseEditPermArgs {
|
2024-04-21 06:03:25 +02:00
|
|
|
/// The name of the database to edit permissions for.
|
2024-08-05 22:37:23 +02:00
|
|
|
pub name: Option<String>,
|
2024-04-21 06:03:25 +02:00
|
|
|
|
|
|
|
#[arg(short, long, value_name = "[DATABASE:]USER:PERMISSIONS", num_args = 0..)]
|
2024-08-05 22:37:23 +02:00
|
|
|
pub perm: Vec<String>,
|
2024-04-21 06:03:25 +02:00
|
|
|
|
|
|
|
/// Whether to output the information in JSON format.
|
|
|
|
#[arg(short, long)]
|
2024-08-05 22:37:23 +02:00
|
|
|
pub json: bool,
|
2024-04-21 06:03:25 +02:00
|
|
|
|
|
|
|
/// Specify the text editor to use for editing permissions.
|
|
|
|
#[arg(short, long)]
|
2024-08-05 22:37:23 +02:00
|
|
|
pub editor: Option<String>,
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-07-09 19:54:27 +02:00
|
|
|
/// Disable interactive confirmation before saving changes.
|
2024-04-21 06:03:25 +02:00
|
|
|
#[arg(short, long)]
|
2024-08-05 22:37:23 +02:00
|
|
|
pub yes: bool,
|
2024-04-21 06:03:25 +02:00
|
|
|
}
|
|
|
|
|
2024-07-09 19:54:27 +02:00
|
|
|
pub async fn handle_command(
|
|
|
|
command: DatabaseCommand,
|
|
|
|
mut conn: MySqlConnection,
|
|
|
|
) -> anyhow::Result<()> {
|
2024-08-07 16:54:26 +02:00
|
|
|
let result = conn
|
2024-08-07 16:55:51 +02:00
|
|
|
.transaction(|txn| {
|
2024-08-07 16:54:26 +02:00
|
|
|
Box::pin(async move {
|
|
|
|
match command {
|
2024-08-07 16:55:51 +02:00
|
|
|
DatabaseCommand::CreateDb(args) => create_databases(args, txn).await,
|
|
|
|
DatabaseCommand::DropDb(args) => drop_databases(args, txn).await,
|
|
|
|
DatabaseCommand::ListDb(args) => list_databases(args, txn).await,
|
|
|
|
DatabaseCommand::ShowDbPerm(args) => show_databases(args, txn).await,
|
|
|
|
DatabaseCommand::EditDbPerm(args) => edit_permissions(args, txn).await,
|
2024-08-07 16:54:26 +02:00
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
.await;
|
2024-04-26 00:29:39 +02:00
|
|
|
|
2024-08-07 16:16:46 +02:00
|
|
|
close_database_connection(conn).await;
|
2024-04-26 00:29:39 +02:00
|
|
|
|
|
|
|
result
|
2024-04-21 06:03:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn create_databases(
|
|
|
|
args: DatabaseCreateArgs,
|
2024-04-26 00:29:39 +02:00
|
|
|
conn: &mut MySqlConnection,
|
2024-04-21 06:03:25 +02:00
|
|
|
) -> anyhow::Result<()> {
|
|
|
|
if args.name.is_empty() {
|
|
|
|
anyhow::bail!("No database names provided");
|
|
|
|
}
|
|
|
|
|
|
|
|
for name in args.name {
|
|
|
|
// TODO: This can be optimized by fetching all the database privileges in one query.
|
2024-08-07 20:50:39 +02:00
|
|
|
if let Err(e) = create_database(&name, conn).await {
|
2024-04-21 06:03:25 +02:00
|
|
|
eprintln!("Failed to create database '{}': {}", name, e);
|
|
|
|
eprintln!("Skipping...");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-04-26 00:29:39 +02:00
|
|
|
async fn drop_databases(args: DatabaseDropArgs, conn: &mut MySqlConnection) -> anyhow::Result<()> {
|
2024-04-21 06:03:25 +02:00
|
|
|
if args.name.is_empty() {
|
|
|
|
anyhow::bail!("No database names provided");
|
|
|
|
}
|
|
|
|
|
|
|
|
for name in args.name {
|
|
|
|
// TODO: This can be optimized by fetching all the database privileges in one query.
|
2024-08-07 20:50:39 +02:00
|
|
|
if let Err(e) = drop_database(&name, conn).await {
|
2024-04-21 06:03:25 +02:00
|
|
|
eprintln!("Failed to drop database '{}': {}", name, e);
|
|
|
|
eprintln!("Skipping...");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-04-26 00:29:39 +02:00
|
|
|
async fn list_databases(args: DatabaseListArgs, conn: &mut MySqlConnection) -> anyhow::Result<()> {
|
2024-08-07 20:50:39 +02:00
|
|
|
let databases = get_database_list(conn).await?;
|
2024-04-21 06:03:25 +02:00
|
|
|
|
|
|
|
if databases.is_empty() {
|
|
|
|
println!("No databases to show.");
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
if args.json {
|
|
|
|
println!("{}", serde_json::to_string_pretty(&databases)?);
|
|
|
|
} else {
|
2024-04-26 00:30:32 +02:00
|
|
|
for db in databases {
|
|
|
|
println!("{}", db);
|
|
|
|
}
|
2024-04-21 06:03:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2024-04-26 00:29:39 +02:00
|
|
|
async fn show_databases(
|
|
|
|
args: DatabaseShowPermArgs,
|
|
|
|
conn: &mut MySqlConnection,
|
|
|
|
) -> anyhow::Result<()> {
|
2024-04-21 06:03:25 +02:00
|
|
|
let database_users_to_show = if args.name.is_empty() {
|
2024-08-07 20:50:39 +02:00
|
|
|
get_all_database_privileges(conn).await?
|
2024-04-21 06:03:25 +02:00
|
|
|
} else {
|
|
|
|
// TODO: This can be optimized by fetching all the database privileges in one query.
|
|
|
|
let mut result = Vec::with_capacity(args.name.len());
|
|
|
|
for name in args.name {
|
2024-08-07 20:50:39 +02:00
|
|
|
match get_database_privileges(&name, conn).await {
|
2024-04-21 06:03:25 +02:00
|
|
|
Ok(db) => result.extend(db),
|
|
|
|
Err(e) => {
|
|
|
|
eprintln!("Failed to show database '{}': {}", name, e);
|
|
|
|
eprintln!("Skipping...");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
result
|
|
|
|
};
|
|
|
|
|
|
|
|
if database_users_to_show.is_empty() {
|
|
|
|
println!("No database users to show.");
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
if args.json {
|
|
|
|
println!("{}", serde_json::to_string_pretty(&database_users_to_show)?);
|
|
|
|
} else {
|
|
|
|
let mut table = Table::new();
|
|
|
|
table.add_row(Row::new(
|
2024-04-26 00:30:32 +02:00
|
|
|
DATABASE_PRIVILEGE_FIELDS
|
|
|
|
.into_iter()
|
|
|
|
.map(db_priv_field_human_readable_name)
|
|
|
|
.map(|name| Cell::new(&name))
|
2024-04-21 06:03:25 +02:00
|
|
|
.collect(),
|
|
|
|
));
|
|
|
|
|
|
|
|
for row in database_users_to_show {
|
|
|
|
table.add_row(row![
|
|
|
|
row.db,
|
|
|
|
row.user,
|
2024-07-12 23:35:57 +02:00
|
|
|
c->yn(row.select_priv),
|
|
|
|
c->yn(row.insert_priv),
|
|
|
|
c->yn(row.update_priv),
|
|
|
|
c->yn(row.delete_priv),
|
|
|
|
c->yn(row.create_priv),
|
|
|
|
c->yn(row.drop_priv),
|
|
|
|
c->yn(row.alter_priv),
|
|
|
|
c->yn(row.index_priv),
|
|
|
|
c->yn(row.create_tmp_table_priv),
|
|
|
|
c->yn(row.lock_tables_priv),
|
|
|
|
c->yn(row.references_priv),
|
2024-04-21 06:03:25 +02:00
|
|
|
]);
|
|
|
|
}
|
|
|
|
table.printstd();
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// See documentation for `DatabaseCommand::EditPerm`.
|
2024-08-07 20:50:39 +02:00
|
|
|
fn parse_permission_table_cli_arg(arg: &str) -> anyhow::Result<DatabasePrivilegeRow> {
|
2024-04-21 06:03:25 +02:00
|
|
|
let parts: Vec<&str> = arg.split(':').collect();
|
|
|
|
if parts.len() != 3 {
|
|
|
|
anyhow::bail!("Invalid argument format. See `edit-perm --help` for more information.");
|
|
|
|
}
|
|
|
|
|
|
|
|
let db = parts[0].to_string();
|
|
|
|
let user = parts[1].to_string();
|
|
|
|
let privs = parts[2].to_string();
|
|
|
|
|
2024-08-07 20:50:39 +02:00
|
|
|
let mut result = DatabasePrivilegeRow {
|
2024-04-21 06:03:25 +02:00
|
|
|
db,
|
|
|
|
user,
|
2024-04-26 00:30:32 +02:00
|
|
|
select_priv: false,
|
|
|
|
insert_priv: false,
|
|
|
|
update_priv: false,
|
|
|
|
delete_priv: false,
|
|
|
|
create_priv: false,
|
|
|
|
drop_priv: false,
|
|
|
|
alter_priv: false,
|
|
|
|
index_priv: false,
|
|
|
|
create_tmp_table_priv: false,
|
|
|
|
lock_tables_priv: false,
|
|
|
|
references_priv: false,
|
2024-04-21 06:03:25 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
for char in privs.chars() {
|
|
|
|
match char {
|
2024-04-26 00:30:32 +02:00
|
|
|
's' => result.select_priv = true,
|
|
|
|
'i' => result.insert_priv = true,
|
|
|
|
'u' => result.update_priv = true,
|
|
|
|
'd' => result.delete_priv = true,
|
|
|
|
'c' => result.create_priv = true,
|
|
|
|
'D' => result.drop_priv = true,
|
|
|
|
'a' => result.alter_priv = true,
|
|
|
|
'I' => result.index_priv = true,
|
|
|
|
't' => result.create_tmp_table_priv = true,
|
|
|
|
'l' => result.lock_tables_priv = true,
|
|
|
|
'r' => result.references_priv = true,
|
2024-04-21 06:03:25 +02:00
|
|
|
'A' => {
|
2024-04-26 00:30:32 +02:00
|
|
|
result.select_priv = true;
|
|
|
|
result.insert_priv = true;
|
|
|
|
result.update_priv = true;
|
|
|
|
result.delete_priv = true;
|
|
|
|
result.create_priv = true;
|
|
|
|
result.drop_priv = true;
|
|
|
|
result.alter_priv = true;
|
|
|
|
result.index_priv = true;
|
|
|
|
result.create_tmp_table_priv = true;
|
|
|
|
result.lock_tables_priv = true;
|
|
|
|
result.references_priv = true;
|
2024-04-21 06:03:25 +02:00
|
|
|
}
|
|
|
|
_ => anyhow::bail!("Invalid permission character: {}", char),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(result)
|
|
|
|
}
|
|
|
|
|
2024-04-26 00:30:32 +02:00
|
|
|
fn parse_permission(yn: &str) -> anyhow::Result<bool> {
|
|
|
|
match yn.to_ascii_lowercase().as_str() {
|
|
|
|
"y" => Ok(true),
|
|
|
|
"n" => Ok(false),
|
|
|
|
_ => Err(anyhow!("Expected Y or N, found {}", yn)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-07 20:50:39 +02:00
|
|
|
fn parse_permission_data_from_editor(content: String) -> anyhow::Result<Vec<DatabasePrivilegeRow>> {
|
2024-04-26 00:30:32 +02:00
|
|
|
content
|
|
|
|
.trim()
|
|
|
|
.split('\n')
|
|
|
|
.map(|line| line.trim())
|
|
|
|
.filter(|line| !(line.starts_with('#') || line.starts_with("//") || line == &""))
|
|
|
|
.skip(1)
|
|
|
|
.map(|line| {
|
|
|
|
let line_parts: Vec<&str> = line.trim().split_ascii_whitespace().collect();
|
|
|
|
if line_parts.len() != DATABASE_PRIVILEGE_FIELDS.len() {
|
|
|
|
anyhow::bail!("")
|
|
|
|
}
|
|
|
|
|
2024-08-07 20:50:39 +02:00
|
|
|
Ok(DatabasePrivilegeRow {
|
2024-07-12 21:59:44 +02:00
|
|
|
db: (*line_parts.first().unwrap()).to_owned(),
|
2024-04-26 00:30:32 +02:00
|
|
|
user: (*line_parts.get(1).unwrap()).to_owned(),
|
2024-07-12 21:59:44 +02:00
|
|
|
select_priv: parse_permission(line_parts.get(2).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse SELECT privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
insert_priv: parse_permission(line_parts.get(3).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse INSERT privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
update_priv: parse_permission(line_parts.get(4).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse UPDATE privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
delete_priv: parse_permission(line_parts.get(5).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse DELETE privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
create_priv: parse_permission(line_parts.get(6).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse CREATE privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
drop_priv: parse_permission(line_parts.get(7).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse DROP privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
alter_priv: parse_permission(line_parts.get(8).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse ALTER privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
index_priv: parse_permission(line_parts.get(9).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse INDEX privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
create_tmp_table_priv: parse_permission(line_parts.get(10).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse CREATE TEMPORARY TABLE privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
lock_tables_priv: parse_permission(line_parts.get(11).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse LOCK TABLES privilege")?,
|
2024-07-12 21:59:44 +02:00
|
|
|
references_priv: parse_permission(line_parts.get(12).unwrap())
|
2024-04-26 00:30:32 +02:00
|
|
|
.context("Could not parse REFERENCES privilege")?,
|
|
|
|
})
|
|
|
|
})
|
2024-08-07 20:50:39 +02:00
|
|
|
.collect::<anyhow::Result<Vec<DatabasePrivilegeRow>>>()
|
2024-04-26 00:30:32 +02:00
|
|
|
}
|
|
|
|
|
2024-07-12 23:35:57 +02:00
|
|
|
fn format_privileges_line(
|
2024-08-07 20:50:39 +02:00
|
|
|
privs: &DatabasePrivilegeRow,
|
2024-07-12 23:35:57 +02:00
|
|
|
username_len: usize,
|
|
|
|
database_name_len: usize,
|
|
|
|
) -> String {
|
|
|
|
// Format a privileges line by padding each value with spaces
|
|
|
|
// The first two fields are padded to the length of the longest username and database name
|
|
|
|
// The remaining fields are padded to the length of the corresponding field name
|
|
|
|
|
|
|
|
DATABASE_PRIVILEGE_FIELDS
|
|
|
|
.into_iter()
|
|
|
|
.map(|field| match field {
|
|
|
|
"db" => format!("{:width$}", privs.db, width = database_name_len),
|
|
|
|
"user" => format!("{:width$}", privs.user, width = username_len),
|
|
|
|
privilege => format!(
|
|
|
|
"{:width$}",
|
|
|
|
yn(privs.get_privilege_by_name(privilege)),
|
|
|
|
width = db_priv_field_human_readable_name(privilege).len()
|
|
|
|
),
|
|
|
|
})
|
|
|
|
.join(" ")
|
|
|
|
.trim()
|
|
|
|
.to_string()
|
2024-04-26 00:30:32 +02:00
|
|
|
}
|
|
|
|
|
2024-08-05 22:37:23 +02:00
|
|
|
pub async fn edit_permissions(
|
2024-04-26 00:29:39 +02:00
|
|
|
args: DatabaseEditPermArgs,
|
|
|
|
conn: &mut MySqlConnection,
|
|
|
|
) -> anyhow::Result<()> {
|
2024-04-26 00:30:32 +02:00
|
|
|
let permission_data = if let Some(name) = &args.name {
|
2024-08-07 20:50:39 +02:00
|
|
|
get_database_privileges(name, conn).await?
|
2024-04-21 06:03:25 +02:00
|
|
|
} else {
|
2024-08-07 20:50:39 +02:00
|
|
|
get_all_database_privileges(conn).await?
|
2024-04-21 06:03:25 +02:00
|
|
|
};
|
|
|
|
|
2024-04-26 00:30:32 +02:00
|
|
|
let permissions_to_change = if !args.perm.is_empty() {
|
|
|
|
if let Some(name) = args.name {
|
2024-04-21 06:03:25 +02:00
|
|
|
args.perm
|
|
|
|
.iter()
|
|
|
|
.map(|perm| {
|
|
|
|
parse_permission_table_cli_arg(&format!("{}:{}", name, &perm))
|
|
|
|
.context(format!("Failed parsing database permissions: `{}`", &perm))
|
|
|
|
})
|
2024-08-07 20:50:39 +02:00
|
|
|
.collect::<anyhow::Result<Vec<DatabasePrivilegeRow>>>()?
|
2024-04-21 06:03:25 +02:00
|
|
|
} else {
|
|
|
|
args.perm
|
|
|
|
.iter()
|
|
|
|
.map(|perm| {
|
|
|
|
parse_permission_table_cli_arg(perm)
|
|
|
|
.context(format!("Failed parsing database permissions: `{}`", &perm))
|
|
|
|
})
|
2024-08-07 20:50:39 +02:00
|
|
|
.collect::<anyhow::Result<Vec<DatabasePrivilegeRow>>>()?
|
2024-04-26 00:30:32 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let comment = indoc! {r#"
|
|
|
|
# Welcome to the permission editor.
|
2024-07-12 21:59:44 +02:00
|
|
|
# Each line defines what permissions a single user has on a single database.
|
|
|
|
# The first two columns respectively represent the database name and the user, and the remaining columns are the permissions.
|
|
|
|
# If the user should have a permission, write 'Y', otherwise write 'N'.
|
|
|
|
#
|
|
|
|
# Lines starting with '#' are comments and will be ignored.
|
2024-04-26 00:30:32 +02:00
|
|
|
"#};
|
2024-07-12 21:59:44 +02:00
|
|
|
|
2024-07-12 23:35:57 +02:00
|
|
|
let unix_user = get_current_unix_user()?;
|
|
|
|
let example_user = format!("{}_user", unix_user.name);
|
|
|
|
let example_db = format!("{}_db", unix_user.name);
|
|
|
|
|
|
|
|
let longest_username = permission_data
|
|
|
|
.iter()
|
|
|
|
.map(|p| p.user.len())
|
|
|
|
.max()
|
|
|
|
.unwrap_or(example_user.len());
|
|
|
|
|
|
|
|
let longest_database_name = permission_data
|
|
|
|
.iter()
|
|
|
|
.map(|p| p.db.len())
|
|
|
|
.max()
|
|
|
|
.unwrap_or(example_db.len());
|
|
|
|
|
|
|
|
let mut header: Vec<_> = DATABASE_PRIVILEGE_FIELDS
|
|
|
|
.into_iter()
|
|
|
|
.map(db_priv_field_human_readable_name)
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
// Pad the first two columns with spaces to align the permissions.
|
|
|
|
header[0] = format!("{:width$}", header[0], width = longest_database_name);
|
|
|
|
header[1] = format!("{:width$}", header[1], width = longest_username);
|
|
|
|
|
|
|
|
let example_line = format_privileges_line(
|
2024-08-07 20:50:39 +02:00
|
|
|
&DatabasePrivilegeRow {
|
2024-07-12 23:35:57 +02:00
|
|
|
db: example_db,
|
|
|
|
user: example_user,
|
|
|
|
select_priv: true,
|
|
|
|
insert_priv: true,
|
|
|
|
update_priv: true,
|
|
|
|
delete_priv: true,
|
|
|
|
create_priv: false,
|
|
|
|
drop_priv: false,
|
|
|
|
alter_priv: false,
|
|
|
|
index_priv: false,
|
|
|
|
create_tmp_table_priv: false,
|
|
|
|
lock_tables_priv: false,
|
|
|
|
references_priv: false,
|
|
|
|
},
|
|
|
|
longest_username,
|
|
|
|
longest_database_name,
|
|
|
|
);
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-08-07 16:43:26 +02:00
|
|
|
// TODO: handle errors better here
|
|
|
|
let result = Editor::new()
|
|
|
|
.extension("tsv")
|
|
|
|
.edit(
|
|
|
|
format!(
|
|
|
|
"{}\n{}\n{}",
|
|
|
|
comment,
|
|
|
|
header.join(" "),
|
|
|
|
if permission_data.is_empty() {
|
|
|
|
format!("# {}", example_line)
|
|
|
|
} else {
|
|
|
|
permission_data
|
|
|
|
.iter()
|
|
|
|
.map(|perm| {
|
|
|
|
format_privileges_line(
|
|
|
|
perm,
|
|
|
|
longest_username,
|
|
|
|
longest_database_name,
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.join("\n")
|
|
|
|
}
|
|
|
|
)
|
|
|
|
.as_str(),
|
|
|
|
)?
|
|
|
|
.unwrap();
|
2024-04-26 00:30:32 +02:00
|
|
|
|
|
|
|
parse_permission_data_from_editor(result)
|
|
|
|
.context("Could not parse permission data from editor")?
|
|
|
|
};
|
|
|
|
|
2024-08-06 23:41:11 +02:00
|
|
|
for row in permissions_to_change.iter() {
|
2024-08-06 23:48:31 +02:00
|
|
|
if !user_exists(&row.user, conn).await? {
|
|
|
|
// TODO: allow user to return and correct their mistake
|
|
|
|
anyhow::bail!("User {} does not exist", row.user);
|
|
|
|
}
|
2024-08-06 23:41:11 +02:00
|
|
|
}
|
|
|
|
|
2024-04-26 00:30:32 +02:00
|
|
|
let diffs = diff_permissions(permission_data, &permissions_to_change).await;
|
|
|
|
|
|
|
|
if diffs.is_empty() {
|
|
|
|
println!("No changes to make.");
|
|
|
|
return Ok(());
|
2024-04-21 06:03:25 +02:00
|
|
|
}
|
|
|
|
|
2024-04-26 00:30:32 +02:00
|
|
|
// TODO: Add confirmation prompt.
|
|
|
|
|
|
|
|
apply_permission_diffs(diffs, conn).await?;
|
2024-04-21 06:03:25 +02:00
|
|
|
|
2024-04-26 00:30:32 +02:00
|
|
|
Ok(())
|
2024-04-21 06:03:25 +02:00
|
|
|
}
|