From 18f814dec9afbd9cd384c0046ba269974667334f Mon Sep 17 00:00:00 2001 From: Delta1925 Date: Wed, 19 Apr 2023 00:25:40 +0200 Subject: [PATCH] Improve logging --- backend/src/confirmation.rs | 15 ++++++++++----- backend/src/errors.rs | 2 +- backend/src/main.rs | 29 +++++++++++++++++++++-------- backend/src/management.rs | 3 ++- backend/src/settings.rs | 10 ++++++++-- backend/src/utils.rs | 8 +++----- 6 files changed, 45 insertions(+), 22 deletions(-) diff --git a/backend/src/confirmation.rs b/backend/src/confirmation.rs index 3c0914e..fc2ae9f 100644 --- a/backend/src/confirmation.rs +++ b/backend/src/confirmation.rs @@ -1,6 +1,6 @@ use chrono::Utc; use lettre::message::header::ContentType; -use log::{warn, debug}; +use log::{debug, error, warn}; use crate::errors::SpecialErrors; use crate::management::{delete_key, Action, Pending}; @@ -15,10 +15,11 @@ use std::path::Path; pub fn confirm_action(token: &str) -> Result<(Action, String)> { let pending_path = pending_path().join(token); - let content = read_file(&pending_path)?; + let content = log_err!(read_file(&pending_path), debug)?; let key = log_err!(toml::from_str::(&content), warn)?; if Utc::now().timestamp() - key.timestamp() > SETTINGS.max_age { log_err!(fs::remove_file(&pending_path), warn)?; + debug!("Token {} was stale", token); Err(SpecialErrors::ExpiredRequest)? } else { let address = match key.action() { @@ -43,7 +44,11 @@ pub fn confirm_action(token: &str) -> Result<(Action, String)> { } pub fn send_confirmation_email(address: &str, action: &Action, token: &str) -> Result<()> { - let template = read_file(&Path::new("assets").join("mail-template.html"))?; + let template = log_err!( + read_file(&Path::new("assets").join("mail-template.html")), + error, + true + )?; let mut url = SETTINGS .external_url .join("api/") @@ -77,8 +82,8 @@ pub fn send_confirmation_email(address: &str, action: &Action, token: &str) -> R let email = log_err!(email, warn)?; - match log_err!(MAILER.send(&email), warn){ + match log_err!(MAILER.send(&email), warn) { Ok(_) => Ok(()), - Err(_) => Err(SpecialErrors::MailErr)? + Err(_) => Err(SpecialErrors::MailErr)?, } } diff --git a/backend/src/errors.rs b/backend/src/errors.rs index bdce6b7..903c5d9 100644 --- a/backend/src/errors.rs +++ b/backend/src/errors.rs @@ -22,7 +22,7 @@ macro_rules! log_err { }}; ($var: expr, $level: ident, $panic: expr) => {{ let test = $var; - if log_err!(test, $level).is_err() { + if log_err!(&test, $level).is_err() { if $panic == true { panic!("{} {}", $crate::settings::ERROR_TEXT, test.unwrap_err()); } else { diff --git a/backend/src/main.rs b/backend/src/main.rs index 4fa040c..ccd0187 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -10,7 +10,8 @@ use crate::errors::SpecialErrors; use crate::management::{clean_stale, store_pending_addition, store_pending_deletion, Action}; use crate::settings::{ROOT_FOLDER, SETTINGS}; use crate::utils::{ - gen_random_token, get_email_from_cert, is_email_allowed, parse_pem, read_file, return_outcome, key_exists, + gen_random_token, get_email_from_cert, is_email_allowed, key_exists, parse_pem, read_file, + return_outcome, }; use actix_files::Files; @@ -70,7 +71,6 @@ async fn main() -> std::io::Result<()> { }) .bind((SETTINGS.bind_host.to_string(), SETTINGS.port))? .run(); - debug!("Server started successfully!"); info!( "Listening on: {}:{} (External url: {})", SETTINGS.bind_host, SETTINGS.port, SETTINGS.external_url @@ -87,7 +87,7 @@ async fn index(req: HttpRequest) -> Result { path.join(file) }; if path.is_file() { - let template = read_file(&path)?; + let template = log_err!(read_file(&path), error, true)?; let page = template.replace("((%u))", SETTINGS.external_url.as_ref()); return Ok(HttpResponseBuilder::new(StatusCode::OK) .insert_header(ContentType::html()) @@ -106,7 +106,10 @@ async fn submit(pem: web::Form) -> Result { is_email_allowed(&email)?; let token = gen_random_token(); store_pending_addition(pem.key.clone(), &email, &token)?; - debug!("Sending email to {} to add a key... (Request token: {})", email, token); + debug!( + "Sending email to {} to add a key... (Request token: {})", + email, token + ); send_confirmation_email(&email, &Action::Add, &token)?; info!("User {} requested to add a key successfully!", email); Ok(return_outcome(Ok("You submitted your key successfully!"))?) @@ -116,7 +119,11 @@ async fn submit(pem: web::Form) -> Result { async fn confirm(token: web::Query) -> Result { debug!("Handling token {}...", token.token); let (action, email) = confirm_action(&token.token)?; - info!("User {} confirmed to {} his key successfully!", email, action.to_string().to_lowercase()); + info!( + "User {} confirmed to {} his key successfully!", + email, + action.to_string().to_lowercase() + ); match action { Action::Add => Ok(return_outcome(Ok("Your key was added successfully!"))?), Action::Delete => Ok(return_outcome(Ok("Your key was deleted successfully!"))?), @@ -125,13 +132,19 @@ async fn confirm(token: web::Query) -> Result { #[get("/api/delete")] async fn delete(email: web::Query) -> Result { - debug!("Handling user {} request to add a key...", email.email); + debug!("Handling user {} request to delete a key...", email.email); key_exists(&email.email)?; let token = gen_random_token(); store_pending_deletion(email.email.clone(), &token)?; - debug!("Sending email to {} to add a key... (Request token: {})", email.email, token); + debug!( + "Sending email to {} to delete a key... (Request token: {})", + email.email, token + ); send_confirmation_email(&email.email, &Action::Delete, &token)?; - info!("User {} requested to delete his key successfully!", email.email); + info!( + "User {} requested to delete his key successfully!", + email.email + ); Ok(return_outcome(Ok( "You requested the deletion of your key successfully!", ))?) diff --git a/backend/src/management.rs b/backend/src/management.rs index 493c2b3..a9f6458 100644 --- a/backend/src/management.rs +++ b/backend/src/management.rs @@ -77,7 +77,8 @@ pub fn clean_stale(max_age: i64) { let file_path = path.path(); let content = match read_file(&file_path) { Ok(content) => content, - Err(_) => { + Err(error) => { + warn!("{} {}", ERROR_TEXT, error); continue; } }; diff --git a/backend/src/settings.rs b/backend/src/settings.rs index 6be45dd..9953799 100644 --- a/backend/src/settings.rs +++ b/backend/src/settings.rs @@ -1,5 +1,5 @@ use lettre::{transport::smtp::authentication::Credentials, SmtpTransport}; -use log::error; +use log::{debug, error, warn}; use once_cell::sync::Lazy; use sequoia_net::wkd::Variant; use sequoia_openpgp::policy::StandardPolicy; @@ -47,15 +47,18 @@ pub enum SMTPEncryption { } fn get_settings() -> Settings { + debug!("Parsing settings..."); let content = match read_file(&PathBuf::from("config.toml")) { Ok(content) => content, Err(_) => { + error!("Unable to access settings file!"); panic!("Unable to access settings file!") } }; let settings = match log_err!(toml::from_str(&content), error) { Ok(settings) => settings, Err(_) => { + error!("Unable to parse settings from file!"); panic!("Unable to parse settings from file!") } }; @@ -63,6 +66,7 @@ fn get_settings() -> Settings { } fn get_mailer() -> SmtpTransport { + debug!("Setting up smtp..."); let creds = Credentials::new( SETTINGS.mail_settings.smtp_username.to_owned(), SETTINGS.mail_settings.smtp_password.to_owned(), @@ -76,13 +80,15 @@ fn get_mailer() -> SmtpTransport { let mailer = match builder { Ok(builder) => builder, Err(_) => { + error!("Unable to set up smtp"); panic!("Unable to set up smtp") } } .credentials(creds) .port(SETTINGS.mail_settings.smtp_port) .build(); - let _ = mailer.test_connection(); + debug!("Testing smtp connection..."); + let _ = log_err!(mailer.test_connection(), warn); mailer } diff --git a/backend/src/utils.rs b/backend/src/utils.rs index 70b29d7..875b6f2 100644 --- a/backend/src/utils.rs +++ b/backend/src/utils.rs @@ -12,8 +12,7 @@ use actix_web::{ use anyhow::Result; use flexi_logger::{style, DeferredNow, FileSpec, FlexiLoggerError, Logger, LoggerHandle, Record}; use log::debug; -use log::trace; -use log::warn; +use log::error; use rand::{distributions::Alphanumeric, thread_rng, Rng}; use sequoia_net::wkd::Url; use sequoia_openpgp::{parse::Parse, Cert}; @@ -42,9 +41,8 @@ pub fn webpage_path() -> PathBuf { pub fn read_file(path: &PathBuf) -> Result { if path.is_file() { - Ok(log_err!(fs::read_to_string(path), warn)?) + Ok(fs::read_to_string(path)?) } else { - trace!("The requested file {} does not exist", path.display()); Err(SpecialErrors::MissingFile)? } } @@ -171,7 +169,7 @@ pub fn init_logger() -> Result { pub fn return_outcome(data: Result<&str, &CompatErr>) -> Result { let path = webpage_path().join("status").join("index.html"); - let template = read_file(&path)?; + let template = log_err!(read_file(&path), error, true)?; let (page, message) = match data { Ok(message) => (template.replace("((%s))", "Success!"), message.to_string()), Err(error) => (template.replace("((%s))", "Failure!"), error.to_string()),