Skip to content
Open
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -21,6 +22,12 @@ features = [
]
default-features = false

[dependencies.zeroize]
version = "1.9.0"
features = [
"serde",
]

[dependencies.serde]
version = "1.0.203"
features = [
Expand Down
4 changes: 2 additions & 2 deletions src/api/manage_jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(())
Expand Down
58 changes: 45 additions & 13 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -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<dyn SecretStore>,
}

impl Client {
pub fn new(
server_url: String,
token: String,
secret_store: Arc<dyn SecretStore>,
unsecured_certificate: bool,
with_proxy: bool,
) -> Client {
Expand Down Expand Up @@ -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<HeaderValue, Error> {
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<reqwest::blocking::RequestBuilder, Error> {
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<reqwest::blocking::RequestBuilder, Error> {
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<reqwest::blocking::RequestBuilder, Error> {
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 <token>` 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<HeaderValue, Error> {
// 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)
}
2 changes: 1 addition & 1 deletion src/api/register_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(&register_endpoint).json(&post_data).send() {
match self.post(&register_endpoint)?.json(&post_data).send() {
Ok(response) => {
if response.status().is_success() {
response
Expand Down
79 changes: 59 additions & 20 deletions src/config/settings.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,42 @@
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<String>,
pub unsecured_certificate: bool,
pub with_proxy: bool,
pub installation_mode: String,
pub service_name: String,
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", &"<redacted>")
.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
}
Expand Down Expand Up @@ -61,25 +81,44 @@ impl Settings {
}

pub fn new() -> Result<Self, ConfigError> {
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/<env>.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<Settings, ConfigError> {
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()
}
}
7 changes: 4 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ mod api;
mod common;
mod config;
mod process;
mod secrets;
mod windows;

#[cfg(test)]
Expand Down Expand Up @@ -61,7 +62,7 @@ fn compute_working_dir() -> PathBuf {

fn agent_start(settings_data: Settings, is_service: bool) -> Result<Vec<JoinHandle<()>>, 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;
Expand All @@ -81,7 +82,7 @@ fn agent_start(settings_data: Settings, is_service: bool) -> Result<Vec<JoinHand

let keep_alive_thread = keep_alive::ping(
url.clone(),
token.clone(),
secret_store.clone(),
unsecured_certificate,
with_proxy,
installation_mode,
Expand All @@ -92,7 +93,7 @@ fn agent_start(settings_data: Settings, is_service: bool) -> Result<Vec<JoinHand
// Starts the agent listening thread
let agent_job_thread = agent_job::listen(
url.clone(),
token.clone(),
secret_store,
unsecured_certificate,
with_proxy,
execution_details.clone(),
Expand Down
6 changes: 4 additions & 2 deletions src/process/agent_job.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
use crate::api::Client;
use crate::config::execution_details::ExecutionDetails;
use crate::process::agent_exec;
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;

pub fn listen(
uri: String,
token: String,
secret_store: Arc<dyn SecretStore>,
unsecured_certificate: bool,
with_proxy: bool,
execution_details: ExecutionDetails,
tenant_id: String,
) -> Result<JoinHandle<()>, 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) {
Expand Down
6 changes: 4 additions & 2 deletions src/process/keep_alive.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
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;

#[allow(clippy::too_many_arguments)]
pub fn ping(
uri: String,
token: String,
secret_store: Arc<dyn SecretStore>,
unsecured_certificate: bool,
with_proxy: bool,
installation_mode: String,
Expand All @@ -20,7 +22,7 @@ pub fn ping(
tenant_id: String,
) -> Result<JoinHandle<()>, 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) {
Expand Down
Loading
Loading