Skip to content

Commit

Permalink
enhance error tracing and logging accross the codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
Hermann-Core committed Nov 21, 2024
1 parent 4551712 commit a962f0e
Show file tree
Hide file tree
Showing 28 changed files with 184 additions and 170 deletions.
20 changes: 16 additions & 4 deletions crates/filesystem/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,17 @@ impl FileSystem for StdFileSystem {
flock(file.as_raw_fd(), FlockArg::LockExclusive)
.map_err(|_| IoError::new(ErrorKind::Other, "Error acquiring file lock"))?;

std::fs::write(path, &content).expect("Error saving base64-encoded image to file");
std::fs::write(path, &content).map_err(|_| {
IoError::new(
ErrorKind::Other,
"Error saving base64-encoded image to file",
)
})?;

// Release the lock after writing to the file
flock(file.as_raw_fd(), FlockArg::Unlock).expect("Error releasing file lock");
flock(file.as_raw_fd(), FlockArg::Unlock)
.map_err(|_| IoError::new(ErrorKind::Other, "Error releasing file lock"))?;

Ok(())
}

Expand Down Expand Up @@ -112,11 +119,16 @@ mod tests {

impl FileSystem for MockFileSystem {
fn read_to_string(&self, path: &Path) -> IoResult<String> {
Ok(self.map.get(path.to_str().unwrap()).cloned().unwrap_or_default())
Ok(self
.map
.get(path.to_str().unwrap())
.cloned()
.unwrap_or_default())
}

fn write(&mut self, path: &Path, content: &str) -> IoResult<()> {
self.map.insert(path.to_str().unwrap().to_string(), content.to_string());
self.map
.insert(path.to_str().unwrap().to_string(), content.to_string());
Ok(())
}

Expand Down
6 changes: 4 additions & 2 deletions crates/plugin-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ use axum::Router;

#[derive(Debug, Error, PartialEq)]
pub enum PluginError {
#[error("cause: {0}")]
#[error("{0}")]
InitError(String),
#[error("{0}")]
Other(String),
}

pub trait Plugin: Sync + Send {
Expand All @@ -23,7 +25,7 @@ pub trait Plugin: Sync + Send {
fn unmount(&self) -> Result<(), PluginError>;

/// Export managed endpoints
fn routes(&self) -> Router;
fn routes(&self) -> Result<Router, PluginError>;
}

impl Eq for dyn Plugin {}
Expand Down
8 changes: 5 additions & 3 deletions crates/web-plugins/did-endpoint/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,10 @@ impl Plugin for DidEndpoint {
Ok(())
}

fn routes(&self) -> Router {
let state = self.state.as_ref().expect("Plugin not mounted");
web::routes(Arc::new(state.clone()))
fn routes(&self) -> Result<Router, PluginError> {
let state = self.state.as_ref().ok_or(PluginError::Other(
"missing state, plugin not mounted".to_owned(),
))?;
Ok(web::routes(Arc::new(state.clone())))
}
}
5 changes: 4 additions & 1 deletion crates/web-plugins/did-endpoint/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ async fn diddoc(State(state): State<Arc<DidEndPointState>>) -> Result<Json<Value
let did_path = Path::new(&storage_dirpath).join("did.json");

match filesystem.read_to_string(&did_path).as_ref() {
Ok(content) => Ok(Json(serde_json::from_str(&content).unwrap())),
Ok(content) => Ok(Json(serde_json::from_str(&content).map_err(|_| {
tracing::error!("Unparseable did.json");
StatusCode::NOT_FOUND
})?)),
Err(_) => Err(StatusCode::NOT_FOUND),
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::error::ForwardError;
use crate::ForwardError;
use database::Repository;
use didcomm::{AttachmentData, Message};
use mongodb::bson::doc;
Expand All @@ -9,30 +9,12 @@ use shared::{
};
use std::sync::Arc;

async fn checks(
message: &Message,
connection_repository: &Arc<dyn Repository<Connection>>,
) -> Result<String, ForwardError> {
let next = message.body.get("next").and_then(Value::as_str);
match next {
Some(next) => next,
None => return Err(ForwardError::MalformedBody),
};

// Check if the client's did in mediator's keylist
let _connection = match connection_repository
.find_one_by(doc! {"keylist": doc!{ "$elemMatch": { "$eq": &next}}})
.await
.map_err(|_| ForwardError::InternalServerError)?
{
Some(connection) => connection,
None => return Err(ForwardError::UncoordinatedSender),
};

Ok(next.unwrap().to_string())
}

pub(crate) async fn handler(state: Arc<AppState>, message: Message) -> Result<Option<Message>, ForwardError> {
/// Mediator receives forwarded messages, extract the next field in the message body, and the attachments in the message
/// then stores the attachment with the next field as key for pickup
pub async fn mediator_forward_process(
state: Arc<AppState>,
message: Message,
) -> Result<Option<Message>, ForwardError> {
let AppStateRepository {
message_repository,
connection_repository,
Expand Down Expand Up @@ -66,10 +48,31 @@ pub(crate) async fn handler(state: Arc<AppState>, message: Message) -> Result<Op
Ok(None)
}

async fn checks(
message: &Message,
connection_repository: &Arc<dyn Repository<Connection>>,
) -> Result<String, ForwardError> {
let next = message.body.get("next").and_then(Value::as_str);
match next {
Some(next) => next,
None => return Err(ForwardError::MalformedBody),
};

// Check if the client's did in mediator's keylist
let _connection = match connection_repository
.find_one_by(doc! {"keylist": doc!{ "$elemMatch": { "$eq": &next}}})
.await
.map_err(|_| ForwardError::InternalServerError)?
{
Some(connection) => connection,
None => return Err(ForwardError::UncoordinatedSender),
};

Ok(next.unwrap().to_string())
}

#[cfg(test)]
mod test {
use crate::web::handler::mediator_forward_process;

use super::*;
use did_utils::jwk::Jwk;
use didcomm::{
Expand Down Expand Up @@ -163,7 +166,9 @@ mod test {
.await
.expect("Unable unpack");

let msg = mediator_forward_process(Arc::new(state.clone()), msg).await.unwrap();
let msg = mediator_forward_process(Arc::new(state.clone()), msg)
.await
.unwrap();

println!("Mediator1 is forwarding message \n{:?}\n", msg);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
mod error;
pub mod web;
pub mod handler;

// Re-exports
pub use error::ForwardError;

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ multibase.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tracing.workspace = true
json-canon.workspace = true
didcomm = { workspace = true, features = ["uniffi"] }
tokio = { workspace = true, features = ["full"] }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub enum MediationError {
UncoordinatedSender,
#[error("could not parse into expected message format")]
UnexpectedMessageFormat,
#[error("internal server error")]
InternalServerError,
}

impl IntoResponse for MediationError {
Expand All @@ -23,6 +25,7 @@ impl IntoResponse for MediationError {
}
MediationError::UncoordinatedSender => StatusCode::UNAUTHORIZED,
MediationError::UnexpectedMessageFormat => StatusCode::BAD_REQUEST,
MediationError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
};

let body = Json(serde_json::json!({
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use crate::{
errors::MediationError,
handler::midlw::ensure_jwm_type_is_mediation_request,
model::stateful::coord::{
Keylist, KeylistBody, KeylistEntry, KeylistUpdateAction, KeylistUpdateBody,
KeylistUpdateConfirmation, KeylistUpdateResponseBody, KeylistUpdateResult, MediationDeny,
MediationGrant, MediationGrantBody,
},
web::handler::midlw::ensure_jwm_type_is_mediation_request,
};
use did_utils::{
crypto::{Ed25519KeyPair, Generate, ToMultikey, X25519KeyPair},
Expand Down Expand Up @@ -40,10 +40,7 @@ pub async fn process_mediate_request(

let mediator_did = &state.diddoc.id;

let sender_did = plain_message
.from
.as_ref()
.expect("should not panic as anonymous requests are rejected earlier");
let sender_did = plain_message.from.as_ref().unwrap();

// Retrieve repository to connection entities

Expand All @@ -53,15 +50,15 @@ pub async fn process_mediate_request(
} = state
.repository
.as_ref()
.expect("missing persistence layer");
.ok_or(MediationError::InternalServerError)?;

// If there is already mediation, send mediate deny
if let Some(_connection) = connection_repository
.find_one_by(doc! { "client_did": sender_did})
.await
.unwrap()
.map_err(|_| MediationError::InternalServerError)?
{
println!("Sending mediate deny.");
tracing::info!("Sending mediate deny.");
return Ok(Some(
Message::build(
format!("urn:uuid:{}", Uuid::new_v4()),
Expand All @@ -78,24 +75,27 @@ pub async fn process_mediate_request(
));
} else {
/* Issue mediate grant response */
println!("Sending mediate grant.");
tracing::info!("Sending mediate grant.");
// Create routing, store it and send mediation grant
let (routing_did, auth_keys, agreem_keys) =
generate_did_peer(state.public_domain.to_string());

let AppStateRepository { keystore, .. } = state
.repository
.as_ref()
.expect("missing persistence layer");
.ok_or(MediationError::InternalServerError)?;

let diddoc = state
.did_resolver
.resolve(&routing_did)
.await
.unwrap()
.expect("Could not resolve DID");
.map_err(|err| {
tracing::error!("Failed to resolve DID: {:?}", err);
MediationError::InternalServerError
})?
.ok_or(MediationError::InternalServerError)?;

let agreem_keys_jwk: Jwk = agreem_keys.try_into().expect("MediateRequestError");
let agreem_keys_jwk: Jwk = agreem_keys.try_into().unwrap();

let agreem_keys_secret = Secrets {
id: None,
Expand All @@ -105,12 +105,12 @@ pub async fn process_mediate_request(

match keystore.store(agreem_keys_secret).await {
Ok(_stored_connection) => {
println!("Successfully stored connection.")
tracing::info!("Successfully stored agreement keys.")
}
Err(error) => eprintln!("Error storing connection: {:?}", error),
Err(error) => tracing::debug!("Error storing agreement keys: {:?}", error),
}

let auth_keys_jwk: Jwk = auth_keys.try_into().expect("MediateRequestError");
let auth_keys_jwk: Jwk = auth_keys.try_into().unwrap();

let auth_keys_secret = Secrets {
id: None,
Expand All @@ -120,9 +120,9 @@ pub async fn process_mediate_request(

match keystore.store(auth_keys_secret).await {
Ok(_stored_connection) => {
println!("Successfully stored connection.")
tracing::info!("Successfully stored authentication keys.")
}
Err(error) => eprintln!("Error storing connection: {:?}", error),
Err(error) => tracing::debug!("Error storing authentication keys: {:?}", error),
}

let mediation_grant = create_mediation_grant(&routing_did);
Expand All @@ -138,9 +138,9 @@ pub async fn process_mediate_request(
// Use store_one to store the sample connection
match connection_repository.store(new_connection).await {
Ok(_stored_connection) => {
println!("Successfully stored connection: ")
tracing::info!("Successfully stored connection: ")
}
Err(error) => eprintln!("Error storing connection: {:?}", error),
Err(error) => tracing::debug!("Error storing connection: {:?}", error),
}

Ok(Some(
Expand Down Expand Up @@ -225,7 +225,7 @@ pub async fn process_plain_keylist_update_message(
} = state
.repository
.as_ref()
.expect("missing persistence layer");
.ok_or(MediationError::InternalServerError)?;

// Find connection for this keylist update

Expand Down Expand Up @@ -345,7 +345,7 @@ pub async fn process_plain_keylist_query_message(
} = state
.repository
.as_ref()
.expect("missing persistence layer");
.ok_or(MediationError::InternalServerError)?;

let connection = connection_repository
.find_one_by(doc! { "client_did": &sender })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ mod jose;
mod model;

pub mod client;
pub mod web;
pub mod handler;

// Re-exports
pub use errors::MediationError;

This file was deleted.

2 changes: 2 additions & 0 deletions crates/web-plugins/didcomm-messaging/shared/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ serde.workspace = true
serde_json.workspace = true
async-trait.workspace = true
mongodb.workspace = true
tracing.workspace = true
eyre.workspace = true
hyper = { workspace = true, features = ["full"] }
tokio = { workspace = true, features = ["full"] }
axum = { workspace = true, features = ["macros"] }
Expand Down
Loading

0 comments on commit a962f0e

Please sign in to comment.