From ef4c399525db6fc21b2050324beffe432b641987 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Wed, 24 Apr 2024 14:24:22 +0200 Subject: [PATCH] Replace nl-unit-test for pigweed for crypto (#33042) * Fix test chip crypto * Crypto to pigweed * Fix bugs * Fix * Style * Bug fixes * Fix CI errors * fix code not compiled on linux * Remove empty tests * Expect to assert * Initialize PSA crypto in test setup * Fix tests * fix openiotsdk tests list * fix unused function * fix deps list * fix deps list * Make memory init setup in testsuite * Add TODO --- src/crypto/tests/BUILD.gn | 5 +- src/crypto/tests/TestChipCryptoPAL.cpp | 1240 ++++++++--------- .../tests/TestGroupOperationalCredentials.cpp | 59 +- src/crypto/tests/TestPSAOpKeyStore.cpp | 229 ++- .../tests/TestPersistentStorageOpKeyStore.cpp | 227 ++- src/crypto/tests/TestSessionKeystore.cpp | 102 +- .../tests/TestAbortExchangesForFabric.cpp | 16 +- src/messaging/tests/TestExchangeMgr.cpp | 18 +- .../tests/TestReliableMessageProtocol.cpp | 7 + .../openiotsdk/unit-tests/test_components.txt | 3 +- .../unit-tests/test_components_nl.txt | 1 - 11 files changed, 840 insertions(+), 1067 deletions(-) diff --git a/src/crypto/tests/BUILD.gn b/src/crypto/tests/BUILD.gn index 1599b942269ae6..8570ed3defc157 100644 --- a/src/crypto/tests/BUILD.gn +++ b/src/crypto/tests/BUILD.gn @@ -14,12 +14,11 @@ import("//build_overrides/build.gni") import("//build_overrides/chip.gni") -import("//build_overrides/nlunit_test.gni") import("${chip_root}/build/chip/chip_test_suite.gni") import("${chip_root}/src/crypto/crypto.gni") -chip_test_suite_using_nltest("tests") { +chip_test_suite("tests") { output_name = "libChipCryptoTests" sources = [ @@ -70,8 +69,6 @@ chip_test_suite_using_nltest("tests") { "${chip_root}/src/crypto", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support:testing", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/platform", - "${nlunit_test_root}:nlunit-test", ] } diff --git a/src/crypto/tests/TestChipCryptoPAL.cpp b/src/crypto/tests/TestChipCryptoPAL.cpp index 0cf3a877fcf828..c7ad4f3f290522 100644 --- a/src/crypto/tests/TestChipCryptoPAL.cpp +++ b/src/crypto/tests/TestChipCryptoPAL.cpp @@ -37,12 +37,10 @@ #include #include +#include #include #include #include -#include -#include -#include #include #include @@ -93,9 +91,8 @@ using TestHMAC_sha = HMAC_sha; class HeapChecker { public: - explicit HeapChecker(nlTestSuite * testSuite) : mTestSuite(testSuite) + explicit HeapChecker() { - size_t numBlocks; mbedtls_memory_buffer_alloc_cur_get(&mHeapBytesUsed, &numBlocks); } @@ -109,19 +106,18 @@ class HeapChecker if (bytesUsed != mHeapBytesUsed) { mbedtls_memory_buffer_alloc_status(); - NL_TEST_ASSERT(mTestSuite, bytesUsed == mHeapBytesUsed); + EXPECT_EQ(bytesUsed, mHeapBytesUsed); } } private: - nlTestSuite * mTestSuite; size_t mHeapBytesUsed; }; #else class HeapChecker { public: - explicit HeapChecker(nlTestSuite *) {} + explicit HeapChecker() {} }; #endif @@ -129,7 +125,7 @@ class HeapChecker // Verify that two HKDF keys are equal by checking if they generate the same attestation challenge. // Note that the keys cannot be compared directly because they are given as key handles. -void AssertKeysEqual(nlTestSuite * inSuite, SessionKeystore & keystore, HkdfKeyHandle & left, const HkdfKeyHandle & right) +void AssertKeysEqual(SessionKeystore & keystore, HkdfKeyHandle & left, const HkdfKeyHandle & right) { auto generateChallenge = [&](const HkdfKeyHandle & key, AttestationChallenge & challenge) -> void { constexpr uint8_t kTestSalt[] = { 'T', 'E', 'S', 'T', 'S', 'A', 'L', 'T' }; @@ -139,7 +135,7 @@ void AssertKeysEqual(nlTestSuite * inSuite, SessionKeystore & keystore, HkdfKeyH Aes128KeyHandle r2iKey; CHIP_ERROR error = keystore.DeriveSessionKeys(key, ByteSpan(kTestSalt), ByteSpan(kTestInfo), i2rKey, r2iKey, challenge); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Ignore the keys, just return the attestation challenge keystore.DestroyKey(i2rKey); @@ -152,10 +148,13 @@ void AssertKeysEqual(nlTestSuite * inSuite, SessionKeystore & keystore, HkdfKeyH generateChallenge(left, leftChallenge); generateChallenge(right, rightChallenge); - NL_TEST_ASSERT(inSuite, memcmp(leftChallenge.ConstBytes(), rightChallenge.ConstBytes(), AttestationChallenge::Capacity()) == 0); + EXPECT_EQ(memcmp(leftChallenge.ConstBytes(), rightChallenge.ConstBytes(), AttestationChallenge::Capacity()), 0); } } // namespace + // + +#if CHIP_CRYPTO_OPENSSL || CHIP_CRYPTO_MBEDTLS static uint32_t gs_test_entropy_source_called = 0; static int test_entropy_source(void * data, uint8_t * output, size_t len, size_t * olen) @@ -165,6 +164,8 @@ static int test_entropy_source(void * data, uint8_t * output, size_t len, size_t return 0; } +#endif // CHIP_CRYPTO_OPENSSL || CHIP_CRYPTO_MBEDTLS + constexpr size_t KEY_LENGTH = Crypto::kAES_CCM128_Key_Length; constexpr size_t NONCE_LENGTH = Crypto::kAES_CCM128_Nonce_Length; @@ -210,13 +211,13 @@ const AesCtrTestEntry theAesCtrTestVector[] = { struct TestAesKey { public: - TestAesKey(nlTestSuite * inSuite, const uint8_t * keyBytes, size_t keyLength) + TestAesKey(const uint8_t * keyBytes, size_t keyLength) { Crypto::Symmetric128BitsKeyByteArray keyMaterial; memcpy(&keyMaterial, keyBytes, keyLength); CHIP_ERROR err = keystore.CreateKey(keyMaterial, key); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } ~TestAesKey() { keystore.DestroyKey(key); } @@ -228,13 +229,13 @@ struct TestAesKey struct TestHmacKey { public: - TestHmacKey(nlTestSuite * inSuite, const uint8_t * keyBytes, size_t keyLength) + TestHmacKey(const uint8_t * keyBytes, size_t keyLength) { Crypto::Symmetric128BitsKeyByteArray keyMaterial; memcpy(&keyMaterial, keyBytes, keyLength); CHIP_ERROR err = keystore.CreateKey(keyMaterial, key); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); } ~TestHmacKey() { keystore.DestroyKey(key); } @@ -243,64 +244,76 @@ struct TestHmacKey Hmac128KeyHandle key; }; -static void TestAES_CTR_128_Encrypt(nlTestSuite * inSuite, const AesCtrTestEntry * vector) +static void TestAES_CTR_128_Encrypt(const AesCtrTestEntry * vector) { chip::Platform::ScopedMemoryBuffer outBuffer; outBuffer.Alloc(vector->ciphertextLen); - NL_TEST_ASSERT(inSuite, outBuffer); + EXPECT_TRUE(outBuffer); - TestAesKey key(inSuite, vector->key, KEY_LENGTH); + TestAesKey key(vector->key, KEY_LENGTH); CHIP_ERROR err = AES_CTR_crypt(vector->plaintext, vector->plaintextLen, key.key, vector->nonce, NONCE_LENGTH, outBuffer.Get()); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); bool outputMatches = memcmp(outBuffer.Get(), vector->ciphertext, vector->ciphertextLen) == 0; - NL_TEST_ASSERT(inSuite, outputMatches); + EXPECT_TRUE(outputMatches); if (!outputMatches) { printf("\n Test failed due to mismatching ciphertext\n"); } } -static void TestAES_CTR_128_Decrypt(nlTestSuite * inSuite, const AesCtrTestEntry * vector) +static void TestAES_CTR_128_Decrypt(const AesCtrTestEntry * vector) { chip::Platform::ScopedMemoryBuffer outBuffer; outBuffer.Alloc(vector->plaintextLen); - NL_TEST_ASSERT(inSuite, outBuffer); + EXPECT_TRUE(outBuffer); - TestAesKey key(inSuite, vector->key, KEY_LENGTH); + TestAesKey key(vector->key, KEY_LENGTH); CHIP_ERROR err = AES_CTR_crypt(vector->ciphertext, vector->ciphertextLen, key.key, vector->nonce, NONCE_LENGTH, outBuffer.Get()); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); bool outputMatches = memcmp(outBuffer.Get(), vector->plaintext, vector->plaintextLen) == 0; - NL_TEST_ASSERT(inSuite, outputMatches); + EXPECT_TRUE(outputMatches); if (!outputMatches) { printf("\n Test failed due to mismatching plaintext\n"); } } -static void TestAES_CTR_128CryptTestVectors(nlTestSuite * inSuite, void * inContext) +struct TestChipCryptoPAL : public ::testing::Test +{ + static void SetUpTestSuite() + { + ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); +#if CHIP_CRYPTO_PSA + psa_crypto_init(); +#endif + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestChipCryptoPAL, TestAES_CTR_128CryptTestVectors) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestsRan = 0; for (const auto & vector : theAesCtrTestVector) { if (vector.plaintextLen > 0) { numOfTestsRan++; - TestAES_CTR_128_Encrypt(inSuite, &vector); - TestAES_CTR_128_Decrypt(inSuite, &vector); + TestAES_CTR_128_Encrypt(&vector); + TestAES_CTR_128_Decrypt(&vector); } } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestAES_CCM_128EncryptTestVectors(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAES_CCM_128EncryptTestVectors) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestVectors = ArraySize(ccm_128_test_vectors); int numOfTestsRan = 0; for (int vectorIndex = 0; vectorIndex < numOfTestVectors; vectorIndex++) @@ -311,23 +324,23 @@ static void TestAES_CCM_128EncryptTestVectors(nlTestSuite * inSuite, void * inCo numOfTestsRan++; chip::Platform::ScopedMemoryBuffer out_ct; out_ct.Alloc(vector->ct_len); - NL_TEST_ASSERT(inSuite, out_ct); + EXPECT_TRUE(out_ct); chip::Platform::ScopedMemoryBuffer out_tag; out_tag.Alloc(vector->tag_len); - NL_TEST_ASSERT(inSuite, out_tag); + EXPECT_TRUE(out_tag); - TestAesKey key(inSuite, vector->key, vector->key_len); + TestAesKey key(vector->key, vector->key_len); CHIP_ERROR err = AES_CCM_encrypt(vector->pt, vector->pt_len, vector->aad, vector->aad_len, key.key, vector->nonce, vector->nonce_len, out_ct.Get(), out_tag.Get(), vector->tag_len); - NL_TEST_ASSERT(inSuite, err == vector->result); + EXPECT_EQ(err, vector->result); if (vector->result == CHIP_NO_ERROR) { bool areCTsEqual = memcmp(out_ct.Get(), vector->ct, vector->ct_len) == 0; bool areTagsEqual = memcmp(out_tag.Get(), vector->tag, vector->tag_len) == 0; - NL_TEST_ASSERT(inSuite, areCTsEqual); - NL_TEST_ASSERT(inSuite, areTagsEqual); + EXPECT_TRUE(areCTsEqual); + EXPECT_TRUE(areTagsEqual); if (!areCTsEqual) { printf("\n Test %d failed due to mismatching ciphertext\n", vector->tcId); @@ -339,12 +352,12 @@ static void TestAES_CCM_128EncryptTestVectors(nlTestSuite * inSuite, void * inCo } } } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestAES_CCM_128DecryptTestVectors(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAES_CCM_128DecryptTestVectors) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestVectors = ArraySize(ccm_128_test_vectors); int numOfTestsRan = 0; for (int vectorIndex = 0; vectorIndex < numOfTestVectors; vectorIndex++) @@ -355,18 +368,18 @@ static void TestAES_CCM_128DecryptTestVectors(nlTestSuite * inSuite, void * inCo numOfTestsRan++; chip::Platform::ScopedMemoryBuffer out_pt; out_pt.Alloc(vector->pt_len); - NL_TEST_ASSERT(inSuite, out_pt); + EXPECT_TRUE(out_pt); - TestAesKey key(inSuite, vector->key, vector->key_len); + TestAesKey key(vector->key, vector->key_len); CHIP_ERROR err = AES_CCM_decrypt(vector->ct, vector->ct_len, vector->aad, vector->aad_len, vector->tag, vector->tag_len, key.key, vector->nonce, vector->nonce_len, out_pt.Get()); - NL_TEST_ASSERT(inSuite, err == vector->result); + EXPECT_EQ(err, vector->result); if (vector->result == CHIP_NO_ERROR) { bool arePTsEqual = memcmp(vector->pt, out_pt.Get(), vector->pt_len) == 0; - NL_TEST_ASSERT(inSuite, arePTsEqual); + EXPECT_TRUE(arePTsEqual); if (!arePTsEqual) { printf("\n Test %d failed due to mismatching plaintext\n", vector->tcId); @@ -374,12 +387,12 @@ static void TestAES_CCM_128DecryptTestVectors(nlTestSuite * inSuite, void * inCo } } } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestAES_CCM_128EncryptInvalidNonceLen(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAES_CCM_128EncryptInvalidNonceLen) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestVectors = ArraySize(ccm_128_test_vectors); int numOfTestsRan = 0; for (int vectorIndex = 0; vectorIndex < numOfTestVectors; vectorIndex++) @@ -390,25 +403,25 @@ static void TestAES_CCM_128EncryptInvalidNonceLen(nlTestSuite * inSuite, void * numOfTestsRan++; chip::Platform::ScopedMemoryBuffer out_ct; out_ct.Alloc(vector->ct_len); - NL_TEST_ASSERT(inSuite, out_ct); + EXPECT_TRUE(out_ct); chip::Platform::ScopedMemoryBuffer out_tag; out_tag.Alloc(vector->tag_len); - NL_TEST_ASSERT(inSuite, out_tag); + EXPECT_TRUE(out_tag); - TestAesKey key(inSuite, vector->key, vector->key_len); + TestAesKey key(vector->key, vector->key_len); CHIP_ERROR err = AES_CCM_encrypt(vector->pt, vector->pt_len, vector->aad, vector->aad_len, key.key, vector->nonce, 0, out_ct.Get(), out_tag.Get(), vector->tag_len); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(err, CHIP_ERROR_INVALID_ARGUMENT); break; } } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestAES_CCM_128EncryptInvalidTagLen(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAES_CCM_128EncryptInvalidTagLen) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestVectors = ArraySize(ccm_128_test_vectors); int numOfTestsRan = 0; for (int vectorIndex = 0; vectorIndex < numOfTestVectors; vectorIndex++) @@ -419,25 +432,25 @@ static void TestAES_CCM_128EncryptInvalidTagLen(nlTestSuite * inSuite, void * in numOfTestsRan++; chip::Platform::ScopedMemoryBuffer out_ct; out_ct.Alloc(vector->ct_len); - NL_TEST_ASSERT(inSuite, out_ct); + EXPECT_TRUE(out_ct); chip::Platform::ScopedMemoryBuffer out_tag; out_tag.Alloc(vector->tag_len); - NL_TEST_ASSERT(inSuite, out_tag); + EXPECT_TRUE(out_tag); - TestAesKey key(inSuite, vector->key, vector->key_len); + TestAesKey key(vector->key, vector->key_len); CHIP_ERROR err = AES_CCM_encrypt(vector->pt, vector->pt_len, vector->aad, vector->aad_len, key.key, vector->nonce, vector->nonce_len, out_ct.Get(), out_tag.Get(), 13); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(err, CHIP_ERROR_INVALID_ARGUMENT); break; } } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestAES_CCM_128DecryptInvalidNonceLen(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAES_CCM_128DecryptInvalidNonceLen) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestVectors = ArraySize(ccm_128_test_vectors); int numOfTestsRan = 0; for (int vectorIndex = 0; vectorIndex < numOfTestVectors; vectorIndex++) @@ -448,22 +461,22 @@ static void TestAES_CCM_128DecryptInvalidNonceLen(nlTestSuite * inSuite, void * numOfTestsRan++; Platform::ScopedMemoryBuffer out_pt; out_pt.Alloc(vector->pt_len); - NL_TEST_ASSERT(inSuite, out_pt); + EXPECT_TRUE(out_pt); - TestAesKey key(inSuite, vector->key, vector->key_len); + TestAesKey key(vector->key, vector->key_len); CHIP_ERROR err = AES_CCM_decrypt(vector->ct, vector->ct_len, vector->aad, vector->aad_len, vector->tag, vector->tag_len, key.key, vector->nonce, 0, out_pt.Get()); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(err, CHIP_ERROR_INVALID_ARGUMENT); break; } } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestSensitiveDataBuffer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSensitiveDataBuffer) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; constexpr size_t kCapacity = 32; constexpr size_t kLength = 16; @@ -473,32 +486,32 @@ static void TestSensitiveDataBuffer(nlTestSuite * inSuite, void * inContext) // Give us some data. CHIP_ERROR err = DRBG_get_bytes(testVector, sizeof(testVector)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Test initial value Buffer buffer; - NL_TEST_ASSERT(inSuite, buffer.ConstBytes() == (const uint8_t *) buffer.Bytes()); - NL_TEST_ASSERT(inSuite, buffer.Length() == 0); + EXPECT_EQ(buffer.ConstBytes(), (const uint8_t *) buffer.Bytes()); + EXPECT_EQ(buffer.Length(), 0u); // Put data in the buffer and test all accessors memcpy(buffer.Bytes(), testVector, kCapacity); buffer.SetLength(kLength); - NL_TEST_ASSERT(inSuite, buffer.ConstBytes() == (const uint8_t *) buffer.Bytes()); - NL_TEST_ASSERT(inSuite, buffer.ConstBytes() == buffer.Span().data()); - NL_TEST_ASSERT(inSuite, buffer.Length() == kLength); - NL_TEST_ASSERT(inSuite, buffer.Length() == buffer.Span().size()); + EXPECT_EQ(buffer.ConstBytes(), (const uint8_t *) buffer.Bytes()); + EXPECT_EQ(buffer.ConstBytes(), buffer.Span().data()); + EXPECT_EQ(buffer.Length(), kLength); + EXPECT_EQ(buffer.Length(), buffer.Span().size()); // Test sanitization of entire buffer (even though length < capacity) const void * bufferStorage = buffer.ConstBytes(); buffer.~Buffer(); - NL_TEST_ASSERT(inSuite, memcmp(bufferStorage, kAllZeros, kCapacity) == 0); - NL_TEST_ASSERT(inSuite, memcmp(bufferStorage, testVector, kCapacity)); + EXPECT_EQ(memcmp(bufferStorage, kAllZeros, kCapacity), 0); + EXPECT_TRUE(memcmp(bufferStorage, testVector, kCapacity)); } -static void TestSensitiveDataFixedBuffer(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSensitiveDataFixedBuffer) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; constexpr size_t kCapacity = 32; using Buffer = SensitiveDataFixedBuffer; @@ -508,34 +521,34 @@ static void TestSensitiveDataFixedBuffer(nlTestSuite * inSuite, void * inContext // Give us some data. CHIP_ERROR err = DRBG_get_bytes(testVector, sizeof(testVector)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Test construction from array and all accessors Buffer buffer(testVector); - NL_TEST_ASSERT(inSuite, buffer.ConstBytes() == (const uint8_t *) buffer.Bytes()); - NL_TEST_ASSERT(inSuite, buffer.ConstBytes() == buffer.Span().data()); - NL_TEST_ASSERT(inSuite, memcmp(buffer.ConstBytes(), testVector, kCapacity) == 0); + EXPECT_EQ(buffer.ConstBytes(), (const uint8_t *) buffer.Bytes()); + EXPECT_EQ(buffer.ConstBytes(), buffer.Span().data()); + EXPECT_EQ(memcmp(buffer.ConstBytes(), testVector, kCapacity), 0); // Test sanitization const void * bufferStorage = buffer.ConstBytes(); buffer.~Buffer(); - NL_TEST_ASSERT(inSuite, memcmp(bufferStorage, kAllZeros, kCapacity) == 0); - NL_TEST_ASSERT(inSuite, memcmp(bufferStorage, testVector, kCapacity)); + EXPECT_EQ(memcmp(bufferStorage, kAllZeros, kCapacity), 0); + EXPECT_TRUE(memcmp(bufferStorage, testVector, kCapacity)); // Give us different data err = DRBG_get_bytes(testVector, sizeof(testVector)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Test construction from span and all accessors new (&buffer) Buffer(BufferSpan(testVector)); - NL_TEST_ASSERT(inSuite, buffer.ConstBytes() == (const uint8_t *) buffer.Bytes()); - NL_TEST_ASSERT(inSuite, buffer.ConstBytes() == buffer.Span().data()); - NL_TEST_ASSERT(inSuite, memcmp(buffer.ConstBytes(), testVector, kCapacity) == 0); + EXPECT_EQ(buffer.ConstBytes(), (const uint8_t *) buffer.Bytes()); + EXPECT_EQ(buffer.ConstBytes(), buffer.Span().data()); + EXPECT_EQ(memcmp(buffer.ConstBytes(), testVector, kCapacity), 0); } -static void TestAsn1Conversions(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAsn1Conversions) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; static_assert(sizeof(kDerSigConvDerCase4) == (sizeof(kDerSigConvRawCase4) + chip::Crypto::kMax_ECDSA_X9Dot62_Asn1_Overhead), "kDerSigConvDerCase4 must have worst case overhead"); @@ -547,36 +560,36 @@ static void TestAsn1Conversions(nlTestSuite * inSuite, void * inContext) chip::Platform::ScopedMemoryBuffer out_raw_sig; size_t out_raw_sig_allocated_size = vector->fe_length_bytes * 2; out_raw_sig.Calloc(out_raw_sig_allocated_size); - NL_TEST_ASSERT(inSuite, out_raw_sig); + EXPECT_TRUE(out_raw_sig); chip::Platform::ScopedMemoryBuffer out_der_sig; size_t out_der_sig_allocated_size = (vector->fe_length_bytes * 2) + kMax_ECDSA_X9Dot62_Asn1_Overhead; out_der_sig.Calloc(out_der_sig_allocated_size); - NL_TEST_ASSERT(inSuite, out_der_sig); + EXPECT_TRUE(out_der_sig); // Test conversion from ASN.1 ER to raw MutableByteSpan out_raw_sig_span(out_raw_sig.Get(), out_raw_sig_allocated_size); CHIP_ERROR status = EcdsaAsn1SignatureToRaw(vector->fe_length_bytes, ByteSpan{ vector->der_version, vector->der_version_length }, out_raw_sig_span); - NL_TEST_ASSERT(inSuite, status == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, out_raw_sig_span.size() == vector->raw_version_length); - NL_TEST_ASSERT(inSuite, (memcmp(out_raw_sig_span.data(), vector->raw_version, vector->raw_version_length) == 0)); + EXPECT_EQ(status, CHIP_NO_ERROR); + EXPECT_EQ(out_raw_sig_span.size(), vector->raw_version_length); + EXPECT_EQ(memcmp(out_raw_sig_span.data(), vector->raw_version, vector->raw_version_length), 0); // Test conversion from raw to ASN.1 DER MutableByteSpan out_der_sig_span(out_der_sig.Get(), out_der_sig_allocated_size); status = EcdsaRawSignatureToAsn1(vector->fe_length_bytes, ByteSpan{ vector->raw_version, vector->raw_version_length }, out_der_sig_span); - NL_TEST_ASSERT(inSuite, status == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, out_der_sig_span.size() <= out_der_sig_allocated_size); - NL_TEST_ASSERT(inSuite, out_der_sig_span.size() == vector->der_version_length); - NL_TEST_ASSERT(inSuite, (memcmp(out_der_sig_span.data(), vector->der_version, vector->der_version_length) == 0)); + EXPECT_EQ(status, CHIP_NO_ERROR); + EXPECT_LE(out_der_sig_span.size(), out_der_sig_allocated_size); + EXPECT_EQ(out_der_sig_span.size(), vector->der_version_length); + EXPECT_EQ(memcmp(out_der_sig_span.data(), vector->der_version, vector->der_version_length), 0); } } -static void TestRawIntegerToDerValidCases(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestRawIntegerToDerValidCases) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestCases = ArraySize(kRawIntegerToDerVectors); for (int testIdx = 0; testIdx < numOfTestCases; testIdx++) @@ -587,39 +600,39 @@ static void TestRawIntegerToDerValidCases(nlTestSuite * inSuite, void * inContex { chip::Platform::ScopedMemoryBuffer out_der_buffer; out_der_buffer.Alloc(v.expected_size); - NL_TEST_ASSERT(inSuite, out_der_buffer); + EXPECT_TRUE(out_der_buffer); MutableByteSpan out_der_integer(out_der_buffer.Get(), v.expected_size); CHIP_ERROR status = ConvertIntegerRawToDer(ByteSpan{ v.candidate, v.candidate_size }, out_der_integer); - NL_TEST_ASSERT(inSuite, status == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, out_der_integer.size() == v.expected_size); - NL_TEST_ASSERT(inSuite, out_der_integer.data_equal(ByteSpan(v.expected, v.expected_size))); + EXPECT_EQ(status, CHIP_NO_ERROR); + EXPECT_EQ(out_der_integer.size(), v.expected_size); + EXPECT_TRUE(out_der_integer.data_equal(ByteSpan(v.expected, v.expected_size))); // Cover case of buffer too small MutableByteSpan out_der_integer_too_small(out_der_buffer.Get(), v.expected_size - 1); status = ConvertIntegerRawToDer(ByteSpan{ v.candidate, v.candidate_size }, out_der_integer_too_small); - NL_TEST_ASSERT(inSuite, status == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(status, CHIP_ERROR_BUFFER_TOO_SMALL); } // Cover case without tag/length { chip::Platform::ScopedMemoryBuffer out_der_buffer; out_der_buffer.Alloc(v.expected_without_tag_size); - NL_TEST_ASSERT(inSuite, out_der_buffer); + EXPECT_TRUE(out_der_buffer); MutableByteSpan out_der_integer(out_der_buffer.Get(), v.expected_without_tag_size); CHIP_ERROR status = ConvertIntegerRawToDerWithoutTag(ByteSpan{ v.candidate, v.candidate_size }, out_der_integer); - NL_TEST_ASSERT(inSuite, status == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, out_der_integer.size() == v.expected_without_tag_size); - NL_TEST_ASSERT(inSuite, out_der_integer.data_equal(ByteSpan(v.expected_without_tag, v.expected_without_tag_size))); + EXPECT_EQ(status, CHIP_NO_ERROR); + EXPECT_EQ(out_der_integer.size(), v.expected_without_tag_size); + EXPECT_TRUE(out_der_integer.data_equal(ByteSpan(v.expected_without_tag, v.expected_without_tag_size))); } } } -static void TestRawIntegerToDerInvalidCases(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestRawIntegerToDerInvalidCases) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; // Cover case of invalid buffers uint8_t placeholder[10] = { 0 }; MutableByteSpan good_out_buffer(placeholder); @@ -647,13 +660,13 @@ static void TestRawIntegerToDerInvalidCases(nlTestSuite * inSuite, void * inCont if (status != v.expected_status) { ChipLogError(Crypto, "Failed TestRawIntegerToDerInvalidCases sub-case %d", case_idx); - NL_TEST_ASSERT(inSuite, v.expected_status == status); + EXPECT_EQ(v.expected_status, status); } ++case_idx; } } -static void TestReadDerLengthValidCases(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestReadDerLengthValidCases) { const uint8_t short_zero_length[] = { 0x00 }; ByteSpan short_zero_length_buf(short_zero_length); @@ -713,14 +726,14 @@ static void TestReadDerLengthValidCases(nlTestSuite * inSuite, void * inContext) if ((status != CHIP_NO_ERROR) || (v.expected_length != output_length)) { ChipLogError(Crypto, "Failed TestReadDerLengthValidCases sub-case %d", case_idx); - NL_TEST_ASSERT_EQUALS(inSuite, output_length, v.expected_length); - NL_TEST_ASSERT_SUCCESS(inSuite, status); + EXPECT_EQ(output_length, v.expected_length); + EXPECT_EQ(status, CHIP_NO_ERROR); } ++case_idx; } } -static void TestReadDerLengthInvalidCases(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestReadDerLengthInvalidCases) { uint8_t placeholder[1]; @@ -777,17 +790,17 @@ static void TestReadDerLengthInvalidCases(nlTestSuite * inSuite, void * inContex if (status != v.expected_status) { ChipLogError(Crypto, "Failed TestReadDerLengthInvalidCases sub-case %d", case_idx); - NL_TEST_ASSERT_EQUALS(inSuite, v.expected_status, status); + EXPECT_EQ(v.expected_status, status); } ++case_idx; } } -static void TestHash_SHA256(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestHash_SHA256) { - HeapChecker heapChecker(inSuite); - int numOfTestCases = ArraySize(hash_sha256_test_vectors); - int numOfTestsExecuted = 0; + HeapChecker heapChecker; + unsigned int numOfTestCases = ArraySize(hash_sha256_test_vectors); + unsigned int numOfTestsExecuted = 0; for (numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) { @@ -795,17 +808,17 @@ static void TestHash_SHA256(nlTestSuite * inSuite, void * inContext) uint8_t out_buffer[kSHA256_Hash_Length]; Hash_SHA256(v.data, v.data_length, out_buffer); bool success = memcmp(v.hash, out_buffer, sizeof(out_buffer)) == 0; - NL_TEST_ASSERT(inSuite, success); + EXPECT_TRUE(success); } - NL_TEST_ASSERT(inSuite, numOfTestsExecuted == ArraySize(hash_sha256_test_vectors)); + EXPECT_EQ(numOfTestsExecuted, ArraySize(hash_sha256_test_vectors)); } -static void TestHash_SHA256_Stream(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestHash_SHA256_Stream) { - HeapChecker heapChecker(inSuite); - int numOfTestCases = ArraySize(hash_sha256_test_vectors); - int numOfTestsExecuted = 0; - CHIP_ERROR error = CHIP_NO_ERROR; + HeapChecker heapChecker; + unsigned int numOfTestCases = ArraySize(hash_sha256_test_vectors); + unsigned int numOfTestsExecuted = 0; + CHIP_ERROR error = CHIP_NO_ERROR; for (numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) { @@ -817,7 +830,7 @@ static void TestHash_SHA256_Stream(nlTestSuite * inSuite, void * inContext) Hash_SHA256_stream sha256; error = sha256.Begin(); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Split data into 3 random streams. for (int i = 0; i < 2; ++i) @@ -825,25 +838,25 @@ static void TestHash_SHA256_Stream(nlTestSuite * inSuite, void * inContext) size_t rand_data_length = static_cast(rand()) % (data_length + 1); error = sha256.AddData(ByteSpan{ data, rand_data_length }); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); data += rand_data_length; data_length -= rand_data_length; } error = sha256.AddData(ByteSpan{ data, data_length }); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); MutableByteSpan out_span(out_buffer); error = sha256.Finish(out_span); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, out_span.size() == kSHA256_Hash_Length); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(out_span.size(), kSHA256_Hash_Length); bool success = memcmp(v.hash, out_span.data(), out_span.size()) == 0; - NL_TEST_ASSERT(inSuite, success); + EXPECT_TRUE(success); } - NL_TEST_ASSERT(inSuite, numOfTestsExecuted == ArraySize(hash_sha256_test_vectors)); + EXPECT_EQ(numOfTestsExecuted, ArraySize(hash_sha256_test_vectors)); // Test partial digests uint8_t source_buf[2 * kSHA256_Hash_Length]; @@ -870,30 +883,30 @@ static void TestHash_SHA256_Stream(nlTestSuite * inSuite, void * inContext) MutableByteSpan total_digest_span(total_digest); Hash_SHA256_stream sha256; - NL_TEST_ASSERT(inSuite, sha256.Begin() == CHIP_NO_ERROR); + EXPECT_EQ(sha256.Begin(), CHIP_NO_ERROR); // Compute partial digest after first block - NL_TEST_ASSERT(inSuite, sha256.AddData(ByteSpan{ &source_buf[0], block1_size }) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, sha256.GetDigest(partial_digest_span1) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, partial_digest_span1.size() == kSHA256_Hash_Length); + EXPECT_EQ(sha256.AddData(ByteSpan{ &source_buf[0], block1_size }), CHIP_NO_ERROR); + EXPECT_EQ(sha256.GetDigest(partial_digest_span1), CHIP_NO_ERROR); + EXPECT_EQ(partial_digest_span1.size(), kSHA256_Hash_Length); // Validate partial digest matches expectations Hash_SHA256(&source_buf[0], block1_size, &partial_digest_ref[0]); - NL_TEST_ASSERT(inSuite, 0 == memcmp(partial_digest_span1.data(), partial_digest_ref, partial_digest_span1.size())); + EXPECT_EQ(0, memcmp(partial_digest_span1.data(), partial_digest_ref, partial_digest_span1.size())); // Compute partial digest and total digest after second block - NL_TEST_ASSERT(inSuite, sha256.AddData(ByteSpan{ &source_buf[block1_size], block2_size }) == CHIP_NO_ERROR); + EXPECT_EQ(sha256.AddData(ByteSpan{ &source_buf[block1_size], block2_size }), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, sha256.GetDigest(partial_digest_span2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, partial_digest_span2.size() == kSHA256_Hash_Length); + EXPECT_EQ(sha256.GetDigest(partial_digest_span2), CHIP_NO_ERROR); + EXPECT_EQ(partial_digest_span2.size(), kSHA256_Hash_Length); - NL_TEST_ASSERT(inSuite, sha256.Finish(total_digest_span) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, total_digest_span.size() == kSHA256_Hash_Length); + EXPECT_EQ(sha256.Finish(total_digest_span), CHIP_NO_ERROR); + EXPECT_EQ(total_digest_span.size(), kSHA256_Hash_Length); // Validate second partial digest matches final digest Hash_SHA256(&source_buf[0], block1_size + block2_size, &total_digest_ref[0]); - NL_TEST_ASSERT(inSuite, 0 == memcmp(partial_digest_span2.data(), total_digest_ref, partial_digest_span2.size())); - NL_TEST_ASSERT(inSuite, 0 == memcmp(total_digest_span.data(), total_digest_ref, total_digest_span.size())); + EXPECT_EQ(0, memcmp(partial_digest_span2.data(), total_digest_ref, partial_digest_span2.size())); + EXPECT_EQ(0, memcmp(total_digest_span.data(), total_digest_ref, total_digest_span.size())); } } @@ -909,28 +922,28 @@ static void TestHash_SHA256_Stream(nlTestSuite * inSuite, void * inContext) Hash_SHA256(&source_buf2[0], sizeof(source_buf2), &digest_buf_ref[0]); Hash_SHA256_stream sha256; - NL_TEST_ASSERT(inSuite, sha256.Begin() == CHIP_NO_ERROR); + EXPECT_EQ(sha256.Begin(), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, sha256.AddData(ByteSpan{ source_buf2 }) == CHIP_NO_ERROR); + EXPECT_EQ(sha256.AddData(ByteSpan{ source_buf2 }), CHIP_NO_ERROR); // Check that error behavior works on buffer too small - NL_TEST_ASSERT(inSuite, sha256.GetDigest(digest_span_too_small) == CHIP_ERROR_BUFFER_TOO_SMALL); - NL_TEST_ASSERT(inSuite, sha256.Finish(digest_span_too_small) == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(sha256.GetDigest(digest_span_too_small), CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(sha256.Finish(digest_span_too_small), CHIP_ERROR_BUFFER_TOO_SMALL); // Check that both GetDigest/Finish can still work after error. - NL_TEST_ASSERT(inSuite, sha256.GetDigest(digest_span_ok) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, 0 == memcmp(digest_span_ok.data(), digest_buf_ref, digest_span_ok.size())); + EXPECT_EQ(sha256.GetDigest(digest_span_ok), CHIP_NO_ERROR); + EXPECT_EQ(0, memcmp(digest_span_ok.data(), digest_buf_ref, digest_span_ok.size())); memset(digest_buf_ok, 0, sizeof(digest_buf_ok)); - NL_TEST_ASSERT(inSuite, sha256.Finish(digest_span_ok) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, 0 == memcmp(digest_span_ok.data(), digest_buf_ref, digest_span_ok.size())); + EXPECT_EQ(sha256.Finish(digest_span_ok), CHIP_NO_ERROR); + EXPECT_EQ(0, memcmp(digest_span_ok.data(), digest_buf_ref, digest_span_ok.size())); } } -static void TestHMAC_SHA256_RawKey(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestHMAC_SHA256_RawKey) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestCases = ArraySize(hmac_sha256_test_vectors_raw_key); int numOfTestsExecuted = 0; TestHMAC_sha mHMAC; @@ -941,17 +954,17 @@ static void TestHMAC_SHA256_RawKey(nlTestSuite * inSuite, void * inContext) size_t out_length = v.output_hash_length; chip::Platform::ScopedMemoryBuffer out_buffer; out_buffer.Alloc(out_length); - NL_TEST_ASSERT(inSuite, out_buffer); + EXPECT_TRUE(out_buffer); mHMAC.HMAC_SHA256(v.key, v.key_length, v.message, v.message_length, out_buffer.Get(), v.output_hash_length); bool success = memcmp(v.output_hash, out_buffer.Get(), out_length) == 0; - NL_TEST_ASSERT(inSuite, success); + EXPECT_TRUE(success); } - NL_TEST_ASSERT(inSuite, numOfTestsExecuted == numOfTestCases); + EXPECT_EQ(numOfTestsExecuted, numOfTestCases); } -static void TestHMAC_SHA256_KeyHandle(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestHMAC_SHA256_KeyHandle) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestCases = ArraySize(hmac_sha256_test_vectors_key_handle); int numOfTestsExecuted = 0; TestHMAC_sha mHMAC; @@ -962,27 +975,27 @@ static void TestHMAC_SHA256_KeyHandle(nlTestSuite * inSuite, void * inContext) size_t out_length = v.output_hash_length; chip::Platform::ScopedMemoryBuffer out_buffer; out_buffer.Alloc(out_length); - NL_TEST_ASSERT(inSuite, out_buffer); + EXPECT_TRUE(out_buffer); Crypto::DefaultSessionKeystore keystore; Symmetric128BitsKeyByteArray keyMaterial; memcpy(keyMaterial, v.key, v.key_length); Hmac128KeyHandle keyHandle; - NL_TEST_ASSERT_SUCCESS(inSuite, keystore.CreateKey(keyMaterial, keyHandle)); + EXPECT_EQ(keystore.CreateKey(keyMaterial, keyHandle), CHIP_NO_ERROR); mHMAC.HMAC_SHA256(keyHandle, v.message, v.message_length, out_buffer.Get(), v.output_hash_length); bool success = memcmp(v.output_hash, out_buffer.Get(), out_length) == 0; - NL_TEST_ASSERT(inSuite, success); + EXPECT_TRUE(success); keystore.DestroyKey(keyHandle); } - NL_TEST_ASSERT(inSuite, numOfTestsExecuted == numOfTestCases); + EXPECT_EQ(numOfTestsExecuted, numOfTestCases); } -static void TestHKDF_SHA256(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestHKDF_SHA256) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestCases = ArraySize(hkdf_sha256_test_vectors); int numOfTestsExecuted = 0; TestHKDF_sha mHKDF; @@ -993,28 +1006,28 @@ static void TestHKDF_SHA256(nlTestSuite * inSuite, void * inContext) size_t out_length = v.output_key_material_length; chip::Platform::ScopedMemoryBuffer out_buffer; out_buffer.Alloc(out_length); - NL_TEST_ASSERT(inSuite, out_buffer); + EXPECT_TRUE(out_buffer); mHKDF.HKDF_SHA256(v.initial_key_material, v.initial_key_material_length, v.salt, v.salt_length, v.info, v.info_length, out_buffer.Get(), v.output_key_material_length); bool success = memcmp(v.output_key_material, out_buffer.Get(), out_length) == 0; - NL_TEST_ASSERT(inSuite, success); + EXPECT_TRUE(success); } - NL_TEST_ASSERT(inSuite, numOfTestsExecuted == 3); + EXPECT_EQ(numOfTestsExecuted, 3); } -static void TestDRBG_InvalidInputs(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestDRBG_InvalidInputs) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR error = CHIP_NO_ERROR; error = DRBG_get_bytes(nullptr, 10); - NL_TEST_ASSERT(inSuite, error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(error, CHIP_ERROR_INVALID_ARGUMENT); error = CHIP_NO_ERROR; uint8_t buffer[5]; error = DRBG_get_bytes(buffer, 0); - NL_TEST_ASSERT(inSuite, error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(error, CHIP_ERROR_INVALID_ARGUMENT); } -static void TestDRBG_Output(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestDRBG_Output) { // No good way to unit test a DRBG. Just validate that we get out something CHIP_ERROR error = CHIP_ERROR_INVALID_ARGUMENT; @@ -1022,38 +1035,38 @@ static void TestDRBG_Output(nlTestSuite * inSuite, void * inContext) uint8_t orig_buf[10] = { 0 }; error = DRBG_get_bytes(out_buf, sizeof(out_buf)); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(out_buf, orig_buf, sizeof(out_buf)) != 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_NE(memcmp(out_buf, orig_buf, sizeof(out_buf)), 0); } -static void TestECDSA_Signing_SHA256_Msg(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_Signing_SHA256_Msg) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const char * msg = "Hello World!"; size_t msg_length = strlen(msg); Test_P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256ECDSASignature signature; CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(reinterpret_cast(msg), msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_NO_ERROR); + EXPECT_EQ(signing_error, CHIP_NO_ERROR); CHIP_ERROR validation_error = keypair.Pubkey().ECDSA_validate_msg_signature(reinterpret_cast(msg), msg_length, signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_NO_ERROR); + EXPECT_EQ(validation_error, CHIP_NO_ERROR); } -static void TestECDSA_Signing_SHA256_Hash(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_Signing_SHA256_Hash) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const uint8_t msg[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; size_t msg_length = sizeof(msg); Test_P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); // TODO: Need to make this large number (1k+) to catch some signature serialization corner cases // but this is too slow on QEMU/embedded, so we need to parametrize. Signing with ECDSA @@ -1066,13 +1079,13 @@ static void TestECDSA_Signing_SHA256_Hash(nlTestSuite * inSuite, void * inContex P256ECDSASignature signature; uint8_t hash[Crypto::kSHA256_Hash_Length]; - NL_TEST_ASSERT(inSuite, Hash_SHA256(&msg[0], msg_length, &hash[0]) == CHIP_NO_ERROR); + EXPECT_EQ(Hash_SHA256(&msg[0], msg_length, &hash[0]), CHIP_NO_ERROR); CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(msg, msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_NO_ERROR); + EXPECT_EQ(signing_error, CHIP_NO_ERROR); CHIP_ERROR validation_error = keypair.Pubkey().ECDSA_validate_hash_signature(hash, sizeof(hash), signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_NO_ERROR); + EXPECT_EQ(validation_error, CHIP_NO_ERROR); if ((signing_error != CHIP_NO_ERROR) || (validation_error != CHIP_NO_ERROR)) { @@ -1082,142 +1095,142 @@ static void TestECDSA_Signing_SHA256_Hash(nlTestSuite * inSuite, void * inContex } } -static void TestECDSA_ValidationFailsDifferentMessage(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_ValidationFailsDifferentMessage) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const char * msg = "Hello World!"; size_t msg_length = strlen(msg); P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256ECDSASignature signature; CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(reinterpret_cast(msg), msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_NO_ERROR); + EXPECT_EQ(signing_error, CHIP_NO_ERROR); const char * diff_msg = "NOT Hello World!"; size_t diff_msg_length = strlen(msg); CHIP_ERROR validation_error = keypair.Pubkey().ECDSA_validate_msg_signature(reinterpret_cast(diff_msg), diff_msg_length, signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_ERROR_INVALID_SIGNATURE); + EXPECT_EQ(validation_error, CHIP_ERROR_INVALID_SIGNATURE); } -static void TestECDSA_ValidationFailIncorrectMsgSignature(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_ValidationFailIncorrectMsgSignature) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const char * msg = "Hello World!"; size_t msg_length = strlen(msg); P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256ECDSASignature signature; CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(reinterpret_cast(msg), msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_NO_ERROR); + EXPECT_EQ(signing_error, CHIP_NO_ERROR); signature.Bytes()[0] = static_cast(~signature.ConstBytes()[0]); // Flipping bits should invalidate the signature. CHIP_ERROR validation_error = keypair.Pubkey().ECDSA_validate_msg_signature(reinterpret_cast(msg), msg_length, signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_ERROR_INVALID_SIGNATURE); + EXPECT_EQ(validation_error, CHIP_ERROR_INVALID_SIGNATURE); } -static void TestECDSA_ValidationFailIncorrectHashSignature(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_ValidationFailIncorrectHashSignature) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const uint8_t msg[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; size_t msg_length = sizeof(msg); uint8_t hash[Crypto::kSHA256_Hash_Length]; - NL_TEST_ASSERT(inSuite, Hash_SHA256(&msg[0], msg_length, &hash[0]) == CHIP_NO_ERROR); + EXPECT_EQ(Hash_SHA256(&msg[0], msg_length, &hash[0]), CHIP_NO_ERROR); P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256ECDSASignature signature; CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(msg, msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_NO_ERROR); + EXPECT_EQ(signing_error, CHIP_NO_ERROR); signature.Bytes()[0] = static_cast(~signature.ConstBytes()[0]); // Flipping bits should invalidate the signature. CHIP_ERROR validation_error = keypair.Pubkey().ECDSA_validate_hash_signature(hash, sizeof(hash), signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_ERROR_INVALID_SIGNATURE); + EXPECT_EQ(validation_error, CHIP_ERROR_INVALID_SIGNATURE); } -static void TestECDSA_SigningMsgInvalidParams(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_SigningMsgInvalidParams) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const uint8_t * msg = reinterpret_cast("Hello World!"); size_t msg_length = strlen(reinterpret_cast(msg)); P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256ECDSASignature signature; CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(nullptr, msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(signing_error, CHIP_ERROR_INVALID_ARGUMENT); signing_error = CHIP_NO_ERROR; signing_error = keypair.ECDSA_sign_msg(msg, 0, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(signing_error, CHIP_ERROR_INVALID_ARGUMENT); signing_error = CHIP_NO_ERROR; } -static void TestECDSA_ValidationMsgInvalidParam(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_ValidationMsgInvalidParam) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const char * msg = "Hello World!"; size_t msg_length = strlen(msg); P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256ECDSASignature signature; CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(reinterpret_cast(msg), msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_NO_ERROR); + EXPECT_EQ(signing_error, CHIP_NO_ERROR); CHIP_ERROR validation_error = keypair.Pubkey().ECDSA_validate_msg_signature(nullptr, msg_length, signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(validation_error, CHIP_ERROR_INVALID_ARGUMENT); validation_error = CHIP_NO_ERROR; validation_error = keypair.Pubkey().ECDSA_validate_msg_signature(reinterpret_cast(msg), 0, signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(validation_error, CHIP_ERROR_INVALID_ARGUMENT); validation_error = CHIP_NO_ERROR; } -static void TestECDSA_ValidationHashInvalidParam(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDSA_ValidationHashInvalidParam) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; const uint8_t msg[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }; size_t msg_length = sizeof(msg); uint8_t hash[Crypto::kSHA256_Hash_Length]; - NL_TEST_ASSERT(inSuite, Hash_SHA256(&msg[0], msg_length, &hash[0]) == CHIP_NO_ERROR); + EXPECT_EQ(Hash_SHA256(&msg[0], msg_length, &hash[0]), CHIP_NO_ERROR); P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256ECDSASignature signature; CHIP_ERROR signing_error = keypair.ECDSA_sign_msg(msg, msg_length, signature); - NL_TEST_ASSERT(inSuite, signing_error == CHIP_NO_ERROR); + EXPECT_EQ(signing_error, CHIP_NO_ERROR); CHIP_ERROR validation_error = keypair.Pubkey().ECDSA_validate_hash_signature(nullptr, sizeof(hash), signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(validation_error, CHIP_ERROR_INVALID_ARGUMENT); signing_error = CHIP_NO_ERROR; validation_error = keypair.Pubkey().ECDSA_validate_hash_signature(hash, sizeof(hash) - 5, signature); - NL_TEST_ASSERT(inSuite, validation_error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(validation_error, CHIP_ERROR_INVALID_ARGUMENT); signing_error = CHIP_NO_ERROR; } -static void TestECDH_EstablishSecret(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestECDH_EstablishSecret) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; Test_P256Keypair keypair1; - NL_TEST_ASSERT(inSuite, keypair1.Initialize(ECPKeyTarget::ECDH) == CHIP_NO_ERROR); + EXPECT_EQ(keypair1.Initialize(ECPKeyTarget::ECDH), CHIP_NO_ERROR); Test_P256Keypair keypair2; - NL_TEST_ASSERT(inSuite, keypair2.Initialize(ECPKeyTarget::ECDH) == CHIP_NO_ERROR); + EXPECT_EQ(keypair2.Initialize(ECPKeyTarget::ECDH), CHIP_NO_ERROR); P256ECDHDerivedSecret out_secret1; out_secret1.Bytes()[0] = 0; @@ -1226,66 +1239,53 @@ static void TestECDH_EstablishSecret(nlTestSuite * inSuite, void * inContext) out_secret2.Bytes()[0] = 1; CHIP_ERROR error = CHIP_NO_ERROR; - NL_TEST_ASSERT(inSuite, - memcmp(out_secret1.ConstBytes(), out_secret2.ConstBytes(), out_secret1.Capacity()) != - 0); // Validate that buffers are indeed different. + EXPECT_NE(memcmp(out_secret1.ConstBytes(), out_secret2.ConstBytes(), out_secret1.Capacity()), + 0); // Validate that buffers are indeed different. error = keypair2.ECDH_derive_secret(keypair1.Pubkey(), out_secret1); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = keypair1.ECDH_derive_secret(keypair2.Pubkey(), out_secret2); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); bool signature_lengths_match = out_secret1.Length() == out_secret2.Length(); - NL_TEST_ASSERT(inSuite, signature_lengths_match); + EXPECT_TRUE(signature_lengths_match); bool signatures_match = (memcmp(out_secret1.ConstBytes(), out_secret2.ConstBytes(), out_secret1.Length()) == 0); - NL_TEST_ASSERT(inSuite, signatures_match); + EXPECT_TRUE(signatures_match); } #if CHIP_CRYPTO_OPENSSL -static void TestAddEntropySources(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAddEntropySources) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR error = add_entropy_source(test_entropy_source, nullptr, 10); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); uint8_t buffer[5]; - NL_TEST_ASSERT(inSuite, DRBG_get_bytes(buffer, sizeof(buffer)) == CHIP_NO_ERROR); + EXPECT_EQ(DRBG_get_bytes(buffer, sizeof(buffer)), CHIP_NO_ERROR); } #endif #if CHIP_CRYPTO_MBEDTLS -static void TestAddEntropySources(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAddEntropySources) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR error = add_entropy_source(test_entropy_source, nullptr, 10); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); uint8_t buffer[5]; uint32_t test_entropy_source_call_count = gs_test_entropy_source_called; - NL_TEST_ASSERT(inSuite, DRBG_get_bytes(buffer, sizeof(buffer)) == CHIP_NO_ERROR); + EXPECT_EQ(DRBG_get_bytes(buffer, sizeof(buffer)), CHIP_NO_ERROR); for (int i = 0; i < 5000 * 2; i++) { (void) DRBG_get_bytes(buffer, sizeof(buffer)); } - NL_TEST_ASSERT(inSuite, gs_test_entropy_source_called > test_entropy_source_call_count); + EXPECT_GT(gs_test_entropy_source_called, test_entropy_source_call_count); } #endif -#if CHIP_CRYPTO_PSA -static void TestAddEntropySources(nlTestSuite * inSuite, void * inContext) {} -#endif - -#if CHIP_CRYPTO_BORINGSSL -static void TestAddEntropySources(nlTestSuite * inSuite, void * inContext) {} -#endif - -#if CHIP_CRYPTO_PLATFORM -static void TestAddEntropySources(nlTestSuite * inSuite, void * inContext) {} -#endif - -static void TestPBKDF2_SHA256_TestVectors(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestPBKDF2_SHA256_TestVectors) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestVectors = ArraySize(pbkdf2_sha256_test_vectors); int numOfTestsRan = 0; TestPBKDF2_sha256 pbkdf1; @@ -1297,37 +1297,37 @@ static void TestPBKDF2_SHA256_TestVectors(nlTestSuite * inSuite, void * inContex numOfTestsRan++; chip::Platform::ScopedMemoryBuffer out_key; out_key.Alloc(vector->key_len); - NL_TEST_ASSERT(inSuite, out_key); + EXPECT_TRUE(out_key); CHIP_ERROR err = pbkdf1.pbkdf2_sha256(vector->password, vector->plen, vector->salt, vector->slen, vector->iter, vector->key_len, out_key.Get()); - NL_TEST_ASSERT(inSuite, err == vector->result); + EXPECT_EQ(err, vector->result); if (vector->result == CHIP_NO_ERROR) { - NL_TEST_ASSERT(inSuite, memcmp(out_key.Get(), vector->key, vector->key_len) == 0); + EXPECT_EQ(memcmp(out_key.Get(), vector->key, vector->key_len), 0); } } } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); + EXPECT_GT(numOfTestsRan, 0); } -static void TestP256_Keygen(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestP256_Keygen) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); const char * msg = "Test Message for Keygen"; const uint8_t * test_msg = Uint8::from_const_char(msg); size_t msglen = strlen(msg); P256ECDSASignature test_sig; - NL_TEST_ASSERT(inSuite, keypair.ECDSA_sign_msg(test_msg, msglen, test_sig) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, keypair.Pubkey().ECDSA_validate_msg_signature(test_msg, msglen, test_sig) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.ECDSA_sign_msg(test_msg, msglen, test_sig), CHIP_NO_ERROR); + EXPECT_EQ(keypair.Pubkey().ECDSA_validate_msg_signature(test_msg, msglen, test_sig), CHIP_NO_ERROR); } -void TestCSR_Verify(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestCSR_Verify) { Crypto::P256PublicKey pubKey; CHIP_ERROR err; @@ -1361,10 +1361,10 @@ void TestCSR_Verify(nlTestSuite * inSuite, void * inContext) return; } - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); err = VerifyCertificateSigningRequestFormat(&kBadTrailingGarbageCsr[0], sizeof(kBadTrailingGarbageCsr)); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); + EXPECT_EQ(err, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); } // Second case: correct CSR @@ -1392,13 +1392,13 @@ void TestCSR_Verify(nlTestSuite * inSuite, void * inContext) Crypto::ClearSecretData(pubKey.Bytes(), pubKey.Length()); err = VerifyCertificateSigningRequestFormat(&kGoodCsr[0], sizeof(kGoodCsr)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = VerifyCertificateSigningRequest(&kGoodCsr[0], sizeof(kGoodCsr), pubKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); Crypto::P256PublicKey expected(kGoodCsrSubjectPublicKey); - NL_TEST_ASSERT(inSuite, pubKey.Matches(expected)); + EXPECT_TRUE(pubKey.Matches(expected)); } // Third case: bad signature @@ -1420,10 +1420,10 @@ void TestCSR_Verify(nlTestSuite * inSuite, void * inContext) Crypto::ClearSecretData(pubKey.Bytes(), pubKey.Length()); err = VerifyCertificateSigningRequestFormat(&kBadSignatureSignatureCsr[0], sizeof(kBadSignatureSignatureCsr)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = VerifyCertificateSigningRequest(&kBadSignatureSignatureCsr[0], sizeof(kBadSignatureSignatureCsr), pubKey); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } // Fourth case: CSR too big @@ -1446,10 +1446,10 @@ void TestCSR_Verify(nlTestSuite * inSuite, void * inContext) Crypto::ClearSecretData(pubKey.Bytes(), pubKey.Length()); err = VerifyCertificateSigningRequestFormat(&kBadTooBigCsr[0], sizeof(kBadTooBigCsr)); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); + EXPECT_EQ(err, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); err = VerifyCertificateSigningRequest(&kBadTooBigCsr[0], sizeof(kBadTooBigCsr), pubKey); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } // Fifth case: obviously invalid CSR (1/2) @@ -1461,10 +1461,10 @@ void TestCSR_Verify(nlTestSuite * inSuite, void * inContext) Crypto::ClearSecretData(pubKey.Bytes(), pubKey.Length()); err = VerifyCertificateSigningRequestFormat(&kTooSmallCsr[0], sizeof(kTooSmallCsr)); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); + EXPECT_EQ(err, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); err = VerifyCertificateSigningRequest(&kTooSmallCsr[0], sizeof(kTooSmallCsr), pubKey); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } // Sixth case: obviously invalid CSR (2/2) @@ -1486,14 +1486,14 @@ void TestCSR_Verify(nlTestSuite * inSuite, void * inContext) Crypto::ClearSecretData(pubKey.Bytes(), pubKey.Length()); err = VerifyCertificateSigningRequestFormat(&kNotSequenceCsr[0], sizeof(kNotSequenceCsr)); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); + EXPECT_EQ(err, CHIP_ERROR_UNSUPPORTED_CERT_FORMAT); err = VerifyCertificateSigningRequest(&kNotSequenceCsr[0], sizeof(kNotSequenceCsr), pubKey); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } } -void TestCSR_GenDirect(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestCSR_GenDirect) { uint8_t csrBuf[kMIN_CSR_Buffer_Size]; ClearSecretData(csrBuf); @@ -1501,35 +1501,35 @@ void TestCSR_GenDirect(nlTestSuite * inSuite, void * inContext) Test_P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); // Validate case of buffer too small uint8_t csrBufTooSmall[kMIN_CSR_Buffer_Size - 1]; MutableByteSpan csrSpanTooSmall(csrBufTooSmall); - NL_TEST_ASSERT(inSuite, GenerateCertificateSigningRequest(&keypair, csrSpanTooSmall) == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(GenerateCertificateSigningRequest(&keypair, csrSpanTooSmall), CHIP_ERROR_BUFFER_TOO_SMALL); // Validate case of null keypair - NL_TEST_ASSERT(inSuite, GenerateCertificateSigningRequest(nullptr, csrSpan) == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(GenerateCertificateSigningRequest(nullptr, csrSpan), CHIP_ERROR_INVALID_ARGUMENT); // Validate normal case ClearSecretData(csrBuf); - NL_TEST_ASSERT(inSuite, GenerateCertificateSigningRequest(&keypair, csrSpan) == CHIP_NO_ERROR); + EXPECT_EQ(GenerateCertificateSigningRequest(&keypair, csrSpan), CHIP_NO_ERROR); P256PublicKey pubkey; CHIP_ERROR err = VerifyCertificateSigningRequest(csrSpan.data(), csrSpan.size(), pubkey); if (err != CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE) { - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, pubkey.Length() == kP256_PublicKey_Length); - NL_TEST_ASSERT(inSuite, memcmp(pubkey.ConstBytes(), keypair.Pubkey().ConstBytes(), pubkey.Length()) == 0); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(pubkey.Length(), kP256_PublicKey_Length); + EXPECT_EQ(memcmp(pubkey.ConstBytes(), keypair.Pubkey().ConstBytes(), pubkey.Length()), 0); // Let's corrupt the CSR buffer and make sure it fails to verify size_t length = csrSpan.size(); csrBuf[length - 2] = (uint8_t) (csrBuf[length - 2] + 1); csrBuf[length - 1] = (uint8_t) (csrBuf[length - 1] + 1); - NL_TEST_ASSERT(inSuite, VerifyCertificateSigningRequest(csrSpan.data(), csrSpan.size(), pubkey) != CHIP_NO_ERROR); + EXPECT_NE(VerifyCertificateSigningRequest(csrSpan.data(), csrSpan.size(), pubkey), CHIP_NO_ERROR); } else { @@ -1537,30 +1537,30 @@ void TestCSR_GenDirect(nlTestSuite * inSuite, void * inContext) } } -static void TestCSR_GenByKeypair(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestCSR_GenByKeypair) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; uint8_t csr[kMIN_CSR_Buffer_Size]; size_t length = sizeof(csr); Test_P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, keypair.NewCertificateSigningRequest(csr, length) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, length > 0); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); + EXPECT_EQ(keypair.NewCertificateSigningRequest(csr, length), CHIP_NO_ERROR); + EXPECT_GT(length, 0u); P256PublicKey pubkey; CHIP_ERROR err = VerifyCertificateSigningRequest(csr, length, pubkey); if (err != CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE) { - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, pubkey.Length() == kP256_PublicKey_Length); - NL_TEST_ASSERT(inSuite, memcmp(pubkey.ConstBytes(), keypair.Pubkey().ConstBytes(), pubkey.Length()) == 0); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(pubkey.Length(), kP256_PublicKey_Length); + EXPECT_EQ(memcmp(pubkey.ConstBytes(), keypair.Pubkey().ConstBytes(), pubkey.Length()), 0); // Let's corrupt the CSR buffer and make sure it fails to verify csr[length - 2] = (uint8_t) (csr[length - 2] + 1); csr[length - 1] = (uint8_t) (csr[length - 1] + 1); - NL_TEST_ASSERT(inSuite, VerifyCertificateSigningRequest(csr, length, pubkey) != CHIP_NO_ERROR); + EXPECT_NE(VerifyCertificateSigningRequest(csr, length, pubkey), CHIP_NO_ERROR); } else { @@ -1568,34 +1568,34 @@ static void TestCSR_GenByKeypair(nlTestSuite * inSuite, void * inContext) } } -static void TestKeypair_Serialize(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestKeypair_Serialize) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; Test_P256Keypair keypair; - NL_TEST_ASSERT(inSuite, keypair.Initialize(ECPKeyTarget::ECDSA) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Initialize(ECPKeyTarget::ECDSA), CHIP_NO_ERROR); P256SerializedKeypair serialized; - NL_TEST_ASSERT(inSuite, keypair.Serialize(serialized) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.Serialize(serialized), CHIP_NO_ERROR); Test_P256Keypair keypair_dup; - NL_TEST_ASSERT(inSuite, keypair_dup.Deserialize(serialized) == CHIP_NO_ERROR); + EXPECT_EQ(keypair_dup.Deserialize(serialized), CHIP_NO_ERROR); const char * msg = "Test Message for Keygen"; const uint8_t * test_msg = Uint8::from_const_char(msg); size_t msglen = strlen(msg); P256ECDSASignature test_sig; - NL_TEST_ASSERT(inSuite, keypair.ECDSA_sign_msg(test_msg, msglen, test_sig) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, keypair_dup.Pubkey().ECDSA_validate_msg_signature(test_msg, msglen, test_sig) == CHIP_NO_ERROR); + EXPECT_EQ(keypair.ECDSA_sign_msg(test_msg, msglen, test_sig), CHIP_NO_ERROR); + EXPECT_EQ(keypair_dup.Pubkey().ECDSA_validate_msg_signature(test_msg, msglen, test_sig), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, keypair_dup.ECDSA_sign_msg(test_msg, msglen, test_sig) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, keypair.Pubkey().ECDSA_validate_msg_signature(test_msg, msglen, test_sig) == CHIP_NO_ERROR); + EXPECT_EQ(keypair_dup.ECDSA_sign_msg(test_msg, msglen, test_sig), CHIP_NO_ERROR); + EXPECT_EQ(keypair.Pubkey().ECDSA_validate_msg_signature(test_msg, msglen, test_sig), CHIP_NO_ERROR); } -static void TestSPAKE2P_spake2p_FEMul(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_spake2p_FEMul) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; uint8_t fe_out[kMAX_FE_Length]; int numOfTestVectors = ArraySize(fe_mul_tvs); @@ -1607,30 +1607,30 @@ static void TestSPAKE2P_spake2p_FEMul(nlTestSuite * inSuite, void * inContext) TestSpake2p_P256_SHA256_HKDF_HMAC spake2p; CHIP_ERROR err = spake2p.Init(nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FELoad(vector->fe1, vector->fe1_len, spake2p.w0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FELoad(vector->fe2, vector->fe2_len, spake2p.w1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FEMul(spake2p.xy, spake2p.w0, spake2p.w1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FEWrite(spake2p.xy, fe_out, sizeof(fe_out)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(fe_out, vector->fe_out, vector->fe_out_len) == 0); + EXPECT_EQ(memcmp(fe_out, vector->fe_out, vector->fe_out_len), 0); numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } -static void TestSPAKE2P_spake2p_FELoadWrite(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_spake2p_FELoadWrite) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; uint8_t fe_out[kMAX_FE_Length]; int numOfTestVectors = ArraySize(fe_rw_tvs); @@ -1642,24 +1642,24 @@ static void TestSPAKE2P_spake2p_FELoadWrite(nlTestSuite * inSuite, void * inCont TestSpake2p_P256_SHA256_HKDF_HMAC spake2p; CHIP_ERROR err = spake2p.Init(nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FELoad(vector->fe_in, vector->fe_in_len, spake2p.w0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FEWrite(spake2p.w0, fe_out, sizeof(fe_out)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(fe_out, vector->fe_out, vector->fe_out_len) == 0); + EXPECT_EQ(memcmp(fe_out, vector->fe_out, vector->fe_out_len), 0); numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } -static void TestSPAKE2P_spake2p_Mac(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_spake2p_Mac) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; uint8_t mac[kMAX_Hash_Length]; MutableByteSpan mac_span{ mac }; @@ -1672,25 +1672,25 @@ static void TestSPAKE2P_spake2p_Mac(nlTestSuite * inSuite, void * inContext) TestSpake2p_P256_SHA256_HKDF_HMAC spake2p; CHIP_ERROR err = spake2p.Init(nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.Mac(vector->key, vector->key_len, vector->input, vector->input_len, mac_span); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(mac_span.data(), vector->output, vector->output_len) == 0); + EXPECT_EQ(memcmp(mac_span.data(), vector->output, vector->output_len), 0); err = spake2p.MacVerify(vector->key, vector->key_len, vector->output, vector->output_len, vector->input, vector->input_len); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } -static void TestSPAKE2P_spake2p_PointMul(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_spake2p_PointMul) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; uint8_t output[kMAX_Point_Length]; size_t out_len = sizeof(output); @@ -1704,31 +1704,31 @@ static void TestSPAKE2P_spake2p_PointMul(nlTestSuite * inSuite, void * inContext TestSpake2p_P256_SHA256_HKDF_HMAC spake2p; CHIP_ERROR err = spake2p.Init(nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointLoad(vector->point, vector->point_len, spake2p.L); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FELoad(vector->scalar, vector->scalar_len, spake2p.w0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointMul(spake2p.X, spake2p.L, spake2p.w0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointWrite(spake2p.X, output, out_len); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(output, vector->out_point, vector->out_point_len) == 0); + EXPECT_EQ(memcmp(output, vector->out_point, vector->out_point_len), 0); numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } -static void TestSPAKE2P_spake2p_PointMulAdd(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_spake2p_PointMulAdd) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; uint8_t output[kMAX_Point_Length]; size_t out_len = sizeof(output); @@ -1742,37 +1742,37 @@ static void TestSPAKE2P_spake2p_PointMulAdd(nlTestSuite * inSuite, void * inCont TestSpake2p_P256_SHA256_HKDF_HMAC spake2p; CHIP_ERROR err = spake2p.Init(nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointLoad(vector->point1, vector->point1_len, spake2p.X); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointLoad(vector->point2, vector->point2_len, spake2p.Y); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FELoad(vector->scalar1, vector->scalar1_len, spake2p.w0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.FELoad(vector->scalar2, vector->scalar2_len, spake2p.w1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointAddMul(spake2p.L, spake2p.X, spake2p.w0, spake2p.Y, spake2p.w1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointWrite(spake2p.L, output, out_len); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(output, vector->out_point, vector->out_point_len) == 0); + EXPECT_EQ(memcmp(output, vector->out_point, vector->out_point_len), 0); numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } -static void TestSPAKE2P_spake2p_PointLoadWrite(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_spake2p_PointLoadWrite) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; uint8_t output[kMAX_Point_Length]; size_t out_len = sizeof(output); @@ -1786,25 +1786,25 @@ static void TestSPAKE2P_spake2p_PointLoadWrite(nlTestSuite * inSuite, void * inC TestSpake2p_P256_SHA256_HKDF_HMAC spake2p; CHIP_ERROR err = spake2p.Init(nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointLoad(vector->point, vector->point_len, spake2p.L); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointWrite(spake2p.L, output, out_len); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(output, vector->point, vector->point_len) == 0); + EXPECT_EQ(memcmp(output, vector->point, vector->point_len), 0); numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } -static void TestSPAKE2P_spake2p_PointIsValid(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_spake2p_PointIsValid) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; int numOfTestVectors = ArraySize(point_valid_tvs); int numOfTestsRan = 0; for (int vectorIndex = 0; vectorIndex < numOfTestVectors; vectorIndex++) @@ -1814,19 +1814,19 @@ static void TestSPAKE2P_spake2p_PointIsValid(nlTestSuite * inSuite, void * inCon TestSpake2p_P256_SHA256_HKDF_HMAC spake2p; CHIP_ERROR err = spake2p.Init(nullptr, 0); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = spake2p.PointLoad(vector->point, vector->point_len, spake2p.L); // The underlying implementation may (i.e. should) check for validity when loading a point. Let's catch this case. - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR || vector->valid == 0); + EXPECT_TRUE(err == CHIP_NO_ERROR || vector->valid == 0); err = spake2p.PointIsValid(spake2p.L); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR || vector->valid == 0); + EXPECT_TRUE(err == CHIP_NO_ERROR || vector->valid == 0); numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } // We need to "generate" specific field elements @@ -1852,9 +1852,9 @@ class Test_Spake2p_P256_SHA256_HKDF_HMAC : public Spake2p_P256_SHA256_HKDF_HMAC size_t fe_len; }; -static void TestSPAKE2P_RFC(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_RFC) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR error = CHIP_NO_ERROR; uint8_t L[kMAX_Point_Length]; size_t L_len = sizeof(L); @@ -1885,103 +1885,103 @@ static void TestSPAKE2P_RFC(nlTestSuite * inSuite, void * inContext) // First start the prover error = Prover.Init(vector->context, vector->context_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = Prover.BeginProver(vector->prover_identity, vector->prover_identity_len, vector->verifier_identity, vector->verifier_identity_len, vector->w0, vector->w0_len, vector->w1, vector->w1_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Monkey patch the generated x coordinate error = Prover.TestSetFE(vector->x, vector->x_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Compute the first round and send it to the verifier X_len = sizeof(X); error = Prover.ComputeRoundOne(nullptr, 0, X, &X_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, X_len == vector->X_len); - NL_TEST_ASSERT(inSuite, memcmp(X, vector->X, vector->X_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(X_len, vector->X_len); + EXPECT_EQ(memcmp(X, vector->X, vector->X_len), 0); // Start up the verifier error = Verifier.Init(vector->context, vector->context_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // First pre-compute L (accessories with dynamic setup codes will do this) L_len = sizeof(L); error = Verifier.ComputeL(L, &L_len, vector->w1, vector->w1_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, L_len == vector->L_len); - NL_TEST_ASSERT(inSuite, memcmp(L, vector->L, vector->L_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(L_len, vector->L_len); + EXPECT_EQ(memcmp(L, vector->L, vector->L_len), 0); // Start up the verifier error = Verifier.BeginVerifier(vector->verifier_identity, vector->verifier_identity_len, vector->prover_identity, vector->prover_identity_len, vector->w0, vector->w0_len, L, L_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Monkey patch the generated y coordinate error = Verifier.TestSetFE(vector->y, vector->y_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Compute the first round and send it to the prover Y_len = sizeof(Y); error = Verifier.ComputeRoundOne(X, X_len, Y, &Y_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, Y_len == vector->Y_len); - NL_TEST_ASSERT(inSuite, memcmp(Y, vector->Y, vector->Y_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(Y_len, vector->Y_len); + EXPECT_EQ(memcmp(Y, vector->Y, vector->Y_len), 0); // Compute the second round to also send to the prover Vverifier_len = sizeof(Vverifier); error = Verifier.ComputeRoundTwo(X, X_len, Vverifier, &Vverifier_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, Vverifier_len == vector->MAC_KcB_len); - NL_TEST_ASSERT(inSuite, memcmp(Vverifier, vector->MAC_KcB, vector->MAC_KcB_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(Vverifier_len, vector->MAC_KcB_len); + EXPECT_EQ(memcmp(Vverifier, vector->MAC_KcB, vector->MAC_KcB_len), 0); error = Verifier.PointWrite(Verifier.Z, Z, kP256_Point_Length); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(Z, vector->Z, vector->Z_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(memcmp(Z, vector->Z, vector->Z_len), 0); error = Verifier.PointWrite(Verifier.V, V, kP256_Point_Length); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(V, vector->V, vector->V_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(memcmp(V, vector->V, vector->V_len), 0); // Now the prover computes round 2 Pverifier_len = sizeof(Pverifier); error = Prover.ComputeRoundTwo(Y, Y_len, Pverifier, &Pverifier_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, Pverifier_len == vector->MAC_KcA_len); - NL_TEST_ASSERT(inSuite, memcmp(Pverifier, vector->MAC_KcA, vector->MAC_KcA_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(Pverifier_len, vector->MAC_KcA_len); + EXPECT_EQ(memcmp(Pverifier, vector->MAC_KcA, vector->MAC_KcA_len), 0); error = Prover.PointWrite(Verifier.Z, Z, kP256_Point_Length); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(Z, vector->Z, vector->Z_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(memcmp(Z, vector->Z, vector->Z_len), 0); error = Prover.PointWrite(Verifier.V, V, kP256_Point_Length); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(V, vector->V, vector->V_len) == 0); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(memcmp(V, vector->V, vector->V_len), 0); // Both sides now confirm the keys they received error = Prover.KeyConfirm(Vverifier, Vverifier_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); error = Verifier.KeyConfirm(Pverifier, Pverifier_len); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Import HKDF key from the test vector to the keystore HkdfKeyHandle vectorKe; error = keystore.CreateKey(ByteSpan(vector->Ke, vector->Ke_len), vectorKe); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); + EXPECT_EQ(error, CHIP_NO_ERROR); // Verify that both sides generated the same HKDF key as in the test vector // Since the HKDF keys may not be availabe in the raw form, do not compare them directly, // but rather check if the same attestation challenge is derived from HkdfKeyHandle PKe; error = Prover.GetKeys(keystore, PKe); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - AssertKeysEqual(inSuite, keystore, PKe, vectorKe); + EXPECT_EQ(error, CHIP_NO_ERROR); + AssertKeysEqual(keystore, PKe, vectorKe); HkdfKeyHandle VKe; error = Verifier.GetKeys(keystore, VKe); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - AssertKeysEqual(inSuite, keystore, VKe, vectorKe); + EXPECT_EQ(error, CHIP_NO_ERROR); + AssertKeysEqual(keystore, VKe, vectorKe); keystore.DestroyKey(vectorKe); keystore.DestroyKey(PKe); @@ -1989,27 +1989,27 @@ static void TestSPAKE2P_RFC(nlTestSuite * inSuite, void * inContext) numOfTestsRan += 1; } - NL_TEST_ASSERT(inSuite, numOfTestsRan > 0); - NL_TEST_ASSERT(inSuite, numOfTestsRan == numOfTestVectors); + EXPECT_GT(numOfTestsRan, 0); + EXPECT_EQ(numOfTestsRan, numOfTestVectors); } -static void TestSPAKE2P_Reuse(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSPAKE2P_Reuse) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; Test_Spake2p_P256_SHA256_HKDF_HMAC spake2; // Veriy Init -> Clear -> Init sequence works and does not leak memory - NL_TEST_ASSERT(inSuite, spake2.Init(nullptr, 0) == CHIP_NO_ERROR); + EXPECT_EQ(spake2.Init(nullptr, 0), CHIP_NO_ERROR); spake2.Clear(); - NL_TEST_ASSERT(inSuite, spake2.Init(nullptr, 0) == CHIP_NO_ERROR); + EXPECT_EQ(spake2.Init(nullptr, 0), CHIP_NO_ERROR); // Even without an explicit Clear, Init does not leak memory - NL_TEST_ASSERT(inSuite, spake2.Init(nullptr, 0) == CHIP_NO_ERROR); + EXPECT_EQ(spake2.Init(nullptr, 0), CHIP_NO_ERROR); } -static void TestCompressedFabricIdentifier(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestCompressedFabricIdentifier) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; // Data from spec test vector (see Operational Discovery section) const uint8_t kRootPublicKey[] = { 0x04, 0x4a, 0x9f, 0x42, 0xb1, 0xca, 0x48, 0x40, 0xd3, 0x72, 0x92, 0xbb, 0xc7, 0xf6, 0xa7, 0xe1, 0x1e, @@ -2034,12 +2034,11 @@ static void TestCompressedFabricIdentifier(nlTestSuite * inSuite, void * inConte uint64_t compressed_fabric_id_int; CHIP_ERROR error = GenerateCompressedFabricId(root_public_key, kFabricId, compressed_fabric_id_span); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, compressed_fabric_id_span.size() == kCompressedFabricIdentifierSize); - NL_TEST_ASSERT(inSuite, - 0 == - memcmp(compressed_fabric_id_span.data(), kExpectedCompressedFabricIdentifier, - sizeof(kExpectedCompressedFabricIdentifier))); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(compressed_fabric_id_span.size(), kCompressedFabricIdentifierSize); + EXPECT_EQ( + 0, + memcmp(compressed_fabric_id_span.data(), kExpectedCompressedFabricIdentifier, sizeof(kExpectedCompressedFabricIdentifier))); // Test bigger input buffer than needed uint8_t compressed_fabric_id_large[3 * kCompressedFabricIdentifierSize]; @@ -2047,22 +2046,21 @@ static void TestCompressedFabricIdentifier(nlTestSuite * inSuite, void * inConte ClearSecretData(compressed_fabric_id_large, sizeof(compressed_fabric_id_large)); error = GenerateCompressedFabricId(root_public_key, kFabricId, compressed_fabric_id_large_span); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, compressed_fabric_id_large_span.size() == kCompressedFabricIdentifierSize); - NL_TEST_ASSERT(inSuite, - 0 == - memcmp(compressed_fabric_id_large_span.data(), kExpectedCompressedFabricIdentifier, - sizeof(kExpectedCompressedFabricIdentifier))); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(compressed_fabric_id_large_span.size(), kCompressedFabricIdentifierSize); + EXPECT_EQ(0, + memcmp(compressed_fabric_id_large_span.data(), kExpectedCompressedFabricIdentifier, + sizeof(kExpectedCompressedFabricIdentifier))); // Test smaller buffer than needed MutableByteSpan compressed_fabric_id_small_span(compressed_fabric_id, kCompressedFabricIdentifierSize - 1); error = GenerateCompressedFabricId(root_public_key, kFabricId, compressed_fabric_id_small_span); - NL_TEST_ASSERT(inSuite, error == CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(error, CHIP_ERROR_BUFFER_TOO_SMALL); // Test overload that writes to an integer output type. error = GenerateCompressedFabricId(root_public_key, kFabricId, compressed_fabric_id_int); - NL_TEST_ASSERT(inSuite, error == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, compressed_fabric_id_int == kExpectedCompressedFabricIdentifierInt); + EXPECT_EQ(error, CHIP_NO_ERROR); + EXPECT_EQ(compressed_fabric_id_int, kExpectedCompressedFabricIdentifierInt); // Test invalid public key const uint8_t kInvalidRootPublicKey[] = { @@ -2074,14 +2072,14 @@ static void TestCompressedFabricIdentifier(nlTestSuite * inSuite, void * inConte P256PublicKey invalid_root_public_key(kInvalidRootPublicKey); error = GenerateCompressedFabricId(invalid_root_public_key, kFabricId, compressed_fabric_id_span); - NL_TEST_ASSERT(inSuite, error == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(error, CHIP_ERROR_INVALID_ARGUMENT); } -static void TestPubkey_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestPubkey_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; P256PublicKey publicKey; @@ -2093,22 +2091,22 @@ static void TestPubkey_x509Extraction(nlTestSuite * inSuite, void * inContext) TestCert certType = TestCerts::gTestCerts[i]; err = GetTestCert(certType, TestCertLoadFlags::kDERForm, cert); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = GetTestCertPubkey(certType, pubkeySpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = ExtractPubkeyFromX509Cert(cert, publicKey); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, publicKey.Length() == pubkeySpan.size()); - NL_TEST_ASSERT(inSuite, memcmp(publicKey.ConstBytes(), pubkeySpan.data(), pubkeySpan.size()) == 0); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(publicKey.Length(), pubkeySpan.size()); + EXPECT_EQ(memcmp(publicKey.ConstBytes(), pubkeySpan.data(), pubkeySpan.size()), 0); } } -static void TestX509_VerifyAttestationCertificateFormat(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestX509_VerifyAttestationCertificateFormat) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; struct ValidationTestCase { @@ -2145,16 +2143,16 @@ static void TestX509_VerifyAttestationCertificateFormat(nlTestSuite * inSuite, v ChipLogError(Crypto, "Failed TestX509_VerifyAttestationCertificateFormat sub-case %d, err: %" CHIP_ERROR_FORMAT, case_idx, err.Format()); } - NL_TEST_ASSERT(inSuite, err == testCase.expectedError); + EXPECT_EQ(err, testCase.expectedError); ++case_idx; } } -static void TestX509_CertChainValidation(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestX509_CertChainValidation) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; struct ValidationTestCase @@ -2208,17 +2206,17 @@ static void TestX509_CertChainValidation(nlTestSuite * inSuite, void * inContext CertificateChainValidationResult chainValidationResult; err = ValidateCertificateChain(testCase.root.data(), testCase.root.size(), testCase.ica.data(), testCase.ica.size(), testCase.leaf.data(), testCase.leaf.size(), chainValidationResult); - NL_TEST_ASSERT(inSuite, err == testCase.expectedError); - NL_TEST_ASSERT(inSuite, chainValidationResult == testCase.expectedValResult); + EXPECT_EQ(err, testCase.expectedError); + EXPECT_EQ(chainValidationResult, testCase.expectedValResult); } } -static void TestX509_IssuingTimestampValidation(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestX509_IssuingTimestampValidation) { using namespace TestCerts; using namespace ASN1; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; struct ValidationTestCase @@ -2254,21 +2252,21 @@ static void TestX509_IssuingTimestampValidation(nlTestSuite * inSuite, void * in for (auto & testCase : sValidationTestCases) { err = IsCertificateValidAtIssuance(testCase.refCert, testCase.evaluatedCert); - NL_TEST_ASSERT(inSuite, err == testCase.expectedError); + EXPECT_EQ(err, testCase.expectedError); } #if !defined(CURRENT_TIME_NOT_IMPLEMENTED) // test certificate validity (this one contains validity until year 9999 so it will not fail soon) err = IsCertificateValidAtCurrentTime(sTestCert_DAC_FFF2_8001_0008_Cert); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); #endif } -static void TestSKID_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSKID_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; uint8_t skidBuf[kSubjectKeyIdentifierLength]; MutableByteSpan skidOut(skidBuf); @@ -2281,28 +2279,28 @@ static void TestSKID_x509Extraction(nlTestSuite * inSuite, void * inContext) TestCert certType = gTestCerts[i]; err = GetTestCert(certType, TestCertLoadFlags::kDERForm, cert); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = GetTestCertSKID(certType, skidSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = ExtractSKIDFromX509Cert(cert, skidOut); if (!skidSpan.empty()) { - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, skidSpan.data_equal(skidOut)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(skidSpan.data_equal(skidOut)); } else { - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_NOT_FOUND); } } } -static void TestAKID_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestAKID_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; uint8_t akidBuf[kAuthorityKeyIdentifierLength]; MutableByteSpan akidOut(akidBuf); @@ -2315,28 +2313,28 @@ static void TestAKID_x509Extraction(nlTestSuite * inSuite, void * inContext) TestCert certType = gTestCerts[i]; err = GetTestCert(certType, TestCertLoadFlags::kDERForm, cert); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = GetTestCertAKID(certType, akidSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = ExtractAKIDFromX509Cert(cert, akidOut); if (!akidSpan.empty()) { - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, akidSpan.data_equal(akidOut)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(akidSpan.data_equal(akidOut)); } else { - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_NOT_FOUND); + EXPECT_EQ(err, CHIP_ERROR_NOT_FOUND); } } } -static void TestCDPExtension_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestCDPExtension_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; struct CDPTestCase @@ -2382,20 +2380,20 @@ static void TestCDPExtension_x509Extraction(nlTestSuite * inSuite, void * inCont char cdpBuf[kMaxCRLDistributionPointURLLength] = { '\0' }; MutableCharSpan cdp(cdpBuf); err = ExtractCRLDistributionPointURIFromX509Cert(testCase.Cert, cdp); - NL_TEST_ASSERT(inSuite, err == testCase.mExpectedError); + EXPECT_EQ(err, testCase.mExpectedError); if (testCase.mExpectedError == CHIP_NO_ERROR) { - NL_TEST_ASSERT(inSuite, cdp.size() == testCase.mExpectedResult.size()); - NL_TEST_ASSERT(inSuite, cdp.data_equal(testCase.mExpectedResult)); + EXPECT_EQ(cdp.size(), testCase.mExpectedResult.size()); + EXPECT_TRUE(cdp.data_equal(testCase.mExpectedResult)); } } } -static void TestCDPCRLIssuerExtension_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestCDPCRLIssuerExtension_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; struct CDPTestCase @@ -2436,25 +2434,25 @@ static void TestCDPCRLIssuerExtension_x509Extraction(nlTestSuite * inSuite, void uint8_t crlIssuerBuf[kMaxCertificateDistinguishedNameLength] = { 0 }; MutableByteSpan crlIssuer(crlIssuerBuf); err = ExtractCDPExtensionCRLIssuerFromX509Cert(testCase.Cert, crlIssuer); - NL_TEST_ASSERT(inSuite, err == testCase.mExpectedError); + EXPECT_EQ(err, testCase.mExpectedError); if (testCase.mExpectedError == CHIP_NO_ERROR) { uint8_t crlIssuerSubjectBuf[kMaxCertificateDistinguishedNameLength] = { 0 }; MutableByteSpan crlIssuerSubject(crlIssuerSubjectBuf); err = ExtractSubjectFromX509Cert(testCase.mCRLIssuerCert, crlIssuerSubject); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, crlIssuer.data_equal(crlIssuerSubject)); + EXPECT_TRUE(crlIssuer.data_equal(crlIssuerSubject)); } } } -static void TestSerialNumber_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSerialNumber_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; struct SerialNumberTestCase @@ -2481,21 +2479,21 @@ static void TestSerialNumber_x509Extraction(nlTestSuite * inSuite, void * inCont { ByteSpan cert; err = GetTestCert(testCase.Cert, TestCertLoadFlags::kDERForm, cert); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint8_t serialNumberBuf[kMaxCertificateSerialNumberLength] = { 0 }; MutableByteSpan serialNumber(serialNumberBuf); err = ExtractSerialNumberFromX509Cert(cert, serialNumber); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, serialNumber.data_equal(testCase.mExpectedResult)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(serialNumber.data_equal(testCase.mExpectedResult)); } } -static void TestSubject_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestSubject_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; struct TestCase @@ -2505,27 +2503,25 @@ static void TestSubject_x509Extraction(nlTestSuite * inSuite, void * inContext) }; ChipDN subjectDN_Root01; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Root01.AddAttribute_MatterRCACId(0xCACACACA00000001)); + EXPECT_EQ(subjectDN_Root01.AddAttribute_MatterRCACId(0xCACACACA00000001), CHIP_NO_ERROR); ChipDN subjectDN_ICA01; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_ICA01.AddAttribute_MatterICACId(0xCACACACA00000003)); + EXPECT_EQ(subjectDN_ICA01.AddAttribute_MatterICACId(0xCACACACA00000003), CHIP_NO_ERROR); ChipDN subjectDN_Node02_02; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_02.AddAttribute_MatterNodeId(0xDEDEDEDE00020002)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_02.AddAttribute_MatterFabricId(0xFAB000000000001D)); - NL_TEST_ASSERT(inSuite, - CHIP_NO_ERROR == - subjectDN_Node02_02.AddAttribute_CommonName("TEST CERT COMMON NAME Attr for Node02_02"_span, false)); + EXPECT_EQ(subjectDN_Node02_02.AddAttribute_MatterNodeId(0xDEDEDEDE00020002), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_02.AddAttribute_MatterFabricId(0xFAB000000000001D), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_02.AddAttribute_CommonName("TEST CERT COMMON NAME Attr for Node02_02"_span, false), CHIP_NO_ERROR); ChipDN subjectDN_Node02_04; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_04.AddAttribute_MatterCASEAuthTag(0xABCE1002)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_04.AddAttribute_CommonName("TestCert02_04"_span, false)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_04.AddAttribute_MatterFabricId(0xFAB000000000001D)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_04.AddAttribute_MatterCASEAuthTag(0xABCD0003)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_04.AddAttribute_MatterNodeId(0xDEDEDEDE00020004)); + EXPECT_EQ(subjectDN_Node02_04.AddAttribute_MatterCASEAuthTag(0xABCE1002), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_04.AddAttribute_CommonName("TestCert02_04"_span, false), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_04.AddAttribute_MatterFabricId(0xFAB000000000001D), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_04.AddAttribute_MatterCASEAuthTag(0xABCD0003), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_04.AddAttribute_MatterNodeId(0xDEDEDEDE00020004), CHIP_NO_ERROR); ChipDN subjectDN_Node02_08; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_08.AddAttribute_MatterCASEAuthTag(0xABCF00A0)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_08.AddAttribute_MatterNodeId(0xDEDEDEDE00020008)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_08.AddAttribute_MatterCASEAuthTag(0xABCD0020)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_08.AddAttribute_MatterFabricId(0xFAB000000000001D)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == subjectDN_Node02_08.AddAttribute_MatterCASEAuthTag(0xABCE0100)); + EXPECT_EQ(subjectDN_Node02_08.AddAttribute_MatterCASEAuthTag(0xABCF00A0), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_08.AddAttribute_MatterNodeId(0xDEDEDEDE00020008), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_08.AddAttribute_MatterCASEAuthTag(0xABCD0020), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_08.AddAttribute_MatterFabricId(0xFAB000000000001D), CHIP_NO_ERROR); + EXPECT_EQ(subjectDN_Node02_08.AddAttribute_MatterCASEAuthTag(0xABCE0100), CHIP_NO_ERROR); // clang-format off static TestCase sTestCases[] = { @@ -2543,30 +2539,30 @@ static void TestSubject_x509Extraction(nlTestSuite * inSuite, void * inContext) { ByteSpan cert; err = GetTestCert(testCase.Cert, TestCertLoadFlags::kDERForm, cert); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint8_t subjectBuf[kMaxCertificateDistinguishedNameLength] = { 0 }; MutableByteSpan subject(subjectBuf); err = ExtractSubjectFromX509Cert(cert, subject); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); static uint8_t expectedSubjectBuf[kMaxCertificateDistinguishedNameLength] = { 0 }; ASN1::ASN1Writer writer; writer.Init(expectedSubjectBuf); err = testCase.mExpectedDN.EncodeToASN1(writer); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); size_t expectedSubjectLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, expectedSubjectLen == subject.size()); - NL_TEST_ASSERT(inSuite, memcmp(subject.data(), expectedSubjectBuf, expectedSubjectLen) == 0); + EXPECT_EQ(expectedSubjectLen, subject.size()); + EXPECT_EQ(memcmp(subject.data(), expectedSubjectBuf, expectedSubjectLen), 0); } } -static void TestIssuer_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestIssuer_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; CHIP_ERROR err = CHIP_NO_ERROR; struct TestCase @@ -2576,13 +2572,13 @@ static void TestIssuer_x509Extraction(nlTestSuite * inSuite, void * inContext) }; ChipDN issuerDN_Root01; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == issuerDN_Root01.AddAttribute_MatterRCACId(0xCACACACA00000001)); + EXPECT_EQ(CHIP_NO_ERROR, issuerDN_Root01.AddAttribute_MatterRCACId(0xCACACACA00000001)); ChipDN issuerDN_ICA02; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == issuerDN_ICA02.AddAttribute_MatterRCACId(0xCACACACA00000002)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == issuerDN_ICA02.AddAttribute_MatterFabricId(0xFAB000000000001D)); + EXPECT_EQ(CHIP_NO_ERROR, issuerDN_ICA02.AddAttribute_MatterRCACId(0xCACACACA00000002)); + EXPECT_EQ(CHIP_NO_ERROR, issuerDN_ICA02.AddAttribute_MatterFabricId(0xFAB000000000001D)); ChipDN issuerDN_Node02_02; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == issuerDN_Node02_02.AddAttribute_MatterICACId(0xCACACACA00000004)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == issuerDN_Node02_02.AddAttribute_MatterFabricId(0xFAB000000000001D)); + EXPECT_EQ(CHIP_NO_ERROR, issuerDN_Node02_02.AddAttribute_MatterICACId(0xCACACACA00000004)); + EXPECT_EQ(CHIP_NO_ERROR, issuerDN_Node02_02.AddAttribute_MatterFabricId(0xFAB000000000001D)); // clang-format off static TestCase sTestCases[] = { @@ -2598,28 +2594,28 @@ static void TestIssuer_x509Extraction(nlTestSuite * inSuite, void * inContext) { ByteSpan cert; err = GetTestCert(testCase.Cert, TestCertLoadFlags::kDERForm, cert); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); uint8_t issuerBuf[kMaxCertificateDistinguishedNameLength] = { 0 }; MutableByteSpan issuer(issuerBuf); err = ExtractIssuerFromX509Cert(cert, issuer); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); static uint8_t expectedIssuerBuf[kMaxCertificateDistinguishedNameLength] = { 0 }; ASN1::ASN1Writer writer; writer.Init(expectedIssuerBuf); err = testCase.mExpectedDN.EncodeToASN1(writer); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); size_t expectedIssuerLen = writer.GetLengthWritten(); - NL_TEST_ASSERT(inSuite, expectedIssuerLen == issuer.size()); - NL_TEST_ASSERT(inSuite, memcmp(issuer.data(), expectedIssuerBuf, expectedIssuerLen) == 0); + EXPECT_EQ(expectedIssuerLen, issuer.size()); + EXPECT_EQ(memcmp(issuer.data(), expectedIssuerBuf, expectedIssuerLen), 0); } } -static void TestVIDPID_StringExtraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestVIDPID_StringExtraction) { - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; // Matter VID/PID Attribute examples (from the spec): const char * sTestMatterAttribute01 = "FFF1"; @@ -2730,7 +2726,7 @@ static void TestVIDPID_StringExtraction(nlTestSuite * inSuite, void * inContext) { ChipLogError(Crypto, "Actual result: %" CHIP_ERROR_FORMAT, result.Format()); } - NL_TEST_ASSERT(inSuite, result == testCase.expectedResult); + EXPECT_EQ(result, testCase.expectedResult); // Only do assertions on output params in case of success since otherwise // many of the output params are intermediate outputs. @@ -2738,41 +2734,41 @@ static void TestVIDPID_StringExtraction(nlTestSuite * inSuite, void * inContext) { if (testCase.attrType == DNAttrType::kMatterVID || testCase.attrType == DNAttrType::kMatterPID) { - NL_TEST_ASSERT(inSuite, !vidpidFromCN.Initialized()); + EXPECT_FALSE(vidpidFromCN.Initialized()); vidpidToCheck = vidpid; } else if (testCase.attrType == DNAttrType::kCommonName) { - NL_TEST_ASSERT(inSuite, !vidpid.Initialized()); + EXPECT_FALSE(vidpid.Initialized()); vidpidToCheck = vidpidFromCN; } - NL_TEST_ASSERT(inSuite, vidpidToCheck.mVendorId.HasValue() == testCase.expectedVidPresent); - NL_TEST_ASSERT(inSuite, vidpidToCheck.mProductId.HasValue() == testCase.expectedPidPresent); + EXPECT_EQ(vidpidToCheck.mVendorId.HasValue(), testCase.expectedVidPresent); + EXPECT_EQ(vidpidToCheck.mProductId.HasValue(), testCase.expectedPidPresent); if (testCase.expectedVidPresent) { - NL_TEST_ASSERT(inSuite, vidpidToCheck.mVendorId.Value() == testCase.expectedVid); + EXPECT_EQ(vidpidToCheck.mVendorId.Value(), testCase.expectedVid); } if (testCase.expectedPidPresent) { - NL_TEST_ASSERT(inSuite, vidpidToCheck.mProductId.Value() == testCase.expectedPid); + EXPECT_EQ(vidpidToCheck.mProductId.Value(), testCase.expectedPid); } } ++caseIdx; } } -static void TestVIDPID_x509Extraction(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestVIDPID_x509Extraction) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; // Test scenario where Certificate does not contain a Vendor ID field ByteSpan kOpCertNoVID; - NL_TEST_ASSERT(inSuite, GetTestCert(TestCert::kNode01_01, TestCertLoadFlags::kDERForm, kOpCertNoVID) == CHIP_NO_ERROR); + EXPECT_EQ(GetTestCert(TestCert::kNode01_01, TestCertLoadFlags::kDERForm, kOpCertNoVID), CHIP_NO_ERROR); struct TestCase { @@ -2807,29 +2803,29 @@ static void TestVIDPID_x509Extraction(nlTestSuite * inSuite, void * inContext) { AttestationCertVidPid vidpid; CHIP_ERROR result = ExtractVIDPIDFromX509Cert(testCase.cert, vidpid); - NL_TEST_ASSERT(inSuite, result == testCase.expectedResult); - NL_TEST_ASSERT(inSuite, vidpid.mVendorId.HasValue() == testCase.expectedVidPresent); - NL_TEST_ASSERT(inSuite, vidpid.mProductId.HasValue() == testCase.expectedPidPresent); + EXPECT_EQ(result, testCase.expectedResult); + EXPECT_EQ(vidpid.mVendorId.HasValue(), testCase.expectedVidPresent); + EXPECT_EQ(vidpid.mProductId.HasValue(), testCase.expectedPidPresent); // If present, make sure the VID matches expectation. if (testCase.expectedVidPresent) { - NL_TEST_ASSERT(inSuite, vidpid.mVendorId.Value() == testCase.expectedVid); + EXPECT_EQ(vidpid.mVendorId.Value(), testCase.expectedVid); } // If present, make sure the VID matches expectation. if (testCase.expectedPidPresent) { - NL_TEST_ASSERT(inSuite, vidpid.mProductId.Value() == testCase.expectedPid); + EXPECT_EQ(vidpid.mProductId.Value(), testCase.expectedPid); } } } -static void TestX509_ReplaceCertIfResignedCertFound(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestX509_ReplaceCertIfResignedCertFound) { using namespace TestCerts; - HeapChecker heapChecker(inSuite); + HeapChecker heapChecker; struct TestCase { @@ -2885,8 +2881,8 @@ static void TestX509_ReplaceCertIfResignedCertFound(nlTestSuite * inSuite, void CHIP_ERROR result = ReplaceCertIfResignedCertFound(testCase.referenceCert, testCase.candidateCertsList, testCase.candidateCertsCount, outCert); - NL_TEST_ASSERT(inSuite, result == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, outCert.data_equal(testCase.expectedOutCert)); + EXPECT_EQ(result, CHIP_NO_ERROR); + EXPECT_TRUE(outCert.data_equal(testCase.expectedOutCert)); } // Error case: invalid input argument for referenceCertificate @@ -2894,7 +2890,7 @@ static void TestX509_ReplaceCertIfResignedCertFound(nlTestSuite * inSuite, void ByteSpan outCert; CHIP_ERROR result = ReplaceCertIfResignedCertFound(ByteSpan(), TestCandidateCertsList7, ArraySize(TestCandidateCertsList7), outCert); - NL_TEST_ASSERT(inSuite, result == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(result, CHIP_ERROR_INVALID_ARGUMENT); } // Error case: invalid input argument for one of the certificates in the candidateCertificates list @@ -2902,7 +2898,7 @@ static void TestX509_ReplaceCertIfResignedCertFound(nlTestSuite * inSuite, void ByteSpan outCert; CHIP_ERROR result = ReplaceCertIfResignedCertFound(ByteSpan(), TestCandidateCertsList8, ArraySize(TestCandidateCertsList8), outCert); - NL_TEST_ASSERT(inSuite, result == CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(result, CHIP_ERROR_INVALID_ARGUMENT); } } @@ -2939,7 +2935,7 @@ static const uint8_t kGroupPrivacyKey3[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_ 0xf1, 0x94, 0x08, 0x25, 0x72, 0xd4, 0x9b, 0x1f, 0xdc, 0x73 }; -static void TestGroup_OperationalKeyDerivation(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestGroup_OperationalKeyDerivation) { uint8_t key_buffer[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES] = { 0 }; ByteSpan epoch_key(kEpochKeyBuffer1, sizeof(kEpochKeyBuffer1)); @@ -2947,181 +2943,63 @@ static void TestGroup_OperationalKeyDerivation(nlTestSuite * inSuite, void * inC ByteSpan compressed_fabric_id(kCompressedFabricId); // Invalid Epoch Key - NL_TEST_ASSERT(inSuite, - CHIP_ERROR_INVALID_ARGUMENT == DeriveGroupOperationalKey(ByteSpan(), compressed_fabric_id, operational_key)); + EXPECT_EQ(CHIP_ERROR_INVALID_ARGUMENT, DeriveGroupOperationalKey(ByteSpan(), compressed_fabric_id, operational_key)); // Epoch Key 1 - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupOperationalKey(epoch_key, compressed_fabric_id, operational_key)); - NL_TEST_ASSERT(inSuite, 0 == memcmp(operational_key.data(), kGroupOperationalKey1, sizeof(kGroupOperationalKey1))); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupOperationalKey(epoch_key, compressed_fabric_id, operational_key)); + EXPECT_EQ(0, memcmp(operational_key.data(), kGroupOperationalKey1, sizeof(kGroupOperationalKey1))); // Epoch Key 2 epoch_key = ByteSpan(kEpochKeyBuffer2, sizeof(kEpochKeyBuffer2)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupOperationalKey(epoch_key, compressed_fabric_id, operational_key)); - NL_TEST_ASSERT(inSuite, 0 == memcmp(operational_key.data(), kGroupOperationalKey2, sizeof(kGroupOperationalKey2))); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupOperationalKey(epoch_key, compressed_fabric_id, operational_key)); + EXPECT_EQ(0, memcmp(operational_key.data(), kGroupOperationalKey2, sizeof(kGroupOperationalKey2))); // Epoch Key 3 (example from spec) epoch_key = ByteSpan(kEpochKeyBuffer3, sizeof(kEpochKeyBuffer3)); compressed_fabric_id = ByteSpan(kCompressedFabricId2); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupOperationalKey(epoch_key, compressed_fabric_id, operational_key)); - NL_TEST_ASSERT(inSuite, 0 == memcmp(operational_key.data(), kGroupOperationalKey3, sizeof(kGroupOperationalKey3))); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupOperationalKey(epoch_key, compressed_fabric_id, operational_key)); + EXPECT_EQ(0, memcmp(operational_key.data(), kGroupOperationalKey3, sizeof(kGroupOperationalKey3))); } -static void TestGroup_SessionIdDerivation(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestGroup_SessionIdDerivation) { ByteSpan operational_key1(kGroupOperationalKey1, sizeof(kGroupOperationalKey1)); ByteSpan operational_key2(kGroupOperationalKey2, sizeof(kGroupOperationalKey2)); uint16_t session_id = 0; // Bad Key - NL_TEST_ASSERT(inSuite, CHIP_ERROR_INVALID_ARGUMENT == DeriveGroupSessionId(ByteSpan(), session_id)); + EXPECT_EQ(CHIP_ERROR_INVALID_ARGUMENT, DeriveGroupSessionId(ByteSpan(), session_id)); // Session ID 1 - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupSessionId(operational_key1, session_id)); - NL_TEST_ASSERT(inSuite, kGroupSessionId1 == session_id); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupSessionId(operational_key1, session_id)); + EXPECT_EQ(kGroupSessionId1, session_id); // Session ID 2 - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupSessionId(operational_key2, session_id)); - NL_TEST_ASSERT(inSuite, kGroupSessionId2 == session_id); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupSessionId(operational_key2, session_id)); + EXPECT_EQ(kGroupSessionId2, session_id); } -static void TestGroup_PrivacyKeyDerivation(nlTestSuite * inSuite, void * inContext) +TEST_F(TestChipCryptoPAL, TestGroup_PrivacyKeyDerivation) { uint8_t key_buffer[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES] = { 0 }; ByteSpan encryption_key; MutableByteSpan privacy_key(key_buffer, sizeof(key_buffer)); // Invalid Epoch Key - NL_TEST_ASSERT(inSuite, CHIP_ERROR_INVALID_ARGUMENT == DeriveGroupPrivacyKey(ByteSpan(), privacy_key)); + EXPECT_EQ(CHIP_ERROR_INVALID_ARGUMENT, DeriveGroupPrivacyKey(ByteSpan(), privacy_key)); // Epoch Key 1 encryption_key = ByteSpan(kGroupOperationalKey1, sizeof(kGroupOperationalKey1)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupPrivacyKey(encryption_key, privacy_key)); - NL_TEST_ASSERT(inSuite, 0 == memcmp(privacy_key.data(), kGroupPrivacyKey1, sizeof(kGroupPrivacyKey1))); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupPrivacyKey(encryption_key, privacy_key)); + EXPECT_EQ(0, memcmp(privacy_key.data(), kGroupPrivacyKey1, sizeof(kGroupPrivacyKey1))); // Epoch Key 2 encryption_key = ByteSpan(kGroupOperationalKey2, sizeof(kGroupOperationalKey2)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupPrivacyKey(encryption_key, privacy_key)); - NL_TEST_ASSERT(inSuite, 0 == memcmp(privacy_key.data(), kGroupPrivacyKey2, sizeof(kGroupPrivacyKey2))); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupPrivacyKey(encryption_key, privacy_key)); + EXPECT_EQ(0, memcmp(privacy_key.data(), kGroupPrivacyKey2, sizeof(kGroupPrivacyKey2))); // Epoch Key 3 (example from spec) encryption_key = ByteSpan(kGroupOperationalKey3, sizeof(kGroupOperationalKey3)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == DeriveGroupPrivacyKey(encryption_key, privacy_key)); - NL_TEST_ASSERT(inSuite, 0 == memcmp(privacy_key.data(), kGroupPrivacyKey3, sizeof(kGroupPrivacyKey3))); + EXPECT_EQ(CHIP_NO_ERROR, DeriveGroupPrivacyKey(encryption_key, privacy_key)); + EXPECT_EQ(0, memcmp(privacy_key.data(), kGroupPrivacyKey3, sizeof(kGroupPrivacyKey3))); } - -/** - * Test Suite. It lists all the test functions. - */ - -static const nlTest sTests[] = { - - NL_TEST_DEF("Test encrypting AES-CCM-128 test vectors", TestAES_CCM_128EncryptTestVectors), - NL_TEST_DEF("Test decrypting AES-CCM-128 test vectors", TestAES_CCM_128DecryptTestVectors), - NL_TEST_DEF("Test encrypting AES-CCM-128 using invalid nonce", TestAES_CCM_128EncryptInvalidNonceLen), - NL_TEST_DEF("Test encrypting AES-CCM-128 using invalid tag", TestAES_CCM_128EncryptInvalidTagLen), - NL_TEST_DEF("Test decrypting AES-CCM-128 invalid nonce", TestAES_CCM_128DecryptInvalidNonceLen), - NL_TEST_DEF("Test encrypt/decrypt AES-CTR-128 test vectors", TestAES_CTR_128CryptTestVectors), - NL_TEST_DEF("Test ASN.1 signature conversion routines", TestAsn1Conversions), - NL_TEST_DEF("Test reading a length from ASN.1 DER stream success cases", TestReadDerLengthValidCases), - NL_TEST_DEF("Test reading a length from ASN.1 DER stream error cases", TestReadDerLengthInvalidCases), - NL_TEST_DEF("Test Integer to ASN.1 DER conversion", TestRawIntegerToDerValidCases), - NL_TEST_DEF("Test Integer to ASN.1 DER conversion error cases", TestRawIntegerToDerInvalidCases), - NL_TEST_DEF("Test ECDSA signing and validation message using SHA256", TestECDSA_Signing_SHA256_Msg), - NL_TEST_DEF("Test ECDSA signing and validation SHA256 Hash", TestECDSA_Signing_SHA256_Hash), - NL_TEST_DEF("Test ECDSA signature validation fail - Different msg", TestECDSA_ValidationFailsDifferentMessage), - NL_TEST_DEF("Test ECDSA signature validation fail - Different msg signature", TestECDSA_ValidationFailIncorrectMsgSignature), - NL_TEST_DEF("Test ECDSA signature validation fail - Different hash signature", TestECDSA_ValidationFailIncorrectHashSignature), - NL_TEST_DEF("Test ECDSA sign msg invalid parameters", TestECDSA_SigningMsgInvalidParams), - NL_TEST_DEF("Test ECDSA msg signature validation invalid parameters", TestECDSA_ValidationMsgInvalidParam), - NL_TEST_DEF("Test ECDSA hash signature validation invalid parameters", TestECDSA_ValidationHashInvalidParam), - NL_TEST_DEF("Test Hash SHA 256", TestHash_SHA256), - NL_TEST_DEF("Test Hash SHA 256 Stream", TestHash_SHA256_Stream), - NL_TEST_DEF("Test HKDF SHA 256", TestHKDF_SHA256), - NL_TEST_DEF("Test HMAC SHA 256 - Raw Key", TestHMAC_SHA256_RawKey), - NL_TEST_DEF("Test HMAC SHA 256 - Key Handle", TestHMAC_SHA256_KeyHandle), - NL_TEST_DEF("Test DRBG invalid inputs", TestDRBG_InvalidInputs), - NL_TEST_DEF("Test DRBG output", TestDRBG_Output), - NL_TEST_DEF("Test ECDH derive shared secret", TestECDH_EstablishSecret), - NL_TEST_DEF("Test adding entropy sources", TestAddEntropySources), - NL_TEST_DEF("Test PBKDF2 SHA256", TestPBKDF2_SHA256_TestVectors), - NL_TEST_DEF("Test P256 Keygen", TestP256_Keygen), - NL_TEST_DEF("Test CSR Verification + PK extraction", TestCSR_Verify), - NL_TEST_DEF("Test CSR Generation via P256Keypair method", TestCSR_GenByKeypair), - NL_TEST_DEF("Test Direct CSR Generation", TestCSR_GenDirect), - NL_TEST_DEF("Test Keypair Serialize", TestKeypair_Serialize), - NL_TEST_DEF("Test Spake2p_spake2p FEMul", TestSPAKE2P_spake2p_FEMul), - NL_TEST_DEF("Test Spake2p_spake2p FELoad/FEWrite", TestSPAKE2P_spake2p_FELoadWrite), - NL_TEST_DEF("Test Spake2p_spake2p Mac", TestSPAKE2P_spake2p_Mac), - NL_TEST_DEF("Test Spake2p_spake2p PointMul", TestSPAKE2P_spake2p_PointMul), - NL_TEST_DEF("Test Spake2p_spake2p PointMulAdd", TestSPAKE2P_spake2p_PointMulAdd), - NL_TEST_DEF("Test Spake2p_spake2p PointLoad/PointWrite", TestSPAKE2P_spake2p_PointLoadWrite), - NL_TEST_DEF("Test Spake2p_spake2p PointIsValid", TestSPAKE2P_spake2p_PointIsValid), - NL_TEST_DEF("Test Spake2+ against RFC test vectors", TestSPAKE2P_RFC), - NL_TEST_DEF("Test Spake2+ object reuse", TestSPAKE2P_Reuse), - NL_TEST_DEF("Test compressed fabric identifier", TestCompressedFabricIdentifier), - NL_TEST_DEF("Test Pubkey Extraction from x509 Certificate", TestPubkey_x509Extraction), - NL_TEST_DEF("Test x509 Attestation Certificate Format Validation", TestX509_VerifyAttestationCertificateFormat), - NL_TEST_DEF("Test x509 Certificate Chain Validation", TestX509_CertChainValidation), - NL_TEST_DEF("Test x509 Certificate Timestamp Validation", TestX509_IssuingTimestampValidation), - NL_TEST_DEF("Test Subject Key Id Extraction from x509 Certificate", TestSKID_x509Extraction), - NL_TEST_DEF("Test Authority Key Id Extraction from x509 Certificate", TestAKID_x509Extraction), - NL_TEST_DEF("Test CRL Distribution Point Extension Extraction from x509 Certificate", TestCDPExtension_x509Extraction), - NL_TEST_DEF("Test CDP Extension CRL Issuer Extraction from x509 Certificate", TestCDPCRLIssuerExtension_x509Extraction), - NL_TEST_DEF("Test Serial Number Extraction from x509 Certificate", TestSerialNumber_x509Extraction), - NL_TEST_DEF("Test Subject Extraction from x509 Certificate", TestSubject_x509Extraction), - NL_TEST_DEF("Test Issuer Extraction from x509 Certificate", TestIssuer_x509Extraction), - NL_TEST_DEF("Test Vendor ID and Product ID Extraction from Attribute String", TestVIDPID_StringExtraction), - NL_TEST_DEF("Test Vendor ID and Product ID Extraction from x509 Attestation Certificate", TestVIDPID_x509Extraction), - NL_TEST_DEF("Test Replace Resigned Certificate Version if Found", TestX509_ReplaceCertIfResignedCertFound), - NL_TEST_DEF("Test Group Operation Key Derivation", TestGroup_OperationalKeyDerivation), - NL_TEST_DEF("Test Group Session ID Derivation", TestGroup_SessionIdDerivation), - NL_TEST_DEF("Test Group Privacy Key Derivation", TestGroup_PrivacyKeyDerivation), - NL_TEST_DEF("Test sensitive data buffer", TestSensitiveDataBuffer), - NL_TEST_DEF("Test sensitive data fixed buffer", TestSensitiveDataFixedBuffer), - NL_TEST_SENTINEL() -}; - -/** - * Set up the test suite. - */ -int TestCHIPCryptoPAL_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - -#if CHIP_CRYPTO_PSA - psa_crypto_init(); -#endif - - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestCHIPCryptoPAL_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -int TestChipCryptoPal() -{ - // clang-format off - nlTestSuite theSuite = - { - "CHIP Crypto PAL tests", - &sTests[0], - TestCHIPCryptoPAL_Setup, - TestCHIPCryptoPAL_Teardown - }; - // clang-format on - // Run test suite against one context. - nlTestRunner(&theSuite, nullptr); - - add_entropy_source(test_entropy_source, nullptr, 16); - return (nlTestRunnerStats(&theSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestChipCryptoPal) diff --git a/src/crypto/tests/TestGroupOperationalCredentials.cpp b/src/crypto/tests/TestGroupOperationalCredentials.cpp index 1f0eeb5f17e503..941423e327f873 100644 --- a/src/crypto/tests/TestGroupOperationalCredentials.cpp +++ b/src/crypto/tests/TestGroupOperationalCredentials.cpp @@ -21,9 +21,8 @@ #include #include #include -#include -#include +#include using namespace chip; using namespace chip::Crypto; @@ -80,59 +79,25 @@ struct GroupKeySetTestEntry theGroupKeySetTestVector[] = { }, }; -void TestDeriveGroupOperationalCredentials(nlTestSuite * apSuite, void * apContext) +struct TestGroupOperationalCredentials : public ::testing::Test +{ + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestGroupOperationalCredentials, TestDeriveGroupOperationalCredentials) { GroupOperationalCredentials opCreds; for (const auto & testVector : theGroupKeySetTestVector) { const ByteSpan epochKey(testVector.epochKey, KEY_LENGTH); - NL_TEST_ASSERT(apSuite, - CHIP_NO_ERROR == Crypto::DeriveGroupOperationalCredentials(epochKey, kCompressedFabricId1, opCreds)); + EXPECT_EQ(CHIP_NO_ERROR, Crypto::DeriveGroupOperationalCredentials(epochKey, kCompressedFabricId1, opCreds)); - NL_TEST_ASSERT(apSuite, opCreds.hash == testVector.groupKeys->hash); - NL_TEST_ASSERT(apSuite, 0 == memcmp(opCreds.encryption_key, testVector.groupKeys->encryption_key, KEY_LENGTH)); - NL_TEST_ASSERT(apSuite, 0 == memcmp(opCreds.privacy_key, testVector.groupKeys->privacy_key, KEY_LENGTH)); + EXPECT_EQ(opCreds.hash, testVector.groupKeys->hash); + EXPECT_EQ(0, memcmp(opCreds.encryption_key, testVector.groupKeys->encryption_key, KEY_LENGTH)); + EXPECT_EQ(0, memcmp(opCreds.privacy_key, testVector.groupKeys->privacy_key, KEY_LENGTH)); } } -/** - * Test Suite. It lists all the test functions. - */ -const nlTest sTests[] = { NL_TEST_DEF("TestDeriveGroupOperationalCredentials", TestDeriveGroupOperationalCredentials), - NL_TEST_SENTINEL() }; - -/** - * Set up the test suite. - */ -int Test_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - VerifyOrReturnError(error == CHIP_NO_ERROR, FAILURE); - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int Test_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - } // namespace - -/** - * Main - */ -int TestGroupOperationalCredentials() -{ - nlTestSuite theSuite = { "TestGroupOperationalCredentials", &sTests[0], Test_Setup, Test_Teardown }; - - // Run test suite againt one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestGroupOperationalCredentials) diff --git a/src/crypto/tests/TestPSAOpKeyStore.cpp b/src/crypto/tests/TestPSAOpKeyStore.cpp index 9ed39c5c3831de..4a16a19e254b60 100644 --- a/src/crypto/tests/TestPSAOpKeyStore.cpp +++ b/src/crypto/tests/TestPSAOpKeyStore.cpp @@ -25,16 +25,28 @@ #include #include #include -#include -#include -#include + +#include using namespace chip; using namespace chip::Crypto; namespace { -void TestBasicLifeCycle(nlTestSuite * inSuite, void * inContext) +struct TestPSAOpKeyStore : public ::testing::Test +{ + static void SetUpTestSuite() + { + ASSERT_EQ(CHIP_NO_ERROR, chip::Platform::MemoryInit()); + +#if CHIP_CRYPTO_PSA + psa_crypto_init(); +#endif + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestPSAOpKeyStore, TestBasicLifeCycle) { PSAOperationalKeystore opKeystore; @@ -45,125 +57,124 @@ void TestBasicLifeCycle(nlTestSuite * inSuite, void * inContext) uint8_t csrBuf[kMIN_CSR_Buffer_Size]; MutableByteSpan csrSpan{ csrBuf }; CHIP_ERROR err = opKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); P256PublicKey csrPublicKey1; err = VerifyCertificateSigningRequest(csrSpan.data(), csrSpan.size(), csrPublicKey1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Can regenerate a second CSR and it has different PK csrSpan = MutableByteSpan{ csrBuf }; err = opKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); P256PublicKey csrPublicKey2; err = VerifyCertificateSigningRequest(csrSpan.data(), csrSpan.size(), csrPublicKey2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, !csrPublicKey1.Matches(csrPublicKey2)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(csrPublicKey1.Matches(csrPublicKey2)); // Cannot NewOpKeypair for a different fabric if one already pending uint8_t badCsrBuf[kMIN_CSR_Buffer_Size]; MutableByteSpan badCsrSpan{ badCsrBuf }; err = opKeystore.NewOpKeypairForFabric(kBadFabricIndex, badCsrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); // Fail to generate CSR for invalid fabrics csrSpan = MutableByteSpan{ csrBuf }; err = opKeystore.NewOpKeypairForFabric(kUndefinedFabricIndex, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); csrSpan = MutableByteSpan{ csrBuf }; err = opKeystore.NewOpKeypairForFabric(kMaxValidFabricIndex + 1, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); // No storage done by NewOpKeypairForFabric - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Even after error, the previous valid pending keypair stays valid. - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); // Activating with mismatching fabricIndex and matching public key fails err = opKeystore.ActivateOpKeypairForFabric(kBadFabricIndex, csrPublicKey2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Activating with matching fabricIndex and mismatching public key fails err = opKeystore.ActivateOpKeypairForFabric(kFabricIndex, csrPublicKey1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_PUBLIC_KEY); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(err, CHIP_ERROR_INVALID_PUBLIC_KEY); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Before successful activation, cannot sign uint8_t message[] = { 1, 2, 3, 4 }; P256ECDSASignature sig1; err = opKeystore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message }, sig1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); // Activating with matching fabricIndex and matching public key succeeds err = opKeystore.ActivateOpKeypairForFabric(kFabricIndex, csrPublicKey2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Activating does not store, and keeps pending - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kBadFabricIndex) == false); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_TRUE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kBadFabricIndex)); // Can't sign for wrong fabric after activation P256ECDSASignature sig2; err = opKeystore.SignWithOpKeypair(kBadFabricIndex, ByteSpan{ message }, sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); // Can sign after activation err = opKeystore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message }, sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Signature matches pending key err = csrPublicKey2.ECDSA_validate_msg_signature(message, sizeof(message), sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Signature does not match a previous pending key err = csrPublicKey1.ECDSA_validate_msg_signature(message, sizeof(message), sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_SIGNATURE); + EXPECT_EQ(err, CHIP_ERROR_INVALID_SIGNATURE); // Committing with mismatching fabric fails, leaves pending err = opKeystore.CommitOpKeypairForFabric(kBadFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == true); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_TRUE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Committing key resets pending state err = opKeystore.CommitOpKeypairForFabric(kFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == false); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(opKeystore.HasPendingOpKeypair()); + EXPECT_TRUE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Verify if the key is not exportable - the PSA_KEY_USAGE_EXPORT psa flag should not be set P256SerializedKeypair serializedKeypair; - NL_TEST_ASSERT(inSuite, - opKeystore.ExportOpKeypairForFabric(kFabricIndex, serializedKeypair) == CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); + EXPECT_EQ(opKeystore.ExportOpKeypairForFabric(kFabricIndex, serializedKeypair), CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE); // After committing, signing works with the key that was pending P256ECDSASignature sig3; uint8_t message2[] = { 10, 11, 12, 13 }; err = opKeystore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message2 }, sig3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = csrPublicKey2.ECDSA_validate_msg_signature(message2, sizeof(message2), sig3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Let's remove the opkey for a fabric, it disappears err = opKeystore.RemoveOpKeypairForFabric(kFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == false); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); } -void TestEphemeralKeys(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPSAOpKeyStore, TestEphemeralKeys) { PSAOperationalKeystore opKeyStore; @@ -171,16 +182,16 @@ void TestEphemeralKeys(nlTestSuite * inSuite, void * inContext) uint8_t message[] = { 'm', 's', 'g' }; Crypto::P256Keypair * ephemeralKeypair = opKeyStore.AllocateEphemeralKeypairForCASE(); - NL_TEST_ASSERT(inSuite, ephemeralKeypair != nullptr); - NL_TEST_ASSERT_SUCCESS(inSuite, ephemeralKeypair->Initialize(Crypto::ECPKeyTarget::ECDSA)); + EXPECT_NE(nullptr, ephemeralKeypair); + EXPECT_EQ(ephemeralKeypair->Initialize(Crypto::ECPKeyTarget::ECDSA), CHIP_NO_ERROR); - NL_TEST_ASSERT_SUCCESS(inSuite, ephemeralKeypair->ECDSA_sign_msg(message, sizeof(message), sig)); - NL_TEST_ASSERT_SUCCESS(inSuite, ephemeralKeypair->Pubkey().ECDSA_validate_msg_signature(message, sizeof(message), sig)); + EXPECT_EQ(ephemeralKeypair->ECDSA_sign_msg(message, sizeof(message), sig), CHIP_NO_ERROR); + EXPECT_EQ(ephemeralKeypair->Pubkey().ECDSA_validate_msg_signature(message, sizeof(message), sig), CHIP_NO_ERROR); opKeyStore.ReleaseEphemeralKeypair(ephemeralKeypair); } -void TestMigrationKeys(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPSAOpKeyStore, TestMigrationKeys) { chip::TestPersistentStorageDelegate storage; PSAOperationalKeystore psaOpKeyStore; @@ -188,39 +199,35 @@ void TestMigrationKeys(nlTestSuite * inSuite, void * inContext) constexpr FabricIndex kFabricIndex = 111; // Failure before Init of MoveOpKeysFromPersistentStorageToITS - NL_TEST_ASSERT(inSuite, - psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore) == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore), CHIP_ERROR_INCORRECT_STATE); // Initialize both operational key stores - NL_TEST_ASSERT(inSuite, persistentOpKeyStore.Init(&storage) == CHIP_NO_ERROR); + EXPECT_EQ(persistentOpKeyStore.Init(&storage), CHIP_NO_ERROR); // Failure on invalid Fabric indexes - NL_TEST_ASSERT(inSuite, - psaOpKeyStore.MigrateOpKeypairForFabric(kUndefinedFabricIndex, persistentOpKeyStore) == - CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, - psaOpKeyStore.MigrateOpKeypairForFabric(kMaxValidFabricIndex + 1, persistentOpKeyStore) == - CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(psaOpKeyStore.MigrateOpKeypairForFabric(kUndefinedFabricIndex, persistentOpKeyStore), + CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(psaOpKeyStore.MigrateOpKeypairForFabric(kMaxValidFabricIndex + 1, persistentOpKeyStore), + CHIP_ERROR_INVALID_FABRIC_INDEX); // Failure on the key migration, while the key does not exist in the any keystore. - NL_TEST_ASSERT(inSuite, storage.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName()) == false); - NL_TEST_ASSERT(inSuite, psaOpKeyStore.HasOpKeypairForFabric(kFabricIndex) == false); - NL_TEST_ASSERT(inSuite, - psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore) == - CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(storage.GetNumKeys(), 0u); + EXPECT_FALSE(storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName())); + EXPECT_FALSE(psaOpKeyStore.HasOpKeypairForFabric(kFabricIndex)); + EXPECT_EQ(psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore), + CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); auto generateAndStore = [&](FabricIndex index, MutableByteSpan & buf, P256PublicKey & pubKey) { - NL_TEST_ASSERT(inSuite, persistentOpKeyStore.HasPendingOpKeypair() == false); - NL_TEST_ASSERT(inSuite, persistentOpKeyStore.NewOpKeypairForFabric(kFabricIndex, buf) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, VerifyCertificateSigningRequest(buf.data(), buf.size(), pubKey) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, persistentOpKeyStore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, persistentOpKeyStore.ActivateOpKeypairForFabric(kFabricIndex, pubKey) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, storage.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, persistentOpKeyStore.CommitOpKeypairForFabric(kFabricIndex) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, persistentOpKeyStore.HasPendingOpKeypair() == false); - NL_TEST_ASSERT(inSuite, storage.GetNumKeys() == 1); - NL_TEST_ASSERT(inSuite, storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName()) == true); + EXPECT_FALSE(persistentOpKeyStore.HasPendingOpKeypair()); + EXPECT_EQ(persistentOpKeyStore.NewOpKeypairForFabric(kFabricIndex, buf), CHIP_NO_ERROR); + EXPECT_EQ(VerifyCertificateSigningRequest(buf.data(), buf.size(), pubKey), CHIP_NO_ERROR); + EXPECT_TRUE(persistentOpKeyStore.HasPendingOpKeypair()); + EXPECT_EQ(persistentOpKeyStore.ActivateOpKeypairForFabric(kFabricIndex, pubKey), CHIP_NO_ERROR); + EXPECT_EQ(storage.GetNumKeys(), 0u); + EXPECT_EQ(persistentOpKeyStore.CommitOpKeypairForFabric(kFabricIndex), CHIP_NO_ERROR); + EXPECT_FALSE(persistentOpKeyStore.HasPendingOpKeypair()); + EXPECT_EQ(storage.GetNumKeys(), 1u); + EXPECT_TRUE(storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName())); }; // Save a key to the old persistent storage @@ -230,83 +237,35 @@ void TestMigrationKeys(nlTestSuite * inSuite, void * inContext) generateAndStore(kFabricIndex, csrSpan, csrPublicKey1); // Migrate key to PSA ITS - NL_TEST_ASSERT(inSuite, psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, psaOpKeyStore.HasOpKeypairForFabric(kFabricIndex) == true); + EXPECT_EQ(psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore), CHIP_NO_ERROR); + EXPECT_TRUE(psaOpKeyStore.HasOpKeypairForFabric(kFabricIndex)); // Verify the migrated keys P256ECDSASignature sig1; uint8_t message1[] = { 10, 11, 12, 13 }; - NL_TEST_ASSERT(inSuite, psaOpKeyStore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message1 }, sig1) == CHIP_NO_ERROR); + EXPECT_EQ(psaOpKeyStore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message1 }, sig1), CHIP_NO_ERROR); // To verify use the public key generated by the old persistent storage - NL_TEST_ASSERT(inSuite, csrPublicKey1.ECDSA_validate_msg_signature(message1, sizeof(message1), sig1) == CHIP_NO_ERROR); + EXPECT_EQ(csrPublicKey1.ECDSA_validate_msg_signature(message1, sizeof(message1), sig1), CHIP_NO_ERROR); // After migration there should be no old keys anymore - NL_TEST_ASSERT(inSuite, storage.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName()) == false); + EXPECT_EQ(storage.GetNumKeys(), 0u); + EXPECT_FALSE(storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName())); // Verify that migration method returns success when there is no OpKey stored in the old keystore, but already exists in PSA // ITS. - NL_TEST_ASSERT(inSuite, psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore) == CHIP_NO_ERROR); + EXPECT_EQ(psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore), CHIP_NO_ERROR); // The key already exists in ITS, but there is an another attempt to migrate the new key. // The key should not be overwritten, but the key from the previous persistent keystore should be removed. MutableByteSpan csrSpan2{ csrBuf }; generateAndStore(kFabricIndex, csrSpan2, csrPublicKey1); - NL_TEST_ASSERT(inSuite, psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, storage.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName()) == false); + EXPECT_EQ(psaOpKeyStore.MigrateOpKeypairForFabric(kFabricIndex, persistentOpKeyStore), CHIP_NO_ERROR); + EXPECT_EQ(storage.GetNumKeys(), 0u); + EXPECT_FALSE(storage.HasKey(DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName())); // Finalize persistentOpKeyStore.Finish(); } -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { - NL_TEST_DEF("Test Basic Lifecycle of PersistentStorageOperationalKeystore", TestBasicLifeCycle), - NL_TEST_DEF("Test ephemeral key management", TestEphemeralKeys), - NL_TEST_DEF("Test keys migration to ITS", TestMigrationKeys), - NL_TEST_SENTINEL(), -}; - -/** - * Set up the test suite. - */ -int Test_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - VerifyOrReturnError(error == CHIP_NO_ERROR, FAILURE); - -#if CHIP_CRYPTO_PSA - psa_crypto_init(); -#endif - - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int Test_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - } // namespace - -/** - * Main - */ -int TestPSAOperationalKeystore() -{ - nlTestSuite theSuite = { "PSAOperationalKeystore tests", &sTests[0], Test_Setup, Test_Teardown }; - - // Run test suite againt one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPSAOperationalKeystore) diff --git a/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp b/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp index c3dd0fcdec0447..4448004ff2d3a3 100644 --- a/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp +++ b/src/crypto/tests/TestPersistentStorageOpKeyStore.cpp @@ -24,9 +24,8 @@ #include #include #include -#include -#include -#include + +#include #include @@ -130,7 +129,13 @@ class TestOperationalKeystore final : public Crypto::OperationalKeystore FabricIndex mUsedFabricIndex = 0; }; -void TestBasicLifeCycle(nlTestSuite * inSuite, void * inContext) +struct TestPersistentStorageOpKeyStore : public ::testing::Test +{ + static void SetUpTestSuite() { ASSERT_EQ(chip::Platform::MemoryInit(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestPersistentStorageOpKeyStore, TestBasicLifeCycle) { TestPersistentStorageDelegate storageDelegate; PersistentStorageOperationalKeystore opKeystore; @@ -141,188 +146,187 @@ void TestBasicLifeCycle(nlTestSuite * inSuite, void * inContext) // Failure before Init of ActivateOpKeypairForFabric P256PublicKey placeHolderPublicKey; CHIP_ERROR err = opKeystore.ActivateOpKeypairForFabric(kFabricIndex, placeHolderPublicKey); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(storageDelegate.GetNumKeys(), 0u); // Failure before Init of NewOpKeypairForFabric uint8_t unusedCsrBuf[kMIN_CSR_Buffer_Size]; MutableByteSpan unusedCsrSpan{ unusedCsrBuf }; err = opKeystore.NewOpKeypairForFabric(kFabricIndex, unusedCsrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // Failure before Init of CommitOpKeypairForFabric err = opKeystore.CommitOpKeypairForFabric(kFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // Failure before Init of RemoveOpKeypairForFabric err = opKeystore.RemoveOpKeypairForFabric(kFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INCORRECT_STATE); + EXPECT_EQ(err, CHIP_ERROR_INCORRECT_STATE); // Success after Init err = opKeystore.Init(&storageDelegate); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Can generate a key and get a CSR uint8_t csrBuf[kMIN_CSR_Buffer_Size]; MutableByteSpan csrSpan{ csrBuf }; err = opKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); P256PublicKey csrPublicKey1; err = VerifyCertificateSigningRequest(csrSpan.data(), csrSpan.size(), csrPublicKey1); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, csrPublicKey1.Matches(csrPublicKey1)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(csrPublicKey1.Matches(csrPublicKey1)); // Can regenerate a second CSR and it has different PK csrSpan = MutableByteSpan{ csrBuf }; err = opKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); // Cannot NewOpKeypair for a different fabric if one already pending uint8_t badCsrBuf[kMIN_CSR_Buffer_Size]; MutableByteSpan badCsrSpan = MutableByteSpan{ badCsrBuf }; err = opKeystore.NewOpKeypairForFabric(kBadFabricIndex, badCsrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); P256PublicKey csrPublicKey2; err = VerifyCertificateSigningRequest(csrSpan.data(), csrSpan.size(), csrPublicKey2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, !csrPublicKey1.Matches(csrPublicKey2)); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(csrPublicKey1.Matches(csrPublicKey2)); // Fail to generate CSR for invalid fabrics csrSpan = MutableByteSpan{ csrBuf }; err = opKeystore.NewOpKeypairForFabric(kUndefinedFabricIndex, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); csrSpan = MutableByteSpan{ csrBuf }; err = opKeystore.NewOpKeypairForFabric(kMaxValidFabricIndex + 1, csrSpan); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); // No storage done by NewOpKeypairForFabric - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(storageDelegate.GetNumKeys(), 0u); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Even after error, the previous valid pending keypair stays valid. - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); // Activating with mismatching fabricIndex and matching public key fails err = opKeystore.ActivateOpKeypairForFabric(kBadFabricIndex, csrPublicKey2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(storageDelegate.GetNumKeys(), 0u); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Activating with matching fabricIndex and mismatching public key fails err = opKeystore.ActivateOpKeypairForFabric(kFabricIndex, csrPublicKey1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_PUBLIC_KEY); - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(err, CHIP_ERROR_INVALID_PUBLIC_KEY); + EXPECT_EQ(storageDelegate.GetNumKeys(), 0u); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); uint8_t message[] = { 1, 2, 3, 4 }; P256ECDSASignature sig1; // Before successful activation, cannot sign err = opKeystore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message }, sig1); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); // Activating with matching fabricIndex and matching public key succeeds err = opKeystore.ActivateOpKeypairForFabric(kFabricIndex, csrPublicKey2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Activating does not store, and keeps pending - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kBadFabricIndex) == false); + EXPECT_EQ(storageDelegate.GetNumKeys(), 0u); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_TRUE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kBadFabricIndex)); // Can't sign for wrong fabric after activation P256ECDSASignature sig2; err = opKeystore.SignWithOpKeypair(kBadFabricIndex, ByteSpan{ message }, sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); // Can sign after activation err = opKeystore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message }, sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Signature matches pending key err = csrPublicKey2.ECDSA_validate_msg_signature(message, sizeof(message), sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Signature does not match a previous pending key err = csrPublicKey1.ECDSA_validate_msg_signature(message, sizeof(message), sig2); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_SIGNATURE); + EXPECT_EQ(err, CHIP_ERROR_INVALID_SIGNATURE); // Committing with mismatching fabric fails, leaves pending err = opKeystore.CommitOpKeypairForFabric(kBadFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == true); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == true); + EXPECT_EQ(err, CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(storageDelegate.GetNumKeys(), 0u); + EXPECT_TRUE(opKeystore.HasPendingOpKeypair()); + EXPECT_TRUE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); // Committing key resets pending state and adds storage std::string opKeyStorageKey = DefaultStorageKeyAllocator::FabricOpKey(kFabricIndex).KeyName(); err = opKeystore.CommitOpKeypairForFabric(kFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == false); - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 1); - NL_TEST_ASSERT(inSuite, storageDelegate.HasKey(opKeyStorageKey) == true); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(opKeystore.HasPendingOpKeypair()); + EXPECT_EQ(storageDelegate.GetNumKeys(), 1u); + EXPECT_TRUE(storageDelegate.HasKey(opKeyStorageKey)); // Exporting a key P256SerializedKeypair serializedKeypair; - NL_TEST_ASSERT(inSuite, opKeystore.ExportOpKeypairForFabric(kFabricIndex, serializedKeypair) == CHIP_NO_ERROR); + EXPECT_EQ(opKeystore.ExportOpKeypairForFabric(kFabricIndex, serializedKeypair), CHIP_NO_ERROR); // Exporting a key from the bad fabric index - NL_TEST_ASSERT(inSuite, - opKeystore.ExportOpKeypairForFabric(kBadFabricIndex, serializedKeypair) == - CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(opKeystore.ExportOpKeypairForFabric(kBadFabricIndex, serializedKeypair), + CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); // After committing, signing works with the key that was pending P256ECDSASignature sig3; uint8_t message2[] = { 10, 11, 12, 13 }; err = opKeystore.SignWithOpKeypair(kFabricIndex, ByteSpan{ message2 }, sig3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); err = csrPublicKey2.ECDSA_validate_msg_signature(message2, sizeof(message2), sig3); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); // Let's remove the opkey for a fabric, it disappears err = opKeystore.RemoveOpKeypairForFabric(kFabricIndex); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, opKeystore.HasPendingOpKeypair() == false); - NL_TEST_ASSERT(inSuite, opKeystore.HasOpKeypairForFabric(kFabricIndex) == false); - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 0); - NL_TEST_ASSERT(inSuite, storageDelegate.HasKey(opKeyStorageKey) == false); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_FALSE(opKeystore.HasPendingOpKeypair()); + EXPECT_FALSE(opKeystore.HasOpKeypairForFabric(kFabricIndex)); + EXPECT_EQ(storageDelegate.GetNumKeys(), 0u); + EXPECT_FALSE(storageDelegate.HasKey(opKeyStorageKey)); opKeystore.Finish(); } -void TestEphemeralKeys(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPersistentStorageOpKeyStore, TestEphemeralKeys) { chip::TestPersistentStorageDelegate storage; PersistentStorageOperationalKeystore opKeyStore; - NL_TEST_ASSERT_SUCCESS(inSuite, opKeyStore.Init(&storage)); + EXPECT_EQ(opKeyStore.Init(&storage), CHIP_NO_ERROR); Crypto::P256ECDSASignature sig; uint8_t message[] = { 'm', 's', 'g' }; Crypto::P256Keypair * ephemeralKeypair = opKeyStore.AllocateEphemeralKeypairForCASE(); - NL_TEST_ASSERT(inSuite, ephemeralKeypair != nullptr); - NL_TEST_ASSERT_SUCCESS(inSuite, ephemeralKeypair->Initialize(Crypto::ECPKeyTarget::ECDSA)); + ASSERT_NE(ephemeralKeypair, nullptr); + EXPECT_EQ(ephemeralKeypair->Initialize(Crypto::ECPKeyTarget::ECDSA), CHIP_NO_ERROR); - NL_TEST_ASSERT_SUCCESS(inSuite, ephemeralKeypair->ECDSA_sign_msg(message, sizeof(message), sig)); - NL_TEST_ASSERT_SUCCESS(inSuite, ephemeralKeypair->Pubkey().ECDSA_validate_msg_signature(message, sizeof(message), sig)); + EXPECT_EQ(ephemeralKeypair->ECDSA_sign_msg(message, sizeof(message), sig), CHIP_NO_ERROR); + EXPECT_EQ(ephemeralKeypair->Pubkey().ECDSA_validate_msg_signature(message, sizeof(message), sig), CHIP_NO_ERROR); opKeyStore.ReleaseEphemeralKeypair(ephemeralKeypair); opKeyStore.Finish(); } -void TestMigrationKeys(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPersistentStorageOpKeyStore, TestMigrationKeys) { chip::TestPersistentStorageDelegate storageDelegate; @@ -334,89 +338,46 @@ void TestMigrationKeys(nlTestSuite * inSuite, void * inContext) opKeyStore.Init(&storageDelegate); // Failure on invalid Fabric indexes - NL_TEST_ASSERT(inSuite, - opKeyStore.MigrateOpKeypairForFabric(kUndefinedFabricIndex, testOperationalKeystore) == - CHIP_ERROR_INVALID_FABRIC_INDEX); - NL_TEST_ASSERT(inSuite, - opKeyStore.MigrateOpKeypairForFabric(kMaxValidFabricIndex + 1, testOperationalKeystore) == - CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(opKeyStore.MigrateOpKeypairForFabric(kUndefinedFabricIndex, testOperationalKeystore), + CHIP_ERROR_INVALID_FABRIC_INDEX); + EXPECT_EQ(opKeyStore.MigrateOpKeypairForFabric(kMaxValidFabricIndex + 1, testOperationalKeystore), + CHIP_ERROR_INVALID_FABRIC_INDEX); // The key does not exists in the any of the Operational Keystores - NL_TEST_ASSERT(inSuite, storageDelegate.HasKey(opKeyStorageKey) == false); - NL_TEST_ASSERT(inSuite, testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex) == false); - NL_TEST_ASSERT(inSuite, - opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore) == - CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_FALSE(storageDelegate.HasKey(opKeyStorageKey)); + EXPECT_FALSE(testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex)); + EXPECT_EQ(opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore), + CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); // Create a key in the old Operational Keystore uint8_t csrBuf[kMIN_CSR_Buffer_Size]; MutableByteSpan csrSpan{ csrBuf }; - NL_TEST_ASSERT(inSuite, testOperationalKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan) == CHIP_NO_ERROR); + EXPECT_EQ(testOperationalKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan), CHIP_NO_ERROR); // Migrate the key to the PersistentStorageOperationalKeystore - NL_TEST_ASSERT(inSuite, opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, storageDelegate.GetNumKeys() == 1); - NL_TEST_ASSERT(inSuite, storageDelegate.HasKey(opKeyStorageKey) == true); - NL_TEST_ASSERT(inSuite, testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore), CHIP_NO_ERROR); + EXPECT_EQ(storageDelegate.GetNumKeys(), 1u); + EXPECT_TRUE(storageDelegate.HasKey(opKeyStorageKey)); + EXPECT_FALSE(testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex)); // Verify the migration P256SerializedKeypair serializedKeypair; - NL_TEST_ASSERT(inSuite, opKeyStore.ExportOpKeypairForFabric(kFabricIndex, serializedKeypair) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, testOperationalKeystore.ValidateKeypair(serializedKeypair)); + EXPECT_EQ(opKeyStore.ExportOpKeypairForFabric(kFabricIndex, serializedKeypair), CHIP_NO_ERROR); + EXPECT_TRUE(testOperationalKeystore.ValidateKeypair(serializedKeypair)); // Verify that migration method returns success when there is no OpKey stored in the old keystore, but already exists in PSA // ITS. - NL_TEST_ASSERT(inSuite, opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore) == CHIP_NO_ERROR); + EXPECT_EQ(opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore), CHIP_NO_ERROR); // The key already exists in ITS, but there is an another attempt to migrate the new key. // The key should not be overwritten, but the key from the previous persistent keystore should be removed. MutableByteSpan csrSpan2{ csrBuf }; - NL_TEST_ASSERT(inSuite, testOperationalKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan2) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex) == true); - NL_TEST_ASSERT(inSuite, opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex) == false); + EXPECT_EQ(testOperationalKeystore.NewOpKeypairForFabric(kFabricIndex, csrSpan2), CHIP_NO_ERROR); + EXPECT_TRUE(testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex)); + EXPECT_EQ(opKeyStore.MigrateOpKeypairForFabric(kFabricIndex, testOperationalKeystore), CHIP_NO_ERROR); + EXPECT_FALSE(testOperationalKeystore.HasOpKeypairForFabric(kFabricIndex)); opKeyStore.Finish(); } -/** - * Test Suite. It lists all the test functions. - */ -static const nlTest sTests[] = { NL_TEST_DEF("Test Basic Lifecycle of PersistentStorageOperationalKeystore", TestBasicLifeCycle), - NL_TEST_DEF("Test ephemeral key management", TestEphemeralKeys), - NL_TEST_DEF("Test keys migration ", TestMigrationKeys), NL_TEST_SENTINEL() }; - -/** - * Set up the test suite. - */ -int Test_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - VerifyOrReturnError(error == CHIP_NO_ERROR, FAILURE); - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int Test_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - } // namespace - -/** - * Main - */ -int TestPersistentStorageOperationalKeystore() -{ - nlTestSuite theSuite = { "PersistentStorageOperationalKeystore tests", &sTests[0], Test_Setup, Test_Teardown }; - - // Run test suite againt one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPersistentStorageOperationalKeystore) diff --git a/src/crypto/tests/TestSessionKeystore.cpp b/src/crypto/tests/TestSessionKeystore.cpp index 025cd5c9233cbe..b3908d1695aaac 100644 --- a/src/crypto/tests/TestSessionKeystore.cpp +++ b/src/crypto/tests/TestSessionKeystore.cpp @@ -24,10 +24,8 @@ #include #include #include -#include -#include -#include +#include #if CHIP_CRYPTO_PSA #include @@ -101,7 +99,21 @@ ByteSpan ToSpan(const char * str) return ByteSpan(reinterpret_cast(str), strlen(str)); } -void TestBasicImport(nlTestSuite * inSuite, void * inContext) +struct TestSessionKeystore : public ::testing::Test +{ + static void SetUpTestSuite() + { + ASSERT_EQ(Platform::MemoryInit(), CHIP_NO_ERROR); + +#if CHIP_CRYPTO_PSA + psa_crypto_init(); +#endif + } + + static void TearDownTestSuite() { Platform::MemoryShutdown(); } +}; + +TEST_F(TestSessionKeystore, TestBasicImport) { TestSessionKeystoreImpl keystore; @@ -114,23 +126,23 @@ void TestBasicImport(nlTestSuite * inSuite, void * inContext) memcpy(keyMaterial, test.key, test.key_len); Aes128KeyHandle keyHandle; - NL_TEST_ASSERT_SUCCESS(inSuite, keystore.CreateKey(keyMaterial, keyHandle)); + EXPECT_EQ(keystore.CreateKey(keyMaterial, keyHandle), CHIP_NO_ERROR); Platform::ScopedMemoryBuffer ciphertext; Platform::ScopedMemoryBuffer tag; - NL_TEST_ASSERT(inSuite, ciphertext.Alloc(test.ct_len)); - NL_TEST_ASSERT(inSuite, tag.Alloc(test.tag_len)); - NL_TEST_ASSERT(inSuite, - AES_CCM_encrypt(test.pt, test.pt_len, test.aad, test.aad_len, keyHandle, test.nonce, test.nonce_len, - ciphertext.Get(), tag.Get(), test.tag_len) == test.result); - NL_TEST_ASSERT(inSuite, memcmp(ciphertext.Get(), test.ct, test.ct_len) == 0); - NL_TEST_ASSERT(inSuite, memcmp(tag.Get(), test.tag, test.tag_len) == 0); + EXPECT_TRUE(ciphertext.Alloc(test.ct_len)); + EXPECT_TRUE(tag.Alloc(test.tag_len)); + EXPECT_EQ(AES_CCM_encrypt(test.pt, test.pt_len, test.aad, test.aad_len, keyHandle, test.nonce, test.nonce_len, + ciphertext.Get(), tag.Get(), test.tag_len), + test.result); + EXPECT_EQ(memcmp(ciphertext.Get(), test.ct, test.ct_len), 0); + EXPECT_EQ(memcmp(tag.Get(), test.tag, test.tag_len), 0); keystore.DestroyKey(keyHandle); } } -void TestDeriveKey(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSessionKeystore, TestDeriveKey) { TestSessionKeystoreImpl keystore; @@ -141,18 +153,18 @@ void TestDeriveKey(nlTestSuite * inSuite, void * inContext) secret.SetLength(strlen(test.secret)); Aes128KeyHandle keyHandle; - NL_TEST_ASSERT_SUCCESS(inSuite, keystore.DeriveKey(secret, ToSpan(test.salt), ToSpan(test.info), keyHandle)); + EXPECT_EQ(keystore.DeriveKey(secret, ToSpan(test.salt), ToSpan(test.info), keyHandle), CHIP_NO_ERROR); uint8_t ciphertext[sizeof(test.ciphertext)]; - NL_TEST_ASSERT_SUCCESS( - inSuite, AES_CTR_crypt(test.plaintext, sizeof(test.plaintext), keyHandle, test.nonce, sizeof(test.nonce), ciphertext)); - NL_TEST_ASSERT(inSuite, memcmp(ciphertext, test.ciphertext, sizeof(test.ciphertext)) == 0); + EXPECT_EQ(AES_CTR_crypt(test.plaintext, sizeof(test.plaintext), keyHandle, test.nonce, sizeof(test.nonce), ciphertext), + CHIP_NO_ERROR); + EXPECT_EQ(memcmp(ciphertext, test.ciphertext, sizeof(test.ciphertext)), 0); keystore.DestroyKey(keyHandle); } } -void TestDeriveSessionKeys(nlTestSuite * inSuite, void * inContext) +TEST_F(TestSessionKeystore, TestDeriveSessionKeys) { TestSessionKeystoreImpl keystore; @@ -165,63 +177,27 @@ void TestDeriveSessionKeys(nlTestSuite * inSuite, void * inContext) Aes128KeyHandle i2r; Aes128KeyHandle r2i; AttestationChallenge challenge; - NL_TEST_ASSERT_SUCCESS( - inSuite, keystore.DeriveSessionKeys(ToSpan(test.secret), ToSpan(test.salt), ToSpan(test.info), i2r, r2i, challenge)); + EXPECT_EQ(keystore.DeriveSessionKeys(ToSpan(test.secret), ToSpan(test.salt), ToSpan(test.info), i2r, r2i, challenge), + CHIP_NO_ERROR); uint8_t ciphertext[sizeof(test.i2rCiphertext)]; // Test I2R key - NL_TEST_ASSERT_SUCCESS( - inSuite, AES_CTR_crypt(test.plaintext, sizeof(test.plaintext), i2r, test.nonce, sizeof(test.nonce), ciphertext)); - NL_TEST_ASSERT(inSuite, memcmp(ciphertext, test.i2rCiphertext, sizeof(test.i2rCiphertext)) == 0); + EXPECT_EQ(AES_CTR_crypt(test.plaintext, sizeof(test.plaintext), i2r, test.nonce, sizeof(test.nonce), ciphertext), + CHIP_NO_ERROR); + EXPECT_EQ(memcmp(ciphertext, test.i2rCiphertext, sizeof(test.i2rCiphertext)), 0); // Test R2I key - NL_TEST_ASSERT_SUCCESS( - inSuite, AES_CTR_crypt(test.plaintext, sizeof(test.plaintext), r2i, test.nonce, sizeof(test.nonce), ciphertext)); - NL_TEST_ASSERT(inSuite, memcmp(ciphertext, test.r2iCiphertext, sizeof(test.r2iCiphertext)) == 0); + EXPECT_EQ(AES_CTR_crypt(test.plaintext, sizeof(test.plaintext), r2i, test.nonce, sizeof(test.nonce), ciphertext), + CHIP_NO_ERROR); + EXPECT_EQ(memcmp(ciphertext, test.r2iCiphertext, sizeof(test.r2iCiphertext)), 0); // Check attestation challenge - NL_TEST_ASSERT(inSuite, memcmp(challenge.Bytes(), test.attestationChallenge, sizeof(test.attestationChallenge)) == 0); + EXPECT_EQ(memcmp(challenge.Bytes(), test.attestationChallenge, sizeof(test.attestationChallenge)), 0); keystore.DestroyKey(i2r); keystore.DestroyKey(r2i); } } -const nlTest sTests[] = { NL_TEST_DEF("Test basic import", TestBasicImport), NL_TEST_DEF("Test derive key", TestDeriveKey), - NL_TEST_DEF("Test derive session keys", TestDeriveSessionKeys), NL_TEST_SENTINEL() }; - -int Test_Setup(void * inContext) -{ - CHIP_ERROR error = Platform::MemoryInit(); - VerifyOrReturnError(error == CHIP_NO_ERROR, FAILURE); - -#if CHIP_CRYPTO_PSA - psa_crypto_init(); -#endif - - return SUCCESS; -} - -int Test_Teardown(void * inContext) -{ - Platform::MemoryShutdown(); - - return SUCCESS; -} - } // namespace - -/** - * Main - */ -int TestSessionKeystore() -{ - nlTestSuite theSuite = { "SessionKeystore tests", &sTests[0], Test_Setup, Test_Teardown }; - - // Run test suite againt one context. - nlTestRunner(&theSuite, nullptr); - return nlTestRunnerStats(&theSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestSessionKeystore) diff --git a/src/messaging/tests/TestAbortExchangesForFabric.cpp b/src/messaging/tests/TestAbortExchangesForFabric.cpp index a9999eb6c2f9e0..6dc5d8c2775cd3 100644 --- a/src/messaging/tests/TestAbortExchangesForFabric.cpp +++ b/src/messaging/tests/TestAbortExchangesForFabric.cpp @@ -37,6 +37,10 @@ #include // nogncheck #endif +#if CHIP_CRYPTO_PSA +#include "psa/crypto.h" +#endif + namespace { using namespace chip; @@ -45,7 +49,17 @@ using namespace chip::System; using namespace chip::System::Clock::Literals; using namespace chip::Protocols; -using TestContext = Test::LoopbackMessagingContext; +struct TestContext : Test::LoopbackMessagingContext +{ + virtual CHIP_ERROR SetUp() + { +#if CHIP_CRYPTO_PSA + ReturnErrorOnFailure(psa_crypto_init() == PSA_SUCCESS ? CHIP_NO_ERROR : CHIP_ERROR_INTERNAL); +#endif + ReturnErrorOnFailure(chip::Test::LoopbackMessagingContext::SetUp()); + return CHIP_NO_ERROR; + } +}; class MockAppDelegate : public ExchangeDelegate { diff --git a/src/messaging/tests/TestExchangeMgr.cpp b/src/messaging/tests/TestExchangeMgr.cpp index 69e1fbaa8f9afa..f85bebe455259e 100644 --- a/src/messaging/tests/TestExchangeMgr.cpp +++ b/src/messaging/tests/TestExchangeMgr.cpp @@ -40,6 +40,10 @@ #include #include +#if CHIP_CRYPTO_PSA +#include "psa/crypto.h" +#endif + namespace { using namespace chip; @@ -47,7 +51,19 @@ using namespace chip::Inet; using namespace chip::Transport; using namespace chip::Messaging; -using TestContext = Test::LoopbackMessagingContext; +struct TestContext : Test::LoopbackMessagingContext +{ + // TODO Add TearDown function during changing test framework to Pigweed to make it more clear how does it work. + // Currently, the TearDown function is from LoopbackMessagingContext + virtual CHIP_ERROR SetUp() + { +#if CHIP_CRYPTO_PSA + ReturnErrorOnFailure(psa_crypto_init() == PSA_SUCCESS ? CHIP_NO_ERROR : CHIP_ERROR_INTERNAL); +#endif + ReturnErrorOnFailure(chip::Test::LoopbackMessagingContext::SetUp()); + return CHIP_NO_ERROR; + } +}; enum : uint8_t { diff --git a/src/messaging/tests/TestReliableMessageProtocol.cpp b/src/messaging/tests/TestReliableMessageProtocol.cpp index 04b8a1aadb149f..7233e45fd846b5 100644 --- a/src/messaging/tests/TestReliableMessageProtocol.cpp +++ b/src/messaging/tests/TestReliableMessageProtocol.cpp @@ -50,6 +50,10 @@ #include // nogncheck #endif +#if CHIP_CRYPTO_PSA +#include "psa/crypto.h" +#endif + namespace { using namespace chip; @@ -75,6 +79,9 @@ class TestContext : public chip::Test::LoopbackMessagingContext // Performs setup for each individual test in the test suite CHIP_ERROR SetUp() override { +#if CHIP_CRYPTO_PSA + ReturnErrorOnFailure(psa_crypto_init() == PSA_SUCCESS ? CHIP_NO_ERROR : CHIP_ERROR_INTERNAL); +#endif ReturnErrorOnFailure(chip::Test::LoopbackMessagingContext::SetUp()); GetSessionAliceToBob()->AsSecureSession()->SetRemoteSessionParameters(GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())); GetSessionBobToAlice()->AsSecureSession()->SetRemoteSessionParameters(GetLocalMRPConfig().ValueOr(GetDefaultMRPConfig())); diff --git a/src/test_driver/openiotsdk/unit-tests/test_components.txt b/src/test_driver/openiotsdk/unit-tests/test_components.txt index 43a4bf883a9567..83dfc0d577bdb7 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components.txt @@ -1,12 +1,13 @@ accesstest +SystemLayerTests ASN1Tests MinimalMdnsCoreTests +ChipCryptoTests MinimalMdnsRecordsTests MinimalMdnsRespondersTests CoreTests MdnsTests PlatformTests -SystemLayerTests TestShell SetupPayloadTests SupportTests \ No newline at end of file diff --git a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt index 809a36b167c817..50b0fed3b5e724 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt @@ -1,6 +1,5 @@ AppTests BDXTests -ChipCryptoTests CredentialsTest DataModelTests InetLayerTests