Skip to content

Commit

Permalink
Refactor sending Aries messages
Browse files Browse the repository at this point in the history
Signed-off-by: Patrik Stas <patrik.stas@absa.africa>
  • Loading branch information
Patrik-Stas committed Dec 25, 2020
1 parent 8185e49 commit a5ad711
Show file tree
Hide file tree
Showing 12 changed files with 98 additions and 26 deletions.
12 changes: 1 addition & 11 deletions libvcx/src/aries/handlers/connection/agent_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::connection::create_agent_keys;
use crate::error::prelude::*;
use crate::libindy::utils::signus::create_and_store_my_did;
use crate::settings;
use crate::agency_client::httpclient;
use crate::utils::httpclient;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentInfo {
Expand Down Expand Up @@ -149,16 +149,6 @@ impl AgentInfo {
EncryptionEnvelope::anon_unpack(message.payload()?)
}

/**
Sends authenticated message to connection counterparty
*/
pub fn send_message(&self, message: &A2AMessage, did_dod: &DidDoc) -> VcxResult<()> {
trace!("Agent::send_message >>> message: {:?}, did_doc: {:?}", message, did_dod);
let envelope = EncryptionEnvelope::create(&message, Some(&self.pw_vk), &did_dod)?;
httpclient::post_message(&envelope.0, &did_dod.get_endpoint())?;
Ok(())
}

/**
Sends message to one's agency signalling resources related to this connection agent can be deleted.
*/
Expand Down
2 changes: 1 addition & 1 deletion libvcx/src/aries/handlers/connection/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ Get messages received from connection counterparty.
.ok_or(VcxError::from_msg(VcxErrorKind::NotReady, "Cannot send message: Remote Connection information is not set"))?;

warn!("Connection resolved did_doc = {:?}", did_doc);
self.agent_info().send_message(message, &did_doc)
did_doc.send_message(message, &self.agent_info().pw_vk)
}

