diff --git a/libvcx/src/api/credential.rs b/libvcx/src/api/credential.rs index 1b80ccb098..505db40e09 100644 --- a/libvcx/src/api/credential.rs +++ b/libvcx/src/api/credential.rs @@ -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); diff --git a/libvcx/src/api/proof.rs b/libvcx/src/api/proof.rs index 95d5929ac9..3e5d61a6ce 100644 --- a/libvcx/src/api/proof.rs +++ b/libvcx/src/api/proof.rs @@ -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] diff --git a/libvcx/src/api/utils.rs b/libvcx/src/api/utils.rs index 6241a598a1..f62af87492 100644 --- a/libvcx/src/api/utils.rs +++ b/libvcx/src/api/utils.rs @@ -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, diff --git a/libvcx/src/api/wallet.rs b/libvcx/src/api/wallet.rs index dbd4beee30..b0db52a160 100644 --- a/libvcx/src/api/wallet.rs +++ b/libvcx/src/api/wallet.rs @@ -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(); diff --git a/libvcx/src/aries/handlers/connection/agent_info.rs b/libvcx/src/aries/handlers/connection/agent_info.rs index 2791b287d7..ee0f4cdf52 100644 --- a/libvcx/src/aries/handlers/connection/agent_info.rs +++ b/libvcx/src/aries/handlers/connection/agent_info.rs @@ -35,12 +35,12 @@ impl Default for AgentInfo { fn _log_messages_optionally(a2a_messages: &HashMap) { #[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 { @@ -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, expected_sender_vk: &str) -> VcxResult> { let mut a2a_messages: HashMap = 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) -> VcxResult> { let mut a2a_messages: HashMap = 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 { - trace!("Agent::decode_message >>> message = {:?}", json!(&message).to_string()); + fn decrypt_decode_message(&self, message: &Message, expected_sender_vk: &str) -> VcxResult { EncryptionEnvelope::auth_unpack(message.payload()?, &expected_sender_vk) } - fn decode_message_noauth(&self, message: &Message) -> VcxResult { - trace!("Agent::decode_message_noatuh >>> message = {:?}", json!(&message).to_string()); + fn decrypt_decode_message_noauth(&self, message: &Message) -> VcxResult { EncryptionEnvelope::anon_unpack(message.payload()?) } diff --git a/libvcx/src/aries/handlers/connection/inviter/state_machine.rs b/libvcx/src/aries/handlers/connection/inviter/state_machine.rs index 7a5c7e9b02..d0a5c3bc22 100644 --- a/libvcx/src/aries/handlers/connection/inviter/state_machine.rs +++ b/libvcx/src/aries/handlers/connection/inviter/state_machine.rs @@ -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; @@ -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 { @@ -120,12 +120,12 @@ impl SmConnectionInviter { } pub fn get_bootstrap_agent_messages(&self) -> VcxResult, 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) @@ -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; @@ -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::*; diff --git a/libvcx/src/aries/messages/connection/response.rs b/libvcx/src/aries/messages/connection/response.rs index 97bbe16c3c..bce87ab105 100644 --- a/libvcx/src/aries/messages/connection/response.rs +++ b/libvcx/src/aries/messages/connection/response.rs @@ -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") @@ -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()); } } \ No newline at end of file diff --git a/libvcx/src/aries/mod.rs b/libvcx/src/aries/mod.rs index efca98f4cf..7e8bc536c9 100644 --- a/libvcx/src/aries/mod.rs +++ b/libvcx/src/aries/mod.rs @@ -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, @@ -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") } @@ -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(); diff --git a/libvcx/src/aries/utils/encryption_envelope.rs b/libvcx/src/aries/utils/encryption_envelope.rs index e4e3af447f..a8572be18e 100644 --- a/libvcx/src/aries/utils/encryption_envelope.rs +++ b/libvcx/src/aries/utils/encryption_envelope.rs @@ -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()) } @@ -93,7 +94,7 @@ impl EncryptionEnvelope { } pub fn auth_unpack(payload: Vec, expected_vk: &str) -> VcxResult { - 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"); @@ -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"); @@ -140,11 +144,12 @@ 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); } @@ -152,11 +157,12 @@ pub mod tests { #[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()); } @@ -164,7 +170,9 @@ pub mod tests { #[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(); @@ -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(); @@ -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()); + } } diff --git a/libvcx/src/credential.rs b/libvcx/src/credential.rs index 37994be7b5..c2eb090491 100644 --- a/libvcx/src/credential.rs +++ b/libvcx/src/credential.rs @@ -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(); } diff --git a/libvcx/src/messages/mod.rs b/libvcx/src/messages/mod.rs index 697f2fe608..6fe0527650 100644 --- a/libvcx/src/messages/mod.rs +++ b/libvcx/src/messages/mod.rs @@ -771,7 +771,7 @@ pub mod tests { let vec: Vec = 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] @@ -781,7 +781,7 @@ pub mod tests { let vec: Vec = 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); } } diff --git a/libvcx/src/utils/libindy/mod.rs b/libvcx/src/utils/libindy/mod.rs index 684b063d40..42b696d7aa 100644 --- a/libvcx/src/utils/libindy/mod.rs +++ b/libvcx/src/utils/libindy/mod.rs @@ -66,32 +66,39 @@ pub mod tests { pub const TRUSTEE_SEED: &'static str = "000000000000000000000000Trustee1"; pub const WALLET_CREDENTIALS: &'static str = r#"{"key":"8dvfYSt5d1taSd6yJdpjq4emkwsPDDLYxkNFysFD2cZY", "key_derivation_method":"RAW"}"#; - pub struct Setup { + pub struct WalletSetup { pub name: String, pub wallet_config: String, - pub wallet_handle: indy::WalletHandle, - pub key: String, + pub wh: indy::WalletHandle, } - pub fn key() -> Setup { + pub fn setup_wallet() -> WalletSetup { let name: String = ::rand::thread_rng().gen_ascii_chars().take(25).collect::(); let wallet_config = json!({"id": name}).to_string(); - let key_config = json!({"seed": TRUSTEE_SEED}).to_string(); indy::wallet::create_wallet(&wallet_config, WALLET_CREDENTIALS).wait().unwrap(); let wallet_handle = indy::wallet::open_wallet(&wallet_config, WALLET_CREDENTIALS).wait().unwrap(); - let key = indy::crypto::create_key(wallet_handle, Some(&key_config)).wait().unwrap(); - wallet::set_wallet_handle(wallet_handle); - Setup { name, wallet_config, wallet_handle, key } + WalletSetup { name, wallet_config, wh: wallet_handle } + } + + pub fn create_trustee_key(wallet_handle: indy::WalletHandle) -> String { + let key_config = json!({"seed": TRUSTEE_SEED}).to_string(); + indy::crypto::create_key(wallet_handle, Some(&key_config)).wait().unwrap() + } + + pub fn create_key(wallet_handle: indy::WalletHandle) -> String { + let seed = ::rand::thread_rng().gen_ascii_chars().take(32).collect::(); + let key_config = json!({"seed": seed}).to_string(); + indy::crypto::create_key(wallet_handle, Some(&key_config)).wait().unwrap() } - impl Drop for Setup { + impl Drop for WalletSetup { fn drop(&mut self) { - if self.wallet_handle.0 != 0 { - indy::wallet::close_wallet(self.wallet_handle).wait().unwrap(); + if self.wh.0 != 0 { + indy::wallet::close_wallet(self.wh).wait().unwrap(); indy::wallet::delete_wallet(&self.wallet_config, WALLET_CREDENTIALS).wait().unwrap(); } } diff --git a/libvcx/src/utils/libindy/payments.rs b/libvcx/src/utils/libindy/payments.rs index 041d1432b0..eb15830a2e 100644 --- a/libvcx/src/utils/libindy/payments.rs +++ b/libvcx/src/utils/libindy/payments.rs @@ -497,7 +497,7 @@ pub fn mint_tokens_and_set_fees(number_of_addresses: Option, tokens_per_add match ::utils::libindy::ledger::libindy_submit_request(&sign4) { Ok(_) => (), - Err(x) => println!("failure minting tokens: {}", x), + Err(x) => error!("failure minting tokens: {}", x), }; } @@ -947,7 +947,6 @@ pub mod tests { let _setup = SetupLibraryWalletPoolZeroFees::init(); let fees = get_ledger_fees().unwrap(); - println!("fees: {}", fees); ::utils::libindy::anoncreds::tests::create_and_write_test_schema(::utils::constants::DEFAULT_SCHEMA_ATTRS); } @@ -958,7 +957,6 @@ pub mod tests { mint_tokens_and_set_fees(Some(0), Some(0), Some("{\"101\":0, \"102\":0}".to_string()), None).unwrap(); let fees = get_ledger_fees().unwrap(); - println!("fees: {}", fees); ::utils::libindy::anoncreds::tests::create_and_write_test_schema(::utils::constants::DEFAULT_SCHEMA_ATTRS); }