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 #include "shared_test_util.h"
16
17 #include <cstdlib>
18
19 #include "nearby_protocol.h"
20
PanicReasonToString(nearby_protocol::PanicReason reason)21 std::string PanicReasonToString(nearby_protocol::PanicReason reason) {
22 switch (reason) {
23 case nearby_protocol::PanicReason::EnumCastFailed: {
24 return "EnumCastFailed";
25 }
26 case nearby_protocol::PanicReason::AssertFailed: {
27 return "AssertFailed";
28 }
29 case nearby_protocol::PanicReason::InvalidStackDataStructure: {
30 return "InvalidStackDataStructure";
31 }
32 case np_ffi::internal::PanicReason::ExceededMaxHandleAllocations:
33 return "ExceededMaxHandleAllocations";
34 }
35 }
36
test_panic_handler(nearby_protocol::PanicReason reason)37 void test_panic_handler(nearby_protocol::PanicReason reason) {
38 std::cout << "Panicking! Reason: " << PanicReasonToString(reason);
39 std::abort();
40 }
41
generate_hex_string(const size_t length)42 std::string generate_hex_string(const size_t length) {
43 std::string result;
44 result.reserve(length);
45
46 // hexadecimal characters
47 char hex_characters[] = {'0', '1', '2', '3', '4', '5', '6', '7',
48 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
49
50 for (size_t i = 0; i < length; i++) {
51 result.push_back(hex_characters[rand() % 16]); // NOLINT(cert-msc50-cpp)
52 }
53
54 return result;
55 }
56
GenerateRandomCredentialV0()57 nearby_protocol::V0MatchableCredential GenerateRandomCredentialV0() {
58 auto key_seed = create_random_array<32>();
59 auto legacy_metadata_key_hmac = create_random_array<32>();
60 auto encrypted_metadata_bytes = create_random_array<200>();
61 nearby_protocol::MatchedCredentialData matched_cred(rand(),
62 encrypted_metadata_bytes);
63 return {key_seed, legacy_metadata_key_hmac, matched_cred};
64 }
65
GenerateRandomCredentialV1()66 nearby_protocol::V1MatchableCredential GenerateRandomCredentialV1() {
67 auto key_seed = create_random_array<32>();
68 auto expected_unsigned_metadata_key_hmac = create_random_array<32>();
69 auto expected_signed_metadata_key_hmac = create_random_array<32>();
70 auto pub_key = create_random_array<32>();
71 auto encrypted_metadata_bytes = create_random_array<200>();
72 nearby_protocol::MatchedCredentialData matched_cred(rand(),
73 encrypted_metadata_bytes);
74 return {key_seed, expected_unsigned_metadata_key_hmac,
75 expected_signed_metadata_key_hmac, pub_key, matched_cred};
76 }
77