Skip to content

Commit

Permalink
Use coordinate_mediation messages from aries-vcx
Browse files Browse the repository at this point in the history
Signed-off-by: Naian <[email protected]>
  • Loading branch information
nain-F49FF806 committed Nov 9, 2023
1 parent 9a12b46 commit a7c98b1
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 83 deletions.
9 changes: 5 additions & 4 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions agents/rust/mediator/mediation/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
1 change: 0 additions & 1 deletion agents/rust/mediator/mediation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
9 changes: 3 additions & 6 deletions agents/rust/mediator/mediation/src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};

Expand All @@ -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))
Expand Down
97 changes: 65 additions & 32 deletions agents/rust/mediator/mediation/src/routes/coordination.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: MediatorPersistence>(
State(storage): State<Arc<T>>,
Json(message): Json<MediatorCoordMsgEnum>,
Json(message): Json<CoordinateMediation>,
auth_pubkey: &str,
) -> Json<MediatorCoordMsgEnum> {
) -> Json<CoordinateMediation> {
match message {
MediateRequest => {
CoordinateMediation::MediateRequest(_mediate_request) => {
panic!(
"Use handle_mediate_request directly. This handler is for preregistered clients."
);
Expand All @@ -32,63 +39,84 @@ pub async fn handle_coord_authenticated<T: MediatorPersistence>(
// )
// .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<MediatorCoordMsgEnum> {
Json(MediatorCoordMsgEnum::XumErrorMsg {
error: "Unimplemented".to_owned(),
})
pub async fn handle_unimplemented() -> Json<CoordinateMediation> {
todo!("This error should ideally be handled on outer layer. Panicking for now.")
}

pub async fn handle_mediate_request<T: MediatorPersistence>(
storage: Arc<T>,
auth_pubkey: &str,
did_doc: &str,
our_signing_key: &str,
grant_data: MediateGrantData,
) -> Json<MediatorCoordMsgEnum> {
grant_content: MediateGrantContent,
) -> Json<CoordinateMediation> {
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<T: MediatorPersistence>(
storage: Arc<T>,
//todo: use the limits mentioned in the KeylistQueryData to modify response
_keylist_query_data: KeylistQueryData,
_keylist_query_data: KeylistQueryContent,
auth_pubkey: &str,
) -> Json<MediatorCoordMsgEnum> {
) -> Json<CoordinateMediation> {
let keylist_items: Vec<KeylistItem> = 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<T: MediatorPersistence>(
storage: Arc<T>,
keylist_update_data: KeylistUpdateRequestData,
keylist_update_data: KeylistUpdateContent,
auth_pubkey: &str,
) -> Json<MediatorCoordMsgEnum> {
) -> Json<CoordinateMediation> {
let updates: Vec<KeylistUpdateItem> = keylist_update_data.updates;
let mut updated: Vec<KeylistUpdateItem> = Vec::new();
let mut updated: Vec<KeylistUpdateResponseItem> = Vec::new();
for update_item in updates.into_iter() {
let result = match &update_item.action {
KeylistUpdateItemAction::Add => {
Expand All @@ -106,13 +134,18 @@ pub async fn handle_keylist_update<T: MediatorPersistence>(
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,
))
}
44 changes: 37 additions & 7 deletions agents/rust/mediator/mediation/src/routes/forward.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(
State(storage): State<Arc<T>>,
Json(forward_msg): Json<ForwardMsg>,
) -> Json<ForwardMsg>
Json(forward_msg): Json<Forward>,
) -> Json<Ack>
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)
}
12 changes: 5 additions & 7 deletions agents/rust/mediator/src/didcomm_handlers/forward.rs
Original file line number Diff line number Diff line change
@@ -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<impl BaseWallet + 'static, impl MediatorPersistence>,
forward: Forward,
) -> Result<(), String> {
) -> Result<Ack, String> {
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)
}
21 changes: 15 additions & 6 deletions agents/rust/mediator/src/didcomm_handlers/mediator_coord.rs
Original file line number Diff line number Diff line change
@@ -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<impl BaseWallet + 'static, impl MediatorPersistence>,
coord_msg: MediatorCoordMsgEnum,
coord_msg: CoordinateMediation,
auth_pubkey: &str,
) -> Result<MediatorCoordMsgEnum, String> {
if let MediatorCoordMsgEnum::MediateRequest = coord_msg {
) -> Result<CoordinateMediation, String> {
if let CoordinateMediation::MediateRequest(_mediate_request) = coord_msg {
let service = agent
.get_service_ref()
.ok_or("Mediation agent must have service defined.")?;
Expand All @@ -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(
Expand Down
Loading

0 comments on commit a7c98b1

Please sign in to comment.