Misc 6 #77

Merged
oysteikt merged 9 commits from misc into main 2024-08-19 18:14:14 +02:00
3 changed files with 92 additions and 31 deletions
Showing only changes of commit ed12a3153b - Show all commits

View File

@ -1,8 +1,22 @@
# This should go to `/etc/mysqladm/config.toml` # This should go to `/etc/mysqladm/config.toml`
[server]
# Note that this gets ignored if you are using socket activation.
socket_path = "/var/run/mysqladm/mysqladm.sock"
[mysql] [mysql]
# if you use a socket, the host and port will be ignored
# socket_path = "/var/run/mysql/mysql.sock"
host = "localhost" host = "localhost"
port = 3306 port = 3306
# The username and password can be omitted if you are using
# socket based authentication. However, the vendored systemd
# service is running as DynamicUser, so by default you need
# to at least specify the username.
username = "root" username = "root"
password = "secret" password = "secret"
timeout = 2 # seconds timeout = 2 # seconds

View File

@ -7,7 +7,7 @@ use tokio::net::UnixStream as TokioUnixStream;
use crate::{ use crate::{
core::common::{UnixUser, DEFAULT_CONFIG_PATH, DEFAULT_SOCKET_PATH}, core::common::{UnixUser, DEFAULT_CONFIG_PATH, DEFAULT_SOCKET_PATH},
server::{config::read_config_form_path, server_loop::handle_requests_for_single_session}, server::{config::read_config_from_path, server_loop::handle_requests_for_single_session},
}; };
// TODO: this function is security critical, it should be integration tested // TODO: this function is security critical, it should be integration tested
@ -140,7 +140,7 @@ fn run_forked_server(
server_socket: StdUnixStream, server_socket: StdUnixStream,
unix_user: UnixUser, unix_user: UnixUser,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
let config = read_config_form_path(Some(config_path))?; let config = read_config_from_path(Some(config_path))?;
let result: anyhow::Result<()> = tokio::runtime::Builder::new_current_thread() let result: anyhow::Result<()> = tokio::runtime::Builder::new_current_thread()
.enable_all() .enable_all()

View File

@ -21,21 +21,37 @@ pub struct ServerConfig {
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename = "mysql")] #[serde(rename = "mysql")]
pub struct MysqlConfig { pub struct MysqlConfig {
pub host: String, pub socket_path: Option<PathBuf>,
pub host: Option<String>,
pub port: Option<u16>, pub port: Option<u16>,
pub username: String, pub username: Option<String>,
pub password: String, pub password: Option<String>,
pub password_file: Option<PathBuf>,
pub timeout: Option<u64>, pub timeout: Option<u64>,
} }
#[derive(Parser, Debug, Clone)] #[derive(Parser, Debug, Clone)]
pub struct ServerConfigArgs { pub struct ServerConfigArgs {
/// Path to the socket of the MySQL server.
#[arg(long, value_name = "PATH", global = true)]
socket_path: Option<PathBuf>,
/// Hostname of the MySQL server. /// Hostname of the MySQL server.
#[arg(long, value_name = "HOST", global = true)] #[arg(
long,
value_name = "HOST",
global = true,
conflicts_with = "socket_path"
)]
mysql_host: Option<String>, mysql_host: Option<String>,
/// Port of the MySQL server. /// Port of the MySQL server.
#[arg(long, value_name = "PORT", global = true)] #[arg(
long,
value_name = "PORT",
global = true,
conflicts_with = "socket_path"
)]
mysql_port: Option<u16>, mysql_port: Option<u16>,
/// Username to use for the MySQL connection. /// Username to use for the MySQL connection.
@ -44,7 +60,7 @@ pub struct ServerConfigArgs {
/// Path to a file containing the MySQL password. /// Path to a file containing the MySQL password.
#[arg(long, value_name = "PATH", global = true)] #[arg(long, value_name = "PATH", global = true)]
mysql_password_file: Option<String>, mysql_password_file: Option<PathBuf>,
/// Seconds to wait for the MySQL connection to be established. /// Seconds to wait for the MySQL connection to be established.
#[arg(long, value_name = "SECONDS", global = true)] #[arg(long, value_name = "SECONDS", global = true)]
@ -57,30 +73,40 @@ pub fn read_config_from_path_with_arg_overrides(
config_path: Option<PathBuf>, config_path: Option<PathBuf>,
args: ServerConfigArgs, args: ServerConfigArgs,
) -> anyhow::Result<ServerConfig> { ) -> anyhow::Result<ServerConfig> {
let config = read_config_form_path(config_path)?; let config = read_config_from_path(config_path)?;
let mysql = &config.mysql; let mysql = config.mysql;
let password = if let Some(path) = args.mysql_password_file { let password = if let Some(path) = &args.mysql_password_file {
fs::read_to_string(path) Some(
.context("Failed to read MySQL password file") fs::read_to_string(path)
.map(|s| s.trim().to_owned())? .context("Failed to read MySQL password file")
.map(|s| s.trim().to_owned())?,
)
} else if let Some(path) = &mysql.password_file {
Some(
fs::read_to_string(path)
.context("Failed to read MySQL password file")
.map(|s| s.trim().to_owned())?,
)
} else { } else {
mysql.password.to_owned() mysql.password.to_owned()
}; };
Ok(ServerConfig { Ok(ServerConfig {
mysql: MysqlConfig { mysql: MysqlConfig {
host: args.mysql_host.unwrap_or(mysql.host.to_owned()), socket_path: args.socket_path.or(mysql.socket_path),
host: args.mysql_host.or(mysql.host),
port: args.mysql_port.or(mysql.port), port: args.mysql_port.or(mysql.port),
username: args.mysql_user.unwrap_or(mysql.username.to_owned()), username: args.mysql_user.or(mysql.username.to_owned()),
password, password,
password_file: args.mysql_password_file.or(mysql.password_file),
timeout: args.mysql_connect_timeout.or(mysql.timeout), timeout: args.mysql_connect_timeout.or(mysql.timeout),
}, },
}) })
} }
pub fn read_config_form_path(config_path: Option<PathBuf>) -> anyhow::Result<ServerConfig> { pub fn read_config_from_path(config_path: Option<PathBuf>) -> anyhow::Result<ServerConfig> {
let config_path = config_path.unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG_PATH)); let config_path = config_path.unwrap_or_else(|| PathBuf::from(DEFAULT_CONFIG_PATH));
log::debug!("Reading config from {:?}", &config_path); log::debug!("Reading config from {:?}", &config_path);
@ -97,30 +123,51 @@ pub fn read_config_form_path(config_path: Option<PathBuf>) -> anyhow::Result<Ser
)) ))
} }
/// Use the provided configuration to establish a connection to a MySQL server. fn log_config(config: &MysqlConfig) {
pub async fn create_mysql_connection_from_config(
config: &MysqlConfig,
) -> anyhow::Result<MySqlConnection> {
let mut display_config = config.clone(); let mut display_config = config.clone();
"<REDACTED>".clone_into(&mut display_config.password); display_config.password = display_config
.password
.as_ref()
.map(|_| "<REDACTED>".to_owned());
log::debug!( log::debug!(
"Connecting to MySQL server with parameters: {:#?}", "Connecting to MySQL server with parameters: {:#?}",
display_config display_config
); );
}
/// Use the provided configuration to establish a connection to a MySQL server.
pub async fn create_mysql_connection_from_config(
config: &MysqlConfig,
) -> anyhow::Result<MySqlConnection> {
log_config(config);
let mut mysql_options = MySqlConnectOptions::new()
.database("mysql");
if let Some(username) = &config.username {
mysql_options = mysql_options.username(username);
}
if let Some(password) = &config.password {
mysql_options = mysql_options.password(password);
}
if let Some(socket_path) = &config.socket_path {
mysql_options = mysql_options.socket(socket_path);
} else if let Some(host) = &config.host {
mysql_options = mysql_options.host(host);
mysql_options = mysql_options.port(config.port.unwrap_or(DEFAULT_PORT));
} else {
anyhow::bail!("No MySQL host or socket path provided");
}
match tokio::time::timeout( match tokio::time::timeout(
Duration::from_secs(config.timeout.unwrap_or(DEFAULT_TIMEOUT)), Duration::from_secs(config.timeout.unwrap_or(DEFAULT_TIMEOUT)),
MySqlConnectOptions::new() mysql_options.connect(),
.host(&config.host)
.username(&config.username)
.password(&config.password)
.port(config.port.unwrap_or(DEFAULT_PORT))
.database("mysql")
.connect(),
) )
.await .await
{ {
Ok(connection) => connection.context("Failed to connect to MySQL"), Ok(connection) => connection.context("Failed to connect to the database"),
Err(_) => Err(anyhow!("Timed out after 2 seconds")).context("Failed to connect to MySQL"), Err(_) => Err(anyhow!("Timed out after 2 seconds")).context("Failed to connect to the database"),
} }
} }