diff --git a/Cargo.lock b/Cargo.lock index 811857deca..cc64458921 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2899,6 +2899,7 @@ dependencies = [ "serde_json", "serde_with", "sqlx", + "thiserror", "tokio", "uuid 1.5.0", ] @@ -4690,18 +4691,18 @@ checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" [[package]] name = "thiserror" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4" +checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc" +checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", diff --git a/agents/rust/mediator/mediation/Cargo.toml b/agents/rust/mediator/mediation/Cargo.toml index 7a3598d838..f7d8c42da1 100644 --- a/agents/rust/mediator/mediation/Cargo.toml +++ b/agents/rust/mediator/mediation/Cargo.toml @@ -27,6 +27,7 @@ serde = { version = "1.0.164", features = ["derive"] } serde_json = "1.0.104" serde_with = { version = "3.1.0", features = ["base64"] } sqlx = { version = "0.7", features = ["runtime-tokio"], optional = true } +thiserror = "1.0.50" # sqlx = { version = "0.5.8", git = "https://github.com/jovfer/sqlx", branch = "feature/json_no_preserve_order_v5", features = [ "sqlite", "mysql", "json_no_preserve_order", "runtime-tokio-rustls"], optional = true } tokio = { version = "1.28.2", features = ["rt-multi-thread", "macros"] } uuid = { version = "1.5.0", features = ["v4"] } diff --git a/agents/rust/mediator/mediation/src/lib.rs b/agents/rust/mediator/mediation/src/lib.rs index c3773a0ccc..26292da0ad 100644 --- a/agents/rust/mediator/mediation/src/lib.rs +++ b/agents/rust/mediator/mediation/src/lib.rs @@ -1,7 +1,6 @@ // Copyright 2023 Naian G. // SPDX-License-Identifier: Apache-2.0 -pub mod didcomm_types; pub mod logging; pub mod router; pub mod routes; diff --git a/agents/rust/mediator/mediation/src/router.rs b/agents/rust/mediator/mediation/src/router.rs index 1144a39040..5fdf58b322 100644 --- a/agents/rust/mediator/mediation/src/router.rs +++ b/agents/rust/mediator/mediation/src/router.rs @@ -3,13 +3,10 @@ // use crate::routes::coordination::handle_coord; use std::sync::Arc; -use axum::{ - routing::{get, post}, - Router, -}; +use axum::{routing::get, Router}; use crate::{ - routes::{forward::handle_forward, hello_world, json, json::respond_message_json}, + routes::{hello_world, json, json::respond_message_json}, storage, }; @@ -26,7 +23,7 @@ pub async fn create_router() -> Router { "/json", get(json::echo_message_json).post(respond_message_json), ) - .route("/forward", post(handle_forward)) + // .route("/forward", post(handle_forward)) // .route("/pickup", post(handle_pickup)) // .route("/coord", post(handle_coord)) .with_state(Arc::new(storage)) diff --git a/agents/rust/mediator/mediation/src/routes/coordination.rs b/agents/rust/mediator/mediation/src/routes/coordination.rs index 652d52fdad..0088211200 100644 --- a/agents/rust/mediator/mediation/src/routes/coordination.rs +++ b/agents/rust/mediator/mediation/src/routes/coordination.rs @@ -4,19 +4,26 @@ use std::sync::Arc; use axum::{extract::State, Json}; - -use crate::{ - didcomm_types::mediator_coord_structs::{MediatorCoordMsgEnum::*, *}, - storage::MediatorPersistence, +use messages::msg_fields::protocols::coordinate_mediation::{ + keylist::KeylistItem, + keylist_update::{KeylistUpdateItem, KeylistUpdateItemAction}, + keylist_update_response::{KeylistUpdateItemResult, KeylistUpdateResponseItem}, + CoordinateMediation, Keylist, KeylistContent, KeylistDecorators, KeylistQueryContent, + KeylistUpdateContent, KeylistUpdateResponse, KeylistUpdateResponseContent, + KeylistUpdateResponseDecorators, MediateDeny, MediateDenyContent, MediateDenyDecorators, + MediateGrant, MediateGrantContent, MediateGrantDecorators, }; +use uuid::Uuid; + +use crate::storage::MediatorPersistence; pub async fn handle_coord_authenticated( State(storage): State>, - Json(message): Json, + Json(message): Json, auth_pubkey: &str, -) -> Json { +) -> Json { match message { - MediateRequest => { + CoordinateMediation::MediateRequest(_mediate_request) => { panic!( "Use handle_mediate_request directly. This handler is for preregistered clients." ); @@ -32,20 +39,18 @@ pub async fn handle_coord_authenticated( // ) // .await } - KeylistUpdateRequest(keylist_update_data) => { - handle_keylist_update(storage, keylist_update_data, auth_pubkey).await + CoordinateMediation::KeylistUpdate(keylist_update) => { + handle_keylist_update(storage, keylist_update.content, auth_pubkey).await } - KeylistQuery(keylist_query_data) => { - handle_keylist_query(storage, keylist_query_data, auth_pubkey).await + CoordinateMediation::KeylistQuery(keylist_query) => { + handle_keylist_query(storage, keylist_query.content, auth_pubkey).await } _ => handle_unimplemented().await, } } -pub async fn handle_unimplemented() -> Json { - Json(MediatorCoordMsgEnum::XumErrorMsg { - error: "Unimplemented".to_owned(), - }) +pub async fn handle_unimplemented() -> Json { + todo!("This error should ideally be handled on outer layer. Panicking for now.") } pub async fn handle_mediate_request( @@ -53,42 +58,65 @@ pub async fn handle_mediate_request( auth_pubkey: &str, did_doc: &str, our_signing_key: &str, - grant_data: MediateGrantData, -) -> Json { + grant_content: MediateGrantContent, +) -> Json { match storage .create_account(auth_pubkey, our_signing_key, did_doc) .await { - Ok(()) => Json(MediateGrant(grant_data)), - Err(msg) => Json(MediateDeny(MediateDenyData { reason: msg })), + Ok(()) => { + let mediate_grant_msg = MediateGrant::builder() + .content(grant_content) + .decorators(MediateGrantDecorators::default()) + .id(Uuid::new_v4().to_string()) + .build(); + Json(CoordinateMediation::MediateGrant(mediate_grant_msg)) + } + Err(_msg) => { + let mediate_deny_msg = MediateDeny::builder() + .content(MediateDenyContent::default()) + .decorators(MediateDenyDecorators::default()) + .id(Uuid::new_v4().to_string()) + .build(); + Json(CoordinateMediation::MediateDeny(mediate_deny_msg)) + } } } pub async fn handle_keylist_query( storage: Arc, //todo: use the limits mentioned in the KeylistQueryData to modify response - _keylist_query_data: KeylistQueryData, + _keylist_query_data: KeylistQueryContent, auth_pubkey: &str, -) -> Json { +) -> Json { let keylist_items: Vec = match storage.list_recipient_keys(auth_pubkey).await { Ok(recipient_keys) => recipient_keys .into_iter() .map(|recipient_key| KeylistItem { recipient_key }) .collect(), - Err(err) => return Json(MediatorCoordMsgEnum::XumErrorMsg { error: err }), + Err(err) => todo!( + "This error should ideally be handled on outer layer. Panicking for now{}", + err + ), }; - Json(MediatorCoordMsgEnum::Keylist(KeylistData { - keys: keylist_items, - })) + let keylist = Keylist::builder() + .content(KeylistContent { + keys: keylist_items, + pagination: None, + }) + .decorators(KeylistDecorators::default()) + .id(Uuid::new_v4().to_string()) + .build(); + Json(CoordinateMediation::Keylist(keylist)) } pub async fn handle_keylist_update( storage: Arc, - keylist_update_data: KeylistUpdateRequestData, + keylist_update_data: KeylistUpdateContent, auth_pubkey: &str, -) -> Json { +) -> Json { let updates: Vec = keylist_update_data.updates; - let mut updated: Vec = Vec::new(); + let mut updated: Vec = Vec::new(); for update_item in updates.into_iter() { let result = match &update_item.action { KeylistUpdateItemAction::Add => { @@ -106,13 +134,18 @@ pub async fn handle_keylist_update( Ok(()) => KeylistUpdateItemResult::Success, Err(_msg) => KeylistUpdateItemResult::ServerError, }; - updated.push(KeylistUpdateItem { + updated.push(KeylistUpdateResponseItem { recipient_key: update_item.recipient_key, action: update_item.action, - result: Some(update_item_result), + result: update_item_result, }); } - Json(MediatorCoordMsgEnum::KeylistUpdateResponse( - KeylistUpdateResponseData { updated }, + let keylist_update_response = KeylistUpdateResponse::builder() + .content(KeylistUpdateResponseContent { updated }) + .decorators(KeylistUpdateResponseDecorators::default()) + .id(Uuid::new_v4().to_string()) + .build(); + Json(CoordinateMediation::KeylistUpdateResponse( + keylist_update_response, )) } diff --git a/agents/rust/mediator/mediation/src/routes/forward.rs b/agents/rust/mediator/mediation/src/routes/forward.rs index 98269a44f9..03c7b7a034 100644 --- a/agents/rust/mediator/mediation/src/routes/forward.rs +++ b/agents/rust/mediator/mediation/src/routes/forward.rs @@ -5,20 +5,50 @@ use std::sync::Arc; use axum::{extract::State, Json}; use log::{debug, info}; +use messages::{ + decorators::thread::Thread, + msg_fields::protocols::{ + notification::ack::{Ack, AckContent, AckDecorators, AckStatus}, + routing::Forward, + }, +}; +use uuid::Uuid; -use crate::{didcomm_types::ForwardMsg, storage::MediatorPersistence}; +use crate::storage::MediatorPersistence; pub async fn handle_forward( State(storage): State>, - Json(forward_msg): Json, -) -> Json + Json(forward_msg): Json, +) -> Json where T: MediatorPersistence, { info!("Persisting forward message"); debug!("{forward_msg:#?}"); - let _ = storage - .persist_forward_message(&forward_msg.recipient_key, &forward_msg.message_data) - .await; - Json(forward_msg) + let _ack_status = match storage + .persist_forward_message( + &forward_msg.content.to, + &serde_json::to_string(&forward_msg.content.msg).unwrap(), + ) + .await + { + Ok(_) => { + info!("Persisted forward"); + AckStatus::Ok + } + Err(e) => { + info!("Error when persisting forward: {}", e); + AckStatus::Pending + } + }; + let ack_content = AckContent::builder().status(AckStatus::Ok).build(); + let ack_deco = AckDecorators::builder() + .thread(Thread::builder().thid(forward_msg.id).build()) + .build(); + let ack = Ack::builder() + .content(ack_content) + .decorators(ack_deco) + .id(Uuid::new_v4().to_string()) + .build(); + Json(ack) } diff --git a/agents/rust/mediator/src/didcomm_handlers/forward.rs b/agents/rust/mediator/src/didcomm_handlers/forward.rs index c49a9b2553..42d7d50176 100644 --- a/agents/rust/mediator/src/didcomm_handlers/forward.rs +++ b/agents/rust/mediator/src/didcomm_handlers/forward.rs @@ -1,17 +1,15 @@ use axum::{extract::State, Json}; -use mediation::{didcomm_types::ForwardMsg, routes::forward::handle_forward}; -use messages::msg_fields::protocols::routing::Forward; +use mediation::routes::forward::handle_forward; +use messages::msg_fields::protocols::{notification::ack::Ack, routing::Forward}; use super::{utils::prelude::*, ArcAgent}; pub async fn handle_routing_forward( agent: ArcAgent, forward: Forward, -) -> Result<(), String> { +) -> Result { info!("{:?}", forward); - let forward_msg_content_str = serde_json::to_string(&forward.content.msg).unwrap(); - let forward_msg: ForwardMsg = ForwardMsg::new(&forward.content.to, &forward_msg_content_str); + let Json(ack) = handle_forward(State(agent.get_persistence_ref()), Json(forward)).await; - let _ = handle_forward(State(agent.get_persistence_ref()), Json(forward_msg)).await; - Ok(()) + Ok(ack) } diff --git a/agents/rust/mediator/src/didcomm_handlers/mediator_coord.rs b/agents/rust/mediator/src/didcomm_handlers/mediator_coord.rs index 0e7a929fea..ed7a722a9f 100644 --- a/agents/rust/mediator/src/didcomm_handlers/mediator_coord.rs +++ b/agents/rust/mediator/src/didcomm_handlers/mediator_coord.rs @@ -1,14 +1,17 @@ use axum::{extract::State, Json}; -use mediation::didcomm_types::mediator_coord_structs::{MediateGrantData, MediatorCoordMsgEnum}; +use messages::msg_fields::protocols::coordinate_mediation::{ + CoordinateMediation, MediateGrant, MediateGrantContent, MediateGrantDecorators, +}; +use uuid::Uuid; use super::utils::prelude::*; pub async fn handle_mediation_coord( agent: &ArcAgent, - coord_msg: MediatorCoordMsgEnum, + coord_msg: CoordinateMediation, auth_pubkey: &str, -) -> Result { - if let MediatorCoordMsgEnum::MediateRequest = coord_msg { +) -> Result { + if let CoordinateMediation::MediateRequest(_mediate_request) = coord_msg { let service = agent .get_service_ref() .ok_or("Mediation agent must have service defined.")?; @@ -21,10 +24,16 @@ pub async fn handle_mediation_coord( .expect("Service must have recipient key") .to_owned(), ); - let coord_response = MediatorCoordMsgEnum::MediateGrant(MediateGrantData { + let mediate_grant_content = MediateGrantContent { endpoint: service.service_endpoint.to_string(), routing_keys, - }); + }; + let mediate_grant = MediateGrant::builder() + .content(mediate_grant_content) + .decorators(MediateGrantDecorators::default()) + .id(Uuid::new_v4().to_string()) + .build(); + let coord_response = CoordinateMediation::MediateGrant(mediate_grant); return Ok(coord_response); }; let Json(coord_response) = mediation::routes::coordination::handle_coord_authenticated( diff --git a/agents/rust/mediator/src/didcomm_handlers/mod.rs b/agents/rust/mediator/src/didcomm_handlers/mod.rs index f0e60f0296..6e6092e7ce 100644 --- a/agents/rust/mediator/src/didcomm_handlers/mod.rs +++ b/agents/rust/mediator/src/didcomm_handlers/mod.rs @@ -21,7 +21,6 @@ use pickup::handle_pickup_protocol; #[serde(untagged)] enum GeneralAriesMessage { AriesVCXSupported(AriesMessage), - XumCoord(mediation::didcomm_types::mediator_coord_structs::MediatorCoordMsgEnum), } pub fn unhandled_aries_message(message: impl Debug) -> String { format!("Don't know how to handle this message type {:#?}", message) @@ -46,34 +45,32 @@ pub async fn handle_aries( handle_routing_forward(agent.clone(), forward).await?; return Ok(Json(json!({}))); } else { - // Auth known VerKey then process account related messages + // Authenticated flow: Auth known VerKey then process account related messages let (account_name, auth_pubkey, our_signing_key, their_diddoc) = agent.auth_and_get_details(&unpacked.sender_verkey).await?; log::info!("Processing message for {:?}", account_name); - match aries_message { + let aries_response = match aries_message { GeneralAriesMessage::AriesVCXSupported(AriesMessage::Pickup(pickup_message)) => { let pickup_response = handle_pickup_protocol(&agent, pickup_message, &auth_pubkey).await?; - let aries_response = AriesMessage::Pickup(pickup_response); - let aries_response_bytes = - serde_json::to_vec(&aries_response).map_err(string_from_std_error)?; - agent - .pack_didcomm(&aries_response_bytes, &our_signing_key, &their_diddoc) - .await? + AriesMessage::Pickup(pickup_response) } - GeneralAriesMessage::AriesVCXSupported(aries_message) => { - Err(unhandled_aries_message(aries_message))? - } - GeneralAriesMessage::XumCoord(coord_message) => { + GeneralAriesMessage::AriesVCXSupported(AriesMessage::CoordinateMediation( + coord_message, + )) => { let coord_response = handle_mediation_coord(&agent, coord_message, &auth_pubkey).await?; - let aries_response = - serde_json::to_vec(&coord_response).map_err(string_from_std_error)?; - agent - .pack_didcomm(&aries_response, &our_signing_key, &their_diddoc) - .await? + AriesMessage::CoordinateMediation(coord_response) + } + GeneralAriesMessage::AriesVCXSupported(aries_message) => { + Err(unhandled_aries_message(aries_message))? } - } + }; + let aries_response_bytes = + serde_json::to_vec(&aries_response).map_err(string_from_std_error)?; + agent + .pack_didcomm(&aries_response_bytes, &our_signing_key, &their_diddoc) + .await? }; let EncryptionEnvelope(packed_message_bytes) = packed_response; let packed_json = serde_json::from_slice(&packed_message_bytes[..]).unwrap(); diff --git a/messages/src/msg_fields/protocols/coordinate_mediation/keylist.rs b/messages/src/msg_fields/protocols/coordinate_mediation/keylist.rs index b3974327ff..3a6eb2f347 100644 --- a/messages/src/msg_fields/protocols/coordinate_mediation/keylist.rs +++ b/messages/src/msg_fields/protocols/coordinate_mediation/keylist.rs @@ -11,7 +11,7 @@ pub struct KeylistContent { pub keys: Vec, #[builder(default, setter(strip_option))] #[serde(skip_serializing_if = "Option::is_none")] - pagination: Option, + pub pagination: Option, } #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialEq, TypedBuilder)]