Skip to content

Commit

Permalink
Log list of loaded files
Browse files Browse the repository at this point in the history
  • Loading branch information
sosthene-nitrokey committed Jan 24, 2024
1 parent 556f96e commit e81c093
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 33 deletions.
33 changes: 18 additions & 15 deletions pkcs11/src/config/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ pub enum ConfigError {
const CONFIG_FILE_NAME: &str = "p11nethsm.conf";
const ENV_VAR_CONFIG_FILE: &str = "P11NETHSM_CONFIG_FILE";

pub fn config_files() -> Result<Vec<Vec<u8>>, ConfigError> {
pub fn config_files() -> Result<Vec<(Vec<u8>, PathBuf)>, ConfigError> {
if let Ok(file_path) = std::env::var(ENV_VAR_CONFIG_FILE) {
let file = std::fs::read(file_path).map_err(ConfigError::Io)?;
return Ok(vec![file]);
let file = std::fs::read(&file_path).map_err(ConfigError::Io)?;
return Ok(vec![(file, file_path.into())]);
}

let mut config_folders = vec![
Expand All @@ -28,40 +28,43 @@ pub fn config_files() -> Result<Vec<Vec<u8>>, ConfigError> {
config_folders.push(format!("{}/.config/nitrokey", home));
}

let mut res: Vec<Vec<u8>> = Vec::new();
let mut buffer: Vec<u8> = Vec::new();
let mut res = Vec::new();
let mut buffer = Vec::new();
for folder in config_folders {
let file_path = format!("{}/{}", folder, CONFIG_FILE_NAME);
if let Ok(mut file) = std::fs::File::open(file_path) {
if let Ok(mut file) = std::fs::File::open(&file_path) {
file.read_to_end(&mut buffer).map_err(ConfigError::Io)?;
res.push(mem::take(&mut buffer));
res.push((mem::take(&mut buffer), file_path.into()));
}
}

Ok(res)
}

pub fn merge_configurations(configs: Vec<Vec<u8>>) -> Result<P11Config, ConfigError> {
pub fn merge_configurations<'a>(
configs: impl IntoIterator<Item = &'a [u8]>,
) -> Result<P11Config, ConfigError> {
let mut config = P11Config::default();

// if no config file was found, return an error
if configs.is_empty() {
return Err(ConfigError::NoConfigFile);
}

let mut no_config = true;
for file in configs {
let parsed = serde_yaml::from_slice(&file).map_err(ConfigError::Yaml)?;
let parsed = serde_yaml::from_slice(file).map_err(ConfigError::Yaml)?;
no_config = false;
config.merge(parsed);
}

if no_config {
return Err(ConfigError::NoConfigFile);
}

Ok(config)
}

#[cfg(test)]
pub fn read_configuration() -> Result<P11Config, ConfigError> {
let configs = config_files()?;

merge_configurations(configs)
merge_configurations(configs.iter().map(|(data, _)| &**data))
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
Expand Down
37 changes: 21 additions & 16 deletions pkcs11/src/config/initialization.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{
path::PathBuf,
sync::{Arc, Mutex},
thread::available_parallelism,
time::Duration,
Expand All @@ -23,18 +24,22 @@ pub enum InitializationError {
}

pub fn initialize_with_configs(
configs: Result<Vec<Vec<u8>>, ConfigError>,
configs: Result<Vec<(Vec<u8>, PathBuf)>, ConfigError>,
) -> Result<Device, InitializationError> {
// Use a closure called immediately so that `?` can be used
let config_res = (|| {
crate::config::config_file::merge_configurations(
configs.map_err(InitializationError::Config)?,
let configs_files = configs.map_err(InitializationError::Config)?;

let config = crate::config::config_file::merge_configurations(
configs_files.iter().map(|(data, _)| &**data),
)
.map_err(InitializationError::Config)
.map_err(InitializationError::Config)?;
let file_paths: Vec<PathBuf> = configs_files.into_iter().map(|(_, path)| path).collect();
Ok((config, file_paths))
})();

crate::config::logging::configure_logger(&config_res);
let config = config_res?;
let (config, _) = config_res?;

info!("Loaded configuration with {} slots", config.slots.len());
// initialize the clients
Expand Down Expand Up @@ -204,8 +209,7 @@ mod tests {
/// Test various good and bad configs for panics
#[test]
fn test_config_loading() {
let configs: Vec<Vec<u8>> = vec![
r#"
let config_content = r#"
slots:
- label: LocalHSM
description: Local HSM (docker)
Expand All @@ -224,13 +228,13 @@ slots:
count: 10
delay_seconds: 1
timeout_seconds: 10
"#.into(),
];
"#;
let config_path = "/path/to/config.conf";
let configs = vec![(config_content.into(), config_path.into())];

assert!(initialize_with_configs(Ok(configs)).is_ok());

let configs_bad_fingerprint: Vec<Vec<u8>> = vec![
r#"
let config_bad_fingerprint_content = r#"
slots:
- label: LocalHSM
description: Local HSM (docker)
Expand All @@ -249,14 +253,15 @@ slots:
count: 10
delay_seconds: 1
timeout_seconds: 10
"#.into(),
];
"#;
let configs_bad_fingerprint =
vec![(config_bad_fingerprint_content.into(), config_path.into())];
assert!(initialize_with_configs(Ok(configs_bad_fingerprint)).is_err());
let configs_bad_yml: Vec<Vec<u8>> = vec![r#"
let config_bad_yml_content = r#"
dict:
bad_yml
"#
.into()];
"#;
let configs_bad_yml = vec![(config_bad_yml_content.into(), config_path.into())];
assert!(initialize_with_configs(Ok(configs_bad_yml)).is_err());
}
}
11 changes: 9 additions & 2 deletions pkcs11/src/config/logging.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::path::PathBuf;

use log::{info, warn, LevelFilter};
use syslog::{BasicLogger, Formatter3164};

Expand Down Expand Up @@ -39,8 +41,8 @@ impl log::Log for MultiLog {
}

// output to stdout, a file or syslog
pub fn configure_logger(config: &Result<P11Config, InitializationError>) {
let Ok(config) = config else {
pub fn configure_logger(config: &Result<(P11Config, Vec<PathBuf>), InitializationError>) {
let Ok((config, file_paths)) = config else {
let formatter = Formatter3164 {
facility: syslog::Facility::LOG_USER,
hostname: None,
Expand All @@ -66,6 +68,11 @@ pub fn configure_logger(config: &Result<P11Config, InitializationError>) {
let mut messages = Vec::new();
// Info messages to log after logger is configured
let mut info_messages = Vec::new();

for path in file_paths {
info_messages.push(format!("Loaded config file at: {}", path.to_string_lossy()));
}

if config.syslog_socket.is_some() as u32
+ config.syslog_tcp.is_some() as u32
+ config.syslog_udp.is_some() as u32
Expand Down

0 comments on commit e81c093

Please sign in to comment.