1 /*
2 * Copyright (c) 2022 Nordic Semiconductor ASA
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include "mocks/hci_core.h"
8 #include "mocks/hci_core_expects.h"
9 #include "mocks/prng.h"
10 #include "mocks/prng_expects.h"
11
12 #include <zephyr/bluetooth/crypto.h>
13 #include <zephyr/fff.h>
14 #include <zephyr/kernel.h>
15
16 #include <host/crypto.h>
17
18 DEFINE_FFF_GLOBALS;
19
fff_reset_rule_before(const struct ztest_unit_test * test,void * fixture)20 static void fff_reset_rule_before(const struct ztest_unit_test *test, void *fixture)
21 {
22 HCI_CORE_FFF_FAKES_LIST(RESET_FAKE);
23 PRNG_FFF_FAKES_LIST(RESET_FAKE);
24 }
25
26 ZTEST_RULE(fff_reset_rule, fff_reset_rule_before, NULL);
27
28 ZTEST_SUITE(bt_rand, NULL, NULL, NULL, NULL, NULL);
29
30 /*
31 * Test bt_rand() succeeds while 'CONFIG_BT_HOST_CRYPTO_PRNG' isn't enabled.
32 *
33 * Constraints:
34 * - 'CONFIG_BT_HOST_CRYPTO_PRNG' isn't enabled
35 * - bt_hci_le_rand() succeeds and returns 0 (success)
36 *
37 * Expected behaviour:
38 * - bt_rand() returns 0 (success)
39 */
ZTEST(bt_rand,test_bt_rand_succeeds_host_crypto_prng_disabled)40 ZTEST(bt_rand, test_bt_rand_succeeds_host_crypto_prng_disabled)
41 {
42 int err;
43 uint8_t buf[16];
44 size_t buf_len = 16;
45 uint8_t expected_args_history[] = {16};
46
47 Z_TEST_SKIP_IFDEF(CONFIG_BT_HOST_CRYPTO_PRNG);
48
49 bt_hci_le_rand_fake.return_val = 0;
50
51 err = bt_rand(buf, buf_len);
52
53 expect_call_count_bt_hci_le_rand(1, expected_args_history);
54
55 zassert_ok(err, "Unexpected error code '%d' was returned", err);
56 }
57
58 /*
59 * Test bt_rand() succeeds when psa_generate_random() succeeds on the first call while
60 * 'CONFIG_BT_HOST_CRYPTO_PRNG' is enabled.
61 *
62 * Constraints:
63 * - 'CONFIG_BT_HOST_CRYPTO_PRNG' is enabled
64 * - psa_generate_random() succeeds and returns 'PSA_SUCCESS' on the first call.
65 *
66 * Expected behaviour:
67 * - bt_rand() returns 0 (success)
68 */
ZTEST(bt_rand,test_psa_generate_random_succeeds_on_first_call)69 ZTEST(bt_rand, test_psa_generate_random_succeeds_on_first_call)
70 {
71 int err;
72 uint8_t buf[16];
73 size_t buf_len = 16;
74
75 Z_TEST_SKIP_IFNDEF(CONFIG_BT_HOST_CRYPTO_PRNG);
76
77 psa_generate_random_fake.return_val = PSA_SUCCESS;
78
79 err = bt_rand(buf, buf_len);
80
81 expect_single_call_psa_generate_random(buf, buf_len);
82
83 zassert_ok(err, "Unexpected error code '%d' was returned", err);
84 }
85