Compare commits

..

No commits in common. "cd0b2c3e6d6fee6ea9919821b24dc03f8b1d07b9" and "86b5b47f1ea7c02b4487e9688d5900bd6b8dee30" have entirely different histories.

6 changed files with 48 additions and 188 deletions

View File

@ -50,12 +50,10 @@ async fn socket_activate(config: ServerConfig) -> anyhow::Result<()> {
// TODO: allow getting socket path from other socket activation sources
let conn = get_socket_from_systemd().await?;
let uid = conn.peer_cred()?.uid();
let unix_user = UnixUser::from_uid(uid)?;
let unix_user = UnixUser::from_uid(uid.into())?;
log::info!("Accepted connection from {}", unix_user.username);
sd_notify::notify(true, &[sd_notify::NotifyState::Ready]).ok();
handle_requests_for_single_session(conn, &unix_user, &config).await?;
Ok(())

View File

@ -102,11 +102,8 @@ pub async fn create_mysql_connection_from_config(
config: &MysqlConfig,
) -> anyhow::Result<MySqlConnection> {
let mut display_config = config.clone();
"<REDACTED>".clone_into(&mut display_config.password);
log::debug!(
"Connecting to MySQL server with parameters: {:#?}",
display_config
);
display_config.password = "<REDACTED>".to_owned();
log::debug!("Connecting to MySQL server with parameters: {:#?}", display_config);
match tokio::time::timeout(
Duration::from_secs(config.timeout.unwrap_or(DEFAULT_TIMEOUT)),

View File

@ -57,13 +57,11 @@ pub async fn listen_for_incoming_connections(
let listener = UnixListener::bind(socket_path)?;
sd_notify::notify(true, &[sd_notify::NotifyState::Ready]).ok();
while let Ok((mut conn, _addr)) = listener.accept().await {
let uid = conn.peer_cred()?.uid();
log::trace!("Accepted connection from uid {}", uid);
let unix_user = match UnixUser::from_uid(uid) {
let unix_user = match UnixUser::from_uid(uid.into()) {
Ok(user) => user,
Err(e) => {
eprintln!("Failed to get UnixUser from uid: {}", e);

View File

@ -26,17 +26,9 @@ pub(super) async fn unsafe_database_exists(
sqlx::query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?")
.bind(database_name)
.fetch_optional(connection)
.await;
.await?;
if let Err(err) = &result {
log::error!(
"Failed to check if database '{}' exists: {:?}",
&database_name,
err
);
}
Ok(result?.is_some())
Ok(result.is_some())
}
pub async fn create_databases(
@ -88,10 +80,6 @@ pub async fn create_databases(
.map(|_| ())
.map_err(|err| CreateDatabaseError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!("Failed to create database '{}': {:?}", &database_name, err);
}
results.insert(database_name, result);
}
@ -147,10 +135,6 @@ pub async fn drop_databases(
.map(|_| ())
.map_err(|err| DropDatabaseError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!("Failed to drop database '{}': {:?}", &database_name, err);
}
results.insert(database_name, result);
}
@ -161,7 +145,7 @@ pub async fn list_databases_for_user(
unix_user: &UnixUser,
connection: &mut MySqlConnection,
) -> Result<Vec<String>, ListDatabasesError> {
let result = sqlx::query(
sqlx::query(
r#"
SELECT `SCHEMA_NAME` AS `database`
FROM `information_schema`.`SCHEMATA`
@ -177,15 +161,5 @@ pub async fn list_databases_for_user(
.map(|row| row.try_get::<String, _>("database"))
.collect::<Result<Vec<String>, sqlx::Error>>()
})
.map_err(|err| ListDatabasesError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!(
"Failed to list databases for user '{}': {:?}",
unix_user.username,
err
);
}
result
.map_err(|err| ListDatabasesError::MySqlError(err.to_string()))
}

View File

@ -136,7 +136,7 @@ async fn unsafe_get_database_privileges(
database_name: &str,
connection: &mut MySqlConnection,
) -> Result<Vec<DatabasePrivilegeRow>, sqlx::Error> {
let result = sqlx::query_as::<_, DatabasePrivilegeRow>(&format!(
sqlx::query_as::<_, DatabasePrivilegeRow>(&format!(
"SELECT {} FROM `db` WHERE `db` = ?",
DATABASE_PRIVILEGE_FIELDS
.iter()
@ -145,17 +145,7 @@ async fn unsafe_get_database_privileges(
))
.bind(database_name)
.fetch_all(connection)
.await;
if let Err(e) = &result {
log::error!(
"Failed to get database privileges for '{}': {}",
&database_name,
e
);
}
result
.await
}
// NOTE: this function is unsafe because it does no input validation.
@ -165,7 +155,7 @@ pub async fn unsafe_get_database_privileges_for_db_user_pair(
user_name: &str,
connection: &mut MySqlConnection,
) -> Result<Option<DatabasePrivilegeRow>, sqlx::Error> {
let result = sqlx::query_as::<_, DatabasePrivilegeRow>(&format!(
sqlx::query_as::<_, DatabasePrivilegeRow>(&format!(
"SELECT {} FROM `db` WHERE `db` = ? AND `user` = ?",
DATABASE_PRIVILEGE_FIELDS
.iter()
@ -175,18 +165,7 @@ pub async fn unsafe_get_database_privileges_for_db_user_pair(
.bind(database_name)
.bind(user_name)
.fetch_optional(connection)
.await;
if let Err(e) = &result {
log::error!(
"Failed to get database privileges for '{}.{}': {}",
&database_name,
&user_name,
e
);
}
result
.await
}
pub async fn get_databases_privilege_data(
@ -241,7 +220,7 @@ pub async fn get_all_database_privileges(
unix_user: &UnixUser,
connection: &mut MySqlConnection,
) -> GetAllDatabasesPrivilegeData {
let result = sqlx::query_as::<_, DatabasePrivilegeRow>(&format!(
sqlx::query_as::<_, DatabasePrivilegeRow>(&format!(
indoc! {r#"
SELECT {} FROM `db` WHERE `db` IN
(SELECT DISTINCT `SCHEMA_NAME` AS `database`
@ -257,20 +236,14 @@ pub async fn get_all_database_privileges(
.bind(create_user_group_matching_regex(unix_user))
.fetch_all(connection)
.await
.map_err(|e| GetAllDatabasesPrivilegeDataError::MySqlError(e.to_string()));
if let Err(e) = &result {
log::error!("Failed to get all database privileges: {:?}", e);
}
result
.map_err(|e| GetAllDatabasesPrivilegeDataError::MySqlError(e.to_string()))
}
async fn unsafe_apply_privilege_diff(
database_privilege_diff: &DatabasePrivilegesDiff,
connection: &mut MySqlConnection,
) -> Result<(), sqlx::Error> {
let result = match database_privilege_diff {
match database_privilege_diff {
DatabasePrivilegesDiff::New(p) => {
let tables = DATABASE_PRIVILEGE_FIELDS
.iter()
@ -332,13 +305,7 @@ async fn unsafe_apply_privilege_diff(
.await
.map(|_| ())
}
};
if let Err(e) = &result {
log::error!("Failed to apply database privilege diff: {}", e);
}
result
}
async fn validate_diff(

View File

@ -1,6 +1,6 @@
use indoc::formatdoc;
use itertools::Itertools;
use std::collections::BTreeMap;
use indoc::formatdoc;
use serde::{Deserialize, Serialize};
@ -29,7 +29,7 @@ async fn unsafe_user_exists(
db_user: &str,
connection: &mut MySqlConnection,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
sqlx::query(
r#"
SELECT EXISTS(
SELECT 1
@ -41,13 +41,7 @@ async fn unsafe_user_exists(
.bind(db_user)
.fetch_one(connection)
.await
.map(|row| row.get::<bool, _>(0));
if let Err(err) = &result {
log::error!("Failed to check if database user exists: {:?}", err);
}
result
.map(|row| row.get::<bool, _>(0))
}
pub async fn create_database_users(
@ -86,10 +80,6 @@ pub async fn create_database_users(
.map(|_| ())
.map_err(|err| CreateUserError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!("Failed to create database user '{}': {:?}", &db_user, err);
}
results.insert(db_user, result);
}
@ -132,10 +122,6 @@ pub async fn drop_database_users(
.map(|_| ())
.map_err(|err| DropUserError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!("Failed to drop database user '{}': {:?}", &db_user, err);
}
results.insert(db_user, result);
}
@ -162,7 +148,7 @@ pub async fn set_password_for_database_user(
_ => {}
}
let result = sqlx::query(
sqlx::query(
format!(
"ALTER USER {}@'%' IDENTIFIED BY {}",
quote_literal(db_user),
@ -173,17 +159,7 @@ pub async fn set_password_for_database_user(
.execute(&mut *connection)
.await
.map(|_| ())
.map_err(|err| SetPasswordError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!(
"Failed to set password for database user '{}': {:?}",
&db_user,
err
);
}
result
.map_err(|err| SetPasswordError::MySqlError(err.to_string()))
}
// NOTE: this function is unsafe because it does no input validation.
@ -191,7 +167,7 @@ async fn database_user_is_locked_unsafe(
db_user: &str,
connection: &mut MySqlConnection,
) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
sqlx::query(
r#"
SELECT COALESCE(
JSON_EXTRACT(`mysql`.`global_priv`.`priv`, "$.account_locked"),
@ -205,17 +181,7 @@ async fn database_user_is_locked_unsafe(
.bind(db_user)
.fetch_one(connection)
.await
.map(|row| row.get::<bool, _>(0));
if let Err(err) = &result {
log::error!(
"Failed to check if database user is locked '{}': {:?}",
&db_user,
err
);
}
result
.map(|row| row.get::<bool, _>(0))
}
pub async fn lock_database_users(
@ -268,10 +234,6 @@ pub async fn lock_database_users(
.map(|_| ())
.map_err(|err| LockUserError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!("Failed to lock database user '{}': {:?}", &db_user, err);
}
results.insert(db_user, result);
}
@ -328,10 +290,6 @@ pub async fn unlock_database_users(
.map(|_| ())
.map_err(|err| UnlockUserError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!("Failed to unlock database user '{}': {:?}", &db_user, err);
}
results.insert(db_user, result);
}
@ -340,55 +298,39 @@ pub async fn unlock_database_users(
/// This struct contains information about a database user.
/// This can be extended if we need more information in the future.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, FromRow)]
pub struct DatabaseUser {
#[sqlx(rename = "User")]
pub user: String,
#[allow(dead_code)]
#[serde(skip)]
#[sqlx(rename = "Host")]
pub host: String,
#[sqlx(rename = "has_password")]
pub has_password: bool,
#[sqlx(rename = "is_locked")]
pub is_locked: bool,
#[sqlx(skip)]
pub databases: Vec<String>,
}
/// Some mysql versions with some collations mark some columns as binary fields,
/// which in the current version of sqlx is not parsable as string.
/// See: https://github.com/launchbadge/sqlx/issues/3387
#[inline]
fn try_get_with_binary_fallback(
row: &sqlx::mysql::MySqlRow,
column: &str,
) -> Result<String, sqlx::Error> {
row.try_get(column).or_else(|_| {
row.try_get::<Vec<u8>, _>(column)
.map(|v| String::from_utf8_lossy(&v).to_string())
})
}
impl FromRow<'_, sqlx::mysql::MySqlRow> for DatabaseUser {
fn from_row(row: &sqlx::mysql::MySqlRow) -> Result<Self, sqlx::Error> {
Ok(Self {
user: try_get_with_binary_fallback(row, "User")?,
host: try_get_with_binary_fallback(row, "Host")?,
has_password: row.try_get("has_password")?,
is_locked: row.try_get("is_locked")?,
databases: Vec::new(),
})
}
}
const DB_USER_SELECT_STATEMENT: &str = r#"
SELECT
`user`.`User`,
`user`.`Host`,
`user`.`Password` != '' OR `user`.`authentication_string` != '' AS `has_password`,
`mysql`.`user`.`User`,
`mysql`.`user`.`Host`,
`mysql`.`user`.`Password` != '' OR `mysql`.`user`.`authentication_string` != '' AS `has_password`,
COALESCE(
JSON_EXTRACT(`global_priv`.`priv`, "$.account_locked"),
JSON_EXTRACT(`mysql`.`global_priv`.`priv`, "$.account_locked"),
'false'
) != 'false' AS `is_locked`
FROM `user`
JOIN `global_priv` ON
`user`.`User` = `global_priv`.`User`
AND `user`.`Host` = `global_priv`.`Host`
FROM `mysql`.`user`
JOIN `mysql`.`global_priv` ON
`mysql`.`user`.`User` = `mysql`.`global_priv`.`User`
AND `mysql`.`user`.`Host` = `mysql`.`global_priv`.`Host`
"#;
pub async fn list_database_users(
@ -416,10 +358,6 @@ pub async fn list_database_users(
.fetch_optional(&mut *connection)
.await;
if let Err(err) = &result {
log::error!("Failed to list database user '{}': {:?}", &db_user, err);
}
if let Ok(Some(user)) = result.as_mut() {
append_databases_where_user_has_privileges(user, &mut *connection).await;
}
@ -439,17 +377,13 @@ pub async fn list_all_database_users_for_unix_user(
connection: &mut MySqlConnection,
) -> ListAllUsersOutput {
let mut result = sqlx::query_as::<_, DatabaseUser>(
&(DB_USER_SELECT_STATEMENT.to_string() + "WHERE `user`.`User` REGEXP ?"),
&(DB_USER_SELECT_STATEMENT.to_string() + "WHERE `mysql`.`user`.`User` REGEXP ?"),
)
.bind(create_user_group_matching_regex(unix_user))
.fetch_all(&mut *connection)
.await
.map_err(|err| ListAllUsersError::MySqlError(err.to_string()));
if let Err(err) = &result {
log::error!("Failed to list all database users: {:?}", err);
}
if let Ok(users) = result.as_mut() {
for user in users {
append_databases_where_user_has_privileges(user, &mut *connection).await;
@ -460,15 +394,15 @@ pub async fn list_all_database_users_for_unix_user(
}
pub async fn append_databases_where_user_has_privileges(
db_user: &mut DatabaseUser,
database_user: &mut DatabaseUser,
connection: &mut MySqlConnection,
) {
let database_list = sqlx::query(
formatdoc!(
r#"
SELECT `Db` AS `database`
SELECT `db` AS `database`
FROM `db`
WHERE `User` = ? AND ({})
WHERE `user` = ? AND ({})
"#,
DATABASE_PRIVILEGE_FIELDS
.iter()
@ -477,22 +411,14 @@ pub async fn append_databases_where_user_has_privileges(
)
.as_str(),
)
.bind(db_user.user.clone())
.bind(database_user.user.clone())
.fetch_all(&mut *connection)
.await;
if let Err(err) = &database_list {
log::error!(
"Failed to list databases for user '{}': {:?}",
&db_user.user,
err
);
}
db_user.databases = database_list
database_user.databases = database_list
.map(|rows| {
rows.into_iter()
.map(|row| try_get_with_binary_fallback(&row, "database").unwrap())
.map(|row| row.get::<String, _>("database"))
.collect()
})
.unwrap_or_default();