Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / third_party / betocore / np_adv / tests / examples_v1.rs
examples_v1.rs256 lines · 9.2 KiBRaw
| 1 | // Copyright 2023 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | #![allow( |
| 16 | clippy::unwrap_used, |
| 17 | clippy::expect_used, |
| 18 | clippy::indexing_slicing, |
| 19 | clippy::panic, |
| 20 | missing_docs |
| 21 | )] |
| 22 | |
| 23 | use crypto_provider::{CryptoProvider, CryptoRng}; |
| 24 | use crypto_provider_default::CryptoProviderImpl; |
| 25 | use np_adv::credential::matched::{ |
| 26 | EmptyMatchedCredential, MetadataMatchedCredential, WithMatchedCredential, |
| 27 | }; |
| 28 | use np_adv::extended::deserialize::{Section, V1DeserializedSection}; |
| 29 | use np_adv::extended::{V1IdentityToken, V1_ENCODING_UNENCRYPTED}; |
| 30 | use np_adv::{ |
| 31 | credential::{ |
| 32 | book::CredentialBookBuilder, |
| 33 | v1::{V1BroadcastCredential, V1DiscoveryCredential, V1}, |
| 34 | MatchableCredential, |
| 35 | }, |
| 36 | deserialization_arena, deserialize_advertisement, |
| 37 | extended::{ |
| 38 | data_elements::TxPowerDataElement, |
| 39 | de_type::HasDEType, |
| 40 | deserialize::VerificationMode, |
| 41 | serialize::{AdvBuilder, MicEncryptedSectionEncoder, UnencryptedSectionEncoder}, |
| 42 | NP_V1_ADV_MAX_SECTION_COUNT, |
| 43 | }, |
| 44 | shared_data::TxPower, |
| 45 | AdvDeserializationError, AdvDeserializationErrorDetailsHazmat, |
| 46 | }; |
| 47 | use np_hkdf::DerivedSectionKeys; |
| 48 | use serde::{Deserialize, Serialize}; |
| 49 | |
| 50 | #[test] |
| 51 | fn v1_deser_plaintext() { |
| 52 | let mut adv_builder = AdvBuilder::new(); |
| 53 | let mut section_builder = adv_builder.section_builder(UnencryptedSectionEncoder).unwrap(); |
| 54 | section_builder.add_de(&TxPowerDataElement::from(TxPower::try_from(6).unwrap())).unwrap(); |
| 55 | section_builder.add_to_advertisement::<CryptoProviderImpl>(); |
| 56 | let adv = adv_builder.into_advertisement(); |
| 57 | |
| 58 | let cred_book = CredentialBookBuilder::<EmptyMatchedCredential>::build_cached_slice_book::< |
| 59 | 0, |
| 60 | 0, |
| 61 | CryptoProviderImpl, |
| 62 | >(&[], &[]); |
| 63 | |
| 64 | let arena = deserialization_arena!(); |
| 65 | let contents = |
| 66 | deserialize_advertisement::<_, CryptoProviderImpl>(arena, adv.as_slice(), &cred_book) |
| 67 | .expect("Should be a valid advertisemement") |
| 68 | .into_v1() |
| 69 | .expect("Should be V1"); |
| 70 | |
| 71 | assert_eq!(0, contents.invalid_sections_count()); |
| 72 | |
| 73 | let sections = contents.sections().collect::<Vec<_>>(); |
| 74 | |
| 75 | assert_eq!(1, sections.len()); |
| 76 | |
| 77 | let section = match §ions[0] { |
| 78 | V1DeserializedSection::Plaintext(s) => s, |
| 79 | _ => panic!("this is a plaintext adv"), |
| 80 | }; |
| 81 | let data_elements = section.iter_data_elements().collect::<Result<Vec<_>, _>>().unwrap(); |
| 82 | assert_eq!(1, data_elements.len()); |
| 83 | |
| 84 | let de = &data_elements[0]; |
| 85 | assert_eq!(None, de.salt()); |
| 86 | assert_eq!(TxPowerDataElement::DE_TYPE, de.de_type()); |
| 87 | assert_eq!(&[6], de.contents()); |
| 88 | } |
| 89 | |
| 90 | /// Sample contents for some encrypted identity metadata |
| 91 | /// which consists of a UUID together with a display name |
| 92 | /// and a general location. |
| 93 | #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] |
| 94 | struct IdentityMetadata { |
| 95 | uuid: String, |
| 96 | display_name: String, |
| 97 | location: String, |
| 98 | } |
| 99 | |
| 100 | impl IdentityMetadata { |
| 101 | /// Serialize this identity metadata to a json byte-string. |
| 102 | fn to_bytes(&self) -> Vec<u8> { |
| 103 | serde_json::to_vec(self).expect("Identity metadata serialization is infallible") |
| 104 | } |
| 105 | /// Attempt to deserialize identity metadata from a json byte-string. |
| 106 | fn try_from_bytes(serialized: &[u8]) -> Option<Self> { |
| 107 | serde_json::from_slice(serialized).ok() |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | #[test] |
| 112 | fn v1_deser_ciphertext() { |
| 113 | // identity material |
| 114 | let mut rng = <CryptoProviderImpl as CryptoProvider>::CryptoRng::new(); |
| 115 | let token_array: [u8; 16] = rng.gen(); |
| 116 | let identity_token = V1IdentityToken::from(token_array); |
| 117 | let key_seed = rng.gen(); |
| 118 | let hkdf = np_hkdf::NpKeySeedHkdf::<CryptoProviderImpl>::new(&key_seed); |
| 119 | |
| 120 | let broadcast_cred = V1BroadcastCredential::new(key_seed, identity_token); |
| 121 | |
| 122 | // Serialize and encrypt some identity metadata (sender-side) |
| 123 | let sender_metadata = IdentityMetadata { |
| 124 | uuid: "378845e1-2616-420d-86f5-674177a7504d".to_string(), |
| 125 | display_name: "Alice".to_string(), |
| 126 | location: "Wonderland".to_string(), |
| 127 | }; |
| 128 | let sender_metadata_bytes = sender_metadata.to_bytes(); |
| 129 | let encrypted_sender_metadata = MetadataMatchedCredential::<Vec<u8>>::encrypt_from_plaintext::< |
| 130 | V1, |
| 131 | CryptoProviderImpl, |
| 132 | >(&hkdf, identity_token, &sender_metadata_bytes); |
| 133 | |
| 134 | // prepare advertisement |
| 135 | let mut adv_builder = AdvBuilder::new(); |
| 136 | |
| 137 | let mut section_builder = adv_builder |
| 138 | .section_builder(MicEncryptedSectionEncoder::new_random_salt::<CryptoProviderImpl>( |
| 139 | &mut rng, |
| 140 | &broadcast_cred, |
| 141 | )) |
| 142 | .unwrap(); |
| 143 | section_builder.add_de(&TxPowerDataElement::from(TxPower::try_from(7).unwrap())).unwrap(); |
| 144 | section_builder.add_to_advertisement::<CryptoProviderImpl>(); |
| 145 | let adv = adv_builder.into_advertisement(); |
| 146 | println!("adv: {adv:?}"); |
| 147 | |
| 148 | let discovery_credential = V1DiscoveryCredential::new( |
| 149 | key_seed, |
| 150 | hkdf.v1_mic_short_salt_keys() |
| 151 | .identity_token_hmac_key() |
| 152 | .calculate_hmac::<CryptoProviderImpl>(identity_token.bytes()), |
| 153 | hkdf.v1_mic_extended_salt_keys() |
| 154 | .identity_token_hmac_key() |
| 155 | .calculate_hmac::<CryptoProviderImpl>(identity_token.bytes()), |
| 156 | ); |
| 157 | |
| 158 | let credentials: [MatchableCredential<V1, MetadataMatchedCredential<_>>; 1] = |
| 159 | [MatchableCredential { |
| 160 | discovery_credential, |
| 161 | match_data: encrypted_sender_metadata.clone(), |
| 162 | }]; |
| 163 | let cred_book = CredentialBookBuilder::build_cached_slice_book::<0, 0, CryptoProviderImpl>( |
| 164 | &[], |
| 165 | &credentials, |
| 166 | ); |
| 167 | let arena = deserialization_arena!(); |
| 168 | let contents = |
| 169 | deserialize_advertisement::<_, CryptoProviderImpl>(arena, adv.as_slice(), &cred_book) |
| 170 | .expect("Should be a valid advertisement") |
| 171 | .into_v1() |
| 172 | .expect("Should be V1"); |
| 173 | |
| 174 | assert_eq!(0, contents.invalid_sections_count(), "{contents:?}"); |
| 175 | |
| 176 | let sections = contents.sections().collect::<Vec<_>>(); |
| 177 | assert_eq!(1, sections.len()); |
| 178 | |
| 179 | let matched: &WithMatchedCredential<_, _> = match §ions[0] { |
| 180 | V1DeserializedSection::Decrypted(d) => d, |
| 181 | _ => panic!("this is a ciphertext adv"), |
| 182 | }; |
| 183 | |
| 184 | let decrypted_metadata_bytes = matched |
| 185 | .decrypt_metadata::<CryptoProviderImpl>() |
| 186 | .expect("Sender metadata should be decryptable"); |
| 187 | let decrypted_metadata = IdentityMetadata::try_from_bytes(&decrypted_metadata_bytes) |
| 188 | .expect("Sender metadata should be deserializable"); |
| 189 | assert_eq!(sender_metadata, decrypted_metadata); |
| 190 | |
| 191 | let section = matched.contents(); |
| 192 | |
| 193 | assert_eq!(VerificationMode::Mic, section.verification_mode()); |
| 194 | assert_eq!(&identity_token, section.identity_token()); |
| 195 | |
| 196 | let data_elements = section.iter_data_elements().collect::<Result<Vec<_>, _>>().unwrap(); |
| 197 | assert_eq!(1, data_elements.len()); |
| 198 | |
| 199 | let de = &data_elements[0]; |
| 200 | assert_eq!(TxPowerDataElement::DE_TYPE, de.de_type()); |
| 201 | assert_eq!(&[7], de.contents()); |
| 202 | } |
| 203 | |
| 204 | #[test] |
| 205 | fn v1_deser_no_section() { |
| 206 | // TODO: we shouldn't allow this invalid advertisement to be serialized |
| 207 | let adv_builder = AdvBuilder::new(); |
| 208 | let adv = adv_builder.into_advertisement(); |
| 209 | let cred_book = CredentialBookBuilder::<EmptyMatchedCredential>::build_cached_slice_book::< |
| 210 | 0, |
| 211 | 0, |
| 212 | CryptoProviderImpl, |
| 213 | >(&[], &[]); |
| 214 | let arena = deserialization_arena!(); |
| 215 | let v1_deserialize_error = |
| 216 | deserialize_advertisement::<_, CryptoProviderImpl>(arena, adv.as_slice(), &cred_book) |
| 217 | .expect_err(" Expected an error"); |
| 218 | assert_eq!( |
| 219 | v1_deserialize_error, |
| 220 | AdvDeserializationError::ParseError { |
| 221 | details_hazmat: AdvDeserializationErrorDetailsHazmat::AdvertisementDeserializeError |
| 222 | } |
| 223 | ); |
| 224 | } |
| 225 | |
| 226 | #[test] |
| 227 | fn v1_deser_plaintext_over_max_sections() { |
| 228 | let mut adv_builder = AdvBuilder::new(); |
| 229 | for _ in 0..NP_V1_ADV_MAX_SECTION_COUNT { |
| 230 | let mut section_builder = adv_builder.section_builder(UnencryptedSectionEncoder).unwrap(); |
| 231 | section_builder.add_de(&TxPowerDataElement::from(TxPower::try_from(7).unwrap())).unwrap(); |
| 232 | section_builder.add_to_advertisement::<CryptoProviderImpl>(); |
| 233 | } |
| 234 | let mut adv = adv_builder.into_advertisement().as_slice().to_vec(); |
| 235 | // Push an extra section |
| 236 | adv.extend_from_slice( |
| 237 | [ |
| 238 | 0x01, // Section header |
| 239 | V1_ENCODING_UNENCRYPTED.byte_value(), |
| 240 | ] |
| 241 | .as_slice(), |
| 242 | ); |
| 243 | let cred_book = CredentialBookBuilder::<EmptyMatchedCredential>::build_cached_slice_book::< |
| 244 | 0, |
| 245 | 0, |
| 246 | CryptoProviderImpl, |
| 247 | >(&[], &[]); |
| 248 | let arena = deserialization_arena!(); |
| 249 | assert_eq!( |
| 250 | deserialize_advertisement::<_, CryptoProviderImpl>(arena, adv.as_slice(), &cred_book) |
| 251 | .unwrap_err(), |
| 252 | AdvDeserializationError::ParseError { |
| 253 | details_hazmat: AdvDeserializationErrorDetailsHazmat::AdvertisementDeserializeError |
| 254 | } |
| 255 | ); |
| 256 | } |