Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / third_party / betocore / np_adv / tests / examples_v0.rs
examples_v0.rs172 lines · 5.9 KiBRaw
| 1 | // Copyright 2023 Google LLC |
| 2 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | // you may not use this file except in compliance with the License. |
| 4 | // You may obtain a copy of the License at |
| 5 | // |
| 6 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | // |
| 8 | // Unless required by applicable law or agreed to in writing, software |
| 9 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | // See the License for the specific language governing permissions and |
| 12 | // limitations under the License. |
| 13 | |
| 14 | #![allow( |
| 15 | clippy::unwrap_used, |
| 16 | clippy::expect_used, |
| 17 | clippy::indexing_slicing, |
| 18 | clippy::panic, |
| 19 | missing_docs |
| 20 | )] |
| 21 | |
| 22 | use crypto_provider_default::CryptoProviderImpl; |
| 23 | use ldt_np_adv::*; |
| 24 | use np_adv::credential::matched::{ |
| 25 | EmptyMatchedCredential, HasIdentityMatch, MetadataMatchedCredential, |
| 26 | }; |
| 27 | use np_adv::legacy::serialize::{AdvBuilder, LdtEncoder}; |
| 28 | use np_adv::{ |
| 29 | credential::{ |
| 30 | book::CredentialBookBuilder, |
| 31 | v0::{V0BroadcastCredential, V0DiscoveryCredential, V0}, |
| 32 | MatchableCredential, |
| 33 | }, |
| 34 | legacy::{ |
| 35 | data_elements::tx_power::TxPowerDataElement, deserialize::*, V0AdvertisementContents, |
| 36 | }, |
| 37 | shared_data::*, |
| 38 | *, |
| 39 | }; |
| 40 | use serde::{Deserialize, Serialize}; |
| 41 | |
| 42 | #[rustfmt::skip] |
| 43 | #[test] |
| 44 | fn v0_deser_plaintext() { |
| 45 | let cred_book = CredentialBookBuilder::<EmptyMatchedCredential>::build_cached_slice_book::< |
| 46 | 0, |
| 47 | 0, |
| 48 | CryptoProviderImpl, |
| 49 | >(&[], &[]); |
| 50 | let arena = deserialization_arena!(); |
| 51 | let adv = deserialize_advertisement::<_, CryptoProviderImpl>( |
| 52 | arena, |
| 53 | &[ |
| 54 | 0x00, // version header |
| 55 | 0x15, 0x03, // Length 1 Tx Power DE with value 3 |
| 56 | ], |
| 57 | &cred_book, |
| 58 | ) |
| 59 | .expect("Should be a valid advertisement") |
| 60 | .into_v0() |
| 61 | .expect("Should be V0"); |
| 62 | |
| 63 | match adv { |
| 64 | V0AdvertisementContents::Plaintext(p) => { |
| 65 | assert_eq!( |
| 66 | vec![DeserializedDataElement::TxPower(TxPowerDataElement::from( |
| 67 | TxPower::try_from(3).unwrap() |
| 68 | ))], |
| 69 | p.data_elements().collect::<Result<Vec<_>, _>>().unwrap() |
| 70 | ); |
| 71 | } |
| 72 | _ => panic!("this example is plaintext"), |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// Sample contents for some encrypted identity metadata |
| 77 | /// which includes just a name and an e-mail address. |
| 78 | #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] |
| 79 | struct IdentityMetadata { |
| 80 | name: String, |
| 81 | email: String, |
| 82 | } |
| 83 | |
| 84 | impl IdentityMetadata { |
| 85 | /// Serialize this identity metadata to a JSON byte-string. |
| 86 | fn to_bytes(&self) -> Vec<u8> { |
| 87 | serde_json::to_vec(&self).expect("serialization should always succeed") |
| 88 | } |
| 89 | /// Attempt to deserialize identity metadata from a JSON byte-string. |
| 90 | fn try_from_bytes(serialized: &[u8]) -> Option<Self> { |
| 91 | serde_json::from_slice(serialized).ok() |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | #[rustfmt::skip] |
| 96 | #[test] |
| 97 | fn v0_deser_ciphertext() { |
| 98 | // These are kept fixed in this example for reproducibility. |
| 99 | // In practice, these should instead be derived from a cryptographically-secure |
| 100 | // random number generator. |
| 101 | let key_seed = [0x11_u8; 32]; |
| 102 | let identity_token = V0IdentityToken::from([0x33; V0_IDENTITY_TOKEN_LEN]); |
| 103 | |
| 104 | let broadcast_cred = V0BroadcastCredential::new(key_seed, identity_token); |
| 105 | |
| 106 | let hkdf = np_hkdf::NpKeySeedHkdf::<CryptoProviderImpl>::new(&key_seed); |
| 107 | let identity_token_hmac: [u8; 32] = |
| 108 | hkdf.v0_identity_token_hmac_key().calculate_hmac::<CryptoProviderImpl>(&identity_token.bytes()); |
| 109 | |
| 110 | // Serialize and encrypt some identity metadata (sender-side) |
| 111 | let sender_metadata = |
| 112 | IdentityMetadata { name: "Alice".to_string(), email: "[email protected]".to_string() }; |
| 113 | let sender_metadata_bytes = sender_metadata.to_bytes(); |
| 114 | let encrypted_sender_metadata = MetadataMatchedCredential::<Vec<u8>>:: |
| 115 | encrypt_from_plaintext::<V0, CryptoProviderImpl>(&hkdf, |
| 116 | identity_token, |
| 117 | &sender_metadata_bytes); |
| 118 | |
| 119 | // output of building a packet using AdvBuilder |
| 120 | let adv = &[ |
| 121 | 0x04, // version header |
| 122 | 0x22, 0x22, // salt |
| 123 | // ciphertext for metadata key & txpower DE |
| 124 | 0xD8, 0x22, 0x12, 0xEF, 0x16, 0xDB, 0xF8, 0x72, 0xF2, 0xA3, 0xA7, |
| 125 | 0xC0, 0xFA, 0x52, 0x48, 0xEC |
| 126 | ]; |
| 127 | |
| 128 | // make sure output hasn't changed |
| 129 | let mut builder = AdvBuilder::new(LdtEncoder::<CryptoProviderImpl>::new([0x22; 2].into(), &broadcast_cred)); |
| 130 | builder.add_data_element(TxPowerDataElement::from(TxPower::try_from(3).unwrap())).unwrap(); |
| 131 | assert_eq!(adv, builder.into_advertisement().unwrap().as_slice()); |
| 132 | |
| 133 | let discovery_credential = V0DiscoveryCredential::new(key_seed, identity_token_hmac); |
| 134 | |
| 135 | let credentials: [MatchableCredential<V0, MetadataMatchedCredential<_>>; 1] = |
| 136 | [MatchableCredential { discovery_credential, match_data: encrypted_sender_metadata }]; |
| 137 | |
| 138 | let cred_book = CredentialBookBuilder::build_cached_slice_book::<0, 0, CryptoProviderImpl>( |
| 139 | &credentials, |
| 140 | &[], |
| 141 | ); |
| 142 | |
| 143 | let matched = match deserialize_advertisement::<_, CryptoProviderImpl>( |
| 144 | deserialization_arena!(), |
| 145 | adv, |
| 146 | &cred_book, |
| 147 | ) |
| 148 | .expect("Should be a valid advertisement") |
| 149 | .into_v0() |
| 150 | .expect("Should be V0") |
| 151 | { |
| 152 | V0AdvertisementContents::Decrypted(c) => c, |
| 153 | _ => panic!("this example is ciphertext"), |
| 154 | }; |
| 155 | |
| 156 | let decrypted_metadata_bytes = matched |
| 157 | .decrypt_metadata::<CryptoProviderImpl>() |
| 158 | .expect("Sender metadata should be decryptable"); |
| 159 | let decrypted_metadata = IdentityMetadata::try_from_bytes(&decrypted_metadata_bytes) |
| 160 | .expect("Sender metadata should be deserializable"); |
| 161 | |
| 162 | assert_eq!(sender_metadata, decrypted_metadata); |
| 163 | |
| 164 | let decrypted = matched.contents(); |
| 165 | |
| 166 | assert_eq!(identity_token, decrypted.identity_token()); |
| 167 | |
| 168 | assert_eq!( |
| 169 | vec![DeserializedDataElement::TxPower(TxPowerDataElement::from(TxPower::try_from(3).unwrap())),], |
| 170 | decrypted.data_elements().collect::<Result<Vec<_>, _>>().unwrap(), |
| 171 | ); |
| 172 | } |