From 38879492cb2916fee47c3bcb2e1da22362c06c00 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Wed, 15 May 2024 16:35:56 +0200 Subject: [PATCH 01/30] secure channel tests to pigweed --- src/protocols/secure_channel/tests/BUILD.gn | 38 +- .../tests/CheckIn_Message_test_vectors.h | 47 +- .../secure_channel/tests/TestCASESession.cpp | 875 ++++++++---------- .../secure_channel/tests/TestCheckinMsg.cpp | 132 +-- .../TestDefaultSessionResumptionStorage.cpp | 235 ++--- .../tests/TestMessageCounterManager.cpp | 110 +-- .../secure_channel/tests/TestPASESession.cpp | 357 +++---- .../tests/TestPairingSession.cpp | 116 +-- .../TestSimpleSessionResumptionStorage.cpp | 96 +- .../secure_channel/tests/TestStatusReport.cpp | 134 +-- 10 files changed, 868 insertions(+), 1272 deletions(-) diff --git a/src/protocols/secure_channel/tests/BUILD.gn b/src/protocols/secure_channel/tests/BUILD.gn index 371937c4297b7b..0ad5e785a8ca25 100644 --- a/src/protocols/secure_channel/tests/BUILD.gn +++ b/src/protocols/secure_channel/tests/BUILD.gn @@ -1,6 +1,5 @@ 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/app/icd/icd.gni") @@ -8,32 +7,9 @@ chip_test_suite("tests") { output_name = "libSecureChannelTests" test_sources = [ + "TestCASESession.cpp", "TestCheckInCounter.cpp", "TestCheckinMsg.cpp", - ] - - sources = [ "CheckIn_Message_test_vectors.h" ] - - cflags = [ "-Wconversion" ] - public_deps = [ - "${chip_root}/src/app/icd/server:icd-server-config", - "${chip_root}/src/credentials/tests:cert_test_vectors", - "${chip_root}/src/lib/core", - "${chip_root}/src/lib/support", - "${chip_root}/src/lib/support:test_utils", - "${chip_root}/src/lib/support:testing", - "${chip_root}/src/protocols/secure_channel", - "${chip_root}/src/protocols/secure_channel:check-in-counter", - "${dir_pw_unit_test}", - ] -} - -chip_test_suite_using_nltest("tests_nltest") { - # Renamed ouput during the transition away from nltest - output_name = "libSecureChannelTestsNL" - - test_sources = [ - "TestCASESession.cpp", "TestDefaultSessionResumptionStorage.cpp", "TestPASESession.cpp", "TestPairingSession.cpp", @@ -44,22 +20,26 @@ chip_test_suite_using_nltest("tests_nltest") { # "TestMessageCounterManager.cpp", ] + sources = [ "CheckIn_Message_test_vectors.h" ] + + cflags = [ "-Wconversion" ] public_deps = [ + "${chip_root}/src/app/icd/server:icd-server-config", + "${chip_root}/src/credentials/tests:cert_test_vectors", "${chip_root}/src/crypto/tests:tests.lib", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", + "${chip_root}/src/lib/support:pw_tests_wrapper", "${chip_root}/src/lib/support:test_utils", "${chip_root}/src/lib/support:testing", - "${chip_root}/src/lib/support:testing_nlunit", "${chip_root}/src/messaging/tests:helpers", "${chip_root}/src/protocols", "${chip_root}/src/protocols/secure_channel", + "${chip_root}/src/protocols/secure_channel:check-in-counter", "${chip_root}/src/transport/raw/tests:helpers", - "${nlunit_test_root}:nlunit-test", + "${dir_pw_unit_test}", ] - cflags = [ "-Wconversion" ] - if (chip_enable_icd_server) { public_deps += [ "${chip_root}/src/app/icd/server:configuration-data" ] } diff --git a/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h b/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h index 67a50f86c84c7a..5563150ebfee12 100644 --- a/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h +++ b/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h @@ -143,20 +143,19 @@ const CheckIn_Message_test_vector vector3 = { .key = kKey3, const uint8_t kKey4[] = { 0xca, 0x67, 0xd4, 0x1f, 0xf7, 0x11, 0x29, 0x10, 0xfd, 0xd1, 0x8a, 0x1b, 0xf9, 0x9e, 0xa9, 0x74 }; -const uint8_t kApplicationData4[] = { - 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x65, 0x72 -}; +const uint8_t kApplicationData4[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, + 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x75, 0x65, 0x72 }; const uint8_t kNonce4[] = { 0x7a, 0x97, 0x72, 0x24, 0x3c, 0x97, 0xc8, 0x7d, 0x5f, 0x3a, 0x31, 0xc4, 0xe6 }; -const uint8_t kCiphertext4[] = { 0xdb, 0xbc, 0x1a, 0xa5, 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, - 0x06, 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xda, 0x4a }; +const uint8_t kCiphertext4[] = { 0xdb, 0xbc, 0x1a, 0xa5, 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, 0x06, + 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xca, 0x5d, 0xad }; -const uint8_t kMic4[] = { 0x10, 0x5a, 0x13, 0x42, 0xad, 0xbf, 0x3f, 0x47, 0x98, 0xcd, 0x81, 0xb9, 0xef, 0x97, 0xbb, 0xb7 }; +const uint8_t kMic4[] = { 0x3d, 0x79, 0x78, 0xf7, 0x04, 0xe6, 0x30, 0xac, 0x04, 0x3f, 0xbf, 0xaa, 0x81, 0x25, 0xb2, 0xac }; const uint8_t kPayload4[] = { 0x7a, 0x97, 0x72, 0x24, 0x3c, 0x97, 0xc8, 0x7d, 0x5f, 0x3a, 0x31, 0xc4, 0xe6, 0xdb, 0xbc, 0x1a, 0xa5, - 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, 0x06, 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xda, 0x4a, 0x10, - 0x5a, 0x13, 0x42, 0xad, 0xbf, 0x3f, 0x47, 0x98, 0xcd, 0x81, 0xb9, 0xef, 0x97, 0xbb, 0xb7 }; + 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, 0x06, 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xca, 0x5d, 0xad, + 0x3d, 0x79, 0x78, 0xf7, 0x04, 0xe6, 0x30, 0xac, 0x04, 0x3f, 0xbf, 0xaa, 0x81, 0x25, 0xb2, 0xac }; const CheckIn_Message_test_vector vector4 = { .key = kKey4, .key_len = sizeof(kKey4), @@ -179,19 +178,19 @@ const CheckIn_Message_test_vector vector4 = { .key = kKey4, const uint8_t kKey5[] = { 0xca, 0x67, 0xd4, 0x1f, 0xf7, 0x11, 0x29, 0x10, 0xfd, 0xd1, 0x8a, 0x1b, 0xf9, 0x9e, 0xa9, 0x74 }; const uint8_t kApplicationData5[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x6c, 0x6f, - 0x6e, 0x67, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; + 0x6e, 0x67, 0x75, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; const uint8_t kNonce5[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8 }; const uint8_t kCiphertext5[] = { 0x2e, 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, 0x51, - 0x7f, 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x31, 0x5a, 0x1e, 0x32, 0x08, 0xb8 }; + 0x7f, 0xf3, 0xc9, 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x5d, 0x18, 0x29, 0x0f, 0xb1, 0x21 }; -const uint8_t kMic5[] = { 0xec, 0xf6, 0x11, 0x8b, 0x02, 0x1a, 0x5a, 0x4c, 0xd4, 0xe9, 0xd4, 0x13, 0x8d, 0xff, 0x29, 0x71 }; +const uint8_t kMic5[] = { 0x8b, 0x5d, 0xef, 0x99, 0x65, 0xb4, 0xdc, 0x3a, 0x87, 0x25, 0xc2, 0xeb, 0x2e, 0x18, 0x25, 0x98 }; -const uint8_t kPayload5[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8, 0x2e, - 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, 0x51, 0x7f, - 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x31, 0x5a, 0x1e, 0x32, 0x08, 0xb8, 0xec, 0xf6, - 0x11, 0x8b, 0x02, 0x1a, 0x5a, 0x4c, 0xd4, 0xe9, 0xd4, 0x13, 0x8d, 0xff, 0x29, 0x71 }; +const uint8_t kPayload5[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8, 0x2e, 0x5b, + 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, 0x51, 0x7f, 0xf3, 0xc9, + 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x5d, 0x18, 0x29, 0x0f, 0xb1, 0x21, 0x8b, 0x5d, 0xef, 0x99, + 0x65, 0xb4, 0xdc, 0x3a, 0x87, 0x25, 0xc2, 0xeb, 0x2e, 0x18, 0x25, 0x98 }; const CheckIn_Message_test_vector vector5 = { .key = kKey5, .key_len = sizeof(kKey5), @@ -217,25 +216,25 @@ const uint8_t kInvalidNonceKey[] = { 0xca, 0x67, 0xd4, 0x1f, 0xf7, 0x11, 0x29, 0x10, 0xfd, 0xd1, 0x8a, 0x1b, 0xf9, 0x9e, 0xa9, 0x74 }; -const uint8_t kInvalidNonceApplicationData[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, - 0x6c, 0x6f, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x6c, 0x6f, 0x6e, - 0x67, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; +const uint8_t kInvalidNonceApplicationData[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x6c, + 0x6f, 0x6e, 0x67, 0x75, 0x65, 0x72, 0x20, 0x6c, 0x6f, 0x6e, 0x67, + 0x75, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; const uint8_t kInvalidNonceNonce[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8 }; const uint8_t kInvalidNonceCiphertext[] = { 0x29, 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, - 0x53, 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x2e, 0x41, 0x02, - 0x3c, 0x03, 0xad, 0x66, 0xac, 0x4d, 0xca, 0x72, 0x47, 0xe0 }; + 0x53, 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x42, 0x03, + 0x35, 0x01, 0xaa, 0x23, 0xad, 0x19, 0xcb, 0x6f, 0x5b, 0xee, 0x56, 0xb3 }; const uint8_t kInvalidNonceMic[] = { - 0xe4, 0xc6, 0x6b, 0xd9, 0xd3, 0x99, 0x13, 0xe2, 0x3d, 0x82, 0x32, 0xb9, 0x61, 0xfa, 0x92, 0x26 + 0xd5, 0x8a, 0x92, 0x2b, 0x66, 0x44, 0x89, 0x3e, 0x66, 0x31, 0x8b, 0xb5, 0x53, 0x79, 0x24, 0x8b }; const uint8_t kInvalidNoncePayload[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8, 0x29, 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, - 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x2e, 0x41, 0x02, 0x3c, 0x03, - 0xad, 0x66, 0xac, 0x4d, 0xca, 0x72, 0x47, 0xe0, 0xe4, 0xc6, 0x6b, 0xd9, 0xd3, - 0x99, 0x13, 0xe2, 0x3d, 0x82, 0x32, 0xb9, 0x61, 0xfa, 0x92, 0x26 }; + 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x42, 0x03, 0x35, 0x01, + 0xaa, 0x23, 0xad, 0x19, 0xcb, 0x6f, 0x5b, 0xee, 0x56, 0xb3, 0xd5, 0x8a, 0x92, + 0x2b, 0x66, 0x44, 0x89, 0x3e, 0x66, 0x31, 0x8b, 0xb5, 0x53, 0x79, 0x24, 0x8b }; const CheckIn_Message_test_vector invalidNonceVector = { .key = kInvalidNonceKey, .key_len = sizeof(kInvalidNonceKey), diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 5fc6a37f72f4ab..a16ffbca199be8 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -34,13 +35,11 @@ #include #include #include -#include -#include #include -#include #include #include #include +#include #include "credentials/tests/CHIPCert_test_vectors.h" @@ -55,40 +54,177 @@ using namespace chip::Protocols; using namespace chip::Crypto; namespace chip { -namespace { -class TestContext : public Test::LoopbackMessagingContext +class TestCASESecurePairingDelegate; + +class TestOperationalKeystore : public chip::Crypto::OperationalKeystore { public: - // Performs shared setup for all tests in the test suite - static void SetUpTestSuite(); - // Performs shared teardown for all tests in the test suite - static void TearDownTestSuite(); + void Init(FabricIndex fabricIndex, Platform::UniquePtr keypair) + { + mSingleFabricIndex = fabricIndex; + mKeypair = std::move(keypair); + } + void Shutdown() + { + mSingleFabricIndex = kUndefinedFabricIndex; + mKeypair = nullptr; + } + + bool HasPendingOpKeypair() const override { return false; } + bool HasOpKeypairForFabric(FabricIndex fabricIndex) const override { return mSingleFabricIndex != kUndefinedFabricIndex; } + + CHIP_ERROR NewOpKeypairForFabric(FabricIndex fabricIndex, MutableByteSpan & outCertificateSigningRequest) override + { + return CHIP_ERROR_NOT_IMPLEMENTED; + } + + CHIP_ERROR ActivateOpKeypairForFabric(FabricIndex fabricIndex, const Crypto::P256PublicKey & nocPublicKey) override + { + return CHIP_NO_ERROR; + } + + CHIP_ERROR CommitOpKeypairForFabric(FabricIndex fabricIndex) override { return CHIP_ERROR_NOT_IMPLEMENTED; } + CHIP_ERROR RemoveOpKeypairForFabric(FabricIndex fabricIndex) override { return CHIP_ERROR_NOT_IMPLEMENTED; } + + void RevertPendingKeypair() override {} + + CHIP_ERROR SignWithOpKeypair(FabricIndex fabricIndex, const ByteSpan & message, + Crypto::P256ECDSASignature & outSignature) const override + { + VerifyOrReturnError(mKeypair != nullptr, CHIP_ERROR_INCORRECT_STATE); + VerifyOrReturnError(fabricIndex == mSingleFabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX); + return mKeypair->ECDSA_sign_msg(message.data(), message.size(), outSignature); + } + + Crypto::P256Keypair * AllocateEphemeralKeypairForCASE() override { return Platform::New(); } + + void ReleaseEphemeralKeypair(Crypto::P256Keypair * keypair) override { Platform::Delete(keypair); } + +protected: + Platform::UniquePtr mKeypair; + FabricIndex mSingleFabricIndex = kUndefinedFabricIndex; }; -void ServiceEvents(TestContext & ctx) +struct TestCASESession : public Test::LoopbackMessagingContext, public ::testing::Test { - // Takes a few rounds of this because handling IO messages may schedule work, - // and scheduled work may queue messages for sending... - for (int i = 0; i < 3; ++i) + static void SetUpTestSuite() { - ctx.DrainAndServiceIO(); + ConfigInitializeNodes(false); + CHIP_ERROR err = CHIP_NO_ERROR; + LoopbackMessagingContext::SetUpTestSuite(); + err = chip::DeviceLayer::PlatformMgr().InitChipStack(); + + EXPECT_EQ(err, CHIP_NO_ERROR) << "Init CHIP stack failed: " << std::hex << err.Format(); + err = + InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, &gCommissionerOpCertStore); + EXPECT_EQ(err, CHIP_NO_ERROR) << "InitFabricTable failed: " << std::hex << err.Format(); + + err = InitCredentialSets(); + EXPECT_EQ(err, CHIP_NO_ERROR) << "InitCredentialSets failed: " << std::hex << err.Format(); + chip::DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); + } - chip::DeviceLayer::PlatformMgr().ScheduleWork( - [](intptr_t) -> void { chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); }, (intptr_t) nullptr); - chip::DeviceLayer::PlatformMgr().RunEventLoop(); + static void TearDownTestSuite() + { + chip::DeviceLayer::SetSystemLayerForTesting(nullptr); + gDeviceOperationalKeystore.Shutdown(); + gPairingServer.Shutdown(); + gCommissionerStorageDelegate.ClearStorage(); + gDeviceStorageDelegate.ClearStorage(); + gCommissionerFabrics.DeleteAllFabrics(); + gDeviceFabrics.DeleteAllFabrics(); + chip::DeviceLayer::PlatformMgr().Shutdown(); + LoopbackMessagingContext::TearDownTestSuite(); } -} + + void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } + + void ServiceEvents() + { + // Takes a few rounds of this because handling IO messages may schedule work, + // and scheduled work may queue messages for sending... + for (int i = 0; i < 3; ++i) + { + DrainAndServiceIO(); + + chip::DeviceLayer::PlatformMgr().ScheduleWork( + [](intptr_t) -> void { chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); }, (intptr_t) nullptr); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); + } + }; + + static CHIP_ERROR InitCredentialSets(); + static CHIP_ERROR InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, + chip::Crypto::OperationalKeystore * opKeyStore, + chip::Credentials::PersistentStorageOpCertStore * opCertStore); + + void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, + TestCASESecurePairingDelegate & delegateCommissioner); + + void SimulateUpdateNOCInvalidatePendingEstablishment(); + +#if CHIP_CONFIG_SLOW_CRYPTO + constexpr uint32_t sTestCaseMessageCount = 8; + constexpr uint32_t sTestCaseResumptionMessageCount = 6; +#else // CHIP_CONFIG_SLOW_CRYPTO + static constexpr uint32_t sTestCaseMessageCount = 5; + static constexpr uint32_t sTestCaseResumptionMessageCount = 4; +#endif // CHIP_CONFIG_SLOW_CRYPTO + + static FabricTable gCommissionerFabrics; + static FabricIndex gCommissionerFabricIndex; + static GroupDataProviderImpl gCommissionerGroupDataProvider; + static TestPersistentStorageDelegate gCommissionerStorageDelegate; + static Crypto::DefaultSessionKeystore gCommissionerSessionKeystore; + + static FabricTable gDeviceFabrics; + static FabricIndex gDeviceFabricIndex; + static GroupDataProviderImpl gDeviceGroupDataProvider; + static TestPersistentStorageDelegate gDeviceStorageDelegate; + static TestOperationalKeystore gDeviceOperationalKeystore; + static Crypto::DefaultSessionKeystore gDeviceSessionKeystore; + + static Credentials::PersistentStorageOpCertStore gCommissionerOpCertStore; + static Credentials::PersistentStorageOpCertStore gDeviceOpCertStore; + + static CASEServer gPairingServer; + + static NodeId Node01_01; + static NodeId Node01_02; +}; + +NodeId TestCASESession::Node01_01 = 0xDEDEDEDE00010001; +NodeId TestCASESession::Node01_02 = 0xDEDEDEDE00010002; + +FabricTable TestCASESession::gCommissionerFabrics; +FabricIndex TestCASESession::gCommissionerFabricIndex; +GroupDataProviderImpl TestCASESession::gCommissionerGroupDataProvider; +TestPersistentStorageDelegate TestCASESession::gCommissionerStorageDelegate; +Crypto::DefaultSessionKeystore TestCASESession::gCommissionerSessionKeystore; + +FabricTable TestCASESession::gDeviceFabrics; +FabricIndex TestCASESession::gDeviceFabricIndex; +GroupDataProviderImpl TestCASESession::gDeviceGroupDataProvider; +TestPersistentStorageDelegate TestCASESession::gDeviceStorageDelegate; +TestOperationalKeystore TestCASESession::gDeviceOperationalKeystore; +Crypto::DefaultSessionKeystore TestCASESession::gDeviceSessionKeystore; + +Credentials::PersistentStorageOpCertStore TestCASESession::gCommissionerOpCertStore; +Credentials::PersistentStorageOpCertStore TestCASESession::gDeviceOpCertStore; + +CASEServer TestCASESession::gPairingServer; + class TemporarySessionManager { public: - TemporarySessionManager(nlTestSuite * suite, TestContext & ctx) : mCtx(ctx) + TemporarySessionManager(TestCASESession & ctx) : mCtx(ctx) { - NL_TEST_ASSERT(suite, - CHIP_NO_ERROR == - mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), - &mStorage, &ctx.GetFabricTable(), ctx.GetSessionKeystore())); + EXPECT_EQ(CHIP_NO_ERROR, + mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), &mStorage, + &ctx.GetFabricTable(), ctx.GetSessionKeystore())); // The setup here is really weird: we are using one session manager for // the actual messages we send (the PASE handshake, so the // unauthenticated sessions) and a different one for allocating the PASE @@ -108,12 +244,12 @@ class TemporarySessionManager operator SessionManager &() { return mSessionManager; } private: - TestContext & mCtx; + TestCASESession & mCtx; TestPersistentStorageDelegate mStorage; SessionManager mSessionManager; }; -CHIP_ERROR InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, +CHIP_ERROR TestCASESession::InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, chip::Crypto::OperationalKeystore * opKeyStore, chip::Credentials::PersistentStorageOpCertStore * opCertStore) { @@ -155,83 +291,7 @@ class TestCASESecurePairingDelegate : public SessionEstablishmentDelegate uint32_t mNumBusyResponses = 0; }; -class TestOperationalKeystore : public chip::Crypto::OperationalKeystore -{ -public: - void Init(FabricIndex fabricIndex, Platform::UniquePtr keypair) - { - mSingleFabricIndex = fabricIndex; - mKeypair = std::move(keypair); - } - void Shutdown() - { - mSingleFabricIndex = kUndefinedFabricIndex; - mKeypair = nullptr; - } - - bool HasPendingOpKeypair() const override { return false; } - bool HasOpKeypairForFabric(FabricIndex fabricIndex) const override { return mSingleFabricIndex != kUndefinedFabricIndex; } - - CHIP_ERROR NewOpKeypairForFabric(FabricIndex fabricIndex, MutableByteSpan & outCertificateSigningRequest) override - { - return CHIP_ERROR_NOT_IMPLEMENTED; - } - - CHIP_ERROR ActivateOpKeypairForFabric(FabricIndex fabricIndex, const Crypto::P256PublicKey & nocPublicKey) override - { - return CHIP_NO_ERROR; - } - - CHIP_ERROR CommitOpKeypairForFabric(FabricIndex fabricIndex) override { return CHIP_ERROR_NOT_IMPLEMENTED; } - CHIP_ERROR RemoveOpKeypairForFabric(FabricIndex fabricIndex) override { return CHIP_ERROR_NOT_IMPLEMENTED; } - - void RevertPendingKeypair() override {} - - CHIP_ERROR SignWithOpKeypair(FabricIndex fabricIndex, const ByteSpan & message, - Crypto::P256ECDSASignature & outSignature) const override - { - VerifyOrReturnError(mKeypair != nullptr, CHIP_ERROR_INCORRECT_STATE); - VerifyOrReturnError(fabricIndex == mSingleFabricIndex, CHIP_ERROR_INVALID_FABRIC_INDEX); - return mKeypair->ECDSA_sign_msg(message.data(), message.size(), outSignature); - } - - Crypto::P256Keypair * AllocateEphemeralKeypairForCASE() override { return Platform::New(); } - - void ReleaseEphemeralKeypair(Crypto::P256Keypair * keypair) override { Platform::Delete(keypair); } - -protected: - Platform::UniquePtr mKeypair; - FabricIndex mSingleFabricIndex = kUndefinedFabricIndex; -}; - -#if CHIP_CONFIG_SLOW_CRYPTO -constexpr uint32_t sTestCaseMessageCount = 8; -constexpr uint32_t sTestCaseResumptionMessageCount = 6; -#else // CHIP_CONFIG_SLOW_CRYPTO -constexpr uint32_t sTestCaseMessageCount = 5; -constexpr uint32_t sTestCaseResumptionMessageCount = 4; -#endif // CHIP_CONFIG_SLOW_CRYPTO - -FabricTable gCommissionerFabrics; -FabricIndex gCommissionerFabricIndex; -GroupDataProviderImpl gCommissionerGroupDataProvider; -TestPersistentStorageDelegate gCommissionerStorageDelegate; -Crypto::DefaultSessionKeystore gCommissionerSessionKeystore; -FabricTable gDeviceFabrics; -FabricIndex gDeviceFabricIndex; -GroupDataProviderImpl gDeviceGroupDataProvider; -TestPersistentStorageDelegate gDeviceStorageDelegate; -TestOperationalKeystore gDeviceOperationalKeystore; -Crypto::DefaultSessionKeystore gDeviceSessionKeystore; - -Credentials::PersistentStorageOpCertStore gCommissionerOpCertStore; -Credentials::PersistentStorageOpCertStore gDeviceOpCertStore; - -CASEServer gPairingServer; - -NodeId Node01_01 = 0xDEDEDEDE00010001; -NodeId Node01_02 = 0xDEDEDEDE00010002; CHIP_ERROR InitTestIpk(GroupDataProvider & groupDataProvider, const FabricInfo & fabricInfo, size_t numIpks) { @@ -255,7 +315,7 @@ CHIP_ERROR InitTestIpk(GroupDataProvider & groupDataProvider, const FabricInfo & return groupDataProvider.SetKeySet(fabricInfo.GetFabricIndex(), compressedIdSpan, ipkKeySet); } -CHIP_ERROR InitCredentialSets() +CHIP_ERROR TestCASESession::InitCredentialSets() { gCommissionerStorageDelegate.ClearStorage(); gCommissionerGroupDataProvider.SetStorageDelegate(&gCommissionerStorageDelegate); @@ -327,81 +387,32 @@ CHIP_ERROR InitCredentialSets() return CHIP_NO_ERROR; } -void TestContext::SetUpTestSuite() -{ - ConfigInitializeNodes(false); - CHIP_ERROR err = CHIP_NO_ERROR; - LoopbackMessagingContext::SetUpTestSuite(); - // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete - VerifyOrDieWithMsg((err = chip::DeviceLayer::PlatformMgr().InitChipStack()) == CHIP_NO_ERROR, AppServer, - "Init CHIP stack failed: %" CHIP_ERROR_FORMAT, err.Format()); - VerifyOrDieWithMsg((err = InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, - &gCommissionerOpCertStore)) == CHIP_NO_ERROR, - AppServer, "InitFabricTable failed: %" CHIP_ERROR_FORMAT, err.Format()); - VerifyOrDieWithMsg((err = InitCredentialSets()) == CHIP_NO_ERROR, AppServer, "InitCredentialSets failed: %" CHIP_ERROR_FORMAT, - err.Format()); - chip::DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); -} - -void TestContext::TearDownTestSuite() -{ - chip::DeviceLayer::SetSystemLayerForTesting(nullptr); - gDeviceOperationalKeystore.Shutdown(); - gPairingServer.Shutdown(); - gCommissionerStorageDelegate.ClearStorage(); - gDeviceStorageDelegate.ClearStorage(); - gCommissionerFabrics.DeleteAllFabrics(); - gDeviceFabrics.DeleteAllFabrics(); - chip::DeviceLayer::PlatformMgr().Shutdown(); - LoopbackMessagingContext::TearDownTestSuite(); -} - -} // anonymous namespace // Specifically for SimulateUpdateNOCInvalidatePendingEstablishment, we need it to be static so that the class below can // be a friend to CASESession so that test can get access to CASESession::State and test method that are not public. To // keep the rest of this file consistent we brought all other tests into this class. -class TestCASESession -{ -public: - static void SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext); - static void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext); - static void SecurePairingHandshakeTest(nlTestSuite * inSuite, void * inContext); - static void SecurePairingHandshakeServerTest(nlTestSuite * inSuite, void * inContext); - static void ClientReceivesBusyTest(nlTestSuite * inSuite, void * inContext); - static void Sigma1ParsingTest(nlTestSuite * inSuite, void * inContext); - static void DestinationIdTest(nlTestSuite * inSuite, void * inContext); - static void SessionResumptionStorage(nlTestSuite * inSuite, void * inContext); -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - static void SimulateUpdateNOCInvalidatePendingEstablishment(nlTestSuite * inSuite, void * inContext); -#endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST - static void Sigma1BadDestinationIdTest(nlTestSuite * inSuite, void * inContext); -}; -void TestCASESession::SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SecurePairingWaitTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; FabricTable fabrics; CASESession caseSession; - NL_TEST_ASSERT(inSuite, caseSession.GetSecureSessionType() == SecureSession::Type::kCASE); + EXPECT_EQ(caseSession.GetSecureSessionType(), SecureSession::Type::kCASE); caseSession.SetGroupDataProvider(&gDeviceGroupDataProvider); - NL_TEST_ASSERT(inSuite, - caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, nullptr, ScopedNodeId(), - Optional::Missing()) == - CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(inSuite, - caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, &delegate, ScopedNodeId(), - Optional::Missing()) == - CHIP_ERROR_INVALID_ARGUMENT); - NL_TEST_ASSERT(inSuite, - caseSession.PrepareForSessionEstablishment(sessionManager, &fabrics, nullptr, nullptr, &delegate, ScopedNodeId(), - Optional::Missing()) == CHIP_NO_ERROR); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, nullptr, ScopedNodeId(), + Optional::Missing()), + CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, nullptr, nullptr, nullptr, &delegate, ScopedNodeId(), + Optional::Missing()), + CHIP_ERROR_INVALID_ARGUMENT); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, &fabrics, nullptr, nullptr, &delegate, ScopedNodeId(), + Optional::Missing()), + CHIP_NO_ERROR); // Calling Clear() here since ASAN will have an issue if FabricTable destructor is called before CASESession's // destructor. We could reorder FabricTable and CaseSession, but this makes it a little more clear what we are @@ -409,42 +420,38 @@ void TestCASESession::SecurePairingWaitTest(nlTestSuite * inSuite, void * inCont caseSession.Clear(); } -void TestCASESession::SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SecurePairingStartTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; CASESession pairing; pairing.SetGroupDataProvider(&gCommissionerGroupDataProvider); - ExchangeContext * context = ctx.NewUnauthenticatedExchangeToBob(&pairing); + ExchangeContext * context = NewUnauthenticatedExchangeToBob(&pairing); - NL_TEST_ASSERT(inSuite, - pairing.EstablishSession(sessionManager, nullptr, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, nullptr, - nullptr, nullptr, nullptr, - Optional::Missing()) != CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_NE(pairing.EstablishSession(sessionManager, nullptr, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, nullptr, + nullptr, nullptr, nullptr, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, - pairing.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, nullptr, nullptr, nullptr, nullptr, - Optional::Missing()) != CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_NE(pairing.EstablishSession(sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + nullptr, nullptr, nullptr, nullptr, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, - pairing.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, context, nullptr, nullptr, - &delegate, Optional::Missing()) == CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_EQ(pairing.EstablishSession(sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + context, nullptr, nullptr, &delegate, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); // There should have been two message sent: Sigma1 and an ack. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == 2); + EXPECT_EQ(loopback.mSentMessageCount, 2u); - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(inSuite, rm->TestGetCountRetransTable() == 0); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); loopback.mMessageSendError = CHIP_ERROR_BAD_REQUEST; @@ -453,22 +460,19 @@ void TestCASESession::SecurePairingStartTest(nlTestSuite * inSuite, void * inCon loopback.mSentMessageCount = 0; loopback.mMessageSendError = CHIP_ERROR_BAD_REQUEST; - ExchangeContext * context1 = ctx.NewUnauthenticatedExchangeToBob(&pairing1); + ExchangeContext * context1 = NewUnauthenticatedExchangeToBob(&pairing1); - NL_TEST_ASSERT(inSuite, - pairing1.EstablishSession( - sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, context1, - nullptr, nullptr, &delegate, Optional::Missing()) == CHIP_ERROR_BAD_REQUEST); - ServiceEvents(ctx); + EXPECT_EQ(pairing1.EstablishSession(sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + context1, nullptr, nullptr, &delegate, Optional::Missing()), + CHIP_ERROR_BAD_REQUEST); + ServiceEvents(); loopback.mMessageSendError = CHIP_NO_ERROR; } -void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, SessionManager & sessionManager, - CASESession & pairingCommissioner, TestCASESecurePairingDelegate & delegateCommissioner) +void TestCASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, + TestCASESecurePairingDelegate & delegateCommissioner) { - TestContext & ctx = *reinterpret_cast(inContext); - // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegateAccessory; CASESession pairingAccessory; @@ -477,39 +481,36 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S ReliableMessageProtocolConfig nonSleepyCommissionerRmpConfig( System::Clock::Milliseconds32(5000), System::Clock::Milliseconds32(300), System::Clock::Milliseconds16(4000)); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, - &pairingAccessory) == CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, + &pairingAccessory), + CHIP_NO_ERROR); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); pairingAccessory.SetGroupDataProvider(&gDeviceGroupDataProvider); - NL_TEST_ASSERT(inSuite, - pairingAccessory.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, - &delegateAccessory, ScopedNodeId(), - MakeOptional(verySleepyAccessoryRmpConfig)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, - nullptr, nullptr, &delegateCommissioner, - MakeOptional(nonSleepyCommissionerRmpConfig)) == CHIP_NO_ERROR); - ServiceEvents(ctx); - - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout == System::Clock::Milliseconds32(5000)); - NL_TEST_ASSERT(inSuite, pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout == System::Clock::Milliseconds32(300)); - NL_TEST_ASSERT(inSuite, pairingAccessory.GetRemoteMRPConfig().mActiveThresholdTime == System::Clock::Milliseconds16(4000)); - NL_TEST_ASSERT(inSuite, pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout == System::Clock::Milliseconds32(360000)); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout == System::Clock::Milliseconds32(100000)); - NL_TEST_ASSERT(inSuite, pairingCommissioner.GetRemoteMRPConfig().mActiveThresholdTime == System::Clock::Milliseconds16(300)); + EXPECT_EQ(pairingAccessory.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &delegateAccessory, + ScopedNodeId(), MakeOptional(verySleepyAccessoryRmpConfig)), + CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner.EstablishSession( + sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, + nullptr, nullptr, &delegateCommissioner, MakeOptional(nonSleepyCommissionerRmpConfig)), + CHIP_NO_ERROR); + ServiceEvents(); + + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout, System::Clock::Milliseconds32(5000)); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout, System::Clock::Milliseconds32(300)); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mActiveThresholdTime, System::Clock::Milliseconds16(4000)); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout, System::Clock::Milliseconds32(360000)); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout, System::Clock::Milliseconds32(100000)); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mActiveThresholdTime, System::Clock::Milliseconds16(300)); #if CONFIG_BUILD_FOR_HOST_UNIT_TEST // Confirming that FabricTable sending a notification that fabric was updated doesn't affect // already established connections. @@ -517,26 +518,25 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S // This is compiled for host tests which is enough test coverage gCommissionerFabrics.SendUpdateFabricNotificationForTest(gCommissionerFabricIndex); gDeviceFabrics.SendUpdateFabricNotificationForTest(gDeviceFabricIndex); - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST } -void TestCASESession::SecurePairingHandshakeTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SecurePairingHandshakeTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; pairingCommissioner.SetGroupDataProvider(&gCommissionerGroupDataProvider); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, delegateCommissioner); + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, delegateCommissioner); } -void TestCASESession::SecurePairingHandshakeServerTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SecurePairingHandshakeServerTest) { // TODO: Add cases for mismatching IPK config between initiator/responder @@ -545,47 +545,43 @@ void TestCASESession::SecurePairingHandshakeServerTest(nlTestSuite * inSuite, vo auto * pairingCommissioner = chip::Platform::New(); pairingCommissioner->SetGroupDataProvider(&gCommissionerGroupDataProvider); - TestContext & ctx = *reinterpret_cast(inContext); - - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; // Use the same session manager on both CASE client and server sides to validate that both // components may work simultaneously on a single device. - NL_TEST_ASSERT(inSuite, - gPairingServer.ListenForSessionEstablishment(&ctx.GetExchangeManager(), &ctx.GetSecureSessionManager(), - &gDeviceFabrics, nullptr, nullptr, - &gDeviceGroupDataProvider) == CHIP_NO_ERROR); + EXPECT_EQ(gPairingServer.ListenForSessionEstablishment(&GetExchangeManager(), &GetSecureSessionManager(), &gDeviceFabrics, + nullptr, nullptr, &gDeviceGroupDataProvider), + CHIP_NO_ERROR); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(pairingCommissioner); - NL_TEST_ASSERT(inSuite, - pairingCommissioner->EstablishSession(ctx.GetSecureSessionManager(), &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, - nullptr, nullptr, &delegateCommissioner, - Optional::Missing()) == CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_EQ(pairingCommissioner->EstablishSession( + GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + contextCommissioner, nullptr, nullptr, &delegateCommissioner, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); // Validate that secure session is created SessionHolder & holder = delegateCommissioner.GetSessionHolder(); - NL_TEST_ASSERT(inSuite, bool(holder)); + EXPECT_TRUE(bool(holder)); - NL_TEST_ASSERT(inSuite, (holder->GetPeer() == chip::ScopedNodeId{ Node01_01, gCommissionerFabricIndex })); + EXPECT_TRUE((holder->GetPeer() == chip::ScopedNodeId{ Node01_01, gCommissionerFabricIndex })); auto * pairingCommissioner1 = chip::Platform::New(); pairingCommissioner1->SetGroupDataProvider(&gCommissionerGroupDataProvider); - ExchangeContext * contextCommissioner1 = ctx.NewUnauthenticatedExchangeToBob(pairingCommissioner1); + ExchangeContext * contextCommissioner1 = NewUnauthenticatedExchangeToBob(pairingCommissioner1); - NL_TEST_ASSERT(inSuite, - pairingCommissioner1->EstablishSession(ctx.GetSecureSessionManager(), &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, - nullptr, nullptr, &delegateCommissioner, - Optional::Missing()) == CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner1->EstablishSession(GetSecureSessionManager(), &gCommissionerFabrics, + ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, + nullptr, nullptr, &delegateCommissioner, + Optional::Missing()), + CHIP_NO_ERROR); - ServiceEvents(ctx); + ServiceEvents(); chip::Platform::Delete(pairingCommissioner); chip::Platform::Delete(pairingCommissioner1); @@ -593,10 +589,9 @@ void TestCASESession::SecurePairingHandshakeServerTest(nlTestSuite * inSuite, vo gPairingServer.Shutdown(); } -void TestCASESession::ClientReceivesBusyTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, ClientReceivesBusyTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner1, delegateCommissioner2; CASESession pairingCommissioner1, pairingCommissioner2; @@ -604,41 +599,40 @@ void TestCASESession::ClientReceivesBusyTest(nlTestSuite * inSuite, void * inCon pairingCommissioner1.SetGroupDataProvider(&gCommissionerGroupDataProvider); pairingCommissioner2.SetGroupDataProvider(&gCommissionerGroupDataProvider); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - gPairingServer.ListenForSessionEstablishment(&ctx.GetExchangeManager(), &ctx.GetSecureSessionManager(), - &gDeviceFabrics, nullptr, nullptr, - &gDeviceGroupDataProvider) == CHIP_NO_ERROR); + EXPECT_EQ(gPairingServer.ListenForSessionEstablishment(&GetExchangeManager(), &GetSecureSessionManager(), &gDeviceFabrics, + nullptr, nullptr, &gDeviceGroupDataProvider), + CHIP_NO_ERROR); - ExchangeContext * contextCommissioner1 = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner1); - ExchangeContext * contextCommissioner2 = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner2); + ExchangeContext * contextCommissioner1 = NewUnauthenticatedExchangeToBob(&pairingCommissioner1); + ExchangeContext * contextCommissioner2 = NewUnauthenticatedExchangeToBob(&pairingCommissioner2); - NL_TEST_ASSERT(inSuite, - pairingCommissioner1.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, - nullptr, nullptr, &delegateCommissioner1, NullOptional) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - pairingCommissioner2.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner2, - nullptr, nullptr, &delegateCommissioner2, NullOptional) == CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner1.EstablishSession(sessionManager, &gCommissionerFabrics, + ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner1, + nullptr, nullptr, &delegateCommissioner1, NullOptional), + CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner2.EstablishSession(sessionManager, &gCommissionerFabrics, + ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner2, + nullptr, nullptr, &delegateCommissioner2, NullOptional), + CHIP_NO_ERROR); - ServiceEvents(ctx); + ServiceEvents(); // We should have one full handshake and one Sigma1 + Busy + ack. If that // ever changes (e.g. because our server starts supporting multiple parallel // handshakes), this test needs to be fixed so that the server is still // responding BUSY to the client. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == sTestCaseMessageCount + 3); - NL_TEST_ASSERT(inSuite, delegateCommissioner1.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner2.mNumPairingComplete == 0); + EXPECT_EQ(loopback.mSentMessageCount, sTestCaseMessageCount + 3); + EXPECT_EQ(delegateCommissioner1.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner2.mNumPairingComplete, 0u); - NL_TEST_ASSERT(inSuite, delegateCommissioner1.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner2.mNumPairingErrors == 1); + EXPECT_EQ(delegateCommissioner1.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner2.mNumPairingErrors, 1u); - NL_TEST_ASSERT(inSuite, delegateCommissioner1.mNumBusyResponses == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner2.mNumBusyResponses == 1); + EXPECT_EQ(delegateCommissioner1.mNumBusyResponses, 0u); + EXPECT_EQ(delegateCommissioner2.mNumBusyResponses, 1u); gPairingServer.Shutdown(); } @@ -667,7 +661,7 @@ struct Sigma1Params static constexpr bool expectSuccess = true; }; -void TestCASESession::DestinationIdTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, DestinationIdTest) { // Validate example test vector from CASE section of spec @@ -702,9 +696,9 @@ void TestCASESession::DestinationIdTest(nlTestSuite * inSuite, void * inContext) CHIP_ERROR err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, kNodeIdFromSpec, destinationIdSpan); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); - NL_TEST_ASSERT(inSuite, destinationIdSpan.size() == sizeof(destinationIdBuf)); - NL_TEST_ASSERT(inSuite, destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_TRUE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); memset(destinationIdSpan.data(), 0, destinationIdSpan.size()); @@ -713,9 +707,9 @@ void TestCASESession::DestinationIdTest(nlTestSuite * inSuite, void * inContext) ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, kNodeIdFromSpec + 1, // <--- Change node ID destinationIdSpan); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); - NL_TEST_ASSERT(inSuite, destinationIdSpan.size() == sizeof(destinationIdBuf)); - NL_TEST_ASSERT(inSuite, !destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); } template @@ -770,33 +764,35 @@ static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) } // A macro, so we can tell which test failed based on line number. -#define TestSigma1Parsing(inSuite, mem, bufferSize, params) \ - do \ - { \ - MutableByteSpan buf(mem.Get(), bufferSize); \ - CHIP_ERROR err = EncodeSigma1(buf); \ - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); \ - \ - TLV::ContiguousBufferTLVReader reader; \ - reader.Init(buf); \ - \ - ByteSpan initiatorRandom; \ - uint16_t initiatorSessionId; \ - ByteSpan destinationId; \ - ByteSpan initiatorEphPubKey; \ - bool resumptionRequested; \ - ByteSpan resumptionId; \ - ByteSpan initiatorResumeMIC; \ - CASESession session; \ - err = session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, \ - resumptionRequested, resumptionId, initiatorResumeMIC); \ - NL_TEST_ASSERT(inSuite, (err == CHIP_NO_ERROR) == params::expectSuccess); \ - if (params::expectSuccess) \ - { \ - NL_TEST_ASSERT(inSuite, resumptionRequested == (params::resumptionIdLen != 0 && params::initiatorResumeMICLen != 0)); \ - /* Add other verification tests here as desired */ \ - } \ - } while (0) +// #define TestSigma1Parsing(inSuite, mem, bufferSize, params) +template +void TestSigma1Parsing(chip::Platform::ScopedMemoryBuffer & mem) +{ + MutableByteSpan buf(mem.Get(), bufferSize); + CHIP_ERROR err = EncodeSigma1(buf); + EXPECT_EQ(err, CHIP_NO_ERROR); + + TLV::ContiguousBufferTLVReader reader; + reader.Init(buf); + + ByteSpan initiatorRandom; + uint16_t initiatorSessionId; + ByteSpan destinationId; + ByteSpan initiatorEphPubKey; + bool resumptionRequested; + ByteSpan resumptionId; + ByteSpan initiatorResumeMIC; + CASESession session; + err = session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, resumptionRequested, + resumptionId, initiatorResumeMIC); + EXPECT_TRUE((err == CHIP_NO_ERROR) == params::expectSuccess); + if (params::expectSuccess) + { + EXPECT_TRUE(resumptionRequested == + (params::resumptionIdLen != 0 && + params::initiatorResumeMICLen != 0)); /* Add other verification tests here as desired */ + } +} struct BadSigma1ParamsBase : public Sigma1Params { @@ -883,30 +879,29 @@ struct Sigma1SessionIdTooBig : public BadSigma1ParamsBase static constexpr uint32_t initiatorSessionId = UINT16_MAX + 1; }; -void TestCASESession::Sigma1ParsingTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, Sigma1ParsingTest) { // 1280 bytes must be enough by definition. constexpr size_t bufferSize = 1280; chip::Platform::ScopedMemoryBuffer mem; - NL_TEST_ASSERT(inSuite, mem.Calloc(bufferSize)); - - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1Params); - - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1NoStructEnd); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1WrongTags); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongRandom); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortRandom); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongDest); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortDest); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongPubkey); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortPubkey); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1WithResumption); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongResumptionId); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortResumptionId); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooLongResumeMIC); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1TooShortResumeMIC); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1SessionIdMax); - TestSigma1Parsing(inSuite, mem, bufferSize, Sigma1SessionIdTooBig); + EXPECT_TRUE(mem.Calloc(bufferSize)); + + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); + TestSigma1Parsing(mem); } struct SessionResumptionTestStorage : SessionResumptionStorage @@ -956,7 +951,7 @@ struct SessionResumptionTestStorage : SessionResumptionStorage Crypto::P256ECDHDerivedSecret * mSharedSecret = nullptr; }; -void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, SessionResumptionStorage) { // Test the SessionResumptionStorage external interface. // @@ -967,7 +962,6 @@ void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inC // if the peers have mismatched session resumption information, we should // fall back to CASE. - TestContext & ctx = *reinterpret_cast(inContext); TestCASESecurePairingDelegate delegateCommissioner; chip::SessionResumptionStorage::ResumptionIdStorage resumptionIdA; chip::SessionResumptionStorage::ResumptionIdStorage resumptionIdB; @@ -976,19 +970,19 @@ void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inC // Create our fabric-scoped node IDs. const FabricInfo * fabricInfo = gCommissionerFabrics.FindFabricWithIndex(gCommissionerFabricIndex); - NL_TEST_ASSERT(inSuite, fabricInfo != nullptr); + EXPECT_NE(fabricInfo, nullptr); ScopedNodeId initiator = fabricInfo->GetScopedNodeIdForNode(Node01_02); ScopedNodeId responder = fabricInfo->GetScopedNodeIdForNode(Node01_01); // Generate a resumption IDs. - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionIdA.data(), resumptionIdA.size())); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionIdB.data(), resumptionIdB.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionIdA.data(), resumptionIdA.size()), CHIP_NO_ERROR); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionIdB.data(), resumptionIdB.size()), CHIP_NO_ERROR); // Generate a shared secrets. sharedSecretA.SetLength(sharedSecretA.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecretA.Bytes(), sharedSecretA.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecretA.Bytes(), sharedSecretA.Length()), CHIP_NO_ERROR); sharedSecretB.SetLength(sharedSecretB.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecretB.Bytes(), sharedSecretB.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecretB.Bytes(), sharedSecretB.Length()), CHIP_NO_ERROR); struct { @@ -1028,37 +1022,36 @@ void TestCASESession::SessionResumptionStorage(nlTestSuite * inSuite, void * inC }, }; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); for (size_t i = 0; i < sizeof(testVectors) / sizeof(testVectors[0]); ++i) { auto * pairingCommissioner = chip::Platform::New(); pairingCommissioner->SetGroupDataProvider(&gCommissionerGroupDataProvider); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - gPairingServer.ListenForSessionEstablishment(&ctx.GetExchangeManager(), &ctx.GetSecureSessionManager(), - &gDeviceFabrics, &testVectors[i].responderStorage, nullptr, - &gDeviceGroupDataProvider) == CHIP_NO_ERROR); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(pairingCommissioner); + EXPECT_EQ(gPairingServer.ListenForSessionEstablishment(&GetExchangeManager(), &GetSecureSessionManager(), &gDeviceFabrics, + &testVectors[i].responderStorage, nullptr, + &gDeviceGroupDataProvider), + CHIP_NO_ERROR); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(pairingCommissioner); auto establishmentReturnVal = pairingCommissioner->EstablishSession( - ctx.GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, - contextCommissioner, &testVectors[i].initiatorStorage, nullptr, &delegateCommissioner, - Optional::Missing()); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, establishmentReturnVal == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == testVectors[i].expectedSentMessageCount); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == i + 1); + GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + contextCommissioner, &testVectors[i].initiatorStorage, nullptr, &delegateCommissioner, + Optional::Missing()); + ServiceEvents(); + EXPECT_EQ(establishmentReturnVal, CHIP_NO_ERROR); + EXPECT_EQ(loopback.mSentMessageCount, testVectors[i].expectedSentMessageCount); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, i + 1); SessionHolder & holder = delegateCommissioner.GetSessionHolder(); - NL_TEST_ASSERT(inSuite, bool(holder)); - NL_TEST_ASSERT(inSuite, holder->GetPeer() == fabricInfo->GetScopedNodeIdForNode(Node01_01)); + EXPECT_TRUE(bool(holder)); + EXPECT_EQ(holder->GetPeer(), fabricInfo->GetScopedNodeIdForNode(Node01_01)); chip::Platform::Delete(pairingCommissioner); } } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST -void TestCASESession::SimulateUpdateNOCInvalidatePendingEstablishment(nlTestSuite * inSuite, void * inContext) +TEST_F_FROM_FIXTURE(TestCASESession, SimulateUpdateNOCInvalidatePendingEstablishment) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; @@ -1067,60 +1060,58 @@ void TestCASESession::SimulateUpdateNOCInvalidatePendingEstablishment(nlTestSuit TestCASESecurePairingDelegate delegateAccessory; CASESession pairingAccessory; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.mSentMessageCount = 0; - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, - &pairingAccessory) == CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, + &pairingAccessory), + CHIP_NO_ERROR); // In order for all the test iterations below, we need to stop the CASE sigma handshake in the middle such // that the CASE session is in the process of being established. pairingCommissioner.SetStopSigmaHandshakeAt(MakeOptional(CASESession::State::kSentSigma1)); - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); pairingAccessory.SetGroupDataProvider(&gDeviceGroupDataProvider); - NL_TEST_ASSERT(inSuite, - pairingAccessory.PrepareForSessionEstablishment( - sessionManager, &gDeviceFabrics, nullptr, nullptr, &delegateAccessory, ScopedNodeId(), - Optional::Missing()) == CHIP_NO_ERROR); + EXPECT_EQ(pairingAccessory.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &delegateAccessory, + ScopedNodeId(), Optional::Missing()), + CHIP_NO_ERROR); gDeviceFabrics.SendUpdateFabricNotificationForTest(gDeviceFabricIndex); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); + ServiceEvents(); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.EstablishSession(sessionManager, &gCommissionerFabrics, - ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, - nullptr, nullptr, &delegateCommissioner, - Optional::Missing()) == CHIP_NO_ERROR); - ServiceEvents(ctx); + EXPECT_EQ(pairingCommissioner.EstablishSession( + sessionManager, &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, contextCommissioner, + nullptr, nullptr, &delegateCommissioner, Optional::Missing()), + CHIP_NO_ERROR); + ServiceEvents(); // At this point the CASESession is in the process of establishing. Confirm that there are no errors and there are session // has not been established. - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); // Simulating an update to the Fabric NOC for gCommissionerFabrics fabric table. // Confirm that CASESession on commisioner side has reported an error. gCommissionerFabrics.SendUpdateFabricNotificationForTest(gCommissionerFabricIndex); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 1); + ServiceEvents(); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 1u); // Simulating an update to the Fabric NOC for gDeviceFabrics fabric table. // Confirm that CASESession on accessory side has reported an error. gDeviceFabrics.SendUpdateFabricNotificationForTest(gDeviceFabricIndex); - ServiceEvents(ctx); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 1); + ServiceEvents(); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 1u); // Sanity check that pairing did not complete. - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 0); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 0u); } #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST @@ -1128,9 +1119,7 @@ namespace { class ExpectErrorExchangeDelegate : public ExchangeDelegate { public: - ExpectErrorExchangeDelegate(nlTestSuite * suite, uint16_t expectedProtocolCode) : - mSuite(suite), mExpectedProtocolCode(expectedProtocolCode) - {} + ExpectErrorExchangeDelegate(uint16_t expectedProtocolCode) : mExpectedProtocolCode(expectedProtocolCode) {} private: CHIP_ERROR OnMessageReceived(ExchangeContext * ec, const PayloadHeader & payloadHeader, @@ -1138,15 +1127,15 @@ class ExpectErrorExchangeDelegate : public ExchangeDelegate { using namespace SecureChannel; - NL_TEST_ASSERT(mSuite, payloadHeader.HasMessageType(MsgType::StatusReport)); + EXPECT_TRUE(payloadHeader.HasMessageType(MsgType::StatusReport)); SecureChannel::StatusReport statusReport; CHIP_ERROR err = statusReport.Parse(std::move(buf)); - NL_TEST_ASSERT(mSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - NL_TEST_ASSERT(mSuite, statusReport.GetProtocolId() == SecureChannel::Id); - NL_TEST_ASSERT(mSuite, statusReport.GetGeneralCode() == GeneralStatusCode::kFailure); - NL_TEST_ASSERT(mSuite, statusReport.GetProtocolCode() == mExpectedProtocolCode); + EXPECT_EQ(statusReport.GetProtocolId(), SecureChannel::Id); + EXPECT_EQ(statusReport.GetGeneralCode(), GeneralStatusCode::kFailure); + EXPECT_EQ(statusReport.GetProtocolCode(), mExpectedProtocolCode); return CHIP_NO_ERROR; } @@ -1154,105 +1143,55 @@ class ExpectErrorExchangeDelegate : public ExchangeDelegate Messaging::ExchangeMessageDispatch & GetMessageDispatch() override { return SessionEstablishmentExchangeDispatch::Instance(); } - nlTestSuite * mSuite; uint16_t mExpectedProtocolCode; }; } // anonymous namespace -void TestCASESession::Sigma1BadDestinationIdTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestCASESession, Sigma1BadDestinationIdTest) { using SecureChannel::MsgType; - TestContext & ctx = *reinterpret_cast(inContext); - - SessionManager & sessionManager = ctx.GetSecureSessionManager(); + SessionManager & sessionManager = GetSecureSessionManager(); constexpr size_t bufferSize = 600; System::PacketBufferHandle data = chip::System::PacketBufferHandle::New(bufferSize); - NL_TEST_ASSERT(inSuite, !data.IsNull()); + EXPECT_FALSE(data.IsNull()); MutableByteSpan buf(data->Start(), data->AvailableDataLength()); // This uses a bogus destination id that is not going to match anything in practice. CHIP_ERROR err = EncodeSigma1(buf); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); data->SetDataLength(static_cast(buf.size())); - Optional session = sessionManager.CreateUnauthenticatedSession(ctx.GetAliceAddress(), GetDefaultMRPConfig()); - NL_TEST_ASSERT(inSuite, session.HasValue()); + Optional session = sessionManager.CreateUnauthenticatedSession(GetAliceAddress(), GetDefaultMRPConfig()); + EXPECT_TRUE(session.HasValue()); TestCASESecurePairingDelegate caseDelegate; CASESession caseSession; caseSession.SetGroupDataProvider(&gDeviceGroupDataProvider); err = caseSession.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &caseDelegate, ScopedNodeId(), NullOptional); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - err = ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1, &caseSession); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1, &caseSession); + EXPECT_EQ(err, CHIP_NO_ERROR); - ExpectErrorExchangeDelegate delegate(inSuite, SecureChannel::kProtocolCodeNoSharedRoot); - ExchangeContext * exchange = ctx.GetExchangeManager().NewContext(session.Value(), &delegate); - NL_TEST_ASSERT(inSuite, exchange != nullptr); + ExpectErrorExchangeDelegate delegate(SecureChannel::kProtocolCodeNoSharedRoot); + ExchangeContext * exchange = GetExchangeManager().NewContext(session.Value(), &delegate); + EXPECT_NE(exchange, nullptr); err = exchange->SendMessage(MsgType::CASE_Sigma1, std::move(data), SendMessageFlags::kExpectResponse); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + EXPECT_EQ(err, CHIP_NO_ERROR); - ServiceEvents(ctx); + ServiceEvents(); - NL_TEST_ASSERT(inSuite, caseDelegate.mNumPairingErrors == 1); - NL_TEST_ASSERT(inSuite, caseDelegate.mNumPairingComplete == 0); + EXPECT_EQ(caseDelegate.mNumPairingErrors, 1u); + EXPECT_EQ(caseDelegate.mNumPairingComplete, 0u); - ctx.GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1); + GetExchangeManager().UnregisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1); caseSession.Clear(); } } // namespace chip // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("WaitInit", chip::TestCASESession::SecurePairingWaitTest), - NL_TEST_DEF("Start", chip::TestCASESession::SecurePairingStartTest), - NL_TEST_DEF("Handshake", chip::TestCASESession::SecurePairingHandshakeTest), - NL_TEST_DEF("ServerHandshake", chip::TestCASESession::SecurePairingHandshakeServerTest), - NL_TEST_DEF("ClientReceivesBusy", chip::TestCASESession::ClientReceivesBusyTest), - NL_TEST_DEF("Sigma1Parsing", chip::TestCASESession::Sigma1ParsingTest), - NL_TEST_DEF("DestinationId", chip::TestCASESession::DestinationIdTest), - NL_TEST_DEF("SessionResumptionStorage", chip::TestCASESession::SessionResumptionStorage), -#if CONFIG_BUILD_FOR_HOST_UNIT_TEST - // This is compiled for host tests which is enough test coverage to ensure updating NOC invalidates - // CASESession that are in the process of establishing. - NL_TEST_DEF("InvalidatePendingSessionEstablishment", chip::TestCASESession::SimulateUpdateNOCInvalidatePendingEstablishment), -#endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST - NL_TEST_DEF("Sigma1BadDestinationId", chip::TestCASESession::Sigma1BadDestinationIdTest), - - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-SecurePairing-CASE", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -/** - * Main - */ -int TestCASESessionTest() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestCASESessionTest) diff --git a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp index d5885f3a6d06bb..b33c2ff13e08f0 100644 --- a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp +++ b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp @@ -18,9 +18,9 @@ #include #include -#include #include #include +#include #include #include #include @@ -34,7 +34,26 @@ using namespace chip::Protocols::SecureChannel; using namespace chip::Crypto; using TestSessionKeystoreImpl = Crypto::DefaultSessionKeystore; -namespace { +namespace chip { +namespace Protocols { +namespace SecureChannel { + +class TestCheckInMsg : public ::testing::Test +{ +public: + static void SetUpTestSuite() + { + CHIP_ERROR error = chip::Platform::MemoryInit(); + EXPECT_EQ(error, CHIP_NO_ERROR); + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } + +protected: + static CHIP_ERROR GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Message_test_vector & vector); + + static CHIP_ERROR ParseAndVerifyPayload(MutableByteSpan & applicationData, const CheckIn_Message_test_vector & vector, + bool injectInvalidNonce); +}; /** * @brief Helper function that generates the Check-In message based on the test vector @@ -44,7 +63,7 @@ namespace { * @return CHIP_NO_ERROR if the generation was successful * error code if the generation failed - see GenerateCheckinMessagePayload */ -CHIP_ERROR GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Message_test_vector & vector) +CHIP_ERROR TestCheckInMsg::GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Message_test_vector & vector) { TestSessionKeystoreImpl keystore; @@ -56,6 +75,7 @@ CHIP_ERROR GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Mess memcpy(hmacKeyMaterial, vector.key, vector.key_len); Aes128KeyHandle aes128KeyHandle; + EXPECT_EQ(keystore.CreateKey(aesKeyMaterial, aes128KeyHandle), CHIP_NO_ERROR); Hmac128KeyHandle hmac128KeyHandle; @@ -111,8 +131,8 @@ CHIP_ERROR GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Mess * @return CHIP_NO_ERROR if the parsing was successful * error code if the generation failed - see ParseCheckinMessagePayload */ -CHIP_ERROR ParseAndVerifyPayload(MutableByteSpan & applicationData, const CheckIn_Message_test_vector & vector, - bool injectInvalidNonce) +CHIP_ERROR TestCheckInMsg::ParseAndVerifyPayload(MutableByteSpan & applicationData, const CheckIn_Message_test_vector & vector, + bool injectInvalidNonce) { TestSessionKeystoreImpl keystore; @@ -172,7 +192,7 @@ CHIP_ERROR ParseAndVerifyPayload(MutableByteSpan & applicationData, const CheckI /** * @brief Test verifies that the Check-In message generation is successful when using an output size equal to the payload size */ -TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsSameSizeOutputAsPayload) +TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsSameSizeOutputAsPayload) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -193,7 +213,7 @@ TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsSameSizeOutputAsPaylo /** * @brief Test verifies that the Check-In message generation is successful when using an output size greater than the payload size */ -TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsBiggerSizeOutput) +TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsBiggerSizeOutput) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -211,19 +231,20 @@ TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsBiggerSizeOutput) /** * @brief Test verifies that the Check-In message generation returns an error if the output buffer is too small */ -TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsTooSmallOutput) +TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsTooSmallOutput) { CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; // Create output buffer with 0 size MutableByteSpan output; - EXPECT_EQ(GenerateAndVerifyPayload(output, vector), CHIP_ERROR_BUFFER_TOO_SMALL); + + EXPECT_EQ(CHIP_ERROR_BUFFER_TOO_SMALL, GenerateAndVerifyPayload(output, vector)); } /** * @brief Test verifies that the Check-In Message generations returns an error if the AesKeyHandle is empty */ -TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) +TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -247,15 +268,16 @@ TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) // Create application data ByteSpan ByteSpan applicationData(vector.application_data, vector.application_data_len); -/* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. -*/ + /* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. + */ #if 0 - // Verify that the generation fails with an empty key handle - EXPECT_NE( - CHIP_NO_ERROR, - CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, applicationData, output)); + // Verify that the generation fails with an empty key handle + NL_TEST_ASSERT_(inSuite, + CHIP_NO_ERROR != + CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, + applicationData, output)); #endif // Clean up @@ -265,7 +287,7 @@ TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) /** * @brief Test verifies that the Check-In Message generations returns an error if the HmacKeyHandle is empty */ -TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) +TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -288,15 +310,16 @@ TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) // Create application data ByteSpan ByteSpan applicationData(vector.application_data, vector.application_data_len); -/* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. -*/ + /* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. + */ #if 0 // Verify that the generation fails with an empty key handle - EXPECT_NE( - CHIP_NO_ERROR, - CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, applicationData, output)); + NL_TEST_ASSERT_(inSuite, + CHIP_NO_ERROR != + CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, + applicationData, output)); #endif // Clean up @@ -306,7 +329,7 @@ TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) /** * @brief Test verifies that the Check-In message parsing succeeds with the Application buffer set to the minimum required size */ -TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsSameSizeMinAppData) +TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsSameSizeMinAppData) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -324,7 +347,7 @@ TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsSameSizeMinAppData) /** * @brief Test verifies that the Check-In message parsing succeeds with the Application buffer set to a larger than necessary size */ -TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsBiggerSizeMinAppData) +TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsBiggerSizeMinAppData) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -341,20 +364,20 @@ TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsBiggerSizeMinAppData) /** * @brief Test verifies that the Check-In message throws an error if the application data buffer is too small */ -TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsTooSmallAppData) +TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsTooSmallAppData) { CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; // Create applicationData buffer with 0 size MutableByteSpan applicationData; - EXPECT_EQ(ParseAndVerifyPayload(applicationData, vector, false), CHIP_ERROR_BUFFER_TOO_SMALL); + EXPECT_EQ(CHIP_ERROR_BUFFER_TOO_SMALL, ParseAndVerifyPayload(applicationData, vector, false)); } /** * @brief Test verifies that the Check-In Message parsing returns an error if the AesKeyHandle is empty */ -TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) +TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -380,15 +403,15 @@ TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) Hmac128KeyHandle hmac128KeyHandle; EXPECT_EQ(keystore.CreateKey(hmacKeyMaterial, hmac128KeyHandle), CHIP_NO_ERROR); -/* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. -*/ + /* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. + */ #if 0 // Verify that the generation fails with an empty key handle - EXPECT_NE( - CHIP_NO_ERROR, - CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData)); + EXPECT_EQ( + CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData), + CHIP_NO_ERROR); #endif // Clean up @@ -398,7 +421,7 @@ TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) /** * @brief Test verifies that the Check-In Message parsing returns an error if the HmacKeyHandle is empty */ -TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) +TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -424,15 +447,15 @@ TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) Aes128KeyHandle aes128KeyHandle; EXPECT_EQ(keystore.CreateKey(aesKeyMaterial, aes128KeyHandle), CHIP_NO_ERROR); -/* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. -*/ + /* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. + */ #if 0 // Verify that the generation fails with an empty key handle - EXPECT_NE( - CHIP_NO_ERROR, - CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData)); + EXPECT_EQ( + CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData), + CHIP_NO_ERROR); #endif // Clean up @@ -442,7 +465,7 @@ TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) /** * @brief Test verifies that the Check-In message processing throws an error if the nonce is corrupted */ -TEST(TestCheckInMsg, TestCheckinMessageParse_CorruptedNonce) +TEST_F(TestCheckInMsg, TestCheckinMessageParse_CorruptedNonce) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -461,7 +484,7 @@ TEST(TestCheckInMsg, TestCheckinMessageParse_CorruptedNonce) * @brief Test verifies that the Check-In message processing throws an error if the nonce was not calculated with the counter in the * payload */ -TEST(TestCheckInMsg, TestCheckinMessageParse_InvalidNonce) +TEST_F(TestCheckInMsg, TestCheckinMessageParse_InvalidNonce) { CheckIn_Message_test_vector vector = invalidNonceVector; @@ -469,13 +492,13 @@ TEST(TestCheckInMsg, TestCheckinMessageParse_InvalidNonce) MutableByteSpan applicationData(applicationDataBuffer, sizeof(applicationDataBuffer)); applicationData.reduce_size(vector.application_data_len + sizeof(CounterType)); - EXPECT_EQ(ParseAndVerifyPayload(applicationData, vector, true), CHIP_ERROR_INTERNAL); + EXPECT_EQ(ParseAndVerifyPayload(applicationData, vector, false), CHIP_ERROR_INTERNAL); } /** * @brief test verifies that GetAppDataSize returns the correct application data size */ -TEST(TestCheckInMsg, TestCheckInMessagePayloadSize) +TEST_F(TestCheckInMsg, TestCheckInMessagePayloadSize) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -493,14 +516,15 @@ TEST(TestCheckInMsg, TestCheckInMessagePayloadSize) /** * @brief test verifies that GetAppDataSize returns 0 if the payload is smaller that the minimum size */ -TEST(TestCheckInMsg, TestCheckInMessagePayloadSizeNullBuffer) +TEST_F(TestCheckInMsg, TestCheckInMessagePayloadSizeNullBuffer) { ByteSpan payload; size_t calculated_size = CheckinMessage::GetAppDataSize(payload); - size_t expected_size = 0; // Verify that the size is 0 - EXPECT_EQ(calculated_size, expected_size); + EXPECT_EQ(calculated_size, 0u); } -} // namespace +} // namespace SecureChannel +} // namespace Protocols +} // namespace chip diff --git a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp index 82e755b783b4b8..236119462ddcb0 100644 --- a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp @@ -17,14 +17,14 @@ #include #include -#include -#include + +#include // DefaultSessionResumptionStorage is a partial implementation. // Use SimpleSessionResumptionStorage, which extends it, to test. #include -void TestSave(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestSave) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -40,14 +40,11 @@ void TestSave(nlTestSuite * inSuite, void * inContext) // Populate test vectors. for (size_t i = 0; i < ArraySize(vectors); ++i) { - NL_TEST_ASSERT( - inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size()), CHIP_NO_ERROR); *vectors[i].resumptionId.data() = static_cast(i); // set first byte to our index to ensure uniqueness for the FindByResumptionId call vectors[i].sharedSecret.SetLength(vectors[i].sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, - CHIP_NO_ERROR == - chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length()), CHIP_NO_ERROR); vectors[i].node = chip::ScopedNodeId(static_cast(i + 1), static_cast(i + 1)); vectors[i].cats.values[0] = static_cast(rand()); vectors[i].cats.values[1] = static_cast(rand()); @@ -57,9 +54,8 @@ void TestSave(nlTestSuite * inSuite, void * inContext) // Fill storage. for (size_t i = 0; i < CHIP_CONFIG_CASE_SESSION_RESUME_CACHE_SIZE; ++i) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats) == - CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats), + CHIP_NO_ERROR); } // Verify behavior for over-fill. @@ -69,9 +65,9 @@ void TestSave(nlTestSuite * inSuite, void * inContext) // case should be modified to match. { size_t last = ArraySize(vectors) - 1; - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vectors[last].node, vectors[last].resumptionId, vectors[last].sharedSecret, - vectors[last].cats) == CHIP_NO_ERROR); + EXPECT_EQ( + sessionStorage.Save(vectors[last].node, vectors[last].resumptionId, vectors[last].sharedSecret, vectors[last].cats), + CHIP_NO_ERROR); // Copy our data to our test vector index 0 to match // what is now in storage. vectors[0].node = vectors[last].node; @@ -89,28 +85,24 @@ void TestSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify retrieval by node. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(vector.resumptionId.data(), outResumptionId.data(), vector.resumptionId.size()) == 0); - NL_TEST_ASSERT(inSuite, - memcmp(vector.sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vector.cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vector.cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vector.cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(vector.resumptionId.data(), outResumptionId.data(), vector.resumptionId.size()), 0); + EXPECT_EQ(memcmp(vector.sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()), 0); + EXPECT_EQ(vector.cats.values[0], outCats.values[0]); + EXPECT_EQ(vector.cats.values[1], outCats.values[1]); + EXPECT_EQ(vector.cats.values[2], outCats.values[2]); // Validate retrieval by resumption ID. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, vector.node == outNode); - NL_TEST_ASSERT(inSuite, - memcmp(vector.sharedSecret.Bytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vector.cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vector.cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vector.cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(vector.node, outNode); + EXPECT_EQ(memcmp(vector.sharedSecret.Bytes(), outSharedSecret.ConstBytes(), vector.sharedSecret.Length()), 0); + EXPECT_EQ(vector.cats.values[0], outCats.values[0]); + EXPECT_EQ(vector.cats.values[1], outCats.values[1]); + EXPECT_EQ(vector.cats.values[2], outCats.values[2]); } } -void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestInPlaceSave) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -139,14 +131,11 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) // Populate test vectors. for (size_t i = 0; i < ArraySize(vectors); ++i) { - NL_TEST_ASSERT( - inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size()), CHIP_NO_ERROR); *vectors[i].resumptionId.data() = static_cast(i); // set first byte to our index to ensure uniqueness for the FindByResumptionId call vectors[i].sharedSecret.SetLength(vectors[i].sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, - CHIP_NO_ERROR == - chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].sharedSecret.Bytes(), vectors[i].sharedSecret.Length()), CHIP_NO_ERROR); vectors[i].node = nodes[i % ArraySize(nodes)]; vectors[i].cats.values[0] = static_cast(rand()); vectors[i].cats.values[1] = static_cast(rand()); @@ -156,9 +145,8 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) // Add one entry for each node. for (size_t i = 0; i < ArraySize(nodes); ++i) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats) == - CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vectors[i].node, vectors[i].resumptionId, vectors[i].sharedSecret, vectors[i].cats), + CHIP_NO_ERROR); } // Read back and verify values. @@ -170,37 +158,27 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify retrieval by node. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()) == 0); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()), 0); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); // Validate retrieval by resumption ID. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, vectors[i].node == outNode); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(vectors[i].node, outNode); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); } // Now add all test vectors. This should overwrite each node's record // many times. for (auto & vector : vectors) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vector.node, vector.resumptionId, vector.sharedSecret, vector.cats) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vector.node, vector.resumptionId, vector.sharedSecret, vector.cats), CHIP_NO_ERROR); } // Read back and verify that only the last record for each node was retained. @@ -212,36 +190,27 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify retrieval by node. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()) == 0); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(vectors[i].node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(vectors[i].resumptionId.data(), outResumptionId.data(), vectors[i].resumptionId.size()), 0); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); // Validate retrieval by resumption ID. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats) == - CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, vectors[i].node == outNode); - NL_TEST_ASSERT( - inSuite, - memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()) == 0); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[0] == outCats.values[0]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[1] == outCats.values[1]); - NL_TEST_ASSERT(inSuite, vectors[i].cats.values[2] == outCats.values[2]); + EXPECT_EQ(sessionStorage.FindByResumptionId(vectors[i].resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_EQ(vectors[i].node, outNode); + EXPECT_EQ(memcmp(vectors[i].sharedSecret.ConstBytes(), outSharedSecret.ConstBytes(), vectors[i].sharedSecret.Length()), 0); + EXPECT_EQ(vectors[i].cats.values[0], outCats.values[0]); + EXPECT_EQ(vectors[i].cats.values[1], outCats.values[1]); + EXPECT_EQ(vectors[i].cats.values[2], outCats.values[2]); } // Remove all records for all fabrics. If all three tables of (index, state, // links) are in sync, deleting for each fabric should clean error free. for (const auto & node : nodes) { - NL_TEST_ASSERT(inSuite, sessionStorage.DeleteAll(node.GetFabricIndex()) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.DeleteAll(node.GetFabricIndex()), CHIP_NO_ERROR); } // Verify that no entries can be located any longer for any node or @@ -254,12 +223,10 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) chip::CATValues outCats; // Verify all records for all nodes are gone. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); // Verify all records for all resumption IDs are gone. - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); } // Verify no state table persistent storage entries were leaked. @@ -267,7 +234,7 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) { uint16_t size = 0; auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } // Verify no link table persistent storage entries were leaked. for (auto & vector : vectors) @@ -275,11 +242,11 @@ void TestInPlaceSave(nlTestSuite * inSuite, void * inContext) uint16_t size = 0; auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.resumptionId).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } -void TestDelete(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestDelete) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -293,13 +260,12 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) // Create a shared secret. We can use the same one for all entries. sharedSecret.SetLength(sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); // Populate test vectors. for (size_t i = 0; i < ArraySize(vectors); ++i) { - NL_TEST_ASSERT( - inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(vectors[i].resumptionId.data(), vectors[i].resumptionId.size()), CHIP_NO_ERROR); *vectors[i].resumptionId.data() = static_cast(i); // set first byte to our index to ensure uniqueness for the delete test vectors[i].node = chip::ScopedNodeId(static_cast(i + 1), static_cast(i + 1)); @@ -308,8 +274,7 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) // Fill storage. for (auto & vector : vectors) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(vector.node, vector.resumptionId, sharedSecret, chip::CATValues{}) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(vector.node, vector.resumptionId, sharedSecret, chip::CATValues{}), CHIP_NO_ERROR); } // Delete values in turn from storage and verify they are removed. @@ -319,11 +284,9 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) chip::SessionResumptionStorage::ResumptionIdStorage outResumptionId; chip::Crypto::P256ECDHDerivedSecret outSharedSecret; chip::CATValues outCats; - NL_TEST_ASSERT(inSuite, sessionStorage.Delete(vector.node) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats) != CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Delete(vector.node), CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByScopedNodeId(vector.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByResumptionId(vector.resumptionId, outNode, outSharedSecret, outCats), CHIP_NO_ERROR); } // Verify no state or link table persistent storage entries were leaked. @@ -333,17 +296,17 @@ void TestDelete(nlTestSuite * inSuite, void * inContext) { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.node).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(vector.resumptionId).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } } -void TestDeleteAll(nlTestSuite * inSuite, void * inContext) +TEST(TestDefaultSessionResumptionStorage, TestDeleteAll) { chip::SimpleSessionResumptionStorage sessionStorage; chip::TestPersistentStorageDelegate storage; @@ -361,7 +324,7 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) // Create a shared secret. We can use the same one for all entries. sharedSecret.SetLength(sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length())); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); // Populate test vectors. for (size_t i = 0; i < sizeof(vectors) / sizeof(vectors[0]); ++i) @@ -369,10 +332,9 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) vectors[i].fabricIndex = static_cast(i + 1); for (size_t j = 0; j < sizeof(vectors[0].nodes) / sizeof(vectors[0].nodes[0]); ++j) { - NL_TEST_ASSERT( - inSuite, - CHIP_NO_ERROR == - chip::Crypto::DRBG_get_bytes(vectors[i].nodes[j].resumptionId.data(), vectors[i].nodes[j].resumptionId.size())); + EXPECT_EQ( + chip::Crypto::DRBG_get_bytes(vectors[i].nodes[j].resumptionId.data(), vectors[i].nodes[j].resumptionId.size()), + CHIP_NO_ERROR); vectors[i].nodes[j].node = chip::ScopedNodeId(static_cast(j), vectors[i].fabricIndex); } } @@ -382,8 +344,7 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) { for (auto & node : vector.nodes) { - NL_TEST_ASSERT(inSuite, - sessionStorage.Save(node.node, node.resumptionId, sharedSecret, chip::CATValues{}) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.Save(node.node, node.resumptionId, sharedSecret, chip::CATValues{}), CHIP_NO_ERROR); } } @@ -397,16 +358,14 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) // Verify fabric node entries exist. for (const auto & node : vector.nodes) { - NL_TEST_ASSERT( - inSuite, sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); } // Delete fabric. - NL_TEST_ASSERT(inSuite, sessionStorage.DeleteAll(vector.fabricIndex) == CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.DeleteAll(vector.fabricIndex), CHIP_NO_ERROR); // Verify fabric node entries no longer exist. for (const auto & node : vector.nodes) { - NL_TEST_ASSERT( - inSuite, sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats) != CHIP_NO_ERROR); + EXPECT_NE(sessionStorage.FindByScopedNodeId(node.node, outResumptionId, outSharedSecret, outCats), CHIP_NO_ERROR); } } // Verify no state or link table persistent storage entries were leaked. @@ -418,53 +377,13 @@ void TestDeleteAll(nlTestSuite * inSuite, void * inContext) { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node.node).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } { auto rv = storage.SyncGetKeyValue(chip::SimpleSessionResumptionStorage::GetStorageKey(node.resumptionId).KeyName(), nullptr, size); - NL_TEST_ASSERT(inSuite, rv == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(rv, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } } } } - -// Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TestSave", TestSave), - NL_TEST_DEF("TestInPlaceSave", TestInPlaceSave), - NL_TEST_DEF("TestDelete", TestDelete), - NL_TEST_DEF("TestDeleteAll", TestDeleteAll), - - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-DefaultSessionResumptionStorage", - &sTests[0], - nullptr, - nullptr, -}; -// clang-format on - -/** - * Main - */ -int TestDefaultSessionResumptionStorage() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestDefaultSessionResumptionStorage) diff --git a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp index c2e71591acda14..3e5ce9d33121ed 100644 --- a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp +++ b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp @@ -24,7 +24,7 @@ #include #include #include -#include + #include #include #include @@ -35,8 +35,8 @@ #include #include +#include #include -#include #include @@ -48,8 +48,6 @@ using namespace chip::Transport; using namespace chip::Messaging; using namespace chip::Protocols; -using TestContext = chip::Test::LoopbackMessagingContext; - const char PAYLOAD[] = "Hello!"; class MockAppDelegate : public ExchangeDelegate @@ -67,109 +65,57 @@ class MockAppDelegate : public ExchangeDelegate int ReceiveHandlerCallCount = 0; }; -void MessageCounterSyncProcess(nlTestSuite * inSuite, void * inContext) +struct TestMessageCounterManager : public chip::Test::LoopbackMessagingContext, public ::testing::Test +{ + static void SetUpTestSuite() { EXPECT_EQ(chip::Test::LoopbackTransportManager::Init(), CHIP_NO_ERROR); } + static void TearDownTestSuite() { chip::Test::LoopbackTransportManager::Shutdown(); } +}; + +TEST_F(TestMessageCounterManager, MessageCounterSyncProcess) { - TestContext & ctx = *reinterpret_cast(inContext); CHIP_ERROR err = CHIP_NO_ERROR; - SessionHandle localSession = ctx.GetSessionBobToAlice(); - SessionHandle peerSession = ctx.GetSessionAliceToBob(); + SessionHandle localSession = GetSessionBobToAlice(); + SessionHandle peerSession = GetSessionAliceToBob(); - Transport::SecureSession * localState = ctx.GetSecureSessionManager().GetSecureSession(localSession); - Transport::SecureSession * peerState = ctx.GetSecureSessionManager().GetSecureSession(peerSession); + Transport::SecureSession * localState = GetSecureSessionManager().GetSecureSession(localSession); + Transport::SecureSession * peerState = GetSecureSessionManager().GetSecureSession(peerSession); localState->GetSessionMessageCounter().GetPeerMessageCounter().Reset(); - err = ctx.GetMessageCounterManager().SendMsgCounterSyncReq(localSession, localState); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); + err = GetMessageCounterManager().SendMsgCounterSyncReq(localSession, localState); + EXPECT_EQ(err, CHIP_NO_ERROR); MessageCounter & peerCounter = peerState->GetSessionMessageCounter().GetLocalMessageCounter(); PeerMessageCounter & localCounter = localState->GetSessionMessageCounter().GetPeerMessageCounter(); - NL_TEST_ASSERT(inSuite, localCounter.IsSynchronized()); - NL_TEST_ASSERT(inSuite, localCounter.GetCounter() == peerCounter.Value()); + EXPECT_TRUE(localCounter.IsSynchronized()); + EXPECT_EQ(localCounter.GetCounter(), peerCounter.Value()); } -void CheckReceiveMessage(nlTestSuite * inSuite, void * inContext) +TEST_F(TestMessageCounterManager, CheckReceiveMessage) { - TestContext & ctx = *reinterpret_cast(inContext); - CHIP_ERROR err = CHIP_NO_ERROR; + CHIP_ERROR err = CHIP_NO_ERROR; - SessionHandle peerSession = ctx.GetSessionAliceToBob(); - Transport::SecureSession * peerState = ctx.GetSecureSessionManager().GetSecureSession(peerSession); + SessionHandle peerSession = GetSessionAliceToBob(); + Transport::SecureSession * peerState = GetSecureSessionManager().GetSecureSession(peerSession); peerState->GetSessionMessageCounter().GetPeerMessageCounter().Reset(); MockAppDelegate callback; - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(chip::Protocols::Echo::MsgType::EchoRequest, &callback); + GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(chip::Protocols::Echo::MsgType::EchoRequest, &callback); uint16_t payload_len = sizeof(PAYLOAD); System::PacketBufferHandle msgBuf = MessagePacketBuffer::NewWithData(PAYLOAD, payload_len); - NL_TEST_ASSERT(inSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); - Messaging::ExchangeContext * ec = ctx.NewExchangeToAlice(nullptr); - NL_TEST_ASSERT(inSuite, ec != nullptr); + Messaging::ExchangeContext * ec = NewExchangeToAlice(nullptr); + EXPECT_NE(ec, nullptr); err = ec->SendMessage(chip::Protocols::Echo::MsgType::EchoRequest, std::move(msgBuf), Messaging::SendFlags{ Messaging::SendMessageFlags::kNoAutoRequestAck }); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, peerState->GetSessionMessageCounter().GetPeerMessageCounter().IsSynchronized()); - NL_TEST_ASSERT(inSuite, callback.ReceiveHandlerCallCount == 1); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_TRUE(peerState->GetSessionMessageCounter().GetPeerMessageCounter().IsSynchronized()); + EXPECT_EQ(callback.ReceiveHandlerCallCount, 1); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -const nlTest sTests[] = -{ - NL_TEST_DEF("Test MessageCounterManager::MessageCounterSyncProcess", MessageCounterSyncProcess), - NL_TEST_DEF("Test MessageCounterManager::ReceiveMessage", CheckReceiveMessage), - NL_TEST_SENTINEL() -}; -// clang-format on - -int Initialize(void * aContext); -int Finalize(void * aContext); - -// clang-format off -nlTestSuite sSuite = -{ - "Test-MessageCounterManager", - &sTests[0], - Initialize, - Finalize -}; -// clang-format on - -/** - * Initialize the test suite. - */ -int Initialize(void * aContext) -{ - auto * ctx = static_cast(aContext); - VerifyOrReturnError(ctx->Init(&sSuite) == CHIP_NO_ERROR, FAILURE); - - return SUCCESS; -} - -/** - * Finalize the test suite. - */ -int Finalize(void * aContext) -{ - reinterpret_cast(aContext)->Shutdown(); - return SUCCESS; -} - } // namespace - -/** - * Main - */ -int TestMessageCounterManager() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestMessageCounterManager); diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index d610b304cec481..0bf45350e9d366 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -22,15 +22,13 @@ */ #include -#include +#include #include #include #include #include #include -#include -#include #include #include #include @@ -85,7 +83,7 @@ constexpr Spake2pVerifierSerialized sTestSpake2p01_SerializedVerifier = { 0xB7, 0xC0, 0x7F, 0xCC, 0x06, 0x27, 0xA1, 0xB8, 0x57, 0x3A, 0x14, 0x9F, 0xCD, 0x1F, 0xA4, 0x66, 0xCF }; -class TestContext : public chip::Test::LoopbackMessagingContext +class TestPASESession : public chip::Test::LoopbackMessagingContext, public ::testing::Test { public: // Performs shared setup for all tests in the test suite @@ -94,6 +92,11 @@ class TestContext : public chip::Test::LoopbackMessagingContext ConfigInitializeNodes(false); chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } + static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } + + void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + + void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } }; class PASETestLoopbackTransportDelegate : public Test::LoopbackTransportDelegate @@ -129,12 +132,11 @@ class MockAppDelegate : public ExchangeDelegate class TemporarySessionManager { public: - TemporarySessionManager(nlTestSuite * suite, TestContext & ctx) : mCtx(ctx) + TemporarySessionManager(TestPASESession & ctx) : mCtx(ctx) { - NL_TEST_ASSERT(suite, - CHIP_NO_ERROR == - mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), - &mStorage, &ctx.GetFabricTable(), ctx.GetSessionKeystore())); + EXPECT_EQ(CHIP_NO_ERROR, + mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), &mStorage, + &ctx.GetFabricTable(), ctx.GetSessionKeystore())); // The setup here is really weird: we are using one session manager for // the actual messages we send (the PASE handshake, so the // unauthenticated sessions) and a different one for allocating the PASE @@ -154,105 +156,97 @@ class TemporarySessionManager operator SessionManager &() { return mSessionManager; } private: - TestContext & mCtx; + TestPASESession & mCtx; TestPersistentStorageDelegate mStorage; SessionManager mSessionManager; }; using namespace System::Clock::Literals; -void SecurePairingWaitTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingWaitTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestSecurePairingDelegate delegate; PASESession pairing; - NL_TEST_ASSERT(inSuite, pairing.GetSecureSessionType() == SecureSession::Type::kPASE); + EXPECT_EQ(pairing.GetSecureSessionType(), SecureSession::Type::kPASE); - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, ByteSpan(), - Optional::Missing(), - &delegate) == CHIP_ERROR_INVALID_ARGUMENT); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(reinterpret_cast("saltSalt"), 8), - Optional::Missing(), - nullptr) == CHIP_ERROR_INVALID_ARGUMENT); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(reinterpret_cast("saltSalt"), 8), - Optional::Missing(), - &delegate) == CHIP_ERROR_INVALID_ARGUMENT); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(sTestSpake2p01_Salt), Optional::Missing(), - &delegate) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, ByteSpan(), + Optional::Missing(), &delegate), + CHIP_ERROR_INVALID_ARGUMENT); + DrainAndServiceIO(); + + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(reinterpret_cast("saltSalt"), 8), + Optional::Missing(), nullptr), + CHIP_ERROR_INVALID_ARGUMENT); + DrainAndServiceIO(); + + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(reinterpret_cast("saltSalt"), 8), + Optional::Missing(), &delegate), + CHIP_ERROR_INVALID_ARGUMENT); + DrainAndServiceIO(); + + EXPECT_EQ(pairing.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(sTestSpake2p01_Salt), Optional::Missing(), &delegate), + CHIP_NO_ERROR); + DrainAndServiceIO(); } -void SecurePairingStartTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingStartTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestSecurePairingDelegate delegate; PASESession pairing; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); - ExchangeContext * context = ctx.NewUnauthenticatedExchangeToBob(&pairing); + ExchangeContext * context = NewUnauthenticatedExchangeToBob(&pairing); - NL_TEST_ASSERT(inSuite, - pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), nullptr, - nullptr) != CHIP_NO_ERROR); + EXPECT_NE( + pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), nullptr, nullptr), + CHIP_NO_ERROR); loopback.Reset(); - NL_TEST_ASSERT(inSuite, - pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), context, - &delegate) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + EXPECT_EQ(pairing.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), context, + &delegate), + CHIP_NO_ERROR); + DrainAndServiceIO(); // There should have been two messages sent: PBKDFParamRequest and an ack. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount == 2); + EXPECT_EQ(loopback.mSentMessageCount, 2u); - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); - NL_TEST_ASSERT(inSuite, rm->TestGetCountRetransTable() == 0); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); + EXPECT_EQ(rm->TestGetCountRetransTable(), 0); loopback.Reset(); loopback.mSentMessageCount = 0; loopback.mMessageSendError = CHIP_ERROR_BAD_REQUEST; PASESession pairing1; - ExchangeContext * context1 = ctx.NewUnauthenticatedExchangeToBob(&pairing1); - NL_TEST_ASSERT(inSuite, - pairing1.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), - context1, &delegate) == CHIP_ERROR_BAD_REQUEST); - ctx.DrainAndServiceIO(); + ExchangeContext * context1 = NewUnauthenticatedExchangeToBob(&pairing1); + EXPECT_EQ(pairing1.Pair(sessionManager, sTestSpake2p01_PinCode, Optional::Missing(), context1, + &delegate), + CHIP_ERROR_BAD_REQUEST); + DrainAndServiceIO(); loopback.mMessageSendError = CHIP_NO_ERROR; } -void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, SessionManager & sessionManager, - PASESession & pairingCommissioner, +void SecurePairingHandshakeTestCommon(TestPASESession & ctx, SessionManager & sessionManager, PASESession & pairingCommissioner, Optional mrpCommissionerConfig, Optional mrpAccessoryConfig, TestSecurePairingDelegate & delegateCommissioner) { - TestContext & ctx = *reinterpret_cast(inContext); TestSecurePairingDelegate delegateAccessory; PASESession pairingAccessory; @@ -268,8 +262,8 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S { ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); ReliableMessageContext * rc = contextCommissioner->GetReliableMessageContext(); - NL_TEST_ASSERT(inSuite, rm != nullptr); - NL_TEST_ASSERT(inSuite, rc != nullptr); + ASSERT_NE(rm, nullptr); + ASSERT_NE(rc, nullptr); // Adding an if-else to avoid affecting non-ICD tests #if CHIP_CONFIG_ENABLE_ICD_SERVER == 1 @@ -288,31 +282,27 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S #endif // CHIP_CONFIG_ENABLE_ICD_SERVER } - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType( - Protocols::SecureChannel::MsgType::PBKDFParamRequest, &pairingAccessory) == CHIP_NO_ERROR); + EXPECT_EQ(ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType( + Protocols::SecureChannel::MsgType::PBKDFParamRequest, &pairingAccessory), + CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - pairingAccessory.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, - ByteSpan(sTestSpake2p01_Salt), mrpAccessoryConfig, - &delegateAccessory) == CHIP_NO_ERROR); + EXPECT_EQ(pairingAccessory.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(sTestSpake2p01_Salt), mrpAccessoryConfig, &delegateAccessory), + CHIP_NO_ERROR); ctx.DrainAndServiceIO(); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.Pair(sessionManager, sTestSpake2p01_PinCode, mrpCommissionerConfig, contextCommissioner, - &delegateCommissioner) == CHIP_NO_ERROR); + EXPECT_EQ(pairingCommissioner.Pair(sessionManager, sTestSpake2p01_PinCode, mrpCommissionerConfig, contextCommissioner, + &delegateCommissioner), + CHIP_NO_ERROR); ctx.DrainAndServiceIO(); while (delegate.mMessageDropped) { - auto waitTimeout = 100_ms; + auto waitTimeout = 100_ms + CHIP_CONFIG_MRP_RETRY_INTERVAL_SENDER_BOOST; -#if CHIP_CONFIG_ENABLE_ICD_SERVER - // If running as an ICD, increase waitTimeout to account for: - // - longer MRP intervals, configured above to 1s/1s, - // - the fast-polling interval that is added to the MRP backoff time. - waitTimeout += 2000_ms32; - waitTimeout += ICDConfigurationData::GetInstance().GetFastPollingInterval(); +#if CHIP_CONFIG_ENABLE_ICD_SERVER == 1 + // If running as an ICD, increase waitTimeout to account for the polling interval + waitTimeout += ICDConfigurationData::GetInstance().GetSlowPollingInterval(); #endif // Wait some time so the dropped message will be retransmitted when we drain the IO. @@ -326,39 +316,31 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S // via piggybacked acks. So we cannot check for a specific value of mSentMessageCount. // Let's make sure atleast number is >= than the minimum messages required to complete the // handshake. - NL_TEST_ASSERT(inSuite, loopback.mSentMessageCount >= sTestPaseMessageCount); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); + EXPECT_TRUE(loopback.mSentMessageCount >= sTestPaseMessageCount); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); if (mrpCommissionerConfig.HasValue()) { - NL_TEST_ASSERT(inSuite, - pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout == - mrpCommissionerConfig.Value().mIdleRetransTimeout); - NL_TEST_ASSERT(inSuite, - pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout == - mrpCommissionerConfig.Value().mActiveRetransTimeout); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mIdleRetransTimeout, mrpCommissionerConfig.Value().mIdleRetransTimeout); + EXPECT_EQ(pairingAccessory.GetRemoteMRPConfig().mActiveRetransTimeout, mrpCommissionerConfig.Value().mActiveRetransTimeout); } if (mrpAccessoryConfig.HasValue()) { - NL_TEST_ASSERT(inSuite, - pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout == - mrpAccessoryConfig.Value().mIdleRetransTimeout); - NL_TEST_ASSERT(inSuite, - pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout == - mrpAccessoryConfig.Value().mActiveRetransTimeout); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mIdleRetransTimeout, mrpAccessoryConfig.Value().mIdleRetransTimeout); + EXPECT_EQ(pairingCommissioner.GetRemoteMRPConfig().mActiveRetransTimeout, mrpAccessoryConfig.Value().mActiveRetransTimeout); } // Now evict the PASE sessions. auto session = pairingCommissioner.CopySecureSession(); - NL_TEST_ASSERT(inSuite, session.HasValue()); + EXPECT_TRUE(session.HasValue()); session.Value()->AsSecureSession()->MarkForEviction(); session = pairingAccessory.CopySecureSession(); - NL_TEST_ASSERT(inSuite, session.HasValue()); + EXPECT_TRUE(session.HasValue()); session.Value()->AsSecureSession()->MarkForEviction(); // Evicting a session async notifies the PASESession's delegate. Normally @@ -368,95 +350,86 @@ void SecurePairingHandshakeTestCommon(nlTestSuite * inSuite, void * inContext, S ctx.DrainAndServiceIO(); // And check that this did not result in any new notifications. - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 1); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 1u); loopback.SetLoopbackTransportDelegate(nullptr); } -void SecurePairingHandshakeTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, - Optional::Missing(), + SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Missing(), Optional::Missing(), delegateCommissioner); } -void SecurePairingHandshakeWithCommissionerMRPTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithCommissionerMRPTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig config(1000_ms32, 10000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, + SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Value(config), Optional::Missing(), delegateCommissioner); } -void SecurePairingHandshakeWithDeviceMRPTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithDeviceMRPTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig config(1000_ms32, 10000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, - Optional::Missing(), + SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Missing(), Optional::Value(config), delegateCommissioner); } -void SecurePairingHandshakeWithAllMRPTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithAllMRPTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig commissionerConfig(1000_ms32, 10000_ms32, 4000_ms16); ReliableMessageProtocolConfig deviceConfig(2000_ms32, 7000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, + SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Value(commissionerConfig), Optional::Value(deviceConfig), delegateCommissioner); } -void SecurePairingHandshakeWithPacketLossTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingHandshakeWithPacketLossTest) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); loopback.mNumMessagesToDrop = 2; - SecurePairingHandshakeTestCommon(inSuite, inContext, sessionManager, pairingCommissioner, - Optional::Missing(), + SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Missing(), Optional::Missing(), delegateCommissioner); - NL_TEST_ASSERT(inSuite, loopback.mDroppedMessageCount == 2); - NL_TEST_ASSERT(inSuite, loopback.mNumMessagesToDrop == 0); + EXPECT_EQ(loopback.mDroppedMessageCount, 2u); + EXPECT_EQ(loopback.mNumMessagesToDrop, 0u); } -void SecurePairingFailedHandshake(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, SecurePairingFailedHandshake) { - TestContext & ctx = *reinterpret_cast(inContext); - TemporarySessionManager sessionManager(inSuite, ctx); + TemporarySessionManager sessionManager(*this); TestSecurePairingDelegate delegateCommissioner; PASESession pairingCommissioner; @@ -464,98 +437,60 @@ void SecurePairingFailedHandshake(nlTestSuite * inSuite, void * inContext) TestSecurePairingDelegate delegateAccessory; PASESession pairingAccessory; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.Reset(); loopback.mSentMessageCount = 0; - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); ReliableMessageContext * rc = contextCommissioner->GetReliableMessageContext(); - NL_TEST_ASSERT(inSuite, rm != nullptr); - NL_TEST_ASSERT(inSuite, rc != nullptr); + ASSERT_NE(rm, nullptr); + ASSERT_NE(rc, nullptr); contextCommissioner->GetSessionHandle()->AsUnauthenticatedSession()->SetRemoteSessionParameters(ReliableMessageProtocolConfig({ 64_ms32, // CHIP_CONFIG_MRP_LOCAL_IDLE_RETRY_INTERVAL 64_ms32, // CHIP_CONFIG_MRP_LOCAL_ACTIVE_RETRY_INTERVAL })); - NL_TEST_ASSERT(inSuite, - ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType( - Protocols::SecureChannel::MsgType::PBKDFParamRequest, &pairingAccessory) == CHIP_NO_ERROR); - - NL_TEST_ASSERT(inSuite, - pairingAccessory.WaitForPairing( - sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, ByteSpan(sTestSpake2p01_Salt), - Optional::Missing(), &delegateAccessory) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, - pairingCommissioner.Pair(sessionManager, 4321, Optional::Missing(), - contextCommissioner, &delegateCommissioner) == CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); - - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateAccessory.mNumPairingErrors == 1); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingComplete == 0); - NL_TEST_ASSERT(inSuite, delegateCommissioner.mNumPairingErrors == 1); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest, + &pairingAccessory), + CHIP_NO_ERROR); + + EXPECT_EQ(pairingAccessory.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, + ByteSpan(sTestSpake2p01_Salt), Optional::Missing(), + &delegateAccessory), + CHIP_NO_ERROR); + DrainAndServiceIO(); + + EXPECT_EQ(pairingCommissioner.Pair(sessionManager, 4321, Optional::Missing(), + contextCommissioner, &delegateCommissioner), + CHIP_NO_ERROR); + DrainAndServiceIO(); + + EXPECT_EQ(delegateAccessory.mNumPairingComplete, 0u); + EXPECT_EQ(delegateAccessory.mNumPairingErrors, 1u); + EXPECT_EQ(delegateCommissioner.mNumPairingComplete, 0u); + EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 1u); } -void PASEVerifierSerializeTest(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPASESession, PASEVerifierSerializeTest) { Spake2pVerifier verifier; - NL_TEST_ASSERT(inSuite, verifier.Deserialize(ByteSpan(sTestSpake2p01_SerializedVerifier)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(&verifier, &sTestSpake2p01_PASEVerifier, sizeof(Spake2pVerifier)) == 0); + EXPECT_EQ(verifier.Deserialize(ByteSpan(sTestSpake2p01_SerializedVerifier)), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(&verifier, &sTestSpake2p01_PASEVerifier, sizeof(Spake2pVerifier)), 0); Spake2pVerifierSerialized serializedVerifier; MutableByteSpan serializedVerifierSpan(serializedVerifier); - NL_TEST_ASSERT(inSuite, verifier.Serialize(serializedVerifierSpan) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, serializedVerifierSpan.size() == kSpake2p_VerifierSerialized_Length); - NL_TEST_ASSERT(inSuite, memcmp(serializedVerifier, sTestSpake2p01_SerializedVerifier, kSpake2p_VerifierSerialized_Length) == 0); + EXPECT_EQ(verifier.Serialize(serializedVerifierSpan), CHIP_NO_ERROR); + EXPECT_EQ(serializedVerifierSpan.size(), kSpake2p_VerifierSerialized_Length); + EXPECT_EQ(memcmp(serializedVerifier, sTestSpake2p01_SerializedVerifier, kSpake2p_VerifierSerialized_Length), 0); Spake2pVerifierSerialized serializedVerifier2; MutableByteSpan serializedVerifier2Span(serializedVerifier2); - NL_TEST_ASSERT(inSuite, chip::Crypto::DRBG_get_bytes(serializedVerifier, kSpake2p_VerifierSerialized_Length) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, verifier.Deserialize(ByteSpan(serializedVerifier)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, verifier.Serialize(serializedVerifier2Span) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, memcmp(serializedVerifier, serializedVerifier2, kSpake2p_VerifierSerialized_Length) == 0); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(serializedVerifier, kSpake2p_VerifierSerialized_Length), CHIP_NO_ERROR); + EXPECT_EQ(verifier.Deserialize(ByteSpan(serializedVerifier)), CHIP_NO_ERROR); + EXPECT_EQ(verifier.Serialize(serializedVerifier2Span), CHIP_NO_ERROR); + EXPECT_EQ(memcmp(serializedVerifier, serializedVerifier2, kSpake2p_VerifierSerialized_Length), 0); } - -// Test Suite - -static const nlTest sTests[] = { - NL_TEST_DEF("WaitInit", SecurePairingWaitTest), - NL_TEST_DEF("Start", SecurePairingStartTest), - NL_TEST_DEF("Handshake", SecurePairingHandshakeTest), - NL_TEST_DEF("Handshake with Commissioner MRP Parameters", SecurePairingHandshakeWithCommissionerMRPTest), - NL_TEST_DEF("Handshake with Device MRP Parameters", SecurePairingHandshakeWithDeviceMRPTest), - NL_TEST_DEF("Handshake with Both MRP Parameters", SecurePairingHandshakeWithAllMRPTest), - NL_TEST_DEF("Handshake with packet loss", SecurePairingHandshakeWithPacketLossTest), - NL_TEST_DEF("Failed Handshake", SecurePairingFailedHandshake), - NL_TEST_DEF("PASE Verifier Serialize", PASEVerifierSerializeTest), - NL_TEST_SENTINEL(), -}; - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-SecurePairing-PASE", - &sTests[0], - NL_TEST_WRAP_FUNCTION(TestContext::SetUpTestSuite), - NL_TEST_WRAP_FUNCTION(TestContext::TearDownTestSuite), - NL_TEST_WRAP_METHOD(TestContext, SetUp), - NL_TEST_WRAP_METHOD(TestContext, TearDown), -}; -// clang-format on - -} // anonymous namespace - -/** - * Main - */ -int TestPASESession() -{ - return chip::ExecuteTestsWithContext(&sSuite); -} - -CHIP_REGISTER_TEST_SUITE(TestPASESession) +} // namespace diff --git a/src/protocols/secure_channel/tests/TestPairingSession.cpp b/src/protocols/secure_channel/tests/TestPairingSession.cpp index 4a3fe88d55c7aa..6a39b63fdd5e14 100644 --- a/src/protocols/secure_channel/tests/TestPairingSession.cpp +++ b/src/protocols/secure_channel/tests/TestPairingSession.cpp @@ -22,11 +22,11 @@ */ #include -#include +#include #include #include -#include + #include #include #include @@ -36,9 +36,17 @@ using namespace chip; using namespace chip::System::Clock; -class TestPairingSession : public PairingSession +class TestPairingSession : public PairingSession, public ::testing::Test { public: + static void SetUpTestSuite() + { + + CHIP_ERROR error = chip::Platform::MemoryInit(); + EXPECT_EQ(error, CHIP_NO_ERROR); + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } + Transport::SecureSession::Type GetSecureSessionType() const override { return Transport::SecureSession::Type::kPASE; } ScopedNodeId GetPeer() const override { return ScopedNodeId(); } ScopedNodeId GetLocalScopedNodeId() const override { return ScopedNodeId(); } @@ -56,10 +64,8 @@ class TestPairingSession : public PairingSession } }; -void PairingSessionEncodeDecodeMRPParams(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPairingSession, PairingSessionEncodeDecodeMRPParams) { - TestPairingSession session; - ReliableMessageProtocolConfig config(Milliseconds32(100), Milliseconds32(200), Milliseconds16(4000)); System::PacketBufferHandle buf = System::PacketBufferHandle::New(64, 0); @@ -67,108 +73,48 @@ void PairingSessionEncodeDecodeMRPParams(nlTestSuite * inSuite, void * inContext writer.Init(buf.Retain()); TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; - NL_TEST_ASSERT(inSuite, - writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, PairingSession::EncodeSessionParameters(TLV::ContextTag(1), config, writer) == CHIP_NO_ERROR); + EXPECT_EQ(PairingSession::EncodeSessionParameters(TLV::ContextTag(1), config, writer), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.EndContainer(outerContainerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Finalize(&buf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(outerContainerType), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&buf), CHIP_NO_ERROR); System::PacketBufferTLVReader reader; TLV::TLVType containerType = TLV::kTLVType_Structure; reader.Init(std::move(buf)); - NL_TEST_ASSERT(inSuite, reader.Next(containerType, TLV::AnonymousTag()) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.EnterContainer(containerType) == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(containerType, TLV::AnonymousTag()), CHIP_NO_ERROR); + EXPECT_EQ(reader.EnterContainer(containerType), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.DecodeMRPParametersIfPresent(TLV::ContextTag(1), reader) == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); + EXPECT_EQ(DecodeMRPParametersIfPresent(TLV::ContextTag(1), reader), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.GetRemoteMRPConfig() == config); + EXPECT_EQ(GetRemoteMRPConfig(), config); } -void PairingSessionTryDecodeMissingMRPParams(nlTestSuite * inSuite, void * inContext) +TEST_F(TestPairingSession, PairingSessionTryDecodeMissingMRPParams) { - TestPairingSession session; - System::PacketBufferHandle buf = System::PacketBufferHandle::New(64, 0); System::PacketBufferTLVWriter writer; writer.Init(buf.Retain()); TLV::TLVType outerContainerType = TLV::kTLVType_NotSpecified; - NL_TEST_ASSERT(inSuite, - writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Put(TLV::ContextTag(1), static_cast(0x1234)) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.EndContainer(outerContainerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, writer.Finalize(&buf) == CHIP_NO_ERROR); + EXPECT_EQ(writer.StartContainer(TLV::AnonymousTag(), TLV::kTLVType_Structure, outerContainerType), CHIP_NO_ERROR); + EXPECT_EQ(writer.Put(TLV::ContextTag(1), static_cast(0x1234)), CHIP_NO_ERROR); + EXPECT_EQ(writer.EndContainer(outerContainerType), CHIP_NO_ERROR); + EXPECT_EQ(writer.Finalize(&buf), CHIP_NO_ERROR); System::PacketBufferTLVReader reader; TLV::TLVType containerType = TLV::kTLVType_Structure; reader.Init(std::move(buf)); - NL_TEST_ASSERT(inSuite, reader.Next(containerType, TLV::AnonymousTag()) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.EnterContainer(containerType) == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reader.Next() == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.DecodeMRPParametersIfPresent(TLV::ContextTag(2), reader) == CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(containerType, TLV::AnonymousTag()), CHIP_NO_ERROR); + EXPECT_EQ(reader.EnterContainer(containerType), CHIP_NO_ERROR); + EXPECT_EQ(reader.Next(), CHIP_NO_ERROR); + EXPECT_EQ(DecodeMRPParametersIfPresent(TLV::ContextTag(2), reader), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, session.GetRemoteMRPConfig() == GetDefaultMRPConfig()); + EXPECT_EQ(GetRemoteMRPConfig(), GetDefaultMRPConfig()); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("Encode and Decode MRP params", PairingSessionEncodeDecodeMRPParams), - NL_TEST_DEF("Decode missing MRP params", PairingSessionTryDecodeMissingMRPParams), - - NL_TEST_SENTINEL() -}; -// clang-format on - -/** - * Set up the test suite. - */ -int TestPairingSession_Setup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -int TestPairingSession_Teardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-PairingSession", - &sTests[0], - TestPairingSession_Setup, - TestPairingSession_Teardown -}; -// clang-format on - -/** - * Main - */ -int TestPairingSessionInit() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestPairingSessionInit) diff --git a/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp b/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp index cb511f6993c57d..31b964ec99b1cd 100644 --- a/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp @@ -15,8 +15,7 @@ * limitations under the License. */ -#include -#include +#include #include #include @@ -26,27 +25,27 @@ constexpr chip::NodeId node1 = 12344321; constexpr chip::FabricIndex fabric2 = 14; constexpr chip::NodeId node2 = 11223344; -void TestLink(nlTestSuite * inSuite, void * inContext) +TEST(TestSimpleSessionResumptionStorage, TestLink) { chip::TestPersistentStorageDelegate storage; chip::SimpleSessionResumptionStorage sessionStorage; sessionStorage.Init(&storage); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size())); + EXPECT_EQ( chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveLink(resumptionId, chip::ScopedNodeId(node1, fabric1))); + EXPECT_EQ( sessionStorage.SaveLink(resumptionId, chip::ScopedNodeId(node1, fabric1)), CHIP_NO_ERROR); chip::ScopedNodeId node; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadLink(resumptionId, node)); - NL_TEST_ASSERT(inSuite, node == chip::ScopedNodeId(node1, fabric1)); + EXPECT_EQ( sessionStorage.LoadLink(resumptionId, node), CHIP_NO_ERROR); + EXPECT_EQ(node, chip::ScopedNodeId(node1, fabric1)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.DeleteLink(resumptionId)); + EXPECT_EQ( sessionStorage.DeleteLink(resumptionId), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND == sessionStorage.LoadLink(resumptionId, node)); + EXPECT_EQ(sessionStorage.LoadLink(resumptionId, node), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -void TestState(nlTestSuite * inSuite, void * inContext) +TEST(TestSimpleSessionResumptionStorage, TestState) { chip::TestPersistentStorageDelegate storage; chip::SimpleSessionResumptionStorage sessionStorage; @@ -55,31 +54,29 @@ void TestState(nlTestSuite * inSuite, void * inContext) chip::ScopedNodeId node(node1, fabric1); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size())); + EXPECT_EQ( chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); chip::Crypto::P256ECDHDerivedSecret sharedSecret; sharedSecret.SetLength(sharedSecret.Capacity()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length())); + EXPECT_EQ( chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); chip::CATValues peerCATs; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveState(node, resumptionId, sharedSecret, peerCATs)); + EXPECT_EQ( sessionStorage.SaveState(node, resumptionId, sharedSecret, peerCATs), CHIP_NO_ERROR); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId2; chip::Crypto::P256ECDHDerivedSecret sharedSecret2; chip::CATValues peerCATs2; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2)); - NL_TEST_ASSERT(inSuite, resumptionId == resumptionId2); - NL_TEST_ASSERT(inSuite, memcmp(sharedSecret.Bytes(), sharedSecret2.Bytes(), sharedSecret.Length()) == 0); + EXPECT_EQ( sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), CHIP_NO_ERROR); + EXPECT_EQ(resumptionId, resumptionId2); + EXPECT_EQ(memcmp(sharedSecret.Bytes(), sharedSecret2.Bytes(), sharedSecret.Length()), 0); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.DeleteState(node)); + EXPECT_EQ( sessionStorage.DeleteState(node), CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, - CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND == - sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2)); + EXPECT_EQ( sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } -void TestIndex(nlTestSuite * inSuite, void * inContext) +TEST(TestSimpleSessionResumptionStorage, TestIndex) { chip::TestPersistentStorageDelegate storage; chip::SimpleSessionResumptionStorage sessionStorage; @@ -88,63 +85,26 @@ void TestIndex(nlTestSuite * inSuite, void * inContext) chip::ScopedNodeId node(node1, fabric1); chip::DefaultSessionResumptionStorage::SessionIndex index0o; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadIndex(index0o)); - NL_TEST_ASSERT(inSuite, index0o.mSize == 0); + EXPECT_EQ( sessionStorage.LoadIndex(index0o), CHIP_NO_ERROR); + EXPECT_EQ(index0o.mSize, 0u); chip::DefaultSessionResumptionStorage::SessionIndex index1; index1.mSize = 0; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveIndex(index1)); + EXPECT_EQ( sessionStorage.SaveIndex(index1), CHIP_NO_ERROR); chip::DefaultSessionResumptionStorage::SessionIndex index1o; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadIndex(index1o)); - NL_TEST_ASSERT(inSuite, index1o.mSize == 0); + EXPECT_EQ( sessionStorage.LoadIndex(index1o), CHIP_NO_ERROR); + EXPECT_EQ(index1o.mSize, 0u); chip::DefaultSessionResumptionStorage::SessionIndex index2; index2.mSize = 2; index2.mNodes[0] = chip::ScopedNodeId(node1, fabric1); index2.mNodes[1] = chip::ScopedNodeId(node2, fabric2); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.SaveIndex(index2)); + EXPECT_EQ(CHIP_NO_ERROR, sessionStorage.SaveIndex(index2)); chip::DefaultSessionResumptionStorage::SessionIndex index2o; - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == sessionStorage.LoadIndex(index2o)); - NL_TEST_ASSERT(inSuite, index2o.mSize == 2); - NL_TEST_ASSERT(inSuite, index2o.mNodes[0] == chip::ScopedNodeId(node1, fabric1)); - NL_TEST_ASSERT(inSuite, index2o.mNodes[1] == chip::ScopedNodeId(node2, fabric2)); + EXPECT_EQ(CHIP_NO_ERROR, sessionStorage.LoadIndex(index2o)); + EXPECT_EQ(index2o.mSize, 2u); + EXPECT_EQ(index2o.mNodes[0], chip::ScopedNodeId(node1, fabric1)); + EXPECT_EQ(index2o.mNodes[1], chip::ScopedNodeId(node2, fabric2)); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TestLink", TestLink), - NL_TEST_DEF("TestState", TestState), - NL_TEST_DEF("TestIndex", TestState), - - NL_TEST_SENTINEL() -}; -// clang-format on - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-SimpleSessionResumptionStorage", - &sTests[0], - nullptr, - nullptr, -}; -// clang-format on - -/** - * Main - */ -int TestSimpleSessionResumptionStorage() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestSimpleSessionResumptionStorage) diff --git a/src/protocols/secure_channel/tests/TestStatusReport.cpp b/src/protocols/secure_channel/tests/TestStatusReport.cpp index 093453029b156b..3a1bdc38c7bf91 100644 --- a/src/protocols/secure_channel/tests/TestStatusReport.cpp +++ b/src/protocols/secure_channel/tests/TestStatusReport.cpp @@ -19,19 +19,29 @@ #include #include #include -#include + #include #include #include #include -#include +#include using namespace chip; using namespace chip::Protocols; using namespace chip::Protocols::SecureChannel; -void TestStatusReport_NoData(nlTestSuite * inSuite, void * inContext) +struct TestStatusReport : public ::testing::Test +{ + static void SetUpTestSuite() + { + CHIP_ERROR error = chip::Platform::MemoryInit(); + EXPECT_EQ(error, CHIP_NO_ERROR); + } + static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } +}; + +TEST_F(TestStatusReport, NoData) { GeneralStatusCode generalCode = GeneralStatusCode::kSuccess; auto protocolId = SecureChannel::Id; @@ -44,20 +54,20 @@ void TestStatusReport_NoData(nlTestSuite * inSuite, void * inContext) testReport.WriteToBuffer(bbuf); System::PacketBufferHandle msgBuf = bbuf.Finalize(); - NL_TEST_ASSERT(inSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; CHIP_ERROR err = reportToParse.Parse(std::move(msgBuf)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reportToParse.GetGeneralCode() == generalCode); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolId() == protocolId); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolCode() == protocolCode); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); + EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); + EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & data = reportToParse.GetProtocolData(); - NL_TEST_ASSERT(inSuite, data.IsNull()); + EXPECT_TRUE(data.IsNull()); } -void TestStatusReport_WithData(nlTestSuite * inSuite, void * inContext) +TEST_F(TestStatusReport, WithData) { GeneralStatusCode generalCode = GeneralStatusCode::kFailure; auto protocolId = SecureChannel::Id; @@ -73,39 +83,35 @@ void TestStatusReport_WithData(nlTestSuite * inSuite, void * inContext) testReport.WriteToBuffer(bbuf); System::PacketBufferHandle msgBuf = bbuf.Finalize(); - NL_TEST_ASSERT(inSuite, !msgBuf.IsNull()); + EXPECT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; CHIP_ERROR err = reportToParse.Parse(std::move(msgBuf)); - NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); - NL_TEST_ASSERT(inSuite, reportToParse.GetGeneralCode() == generalCode); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolId() == protocolId); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolCode() == protocolCode); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); + EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); + EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & rcvData = reportToParse.GetProtocolData(); - if (rcvData.IsNull()) - { - NL_TEST_ASSERT(inSuite, false); - return; - } - NL_TEST_ASSERT(inSuite, rcvData->DataLength() == dataLen); - NL_TEST_ASSERT(inSuite, !memcmp(rcvData->Start(), data, dataLen)); + EXPECT_FALSE(rcvData.IsNull()); + EXPECT_EQ(rcvData->DataLength(), dataLen); + EXPECT_EQ(memcmp(rcvData->Start(), data, dataLen), 0); } -void TestBadStatusReport(nlTestSuite * inSuite, void * inContext) +TEST_F(TestStatusReport, TestBadStatusReport) { StatusReport report; System::PacketBufferHandle badMsg = System::PacketBufferHandle::New(10); CHIP_ERROR err = report.Parse(std::move(badMsg)); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); StatusReport report2; badMsg = nullptr; err = report2.Parse(std::move(badMsg)); - NL_TEST_ASSERT(inSuite, err != CHIP_NO_ERROR); + EXPECT_NE(err, CHIP_NO_ERROR); } -void TestMakeBusyStatusReport(nlTestSuite * inSuite, void * inContext) +TEST_F(TestStatusReport, TestMakeBusyStatusReport) { GeneralStatusCode generalCode = GeneralStatusCode::kBusy; auto protocolId = SecureChannel::Id; @@ -113,81 +119,23 @@ void TestMakeBusyStatusReport(nlTestSuite * inSuite, void * inContext) System::Clock::Milliseconds16 minimumWaitTime = System::Clock::Milliseconds16(5000); System::PacketBufferHandle handle = StatusReport::MakeBusyStatusReportMessage(minimumWaitTime); - NL_TEST_ASSERT(inSuite, !handle.IsNull()); + EXPECT_FALSE(handle.IsNull()); StatusReport reportToParse; CHIP_ERROR err = reportToParse.Parse(std::move(handle)); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == err); - NL_TEST_ASSERT(inSuite, reportToParse.GetGeneralCode() == generalCode); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolId() == protocolId); - NL_TEST_ASSERT(inSuite, reportToParse.GetProtocolCode() == protocolCode); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); + EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); + EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & rcvData = reportToParse.GetProtocolData(); - NL_TEST_ASSERT(inSuite, !rcvData.IsNull()); - NL_TEST_ASSERT(inSuite, rcvData->DataLength() == sizeof(minimumWaitTime)); + EXPECT_FALSE(rcvData.IsNull()); + EXPECT_EQ(rcvData->DataLength(), sizeof(minimumWaitTime)); uint16_t readMinimumWaitTime = 0; Encoding::LittleEndian::Reader reader(rcvData->Start(), rcvData->DataLength()); - NL_TEST_ASSERT(inSuite, CHIP_NO_ERROR == reader.Read16(&readMinimumWaitTime).StatusCode()); - NL_TEST_ASSERT(inSuite, System::Clock::Milliseconds16(readMinimumWaitTime) == minimumWaitTime); + EXPECT_EQ(reader.Read16(&readMinimumWaitTime).StatusCode(), CHIP_NO_ERROR); + EXPECT_EQ(System::Clock::Milliseconds16(readMinimumWaitTime), minimumWaitTime); } // Test Suite - -/** - * Test Suite that lists all the test functions. - */ -// clang-format off -static const nlTest sTests[] = -{ - NL_TEST_DEF("TestStatusReport_NoData", TestStatusReport_NoData), - NL_TEST_DEF("TestStatusReport_WithData", TestStatusReport_WithData), - NL_TEST_DEF("TestBadStatusReport", TestBadStatusReport), - NL_TEST_DEF("TestMakeBusyStatusReport", TestMakeBusyStatusReport), - - NL_TEST_SENTINEL() -}; -// clang-format on - -/** - * Set up the test suite. - */ -static int TestSetup(void * inContext) -{ - CHIP_ERROR error = chip::Platform::MemoryInit(); - if (error != CHIP_NO_ERROR) - return FAILURE; - return SUCCESS; -} - -/** - * Tear down the test suite. - */ -static int TestTeardown(void * inContext) -{ - chip::Platform::MemoryShutdown(); - return SUCCESS; -} - -// clang-format off -static nlTestSuite sSuite = -{ - "Test-CHIP-StatusReport", - &sTests[0], - TestSetup, - TestTeardown, -}; -// clang-format on - -/** - * Main - */ -int TestStatusReport() -{ - // Run test suit against one context - nlTestRunner(&sSuite, nullptr); - - return (nlTestRunnerStats(&sSuite)); -} - -CHIP_REGISTER_TEST_SUITE(TestStatusReport) From ea09c42e9fef1f2c26dd05601fab3af6984aee77 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Wed, 15 May 2024 16:37:12 +0200 Subject: [PATCH 02/30] Remove nlunit tests dependency --- src/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/src/BUILD.gn b/src/BUILD.gn index cf15f40ec00629..13f09beab2d4df 100644 --- a/src/BUILD.gn +++ b/src/BUILD.gn @@ -100,7 +100,6 @@ if (chip_build_tests) { "${chip_root}/src/lib/format/tests", "${chip_root}/src/lib/support/tests", "${chip_root}/src/protocols/secure_channel/tests", - "${chip_root}/src/protocols/secure_channel/tests:tests_nltest", "${chip_root}/src/system/tests", "${chip_root}/src/transport/tests", ] From 72b3dc038ea13dad72e1879ac3601967d37f981d Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Thu, 16 May 2024 10:34:08 +0200 Subject: [PATCH 03/30] Update conversion to pigweed --- src/lib/support/UnitTest.h | 10 + src/protocols/secure_channel/CASESession.h | 2 +- .../secure_channel/tests/TestCASESession.cpp | 260 ++++++++---------- 3 files changed, 129 insertions(+), 143 deletions(-) diff --git a/src/lib/support/UnitTest.h b/src/lib/support/UnitTest.h index 0cf8a8ef75356c..537eaf3784d318 100644 --- a/src/lib/support/UnitTest.h +++ b/src/lib/support/UnitTest.h @@ -1,5 +1,15 @@ #pragma once +/* + * Run fixture's class function as a test. + */ +#define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ + TEST_F(test_fixture, test_name) \ + { \ + test_name(); \ + } \ + void test_fixture::test_name() + namespace chip { namespace test { diff --git a/src/protocols/secure_channel/CASESession.h b/src/protocols/secure_channel/CASESession.h index 045d1982dd723c..5200cb8f65368e 100644 --- a/src/protocols/secure_channel/CASESession.h +++ b/src/protocols/secure_channel/CASESession.h @@ -212,7 +212,7 @@ class DLL_EXPORT CASESession : public Messaging::UnsolicitedMessageHandler, bool InvokeBackgroundWorkWatchdog(); private: - friend class TestCASESession; + friend class TestCASESessionWithManager; using AutoReleaseSessionKey = Crypto::AutoReleaseSymmetricKey; diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index a16ffbca199be8..3d982ce0a3df5d 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -35,11 +35,11 @@ #include #include #include +#include #include #include #include #include -#include #include "credentials/tests/CHIPCert_test_vectors.h" @@ -106,8 +106,40 @@ class TestOperationalKeystore : public chip::Crypto::OperationalKeystore FabricIndex mSingleFabricIndex = kUndefinedFabricIndex; }; -struct TestCASESession : public Test::LoopbackMessagingContext, public ::testing::Test +namespace { +#if CHIP_CONFIG_SLOW_CRYPTO +constexpr uint32_t sTestCaseMessageCount = 8; +constexpr uint32_t sTestCaseResumptionMessageCount = 6; +#else // CHIP_CONFIG_SLOW_CRYPTO +constexpr uint32_t sTestCaseMessageCount = 5; +constexpr uint32_t sTestCaseResumptionMessageCount = 4; +#endif // CHIP_CONFIG_SLOW_CRYPTO + +FabricTable gCommissionerFabrics; +FabricIndex gCommissionerFabricIndex; +GroupDataProviderImpl gCommissionerGroupDataProvider; +TestPersistentStorageDelegate gCommissionerStorageDelegate; +Crypto::DefaultSessionKeystore gCommissionerSessionKeystore; + +FabricTable gDeviceFabrics; +FabricIndex gDeviceFabricIndex; +GroupDataProviderImpl gDeviceGroupDataProvider; +TestPersistentStorageDelegate gDeviceStorageDelegate; +TestOperationalKeystore gDeviceOperationalKeystore; +Crypto::DefaultSessionKeystore gDeviceSessionKeystore; + +Credentials::PersistentStorageOpCertStore gCommissionerOpCertStore; +Credentials::PersistentStorageOpCertStore gDeviceOpCertStore; + +CASEServer gPairingServer; + +NodeId Node01_01 = 0xDEDEDEDE00010001; +NodeId Node01_02 = 0xDEDEDEDE00010002; +} // namespace + +class TestCASESession : public Test::LoopbackMessagingContext, public ::testing::Test { +public: static void SetUpTestSuite() { ConfigInitializeNodes(false); @@ -115,13 +147,13 @@ struct TestCASESession : public Test::LoopbackMessagingContext, public ::testing LoopbackMessagingContext::SetUpTestSuite(); err = chip::DeviceLayer::PlatformMgr().InitChipStack(); - EXPECT_EQ(err, CHIP_NO_ERROR) << "Init CHIP stack failed: " << std::hex << err.Format(); - err = - InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, &gCommissionerOpCertStore); - EXPECT_EQ(err, CHIP_NO_ERROR) << "InitFabricTable failed: " << std::hex << err.Format(); + ASSERT_EQ(err, CHIP_NO_ERROR) << "Init CHIP stack failed: " << std::hex << err.Format(); + err = InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, + &gCommissionerOpCertStore); + ASSERT_EQ(err, CHIP_NO_ERROR) << "InitFabricTable failed: " << std::hex << err.Format(); err = InitCredentialSets(); - EXPECT_EQ(err, CHIP_NO_ERROR) << "InitCredentialSets failed: " << std::hex << err.Format(); + ASSERT_EQ(err, CHIP_NO_ERROR) << "InitCredentialSets failed: " << std::hex << err.Format(); chip::DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); } @@ -157,101 +189,60 @@ struct TestCASESession : public Test::LoopbackMessagingContext, public ::testing static CHIP_ERROR InitCredentialSets(); static CHIP_ERROR InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, - chip::Crypto::OperationalKeystore * opKeyStore, - chip::Credentials::PersistentStorageOpCertStore * opCertStore); + chip::Crypto::OperationalKeystore * opKeyStore, + chip::Credentials::PersistentStorageOpCertStore * opCertStore); void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, - TestCASESecurePairingDelegate & delegateCommissioner); - - void SimulateUpdateNOCInvalidatePendingEstablishment(); - -#if CHIP_CONFIG_SLOW_CRYPTO - constexpr uint32_t sTestCaseMessageCount = 8; - constexpr uint32_t sTestCaseResumptionMessageCount = 6; -#else // CHIP_CONFIG_SLOW_CRYPTO - static constexpr uint32_t sTestCaseMessageCount = 5; - static constexpr uint32_t sTestCaseResumptionMessageCount = 4; -#endif // CHIP_CONFIG_SLOW_CRYPTO - - static FabricTable gCommissionerFabrics; - static FabricIndex gCommissionerFabricIndex; - static GroupDataProviderImpl gCommissionerGroupDataProvider; - static TestPersistentStorageDelegate gCommissionerStorageDelegate; - static Crypto::DefaultSessionKeystore gCommissionerSessionKeystore; - - static FabricTable gDeviceFabrics; - static FabricIndex gDeviceFabricIndex; - static GroupDataProviderImpl gDeviceGroupDataProvider; - static TestPersistentStorageDelegate gDeviceStorageDelegate; - static TestOperationalKeystore gDeviceOperationalKeystore; - static Crypto::DefaultSessionKeystore gDeviceSessionKeystore; - - static Credentials::PersistentStorageOpCertStore gCommissionerOpCertStore; - static Credentials::PersistentStorageOpCertStore gDeviceOpCertStore; - - static CASEServer gPairingServer; - - static NodeId Node01_01; - static NodeId Node01_02; + TestCASESecurePairingDelegate & delegateCommissioner); }; -NodeId TestCASESession::Node01_01 = 0xDEDEDEDE00010001; -NodeId TestCASESession::Node01_02 = 0xDEDEDEDE00010002; - -FabricTable TestCASESession::gCommissionerFabrics; -FabricIndex TestCASESession::gCommissionerFabricIndex; -GroupDataProviderImpl TestCASESession::gCommissionerGroupDataProvider; -TestPersistentStorageDelegate TestCASESession::gCommissionerStorageDelegate; -Crypto::DefaultSessionKeystore TestCASESession::gCommissionerSessionKeystore; - -FabricTable TestCASESession::gDeviceFabrics; -FabricIndex TestCASESession::gDeviceFabricIndex; -GroupDataProviderImpl TestCASESession::gDeviceGroupDataProvider; -TestPersistentStorageDelegate TestCASESession::gDeviceStorageDelegate; -TestOperationalKeystore TestCASESession::gDeviceOperationalKeystore; -Crypto::DefaultSessionKeystore TestCASESession::gDeviceSessionKeystore; - -Credentials::PersistentStorageOpCertStore TestCASESession::gCommissionerOpCertStore; -Credentials::PersistentStorageOpCertStore TestCASESession::gDeviceOpCertStore; +class TestCASESessionWithManager : public TestCASESession +{ +public: + static void SetUpTestSuite() { TestCASESession::SetUpTestSuite(); } + static void TearDownTestSuite() { TestCASESession::TearDownTestSuite(); } + void SetUp() override + { + TestCASESession::SetUp(); + SetUpSessionManager(); + } -CASEServer TestCASESession::gPairingServer; + void TearDown() override + { + TestCASESession::TearDown(); + TearDownSessionManager(); + } + void SimulateUpdateNOCInvalidatePendingEstablishment(); -class TemporarySessionManager -{ -public: - TemporarySessionManager(TestCASESession & ctx) : mCtx(ctx) + void SetUpSessionManager() { EXPECT_EQ(CHIP_NO_ERROR, - mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), &mStorage, - &ctx.GetFabricTable(), ctx.GetSessionKeystore())); + sessionManager.Init(&GetSystemLayer(), &GetTransportMgr(), &GetMessageCounterManager(), &mStorage, + &GetFabricTable(), GetSessionKeystore())); // The setup here is really weird: we are using one session manager for // the actual messages we send (the PASE handshake, so the // unauthenticated sessions) and a different one for allocating the PASE // sessions. Since our Init() set us up as the thing to handle messages // on the transport manager, undo that. - mCtx.GetTransportMgr().SetSessionManager(&mCtx.GetSecureSessionManager()); + GetTransportMgr().SetSessionManager(&GetSecureSessionManager()); } - ~TemporarySessionManager() + void TearDownSessionManager() { - mSessionManager.Shutdown(); + sessionManager.Shutdown(); // Reset the session manager on the transport again, just in case // shutdown messed with it. - mCtx.GetTransportMgr().SetSessionManager(&mCtx.GetSecureSessionManager()); + GetTransportMgr().SetSessionManager(&GetSecureSessionManager()); } - operator SessionManager &() { return mSessionManager; } - -private: - TestCASESession & mCtx; TestPersistentStorageDelegate mStorage; - SessionManager mSessionManager; + SessionManager sessionManager; }; CHIP_ERROR TestCASESession::InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, - chip::Crypto::OperationalKeystore * opKeyStore, - chip::Credentials::PersistentStorageOpCertStore * opCertStore) + chip::Crypto::OperationalKeystore * opKeyStore, + chip::Credentials::PersistentStorageOpCertStore * opCertStore) { ReturnErrorOnFailure(opCertStore->Init(testStorage)); @@ -291,8 +282,6 @@ class TestCASESecurePairingDelegate : public SessionEstablishmentDelegate uint32_t mNumBusyResponses = 0; }; - - CHIP_ERROR InitTestIpk(GroupDataProvider & groupDataProvider, const FabricInfo & fabricInfo, size_t numIpks) { VerifyOrReturnError((numIpks > 0) && (numIpks <= 3), CHIP_ERROR_INVALID_ARGUMENT); @@ -387,15 +376,12 @@ CHIP_ERROR TestCASESession::InitCredentialSets() return CHIP_NO_ERROR; } - // Specifically for SimulateUpdateNOCInvalidatePendingEstablishment, we need it to be static so that the class below can // be a friend to CASESession so that test can get access to CASESession::State and test method that are not public. To // keep the rest of this file consistent we brought all other tests into this class. -TEST_F(TestCASESession, SecurePairingWaitTest) +TEST_F(TestCASESessionWithManager, SecurePairingWaitTest) { - TemporarySessionManager sessionManager(*this); - // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; FabricTable fabrics; @@ -420,10 +406,8 @@ TEST_F(TestCASESession, SecurePairingWaitTest) caseSession.Clear(); } -TEST_F(TestCASESession, SecurePairingStartTest) +TEST_F(TestCASESessionWithManager, SecurePairingStartTest) { - TemporarySessionManager sessionManager(*this); - // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; CASESession pairing; @@ -471,7 +455,7 @@ TEST_F(TestCASESession, SecurePairingStartTest) } void TestCASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, - TestCASESecurePairingDelegate & delegateCommissioner) + TestCASESecurePairingDelegate & delegateCommissioner) { // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegateAccessory; @@ -485,7 +469,7 @@ void TestCASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionM loopback.mSentMessageCount = 0; EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::CASE_Sigma1, - &pairingAccessory), + &pairingAccessory), CHIP_NO_ERROR); ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); @@ -526,10 +510,8 @@ void TestCASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionM #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST } -TEST_F(TestCASESession, SecurePairingHandshakeTest) +TEST_F(TestCASESessionWithManager, SecurePairingHandshakeTest) { - TemporarySessionManager sessionManager(*this); - TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; pairingCommissioner.SetGroupDataProvider(&gCommissionerGroupDataProvider); @@ -589,10 +571,8 @@ TEST_F(TestCASESession, SecurePairingHandshakeServerTest) gPairingServer.Shutdown(); } -TEST_F(TestCASESession, ClientReceivesBusyTest) +TEST_F(TestCASESessionWithManager, ClientReceivesBusyTest) { - TemporarySessionManager sessionManager(*this); - TestCASESecurePairingDelegate delegateCommissioner1, delegateCommissioner2; CASESession pairingCommissioner1, pairingCommissioner2; @@ -764,35 +744,33 @@ static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) } // A macro, so we can tell which test failed based on line number. -// #define TestSigma1Parsing(inSuite, mem, bufferSize, params) -template -void TestSigma1Parsing(chip::Platform::ScopedMemoryBuffer & mem) -{ - MutableByteSpan buf(mem.Get(), bufferSize); - CHIP_ERROR err = EncodeSigma1(buf); - EXPECT_EQ(err, CHIP_NO_ERROR); - - TLV::ContiguousBufferTLVReader reader; - reader.Init(buf); - - ByteSpan initiatorRandom; - uint16_t initiatorSessionId; - ByteSpan destinationId; - ByteSpan initiatorEphPubKey; - bool resumptionRequested; - ByteSpan resumptionId; - ByteSpan initiatorResumeMIC; - CASESession session; - err = session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, resumptionRequested, - resumptionId, initiatorResumeMIC); - EXPECT_TRUE((err == CHIP_NO_ERROR) == params::expectSuccess); - if (params::expectSuccess) - { - EXPECT_TRUE(resumptionRequested == - (params::resumptionIdLen != 0 && - params::initiatorResumeMICLen != 0)); /* Add other verification tests here as desired */ - } -} +#define TestSigma1Parsing(mem, bufferSize, params) \ + do \ + { \ + MutableByteSpan buf(mem.Get(), bufferSize); \ + CHIP_ERROR err = EncodeSigma1(buf); \ + EXPECT_EQ(err, CHIP_NO_ERROR); \ + \ + TLV::ContiguousBufferTLVReader reader; \ + reader.Init(buf); \ + \ + ByteSpan initiatorRandom; \ + uint16_t initiatorSessionId; \ + ByteSpan destinationId; \ + ByteSpan initiatorEphPubKey; \ + bool resumptionRequested; \ + ByteSpan resumptionId; \ + ByteSpan initiatorResumeMIC; \ + CASESession session; \ + err = session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, \ + resumptionRequested, resumptionId, initiatorResumeMIC); \ + EXPECT_EQ(err == CHIP_NO_ERROR, params::expectSuccess); \ + if (params::expectSuccess) \ + { \ + EXPECT_EQ(resumptionRequested, params::resumptionIdLen != 0 && params::initiatorResumeMICLen != 0); \ + /* Add other verification tests here as desired */ \ + } \ + } while (0) struct BadSigma1ParamsBase : public Sigma1Params { @@ -886,22 +864,22 @@ TEST_F(TestCASESession, Sigma1ParsingTest) chip::Platform::ScopedMemoryBuffer mem; EXPECT_TRUE(mem.Calloc(bufferSize)); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); - TestSigma1Parsing(mem); + TestSigma1Parsing(mem, bufferSize, Sigma1Params); + TestSigma1Parsing(mem, bufferSize, Sigma1NoStructEnd); + TestSigma1Parsing(mem, bufferSize, Sigma1WrongTags); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongRandom); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortRandom); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongDest); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortDest); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongPubkey); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortPubkey); + TestSigma1Parsing(mem, bufferSize, Sigma1WithResumption); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongResumptionId); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortResumptionId); + TestSigma1Parsing(mem, bufferSize, Sigma1TooLongResumeMIC); + TestSigma1Parsing(mem, bufferSize, Sigma1TooShortResumeMIC); + TestSigma1Parsing(mem, bufferSize, Sigma1SessionIdMax); + TestSigma1Parsing(mem, bufferSize, Sigma1SessionIdTooBig); } struct SessionResumptionTestStorage : SessionResumptionStorage @@ -1049,10 +1027,8 @@ TEST_F(TestCASESession, SessionResumptionStorage) } #if CONFIG_BUILD_FOR_HOST_UNIT_TEST -TEST_F_FROM_FIXTURE(TestCASESession, SimulateUpdateNOCInvalidatePendingEstablishment) +TEST_F_FROM_FIXTURE(TestCASESessionWithManager, SimulateUpdateNOCInvalidatePendingEstablishment) { - TemporarySessionManager sessionManager(*this); - TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; pairingCommissioner.SetGroupDataProvider(&gCommissionerGroupDataProvider); From b1a4672805e419c2dc91084c57f5f6fe107132ff Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Thu, 16 May 2024 12:08:51 +0200 Subject: [PATCH 04/30] Relocate class --- .../secure_channel/tests/TestCASESession.cpp | 56 +++++++++---------- 1 file changed, 27 insertions(+), 29 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 3d982ce0a3df5d..f49719be389e02 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -55,7 +55,33 @@ using namespace chip::Crypto; namespace chip { -class TestCASESecurePairingDelegate; +class TestCASESecurePairingDelegate : public SessionEstablishmentDelegate +{ +public: + void OnSessionEstablishmentError(CHIP_ERROR error) override + { + mNumPairingErrors++; + if (error == CHIP_ERROR_BUSY) + { + mNumBusyResponses++; + } + } + + void OnSessionEstablished(const SessionHandle & session) override + { + mSession.Grab(session); + mNumPairingComplete++; + } + + SessionHolder & GetSessionHolder() { return mSession; } + + SessionHolder mSession; + + // TODO: Rename mNumPairing* to mNumEstablishment* + uint32_t mNumPairingErrors = 0; + uint32_t mNumPairingComplete = 0; + uint32_t mNumBusyResponses = 0; +}; class TestOperationalKeystore : public chip::Crypto::OperationalKeystore { @@ -254,34 +280,6 @@ CHIP_ERROR TestCASESession::InitFabricTable(chip::FabricTable & fabricTable, chi return fabricTable.Init(initParams); } -class TestCASESecurePairingDelegate : public SessionEstablishmentDelegate -{ -public: - void OnSessionEstablishmentError(CHIP_ERROR error) override - { - mNumPairingErrors++; - if (error == CHIP_ERROR_BUSY) - { - mNumBusyResponses++; - } - } - - void OnSessionEstablished(const SessionHandle & session) override - { - mSession.Grab(session); - mNumPairingComplete++; - } - - SessionHolder & GetSessionHolder() { return mSession; } - - SessionHolder mSession; - - // TODO: Rename mNumPairing* to mNumEstablishment* - uint32_t mNumPairingErrors = 0; - uint32_t mNumPairingComplete = 0; - uint32_t mNumBusyResponses = 0; -}; - CHIP_ERROR InitTestIpk(GroupDataProvider & groupDataProvider, const FabricInfo & fabricInfo, size_t numIpks) { VerifyOrReturnError((numIpks > 0) && (numIpks <= 3), CHIP_ERROR_INVALID_ARGUMENT); From 389159921c16c12a0ecd2240f557bb547001ea45 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Thu, 16 May 2024 15:08:12 +0200 Subject: [PATCH 05/30] Revert old implementation --- src/protocols/secure_channel/CASESession.h | 2 +- .../secure_channel/tests/TestCASESession.cpp | 255 +++++++++--------- 2 files changed, 124 insertions(+), 133 deletions(-) diff --git a/src/protocols/secure_channel/CASESession.h b/src/protocols/secure_channel/CASESession.h index 5200cb8f65368e..045d1982dd723c 100644 --- a/src/protocols/secure_channel/CASESession.h +++ b/src/protocols/secure_channel/CASESession.h @@ -212,7 +212,7 @@ class DLL_EXPORT CASESession : public Messaging::UnsolicitedMessageHandler, bool InvokeBackgroundWorkWatchdog(); private: - friend class TestCASESessionWithManager; + friend class TestCASESession; using AutoReleaseSessionKey = Crypto::AutoReleaseSymmetricKey; diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index f49719be389e02..286804df333428 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -54,6 +54,84 @@ using namespace chip::Protocols; using namespace chip::Crypto; namespace chip { +class TestCASESecurePairingDelegate; + +class TestCASESession : public Test::LoopbackMessagingContext, public ::testing::Test +{ +public: + // Performs shared setup for all tests in the test suite + static void SetUpTestSuite(); + // Performs shared teardown for all tests in the test suite + static void TearDownTestSuite(); + void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } + + void ServiceEvents(); + void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, + TestCASESecurePairingDelegate & delegateCommissioner); + + void SimulateUpdateNOCInvalidatePendingEstablishment(); +}; + +void TestCASESession::ServiceEvents() +{ + // Takes a few rounds of this because handling IO messages may schedule work, + // and scheduled work may queue messages for sending... + for (int i = 0; i < 3; ++i) + { + DrainAndServiceIO(); + + chip::DeviceLayer::PlatformMgr().ScheduleWork( + [](intptr_t) -> void { chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); }, (intptr_t) nullptr); + chip::DeviceLayer::PlatformMgr().RunEventLoop(); + } +} + +class TemporarySessionManager +{ +public: + TemporarySessionManager(TestCASESession & ctx) : mCtx(ctx) + { + EXPECT_EQ(CHIP_NO_ERROR, + mSessionManager.Init(&ctx.GetSystemLayer(), &ctx.GetTransportMgr(), &ctx.GetMessageCounterManager(), &mStorage, + &ctx.GetFabricTable(), ctx.GetSessionKeystore())); + // The setup here is really weird: we are using one session manager for + // the actual messages we send (the PASE handshake, so the + // unauthenticated sessions) and a different one for allocating the PASE + // sessions. Since our Init() set us up as the thing to handle messages + // on the transport manager, undo that. + mCtx.GetTransportMgr().SetSessionManager(&mCtx.GetSecureSessionManager()); + } + + ~TemporarySessionManager() + { + mSessionManager.Shutdown(); + // Reset the session manager on the transport again, just in case + // shutdown messed with it. + mCtx.GetTransportMgr().SetSessionManager(&mCtx.GetSecureSessionManager()); + } + + operator SessionManager &() { return mSessionManager; } + +private: + TestCASESession & mCtx; + TestPersistentStorageDelegate mStorage; + SessionManager mSessionManager; +}; + +CHIP_ERROR InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, + chip::Crypto::OperationalKeystore * opKeyStore, + chip::Credentials::PersistentStorageOpCertStore * opCertStore) +{ + ReturnErrorOnFailure(opCertStore->Init(testStorage)); + + chip::FabricTable::InitParams initParams; + initParams.storage = testStorage; + initParams.operationalKeystore = opKeyStore; + initParams.opCertStore = opCertStore; + + return fabricTable.Init(initParams); +} class TestCASESecurePairingDelegate : public SessionEstablishmentDelegate { @@ -132,7 +210,6 @@ class TestOperationalKeystore : public chip::Crypto::OperationalKeystore FabricIndex mSingleFabricIndex = kUndefinedFabricIndex; }; -namespace { #if CHIP_CONFIG_SLOW_CRYPTO constexpr uint32_t sTestCaseMessageCount = 8; constexpr uint32_t sTestCaseResumptionMessageCount = 6; @@ -161,124 +238,6 @@ CASEServer gPairingServer; NodeId Node01_01 = 0xDEDEDEDE00010001; NodeId Node01_02 = 0xDEDEDEDE00010002; -} // namespace - -class TestCASESession : public Test::LoopbackMessagingContext, public ::testing::Test -{ -public: - static void SetUpTestSuite() - { - ConfigInitializeNodes(false); - CHIP_ERROR err = CHIP_NO_ERROR; - LoopbackMessagingContext::SetUpTestSuite(); - err = chip::DeviceLayer::PlatformMgr().InitChipStack(); - - ASSERT_EQ(err, CHIP_NO_ERROR) << "Init CHIP stack failed: " << std::hex << err.Format(); - err = InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, - &gCommissionerOpCertStore); - ASSERT_EQ(err, CHIP_NO_ERROR) << "InitFabricTable failed: " << std::hex << err.Format(); - - err = InitCredentialSets(); - ASSERT_EQ(err, CHIP_NO_ERROR) << "InitCredentialSets failed: " << std::hex << err.Format(); - chip::DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); - } - - static void TearDownTestSuite() - { - chip::DeviceLayer::SetSystemLayerForTesting(nullptr); - gDeviceOperationalKeystore.Shutdown(); - gPairingServer.Shutdown(); - gCommissionerStorageDelegate.ClearStorage(); - gDeviceStorageDelegate.ClearStorage(); - gCommissionerFabrics.DeleteAllFabrics(); - gDeviceFabrics.DeleteAllFabrics(); - chip::DeviceLayer::PlatformMgr().Shutdown(); - LoopbackMessagingContext::TearDownTestSuite(); - } - - void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } - - void ServiceEvents() - { - // Takes a few rounds of this because handling IO messages may schedule work, - // and scheduled work may queue messages for sending... - for (int i = 0; i < 3; ++i) - { - DrainAndServiceIO(); - - chip::DeviceLayer::PlatformMgr().ScheduleWork( - [](intptr_t) -> void { chip::DeviceLayer::PlatformMgr().StopEventLoopTask(); }, (intptr_t) nullptr); - chip::DeviceLayer::PlatformMgr().RunEventLoop(); - } - }; - - static CHIP_ERROR InitCredentialSets(); - static CHIP_ERROR InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, - chip::Crypto::OperationalKeystore * opKeyStore, - chip::Credentials::PersistentStorageOpCertStore * opCertStore); - - void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, - TestCASESecurePairingDelegate & delegateCommissioner); -}; - -class TestCASESessionWithManager : public TestCASESession -{ -public: - static void SetUpTestSuite() { TestCASESession::SetUpTestSuite(); } - static void TearDownTestSuite() { TestCASESession::TearDownTestSuite(); } - void SetUp() override - { - TestCASESession::SetUp(); - SetUpSessionManager(); - } - - void TearDown() override - { - TestCASESession::TearDown(); - TearDownSessionManager(); - } - - void SimulateUpdateNOCInvalidatePendingEstablishment(); - - void SetUpSessionManager() - { - EXPECT_EQ(CHIP_NO_ERROR, - sessionManager.Init(&GetSystemLayer(), &GetTransportMgr(), &GetMessageCounterManager(), &mStorage, - &GetFabricTable(), GetSessionKeystore())); - // The setup here is really weird: we are using one session manager for - // the actual messages we send (the PASE handshake, so the - // unauthenticated sessions) and a different one for allocating the PASE - // sessions. Since our Init() set us up as the thing to handle messages - // on the transport manager, undo that. - GetTransportMgr().SetSessionManager(&GetSecureSessionManager()); - } - - void TearDownSessionManager() - { - sessionManager.Shutdown(); - // Reset the session manager on the transport again, just in case - // shutdown messed with it. - GetTransportMgr().SetSessionManager(&GetSecureSessionManager()); - } - - TestPersistentStorageDelegate mStorage; - SessionManager sessionManager; -}; - -CHIP_ERROR TestCASESession::InitFabricTable(chip::FabricTable & fabricTable, chip::TestPersistentStorageDelegate * testStorage, - chip::Crypto::OperationalKeystore * opKeyStore, - chip::Credentials::PersistentStorageOpCertStore * opCertStore) -{ - ReturnErrorOnFailure(opCertStore->Init(testStorage)); - - chip::FabricTable::InitParams initParams; - initParams.storage = testStorage; - initParams.operationalKeystore = opKeyStore; - initParams.opCertStore = opCertStore; - - return fabricTable.Init(initParams); -} CHIP_ERROR InitTestIpk(GroupDataProvider & groupDataProvider, const FabricInfo & fabricInfo, size_t numIpks) { @@ -302,7 +261,7 @@ CHIP_ERROR InitTestIpk(GroupDataProvider & groupDataProvider, const FabricInfo & return groupDataProvider.SetKeySet(fabricInfo.GetFabricIndex(), compressedIdSpan, ipkKeySet); } -CHIP_ERROR TestCASESession::InitCredentialSets() +CHIP_ERROR InitCredentialSets() { gCommissionerStorageDelegate.ClearStorage(); gCommissionerGroupDataProvider.SetStorageDelegate(&gCommissionerStorageDelegate); @@ -374,12 +333,41 @@ CHIP_ERROR TestCASESession::InitCredentialSets() return CHIP_NO_ERROR; } -// Specifically for SimulateUpdateNOCInvalidatePendingEstablishment, we need it to be static so that the class below can -// be a friend to CASESession so that test can get access to CASESession::State and test method that are not public. To -// keep the rest of this file consistent we brought all other tests into this class. +void TestCASESession::SetUpTestSuite() +{ + ConfigInitializeNodes(false); + CHIP_ERROR err = CHIP_NO_ERROR; + LoopbackMessagingContext::SetUpTestSuite(); + + err = chip::DeviceLayer::PlatformMgr().InitChipStack(); + ASSERT_EQ(err, CHIP_NO_ERROR) << "Init CHIP stack failed: " << std::hex << err.Format(); + + err = + InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, &gCommissionerOpCertStore); + ASSERT_EQ(err, CHIP_NO_ERROR) << "InitFabricTable failed: " << std::hex << err.Format(); + + err = InitCredentialSets(); + ASSERT_EQ(err, CHIP_NO_ERROR) << "InitCredentialSets failed: " << std::hex << err.Format(); + + chip::DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); +} + +void TestCASESession::TearDownTestSuite() +{ + chip::DeviceLayer::SetSystemLayerForTesting(nullptr); + gDeviceOperationalKeystore.Shutdown(); + gPairingServer.Shutdown(); + gCommissionerStorageDelegate.ClearStorage(); + gDeviceStorageDelegate.ClearStorage(); + gCommissionerFabrics.DeleteAllFabrics(); + gDeviceFabrics.DeleteAllFabrics(); + chip::DeviceLayer::PlatformMgr().Shutdown(); + LoopbackMessagingContext::TearDownTestSuite(); +} -TEST_F(TestCASESessionWithManager, SecurePairingWaitTest) +TEST_F(TestCASESession, SecurePairingWaitTest) { + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; FabricTable fabrics; @@ -404,8 +392,9 @@ TEST_F(TestCASESessionWithManager, SecurePairingWaitTest) caseSession.Clear(); } -TEST_F(TestCASESessionWithManager, SecurePairingStartTest) +TEST_F(TestCASESession, SecurePairingStartTest) { + TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; CASESession pairing; @@ -508,8 +497,9 @@ void TestCASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionM #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST } -TEST_F(TestCASESessionWithManager, SecurePairingHandshakeTest) +TEST_F(TestCASESession, SecurePairingHandshakeTest) { + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; pairingCommissioner.SetGroupDataProvider(&gCommissionerGroupDataProvider); @@ -569,8 +559,9 @@ TEST_F(TestCASESession, SecurePairingHandshakeServerTest) gPairingServer.Shutdown(); } -TEST_F(TestCASESessionWithManager, ClientReceivesBusyTest) +TEST_F(TestCASESession, ClientReceivesBusyTest) { + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner1, delegateCommissioner2; CASESession pairingCommissioner1, pairingCommissioner2; @@ -1023,10 +1014,12 @@ TEST_F(TestCASESession, SessionResumptionStorage) chip::Platform::Delete(pairingCommissioner); } } +// #endif #if CONFIG_BUILD_FOR_HOST_UNIT_TEST -TEST_F_FROM_FIXTURE(TestCASESessionWithManager, SimulateUpdateNOCInvalidatePendingEstablishment) +TEST_F_FROM_FIXTURE(TestCASESession, SimulateUpdateNOCInvalidatePendingEstablishment) { + TemporarySessionManager sessionManager(*this); TestCASESecurePairingDelegate delegateCommissioner; CASESession pairingCommissioner; pairingCommissioner.SetGroupDataProvider(&gCommissionerGroupDataProvider); @@ -1089,7 +1082,6 @@ TEST_F_FROM_FIXTURE(TestCASESessionWithManager, SimulateUpdateNOCInvalidatePendi } #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST -namespace { class ExpectErrorExchangeDelegate : public ExchangeDelegate { public: @@ -1119,7 +1111,6 @@ class ExpectErrorExchangeDelegate : public ExchangeDelegate uint16_t mExpectedProtocolCode; }; -} // anonymous namespace TEST_F(TestCASESession, Sigma1BadDestinationIdTest) { @@ -1129,7 +1120,7 @@ TEST_F(TestCASESession, Sigma1BadDestinationIdTest) constexpr size_t bufferSize = 600; System::PacketBufferHandle data = chip::System::PacketBufferHandle::New(bufferSize); - EXPECT_FALSE(data.IsNull()); + ASSERT_FALSE(data.IsNull()); MutableByteSpan buf(data->Start(), data->AvailableDataLength()); // This uses a bogus destination id that is not going to match anything in practice. @@ -1152,7 +1143,7 @@ TEST_F(TestCASESession, Sigma1BadDestinationIdTest) ExpectErrorExchangeDelegate delegate(SecureChannel::kProtocolCodeNoSharedRoot); ExchangeContext * exchange = GetExchangeManager().NewContext(session.Value(), &delegate); - EXPECT_NE(exchange, nullptr); + ASSERT_NE(exchange, nullptr); err = exchange->SendMessage(MsgType::CASE_Sigma1, std::move(data), SendMessageFlags::kExpectResponse); EXPECT_EQ(err, CHIP_NO_ERROR); From 500b043524285330b53f5518a539c889f2945adc Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Thu, 16 May 2024 15:38:29 +0200 Subject: [PATCH 06/30] Restore --- .../tests/CheckIn_Message_test_vectors.h | 47 ++++---- .../secure_channel/tests/TestCASESession.cpp | 107 +++++++++--------- 2 files changed, 77 insertions(+), 77 deletions(-) diff --git a/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h b/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h index 5563150ebfee12..67a50f86c84c7a 100644 --- a/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h +++ b/src/protocols/secure_channel/tests/CheckIn_Message_test_vectors.h @@ -143,19 +143,20 @@ const CheckIn_Message_test_vector vector3 = { .key = kKey3, const uint8_t kKey4[] = { 0xca, 0x67, 0xd4, 0x1f, 0xf7, 0x11, 0x29, 0x10, 0xfd, 0xd1, 0x8a, 0x1b, 0xf9, 0x9e, 0xa9, 0x74 }; -const uint8_t kApplicationData4[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, - 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x75, 0x65, 0x72 }; +const uint8_t kApplicationData4[] = { + 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x6c, 0x6f, 0x6e, 0x67, 0x65, 0x72 +}; const uint8_t kNonce4[] = { 0x7a, 0x97, 0x72, 0x24, 0x3c, 0x97, 0xc8, 0x7d, 0x5f, 0x3a, 0x31, 0xc4, 0xe6 }; -const uint8_t kCiphertext4[] = { 0xdb, 0xbc, 0x1a, 0xa5, 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, 0x06, - 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xca, 0x5d, 0xad }; +const uint8_t kCiphertext4[] = { 0xdb, 0xbc, 0x1a, 0xa5, 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, + 0x06, 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xda, 0x4a }; -const uint8_t kMic4[] = { 0x3d, 0x79, 0x78, 0xf7, 0x04, 0xe6, 0x30, 0xac, 0x04, 0x3f, 0xbf, 0xaa, 0x81, 0x25, 0xb2, 0xac }; +const uint8_t kMic4[] = { 0x10, 0x5a, 0x13, 0x42, 0xad, 0xbf, 0x3f, 0x47, 0x98, 0xcd, 0x81, 0xb9, 0xef, 0x97, 0xbb, 0xb7 }; const uint8_t kPayload4[] = { 0x7a, 0x97, 0x72, 0x24, 0x3c, 0x97, 0xc8, 0x7d, 0x5f, 0x3a, 0x31, 0xc4, 0xe6, 0xdb, 0xbc, 0x1a, 0xa5, - 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, 0x06, 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xca, 0x5d, 0xad, - 0x3d, 0x79, 0x78, 0xf7, 0x04, 0xe6, 0x30, 0xac, 0x04, 0x3f, 0xbf, 0xaa, 0x81, 0x25, 0xb2, 0xac }; + 0x66, 0xc4, 0x43, 0xc2, 0x05, 0x86, 0x06, 0x6b, 0x42, 0x7b, 0xfc, 0xaa, 0xad, 0x78, 0xda, 0x4a, 0x10, + 0x5a, 0x13, 0x42, 0xad, 0xbf, 0x3f, 0x47, 0x98, 0xcd, 0x81, 0xb9, 0xef, 0x97, 0xbb, 0xb7 }; const CheckIn_Message_test_vector vector4 = { .key = kKey4, .key_len = sizeof(kKey4), @@ -178,19 +179,19 @@ const CheckIn_Message_test_vector vector4 = { .key = kKey4, const uint8_t kKey5[] = { 0xca, 0x67, 0xd4, 0x1f, 0xf7, 0x11, 0x29, 0x10, 0xfd, 0xd1, 0x8a, 0x1b, 0xf9, 0x9e, 0xa9, 0x74 }; const uint8_t kApplicationData5[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x6c, 0x6f, - 0x6e, 0x67, 0x75, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; + 0x6e, 0x67, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; const uint8_t kNonce5[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8 }; const uint8_t kCiphertext5[] = { 0x2e, 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, 0x51, - 0x7f, 0xf3, 0xc9, 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x5d, 0x18, 0x29, 0x0f, 0xb1, 0x21 }; + 0x7f, 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x31, 0x5a, 0x1e, 0x32, 0x08, 0xb8 }; -const uint8_t kMic5[] = { 0x8b, 0x5d, 0xef, 0x99, 0x65, 0xb4, 0xdc, 0x3a, 0x87, 0x25, 0xc2, 0xeb, 0x2e, 0x18, 0x25, 0x98 }; +const uint8_t kMic5[] = { 0xec, 0xf6, 0x11, 0x8b, 0x02, 0x1a, 0x5a, 0x4c, 0xd4, 0xe9, 0xd4, 0x13, 0x8d, 0xff, 0x29, 0x71 }; -const uint8_t kPayload5[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8, 0x2e, 0x5b, - 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, 0x51, 0x7f, 0xf3, 0xc9, - 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x5d, 0x18, 0x29, 0x0f, 0xb1, 0x21, 0x8b, 0x5d, 0xef, 0x99, - 0x65, 0xb4, 0xdc, 0x3a, 0x87, 0x25, 0xc2, 0xeb, 0x2e, 0x18, 0x25, 0x98 }; +const uint8_t kPayload5[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8, 0x2e, + 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, 0x51, 0x7f, + 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x31, 0x5a, 0x1e, 0x32, 0x08, 0xb8, 0xec, 0xf6, + 0x11, 0x8b, 0x02, 0x1a, 0x5a, 0x4c, 0xd4, 0xe9, 0xd4, 0x13, 0x8d, 0xff, 0x29, 0x71 }; const CheckIn_Message_test_vector vector5 = { .key = kKey5, .key_len = sizeof(kKey5), @@ -216,25 +217,25 @@ const uint8_t kInvalidNonceKey[] = { 0xca, 0x67, 0xd4, 0x1f, 0xf7, 0x11, 0x29, 0x10, 0xfd, 0xd1, 0x8a, 0x1b, 0xf9, 0x9e, 0xa9, 0x74 }; -const uint8_t kInvalidNonceApplicationData[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x6c, - 0x6f, 0x6e, 0x67, 0x75, 0x65, 0x72, 0x20, 0x6c, 0x6f, 0x6e, 0x67, - 0x75, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; +const uint8_t kInvalidNonceApplicationData[] = { 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, + 0x6c, 0x6f, 0x6e, 0x67, 0x65, 0x72, 0x20, 0x6c, 0x6f, 0x6e, + 0x67, 0x65, 0x72, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67 }; const uint8_t kInvalidNonceNonce[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8 }; const uint8_t kInvalidNonceCiphertext[] = { 0x29, 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, - 0x53, 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x42, 0x03, - 0x35, 0x01, 0xaa, 0x23, 0xad, 0x19, 0xcb, 0x6f, 0x5b, 0xee, 0x56, 0xb3 }; + 0x53, 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x2e, 0x41, 0x02, + 0x3c, 0x03, 0xad, 0x66, 0xac, 0x4d, 0xca, 0x72, 0x47, 0xe0 }; const uint8_t kInvalidNonceMic[] = { - 0xd5, 0x8a, 0x92, 0x2b, 0x66, 0x44, 0x89, 0x3e, 0x66, 0x31, 0x8b, 0xb5, 0x53, 0x79, 0x24, 0x8b + 0xe4, 0xc6, 0x6b, 0xd9, 0xd3, 0x99, 0x13, 0xe2, 0x3d, 0x82, 0x32, 0xb9, 0x61, 0xfa, 0x92, 0x26 }; const uint8_t kInvalidNoncePayload[] = { 0x06, 0x34, 0x67, 0x6e, 0xa6, 0xe0, 0x70, 0x7b, 0x7a, 0xd7, 0x81, 0x4f, 0xf8, 0x29, 0x5b, 0x18, 0xd1, 0x9a, 0x23, 0xb2, 0xe4, 0xfa, 0xdf, 0x82, 0x92, 0x53, - 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x9d, 0x50, 0xd6, 0x62, 0x42, 0x03, 0x35, 0x01, - 0xaa, 0x23, 0xad, 0x19, 0xcb, 0x6f, 0x5b, 0xee, 0x56, 0xb3, 0xd5, 0x8a, 0x92, - 0x2b, 0x66, 0x44, 0x89, 0x3e, 0x66, 0x31, 0x8b, 0xb5, 0x53, 0x79, 0x24, 0x8b }; + 0x51, 0x7f, 0xf3, 0xc9, 0x1d, 0x8d, 0x47, 0x84, 0x2e, 0x41, 0x02, 0x3c, 0x03, + 0xad, 0x66, 0xac, 0x4d, 0xca, 0x72, 0x47, 0xe0, 0xe4, 0xc6, 0x6b, 0xd9, 0xd3, + 0x99, 0x13, 0xe2, 0x3d, 0x82, 0x32, 0xb9, 0x61, 0xfa, 0x92, 0x26 }; const CheckIn_Message_test_vector invalidNonceVector = { .key = kInvalidNonceKey, .key_len = sizeof(kInvalidNonceKey), diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 286804df333428..71dbb44bf01858 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -63,8 +63,8 @@ class TestCASESession : public Test::LoopbackMessagingContext, public ::testing: static void SetUpTestSuite(); // Performs shared teardown for all tests in the test suite static void TearDownTestSuite(); - void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } - void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } + virtual void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + virtual void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } void ServiceEvents(); void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, CASESession & pairingCommissioner, @@ -630,57 +630,6 @@ struct Sigma1Params static constexpr bool expectSuccess = true; }; -TEST_F(TestCASESession, DestinationIdTest) -{ - // Validate example test vector from CASE section of spec - - const uint8_t kRootPubKeyFromSpec[Crypto::CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES] = { - 0x04, 0x4a, 0x9f, 0x42, 0xb1, 0xca, 0x48, 0x40, 0xd3, 0x72, 0x92, 0xbb, 0xc7, 0xf6, 0xa7, 0xe1, 0x1e, - 0x22, 0x20, 0x0c, 0x97, 0x6f, 0xc9, 0x00, 0xdb, 0xc9, 0x8a, 0x7a, 0x38, 0x3a, 0x64, 0x1c, 0xb8, 0x25, - 0x4a, 0x2e, 0x56, 0xd4, 0xe2, 0x95, 0xa8, 0x47, 0x94, 0x3b, 0x4e, 0x38, 0x97, 0xc4, 0xa7, 0x73, 0xe9, - 0x30, 0x27, 0x7b, 0x4d, 0x9f, 0xbe, 0xde, 0x8a, 0x05, 0x26, 0x86, 0xbf, 0xac, 0xfa - }; - - const uint8_t kIpkOperationalGroupKeyFromSpec[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES] = { - 0x9b, 0xc6, 0x1c, 0xd9, 0xc6, 0x2a, 0x2d, 0xf6, 0xd6, 0x4d, 0xfc, 0xaa, 0x9d, 0xc4, 0x72, 0xd4 - }; - - const uint8_t kInitiatorRandomFromSpec[Sigma1Params::initiatorRandomLen] = { 0x7e, 0x17, 0x12, 0x31, 0x56, 0x8d, 0xfa, 0x17, - 0x20, 0x6b, 0x3a, 0xcc, 0xf8, 0xfa, 0xec, 0x2f, - 0x4d, 0x21, 0xb5, 0x80, 0x11, 0x31, 0x96, 0xf4, - 0x7c, 0x7c, 0x4d, 0xeb, 0x81, 0x0a, 0x73, 0xdc }; - - const uint8_t kExpectedDestinationIdFromSpec[Crypto::kSHA256_Hash_Length] = { 0xdc, 0x35, 0xdd, 0x5f, 0xc9, 0x13, 0x4c, 0xc5, - 0x54, 0x45, 0x38, 0xc9, 0xc3, 0xfc, 0x42, 0x97, - 0xc1, 0xec, 0x33, 0x70, 0xc8, 0x39, 0x13, 0x6a, - 0x80, 0xe1, 0x07, 0x96, 0x45, 0x1d, 0x4c, 0x53 }; - - const FabricId kFabricIdFromSpec = 0x2906C908D115D362; - const NodeId kNodeIdFromSpec = 0xCD5544AA7B13EF14; - - uint8_t destinationIdBuf[Crypto::kSHA256_Hash_Length] = { 0 }; - MutableByteSpan destinationIdSpan(destinationIdBuf); - - // Test exact example - CHIP_ERROR err = - GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), - ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, kNodeIdFromSpec, destinationIdSpan); - EXPECT_EQ(err, CHIP_NO_ERROR); - EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); - EXPECT_TRUE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); - - memset(destinationIdSpan.data(), 0, destinationIdSpan.size()); - - // Test changing input: should yield different - err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), - ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, - kNodeIdFromSpec + 1, // <--- Change node ID - destinationIdSpan); - EXPECT_EQ(err, CHIP_NO_ERROR); - EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); - EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); -} - template static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) { @@ -918,6 +867,57 @@ struct SessionResumptionTestStorage : SessionResumptionStorage Crypto::P256ECDHDerivedSecret * mSharedSecret = nullptr; }; +TEST_F(TestCASESession, DestinationIdTest) +{ + // Validate example test vector from CASE section of spec + + const uint8_t kRootPubKeyFromSpec[Crypto::CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES] = { + 0x04, 0x4a, 0x9f, 0x42, 0xb1, 0xca, 0x48, 0x40, 0xd3, 0x72, 0x92, 0xbb, 0xc7, 0xf6, 0xa7, 0xe1, 0x1e, + 0x22, 0x20, 0x0c, 0x97, 0x6f, 0xc9, 0x00, 0xdb, 0xc9, 0x8a, 0x7a, 0x38, 0x3a, 0x64, 0x1c, 0xb8, 0x25, + 0x4a, 0x2e, 0x56, 0xd4, 0xe2, 0x95, 0xa8, 0x47, 0x94, 0x3b, 0x4e, 0x38, 0x97, 0xc4, 0xa7, 0x73, 0xe9, + 0x30, 0x27, 0x7b, 0x4d, 0x9f, 0xbe, 0xde, 0x8a, 0x05, 0x26, 0x86, 0xbf, 0xac, 0xfa + }; + + const uint8_t kIpkOperationalGroupKeyFromSpec[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES] = { + 0x9b, 0xc6, 0x1c, 0xd9, 0xc6, 0x2a, 0x2d, 0xf6, 0xd6, 0x4d, 0xfc, 0xaa, 0x9d, 0xc4, 0x72, 0xd4 + }; + + const uint8_t kInitiatorRandomFromSpec[Sigma1Params::initiatorRandomLen] = { 0x7e, 0x17, 0x12, 0x31, 0x56, 0x8d, 0xfa, 0x17, + 0x20, 0x6b, 0x3a, 0xcc, 0xf8, 0xfa, 0xec, 0x2f, + 0x4d, 0x21, 0xb5, 0x80, 0x11, 0x31, 0x96, 0xf4, + 0x7c, 0x7c, 0x4d, 0xeb, 0x81, 0x0a, 0x73, 0xdc }; + + const uint8_t kExpectedDestinationIdFromSpec[Crypto::kSHA256_Hash_Length] = { 0xdc, 0x35, 0xdd, 0x5f, 0xc9, 0x13, 0x4c, 0xc5, + 0x54, 0x45, 0x38, 0xc9, 0xc3, 0xfc, 0x42, 0x97, + 0xc1, 0xec, 0x33, 0x70, 0xc8, 0x39, 0x13, 0x6a, + 0x80, 0xe1, 0x07, 0x96, 0x45, 0x1d, 0x4c, 0x53 }; + + const FabricId kFabricIdFromSpec = 0x2906C908D115D362; + const NodeId kNodeIdFromSpec = 0xCD5544AA7B13EF14; + + uint8_t destinationIdBuf[Crypto::kSHA256_Hash_Length] = { 0 }; + MutableByteSpan destinationIdSpan(destinationIdBuf); + + // Test exact example + CHIP_ERROR err = + GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), + ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, kNodeIdFromSpec, destinationIdSpan); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_TRUE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); + + memset(destinationIdSpan.data(), 0, destinationIdSpan.size()); + + // Test changing input: should yield different + err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), + ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, + kNodeIdFromSpec + 1, // <--- Change node ID + destinationIdSpan); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); +} + TEST_F(TestCASESession, SessionResumptionStorage) { // Test the SessionResumptionStorage external interface. @@ -1015,7 +1015,6 @@ TEST_F(TestCASESession, SessionResumptionStorage) } } // #endif - #if CONFIG_BUILD_FOR_HOST_UNIT_TEST TEST_F_FROM_FIXTURE(TestCASESession, SimulateUpdateNOCInvalidatePendingEstablishment) { From 5b7cf03a95b4922702a34c1ab99004c8a98b32ef Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Thu, 16 May 2024 16:04:56 +0200 Subject: [PATCH 07/30] Move definition of TEST_F_FROM_FIXTURE to UnitTest --- src/system/tests/TestSystemPacketBuffer.cpp | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/system/tests/TestSystemPacketBuffer.cpp b/src/system/tests/TestSystemPacketBuffer.cpp index c71ad542d6225a..6a3a6349325031 100644 --- a/src/system/tests/TestSystemPacketBuffer.cpp +++ b/src/system/tests/TestSystemPacketBuffer.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include @@ -192,16 +193,6 @@ class TestSystemPacketBuffer : public ::testing::Test void CheckSetStart(); }; -/* - * Run fixture's class function as a test. - */ -#define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ - TEST_F(test_fixture, test_name) \ - { \ - test_name(); \ - } \ - void test_fixture::test_name() - /** * Allocate memory for a test buffer and configure according to test buffer configuration. */ From add058f11376a3e985925adbe9fc29c8f8a212ac Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Thu, 16 May 2024 17:12:50 +0200 Subject: [PATCH 08/30] Fix test error --- src/protocols/secure_channel/tests/TestCASESession.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 71dbb44bf01858..771a29a9031ca9 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -1012,6 +1012,7 @@ TEST_F(TestCASESession, SessionResumptionStorage) EXPECT_TRUE(bool(holder)); EXPECT_EQ(holder->GetPeer(), fabricInfo->GetScopedNodeIdForNode(Node01_01)); chip::Platform::Delete(pairingCommissioner); + gPairingServer.Shutdown(); } } // #endif @@ -1157,5 +1158,3 @@ TEST_F(TestCASESession, Sigma1BadDestinationIdTest) } } // namespace chip - -// Test Suite From 5f6fd69c5173f1e371788bf0e43d7ddd5eb804a5 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 07:31:19 +0200 Subject: [PATCH 09/30] Add missing deps --- src/system/tests/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/src/system/tests/BUILD.gn b/src/system/tests/BUILD.gn index 2f2fd4de0a6a6d..3baefdf287c74c 100644 --- a/src/system/tests/BUILD.gn +++ b/src/system/tests/BUILD.gn @@ -46,6 +46,7 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/inet", + "${chip_root}/src/lib/support:pw_tests_wrapper", "${chip_root}/src/platform", "${chip_root}/src/system", ] From 71e6c728185b493f89589eacfee4a77e47e41db5 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 07:35:27 +0200 Subject: [PATCH 10/30] Revert order change --- .../secure_channel/tests/TestCASESession.cpp | 103 +++++++++--------- 1 file changed, 52 insertions(+), 51 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 771a29a9031ca9..02a4da6d466ff4 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -630,6 +630,58 @@ struct Sigma1Params static constexpr bool expectSuccess = true; }; +TEST_F(TestCASESession, DestinationIdTest) +{ + // Validate example test vector from CASE section of spec + + const uint8_t kRootPubKeyFromSpec[Crypto::CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES] = { + 0x04, 0x4a, 0x9f, 0x42, 0xb1, 0xca, 0x48, 0x40, 0xd3, 0x72, 0x92, 0xbb, 0xc7, 0xf6, 0xa7, 0xe1, 0x1e, + 0x22, 0x20, 0x0c, 0x97, 0x6f, 0xc9, 0x00, 0xdb, 0xc9, 0x8a, 0x7a, 0x38, 0x3a, 0x64, 0x1c, 0xb8, 0x25, + 0x4a, 0x2e, 0x56, 0xd4, 0xe2, 0x95, 0xa8, 0x47, 0x94, 0x3b, 0x4e, 0x38, 0x97, 0xc4, 0xa7, 0x73, 0xe9, + 0x30, 0x27, 0x7b, 0x4d, 0x9f, 0xbe, 0xde, 0x8a, 0x05, 0x26, 0x86, 0xbf, 0xac, 0xfa + }; + + const uint8_t kIpkOperationalGroupKeyFromSpec[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES] = { + 0x9b, 0xc6, 0x1c, 0xd9, 0xc6, 0x2a, 0x2d, 0xf6, 0xd6, 0x4d, 0xfc, 0xaa, 0x9d, 0xc4, 0x72, 0xd4 + }; + + const uint8_t kInitiatorRandomFromSpec[Sigma1Params::initiatorRandomLen] = { 0x7e, 0x17, 0x12, 0x31, 0x56, 0x8d, 0xfa, 0x17, + 0x20, 0x6b, 0x3a, 0xcc, 0xf8, 0xfa, 0xec, 0x2f, + 0x4d, 0x21, 0xb5, 0x80, 0x11, 0x31, 0x96, 0xf4, + 0x7c, 0x7c, 0x4d, 0xeb, 0x81, 0x0a, 0x73, 0xdc }; + + const uint8_t kExpectedDestinationIdFromSpec[Crypto::kSHA256_Hash_Length] = { 0xdc, 0x35, 0xdd, 0x5f, 0xc9, 0x13, 0x4c, 0xc5, + 0x54, 0x45, 0x38, 0xc9, 0xc3, 0xfc, 0x42, 0x97, + 0xc1, 0xec, 0x33, 0x70, 0xc8, 0x39, 0x13, 0x6a, + 0x80, 0xe1, 0x07, 0x96, 0x45, 0x1d, 0x4c, 0x53 }; + + const FabricId kFabricIdFromSpec = 0x2906C908D115D362; + const NodeId kNodeIdFromSpec = 0xCD5544AA7B13EF14; + + uint8_t destinationIdBuf[Crypto::kSHA256_Hash_Length] = { 0 }; + MutableByteSpan destinationIdSpan(destinationIdBuf); + + // Test exact example + CHIP_ERROR err = + GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), + ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, kNodeIdFromSpec, destinationIdSpan); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_TRUE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); + + memset(destinationIdSpan.data(), 0, destinationIdSpan.size()); + + // Test changing input: should yield different + err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), + ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, + kNodeIdFromSpec + 1, // <--- Change node ID + destinationIdSpan); + EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); + EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); +} + + template static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) { @@ -867,57 +919,6 @@ struct SessionResumptionTestStorage : SessionResumptionStorage Crypto::P256ECDHDerivedSecret * mSharedSecret = nullptr; }; -TEST_F(TestCASESession, DestinationIdTest) -{ - // Validate example test vector from CASE section of spec - - const uint8_t kRootPubKeyFromSpec[Crypto::CHIP_CRYPTO_PUBLIC_KEY_SIZE_BYTES] = { - 0x04, 0x4a, 0x9f, 0x42, 0xb1, 0xca, 0x48, 0x40, 0xd3, 0x72, 0x92, 0xbb, 0xc7, 0xf6, 0xa7, 0xe1, 0x1e, - 0x22, 0x20, 0x0c, 0x97, 0x6f, 0xc9, 0x00, 0xdb, 0xc9, 0x8a, 0x7a, 0x38, 0x3a, 0x64, 0x1c, 0xb8, 0x25, - 0x4a, 0x2e, 0x56, 0xd4, 0xe2, 0x95, 0xa8, 0x47, 0x94, 0x3b, 0x4e, 0x38, 0x97, 0xc4, 0xa7, 0x73, 0xe9, - 0x30, 0x27, 0x7b, 0x4d, 0x9f, 0xbe, 0xde, 0x8a, 0x05, 0x26, 0x86, 0xbf, 0xac, 0xfa - }; - - const uint8_t kIpkOperationalGroupKeyFromSpec[Crypto::CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES] = { - 0x9b, 0xc6, 0x1c, 0xd9, 0xc6, 0x2a, 0x2d, 0xf6, 0xd6, 0x4d, 0xfc, 0xaa, 0x9d, 0xc4, 0x72, 0xd4 - }; - - const uint8_t kInitiatorRandomFromSpec[Sigma1Params::initiatorRandomLen] = { 0x7e, 0x17, 0x12, 0x31, 0x56, 0x8d, 0xfa, 0x17, - 0x20, 0x6b, 0x3a, 0xcc, 0xf8, 0xfa, 0xec, 0x2f, - 0x4d, 0x21, 0xb5, 0x80, 0x11, 0x31, 0x96, 0xf4, - 0x7c, 0x7c, 0x4d, 0xeb, 0x81, 0x0a, 0x73, 0xdc }; - - const uint8_t kExpectedDestinationIdFromSpec[Crypto::kSHA256_Hash_Length] = { 0xdc, 0x35, 0xdd, 0x5f, 0xc9, 0x13, 0x4c, 0xc5, - 0x54, 0x45, 0x38, 0xc9, 0xc3, 0xfc, 0x42, 0x97, - 0xc1, 0xec, 0x33, 0x70, 0xc8, 0x39, 0x13, 0x6a, - 0x80, 0xe1, 0x07, 0x96, 0x45, 0x1d, 0x4c, 0x53 }; - - const FabricId kFabricIdFromSpec = 0x2906C908D115D362; - const NodeId kNodeIdFromSpec = 0xCD5544AA7B13EF14; - - uint8_t destinationIdBuf[Crypto::kSHA256_Hash_Length] = { 0 }; - MutableByteSpan destinationIdSpan(destinationIdBuf); - - // Test exact example - CHIP_ERROR err = - GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), - ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, kNodeIdFromSpec, destinationIdSpan); - EXPECT_EQ(err, CHIP_NO_ERROR); - EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); - EXPECT_TRUE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); - - memset(destinationIdSpan.data(), 0, destinationIdSpan.size()); - - // Test changing input: should yield different - err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), - ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, - kNodeIdFromSpec + 1, // <--- Change node ID - destinationIdSpan); - EXPECT_EQ(err, CHIP_NO_ERROR); - EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); - EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); -} - TEST_F(TestCASESession, SessionResumptionStorage) { // Test the SessionResumptionStorage external interface. From 99cf0c1de436ceb0eaba5475b7d1b0512e26f95d Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 07:42:56 +0200 Subject: [PATCH 11/30] Restyle --- .../secure_channel/tests/TestCASESession.cpp | 9 ++-- .../secure_channel/tests/TestCheckinMsg.cpp | 44 ++++++++----------- .../TestDefaultSessionResumptionStorage.cpp | 3 +- .../TestSimpleSessionResumptionStorage.cpp | 27 ++++++------ 4 files changed, 38 insertions(+), 45 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 02a4da6d466ff4..b35c9893bbdf24 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -681,7 +681,6 @@ TEST_F(TestCASESession, DestinationIdTest) EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); } - template static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) { @@ -1002,9 +1001,9 @@ TEST_F(TestCASESession, SessionResumptionStorage) CHIP_NO_ERROR); ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(pairingCommissioner); auto establishmentReturnVal = pairingCommissioner->EstablishSession( - GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, - contextCommissioner, &testVectors[i].initiatorStorage, nullptr, &delegateCommissioner, - Optional::Missing()); + GetSecureSessionManager(), &gCommissionerFabrics, ScopedNodeId{ Node01_01, gCommissionerFabricIndex }, + contextCommissioner, &testVectors[i].initiatorStorage, nullptr, &delegateCommissioner, + Optional::Missing()); ServiceEvents(); EXPECT_EQ(establishmentReturnVal, CHIP_NO_ERROR); EXPECT_EQ(loopback.mSentMessageCount, testVectors[i].expectedSentMessageCount); @@ -1016,7 +1015,7 @@ TEST_F(TestCASESession, SessionResumptionStorage) gPairingServer.Shutdown(); } } -// #endif + #if CONFIG_BUILD_FOR_HOST_UNIT_TEST TEST_F_FROM_FIXTURE(TestCASESession, SimulateUpdateNOCInvalidatePendingEstablishment) { diff --git a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp index b33c2ff13e08f0..f819248c4192b1 100644 --- a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp +++ b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp @@ -18,9 +18,9 @@ #include #include +#include #include #include -#include #include #include #include @@ -34,9 +34,7 @@ using namespace chip::Protocols::SecureChannel; using namespace chip::Crypto; using TestSessionKeystoreImpl = Crypto::DefaultSessionKeystore; -namespace chip { -namespace Protocols { -namespace SecureChannel { +namespace { class TestCheckInMsg : public ::testing::Test { @@ -75,7 +73,6 @@ CHIP_ERROR TestCheckInMsg::GenerateAndVerifyPayload(MutableByteSpan & output, co memcpy(hmacKeyMaterial, vector.key, vector.key_len); Aes128KeyHandle aes128KeyHandle; - EXPECT_EQ(keystore.CreateKey(aesKeyMaterial, aes128KeyHandle), CHIP_NO_ERROR); Hmac128KeyHandle hmac128KeyHandle; @@ -237,7 +234,6 @@ TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsTooSmallOutput) // Create output buffer with 0 size MutableByteSpan output; - EXPECT_EQ(CHIP_ERROR_BUFFER_TOO_SMALL, GenerateAndVerifyPayload(output, vector)); } @@ -268,10 +264,10 @@ TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) // Create application data ByteSpan ByteSpan applicationData(vector.application_data, vector.application_data_len); - /* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. - */ +/* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. +*/ #if 0 // Verify that the generation fails with an empty key handle NL_TEST_ASSERT_(inSuite, @@ -310,10 +306,10 @@ TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) // Create application data ByteSpan ByteSpan applicationData(vector.application_data, vector.application_data_len); - /* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. - */ +/* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. +*/ #if 0 // Verify that the generation fails with an empty key handle NL_TEST_ASSERT_(inSuite, @@ -403,10 +399,10 @@ TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) Hmac128KeyHandle hmac128KeyHandle; EXPECT_EQ(keystore.CreateKey(hmacKeyMaterial, hmac128KeyHandle), CHIP_NO_ERROR); - /* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. - */ +/* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. +*/ #if 0 // Verify that the generation fails with an empty key handle EXPECT_EQ( @@ -447,10 +443,10 @@ TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) Aes128KeyHandle aes128KeyHandle; EXPECT_EQ(keystore.CreateKey(aesKeyMaterial, aes128KeyHandle), CHIP_NO_ERROR); - /* - TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. - When using OpenSSL this same test result in a success. - */ +/* + TODO(#28986): Passing an empty key handle while using PSA crypto will result in a failure. + When using OpenSSL this same test result in a success. +*/ #if 0 // Verify that the generation fails with an empty key handle EXPECT_EQ( @@ -525,6 +521,4 @@ TEST_F(TestCheckInMsg, TestCheckInMessagePayloadSizeNullBuffer) EXPECT_EQ(calculated_size, 0u); } -} // namespace SecureChannel -} // namespace Protocols -} // namespace chip +} // namespace diff --git a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp index 236119462ddcb0..59dcf3080a8ec3 100644 --- a/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/tests/TestDefaultSessionResumptionStorage.cpp @@ -15,11 +15,10 @@ * limitations under the License. */ +#include #include #include -#include - // DefaultSessionResumptionStorage is a partial implementation. // Use SimpleSessionResumptionStorage, which extends it, to test. #include diff --git a/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp b/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp index 31b964ec99b1cd..ee107f695542a9 100644 --- a/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp +++ b/src/protocols/secure_channel/tests/TestSimpleSessionResumptionStorage.cpp @@ -32,15 +32,15 @@ TEST(TestSimpleSessionResumptionStorage, TestLink) sessionStorage.Init(&storage); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId; - EXPECT_EQ( chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); - EXPECT_EQ( sessionStorage.SaveLink(resumptionId, chip::ScopedNodeId(node1, fabric1)), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.SaveLink(resumptionId, chip::ScopedNodeId(node1, fabric1)), CHIP_NO_ERROR); chip::ScopedNodeId node; - EXPECT_EQ( sessionStorage.LoadLink(resumptionId, node), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.LoadLink(resumptionId, node), CHIP_NO_ERROR); EXPECT_EQ(node, chip::ScopedNodeId(node1, fabric1)); - EXPECT_EQ( sessionStorage.DeleteLink(resumptionId), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.DeleteLink(resumptionId), CHIP_NO_ERROR); EXPECT_EQ(sessionStorage.LoadLink(resumptionId, node), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } @@ -54,26 +54,27 @@ TEST(TestSimpleSessionResumptionStorage, TestState) chip::ScopedNodeId node(node1, fabric1); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId; - EXPECT_EQ( chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(resumptionId.data(), resumptionId.size()), CHIP_NO_ERROR); chip::Crypto::P256ECDHDerivedSecret sharedSecret; sharedSecret.SetLength(sharedSecret.Capacity()); - EXPECT_EQ( chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); + EXPECT_EQ(chip::Crypto::DRBG_get_bytes(sharedSecret.Bytes(), sharedSecret.Length()), CHIP_NO_ERROR); chip::CATValues peerCATs; - EXPECT_EQ( sessionStorage.SaveState(node, resumptionId, sharedSecret, peerCATs), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.SaveState(node, resumptionId, sharedSecret, peerCATs), CHIP_NO_ERROR); chip::SimpleSessionResumptionStorage::ResumptionIdStorage resumptionId2; chip::Crypto::P256ECDHDerivedSecret sharedSecret2; chip::CATValues peerCATs2; - EXPECT_EQ( sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), CHIP_NO_ERROR); EXPECT_EQ(resumptionId, resumptionId2); EXPECT_EQ(memcmp(sharedSecret.Bytes(), sharedSecret2.Bytes(), sharedSecret.Length()), 0); - EXPECT_EQ( sessionStorage.DeleteState(node), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.DeleteState(node), CHIP_NO_ERROR); - EXPECT_EQ( sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); + EXPECT_EQ(sessionStorage.LoadState(node, resumptionId2, sharedSecret2, peerCATs2), + CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND); } TEST(TestSimpleSessionResumptionStorage, TestIndex) @@ -85,14 +86,14 @@ TEST(TestSimpleSessionResumptionStorage, TestIndex) chip::ScopedNodeId node(node1, fabric1); chip::DefaultSessionResumptionStorage::SessionIndex index0o; - EXPECT_EQ( sessionStorage.LoadIndex(index0o), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.LoadIndex(index0o), CHIP_NO_ERROR); EXPECT_EQ(index0o.mSize, 0u); chip::DefaultSessionResumptionStorage::SessionIndex index1; index1.mSize = 0; - EXPECT_EQ( sessionStorage.SaveIndex(index1), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.SaveIndex(index1), CHIP_NO_ERROR); chip::DefaultSessionResumptionStorage::SessionIndex index1o; - EXPECT_EQ( sessionStorage.LoadIndex(index1o), CHIP_NO_ERROR); + EXPECT_EQ(sessionStorage.LoadIndex(index1o), CHIP_NO_ERROR); EXPECT_EQ(index1o.mSize, 0u); chip::DefaultSessionResumptionStorage::SessionIndex index2; From 192aa023262ebd5684c50c06eea49d5f2110140d Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 07:51:06 +0200 Subject: [PATCH 12/30] Revert --- .../secure_channel/tests/TestCheckinMsg.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp index f819248c4192b1..eda073fe6ab05c 100644 --- a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp +++ b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp @@ -269,11 +269,10 @@ TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) When using OpenSSL this same test result in a success. */ #if 0 - // Verify that the generation fails with an empty key handle - NL_TEST_ASSERT_(inSuite, - CHIP_NO_ERROR != - CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, - applicationData, output)); + // Verify that the generation fails with an empty key handle + EXPECT_NE( + CHIP_NO_ERROR, + CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, applicationData, output)); #endif // Clean up @@ -312,10 +311,9 @@ TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) */ #if 0 // Verify that the generation fails with an empty key handle - NL_TEST_ASSERT_(inSuite, - CHIP_NO_ERROR != - CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, - applicationData, output)); + EXPECT_NE( + CHIP_NO_ERROR, + CheckinMessage::GenerateCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, vector.counter, applicationData, output)); #endif // Clean up From df6771046db5a05d00cb342b9e4182b4756d9520 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 12:03:05 +0200 Subject: [PATCH 13/30] Add missing header --- src/protocols/secure_channel/tests/TestCASESession.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index b35c9893bbdf24..05f583ecdab17a 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -370,7 +371,8 @@ TEST_F(TestCASESession, SecurePairingWaitTest) TemporarySessionManager sessionManager(*this); // Test all combinations of invalid parameters TestCASESecurePairingDelegate delegate; - FabricTable fabrics; + // Making this static to reduce stack usage, as some platforms have limits on stack size. + static FabricTable fabrics; CASESession caseSession; EXPECT_EQ(caseSession.GetSecureSessionType(), SecureSession::Type::kCASE); From dffd7257114c3721e61450909beb004a1c76531a Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 14:26:34 +0200 Subject: [PATCH 14/30] Add UnitTestPigweedUtils --- src/lib/support/BUILD.gn | 10 ++++++++++ src/lib/support/UnitTestPigweedUtils.h | 11 +++++++++++ src/protocols/secure_channel/tests/BUILD.gn | 2 +- .../secure_channel/tests/TestCASESession.cpp | 2 +- src/system/tests/BUILD.gn | 2 +- src/system/tests/TestSystemPacketBuffer.cpp | 2 +- 6 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 src/lib/support/UnitTestPigweedUtils.h diff --git a/src/lib/support/BUILD.gn b/src/lib/support/BUILD.gn index 34906592214fbd..4494f1a6236362 100644 --- a/src/lib/support/BUILD.gn +++ b/src/lib/support/BUILD.gn @@ -341,6 +341,16 @@ static_library("test_utils") { ] } +pw_static_library("pw_test_utils") { + output_name = "libPWTestsUtils" + output_dir = "${root_out_dir}/lib" + public_deps = [ + "$dir_pw_log:impl", + "$dir_pw_unit_test", + ] + sources = [ "UnitTestPigweedUtils.h" ] +} + pw_static_library("pw_tests_wrapper") { if (chip_device_platform == "esp32") { complete_static_lib = true diff --git a/src/lib/support/UnitTestPigweedUtils.h b/src/lib/support/UnitTestPigweedUtils.h new file mode 100644 index 00000000000000..03cbfd2cc912d6 --- /dev/null +++ b/src/lib/support/UnitTestPigweedUtils.h @@ -0,0 +1,11 @@ +#pragma once + +/* + * Run fixture's class function as a test. + */ +#define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ + TEST_F(test_fixture, test_name) \ + { \ + test_name(); \ + } \ + void test_fixture::test_name() diff --git a/src/protocols/secure_channel/tests/BUILD.gn b/src/protocols/secure_channel/tests/BUILD.gn index 0ad5e785a8ca25..7fbb5f9ed79103 100644 --- a/src/protocols/secure_channel/tests/BUILD.gn +++ b/src/protocols/secure_channel/tests/BUILD.gn @@ -29,7 +29,7 @@ chip_test_suite("tests") { "${chip_root}/src/crypto/tests:tests.lib", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", - "${chip_root}/src/lib/support:pw_tests_wrapper", + "${chip_root}/src/lib/support:pw_test_utils", "${chip_root}/src/lib/support:test_utils", "${chip_root}/src/lib/support:testing", "${chip_root}/src/messaging/tests:helpers", diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 05f583ecdab17a..7f29fde5c46b08 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/system/tests/BUILD.gn b/src/system/tests/BUILD.gn index 3baefdf287c74c..d8f1e39dd76a47 100644 --- a/src/system/tests/BUILD.gn +++ b/src/system/tests/BUILD.gn @@ -46,7 +46,7 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/inet", - "${chip_root}/src/lib/support:pw_tests_wrapper", + "${chip_root}/src/lib/support:pw_test_utils", "${chip_root}/src/platform", "${chip_root}/src/system", ] diff --git a/src/system/tests/TestSystemPacketBuffer.cpp b/src/system/tests/TestSystemPacketBuffer.cpp index 6a3a6349325031..d0209b6bb45623 100644 --- a/src/system/tests/TestSystemPacketBuffer.cpp +++ b/src/system/tests/TestSystemPacketBuffer.cpp @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include From 568ab4929aa6bed5322197fe4ba531f6555eb19d Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 14:29:05 +0200 Subject: [PATCH 15/30] IoT SDK update tests list --- src/test_driver/openiotsdk/unit-tests/test_components_nl.txt | 1 - 1 file changed, 1 deletion(-) 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 d57fda14efe12f..d743124194a2ac 100644 --- a/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt +++ b/src/test_driver/openiotsdk/unit-tests/test_components_nl.txt @@ -1,2 +1 @@ AppTests -SecureChannelTestsNL From d7d571b69bb153557636dff3c8aebaba4211dc59 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 14:59:04 +0200 Subject: [PATCH 16/30] Remove unused define --- src/lib/support/UnitTest.h | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/lib/support/UnitTest.h b/src/lib/support/UnitTest.h index 537eaf3784d318..0cf8a8ef75356c 100644 --- a/src/lib/support/UnitTest.h +++ b/src/lib/support/UnitTest.h @@ -1,15 +1,5 @@ #pragma once -/* - * Run fixture's class function as a test. - */ -#define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ - TEST_F(test_fixture, test_name) \ - { \ - test_name(); \ - } \ - void test_fixture::test_name() - namespace chip { namespace test { From ef5c20add940e7d50c8743ee030b7f4e15180596 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 17 May 2024 14:59:19 +0200 Subject: [PATCH 17/30] Change target type --- src/lib/support/BUILD.gn | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib/support/BUILD.gn b/src/lib/support/BUILD.gn index 4494f1a6236362..62999777b09422 100644 --- a/src/lib/support/BUILD.gn +++ b/src/lib/support/BUILD.gn @@ -341,8 +341,7 @@ static_library("test_utils") { ] } -pw_static_library("pw_test_utils") { - output_name = "libPWTestsUtils" +pw_source_set("pw_test_utils") { output_dir = "${root_out_dir}/lib" public_deps = [ "$dir_pw_log:impl", From 467ae6c66f3115fc8623834f3a715a196a36de01 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Tue, 21 May 2024 11:19:08 +0200 Subject: [PATCH 18/30] license --- src/lib/support/UnitTestPigweedUtils.h | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/lib/support/UnitTestPigweedUtils.h b/src/lib/support/UnitTestPigweedUtils.h index 03cbfd2cc912d6..f0c6f1acaa518a 100644 --- a/src/lib/support/UnitTestPigweedUtils.h +++ b/src/lib/support/UnitTestPigweedUtils.h @@ -1,3 +1,20 @@ +/* + * + * Copyright (c) 2024 Project CHIP Authors + * All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ #pragma once /* From 0448aacf588d7ce2e799106ee2d48a92e6b64f06 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Tue, 21 May 2024 11:19:26 +0200 Subject: [PATCH 19/30] Assert --- src/protocols/secure_channel/tests/TestPairingSession.cpp | 2 +- src/protocols/secure_channel/tests/TestStatusReport.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestPairingSession.cpp b/src/protocols/secure_channel/tests/TestPairingSession.cpp index 6a39b63fdd5e14..05e0356519b623 100644 --- a/src/protocols/secure_channel/tests/TestPairingSession.cpp +++ b/src/protocols/secure_channel/tests/TestPairingSession.cpp @@ -43,7 +43,7 @@ class TestPairingSession : public PairingSession, public ::testing::Test { CHIP_ERROR error = chip::Platform::MemoryInit(); - EXPECT_EQ(error, CHIP_NO_ERROR); + ASSERT_EQ(error, CHIP_NO_ERROR); } static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } diff --git a/src/protocols/secure_channel/tests/TestStatusReport.cpp b/src/protocols/secure_channel/tests/TestStatusReport.cpp index 3a1bdc38c7bf91..71900f9d0a645e 100644 --- a/src/protocols/secure_channel/tests/TestStatusReport.cpp +++ b/src/protocols/secure_channel/tests/TestStatusReport.cpp @@ -36,7 +36,7 @@ struct TestStatusReport : public ::testing::Test static void SetUpTestSuite() { CHIP_ERROR error = chip::Platform::MemoryInit(); - EXPECT_EQ(error, CHIP_NO_ERROR); + ASSERT_EQ(error, CHIP_NO_ERROR); } static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } }; From cb4269ac50dc037159326f21e5ab5b701a818df2 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Tue, 21 May 2024 11:19:35 +0200 Subject: [PATCH 20/30] rollback --- .../secure_channel/tests/TestPASESession.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index 0bf45350e9d366..ba4c2ece93c665 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -298,11 +298,14 @@ void SecurePairingHandshakeTestCommon(TestPASESession & ctx, SessionManager & se while (delegate.mMessageDropped) { - auto waitTimeout = 100_ms + CHIP_CONFIG_MRP_RETRY_INTERVAL_SENDER_BOOST; + auto waitTimeout = 100_ms; -#if CHIP_CONFIG_ENABLE_ICD_SERVER == 1 - // If running as an ICD, increase waitTimeout to account for the polling interval - waitTimeout += ICDConfigurationData::GetInstance().GetSlowPollingInterval(); +#if CHIP_CONFIG_ENABLE_ICD_SERVER + // If running as an ICD, increase waitTimeout to account for: + // - longer MRP intervals, configured above to 1s/1s, + // - the fast-polling interval that is added to the MRP backoff time. + waitTimeout += 2000_ms32; + waitTimeout += ICDConfigurationData::GetInstance().GetFastPollingInterval(); #endif // Wait some time so the dropped message will be retransmitted when we drain the IO. From 31dec0e91a3c3f046a47c778d86be24254d7a801 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Tue, 21 May 2024 13:10:50 +0200 Subject: [PATCH 21/30] cleanup --- .../secure_channel/tests/TestCheckinMsg.cpp | 72 ++++++++----------- .../tests/TestMessageCounterManager.cpp | 8 ++- 2 files changed, 33 insertions(+), 47 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp index eda073fe6ab05c..d5885f3a6d06bb 100644 --- a/src/protocols/secure_channel/tests/TestCheckinMsg.cpp +++ b/src/protocols/secure_channel/tests/TestCheckinMsg.cpp @@ -36,23 +36,6 @@ using TestSessionKeystoreImpl = Crypto::DefaultSessionKeystore; namespace { -class TestCheckInMsg : public ::testing::Test -{ -public: - static void SetUpTestSuite() - { - CHIP_ERROR error = chip::Platform::MemoryInit(); - EXPECT_EQ(error, CHIP_NO_ERROR); - } - static void TearDownTestSuite() { chip::Platform::MemoryShutdown(); } - -protected: - static CHIP_ERROR GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Message_test_vector & vector); - - static CHIP_ERROR ParseAndVerifyPayload(MutableByteSpan & applicationData, const CheckIn_Message_test_vector & vector, - bool injectInvalidNonce); -}; - /** * @brief Helper function that generates the Check-In message based on the test vector * and verifies the generated Check-In message @@ -61,7 +44,7 @@ class TestCheckInMsg : public ::testing::Test * @return CHIP_NO_ERROR if the generation was successful * error code if the generation failed - see GenerateCheckinMessagePayload */ -CHIP_ERROR TestCheckInMsg::GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Message_test_vector & vector) +CHIP_ERROR GenerateAndVerifyPayload(MutableByteSpan & output, const CheckIn_Message_test_vector & vector) { TestSessionKeystoreImpl keystore; @@ -128,8 +111,8 @@ CHIP_ERROR TestCheckInMsg::GenerateAndVerifyPayload(MutableByteSpan & output, co * @return CHIP_NO_ERROR if the parsing was successful * error code if the generation failed - see ParseCheckinMessagePayload */ -CHIP_ERROR TestCheckInMsg::ParseAndVerifyPayload(MutableByteSpan & applicationData, const CheckIn_Message_test_vector & vector, - bool injectInvalidNonce) +CHIP_ERROR ParseAndVerifyPayload(MutableByteSpan & applicationData, const CheckIn_Message_test_vector & vector, + bool injectInvalidNonce) { TestSessionKeystoreImpl keystore; @@ -189,7 +172,7 @@ CHIP_ERROR TestCheckInMsg::ParseAndVerifyPayload(MutableByteSpan & applicationDa /** * @brief Test verifies that the Check-In message generation is successful when using an output size equal to the payload size */ -TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsSameSizeOutputAsPayload) +TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsSameSizeOutputAsPayload) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -210,7 +193,7 @@ TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsSameSizeOutputAsPay /** * @brief Test verifies that the Check-In message generation is successful when using an output size greater than the payload size */ -TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsBiggerSizeOutput) +TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsBiggerSizeOutput) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -228,19 +211,19 @@ TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsBiggerSizeOutput) /** * @brief Test verifies that the Check-In message generation returns an error if the output buffer is too small */ -TEST_F(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsTooSmallOutput) +TEST(TestCheckInMsg, TestCheckinMessageGenerate_ValidInputsTooSmallOutput) { CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; // Create output buffer with 0 size MutableByteSpan output; - EXPECT_EQ(CHIP_ERROR_BUFFER_TOO_SMALL, GenerateAndVerifyPayload(output, vector)); + EXPECT_EQ(GenerateAndVerifyPayload(output, vector), CHIP_ERROR_BUFFER_TOO_SMALL); } /** * @brief Test verifies that the Check-In Message generations returns an error if the AesKeyHandle is empty */ -TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) +TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -282,7 +265,7 @@ TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyAesKeyHandle) /** * @brief Test verifies that the Check-In Message generations returns an error if the HmacKeyHandle is empty */ -TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) +TEST(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -323,7 +306,7 @@ TEST_F(TestCheckInMsg, TestCheckInMessageGenerate_EmptyHmacKeyHandle) /** * @brief Test verifies that the Check-In message parsing succeeds with the Application buffer set to the minimum required size */ -TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsSameSizeMinAppData) +TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsSameSizeMinAppData) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -341,7 +324,7 @@ TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsSameSizeMinAppData) /** * @brief Test verifies that the Check-In message parsing succeeds with the Application buffer set to a larger than necessary size */ -TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsBiggerSizeMinAppData) +TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsBiggerSizeMinAppData) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -358,20 +341,20 @@ TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsBiggerSizeMinAppData) /** * @brief Test verifies that the Check-In message throws an error if the application data buffer is too small */ -TEST_F(TestCheckInMsg, TestCheckinMessageParse_ValidInputsTooSmallAppData) +TEST(TestCheckInMsg, TestCheckinMessageParse_ValidInputsTooSmallAppData) { CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; // Create applicationData buffer with 0 size MutableByteSpan applicationData; - EXPECT_EQ(CHIP_ERROR_BUFFER_TOO_SMALL, ParseAndVerifyPayload(applicationData, vector, false)); + EXPECT_EQ(ParseAndVerifyPayload(applicationData, vector, false), CHIP_ERROR_BUFFER_TOO_SMALL); } /** * @brief Test verifies that the Check-In Message parsing returns an error if the AesKeyHandle is empty */ -TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) +TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -403,9 +386,9 @@ TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) */ #if 0 // Verify that the generation fails with an empty key handle - EXPECT_EQ( - CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData), - CHIP_NO_ERROR); + EXPECT_NE( + CHIP_NO_ERROR, + CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData)); #endif // Clean up @@ -415,7 +398,7 @@ TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyAesKeyHandle) /** * @brief Test verifies that the Check-In Message parsing returns an error if the HmacKeyHandle is empty */ -TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) +TEST(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) { TestSessionKeystoreImpl keystore; CheckIn_Message_test_vector vector = checkIn_message_test_vectors[0]; @@ -447,9 +430,9 @@ TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) */ #if 0 // Verify that the generation fails with an empty key handle - EXPECT_EQ( - CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData), - CHIP_NO_ERROR); + EXPECT_NE( + CHIP_NO_ERROR, + CheckinMessage::ParseCheckinMessagePayload(aes128KeyHandle, hmac128KeyHandle, payload, decryptedCounter, applicationData)); #endif // Clean up @@ -459,7 +442,7 @@ TEST_F(TestCheckInMsg, TestCheckInMessageParse_EmptyHmacKeyHandle) /** * @brief Test verifies that the Check-In message processing throws an error if the nonce is corrupted */ -TEST_F(TestCheckInMsg, TestCheckinMessageParse_CorruptedNonce) +TEST(TestCheckInMsg, TestCheckinMessageParse_CorruptedNonce) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -478,7 +461,7 @@ TEST_F(TestCheckInMsg, TestCheckinMessageParse_CorruptedNonce) * @brief Test verifies that the Check-In message processing throws an error if the nonce was not calculated with the counter in the * payload */ -TEST_F(TestCheckInMsg, TestCheckinMessageParse_InvalidNonce) +TEST(TestCheckInMsg, TestCheckinMessageParse_InvalidNonce) { CheckIn_Message_test_vector vector = invalidNonceVector; @@ -486,13 +469,13 @@ TEST_F(TestCheckInMsg, TestCheckinMessageParse_InvalidNonce) MutableByteSpan applicationData(applicationDataBuffer, sizeof(applicationDataBuffer)); applicationData.reduce_size(vector.application_data_len + sizeof(CounterType)); - EXPECT_EQ(ParseAndVerifyPayload(applicationData, vector, false), CHIP_ERROR_INTERNAL); + EXPECT_EQ(ParseAndVerifyPayload(applicationData, vector, true), CHIP_ERROR_INTERNAL); } /** * @brief test verifies that GetAppDataSize returns the correct application data size */ -TEST_F(TestCheckInMsg, TestCheckInMessagePayloadSize) +TEST(TestCheckInMsg, TestCheckInMessagePayloadSize) { int numOfTestCases = ArraySize(checkIn_message_test_vectors); for (int numOfTestsExecuted = 0; numOfTestsExecuted < numOfTestCases; numOfTestsExecuted++) @@ -510,13 +493,14 @@ TEST_F(TestCheckInMsg, TestCheckInMessagePayloadSize) /** * @brief test verifies that GetAppDataSize returns 0 if the payload is smaller that the minimum size */ -TEST_F(TestCheckInMsg, TestCheckInMessagePayloadSizeNullBuffer) +TEST(TestCheckInMsg, TestCheckInMessagePayloadSizeNullBuffer) { ByteSpan payload; size_t calculated_size = CheckinMessage::GetAppDataSize(payload); + size_t expected_size = 0; // Verify that the size is 0 - EXPECT_EQ(calculated_size, 0u); + EXPECT_EQ(calculated_size, expected_size); } } // namespace diff --git a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp index 3e5ce9d33121ed..c1fdf885a27393 100644 --- a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp +++ b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp @@ -23,7 +23,6 @@ #include #include -#include #include #include @@ -67,8 +66,11 @@ class MockAppDelegate : public ExchangeDelegate struct TestMessageCounterManager : public chip::Test::LoopbackMessagingContext, public ::testing::Test { - static void SetUpTestSuite() { EXPECT_EQ(chip::Test::LoopbackTransportManager::Init(), CHIP_NO_ERROR); } - static void TearDownTestSuite() { chip::Test::LoopbackTransportManager::Shutdown(); } + static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } + static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } + + void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } }; TEST_F(TestMessageCounterManager, MessageCounterSyncProcess) From 4e1be2de0590d96e84e21441d9b8962c0ff85ec5 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Tue, 21 May 2024 13:19:09 +0200 Subject: [PATCH 22/30] Change function to method --- .../secure_channel/tests/TestPASESession.cpp | 45 ++++++++++--------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index ba4c2ece93c665..98a5106f53bd11 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -83,6 +83,7 @@ constexpr Spake2pVerifierSerialized sTestSpake2p01_SerializedVerifier = { 0xB7, 0xC0, 0x7F, 0xCC, 0x06, 0x27, 0xA1, 0xB8, 0x57, 0x3A, 0x14, 0x9F, 0xCD, 0x1F, 0xA4, 0x66, 0xCF }; +class TestSecurePairingDelegate; class TestPASESession : public chip::Test::LoopbackMessagingContext, public ::testing::Test { public: @@ -97,6 +98,11 @@ class TestPASESession : public chip::Test::LoopbackMessagingContext, public ::te void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } + + void SecurePairingHandshakeTestCommon(SessionManager & sessionManager, PASESession & pairingCommissioner, + Optional mrpCommissionerConfig, + Optional mrpAccessoryConfig, + TestSecurePairingDelegate & delegateCommissioner); }; class PASETestLoopbackTransportDelegate : public Test::LoopbackTransportDelegate @@ -242,25 +248,25 @@ TEST_F(TestPASESession, SecurePairingStartTest) loopback.mMessageSendError = CHIP_NO_ERROR; } -void SecurePairingHandshakeTestCommon(TestPASESession & ctx, SessionManager & sessionManager, PASESession & pairingCommissioner, - Optional mrpCommissionerConfig, - Optional mrpAccessoryConfig, - TestSecurePairingDelegate & delegateCommissioner) +void TestPASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionManager, PASESession & pairingCommissioner, + Optional mrpCommissionerConfig, + Optional mrpAccessoryConfig, + TestSecurePairingDelegate & delegateCommissioner) { TestSecurePairingDelegate delegateAccessory; PASESession pairingAccessory; PASETestLoopbackTransportDelegate delegate; - auto & loopback = ctx.GetLoopback(); + auto & loopback = GetLoopback(); loopback.SetLoopbackTransportDelegate(&delegate); loopback.mSentMessageCount = 0; - ExchangeContext * contextCommissioner = ctx.NewUnauthenticatedExchangeToBob(&pairingCommissioner); + ExchangeContext * contextCommissioner = NewUnauthenticatedExchangeToBob(&pairingCommissioner); if (loopback.mNumMessagesToDrop != 0) { - ReliableMessageMgr * rm = ctx.GetExchangeManager().GetReliableMessageMgr(); + ReliableMessageMgr * rm = GetExchangeManager().GetReliableMessageMgr(); ReliableMessageContext * rc = contextCommissioner->GetReliableMessageContext(); ASSERT_NE(rm, nullptr); ASSERT_NE(rc, nullptr); @@ -282,19 +288,19 @@ void SecurePairingHandshakeTestCommon(TestPASESession & ctx, SessionManager & se #endif // CHIP_CONFIG_ENABLE_ICD_SERVER } - EXPECT_EQ(ctx.GetExchangeManager().RegisterUnsolicitedMessageHandlerForType( - Protocols::SecureChannel::MsgType::PBKDFParamRequest, &pairingAccessory), + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(Protocols::SecureChannel::MsgType::PBKDFParamRequest, + &pairingAccessory), CHIP_NO_ERROR); EXPECT_EQ(pairingAccessory.WaitForPairing(sessionManager, sTestSpake2p01_PASEVerifier, sTestSpake2p01_IterationCount, ByteSpan(sTestSpake2p01_Salt), mrpAccessoryConfig, &delegateAccessory), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + DrainAndServiceIO(); EXPECT_EQ(pairingCommissioner.Pair(sessionManager, sTestSpake2p01_PinCode, mrpCommissionerConfig, contextCommissioner, &delegateCommissioner), CHIP_NO_ERROR); - ctx.DrainAndServiceIO(); + DrainAndServiceIO(); while (delegate.mMessageDropped) { @@ -311,8 +317,8 @@ void SecurePairingHandshakeTestCommon(TestPASESession & ctx, SessionManager & se // Wait some time so the dropped message will be retransmitted when we drain the IO. chip::test_utils::SleepMillis(waitTimeout.count()); delegate.mMessageDropped = false; - ReliableMessageMgr::Timeout(&ctx.GetSystemLayer(), ctx.GetExchangeManager().GetReliableMessageMgr()); - ctx.DrainAndServiceIO(); + ReliableMessageMgr::Timeout(&GetSystemLayer(), GetExchangeManager().GetReliableMessageMgr()); + DrainAndServiceIO(); }; // Standalone acks also increment the mSentMessageCount. But some messages could be acked @@ -350,7 +356,7 @@ void SecurePairingHandshakeTestCommon(TestPASESession & ctx, SessionManager & se // that notification is what would delete the PASESession, but in our case // that will happen as soon as things come off the stack. So make sure to // process the async bits before that happens. - ctx.DrainAndServiceIO(); + DrainAndServiceIO(); // And check that this did not result in any new notifications. EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); @@ -369,7 +375,7 @@ TEST_F(TestPASESession, SecurePairingHandshakeTest) PASESession pairingCommissioner; auto & loopback = GetLoopback(); loopback.Reset(); - SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Missing(), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Missing(), Optional::Missing(), delegateCommissioner); } @@ -382,8 +388,7 @@ TEST_F(TestPASESession, SecurePairingHandshakeWithCommissionerMRPTest) auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig config(1000_ms32, 10000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, - Optional::Value(config), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Value(config), Optional::Missing(), delegateCommissioner); } @@ -396,7 +401,7 @@ TEST_F(TestPASESession, SecurePairingHandshakeWithDeviceMRPTest) auto & loopback = GetLoopback(); loopback.Reset(); ReliableMessageProtocolConfig config(1000_ms32, 10000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Missing(), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Missing(), Optional::Value(config), delegateCommissioner); } @@ -410,7 +415,7 @@ TEST_F(TestPASESession, SecurePairingHandshakeWithAllMRPTest) loopback.Reset(); ReliableMessageProtocolConfig commissionerConfig(1000_ms32, 10000_ms32, 4000_ms16); ReliableMessageProtocolConfig deviceConfig(2000_ms32, 7000_ms32, 4000_ms16); - SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Value(commissionerConfig), Optional::Value(deviceConfig), delegateCommissioner); } @@ -424,7 +429,7 @@ TEST_F(TestPASESession, SecurePairingHandshakeWithPacketLossTest) auto & loopback = GetLoopback(); loopback.Reset(); loopback.mNumMessagesToDrop = 2; - SecurePairingHandshakeTestCommon(*this, sessionManager, pairingCommissioner, Optional::Missing(), + SecurePairingHandshakeTestCommon(sessionManager, pairingCommissioner, Optional::Missing(), Optional::Missing(), delegateCommissioner); EXPECT_EQ(loopback.mDroppedMessageCount, 2u); EXPECT_EQ(loopback.mNumMessagesToDrop, 0u); From 9cced42a6670a583ca55419606d804d959950907 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Tue, 21 May 2024 13:23:30 +0200 Subject: [PATCH 23/30] Restyle --- src/protocols/secure_channel/tests/TestPairingSession.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/protocols/secure_channel/tests/TestPairingSession.cpp b/src/protocols/secure_channel/tests/TestPairingSession.cpp index 05e0356519b623..5a12f61fc5c69e 100644 --- a/src/protocols/secure_channel/tests/TestPairingSession.cpp +++ b/src/protocols/secure_channel/tests/TestPairingSession.cpp @@ -41,7 +41,6 @@ class TestPairingSession : public PairingSession, public ::testing::Test public: static void SetUpTestSuite() { - CHIP_ERROR error = chip::Platform::MemoryInit(); ASSERT_EQ(error, CHIP_NO_ERROR); } From 00f8f735d632eb259b3597d63cb8df36bd19b86e Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Thu, 23 May 2024 16:24:40 +0200 Subject: [PATCH 24/30] Fix dependency between tests --- src/messaging/tests/MessagingContext.cpp | 4 +--- src/messaging/tests/MessagingContext.h | 4 ++-- src/protocols/secure_channel/tests/TestCASESession.cpp | 9 ++++++++- src/protocols/secure_channel/tests/TestPASESession.cpp | 9 +++++++-- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/messaging/tests/MessagingContext.cpp b/src/messaging/tests/MessagingContext.cpp index 61565da1cd4ac0..909bc90f443575 100644 --- a/src/messaging/tests/MessagingContext.cpp +++ b/src/messaging/tests/MessagingContext.cpp @@ -58,7 +58,7 @@ CHIP_ERROR MessagingContext::Init(TransportMgrBase * transport, IOContext * ioCo ReturnErrorOnFailure(mExchangeManager.Init(&mSessionManager)); ReturnErrorOnFailure(mMessageCounterManager.Init(&mExchangeManager)); - if (sInitializeNodes) + if (mInitializeNodes) { ReturnErrorOnFailure(CreateAliceFabric()); ReturnErrorOnFailure(CreateBobFabric()); @@ -112,8 +112,6 @@ using namespace System::Clock::Literals; constexpr chip::System::Clock::Timeout MessagingContext::kResponsiveIdleRetransTimeout; constexpr chip::System::Clock::Timeout MessagingContext::kResponsiveActiveRetransTimeout; -bool MessagingContext::sInitializeNodes = true; - void MessagingContext::SetMRPMode(MRPMode mode) { if (mode == MRPMode::kDefault) diff --git a/src/messaging/tests/MessagingContext.h b/src/messaging/tests/MessagingContext.h index bd9b0b981926e6..51525f967d1475 100644 --- a/src/messaging/tests/MessagingContext.h +++ b/src/messaging/tests/MessagingContext.h @@ -101,7 +101,7 @@ class MessagingContext : public PlatformMemoryUser ~MessagingContext() { VerifyOrDie(mInitialized == false); } // Whether Alice and Bob are initialized, must be called before Init - static void ConfigInitializeNodes(bool initializeNodes) { sInitializeNodes = initializeNodes; } + void ConfigInitializeNodes(bool initializeNodes) { mInitializeNodes = initializeNodes; } /// Initialize the underlying layers and test suite pointer CHIP_ERROR Init(TransportMgrBase * transport, IOContext * io); @@ -178,7 +178,7 @@ class MessagingContext : public PlatformMemoryUser System::Layer & GetSystemLayer() { return mIOContext->GetSystemLayer(); } private: - static bool sInitializeNodes; + bool mInitializeNodes = true; bool mInitialized; FabricTable mFabricTable; diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 5fc6a37f72f4ab..266d0b0a31c8dc 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -64,6 +64,14 @@ class TestContext : public Test::LoopbackMessagingContext static void SetUpTestSuite(); // Performs shared teardown for all tests in the test suite static void TearDownTestSuite(); + + virtual void SetUp() override + { + ConfigInitializeNodes(false); + chip::Test::LoopbackMessagingContext::SetUp(); + } + virtual void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } + }; void ServiceEvents(TestContext & ctx) @@ -329,7 +337,6 @@ CHIP_ERROR InitCredentialSets() void TestContext::SetUpTestSuite() { - ConfigInitializeNodes(false); CHIP_ERROR err = CHIP_NO_ERROR; LoopbackMessagingContext::SetUpTestSuite(); // TODO: use ASSERT_EQ, once transition to pw_unit_test is complete diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index d610b304cec481..896f721579334d 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -89,11 +89,16 @@ class TestContext : public chip::Test::LoopbackMessagingContext { public: // Performs shared setup for all tests in the test suite - static void SetUpTestSuite() + static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } + static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } + + void SetUp() override { ConfigInitializeNodes(false); - chip::Test::LoopbackMessagingContext::SetUpTestSuite(); + chip::Test::LoopbackMessagingContext::SetUp(); } + + void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } }; class PASETestLoopbackTransportDelegate : public Test::LoopbackTransportDelegate From 71bc5b7275d1a4809ae0f3b448dfb6d2fe8e34c1 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 24 May 2024 13:20:57 +0200 Subject: [PATCH 25/30] Fix merge --- src/protocols/secure_channel/tests/TestPASESession.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index bfaabafa6f3aa0..232608de11b46c 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -91,13 +91,6 @@ class TestPASESession : public chip::Test::LoopbackMessagingContext, public ::te static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - void SetUp() override - { - ConfigInitializeNodes(false); - chip::Test::LoopbackMessagingContext::SetUp(); - } - static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } From fb3758ff325c36981f94045eb4d2feae4b7f7b9d Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Fri, 24 May 2024 13:32:52 +0200 Subject: [PATCH 26/30] Fix --- src/protocols/secure_channel/tests/TestCASESession.cpp | 8 +++++++- src/protocols/secure_channel/tests/TestPASESession.cpp | 6 +++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index 1c0373804125f4..bd5a47d1c0311c 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -64,7 +64,13 @@ class TestCASESession : public Test::LoopbackMessagingContext, public ::testing: static void SetUpTestSuite(); // Performs shared teardown for all tests in the test suite static void TearDownTestSuite(); - virtual void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + + virtual void SetUp() override + { + ConfigInitializeNodes(false); + chip::Test::LoopbackMessagingContext::SetUp(); + } + virtual void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } void ServiceEvents(); diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index 232608de11b46c..34ba8e58b0abd0 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -91,7 +91,11 @@ class TestPASESession : public chip::Test::LoopbackMessagingContext, public ::te static void SetUpTestSuite() { chip::Test::LoopbackMessagingContext::SetUpTestSuite(); } static void TearDownTestSuite() { chip::Test::LoopbackMessagingContext::TearDownTestSuite(); } - void SetUp() override { chip::Test::LoopbackMessagingContext::SetUp(); } + void SetUp() override + { + ConfigInitializeNodes(false); + chip::Test::LoopbackMessagingContext::SetUp(); + } void TearDown() override { chip::Test::LoopbackMessagingContext::TearDown(); } From 7f203fca6783d9b8683c4c857ca0343020abe123 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Mon, 27 May 2024 10:25:47 +0200 Subject: [PATCH 27/30] Review fix --- src/lib/support/BUILD.gn | 9 ---- src/lib/support/tests/BUILD.gn | 9 ++++ .../ExtraPwTestMacros.h} | 30 ++++++++++- src/protocols/secure_channel/tests/BUILD.gn | 2 +- .../secure_channel/tests/TestCASESession.cpp | 53 ++++++++----------- .../tests/TestCheckInCounter.cpp | 2 - .../tests/TestMessageCounterManager.cpp | 13 ++--- .../secure_channel/tests/TestStatusReport.cpp | 9 ++-- src/system/tests/BUILD.gn | 2 +- src/system/tests/TestSystemPacketBuffer.cpp | 2 +- 10 files changed, 70 insertions(+), 61 deletions(-) rename src/lib/support/{UnitTestPigweedUtils.h => tests/ExtraPwTestMacros.h} (64%) diff --git a/src/lib/support/BUILD.gn b/src/lib/support/BUILD.gn index 62999777b09422..34906592214fbd 100644 --- a/src/lib/support/BUILD.gn +++ b/src/lib/support/BUILD.gn @@ -341,15 +341,6 @@ static_library("test_utils") { ] } -pw_source_set("pw_test_utils") { - output_dir = "${root_out_dir}/lib" - public_deps = [ - "$dir_pw_log:impl", - "$dir_pw_unit_test", - ] - sources = [ "UnitTestPigweedUtils.h" ] -} - pw_static_library("pw_tests_wrapper") { if (chip_device_platform == "esp32") { complete_static_lib = true diff --git a/src/lib/support/tests/BUILD.gn b/src/lib/support/tests/BUILD.gn index 565eb85097d133..b8cdcfeb2e059f 100644 --- a/src/lib/support/tests/BUILD.gn +++ b/src/lib/support/tests/BUILD.gn @@ -19,6 +19,15 @@ import("//build_overrides/pigweed.gni") import("${chip_root}/build/chip/chip_test_suite.gni") +pw_source_set("pw-test-macros") { + output_dir = "${root_out_dir}/lib" + public_deps = [ + "$dir_pw_log:impl", + "$dir_pw_unit_test", + ] + sources = [ "ExtraPwTestMacros.h" ] +} + chip_test_suite("tests") { output_name = "libSupportTests" diff --git a/src/lib/support/UnitTestPigweedUtils.h b/src/lib/support/tests/ExtraPwTestMacros.h similarity index 64% rename from src/lib/support/UnitTestPigweedUtils.h rename to src/lib/support/tests/ExtraPwTestMacros.h index f0c6f1acaa518a..871e0b6a283297 100644 --- a/src/lib/support/UnitTestPigweedUtils.h +++ b/src/lib/support/tests/ExtraPwTestMacros.h @@ -18,7 +18,35 @@ #pragma once /* - * Run fixture's class function as a test. + * Run Fixture's class function as a test. + * It is used to execute test cases that need to use private members of a particular class. + * Unlike the pigweed macro `FRIEND_TEST`, this approach allows you to define the entire + * test_fixture class as a friend, rather than having to define each testcase as a friend. + * + * @param test_fixture - the fixture class. + * + * @param test_name - the name of the test function. + * + * Example: + * class Foo // class to be tested + * { + * friend class TestCtx; + * private: + * bool privateFunction(); + * }; + * + * class TestCtx: public ::testing::Test + * { + * public: + * void testFunction(); + * }; + * + * TEST_F_FROM_FIXTURE(TestClass, testFunction) + * { + * Foo foo; + * EXPECT_TRUE(foo.privateFunction()); + * } + * */ #define TEST_F_FROM_FIXTURE(test_fixture, test_name) \ TEST_F(test_fixture, test_name) \ diff --git a/src/protocols/secure_channel/tests/BUILD.gn b/src/protocols/secure_channel/tests/BUILD.gn index 7fbb5f9ed79103..0760998e818422 100644 --- a/src/protocols/secure_channel/tests/BUILD.gn +++ b/src/protocols/secure_channel/tests/BUILD.gn @@ -29,9 +29,9 @@ chip_test_suite("tests") { "${chip_root}/src/crypto/tests:tests.lib", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", - "${chip_root}/src/lib/support:pw_test_utils", "${chip_root}/src/lib/support:test_utils", "${chip_root}/src/lib/support:testing", + "${chip_root}/src/lib/support/tests:pw-test-macros", "${chip_root}/src/messaging/tests:helpers", "${chip_root}/src/protocols", "${chip_root}/src/protocols/secure_channel", diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index bd5a47d1c0311c..f4cc1ba53e4607 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -27,7 +27,6 @@ #include #include #include -#include #include #include #include @@ -36,7 +35,7 @@ #include #include #include -#include +#include #include #include #include @@ -342,18 +341,15 @@ CHIP_ERROR InitCredentialSets() void TestCASESession::SetUpTestSuite() { - CHIP_ERROR err = CHIP_NO_ERROR; LoopbackMessagingContext::SetUpTestSuite(); - err = chip::DeviceLayer::PlatformMgr().InitChipStack(); - ASSERT_EQ(err, CHIP_NO_ERROR) << "Init CHIP stack failed: " << std::hex << err.Format(); + ASSERT_EQ(chip::DeviceLayer::PlatformMgr().InitChipStack(), CHIP_NO_ERROR); - err = - InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, &gCommissionerOpCertStore); - ASSERT_EQ(err, CHIP_NO_ERROR) << "InitFabricTable failed: " << std::hex << err.Format(); + ASSERT_EQ( + InitFabricTable(gCommissionerFabrics, &gCommissionerStorageDelegate, /* opKeyStore = */ nullptr, &gCommissionerOpCertStore), + CHIP_NO_ERROR); - err = InitCredentialSets(); - ASSERT_EQ(err, CHIP_NO_ERROR) << "InitCredentialSets failed: " << std::hex << err.Format(); + ASSERT_EQ(InitCredentialSets(), CHIP_NO_ERROR); chip::DeviceLayer::SetSystemLayerForTesting(&GetSystemLayer()); } @@ -679,11 +675,11 @@ TEST_F(TestCASESession, DestinationIdTest) memset(destinationIdSpan.data(), 0, destinationIdSpan.size()); // Test changing input: should yield different - err = GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), - ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, - kNodeIdFromSpec + 1, // <--- Change node ID - destinationIdSpan); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(GenerateCaseDestinationId(ByteSpan(kIpkOperationalGroupKeyFromSpec), ByteSpan(kInitiatorRandomFromSpec), + ByteSpan(kRootPubKeyFromSpec), kFabricIdFromSpec, + kNodeIdFromSpec + 1, // <--- Change node ID + destinationIdSpan), + CHIP_NO_ERROR); EXPECT_EQ(destinationIdSpan.size(), sizeof(destinationIdBuf)); EXPECT_FALSE(destinationIdSpan.data_equal(ByteSpan(kExpectedDestinationIdFromSpec))); } @@ -744,8 +740,7 @@ static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) do \ { \ MutableByteSpan buf(mem.Get(), bufferSize); \ - CHIP_ERROR err = EncodeSigma1(buf); \ - EXPECT_EQ(err, CHIP_NO_ERROR); \ + EXPECT_EQ(EncodeSigma1(buf), CHIP_NO_ERROR); \ \ TLV::ContiguousBufferTLVReader reader; \ reader.Init(buf); \ @@ -758,9 +753,9 @@ static CHIP_ERROR EncodeSigma1(MutableByteSpan & buf) ByteSpan resumptionId; \ ByteSpan initiatorResumeMIC; \ CASESession session; \ - err = session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, \ - resumptionRequested, resumptionId, initiatorResumeMIC); \ - EXPECT_EQ(err == CHIP_NO_ERROR, params::expectSuccess); \ + EXPECT_EQ(session.ParseSigma1(reader, initiatorRandom, initiatorSessionId, destinationId, initiatorEphPubKey, \ + resumptionRequested, resumptionId, initiatorResumeMIC) == CHIP_NO_ERROR, \ + params::expectSuccess); \ if (params::expectSuccess) \ { \ EXPECT_EQ(resumptionRequested, params::resumptionIdLen != 0 && params::initiatorResumeMICLen != 0); \ @@ -1103,8 +1098,7 @@ class ExpectErrorExchangeDelegate : public ExchangeDelegate EXPECT_TRUE(payloadHeader.HasMessageType(MsgType::StatusReport)); SecureChannel::StatusReport statusReport; - CHIP_ERROR err = statusReport.Parse(std::move(buf)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(statusReport.Parse(std::move(buf)), CHIP_NO_ERROR); EXPECT_EQ(statusReport.GetProtocolId(), SecureChannel::Id); EXPECT_EQ(statusReport.GetGeneralCode(), GeneralStatusCode::kFailure); @@ -1131,8 +1125,7 @@ TEST_F(TestCASESession, Sigma1BadDestinationIdTest) MutableByteSpan buf(data->Start(), data->AvailableDataLength()); // This uses a bogus destination id that is not going to match anything in practice. - CHIP_ERROR err = EncodeSigma1(buf); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(EncodeSigma1(buf), CHIP_NO_ERROR); data->SetDataLength(static_cast(buf.size())); Optional session = sessionManager.CreateUnauthenticatedSession(GetAliceAddress(), GetDefaultMRPConfig()); @@ -1141,19 +1134,17 @@ TEST_F(TestCASESession, Sigma1BadDestinationIdTest) TestCASESecurePairingDelegate caseDelegate; CASESession caseSession; caseSession.SetGroupDataProvider(&gDeviceGroupDataProvider); - err = caseSession.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &caseDelegate, - ScopedNodeId(), NullOptional); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(caseSession.PrepareForSessionEstablishment(sessionManager, &gDeviceFabrics, nullptr, nullptr, &caseDelegate, + ScopedNodeId(), NullOptional), + CHIP_NO_ERROR); - err = GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1, &caseSession); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(GetExchangeManager().RegisterUnsolicitedMessageHandlerForType(MsgType::CASE_Sigma1, &caseSession), CHIP_NO_ERROR); ExpectErrorExchangeDelegate delegate(SecureChannel::kProtocolCodeNoSharedRoot); ExchangeContext * exchange = GetExchangeManager().NewContext(session.Value(), &delegate); ASSERT_NE(exchange, nullptr); - err = exchange->SendMessage(MsgType::CASE_Sigma1, std::move(data), SendMessageFlags::kExpectResponse); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(exchange->SendMessage(MsgType::CASE_Sigma1, std::move(data), SendMessageFlags::kExpectResponse), CHIP_NO_ERROR); ServiceEvents(); diff --git a/src/protocols/secure_channel/tests/TestCheckInCounter.cpp b/src/protocols/secure_channel/tests/TestCheckInCounter.cpp index e4a71777d17b97..57dbd4b3496cdd 100644 --- a/src/protocols/secure_channel/tests/TestCheckInCounter.cpp +++ b/src/protocols/secure_channel/tests/TestCheckInCounter.cpp @@ -56,7 +56,6 @@ void VerifyCheckInCounterValues(uint32_t startValue, uint32_t expectedValue, Che EXPECT_EQ(counter.GetValue(), startValue); // Test operation - CHIP_ERROR err = CHIP_NO_ERROR; switch (operation) { case CheckInCounterOperations::kInvalidateHalf: { @@ -68,7 +67,6 @@ void VerifyCheckInCounterValues(uint32_t startValue, uint32_t expectedValue, Che break; } default: { - err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; FAIL(); } }; diff --git a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp index c1fdf885a27393..6454fbd61c0c22 100644 --- a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp +++ b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp @@ -76,8 +76,6 @@ struct TestMessageCounterManager : public chip::Test::LoopbackMessagingContext, TEST_F(TestMessageCounterManager, MessageCounterSyncProcess) { - CHIP_ERROR err = CHIP_NO_ERROR; - SessionHandle localSession = GetSessionBobToAlice(); SessionHandle peerSession = GetSessionAliceToBob(); @@ -85,8 +83,7 @@ TEST_F(TestMessageCounterManager, MessageCounterSyncProcess) Transport::SecureSession * peerState = GetSecureSessionManager().GetSecureSession(peerSession); localState->GetSessionMessageCounter().GetPeerMessageCounter().Reset(); - err = GetMessageCounterManager().SendMsgCounterSyncReq(localSession, localState); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(GetMessageCounterManager().SendMsgCounterSyncReq(localSession, localState), CHIP_NO_ERROR); MessageCounter & peerCounter = peerState->GetSessionMessageCounter().GetLocalMessageCounter(); PeerMessageCounter & localCounter = localState->GetSessionMessageCounter().GetPeerMessageCounter(); @@ -96,8 +93,6 @@ TEST_F(TestMessageCounterManager, MessageCounterSyncProcess) TEST_F(TestMessageCounterManager, CheckReceiveMessage) { - CHIP_ERROR err = CHIP_NO_ERROR; - SessionHandle peerSession = GetSessionAliceToBob(); Transport::SecureSession * peerState = GetSecureSessionManager().GetSecureSession(peerSession); peerState->GetSessionMessageCounter().GetPeerMessageCounter().Reset(); @@ -112,9 +107,9 @@ TEST_F(TestMessageCounterManager, CheckReceiveMessage) Messaging::ExchangeContext * ec = NewExchangeToAlice(nullptr); EXPECT_NE(ec, nullptr); - err = ec->SendMessage(chip::Protocols::Echo::MsgType::EchoRequest, std::move(msgBuf), - Messaging::SendFlags{ Messaging::SendMessageFlags::kNoAutoRequestAck }); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(ec->SendMessage(chip::Protocols::Echo::MsgType::EchoRequest, std::move(msgBuf), + Messaging::SendFlags{ Messaging::SendMessageFlags::kNoAutoRequestAck }), + CHIP_NO_ERROR); EXPECT_TRUE(peerState->GetSessionMessageCounter().GetPeerMessageCounter().IsSynchronized()); EXPECT_EQ(callback.ReceiveHandlerCallCount, 1); } diff --git a/src/protocols/secure_channel/tests/TestStatusReport.cpp b/src/protocols/secure_channel/tests/TestStatusReport.cpp index 71900f9d0a645e..9d196907332372 100644 --- a/src/protocols/secure_channel/tests/TestStatusReport.cpp +++ b/src/protocols/secure_channel/tests/TestStatusReport.cpp @@ -57,8 +57,7 @@ TEST_F(TestStatusReport, NoData) EXPECT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; - CHIP_ERROR err = reportToParse.Parse(std::move(msgBuf)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.Parse(std::move(msgBuf)), CHIP_NO_ERROR); EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); @@ -86,8 +85,7 @@ TEST_F(TestStatusReport, WithData) EXPECT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; - CHIP_ERROR err = reportToParse.Parse(std::move(msgBuf)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.Parse(std::move(msgBuf)), CHIP_NO_ERROR); EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); @@ -122,8 +120,7 @@ TEST_F(TestStatusReport, TestMakeBusyStatusReport) EXPECT_FALSE(handle.IsNull()); StatusReport reportToParse; - CHIP_ERROR err = reportToParse.Parse(std::move(handle)); - EXPECT_EQ(err, CHIP_NO_ERROR); + EXPECT_EQ(reportToParse.Parse(std::move(handle)), CHIP_NO_ERROR); EXPECT_EQ(reportToParse.GetGeneralCode(), generalCode); EXPECT_EQ(reportToParse.GetProtocolId(), protocolId); EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); diff --git a/src/system/tests/BUILD.gn b/src/system/tests/BUILD.gn index d8f1e39dd76a47..01965170ab9b0c 100644 --- a/src/system/tests/BUILD.gn +++ b/src/system/tests/BUILD.gn @@ -46,7 +46,7 @@ chip_test_suite("tests") { public_deps = [ "${chip_root}/src/inet", - "${chip_root}/src/lib/support:pw_test_utils", + "${chip_root}/src/lib/support/tests:pw-test-macros", "${chip_root}/src/platform", "${chip_root}/src/system", ] diff --git a/src/system/tests/TestSystemPacketBuffer.cpp b/src/system/tests/TestSystemPacketBuffer.cpp index d0209b6bb45623..bf1456487307a3 100644 --- a/src/system/tests/TestSystemPacketBuffer.cpp +++ b/src/system/tests/TestSystemPacketBuffer.cpp @@ -35,7 +35,7 @@ #include #include #include -#include +#include #include #include From 1e5d972af64f3021dbd22cd56802ef0dd596f519 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Mon, 27 May 2024 10:29:08 +0200 Subject: [PATCH 28/30] Fix typo --- src/lib/support/tests/ExtraPwTestMacros.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/support/tests/ExtraPwTestMacros.h b/src/lib/support/tests/ExtraPwTestMacros.h index 871e0b6a283297..ab592800716592 100644 --- a/src/lib/support/tests/ExtraPwTestMacros.h +++ b/src/lib/support/tests/ExtraPwTestMacros.h @@ -41,7 +41,7 @@ * void testFunction(); * }; * - * TEST_F_FROM_FIXTURE(TestClass, testFunction) + * TEST_F_FROM_FIXTURE(TestCtx, testFunction) * { * Foo foo; * EXPECT_TRUE(foo.privateFunction()); From 8f8a2c1bf0cad89ee26547a1d1f039fd9d722348 Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Mon, 3 Jun 2024 09:19:04 +0200 Subject: [PATCH 29/30] Fix review issues --- src/protocols/secure_channel/tests/TestCASESession.cpp | 4 ++-- src/protocols/secure_channel/tests/TestPASESession.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestCASESession.cpp b/src/protocols/secure_channel/tests/TestCASESession.cpp index f4cc1ba53e4607..24aaffce0dbcb4 100644 --- a/src/protocols/secure_channel/tests/TestCASESession.cpp +++ b/src/protocols/secure_channel/tests/TestCASESession.cpp @@ -542,7 +542,7 @@ TEST_F(TestCASESession, SecurePairingHandshakeServerTest) SessionHolder & holder = delegateCommissioner.GetSessionHolder(); EXPECT_TRUE(bool(holder)); - EXPECT_TRUE((holder->GetPeer() == chip::ScopedNodeId{ Node01_01, gCommissionerFabricIndex })); + EXPECT_EQ(holder->GetPeer(), (chip::ScopedNodeId{ Node01_01, gCommissionerFabricIndex })); auto * pairingCommissioner1 = chip::Platform::New(); pairingCommissioner1->SetGroupDataProvider(&gCommissionerGroupDataProvider); @@ -939,7 +939,7 @@ TEST_F(TestCASESession, SessionResumptionStorage) // Create our fabric-scoped node IDs. const FabricInfo * fabricInfo = gCommissionerFabrics.FindFabricWithIndex(gCommissionerFabricIndex); - EXPECT_NE(fabricInfo, nullptr); + ASSERT_NE(fabricInfo, nullptr); ScopedNodeId initiator = fabricInfo->GetScopedNodeIdForNode(Node01_02); ScopedNodeId responder = fabricInfo->GetScopedNodeIdForNode(Node01_01); diff --git a/src/protocols/secure_channel/tests/TestPASESession.cpp b/src/protocols/secure_channel/tests/TestPASESession.cpp index 34ba8e58b0abd0..5b3f957d51bf84 100644 --- a/src/protocols/secure_channel/tests/TestPASESession.cpp +++ b/src/protocols/secure_channel/tests/TestPASESession.cpp @@ -325,7 +325,7 @@ void TestPASESession::SecurePairingHandshakeTestCommon(SessionManager & sessionM // via piggybacked acks. So we cannot check for a specific value of mSentMessageCount. // Let's make sure atleast number is >= than the minimum messages required to complete the // handshake. - EXPECT_TRUE(loopback.mSentMessageCount >= sTestPaseMessageCount); + EXPECT_GE(loopback.mSentMessageCount, sTestPaseMessageCount); EXPECT_EQ(delegateAccessory.mNumPairingErrors, 0u); EXPECT_EQ(delegateAccessory.mNumPairingComplete, 1u); EXPECT_EQ(delegateCommissioner.mNumPairingErrors, 0u); From fda317bc9079edb5c2b7ba70bc11353882fff7ed Mon Sep 17 00:00:00 2001 From: Jakub Latusek Date: Mon, 3 Jun 2024 09:28:58 +0200 Subject: [PATCH 30/30] Fix review issues --- .../secure_channel/tests/TestMessageCounterManager.cpp | 4 ++-- .../secure_channel/tests/TestStatusReport.cpp | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp index 6454fbd61c0c22..41b6539ecf0773 100644 --- a/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp +++ b/src/protocols/secure_channel/tests/TestMessageCounterManager.cpp @@ -102,10 +102,10 @@ TEST_F(TestMessageCounterManager, CheckReceiveMessage) uint16_t payload_len = sizeof(PAYLOAD); System::PacketBufferHandle msgBuf = MessagePacketBuffer::NewWithData(PAYLOAD, payload_len); - EXPECT_FALSE(msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); Messaging::ExchangeContext * ec = NewExchangeToAlice(nullptr); - EXPECT_NE(ec, nullptr); + ASSERT_NE(ec, nullptr); EXPECT_EQ(ec->SendMessage(chip::Protocols::Echo::MsgType::EchoRequest, std::move(msgBuf), Messaging::SendFlags{ Messaging::SendMessageFlags::kNoAutoRequestAck }), diff --git a/src/protocols/secure_channel/tests/TestStatusReport.cpp b/src/protocols/secure_channel/tests/TestStatusReport.cpp index 9d196907332372..65bc639dcca7c3 100644 --- a/src/protocols/secure_channel/tests/TestStatusReport.cpp +++ b/src/protocols/secure_channel/tests/TestStatusReport.cpp @@ -54,7 +54,7 @@ TEST_F(TestStatusReport, NoData) testReport.WriteToBuffer(bbuf); System::PacketBufferHandle msgBuf = bbuf.Finalize(); - EXPECT_FALSE(msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; EXPECT_EQ(reportToParse.Parse(std::move(msgBuf)), CHIP_NO_ERROR); @@ -82,7 +82,7 @@ TEST_F(TestStatusReport, WithData) testReport.WriteToBuffer(bbuf); System::PacketBufferHandle msgBuf = bbuf.Finalize(); - EXPECT_FALSE(msgBuf.IsNull()); + ASSERT_FALSE(msgBuf.IsNull()); StatusReport reportToParse; EXPECT_EQ(reportToParse.Parse(std::move(msgBuf)), CHIP_NO_ERROR); @@ -91,7 +91,7 @@ TEST_F(TestStatusReport, WithData) EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & rcvData = reportToParse.GetProtocolData(); - EXPECT_FALSE(rcvData.IsNull()); + ASSERT_FALSE(rcvData.IsNull()); EXPECT_EQ(rcvData->DataLength(), dataLen); EXPECT_EQ(memcmp(rcvData->Start(), data, dataLen), 0); } @@ -117,7 +117,7 @@ TEST_F(TestStatusReport, TestMakeBusyStatusReport) System::Clock::Milliseconds16 minimumWaitTime = System::Clock::Milliseconds16(5000); System::PacketBufferHandle handle = StatusReport::MakeBusyStatusReportMessage(minimumWaitTime); - EXPECT_FALSE(handle.IsNull()); + ASSERT_FALSE(handle.IsNull()); StatusReport reportToParse; EXPECT_EQ(reportToParse.Parse(std::move(handle)), CHIP_NO_ERROR); @@ -126,7 +126,7 @@ TEST_F(TestStatusReport, TestMakeBusyStatusReport) EXPECT_EQ(reportToParse.GetProtocolCode(), protocolCode); const System::PacketBufferHandle & rcvData = reportToParse.GetProtocolData(); - EXPECT_FALSE(rcvData.IsNull()); + ASSERT_FALSE(rcvData.IsNull()); EXPECT_EQ(rcvData->DataLength(), sizeof(minimumWaitTime)); uint16_t readMinimumWaitTime = 0;