Skip to content

Commit

Permalink
Add auth_unpack tests, remove printlncleanup
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 Oct 19, 2020
1 parent 1ef12f9 commit abcf125
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 60 deletions.
2 changes: 1 addition & 1 deletion libvcx/src/api/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -873,7 +873,7 @@ mod tests {
handle,
Some(cb.get_callback())), error::SUCCESS.code_num);
let credential_json = cb.receive(TimeoutUtils::some_short()).unwrap().unwrap();
println!("Serialized credential: ${:?}", credential_json);
debug!("Serialized credential: {:?}", credential_json);

let object: Value = serde_json::from_str(&credential_json).unwrap();
assert_eq!(object["version"], V3_OBJECT_SERIALIZE_VERSION);
Expand Down
2 changes: 1 addition & 1 deletion libvcx/src/api/proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@ mod tests {
Some(cb.get_callback())),
error::SUCCESS.code_num);
let _ser = cb.receive(TimeoutUtils::some_medium()).unwrap();
println!("Serialize proof: {:?}", _ser);
info!("Serialized proof: {:?}", _ser);
}

#[test]
Expand Down
2 changes: 0 additions & 2 deletions libvcx/src/api/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,6 @@ pub extern fn vcx_download_agent_messages(command_handle: u32,
/// #Returns
/// Error code as a u32
#[no_mangle]
#[deprecated(since = "0.12.0", note = "This is dangerous because downloaded messages are not \
authenticated and a message appearing to be received from certain connection might been spoofed.")]
pub extern fn vcx_messages_download(command_handle: CommandHandle,
message_status: *const c_char,
uids: *const c_char,
Expand Down
2 changes: 1 addition & 1 deletion libvcx/src/api/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1126,7 +1126,7 @@ pub mod tests {
let _setup = SetupLibraryWalletPoolZeroFees::init();

let recipient = CStringUtils::string_to_cstring(build_test_address("2ZrAm5Jc3sP4NAXMQbaWzDxEa12xxJW3VgWjbbPtMPQCoznJyS"));
println!("sending payment to {:?}", recipient);
debug!("sending payment to {:?}", recipient);
let balance = ::utils::libindy::payments::get_wallet_token_info().unwrap().get_balance();
let tokens = 5;
let cb = return_types_u32::Return_U32_STR::new().unwrap();
Expand Down
26 changes: 12 additions & 14 deletions libvcx/src/aries/handlers/connection/agent_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ impl Default for AgentInfo {

fn _log_messages_optionally(a2a_messages: &HashMap<String, A2AMessage>) {
#[cfg(feature = "warnlog_fetched_messages")]
{
for message in a2a_messages.values() {
let serialized_msg = serde_json::to_string_pretty(message).unwrap_or_else(|_err| String::from("Failed to serialize A2AMessage."));
warn!("Fetched decrypted connection messages:\n{}", serialized_msg);
}
{
for message in a2a_messages.values() {
let serialized_msg = serde_json::to_string_pretty(message).unwrap_or_else(|_err| String::from("Failed to serialize A2AMessage."));
warn!("Fetched decrypted connection messages:\n{}", serialized_msg);
}
}
}

impl AgentInfo {
Expand Down Expand Up @@ -120,33 +120,31 @@ impl AgentInfo {
let message = messages
.pop()
.ok_or(VcxError::from_msg(VcxErrorKind::InvalidMessages, format!("Message not found for id: {:?}", msg_id)))?;
let message = self.decode_message(&message, &expected_sender_vk)?;
let message = self.decrypt_decode_message(&message, &expected_sender_vk)?;
Ok(message)
}

fn decrypt_decode_messages(&self, messages: &Vec<Message>, expected_sender_vk: &str) -> VcxResult<HashMap<String, A2AMessage>> {
let mut a2a_messages: HashMap<String, A2AMessage> = HashMap::new();
for message in messages {
a2a_messages.insert(message.uid.clone(), self.decode_message(&message, expected_sender_vk)?);
a2a_messages.insert(message.uid.clone(), self.decrypt_decode_message(&message, expected_sender_vk)?);
}
return Ok(a2a_messages)
return Ok(a2a_messages);
}

fn decrypt_decode_messages_noauth(&self, messages: &Vec<Message>) -> VcxResult<HashMap<String, A2AMessage>> {
let mut a2a_messages: HashMap<String, A2AMessage> = HashMap::new();
for message in messages {
a2a_messages.insert(message.uid.clone(), self.decode_message_noauth(&message)?);
a2a_messages.insert(message.uid.clone(), self.decrypt_decode_message_noauth(&message)?);
}
return Ok(a2a_messages)
return Ok(a2a_messages);
}

fn decode_message(&self, message: &Message, expected_sender_vk: &str) -> VcxResult<A2AMessage> {
trace!("Agent::decode_message >>> message = {:?}", json!(&message).to_string());
fn decrypt_decode_message(&self, message: &Message, expected_sender_vk: &str) -> VcxResult<A2AMessage> {
EncryptionEnvelope::auth_unpack(message.payload()?, &expected_sender_vk)
}

fn decode_message_noauth(&self, message: &Message) -> VcxResult<A2AMessage> {
trace!("Agent::decode_message_noatuh >>> message = {:?}", json!(&message).to_string());
fn decrypt_decode_message_noauth(&self, message: &Message) -> VcxResult<A2AMessage> {
EncryptionEnvelope::anon_unpack(message.payload()?)
}

Expand Down
14 changes: 7 additions & 7 deletions libvcx/src/aries/handlers/connection/inviter/state_machine.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::collections::HashMap;

use api::VcxStateType;
use error::prelude::*;
use aries::handlers::connection::agent_info::AgentInfo;
use aries::handlers::connection::inviter::states::complete::CompleteState;
use aries::handlers::connection::inviter::states::invited::InvitedState;
Expand All @@ -15,6 +14,7 @@ use aries::messages::connection::invite::Invitation;
use aries::messages::connection::problem_report::{ProblemCode, ProblemReport};
use aries::messages::discovery::disclose::ProtocolDescriptor;
use aries::messages::trust_ping::ping::Ping;
use error::prelude::*;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmConnectionInviter {
Expand Down Expand Up @@ -120,12 +120,12 @@ impl SmConnectionInviter {
}

pub fn get_bootstrap_agent_messages(&self) -> VcxResult<Option<(HashMap<String, A2AMessage>, AgentInfo)>> {
let expected_sender_vk = self.remote_vk().ok();
let expected_sender_vk = match self.remote_vk() {
Ok(vk) => vk,
Err(_) => return Ok(None)
};
if let Some(prev_agent_info) = self.prev_agent_info() {
let messages = match expected_sender_vk {
None => prev_agent_info.get_messages_noauth()?,
Some(expected_sender_vk) => prev_agent_info.get_messages(&expected_sender_vk)?
};
let messages = prev_agent_info.get_messages(&expected_sender_vk)?;
return Ok(Some((messages, prev_agent_info.clone())));
}
Ok(None)
Expand Down Expand Up @@ -326,7 +326,6 @@ impl SmConnectionInviter {

#[cfg(test)]
pub mod test {
use utils::devsetup::SetupAriesMocks;
use aries::messages::ack::tests::_ack;
use aries::messages::connection::invite::tests::_invitation;
use aries::messages::connection::problem_report::tests::_problem_report;
Expand All @@ -338,6 +337,7 @@ pub mod test {
use aries::messages::trust_ping::ping_response::tests::_ping_response;
use aries::test::setup::AgencyModeSetup;
use aries::test::source_id;
use utils::devsetup::SetupAriesMocks;

use super::*;

Expand Down
8 changes: 5 additions & 3 deletions libvcx/src/aries/messages/connection/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ pub mod tests {
use aries::messages::connection::did_doc::tests::*;

use super::*;
use utils::libindy::tests::test_setup::create_trustee_key;

fn _did() -> String {
String::from("VsKV7grR1BUE29mG2Fm2kX")
Expand Down Expand Up @@ -214,8 +215,9 @@ pub mod tests {
#[test]
#[cfg(feature = "general_test")]
fn test_response_encode_works() {
let setup = test_setup::key();
let signed_response: SignedResponse = _response().encode(&setup.key).unwrap();
assert_eq!(_response(), signed_response.decode(&setup.key).unwrap());
let setup = test_setup::setup_wallet();
let trustee_key = create_trustee_key(setup.wh);
let signed_response: SignedResponse = _response().encode(&trustee_key).unwrap();
assert_eq!(_response(), signed_response.decode(&trustee_key).unwrap());
}
}
9 changes: 2 additions & 7 deletions libvcx/src/aries/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ pub mod test {
}

fn determine_message_type(a2a_message: A2AMessage) -> PayloadKinds {
println!("determine_message_type >>> a2a_message={:?}", a2a_message);
debug!("determine_message_type >>> a2a_message={:?}", a2a_message);
match a2a_message.clone() {
A2AMessage::PresentationRequest(_) => PayloadKinds::ProofRequest,
A2AMessage::CredentialOffer(offer) => PayloadKinds::CredOffer,
Expand All @@ -142,20 +142,15 @@ pub mod test {
assert_eq!(1, messages.len());
let messages = messages.pop().unwrap();

println!("Going to filter message for type ...");
for message in messages.msgs.into_iter() {
// let decrypted_msg = serde_json::from_str(&message.decrypted_msg.unwrap()).unwrap();
let decrypted_msg = &message.decrypted_msg.unwrap();
println!("Decrypted_msg = {}", decrypted_msg);
let msg_type = str_message_to_payload_type(decrypted_msg).unwrap();
println!("Filtering for {:?}, found {:?}", filter_msg_type, msg_type);
if filter_msg_type == msg_type {
return VcxAgencyMessage {
uid: message.uid,
decrypted_payload: decrypted_msg.clone(),
};
}
// todo: just finished writing this code, needs to be tested
}
panic!("Message not found")
}
Expand Down Expand Up @@ -666,9 +661,9 @@ pub mod test {
}

#[cfg(feature = "pool_tests")]
#[cfg(feature = "to_restore")] // todo: this is the problem alice.download_message("credential-offer");
#[test]
fn aries_demo_download_message_flow() {
SetupEmpty::init();
PaymentPlugin::load();
let _pool = Pool::open();

Expand Down
70 changes: 63 additions & 7 deletions libvcx/src/aries/utils/encryption_envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ impl EncryptionEnvelope {

let receiver_keys = json!(did_doc.recipient_keys()).to_string();

warn!("Encrypting for pairwise; pw_verkey={:?}, receiver_keys={:?}", pw_verkey, receiver_keys);
crypto::pack_message(pw_verkey, &receiver_keys, message.as_bytes())
}

Expand Down Expand Up @@ -93,7 +94,7 @@ impl EncryptionEnvelope {
}

pub fn auth_unpack(payload: Vec<u8>, expected_vk: &str) -> VcxResult<A2AMessage> {
trace!("EncryptionEnvelope::auth_unpack >>> processing payload of {} bytes", payload.len());
trace!("EncryptionEnvelope::auth_unpack >>> processing payload of {} bytes, expected_vk={}", payload.len(), expected_vk);

let message = if AgencyMockDecrypted::has_decrypted_mock_messages() {
trace!("EncryptionEnvelope::auth_unpack >>> returning decrypted mock message");
Expand Down Expand Up @@ -131,6 +132,9 @@ pub mod tests {
use utils::libindy::tests::test_setup;

use super::*;
use utils::devsetup::SetupEmpty;
use utils::libindy::tests::test_setup::create_trustee_key;
use utils::libindy::wallet;

fn _setup() {
::settings::set_config_value(::settings::CONFIG_ENABLE_TEST_MODE, "false");
Expand All @@ -140,31 +144,35 @@ pub mod tests {
#[cfg(feature = "general_test")]
fn test_encryption_envelope_works_for_no_keys() {
_setup();
let setup = test_setup::key();
let setup = test_setup::setup_wallet();
let trustee_key = create_trustee_key(setup.wh);

let message = A2AMessage::Ack(_ack());

let res = EncryptionEnvelope::create(&message, Some(&setup.key), &DidDoc::default());
let res = EncryptionEnvelope::create(&message, Some(&trustee_key), &DidDoc::default());
assert_eq!(res.unwrap_err().kind(), VcxErrorKind::InvalidLibindyParam);
}

#[test]
#[cfg(feature = "general_test")]
fn test_encryption_envelope_works_for_recipient_only() {
_setup();
let setup = test_setup::key();
let setup = test_setup::setup_wallet();
let trustee_key = create_trustee_key(setup.wh);

let message = A2AMessage::Ack(_ack());

let envelope = EncryptionEnvelope::create(&message, Some(&setup.key), &_did_doc_4()).unwrap();
let envelope = EncryptionEnvelope::create(&message, Some(&trustee_key), &_did_doc_4()).unwrap();
assert_eq!(message, EncryptionEnvelope::anon_unpack(envelope.0).unwrap());
}

#[test]
#[cfg(feature = "general_test")]
fn test_encryption_envelope_works_for_routing_keys() {
_setup();
let setup = test_setup::key();
let setup = test_setup::setup_wallet();
let trustee_key = create_trustee_key(setup.wh);

let key_1 = create_key(None).unwrap();
let key_2 = create_key(None).unwrap();

Expand All @@ -174,7 +182,7 @@ pub mod tests {

let ack = A2AMessage::Ack(_ack());

let envelope = EncryptionEnvelope::create(&ack, Some(&setup.key), &did_doc).unwrap();
let envelope = EncryptionEnvelope::create(&ack, Some(&trustee_key), &did_doc).unwrap();

let message_1 = EncryptionEnvelope::anon_unpack(envelope.0).unwrap();

Expand All @@ -198,4 +206,52 @@ pub mod tests {

assert_eq!(ack, EncryptionEnvelope::anon_unpack(message_2).unwrap());
}

#[test]
#[cfg(feature = "general_test")]
fn test_auth_unpack_message_should_succeed_if_sender_key_matches_expectation() {
SetupEmpty::init();
_setup();
let recipient_wallet = test_setup::setup_wallet();
let recipient_key = test_setup::create_key(recipient_wallet.wh);

let sender_wallet = test_setup::setup_wallet();
let sender_key = test_setup::create_key(sender_wallet.wh);

let mut did_doc = DidDoc::default();
did_doc.set_keys(vec![recipient_key], vec![]);

let ack = A2AMessage::Ack(_ack());

wallet::set_wallet_handle(sender_wallet.wh);
let envelope = EncryptionEnvelope::create(&ack, Some(&sender_key), &did_doc).unwrap();

wallet::set_wallet_handle(recipient_wallet.wh);
let message_1 = EncryptionEnvelope::auth_unpack(envelope.0, &sender_key).unwrap();
}

#[test]
#[cfg(feature = "general_test")]
fn test_auth_unpack_message_should_fail_if_sender_key_does_not_match_expectation() {
SetupEmpty::init();
_setup();
let recipient_wallet = test_setup::setup_wallet();
let recipient_key = test_setup::create_key(recipient_wallet.wh);

let sender_wallet = test_setup::setup_wallet();
let sender_key_1 = test_setup::create_key(sender_wallet.wh);
let sender_key_2 = test_setup::create_key(sender_wallet.wh);

let mut did_doc = DidDoc::default();
did_doc.set_keys(vec![recipient_key], vec![]);

let ack = A2AMessage::Ack(_ack());

wallet::set_wallet_handle(sender_wallet.wh);
let envelope = EncryptionEnvelope::create(&ack, Some(&sender_key_2), &did_doc).unwrap();

wallet::set_wallet_handle(recipient_wallet.wh);
let result = EncryptionEnvelope::auth_unpack(envelope.0, &sender_key_1);
assert!(result.is_err());
}
}
2 changes: 1 addition & 1 deletion libvcx/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ pub mod tests {

let offer = get_credential_offer_messages(connection_h).unwrap();
let o: serde_json::Value = serde_json::from_str(&offer).unwrap();
println!("Serialized credential offer: {:?}", &o[0]);
debug!("Serialized credential offer: {:?}", &o[0]);
let _credential_offer: CredentialOffer = serde_json::from_str(&o[0].to_string()).unwrap();
}

Expand Down
4 changes: 2 additions & 2 deletions libvcx/src/messages/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,7 @@ pub mod tests {
let vec: Vec<i8> = vec![-127, -89, 98, 117, 110, 100, 108, 101, 100, -111, -36, 5, -74];

let buf = to_u8(&vec);
println!("new bundle: {:?}", buf);
info!("new bundle: {:?}", buf);
}

#[test]
Expand All @@ -781,7 +781,7 @@ pub mod tests {

let vec: Vec<u8> = vec![129, 167, 98, 117, 110, 100, 108, 101, 100, 145, 220, 19, 13];
let buf = to_i8(&vec);
println!("new bundle: {:?}", buf);
info!("new bundle: {:?}", buf);
}

}
Loading

0 comments on commit abcf125

Please sign in to comment.