fn parse_generic_message(message: &str) -> A2AMessage {
Expand Down
5 changes: 3 additions & 2 deletions libvcx/src/aries/handlers/connection/invitee/state_machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,8 @@ impl SmConnectionInvitee {
.set_keys(agent_info.recipient_keys(), agent_info.routing_keys()?);

trace!("invitation {:?}", state.invitation);
agent_info.send_message(&request.to_a2a_message(), &DidDoc::from(state.invitation.clone()))?;
let ddo = DidDoc::from(state.invitation.clone());
ddo.send_message(&request.to_a2a_message(), &agent_info.pw_vk)?;
InviteeState::Requested((state, request).into())
}
DidExchangeMessages::ProblemReportReceived(problem_report) => {
Expand All @@ -239,7 +240,7 @@ impl SmConnectionInvitee {
.set_problem_code(ProblemCode::ResponseProcessingError)
.set_explain(err.to_string())
.set_thread_id(&state.request.id.0);
agent_info.send_message(&problem_report.to_a2a_message(), &state.did_doc).ok();
state.did_doc.send_message(&problem_report.to_a2a_message(), &agent_info.pw_vk).ok();
InviteeState::Null((state, problem_report).into())
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl CompleteState {
.request_response()
.set_comment(comment);

agent_info.send_message(&ping.to_a2a_message(), &self.did_doc).ok();
self.did_doc.send_message(&ping.to_a2a_message(), &agent_info.pw_did).ok();
Ok(())
}

Expand All @@ -72,8 +72,7 @@ impl CompleteState {
Query::create()
.set_query(query)
.set_comment(comment);

agent_info.send_message(&query_.to_a2a_message(), &self.did_doc)
self.did_doc.send_message(&query_.to_a2a_message(), &agent_info.pw_did)
}

fn handle_discovery_query(&self, query: Query, agent_info: &AgentInfo) -> VcxResult<()> {
Expand All @@ -83,6 +82,6 @@ impl CompleteState {
.set_protocols(protocols)
.set_thread_id(query.id.0.clone());

agent_info.send_message(&disclose.to_a2a_message(), &self.did_doc)
self.did_doc.send_message(&disclose.to_a2a_message(), &agent_info.pw_did)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl RequestedState {
.to_a2a_message()
};

agent_info.send_message(&message, &response.connection.did_doc)?;
response.connection.did_doc.send_message(&message, &agent_info.pw_vk)?;

Ok(response)
}
Expand Down
4 changes: 2 additions & 2 deletions libvcx/src/aries/handlers/connection/inviter/state_machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ impl SmConnectionInviter {
.set_explain(err.to_string())
.set_thread_id(&request.id.0);

agent_info.send_message(&problem_report.to_a2a_message(), &request.connection.did_doc).ok(); // IS is possible?
request.connection.did_doc.send_message(&problem_report.to_a2a_message(), &agent_info.pw_vk).ok();
InviterState::Null((state, problem_report).into())
}
}
Expand Down Expand Up @@ -292,7 +292,7 @@ impl SmConnectionInviter {
.request_response()
.set_comment(comment);

agent_info.send_message(&ping.to_a2a_message(), &state.did_doc).ok();
state.did_doc.send_message(&ping.to_a2a_message(), &agent_info.pw_vk).ok();
InviterState::Responded(state)
}
DidExchangeMessages::PingResponseReceived(ping_response) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl CompleteState {
.request_response()
.set_comment(comment);

agent_info.send_message(&ping.to_a2a_message(), &self.did_doc).ok();
self.did_doc.send_message(&ping.to_a2a_message(), &agent_info.pw_vk).ok();
Ok(())
}

Expand All @@ -73,7 +73,7 @@ impl CompleteState {
.set_query(query)
.set_comment(comment);

agent_info.send_message(&query_.to_a2a_message(), &self.did_doc)
self.did_doc.send_message(&query_.to_a2a_message(), &agent_info.pw_vk)
}

fn handle_discovery_query(&self, query: Query, agent_info: &AgentInfo) -> VcxResult<()> {
Expand All @@ -83,6 +83,6 @@ impl CompleteState {
.set_protocols(protocols)
.set_thread_id(query.id.0.clone());

agent_info.send_message(&disclose.to_a2a_message(), &self.did_doc)
self.did_doc.send_message(&disclose.to_a2a_message(), &agent_info.pw_vk)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ impl InvitedState {
.set_thread_id(&request.id.0)
.encode(&prev_agent_info.pw_vk)?;

new_agent_info.send_message(&signed_response.to_a2a_message(), &request.connection.did_doc)?;

request.connection.did_doc.send_message(&signed_response.to_a2a_message(), &new_agent_info.pw_vk)?;

Ok((signed_response, new_agent_info))
}
Expand Down
3 changes: 2 additions & 1 deletion libvcx/src/aries/handlers/connection/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ pub fn handle_ping(ping: &Ping, agent_info: &AgentInfo, did_doc: &DidDoc) -> Vcx
if ping.response_requested {
let ping_response = PingResponse::create().set_thread_id(
&ping.thread.as_ref().and_then(|thread| thread.thid.clone()).unwrap_or(ping.id.0.clone()));
agent_info.send_message(&ping_response.to_a2a_message(), did_doc)?;

did_doc.send_message(&ping_response.to_a2a_message(), &agent_info.pw_vk)?;
}
Ok(())
}
23 changes: 23 additions & 0 deletions libvcx/src/aries/messages/connection/did_doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ use crate::aries::messages::connection::invite::Invitation;
use crate::error::prelude::*;
use url::Url;
use crate::utils::validation::validate_verkey;
use crate::aries::messages::a2a::A2AMessage;
use crate::aries::utils::encryption_envelope::EncryptionEnvelope;
use crate::utils::httpclient;

pub const CONTEXT: &str = "https://w3id.org/did/v1";
pub const KEY_TYPE: &str = "Ed25519VerificationKey2018";
Expand Down Expand Up @@ -273,6 +276,26 @@ impl DidDoc {
let pars: Vec<&str> = DidDoc::_key_parts(key_reference);
pars.get(1).or(pars.get(0)).map(|s| s.to_string()).unwrap_or_default()
}

/**
Sends authenticated message to connection counterparty
*/
pub fn send_message(&self, message: &A2AMessage, sender_verkey: &str) -> VcxResult<()> {
trace!("DidDoc::send_message >>> message: {:?}, did_doc: {:?}", message, &self);
let envelope = EncryptionEnvelope::create(&message, Some(sender_verkey), &self)?;
httpclient::post_message(&envelope.0, &self.get_endpoint())?;
Ok(())
}

/**
Sends anonymous message to connection counterparty
*/
pub fn send_message_anonymously(&self, message: &A2AMessage) -> VcxResult<()> {
trace!("DidDoc::send_message_anonymously >>> message: {:?}, did_doc: {:?}", message, &self);
let envelope = EncryptionEnvelope::create(&message, None, &self)?;
httpclient::post_message(&envelope.0, &self.get_endpoint())?;
Ok(())
}
}

impl Default for Service {
Expand Down
56 changes: 56 additions & 0 deletions libvcx/src/utils/httpclient.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
use std::env;
use std::io::Read;

use reqwest;
use reqwest::header::CONTENT_TYPE;
use crate::error::{VcxError, VcxErrorKind, VcxResult};
use crate::api::VcxStateType::VcxStateExpired;
use crate::utils::timeout::TimeoutUtils;

pub fn post_message(body_content: &Vec<u8>, url: &str) -> VcxResult<Vec<u8>> {
//Setting SSL Certs location. This is needed on android platform. Or openssl will fail to verify the certs
if cfg!(target_os = "android") {
info!("::Android code");
set_ssl_cert_location();
}
let client = reqwest::ClientBuilder::new().timeout(TimeoutUtils::long_timeout()).build()
.or(Err(VcxError::from_msg(VcxErrorKind::PostMessageFailed, "Preparing Post failed")))?;
debug!("Posting encrypted bundle to: \"{}\"", url);

let mut response =
client.post(url)
.body(body_content.to_owned())
.header(CONTENT_TYPE, "application/ssi-agent-wire")
.send()
.map_err(|err| {
error!("error: {}", err);
VcxError::from_msg(VcxErrorKind::PostMessageFailed, format!("Could not connect {:?}", err))
})?;

trace!("Response Header: {:?}", response);
if !response.status().is_success() {
let mut content = String::new();
match response.read_to_string(&mut content) {
Ok(_) => info!("Request failed: {}", content),
Err(_) => info!("could not read response"),
};
return Err(VcxError::from_msg(VcxErrorKind::PostMessageFailed, format!("POST failed with: {}", content)));
}

let mut content = Vec::new();
response.read_to_end(&mut content)
.or(Err(VcxError::from_msg(VcxErrorKind::PostMessageFailed, "could not read response")))?;

Ok(content)
}

fn set_ssl_cert_location() {
let ssl_cert_file = "SSL_CERT_FILE";
env::set_var(ssl_cert_file, env::var("EXTERNAL_STORAGE").unwrap() + "/cacert.pem"); //TODO: CHANGE ME, HARDCODING FOR TESTING ONLY
match env::var(ssl_cert_file) {
Ok(val) => info!("{}:: {:?}", ssl_cert_file, val),
Err(e) => error!("couldn't find var in env {}:: {}. This needs to be set on Android to make https calls.\n See https://github.com/seanmonstar/reqwest/issues/70 for more info",
ssl_cert_file, e),
}
info!("::SSL_CERT_FILE has been set");
}
1 change: 1 addition & 0 deletions libvcx/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub mod plugins;
pub mod logger;
pub mod object_cache;
pub mod validation;
pub mod httpclient;

pub fn get_temp_dir_path(filename: &str) -> PathBuf {
let mut path = env::temp_dir();
Expand Down

0 comments on commit a5ad711

Please sign in to comment.