sysmonk/squire/startup.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
use std;
use std::io::Write;
use crate::squire::settings;
use crate::{constant, squire};
use chrono::{DateTime, Local};
use regex::Regex;
/// Initializes the logger based on the provided debug flag and cargo information.
///
/// # Arguments
///
/// * `debug` - A flag indicating whether to enable debug mode for detailed logging.
/// * `crate_name` - Name of the crate loaded during compile time.
pub fn init_logger(debug: bool, utc: bool, crate_name: &String) {
if debug {
std::env::set_var("RUST_LOG", format!(
"actix_web=debug,actix_server=info,{}=debug", crate_name
));
std::env::set_var("RUST_BACKTRACE", "1");
} else {
// Set Actix logging to warning mode since it becomes too noisy when streaming
std::env::set_var("RUST_LOG", format!(
"actix_web=warn,actix_server=warn,{}=info", crate_name
));
std::env::set_var("RUST_BACKTRACE", "0");
}
let timestamp = if utc {
DateTime::<chrono::Utc>::from(Local::now())
.format("%Y-%m-%dT%H:%M:%SZ")
.to_string()
} else {
Local::now()
.format("%Y-%m-%dT%H:%M:%SZ")
.to_string()
};
env_logger::Builder::from_default_env()
.format(move |buf, record| {
writeln!(
buf,
"[{} {} {}:{}] - {}",
timestamp,
record.level(),
record.target(),
record.line().unwrap_or(0),
record.args()
)
})
.init();
}
/// Extracts the mandatory env vars by key and parses it as `HashMap<String, String>` and `PathBuf`
///
/// # Returns
///
/// Returns a tuple of `HashMap<String, String>` and `PathBuf`.
///
/// # Panics
///
/// If the value is missing or if there is an error parsing the `HashMap`
fn mandatory_vars() -> (String, String) {
let mut errors = "".to_owned();
let username = match std::env::var("username") {
Ok(val) => val,
Err(_) => {
errors.push_str(
"\nusername\n\texpected a string, received null [value=missing]\n",
);
"".to_string()
}
};
let password = match std::env::var("password") {
Ok(val) => val,
Err(_) => {
errors.push_str(
"\npassword\n\texpected a string, received null [value=missing]\n",
);
"".to_string()
}
};
if !errors.is_empty() {
panic!("{}", errors);
}
(username, password)
}
/// Extracts the env var by key and parses it as a `bool`
///
/// # Arguments
///
/// * `key` - Key for the environment variable.
///
/// # Returns
///
/// Returns an `Option<bool>` if the value is available.
///
/// # Panics
///
/// If the value is present, but it is an invalid data-type.
fn parse_bool(key: &str) -> Option<bool> {
match std::env::var(key) {
Ok(val) => match val.parse() {
Ok(parsed) => Some(parsed),
Err(_) => {
panic!("\n{}\n\texpected bool, received '{}' [value=invalid]\n", key, val);
}
},
Err(_) => None,
}
}
/// Extracts the env var by key and parses it as a `i64`
///
/// # Arguments
///
/// * `key` - Key for the environment variable.
///
/// # Returns
///
/// Returns an `Option<i64>` if the value is available.
///
/// # Panics
///
/// If the value is present, but it is an invalid data-type.
fn parse_i64(key: &str) -> Option<i64> {
match std::env::var(key) {
Ok(val) => match val.parse() {
Ok(parsed) => Some(parsed),
Err(_) => {
panic!("\n{}\n\texpected i64, received '{}' [value=invalid]\n", key, val);
}
},
Err(_) => None,
}
}
/// Extracts the env var by key and parses it as a `u16`
///
/// # Arguments
///
/// * `key` - Key for the environment variable.
///
/// # Returns
///
/// Returns an `Option<u16>` if the value is available.
///
/// # Panics
///
/// If the value is present, but it is an invalid data-type.
fn parse_u16(key: &str) -> Option<u16> {
match std::env::var(key) {
Ok(val) => match val.parse() {
Ok(parsed) => Some(parsed),
Err(_) => {
panic!("\n{}\n\texpected u16, received '{}' [value=invalid]\n", key, val);
}
},
Err(_) => None,
}
}
/// Extracts the env var by key and parses it as a `usize`
///
/// # Arguments
///
/// * `key` - Key for the environment variable.
///
/// # Returns
///
/// Returns an `Option<usize>` if the value is available.
///
/// # Panics
///
/// If the value is present, but it is an invalid data-type.
fn parse_usize(key: &str) -> Option<usize> {
match std::env::var(key) {
Ok(val) => match val.parse() {
Ok(parsed) => Some(parsed),
Err(_) => {
panic!("\n{}\n\texpected usize, received '{}' [value=invalid]\n", key, val);
}
},
Err(_) => None,
}
}
/// Extracts the env var by key and parses it as a `Vec<String>`
///
/// # Arguments
///
/// * `key` - Key for the environment variable.
///
/// # Returns
///
/// Returns an `Option<Vec<String>>` if the value is available.
///
/// # Panics
///
/// If the value is present, but it is an invalid data-type.
fn parse_vec(key: &str) -> Option<Vec<String>> {
match std::env::var(key) {
Ok(val) => match serde_json::from_str::<Vec<String>>(&val) {
Ok(parsed) => Some(parsed),
Err(_) => {
panic!("\n{}\n\texpected vec, received '{}' [value=invalid]\n", key, val);
}
},
Err(_) => None,
}
}
/// Handler that's responsible to parse all the env vars.
///
/// # Returns
///
/// Instantiates the `Config` struct with the required parameters.
fn load_env_vars() -> settings::Config {
let (username, password) = mandatory_vars();
let debug = parse_bool("debug").unwrap_or(settings::default_debug());
let utc_logging = parse_bool("utc_logging").unwrap_or(settings::default_utc_logging());
let host = std::env::var("host").unwrap_or(settings::default_host());
let port = parse_u16("port").unwrap_or(settings::default_port());
let session_duration = parse_i64("session_duration").unwrap_or(settings::default_session_duration());
let workers = parse_usize("workers").unwrap_or(settings::default_workers());
let max_connections = parse_usize("max_connections").unwrap_or(settings::default_max_connections());
let websites = parse_vec("websites").unwrap_or(settings::default_websites());
settings::Config {
username,
password,
debug,
utc_logging,
host,
port,
session_duration,
workers,
max_connections,
websites,
}
}
/// Verifies the strength of a password string.
///
/// A secret is considered strong if it meets the following conditions:
/// - At least 32 characters long
/// - Contains at least one digit
/// - Contains at least one uppercase letter
/// - Contains at least one lowercase letter
/// - Contains at least one special character
///
/// # Arguments
///
/// * `password` - A reference to a string slice (`&str`) that represents the password to check.
///
/// # Returns
///
/// This function returns a `Result<(), String>`.
/// - `Ok(())` is returned if all conditions are met.
/// - `Err(String)` is returned with an error message if any condition fails.
pub fn complexity_checker(password: &str) -> Result<(), String> {
let mock_password = "*".repeat(password.len());
// Check minimum length
if password.len() < 8 {
return Err(
format!(
"\npassword\n\t[{}] password must be at least 8 or more characters [value=invalid]\n", mock_password
)
);
}
// Check for at least one digit
let has_digit = Regex::new(r"\d").unwrap();
if !has_digit.is_match(password) {
return Err(
format!(
"\npassword\n\t[{}] password must include at least one digit [value=invalid]\n", mock_password
)
);
}
// Check for at least one uppercase letter
let has_uppercase = Regex::new(r"[A-Z]").unwrap();
if !has_uppercase.is_match(password) {
return Err(
format!(
"\npassword\n\t[{}] password must include at least one uppercase letter [value=invalid]\n", mock_password
)
);
}
// Check for at least one lowercase letter
let has_lowercase = Regex::new(r"[a-z]").unwrap();
if !has_lowercase.is_match(password) {
return Err(
format!(
"\npassword\n\t[{}] password must include at least one lowercase letter [value=invalid]\n", mock_password
)
);
}
// Check for at least one special character
let has_special_char = Regex::new(r###"[ !#$%&'()*+,./:;<=>?@\\^_`{|}~"-]"###).unwrap();
if !has_special_char.is_match(password) {
return Err(
format!(
"\npassword\n\t[{}] password must contain at least one special character [value=invalid]\n", mock_password
)
);
}
Ok(())
}
/// Validates all the required environment variables with the required settings.
///
/// # Returns
///
/// Returns the `Config` struct containing the required parameters.
fn validate_vars() -> settings::Config {
let config = load_env_vars();
let mut errors = "".to_owned();
if config.username.len() < 4 {
let err1 = format!(
"\nusername\n\t[{}] username should be at least 4 or more characters [value=invalid]\n",
config.username
);
errors.push_str(&err1);
}
match complexity_checker(&config.password) {
Ok(_) => (),
Err(err) => {
errors.push_str(&err);
}
}
if !errors.is_empty() {
panic!("{}", errors);
}
config
}
/// Retrieves the environment variables and parses as the data-type specified in Config struct.
///
/// # Arguments
///
/// * `metadata` - Struct containing metadata of the application.
///
/// # Returns
///
/// Converts the config struct into an `Arc` and returns it.
pub fn get_config(metadata: &constant::MetaData) -> std::sync::Arc<settings::Config> {
let mut env_file = squire::parser::arguments(metadata);
if env_file.is_empty() {
env_file = std::env::var("env_file")
.unwrap_or(std::env::var("ENV_FILE")
.unwrap_or(".env".to_string()));
}
let env_file_path = std::env::current_dir()
.unwrap_or_default()
.join(env_file);
let _ = dotenv::from_path(env_file_path.as_path());
std::sync::Arc::new(validate_vars())
}