diff --git a/Cargo.lock b/Cargo.lock index 9e84981e..0bd708a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1144,6 +1144,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" name = "openaev-agent" version = "3.261118.0" dependencies = [ + "bytes", "config", "filetime", "hostname", @@ -1162,6 +1163,7 @@ dependencies = [ "webpki-root-certs", "windows-service", "windows-service-detector", + "zeroize", ] [[package]] @@ -2764,6 +2766,9 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "serde", +] [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index cecd12bf..3358ac73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ mid = "=3.0.7" tracing-appender = "0.2.3" rolling-file = "0.2.0" webpki-root-certs = "1.0.10" +bytes = "1.12.1" [dependencies.reqwest] version = "0.13.0" @@ -21,6 +22,12 @@ features = [ ] default-features = false +[dependencies.zeroize] +version = "1.9.0" +features = [ + "serde", +] + [dependencies.serde] version = "1.0.203" features = [ diff --git a/src/api/manage_jobs.rs b/src/api/manage_jobs.rs index e21904bf..721fcae2 100644 --- a/src/api/manage_jobs.rs +++ b/src/api/manage_jobs.rs @@ -36,7 +36,7 @@ impl Client { "agent_executed_by_user": executed_by_user }); let jobs_endpoint = format!("/api/tenants/{}/endpoints/jobs", tenant_id); - match self.post(&jobs_endpoint).json(&post_data).send() { + match self.post(&jobs_endpoint)?.json(&post_data).send() { Ok(response) => { if response.status().is_success() { response @@ -59,7 +59,7 @@ impl Client { pub fn clean_job(&self, job_id: &str, tenant_id: String) -> Result<(), Error> { // Post the input to the OpenAEV API let jobs_endpoint = format!("/api/tenants/{}/endpoints/jobs/{}", tenant_id, job_id); - match self.delete(&jobs_endpoint).send() { + match self.delete(&jobs_endpoint)?.send() { Ok(response) => { if response.status().is_success() { Ok(()) diff --git a/src/api/mod.rs b/src/api/mod.rs index 1bf4aa71..cc19f65b 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,22 +1,28 @@ +use crate::common::error_model::Error; +use crate::secrets::{SecretStore, TOKEN}; +use bytes::Bytes; +use reqwest::header::HeaderValue; +use std::sync::Arc; use std::time::Duration; +use zeroize::Zeroizing; mod manage_jobs; mod register_agent; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const AUTHORIZATION_HEADER: &str = "Authorization"; +const BEARER_PREFIX: &[u8] = b"Bearer "; -#[derive(Debug)] pub struct Client { http_client: reqwest::blocking::Client, server_url: String, - token: String, + secret_store: Arc, } impl Client { pub fn new( server_url: String, - token: String, + secret_store: Arc, unsecured_certificate: bool, with_proxy: bool, ) -> Client { @@ -48,29 +54,55 @@ impl Client { Client { http_client: http_client.build().unwrap(), server_url: url, - token, + secret_store, } } + /// Reads the token from the store for this request only, so it is not kept in memory. + fn authorization(&self) -> Result { + let token = self.secret_store.get(TOKEN)?; + bearer_header(token.as_bytes()) + } + #[cfg(test)] - pub fn get(&self, route: &str) -> reqwest::blocking::RequestBuilder { + pub fn get(&self, route: &str) -> Result { let api_route = format!("{}{}", self.server_url, route); - self.http_client + Ok(self + .http_client .get(&api_route) - .header(AUTHORIZATION_HEADER, &format!("Bearer {}", self.token)) + .header(AUTHORIZATION_HEADER, self.authorization()?)) } - pub fn post(&self, route: &str) -> reqwest::blocking::RequestBuilder { + pub fn post(&self, route: &str) -> Result { let api_route = format!("{}{}", self.server_url, route); - self.http_client + Ok(self + .http_client .post(&api_route) - .header(AUTHORIZATION_HEADER, &format!("Bearer {}", self.token)) + .header(AUTHORIZATION_HEADER, self.authorization()?)) } - pub fn delete(&self, route: &str) -> reqwest::blocking::RequestBuilder { + pub fn delete(&self, route: &str) -> Result { let api_route = format!("{}{}", self.server_url, route); - self.http_client + Ok(self + .http_client .delete(&api_route) - .header(AUTHORIZATION_HEADER, &format!("Bearer {}", self.token)) + .header(AUTHORIZATION_HEADER, self.authorization()?)) } } + +/// Builds the `Bearer ` header value in a `Zeroizing` buffer. +/// +/// `Bytes::from_owner` makes the header own that buffer instead of copying it, so the token is +/// wiped when the last copy of the header is dropped. Limit: the HTTP and TLS layers copy the +/// bytes they send, and those copies are not wiped. +pub(crate) fn bearer_header(token: &[u8]) -> Result { + // Exact capacity: if the Vec had to grow, it would leave an unwiped copy of the token behind. + let mut bearer = Zeroizing::new(Vec::with_capacity(BEARER_PREFIX.len() + token.len())); + bearer.extend_from_slice(BEARER_PREFIX); + bearer.extend_from_slice(token); + let mut value = HeaderValue::from_maybe_shared(Bytes::from_owner(bearer)) + .map_err(|err| Error::Internal(err.to_string()))?; + // Hides the value in reqwest's `Debug` output. + value.set_sensitive(true); + Ok(value) +} diff --git a/src/api/register_agent.rs b/src/api/register_agent.rs index eca7e6fb..b5da5f55 100644 --- a/src/api/register_agent.rs +++ b/src/api/register_agent.rs @@ -117,7 +117,7 @@ impl Client { // endregion // Post the input to the OpenAEV API let register_endpoint = format!("/api/tenants/{}/endpoints/register", tenant_id); - match self.post(®ister_endpoint).json(&post_data).send() { + match self.post(®ister_endpoint)?.json(&post_data).send() { Ok(response) => { if response.status().is_success() { response diff --git a/src/config/settings.rs b/src/config/settings.rs index 11a85ff1..8c1dbb6f 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -1,15 +1,20 @@ use config::{Config, ConfigError, Environment, File}; use serde::Deserialize; use std::env; +use std::fmt; +use std::path::PathBuf; +use zeroize::Zeroizing; const ENV_PRODUCTION: &str = "production"; const ENV_PRODUCTION_CONFIG_FILE: &str = "openaev-agent-config"; -#[derive(Debug, Deserialize, Clone)] +#[derive(Deserialize, Clone)] #[allow(unused)] pub struct OpenAEV { pub url: String, - pub token: String, + // Wiped from memory when dropped. Limit: the copies the `config` crate makes while parsing + // the file are not wiped. + pub token: Zeroizing, pub unsecured_certificate: bool, pub with_proxy: bool, pub installation_mode: String, @@ -17,6 +22,21 @@ pub struct OpenAEV { pub tenant_id: String, } +// Written by hand so that the token is never printed. +impl fmt::Debug for OpenAEV { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OpenAEV") + .field("url", &self.url) + .field("token", &"") + .field("unsecured_certificate", &self.unsecured_certificate) + .field("with_proxy", &self.with_proxy) + .field("installation_mode", &self.installation_mode) + .field("service_name", &self.service_name) + .field("tenant_id", &self.tenant_id) + .finish() + } +} + fn default_executing_max_time_minutes() -> u64 { 10 } @@ -61,25 +81,44 @@ impl Settings { } pub fn new() -> Result { - let run_mode = Self::mode(); + Self::source().load() + } + + /// Where to read the settings: the config file next to the executable in production, the + /// `config/` folder otherwise. + pub fn source() -> SettingsSource { + if Self::mode() != ENV_PRODUCTION { + return SettingsSource::Development; + } + let current_exe_path = env::current_exe().unwrap(); + let parent_path = current_exe_path.parent().unwrap(); + SettingsSource::File(parent_path.join(ENV_PRODUCTION_CONFIG_FILE)) + } +} + +/// Where the settings are read from. It stores the location only, not the values, so keeping +/// it does not keep the token in memory. +#[derive(Clone, Debug)] +pub enum SettingsSource { + /// `config/default.toml`, then `config/.toml` if it exists. + Development, + /// The config file the installers write, given without its extension. + File(PathBuf), +} + +impl SettingsSource { + /// Reads the settings from this source. `OPENAEV_*` environment variables override the file. + pub fn load(&self) -> Result { let config = Config::builder().add_source(Environment::with_prefix("openaev")); - if run_mode == ENV_PRODUCTION { - // Get the current executable path - let current_exe_patch = env::current_exe().unwrap(); - let parent_path = current_exe_patch.parent().unwrap(); - // Join the expected config file with the parent - let config_file = parent_path.join(ENV_PRODUCTION_CONFIG_FILE); - let config_path = config_file.display(); - config - .add_source(File::with_name(&config_path.to_string()).required(true)) - .build()? - .try_deserialize() - } else { - config + let config = match self { + SettingsSource::Development => config .add_source(File::with_name("config/default")) - .add_source(File::with_name(&format!("config/{run_mode}")).required(false)) - .build()? - .try_deserialize() - } + .add_source( + File::with_name(&format!("config/{}", Settings::mode())).required(false), + ), + SettingsSource::File(config_file) => config + .add_source(File::with_name(&config_file.display().to_string()).required(true)), + }; + config.build()?.try_deserialize() } } diff --git a/src/main.rs b/src/main.rs index 3db4d690..25757b56 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ mod api; mod common; mod config; mod process; +mod secrets; mod windows; #[cfg(test)] @@ -61,7 +62,7 @@ fn compute_working_dir() -> PathBuf { fn agent_start(settings_data: Settings, is_service: bool) -> Result>, Error> { let url = settings_data.openaev.url; - let token = settings_data.openaev.token; + let secret_store = secrets::open(); let unsecured_certificate = settings_data.openaev.unsecured_certificate; let with_proxy = settings_data.openaev.with_proxy; let installation_mode = settings_data.openaev.installation_mode; @@ -81,7 +82,7 @@ fn agent_start(settings_data: Settings, is_service: bool) -> Result Result, unsecured_certificate: bool, with_proxy: bool, execution_details: ExecutionDetails, tenant_id: String, ) -> Result, Error> { info!("Starting listening jobs thread"); - let api = Client::new(uri, token, unsecured_certificate, with_proxy); + let api = Client::new(uri, secret_store, unsecured_certificate, with_proxy); let handle = thread::spawn(move || { // While no stop signal received while THREADS_CONTROL.load(Ordering::Relaxed) { diff --git a/src/process/keep_alive.rs b/src/process/keep_alive.rs index 74d7e105..e72fc793 100644 --- a/src/process/keep_alive.rs +++ b/src/process/keep_alive.rs @@ -1,9 +1,11 @@ use crate::api::Client; use crate::config::execution_details::ExecutionDetails; +use crate::secrets::SecretStore; use crate::THREADS_CONTROL; use log::{error, info}; use std::io::Error; use std::sync::atomic::Ordering; +use std::sync::Arc; use std::thread; use std::thread::{sleep, JoinHandle}; use std::time::Duration; @@ -11,7 +13,7 @@ use std::time::Duration; #[allow(clippy::too_many_arguments)] pub fn ping( uri: String, - token: String, + secret_store: Arc, unsecured_certificate: bool, with_proxy: bool, installation_mode: String, @@ -20,7 +22,7 @@ pub fn ping( tenant_id: String, ) -> Result, Error> { info!("Starting ping thread"); - let api = Client::new(uri, token, unsecured_certificate, with_proxy); + let api = Client::new(uri, secret_store, unsecured_certificate, with_proxy); let handle = thread::spawn(move || { // While no stop signal received while THREADS_CONTROL.load(Ordering::Relaxed) { diff --git a/src/secrets/config_store.rs b/src/secrets/config_store.rs new file mode 100644 index 00000000..1ba19ad7 --- /dev/null +++ b/src/secrets/config_store.rs @@ -0,0 +1,58 @@ +use super::{SecretStore, TOKEN}; +use crate::common::error_model::Error; +use crate::config::settings::SettingsSource; +use config::ConfigError; +use log::error; +use std::io; +use zeroize::Zeroizing; + +/// Reads the token from the agent config file on each call. Nothing is cached. +pub struct ConfigStore { + source: SettingsSource, +} + +impl ConfigStore { + pub fn new(source: SettingsSource) -> Self { + ConfigStore { source } + } +} + +impl SecretStore for ConfigStore { + fn get(&self, name: &str) -> Result, Error> { + if name != TOKEN { + return Err(Error::Internal(format!("no secret named {name}"))); + } + let settings = self.source.load().map_err(|err| { + let message = format!( + "Unable to read token from agent configuration: {}", + reason(&err) + ); + error!("{message}"); + Error::Internal(message) + })?; + Ok(settings.openaev.token) + } +} + +/// Says why the config could not be read, using only the error kind and the setting name. +/// The error's own text is not used: it can contain the token (a parse error quotes the failing +/// line, a type error quotes the value). +pub(crate) fn reason(err: &ConfigError) -> String { + match err { + ConfigError::Foreign(cause) => match cause.downcast_ref::().map(io::Error::kind) + { + Some(io::ErrorKind::NotFound) => "the config file is missing".to_string(), + Some(io::ErrorKind::PermissionDenied) => { + "access to the config file is denied".to_string() + } + _ => "the config file cannot be read".to_string(), + }, + ConfigError::FileParse { .. } => "the config file is not valid".to_string(), + ConfigError::NotFound(key) => format!("the setting `{key}` is missing"), + ConfigError::Type { key: Some(key), .. } => { + format!("the setting `{key}` has the wrong type") + } + ConfigError::At { error, .. } => reason(error), + _ => "a setting is invalid".to_string(), + } +} diff --git a/src/secrets/mod.rs b/src/secrets/mod.rs new file mode 100644 index 00000000..744f3dae --- /dev/null +++ b/src/secrets/mod.rs @@ -0,0 +1,26 @@ +//! Secrets the agent authenticates with (today, only the platform token). +//! +//! The token is read through a [`SecretStore`] on each use instead of being kept in memory. +//! `ConfigStore` is the only store for now; OS secret stores will implement the same trait. + +pub(crate) mod config_store; + +pub use config_store::ConfigStore; + +use crate::common::error_model::Error; +use crate::config::settings::Settings; +use std::sync::Arc; +use zeroize::Zeroizing; + +/// Name of the platform token secret. +pub const TOKEN: &str = "token"; + +pub trait SecretStore: Send + Sync { + /// Reads the secret. The returned value is wiped from memory when dropped. + fn get(&self, name: &str) -> Result, Error>; +} + +/// Opens the store the agent reads its token from. +pub fn open() -> Arc { + Arc::new(ConfigStore::new(Settings::source())) +} diff --git a/src/tests/api/client.rs b/src/tests/api/client.rs index b8e97eb2..feb605d3 100644 --- a/src/tests/api/client.rs +++ b/src/tests/api/client.rs @@ -1,14 +1,19 @@ -const TOKEN: &str = "token"; +const TOKEN: &str = "test-token-value"; #[cfg(test)] mod tests { - use crate::api::{Client, AUTHORIZATION_HEADER}; + use crate::api::{bearer_header, Client, AUTHORIZATION_HEADER}; use crate::tests::api::client::TOKEN; use crate::tests::api::tls_server::serve_self_signed_https; + use crate::tests::secrets::MemoryStore; + use bytes::Bytes; use mockito; + use reqwest::header::HeaderValue; use std::env; use std::error::Error; use std::io; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; fn is_invalid_certificate(err: &reqwest::Error) -> bool { let mut current: Option<&(dyn Error + 'static)> = Some(err); @@ -39,13 +44,46 @@ mod tests { .match_header(AUTHORIZATION_HEADER, format!("Bearer {}", TOKEN).as_str()) .with_status(200) .create(); - let client = Client::new(server_url, TOKEN.to_string(), false, false); + let client = Client::new(server_url, MemoryStore::with_token(TOKEN), false, false); // -- EXECUTE & ASSERT -- - let res = client.post("/api/test").send(); + let res = client.post("/api/test").unwrap().send(); assert!(res.is_ok(), "User-Agent should match expected format"); } + #[test] + fn test_client_fails_the_request_without_a_token() { + // -- PREPARE -- + let client = Client::new( + "http://localhost".to_string(), + Arc::new(MemoryStore::default()), + false, + false, + ); + + // -- EXECUTE & ASSERT -- + assert!(client.post("/api/test").is_err()); + } + + #[test] + fn test_client_keeps_the_token_out_of_debug_output() { + // -- PREPARE -- + let client = Client::new( + "http://localhost".to_string(), + MemoryStore::with_token(TOKEN), + false, + false, + ); + + // -- EXECUTE -- + let request = client.post("/api/test").unwrap().build().unwrap(); + + // -- ASSERT -- + let header = request.headers().get(AUTHORIZATION_HEADER).unwrap(); + assert!(header.is_sensitive()); + assert!(!format!("{request:?}").contains(TOKEN)); + } + #[test] fn test_with_proxy_disables_http_proxy() { // -- PREPARE -- @@ -54,12 +92,22 @@ mod tests { let mut server = mockito::Server::new(); let server_url = server.url(); server.mock("POST", "/api/test").with_status(200).create(); - let client_without_proxy = Client::new(server_url.clone(), TOKEN.to_string(), false, false); - let client_with_proxy = Client::new(server_url.clone(), TOKEN.to_string(), false, true); + let client_without_proxy = Client::new( + server_url.clone(), + MemoryStore::with_token(TOKEN), + false, + false, + ); + let client_with_proxy = Client::new( + server_url.clone(), + MemoryStore::with_token(TOKEN), + false, + true, + ); // -- EXECUTE -- - let res_without_proxy = client_without_proxy.post("/api/test").send(); - let res_with_proxy = client_with_proxy.post("/api/test").send(); + let res_without_proxy = client_without_proxy.post("/api/test").unwrap().send(); + let res_with_proxy = client_with_proxy.post("/api/test").unwrap().send(); // -- ASSERT -- assert!(res_without_proxy.is_ok(), "Client should bypass the proxy"); @@ -77,12 +125,15 @@ mod tests { // -- PREPARE -- let url = serve_self_signed_https(); let client_without_unsecured_certificate = - Client::new(url.clone(), TOKEN.to_string(), false, false); - let client_with_unsecured_certificate = Client::new(url, TOKEN.to_string(), true, false); + Client::new(url.clone(), MemoryStore::with_token(TOKEN), false, false); + let client_with_unsecured_certificate = + Client::new(url, MemoryStore::with_token(TOKEN), true, false); // -- EXECUTE -- - let res_without_unsecured_certificate = client_without_unsecured_certificate.get("").send(); - let res_with_unsecured_certificate = client_with_unsecured_certificate.get("").send(); + let res_without_unsecured_certificate = + client_without_unsecured_certificate.get("").unwrap().send(); + let res_with_unsecured_certificate = + client_with_unsecured_certificate.get("").unwrap().send(); // -- ASSERT -- assert!( @@ -106,10 +157,10 @@ mod tests { // the CI job empties the OS trust store, so only the bundled roots can validate this URL let url = env::var("OAEV_BUNDLED_ROOTS_URL") .expect("OAEV_BUNDLED_ROOTS_URL must be set by the os-trust-store CI job"); - let client = Client::new(url, TOKEN.to_string(), false, false); + let client = Client::new(url, MemoryStore::with_token(TOKEN), false, false); // -- EXECUTE -- - let res = client.get("").send(); + let res = client.get("").unwrap().send(); // -- ASSERT -- assert!( @@ -125,12 +176,115 @@ mod tests { // -- PREPARE -- let url = env::var("OAEV_OS_TRUST_URL") .expect("OAEV_OS_TRUST_URL must be set by the os-trust-store CI job"); - let client = Client::new(url, TOKEN.to_string(), false, false); + let client = Client::new(url, MemoryStore::with_token(TOKEN), false, false); // -- EXECUTE & ASSERT -- assert!( - client.get("").send().is_ok(), + client.get("").unwrap().send().is_ok(), "Client should trust a CA present only in the OS trust store" ); } + + #[test] + fn test_bearer_header_holds_the_token_and_is_sensitive() { + // -- EXECUTE -- + let value = bearer_header(TOKEN.as_bytes()).unwrap(); + + // -- ASSERT -- + assert_eq!(value.as_bytes(), format!("Bearer {TOKEN}").as_bytes()); + assert!(value.is_sensitive()); + } + + /// Fake `Zeroizing` buffer: records when it is dropped (when the real one would be wiped). + struct DropFlag(Vec, Arc); + + impl AsRef<[u8]> for DropFlag { + fn as_ref(&self) -> &[u8] { + &self.0 + } + } + + impl Drop for DropFlag { + fn drop(&mut self) { + self.1.store(true, Ordering::SeqCst); + } + } + + #[test] + fn test_header_value_keeps_the_owned_buffer_until_its_last_copy_is_dropped() { + // -- PREPARE -- + let dropped = Arc::new(AtomicBool::new(false)); + let bytes = Bytes::from_owner(DropFlag(b"Bearer token".to_vec(), dropped.clone())); + let buffer = bytes.as_ptr(); + + // -- EXECUTE -- + let value = HeaderValue::from_maybe_shared(bytes).unwrap(); + let copy = value.clone(); + + // -- ASSERT -- + // A copy of the bytes would never be wiped: the header must point at the buffer. + assert_eq!(value.as_bytes().as_ptr(), buffer); + assert_eq!(copy.as_bytes().as_ptr(), buffer); + drop(value); + assert!(!dropped.load(Ordering::SeqCst), "a copy still uses it"); + drop(copy); + assert!(dropped.load(Ordering::SeqCst), "wiped with its last copy"); + } + + #[test] + fn test_client_sends_the_new_token_after_a_rotation() { + // -- PREPARE -- + let mut server = mockito::Server::new(); + let old_token = server + .mock("POST", "/api/test") + .match_header(AUTHORIZATION_HEADER, "Bearer old-token") + .with_status(200) + .expect(1) + .create(); + let new_token = server + .mock("POST", "/api/test") + .match_header(AUTHORIZATION_HEADER, "Bearer new-token") + .with_status(200) + .expect(1) + .create(); + let store = MemoryStore::with_token("old-token"); + let client = Client::new(server.url(), store.clone(), false, false); + + // -- EXECUTE -- + let before = client.post("/api/test").unwrap().send().unwrap(); + store.set_token("new-token"); + let after = client.post("/api/test").unwrap().send().unwrap(); + + // -- ASSERT -- + // The same client picks up the new token: it is read from the store on each call. + assert!(before.status().is_success()); + assert!(after.status().is_success()); + old_token.assert(); + new_token.assert(); + } + + #[test] + fn test_client_recovers_once_the_store_can_be_read_again() { + // -- PREPARE -- + let mut server = mockito::Server::new(); + let request = server + .mock("POST", "/api/test") + .match_header(AUTHORIZATION_HEADER, format!("Bearer {TOKEN}").as_str()) + .with_status(200) + .expect(1) + .create(); + let store = Arc::new(MemoryStore::default()); + let client = Client::new(server.url(), store.clone(), false, false); + + // -- EXECUTE -- + let failed = client.post("/api/test"); + store.set_token(TOKEN); + let recovered = client.post("/api/test").unwrap().send().unwrap(); + + // -- ASSERT -- + assert!(failed.is_err(), "no request without a token"); + assert!(recovered.status().is_success()); + // Exactly one request reached the platform: none was sent while the store failed. + request.assert(); + } } diff --git a/src/tests/config/mod.rs b/src/tests/config/mod.rs index 38c01cf6..3b13f58c 100644 --- a/src/tests/config/mod.rs +++ b/src/tests/config/mod.rs @@ -1 +1,2 @@ mod execution_details_tests; +mod settings_tests; diff --git a/src/tests/config/settings_tests.rs b/src/tests/config/settings_tests.rs new file mode 100644 index 00000000..d0c4b2aa --- /dev/null +++ b/src/tests/config/settings_tests.rs @@ -0,0 +1,57 @@ +#[cfg(test)] +mod tests { + use crate::config::settings::OpenAEV; + use zeroize::Zeroizing; + + #[test] + fn test_debug_output_redacts_the_token() { + // -- PREPARE -- + let settings = OpenAEV { + url: "http://localhost:3001".to_string(), + token: Zeroizing::new("secret-token".to_string()), + unsecured_certificate: false, + with_proxy: false, + installation_mode: "service".to_string(), + service_name: "OAEVAgentService".to_string(), + tenant_id: "tenant".to_string(), + }; + + // -- EXECUTE -- + let output = format!("{settings:?}"); + + // -- ASSERT -- + assert!(!output.contains("secret-token")); + assert!(output.contains("")); + } + + #[test] + fn test_token_is_deserialized_straight_into_a_zeroizing_buffer() { + // -- PREPARE -- + let json = r#"{"url": "http://localhost:3001", "token": "secret-token", + "unsecured_certificate": false, "with_proxy": false, + "installation_mode": "service", "service_name": "OAEVAgentService", + "tenant_id": "tenant"}"#; + + // -- EXECUTE -- + let settings: OpenAEV = serde_json::from_str(json).unwrap(); + + // -- ASSERT -- + let token: Zeroizing = settings.token; + assert_eq!(token.as_str(), "secret-token"); + } + + #[test] + fn test_token_is_required() { + // -- PREPARE -- + let json = r#"{"url": "http://localhost:3001", + "unsecured_certificate": false, "with_proxy": false, + "installation_mode": "service", "service_name": "OAEVAgentService", + "tenant_id": "tenant"}"#; + + // -- EXECUTE -- + let result = serde_json::from_str::(json); + + // -- ASSERT -- + assert!(result.is_err()); + } +} diff --git a/src/tests/mod.rs b/src/tests/mod.rs index caa31c5a..8bb934d0 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -1,3 +1,4 @@ pub mod api; pub mod config; pub mod process; +pub mod secrets; diff --git a/src/tests/secrets/config_store_tests.rs b/src/tests/secrets/config_store_tests.rs new file mode 100644 index 00000000..ac3e600b --- /dev/null +++ b/src/tests/secrets/config_store_tests.rs @@ -0,0 +1,155 @@ +#[cfg(test)] +mod tests { + use crate::config::settings::SettingsSource; + use crate::secrets::config_store::reason; + use crate::secrets::{ConfigStore, SecretStore, TOKEN}; + use crate::tests::secrets::test_dir; + use config::ConfigError; + use std::fs; + use std::io; + use std::path::{Path, PathBuf}; + + /// A config like the one the installers write, holding `token`. + fn config(token: &str) -> String { + format!( + "debug = false\n\n[openaev]\nurl = \"http://localhost:3001\"\ntoken = \"{token}\"\n\ + unsecured_certificate = false\nwith_proxy = false\ninstallation_mode = \"service\"\n\ + service_name = \"OAEVAgentService\"\ntenant_id = \"tenant\"\n" + ) + } + + /// A store reading `agent-config.toml` in `dir`, given without its extension as in + /// production. + fn store_in(dir: &Path) -> (ConfigStore, PathBuf) { + let store = ConfigStore::new(SettingsSource::File(dir.join("agent-config"))); + (store, dir.join("agent-config.toml")) + } + + #[test] + fn test_config_store_only_holds_the_token() { + // -- PREPARE -- + let dir = test_dir("config-store-name"); + let (store, file) = store_in(&dir); + fs::write(&file, config("first-token")).unwrap(); + + // -- EXECUTE & ASSERT -- + assert!(store.get("refresh_token").is_err()); + } + + #[test] + fn test_config_store_reads_the_new_token_after_an_edit() { + // -- PREPARE -- + let dir = test_dir("config-store-edit"); + let (store, file) = store_in(&dir); + fs::write(&file, config("first-token")).unwrap(); + + // -- EXECUTE -- + let before = store.get(TOKEN).unwrap(); + fs::write(&file, config("second-token")).unwrap(); + let after = store.get(TOKEN).unwrap(); + + // -- ASSERT -- + // Same store, no restart: the config is read again on each use. + assert_eq!(before.as_str(), "first-token"); + assert_eq!(after.as_str(), "second-token"); + } + + #[test] + fn test_config_store_fails_without_a_config_and_recovers_once_it_exists() { + // -- PREPARE -- + let dir = test_dir("config-store-missing"); + let (store, file) = store_in(&dir); + + // -- EXECUTE -- + let missing = store.get(TOKEN); + fs::write(&file, config("first-token")).unwrap(); + let recovered = store.get(TOKEN); + + // -- ASSERT -- + let Err(missing) = missing else { + panic!("a missing config must not give a token"); + }; + assert!(missing.to_string().contains("the config file is missing")); + assert_eq!(recovered.unwrap().as_str(), "first-token"); + } + + #[test] + fn test_config_store_fails_on_an_invalid_config_and_recovers_after_repair() { + // -- PREPARE -- + let dir = test_dir("config-store-invalid"); + let (store, file) = store_in(&dir); + // The closing quote is missing on the token line itself. + let broken = config("leaked-token").replace("leaked-token\"", "leaked-token"); + let without_token = config("first-token").replace("token = \"first-token\"\n", ""); + + // -- EXECUTE -- + fs::write(&file, broken).unwrap(); + let invalid = store.get(TOKEN); + fs::write(&file, without_token).unwrap(); + let no_token = store.get(TOKEN); + fs::write(&file, config("first-token")).unwrap(); + let repaired = store.get(TOKEN); + + // -- ASSERT -- + let Err(invalid) = invalid else { + panic!("an invalid config must not give a token"); + }; + // The raw parse error quotes the failing line, here the token: it must not reach the + // error message. + let invalid = invalid.to_string(); + assert!(!invalid.contains("leaked-token"), "{invalid}"); + // It still says why, so that the log is useful. + assert!( + invalid.contains("the config file is not valid"), + "{invalid}" + ); + let Err(no_token) = no_token else { + panic!("a config without a token must not give one"); + }; + let no_token = no_token.to_string(); + assert!( + no_token.contains("the setting `openaev.token` is missing"), + "{no_token}" + ); + assert_eq!(repaired.unwrap().as_str(), "first-token"); + } + + #[test] + fn test_config_store_names_a_setting_of_the_wrong_type_without_its_value() { + // -- PREPARE -- + let dir = test_dir("config-store-type"); + let (store, file) = store_in(&dir); + let wrong_type = config("first-token").replace( + "unsecured_certificate = false", + "unsecured_certificate = \"leaked-value\"", + ); + fs::write(&file, wrong_type).unwrap(); + + // -- EXECUTE -- + let Err(err) = store.get(TOKEN) else { + panic!("a setting of the wrong type must not give a token"); + }; + + // -- ASSERT -- + // The raw type error quotes the value it found, and that value could be a secret. + let message = err.to_string(); + assert!(!message.contains("leaked-value"), "{message}"); + assert!( + message.contains("the setting `openaev.unsecured_certificate` has the wrong type"), + "{message}" + ); + } + + #[test] + fn test_reason_tells_a_denied_access_from_a_missing_file() { + // -- PREPARE -- + // A denied read is hard to set up the same way on every OS, so the errors are built here. + let denied = + ConfigError::Foreign(Box::new(io::Error::from(io::ErrorKind::PermissionDenied))); + let missing = ConfigError::Foreign(Box::new(io::Error::from(io::ErrorKind::NotFound))); + + // -- EXECUTE & ASSERT -- + assert_eq!(reason(&denied), "access to the config file is denied"); + assert_eq!(reason(&missing), "the config file is missing"); + } +} diff --git a/src/tests/secrets/mod.rs b/src/tests/secrets/mod.rs new file mode 100644 index 00000000..61b5dcc4 --- /dev/null +++ b/src/tests/secrets/mod.rs @@ -0,0 +1,77 @@ +mod config_store_tests; + +use crate::common::error_model::Error; +use crate::secrets::SecretStore; +use std::collections::HashMap; +use std::env; +use std::fs; +use std::ops::Deref; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use zeroize::Zeroizing; + +/// A secret store kept in memory, standing in for a real one. When empty, it fails like a +/// store that cannot be read. +#[derive(Default)] +pub struct MemoryStore { + secrets: Mutex>, +} + +impl MemoryStore { + pub fn with_token(token: &str) -> Arc { + let store = MemoryStore::default(); + store.set_token(token); + Arc::new(store) + } + + /// Replaces the token, to simulate a rotation or a store that recovers. + pub fn set_token(&self, token: &str) { + self.secrets + .lock() + .unwrap() + .insert(crate::secrets::TOKEN.to_string(), token.to_string()); + } +} + +impl SecretStore for MemoryStore { + fn get(&self, name: &str) -> Result, Error> { + self.secrets + .lock() + .unwrap() + .get(name) + .map(|value| Zeroizing::new(value.clone())) + .ok_or_else(|| Error::Internal(format!("no secret named {name}"))) + } +} + +/// A directory for one test, deleted with everything in it when dropped. +pub struct TestDir(PathBuf); + +impl Deref for TestDir { + type Target = Path; + + fn deref(&self) -> &Path { + &self.0 + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// A fresh, empty directory for one test, so that tests running in parallel never share a +/// file. Keep it in a variable for the whole test: it is deleted when dropped. +pub fn test_dir(name: &str) -> TestDir { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let dir = env::temp_dir().join(format!( + "openaev-agent-{name}-{}-{}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + TestDir(dir) +}