diff --git a/.clang-format b/.clang-format index 0754102a41..b33cf3f47c 100644 --- a/.clang-format +++ b/.clang-format @@ -32,6 +32,7 @@ InsertNewlineAtEOF: 'true' MaxEmptyLinesToKeep: 1 NamespaceIndentation: All PointerAlignment: Left +QualifierAlignment: Left SeparateDefinitionBlocks: 'Always' SortIncludes: 'true' SpaceAfterCStyleCast: 'false' diff --git a/.clang-tidy b/.clang-tidy index 04da75faf1..b035282b9c 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -24,6 +24,7 @@ Checks: 'clang-diagnostic-*, google-explicit-constructor, hicpp-multiway-paths-covered, hicpp-exception-baseclass, + misc-const-correctness, misc-unconventional-assign-operator, misc-misplaced-const, misc-new-delete-overloads, diff --git a/src/agent/agent_info/src/agent_info.cpp b/src/agent/agent_info/src/agent_info.cpp index af236c155e..5edf29be2f 100644 --- a/src/agent/agent_info/src/agent_info.cpp +++ b/src/agent/agent_info/src/agent_info.cpp @@ -224,7 +224,7 @@ void AgentInfo::LoadEndpointInfo() { if (m_getOSInfo != nullptr) { - nlohmann::json osInfo = m_getOSInfo(); + const nlohmann::json osInfo = m_getOSInfo(); m_endpointInfo["hostname"] = osInfo.value("hostname", "Unknown"); m_endpointInfo["architecture"] = osInfo.value("architecture", "Unknown"); m_endpointInfo["os"] = nlohmann::json::object(); @@ -235,7 +235,7 @@ void AgentInfo::LoadEndpointInfo() if (m_getNetworksInfo != nullptr) { - nlohmann::json networksInfo = m_getNetworksInfo(); + const nlohmann::json networksInfo = m_getNetworksInfo(); m_endpointInfo["ip"] = GetActiveIPAddresses(networksInfo); } } diff --git a/src/agent/agent_info/tests/agent_info_persistance_test.cpp b/src/agent/agent_info/tests/agent_info_persistance_test.cpp index 0484ace062..79bbd5bef6 100644 --- a/src/agent/agent_info/tests/agent_info_persistance_test.cpp +++ b/src/agent/agent_info/tests/agent_info_persistance_test.cpp @@ -36,7 +36,7 @@ TEST_F(AgentInfoPersistanceTest, TestConstruction) TEST_F(AgentInfoPersistanceTest, TestGetNameValue) { - std::vector mockRowName = {{column::ColumnValue("name", column::ColumnType::TEXT, "name_test")}}; + const std::vector mockRowName = {{column::ColumnValue("name", column::ColumnType::TEXT, "name_test")}}; EXPECT_CALL(*mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowName)); @@ -45,7 +45,7 @@ TEST_F(AgentInfoPersistanceTest, TestGetNameValue) TEST_F(AgentInfoPersistanceTest, TestGetNameNotValue) { - std::vector mockRowName = {}; + const std::vector mockRowName = {}; EXPECT_CALL(*mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowName)); @@ -62,7 +62,7 @@ TEST_F(AgentInfoPersistanceTest, TestGetNameCatch) TEST_F(AgentInfoPersistanceTest, TestGetKeyValue) { - std::vector mockRowKey = {{column::ColumnValue("key", column::ColumnType::TEXT, "key_test")}}; + const std::vector mockRowKey = {{column::ColumnValue("key", column::ColumnType::TEXT, "key_test")}}; EXPECT_CALL(*mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowKey)); @@ -71,7 +71,7 @@ TEST_F(AgentInfoPersistanceTest, TestGetKeyValue) TEST_F(AgentInfoPersistanceTest, TestGetKeyNotValue) { - std::vector mockRowKey = {}; + const std::vector mockRowKey = {}; EXPECT_CALL(*mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowKey)); @@ -88,7 +88,7 @@ TEST_F(AgentInfoPersistanceTest, TestGetKeyCatch) TEST_F(AgentInfoPersistanceTest, TestGetUUIDValue) { - std::vector mockRowUUID = {{column::ColumnValue("uuid", column::ColumnType::TEXT, "uuid_test")}}; + const std::vector mockRowUUID = {{column::ColumnValue("uuid", column::ColumnType::TEXT, "uuid_test")}}; EXPECT_CALL(*mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowUUID)); @@ -97,7 +97,7 @@ TEST_F(AgentInfoPersistanceTest, TestGetUUIDValue) TEST_F(AgentInfoPersistanceTest, TestGetUUIDNotValue) { - std::vector mockRowUUID = {}; + const std::vector mockRowUUID = {}; EXPECT_CALL(*mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowUUID)); @@ -114,24 +114,24 @@ TEST_F(AgentInfoPersistanceTest, TestGetUUIDCatch) TEST_F(AgentInfoPersistanceTest, TestGetGroupsValue) { - std::vector mockRowGroups = {{column::ColumnValue("name", column::ColumnType::TEXT, "group_1")}, - {column::ColumnValue("name", column::ColumnType::TEXT, "group_2")}}; + const std::vector mockRowGroups = {{column::ColumnValue("name", column::ColumnType::TEXT, "group_1")}, + {column::ColumnValue("name", column::ColumnType::TEXT, "group_2")}}; EXPECT_CALL(*mockPersistence, Select("agent_group", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowGroups)); - std::vector expectedGroups = {"group_1", "group_2"}; + const std::vector expectedGroups = {"group_1", "group_2"}; EXPECT_EQ(agentInfoPersistance->GetGroups(), expectedGroups); } TEST_F(AgentInfoPersistanceTest, TestGetGroupsNotValue) { - std::vector mockRowGroups = {}; + const std::vector mockRowGroups = {}; EXPECT_CALL(*mockPersistence, Select("agent_group", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(mockRowGroups)); - std::vector expectedGroups = {}; + const std::vector expectedGroups = {}; EXPECT_EQ(agentInfoPersistance->GetGroups(), expectedGroups); } @@ -141,14 +141,14 @@ TEST_F(AgentInfoPersistanceTest, TestGetGroupsCatch) Select("agent_group", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Throw(std::runtime_error("Error Select"))); - std::vector expectedGroups = {}; + const std::vector expectedGroups = {}; EXPECT_EQ(agentInfoPersistance->GetGroups(), expectedGroups); } TEST_F(AgentInfoPersistanceTest, TestSetName) { - std::string expectedColumn = "name"; - std::string newName = "new_name"; + const std::string expectedColumn = "name"; + const std::string newName = "new_name"; EXPECT_CALL(*mockPersistence, Update(testing::Eq("agent_info"), @@ -164,8 +164,8 @@ TEST_F(AgentInfoPersistanceTest, TestSetName) TEST_F(AgentInfoPersistanceTest, TestSetNameCatch) { - std::string expectedColumn = "name"; - std::string newName = "new_name"; + const std::string expectedColumn = "name"; + const std::string newName = "new_name"; EXPECT_CALL(*mockPersistence, Update(testing::Eq("agent_info"), @@ -181,8 +181,8 @@ TEST_F(AgentInfoPersistanceTest, TestSetNameCatch) TEST_F(AgentInfoPersistanceTest, TestSetKey) { - std::string expectedColumn = "key"; - std::string newKey = "new_key"; + const std::string expectedColumn = "key"; + const std::string newKey = "new_key"; EXPECT_CALL(*mockPersistence, Update(testing::Eq("agent_info"), @@ -198,8 +198,8 @@ TEST_F(AgentInfoPersistanceTest, TestSetKey) TEST_F(AgentInfoPersistanceTest, TestSetKeyCatch) { - std::string expectedColumn = "key"; - std::string newKey = "new_key"; + const std::string expectedColumn = "key"; + const std::string newKey = "new_key"; EXPECT_CALL(*mockPersistence, Update(testing::Eq("agent_info"), @@ -215,8 +215,8 @@ TEST_F(AgentInfoPersistanceTest, TestSetKeyCatch) TEST_F(AgentInfoPersistanceTest, TestSetUUID) { - std::string expectedColumn = "uuid"; - std::string newUUID = "new_uuid"; + const std::string expectedColumn = "uuid"; + const std::string newUUID = "new_uuid"; EXPECT_CALL(*mockPersistence, Update(testing::Eq("agent_info"), @@ -232,8 +232,8 @@ TEST_F(AgentInfoPersistanceTest, TestSetUUID) TEST_F(AgentInfoPersistanceTest, TestSetUUIDCatch) { - std::string expectedColumn = "uuid"; - std::string newUUID = "new_uuid"; + const std::string expectedColumn = "uuid"; + const std::string newUUID = "new_uuid"; EXPECT_CALL(*mockPersistence, Update(testing::Eq("agent_info"), @@ -301,7 +301,7 @@ TEST_F(AgentInfoPersistanceTest, TestSetGroupsInsertFails2) EXPECT_CALL(*mockPersistence, BeginTransaction()).Times(1); EXPECT_CALL(*mockPersistence, Remove("agent_group", testing::_, testing::_)).Times(1); - testing::Sequence seq; + const testing::Sequence seq; EXPECT_CALL(*mockPersistence, Insert("agent_group", testing::_)) .InSequence(seq) .WillOnce(testing::Return()) diff --git a/src/agent/agent_info/tests/agent_info_test.cpp b/src/agent/agent_info/tests/agent_info_test.cpp index ade02f5f9e..d52f9a7421 100644 --- a/src/agent/agent_info/tests/agent_info_test.cpp +++ b/src/agent/agent_info/tests/agent_info_test.cpp @@ -52,12 +52,15 @@ class AgentInfoTest : public ::testing::Test void SetUpAgentInfoInitialization() { - std::vector mockRowName = {{column::ColumnValue("name", column::ColumnType::TEXT, "name_test")}}; - std::vector mockRowKey = {{column::ColumnValue("key", column::ColumnType::TEXT, "key_test")}}; - std::vector mockRowUUID = {{column::ColumnValue("uuid", column::ColumnType::TEXT, "uuid_test")}}; - std::vector mockRowGroup = {{}}; - - testing::Sequence seq; + const std::vector mockRowName = { + {column::ColumnValue("name", column::ColumnType::TEXT, "name_test")}}; + const std::vector mockRowKey = { + {column::ColumnValue("key", column::ColumnType::TEXT, "key_test")}}; + const std::vector mockRowUUID = { + {column::ColumnValue("uuid", column::ColumnType::TEXT, "uuid_test")}}; + const std::vector mockRowGroup = {{}}; + + const testing::Sequence seq; EXPECT_CALL(*m_mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .InSequence(seq) diff --git a/src/agent/centralized_configuration/src/centralized_configuration.cpp b/src/agent/centralized_configuration/src/centralized_configuration.cpp index 02d538898e..6e435f78c1 100644 --- a/src/agent/centralized_configuration/src/centralized_configuration.cpp +++ b/src/agent/centralized_configuration/src/centralized_configuration.cpp @@ -19,7 +19,7 @@ namespace std::random_device rd; std::mt19937 generator(rd()); std::uniform_int_distribution distribution(MIN_VALUE, MAX_VALUE); - int random = distribution(generator); + const int random = distribution(generator); auto now = std::chrono::high_resolution_clock::now(); auto timestamp = now.time_since_epoch().count(); diff --git a/src/agent/centralized_configuration/tests/centralized_configuration_tests.cpp b/src/agent/centralized_configuration/tests/centralized_configuration_tests.cpp index e4dd2a8b2a..e54ba9a268 100644 --- a/src/agent/centralized_configuration/tests/centralized_configuration_tests.cpp +++ b/src/agent/centralized_configuration/tests/centralized_configuration_tests.cpp @@ -38,7 +38,7 @@ namespace TEST(CentralizedConfiguration, Constructor) { - EXPECT_NO_THROW(CentralizedConfiguration centralizedConfiguration( + EXPECT_NO_THROW(const CentralizedConfiguration centralizedConfiguration( [](const std::vector&) { return true; }, []() { return std::vector {}; }, [](std::string, std::string) -> boost::asio::awaitable { co_return true; }, @@ -49,7 +49,7 @@ TEST(CentralizedConfiguration, Constructor) TEST(CentralizedConfiguration, ConstructorNoGetGroups) { - EXPECT_THROW(CentralizedConfiguration centralizedConfiguration( + EXPECT_THROW(const CentralizedConfiguration centralizedConfiguration( nullptr, []() { return std::vector {}; }, [](std::string, std::string) -> boost::asio::awaitable { co_return true; }, @@ -61,7 +61,7 @@ TEST(CentralizedConfiguration, ConstructorNoGetGroups) TEST(CentralizedConfiguration, ConstructorNoSetGroups) { - EXPECT_THROW(CentralizedConfiguration centralizedConfiguration( + EXPECT_THROW(const CentralizedConfiguration centralizedConfiguration( [](const std::vector&) { return true; }, nullptr, [](std::string, std::string) -> boost::asio::awaitable { co_return true; }, @@ -73,18 +73,19 @@ TEST(CentralizedConfiguration, ConstructorNoSetGroups) TEST(CentralizedConfiguration, ConstructorNoDownloadGroups) { - EXPECT_THROW(CentralizedConfiguration centralizedConfiguration([](const std::vector&) { return true; }, - []() { return std::vector {}; }, - nullptr, - [](const std::filesystem::path&) { return true; }, - []() {}, - nullptr), - std::runtime_error); + EXPECT_THROW( + const CentralizedConfiguration centralizedConfiguration([](const std::vector&) { return true; }, + []() { return std::vector {}; }, + nullptr, + [](const std::filesystem::path&) { return true; }, + []() {}, + nullptr), + std::runtime_error); } TEST(CentralizedConfiguration, ConstructorNoValidateGroups) { - EXPECT_THROW(CentralizedConfiguration centralizedConfiguration( + EXPECT_THROW(const CentralizedConfiguration centralizedConfiguration( [](const std::vector&) { return true; }, []() { return std::vector {}; }, [](std::string, std::string) -> boost::asio::awaitable { co_return true; }, @@ -96,7 +97,7 @@ TEST(CentralizedConfiguration, ConstructorNoValidateGroups) TEST(CentralizedConfiguration, ConstructorNoReloadModules) { - EXPECT_THROW(CentralizedConfiguration centralizedConfiguration( + EXPECT_THROW(const CentralizedConfiguration centralizedConfiguration( [](const std::vector&) { return true; }, []() { return std::vector {}; }, [](std::string, std::string) -> boost::asio::awaitable { co_return true; }, diff --git a/src/agent/command_handler/tests/command_handler_test.cpp b/src/agent/command_handler/tests/command_handler_test.cpp index 4588c22a1a..836eabb941 100644 --- a/src/agent/command_handler/tests/command_handler_test.cpp +++ b/src/agent/command_handler/tests/command_handler_test.cpp @@ -7,12 +7,12 @@ TEST(CommandHandlerTest, CommandHandlerConstructor) { auto configurationParser = std::make_shared(); - EXPECT_NO_THROW(command_handler::CommandHandler cm(configurationParser)); + EXPECT_NO_THROW(const command_handler::CommandHandler cm(configurationParser)); } TEST(CommandHandlerTest, CommandHandlerConstructorNoConfigParser) { - EXPECT_THROW(command_handler::CommandHandler cm(nullptr), std::runtime_error); + EXPECT_THROW(const command_handler::CommandHandler cm(nullptr), std::runtime_error); } int main(int argc, char** argv) diff --git a/src/agent/command_handler/tests/command_store_test.cpp b/src/agent/command_handler/tests/command_store_test.cpp index 15db6058ed..caf2cef5dd 100644 --- a/src/agent/command_handler/tests/command_store_test.cpp +++ b/src/agent/command_handler/tests/command_store_test.cpp @@ -28,35 +28,32 @@ TEST_F(CommandStoreTest, StoreCommandTest) { m_commandStore->Clear(); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd1(TESTID_5, - "Module1", - "{CommandTextHERE}", - {"Parameter1"}, - module_command::CommandExecutionMode::ASYNC, - "Result1", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd1(TESTID_5, + "Module1", + "{CommandTextHERE}", + {"Parameter1"}, + module_command::CommandExecutionMode::ASYNC, + "Result1", + module_command::Status::IN_PROGRESS); bool retVal = m_commandStore->StoreCommand(cmd1); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd2(TESTID_9, - "Module2", - R"({"Some"="thing"})", - {"Parameter2"}, - module_command::CommandExecutionMode::ASYNC, - "Result2", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd2(TESTID_9, + "Module2", + R"({"Some"="thing"})", + {"Parameter2"}, + module_command::CommandExecutionMode::ASYNC, + "Result2", + module_command::Status::IN_PROGRESS); retVal = m_commandStore->StoreCommand(cmd2); ASSERT_EQ(retVal, true); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd3(TESTID_5, - "Module3", - "{CommandTextHERE}", - {"Parameter3"}, - module_command::CommandExecutionMode::ASYNC, - "Result3", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd3(TESTID_5, + "Module3", + "{CommandTextHERE}", + {"Parameter3"}, + module_command::CommandExecutionMode::ASYNC, + "Result3", + module_command::Status::IN_PROGRESS); retVal = m_commandStore->StoreCommand(cmd3); ASSERT_EQ(retVal, false); @@ -67,28 +64,26 @@ TEST_F(CommandStoreTest, StoreCommandTestParameters) { m_commandStore->Clear(); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd1(TESTID_5, - "Module1", - "{CommandTextHERE}", - {"Parameter1", "Parameter 2", "3"}, - module_command::CommandExecutionMode::ASYNC, - "Result1", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd1(TESTID_5, + "Module1", + "{CommandTextHERE}", + {"Parameter1", "Parameter 2", "3"}, + module_command::CommandExecutionMode::ASYNC, + "Result1", + module_command::Status::IN_PROGRESS); const bool retVal = m_commandStore->StoreCommand(cmd1); ASSERT_TRUE(retVal); ASSERT_EQ(m_commandStore->GetCount(), 1); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::optional retValue = m_commandStore->GetCommand(TESTID_5); + const auto retValue = m_commandStore->GetCommand(TESTID_5); if (retValue.has_value()) { const module_command::CommandEntry& cmd = retValue.value(); ASSERT_EQ(cmd.Id, TESTID_5); ASSERT_EQ(cmd.Module, "Module1"); ASSERT_EQ(cmd.Command, "{CommandTextHERE}"); - std::vector expected = {"Parameter1", "Parameter 2", "3"}; + const std::vector expected = {"Parameter1", "Parameter 2", "3"}; ASSERT_EQ(cmd.Parameters, expected); ASSERT_EQ(cmd.ExecutionMode, module_command::CommandExecutionMode::ASYNC); ASSERT_EQ(cmd.ExecutionResult.Message, "Result1"); @@ -104,41 +99,37 @@ TEST_F(CommandStoreTest, UpdateCommandTest) { m_commandStore->Clear(); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd1(TESTID_5, - "Module1", - "{CommandTextHERE}", - {"Parameter1"}, - module_command::CommandExecutionMode::ASYNC, - "Result1", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd1(TESTID_5, + "Module1", + "{CommandTextHERE}", + {"Parameter1"}, + module_command::CommandExecutionMode::ASYNC, + "Result1", + module_command::Status::IN_PROGRESS); m_commandStore->StoreCommand(cmd1); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd2(TESTID_9, - "Module2", - R"({"Some"="thing"})", - {"Parameter2"}, - module_command::CommandExecutionMode::ASYNC, - "Result2", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd2(TESTID_9, + "Module2", + R"({"Some"="thing"})", + {"Parameter2"}, + module_command::CommandExecutionMode::ASYNC, + "Result2", + module_command::Status::IN_PROGRESS); m_commandStore->StoreCommand(cmd2); ASSERT_EQ(m_commandStore->GetCount(), 2); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmdUpdate(TESTID_9, - "Updated Module", - "Updated CommandEntry", - {"Updated Parameter"}, - module_command::CommandExecutionMode::ASYNC, - "Updated Result", - module_command::Status::SUCCESS); + const module_command::CommandEntry cmdUpdate(TESTID_9, + "Updated Module", + "Updated CommandEntry", + {"Updated Parameter"}, + module_command::CommandExecutionMode::ASYNC, + "Updated Result", + module_command::Status::SUCCESS); bool retVal = m_commandStore->UpdateCommand(cmdUpdate); ASSERT_EQ(retVal, true); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::optional retValue = m_commandStore->GetCommand(TESTID_9); + auto retValue = m_commandStore->GetCommand(TESTID_9); if (retValue.has_value()) { const module_command::CommandEntry& cmd = retValue.value(); @@ -154,19 +145,17 @@ TEST_F(CommandStoreTest, UpdateCommandTest) FAIL(); } - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmdUpdate2(TESTID_9, - "", - "", - {}, - module_command::CommandExecutionMode::ASYNC, - "Newly Updated Result", - module_command::Status::UNKNOWN); + const module_command::CommandEntry cmdUpdate2(TESTID_9, + "", + "", + {}, + module_command::CommandExecutionMode::ASYNC, + "Newly Updated Result", + module_command::Status::UNKNOWN); retVal = m_commandStore->UpdateCommand(cmdUpdate2); ASSERT_EQ(retVal, true); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) retValue = m_commandStore->GetCommand(TESTID_9); if (retValue.has_value()) { @@ -187,9 +176,8 @@ TEST_F(CommandStoreTest, UpdateCommandTest) TEST_F(CommandStoreTest, DeleteCommandTest) { - int initialCount = m_commandStore->GetCount(); + const int initialCount = m_commandStore->GetCount(); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) m_commandStore->DeleteCommand(TESTID_9); ASSERT_EQ(m_commandStore->GetCount(), initialCount - 1); @@ -199,37 +187,33 @@ TEST_F(CommandStoreTest, GetCommandTest) { m_commandStore->Clear(); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd1(TESTID_5, - "Module1", - "{CommandTextHERE}", - {"Parameter1"}, - module_command::CommandExecutionMode::SYNC, - "Result1", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd1(TESTID_5, + "Module1", + "{CommandTextHERE}", + {"Parameter1"}, + module_command::CommandExecutionMode::SYNC, + "Result1", + module_command::Status::IN_PROGRESS); m_commandStore->StoreCommand(cmd1); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd2(TESTID_9, - "Module2", - "TestValue9", - {"Parameter2"}, - module_command::CommandExecutionMode::SYNC, - "Result2", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd2(TESTID_9, + "Module2", + "TestValue9", + {"Parameter2"}, + module_command::CommandExecutionMode::SYNC, + "Result2", + module_command::Status::IN_PROGRESS); m_commandStore->StoreCommand(cmd2); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd3(TESTID_11, - "Module3", - "{CommandTextHERE}", - {"Parameter3"}, - module_command::CommandExecutionMode::SYNC, - "Result3", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd3(TESTID_11, + "Module3", + "{CommandTextHERE}", + {"Parameter3"}, + module_command::CommandExecutionMode::SYNC, + "Result3", + module_command::Status::IN_PROGRESS); m_commandStore->StoreCommand(cmd3); ASSERT_EQ(m_commandStore->GetCount(), 3); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::optional retValue = m_commandStore->GetCommand(TESTID_9); + auto retValue = m_commandStore->GetCommand(TESTID_9); if (retValue.has_value()) { const module_command::CommandEntry& cmd = retValue.value(); @@ -238,7 +222,6 @@ TEST_F(CommandStoreTest, GetCommandTest) ASSERT_EQ(cmd.Command, "TestValue9"); } - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) retValue = m_commandStore->GetCommand(TESTID_11); if (retValue.has_value()) { @@ -253,32 +236,29 @@ TEST_F(CommandStoreTest, GetCommandByStatusTest) { m_commandStore->Clear(); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd1(TESTID_5, - "Module1", - "{CommandTextHERE}", - {"Parameter1"}, - module_command::CommandExecutionMode::SYNC, - "Result1", - module_command::Status::SUCCESS); + const module_command::CommandEntry cmd1(TESTID_5, + "Module1", + "{CommandTextHERE}", + {"Parameter1"}, + module_command::CommandExecutionMode::SYNC, + "Result1", + module_command::Status::SUCCESS); m_commandStore->StoreCommand(cmd1); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd2(TESTID_9, - "Module2", - "TestValue9", - {"Parameter2"}, - module_command::CommandExecutionMode::SYNC, - "Result2", - module_command::Status::IN_PROGRESS); + const module_command::CommandEntry cmd2(TESTID_9, + "Module2", + "TestValue9", + {"Parameter2"}, + module_command::CommandExecutionMode::SYNC, + "Result2", + module_command::Status::IN_PROGRESS); m_commandStore->StoreCommand(cmd2); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - module_command::CommandEntry cmd3(TESTID_11, - "Module3", - "{CommandTextHERE}", - {"Parameter3"}, - module_command::CommandExecutionMode::SYNC, - "Result3", - module_command::Status::SUCCESS); + const module_command::CommandEntry cmd3(TESTID_11, + "Module3", + "{CommandTextHERE}", + {"Parameter3"}, + module_command::CommandExecutionMode::SYNC, + "Result3", + module_command::Status::SUCCESS); m_commandStore->StoreCommand(cmd3); ASSERT_EQ(m_commandStore->GetCount(), 3); diff --git a/src/agent/communicator/src/communicator.cpp b/src/agent/communicator/src/communicator.cpp index cfd12441ea..26140fda10 100644 --- a/src/agent/communicator/src/communicator.cpp +++ b/src/agent/communicator/src/communicator.cpp @@ -1,17 +1,14 @@ #include + #include #include +#include #include - -#include - +#include #include #include - -#include - -#include +#include #include #include @@ -70,7 +67,7 @@ namespace communicator m_serverUrl = configurationParser->GetConfigOrDefault(config::agent::DEFAULT_SERVER_URL, "agent", "server_url"); - if (boost::urls::url_view url(m_serverUrl); url.scheme() != "https") + if (const boost::urls::url_view url(m_serverUrl); url.scheme() != "https") { LogInfo("Using insecure connection."); } @@ -155,19 +152,17 @@ namespace communicator "", body); - const auto res = m_httpClient->PerformHttpRequest(reqParams); - const auto res_status = std::get<0>(res); - const auto res_message = std::get<1>(res); + const auto [statusCode, respondeBody] = m_httpClient->PerformHttpRequest(reqParams); - if (res_status < http_client::HTTP_CODE_OK || res_status >= http_client::HTTP_CODE_MULTIPLE_CHOICES) + if (statusCode < http_client::HTTP_CODE_OK || statusCode >= http_client::HTTP_CODE_MULTIPLE_CHOICES) { - if (res_status == http_client::HTTP_CODE_UNAUTHORIZED || res_status == http_client::HTTP_CODE_FORBIDDEN) + if (statusCode == http_client::HTTP_CODE_UNAUTHORIZED || statusCode == http_client::HTTP_CODE_FORBIDDEN) { std::string message {}; try { - message = nlohmann::json::parse(res_message).at("message").get_ref(); + message = nlohmann::json::parse(respondeBody).at("message").get_ref(); } catch (const std::exception& e) { @@ -179,13 +174,13 @@ namespace communicator throw std::runtime_error(message); } } - LogWarn("Error: {}.", res_status); + LogWarn("Error: {}.", statusCode); return std::nullopt; } try { - return nlohmann::json::parse(res_message).at("token").get_ref(); + return nlohmann::json::parse(respondeBody).at("token").get_ref(); } catch (const std::exception& e) { @@ -299,7 +294,7 @@ namespace communicator void Communicator::TryReAuthenticate() { - std::unique_lock lock(m_reAuthMutex, std::try_to_lock); + const std::unique_lock lock(m_reAuthMutex, std::try_to_lock); if (lock.owns_lock() && !m_isReAuthenticating.exchange(true)) { if (m_tokenExpTimer) @@ -333,23 +328,21 @@ namespace communicator m_verificationMode, *m_token); - const auto res = co_await m_httpClient->Co_PerformHttpRequest(reqParams); - const auto res_status = std::get<0>(res); - const auto res_message = std::get<1>(res); + const auto [statusCode, respondeBody] = co_await m_httpClient->Co_PerformHttpRequest(reqParams); - if (res_status >= http_client::HTTP_CODE_OK && res_status < http_client::HTTP_CODE_MULTIPLE_CHOICES) + if (statusCode >= http_client::HTTP_CODE_OK && statusCode < http_client::HTTP_CODE_MULTIPLE_CHOICES) { std::ofstream file(dstFilePath, std::ios::binary); if (file) { - file << res_message; + file << respondeBody; file.close(); downloaded = true; } } else { - if (res_status == http_client::HTTP_CODE_UNAUTHORIZED || res_status == http_client::HTTP_CODE_FORBIDDEN) + if (statusCode == http_client::HTTP_CODE_UNAUTHORIZED || statusCode == http_client::HTTP_CODE_FORBIDDEN) { TryReAuthenticate(); } @@ -401,26 +394,24 @@ namespace communicator reqParams.Token = *m_token; - const auto res = co_await m_httpClient->Co_PerformHttpRequest(reqParams); - const auto res_status = std::get<0>(res); - const auto res_message = std::get<1>(res); + const auto [statusCode, responseBody] = co_await m_httpClient->Co_PerformHttpRequest(reqParams); std::time_t timerSleep = A_SECOND_IN_MILLIS; - if (res_status >= http_client::HTTP_CODE_OK && res_status < http_client::HTTP_CODE_MULTIPLE_CHOICES) + if (statusCode >= http_client::HTTP_CODE_OK && statusCode < http_client::HTTP_CODE_MULTIPLE_CHOICES) { if (onSuccess != nullptr) { - onSuccess(messagesCount, res_message); + onSuccess(messagesCount, responseBody); } } else { - if (res_status == http_client::HTTP_CODE_UNAUTHORIZED || res_status == http_client::HTTP_CODE_FORBIDDEN) + if (statusCode == http_client::HTTP_CODE_UNAUTHORIZED || statusCode == http_client::HTTP_CODE_FORBIDDEN) { TryReAuthenticate(); } - if (res_status != http_client::HTTP_CODE_TIMEOUT) + if (statusCode != http_client::HTTP_CODE_TIMEOUT) { timerSleep = m_retryInterval; } diff --git a/src/agent/communicator/tests/communicator_test.cpp b/src/agent/communicator/tests/communicator_test.cpp index e77be51e60..44a2440b70 100644 --- a/src/agent/communicator/tests/communicator_test.cpp +++ b/src/agent/communicator/tests/communicator_test.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -46,11 +47,6 @@ namespace .sign(jwt::algorithm::hs256 {"secret"}); } - const auto MOCK_CONFIG_PARSER = std::make_shared(std::string(R"( - agent: - retry_interval: 1s - )")); - const auto MOCK_CONFIG_PARSER_LOOP = std::make_shared(std::string(R"( agent: retry_interval: 5 @@ -58,364 +54,245 @@ namespace events: batch_size: 1 )")); + + void SpawnCoroutine(std::function()> func) + { + boost::asio::io_context ioContext; + boost::asio::co_spawn(ioContext, std::move(func), boost::asio::detached); + ioContext.run(); + } } // namespace -TEST(CommunicatorTest, CommunicatorConstructor) +class CommunicatorTest : public ::testing::Test { - auto mockHttpClient = std::make_unique(); +protected: + void SetUp() override + { - auto configurationParser = std::make_shared(); + auto mockHttpClient = std::make_unique(); + m_mockHttpClientPtr = mockHttpClient.get(); + testing::Mock::AllowLeak(m_mockHttpClientPtr); + m_mockedToken = CreateToken(); - EXPECT_NO_THROW(communicator::Communicator communicator( - std::move(mockHttpClient), configurationParser, "uuid", "key", nullptr)); -} + m_communicator = std::make_shared( + std::move(mockHttpClient), MOCK_CONFIG_PARSER_LOOP, "uuid", "key", nullptr); + + EXPECT_CALL(*m_mockHttpClientPtr, PerformHttpRequest(testing::_)) + .WillRepeatedly(Invoke([token = m_mockedToken]() -> intStringTuple + { return {http_client::HTTP_CODE_OK, R"({"token":")" + token + R"("})"}; })); + } -TEST(CommunicatorTest, CommunicatorConstructorNoHttpClient) + void TearDown() override + { + m_mockedToken.clear(); + m_mockHttpClientPtr = nullptr; + m_communicator = nullptr; + } + + std::shared_ptr m_communicator = nullptr; + MockHttpClient* m_mockHttpClientPtr = nullptr; + std::string m_mockedToken; +}; + +TEST_F(CommunicatorTest, CommunicatorConstructor) { - auto configurationParser = std::make_shared(); + EXPECT_NO_THROW( + const communicator::Communicator communicator(std::make_unique(), + std::make_shared(), + "uuid", + "key", + nullptr)); +} - EXPECT_THROW(communicator::Communicator communicator(nullptr, configurationParser, "uuid", "key", nullptr), +TEST_F(CommunicatorTest, CommunicatorConstructorNoHttpClient) +{ + EXPECT_THROW(const communicator::Communicator communicator( + nullptr, std::make_shared(), "uuid", "key", nullptr), std::runtime_error); } -TEST(CommunicatorTest, CommunicatorConstructorNoConfigParser) +TEST_F(CommunicatorTest, CommunicatorConstructorNoConfigParser) { - auto mockHttpClient = std::make_unique(); - - EXPECT_THROW(communicator::Communicator communicator(std::move(mockHttpClient), nullptr, "uuid", "key", nullptr), + EXPECT_THROW(const communicator::Communicator communicator( + std::make_unique(), nullptr, "uuid", "key", nullptr), std::runtime_error); } -TEST(CommunicatorTest, StatelessMessageProcessingTask_FailedAuthenticationLeavesEmptyToken) +TEST_F(CommunicatorTest, StatelessMessageProcessingTask_FailedAuthenticationLeavesEmptyToken) { - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); - - // not really a leak, as its lifetime is managed by the Communicator - testing::Mock::AllowLeak(mockHttpClientPtr); - - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER_LOOP, "uuid", "key", nullptr); - - // A failed authentication won't return a token - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse {401, R"({"message":"Try again"})"}; - - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) + EXPECT_CALL(*m_mockHttpClientPtr, PerformHttpRequest(testing::_)) .WillOnce(Invoke( - [communicatorPtr, &expectedResponse]() -> intStringTuple + [this]() -> intStringTuple { - communicatorPtr->Stop(); - return expectedResponse; + m_communicator->Stop(); + + // A failed authentication won't return a token + return {http_client::HTTP_CODE_UNAUTHORIZED, R"({"message":"Try again"})"}; })); auto getMessagesCalled = false; auto onSuccessCalled = false; - boost::asio::io_context ioContext; - - boost::asio::co_spawn( - ioContext, - [communicatorPtr, &getMessagesCalled, &onSuccessCalled]() mutable -> boost::asio::awaitable + SpawnCoroutine( + [this, &getMessagesCalled, &onSuccessCalled]() mutable -> boost::asio::awaitable { - communicatorPtr->SendAuthenticationRequest(); - co_await communicatorPtr->StatelessMessageProcessingTask( + m_communicator->SendAuthenticationRequest(); + co_await m_communicator->StatelessMessageProcessingTask( [&getMessagesCalled](const size_t) -> boost::asio::awaitable { getMessagesCalled = true; co_return intStringTuple {1, std::string {"message"}}; }, [&onSuccessCalled](const int, const std::string&) { onSuccessCalled = true; }); - }(), - boost::asio::detached); - - ioContext.run(); + }); EXPECT_FALSE(getMessagesCalled); EXPECT_FALSE(onSuccessCalled); } -TEST(CommunicatorTest, StatelessMessageProcessingTask_CallsWithValidToken) +TEST_F(CommunicatorTest, StatelessMessageProcessingTask_CallsWithValidToken) { - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); - - // not really a leak, as its lifetime is managed by the Communicator - testing::Mock::AllowLeak(mockHttpClientPtr); - - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER_LOOP, "uuid", "key", nullptr); - - const auto mockedToken = CreateToken(); - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse1 {200, R"({"token":")" + mockedToken + R"("})"}; - - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) - .WillOnce(Invoke([communicatorPtr, &expectedResponse1]() -> intStringTuple { return expectedResponse1; })); - const auto reqParams = http_client::HttpRequestParams( http_client::MethodType::POST, "https://localhost:27000", "/api/v1/events/stateless", "", "none"); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse2 {200, "Dummy response"}; - - EXPECT_CALL(*mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, mockedToken, "message"))) + EXPECT_CALL(*m_mockHttpClientPtr, + Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, m_mockedToken, "message"))) .WillOnce(Invoke( - [communicatorPtr, &expectedResponse2]() -> boost::asio::awaitable + [this]() -> boost::asio::awaitable { - communicatorPtr->Stop(); - co_return expectedResponse2; + m_communicator->Stop(); + co_return intStringTuple {http_client::HTTP_CODE_OK, "Dummy response"}; })); auto getMessagesCalled = false; auto onSuccessCalled = false; - boost::asio::io_context ioContext; - - boost::asio::co_spawn( - ioContext, - [communicatorPtr, &getMessagesCalled, &onSuccessCalled]() mutable -> boost::asio::awaitable + SpawnCoroutine( + [this, &getMessagesCalled, &onSuccessCalled]() mutable -> boost::asio::awaitable { - communicatorPtr->SendAuthenticationRequest(); - co_await communicatorPtr->StatelessMessageProcessingTask( + m_communicator->SendAuthenticationRequest(); + co_await m_communicator->StatelessMessageProcessingTask( [&getMessagesCalled](const size_t) -> boost::asio::awaitable { getMessagesCalled = true; co_return intStringTuple {1, std::string {"message"}}; }, [&onSuccessCalled](const int, const std::string&) { onSuccessCalled = true; }); - }(), - boost::asio::detached); - - ioContext.run(); + }); EXPECT_TRUE(getMessagesCalled); EXPECT_TRUE(onSuccessCalled); } -TEST(CommunicatorTest, GetCommandsFromManager_CallsWithValidToken) +TEST_F(CommunicatorTest, GetCommandsFromManager_CallsWithValidToken) { - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); - - // not really a leak, as its lifetime is managed by the Communicator - testing::Mock::AllowLeak(mockHttpClientPtr); - - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER_LOOP, "uuid", "key", nullptr); - - const auto mockedToken = CreateToken(); - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse1 {200, R"({"token":")" + mockedToken + R"("})"}; - - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) - .WillOnce(Invoke([communicatorPtr, &expectedResponse1]() -> intStringTuple { return expectedResponse1; })); - const auto timeout = static_cast(11) * 60 * 1000; const auto reqParams = http_client::HttpRequestParams( http_client::MethodType::GET, "https://localhost:27000", "/api/v1/commands", "", "none", "", "", "", timeout); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse2 {200, "Dummy response"}; - - EXPECT_CALL(*mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, mockedToken, ""))) + EXPECT_CALL(*m_mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, m_mockedToken, ""))) .WillOnce(Invoke( - [communicatorPtr, &expectedResponse2]() -> boost::asio::awaitable + [this]() -> boost::asio::awaitable { - communicatorPtr->Stop(); - co_return expectedResponse2; + m_communicator->Stop(); + co_return intStringTuple {http_client::HTTP_CODE_OK, "Dummy response"}; })); auto onSuccessCalled = false; - boost::asio::io_context ioContext; - - boost::asio::co_spawn( - ioContext, - [communicatorPtr, &onSuccessCalled]() mutable -> boost::asio::awaitable + SpawnCoroutine( + [this, &onSuccessCalled]() mutable -> boost::asio::awaitable { - communicatorPtr->SendAuthenticationRequest(); - co_await communicatorPtr->GetCommandsFromManager([&onSuccessCalled](const int, const std::string&) - { onSuccessCalled = true; }); - }(), - boost::asio::detached); - - ioContext.run(); + m_communicator->SendAuthenticationRequest(); + co_await m_communicator->GetCommandsFromManager([&onSuccessCalled](const int, const std::string&) + { onSuccessCalled = true; }); + }); EXPECT_TRUE(onSuccessCalled); } -TEST(CommunicatorTest, GetCommandsFromManager_Failure) +TEST_F(CommunicatorTest, GetCommandsFromManager_Failure) { - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); - - // not really a leak, as its lifetime is managed by the Communicator - testing::Mock::AllowLeak(mockHttpClientPtr); - - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER_LOOP, "uuid", "key", nullptr); - - const auto mockedToken = CreateToken(); - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse1 {200, R"({"token":")" + mockedToken + R"("})"}; - - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) - .WillOnce(Invoke([communicatorPtr, &expectedResponse1]() -> intStringTuple { return expectedResponse1; })); - const auto timeout = static_cast(11) * 60 * 1000; const auto reqParams = http_client::HttpRequestParams( http_client::MethodType::GET, "https://localhost:27000", "/api/v1/commands", "", "none", "", "", "", timeout); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse2 {401, "Dummy response"}; - - EXPECT_CALL(*mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, mockedToken, ""))) + EXPECT_CALL(*m_mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, m_mockedToken, ""))) .WillOnce(Invoke( - [communicatorPtr, &expectedResponse2]() -> boost::asio::awaitable + [this]() -> boost::asio::awaitable { - communicatorPtr->Stop(); - co_return expectedResponse2; + m_communicator->Stop(); + co_return intStringTuple {http_client::HTTP_CODE_UNAUTHORIZED, "Dummy response"}; })); auto onSuccessCalled = false; - boost::asio::io_context ioContext; - - boost::asio::co_spawn( - ioContext, - [communicatorPtr, &onSuccessCalled]() mutable -> boost::asio::awaitable + SpawnCoroutine( + [this, &onSuccessCalled]() mutable -> boost::asio::awaitable { - communicatorPtr->SendAuthenticationRequest(); - co_await communicatorPtr->GetCommandsFromManager([&onSuccessCalled](const int, const std::string&) - { onSuccessCalled = true; }); - }(), - boost::asio::detached); - - ioContext.run(); + m_communicator->SendAuthenticationRequest(); + co_await m_communicator->GetCommandsFromManager([&onSuccessCalled](const int, const std::string&) + { onSuccessCalled = true; }); + }); EXPECT_FALSE(onSuccessCalled); } -TEST(CommunicatorTest, GetGroupConfigurationFromManager_Success) +TEST_F(CommunicatorTest, GetGroupConfigurationFromManager_Success) { - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); - - // not really a leak, as its lifetime is managed by the Communicator - testing::Mock::AllowLeak(mockHttpClientPtr); - - std::string groupName = "group1"; - std::string dstFilePath = "./test-output"; - - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER_LOOP, "uuid", "key", nullptr); - - const auto mockedToken = CreateToken(); - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse1 {200, R"({"token":")" + mockedToken + R"("})"}; - - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) - .WillOnce(Invoke([communicatorPtr, &expectedResponse1]() -> intStringTuple { return expectedResponse1; })); - const auto reqParams = http_client::HttpRequestParams( http_client::MethodType::GET, "https://localhost:27000", "/api/v1/files?file_name=group1.yml", "", "none"); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse2 {200, "Dummy response"}; - - EXPECT_CALL(*mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, mockedToken, ""))) - .WillOnce(Invoke([communicatorPtr, &expectedResponse2]() -> boost::asio::awaitable - { co_return expectedResponse2; })); + EXPECT_CALL(*m_mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, m_mockedToken, ""))) + .WillOnce(Invoke([]() -> boost::asio::awaitable + { co_return intStringTuple {http_client::HTTP_CODE_OK, "Dummy response"}; })); - std::future result; + auto result = false; - boost::asio::io_context ioContext; - boost::asio::co_spawn( - ioContext, - [&]() -> boost::asio::awaitable + SpawnCoroutine( + [this, &result]() -> boost::asio::awaitable { - communicatorPtr->SendAuthenticationRequest(); - bool value = co_await communicatorPtr->GetGroupConfigurationFromManager(groupName, dstFilePath); - std::promise promise; - promise.set_value(value); - result = promise.get_future(); - }, - boost::asio::detached); - - ioContext.run(); - EXPECT_TRUE(result.get()); -} - -TEST(CommunicatorTest, GetGroupConfigurationFromManager_Error) -{ - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); - - // not really a leak, as its lifetime is managed by the Communicator - testing::Mock::AllowLeak(mockHttpClientPtr); + m_communicator->SendAuthenticationRequest(); - std::string groupName = "group1"; - std::string dstFilePath = "dummy/non/existing/path"; + const std::string groupName = "group1"; + const std::string dstFilePath = "./test-output"; + result = co_await m_communicator->GetGroupConfigurationFromManager(groupName, dstFilePath); + }); - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER_LOOP, "uuid", "key", nullptr); - - const auto mockedToken = CreateToken(); - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse1 {200, R"({"token":")" + mockedToken + R"("})"}; - - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) - .WillOnce(Invoke([communicatorPtr, &expectedResponse1]() -> intStringTuple { return expectedResponse1; })); + EXPECT_TRUE(result); +} +TEST_F(CommunicatorTest, GetGroupConfigurationFromManager_Error) +{ const auto reqParams = http_client::HttpRequestParams( http_client::MethodType::GET, "https://localhost:27000", "/api/v1/files?file_name=group1.yml", "", "none"); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse2 {200, "Dummy response"}; + EXPECT_CALL(*m_mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, m_mockedToken, ""))) + .WillOnce(Invoke([]() -> boost::asio::awaitable + { co_return intStringTuple {http_client::HTTP_CODE_OK, "Dummy response"}; })); - EXPECT_CALL(*mockHttpClientPtr, Co_PerformHttpRequest(HttpRequestParamsCheck(reqParams, mockedToken, ""))) - .WillOnce(Invoke([communicatorPtr, &expectedResponse2]() -> boost::asio::awaitable - { co_return expectedResponse2; })); + auto result = false; - std::future result; - - boost::asio::io_context ioContext; - boost::asio::co_spawn( - ioContext, + SpawnCoroutine( [&]() -> boost::asio::awaitable { - communicatorPtr->SendAuthenticationRequest(); - bool value = co_await communicatorPtr->GetGroupConfigurationFromManager(groupName, dstFilePath); - std::promise promise; - promise.set_value(value); - result = promise.get_future(); - }, - boost::asio::detached); - - ioContext.run(); - EXPECT_FALSE(result.get()); -} + m_communicator->SendAuthenticationRequest(); -TEST(CommunicatorTest, AuthenticateWithUuidAndKey_Success) -{ - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const std::string groupName = "group1"; + const std::string dstFilePath = "dummy/non/existing/path"; + result = co_await m_communicator->GetGroupConfigurationFromManager(groupName, dstFilePath); + }); - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER, "uuid", "key", nullptr); + EXPECT_FALSE(result); +} - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse {200, R"({"token":"valid_token"})"}; +TEST_F(CommunicatorTest, AuthenticateWithUuidAndKey_Success) +{ + const intStringTuple expectedResponse {http_client::HTTP_CODE_OK, R"({"token":"valid_token"})"}; - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); + EXPECT_CALL(*m_mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); - const auto token = communicatorPtr->AuthenticateWithUuidAndKey(); + const auto token = m_communicator->AuthenticateWithUuidAndKey(); ASSERT_TRUE(token.has_value()); @@ -423,38 +300,24 @@ TEST(CommunicatorTest, AuthenticateWithUuidAndKey_Success) EXPECT_EQ(token.value(), "valid_token"); } -TEST(CommunicatorTest, AuthenticateWithUuidAndKey_Failure) +TEST_F(CommunicatorTest, AuthenticateWithUuidAndKey_Failure) { - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const intStringTuple expectedResponse {http_client::HTTP_CODE_UNAUTHORIZED, R"({"message":"Try again"})"}; - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER, "uuid", "key", nullptr); + EXPECT_CALL(*m_mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse {401, R"({"message":"Try again"})"}; - - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); - - const auto token = communicatorPtr->AuthenticateWithUuidAndKey(); + const auto token = m_communicator->AuthenticateWithUuidAndKey(); EXPECT_FALSE(token.has_value()); } -TEST(CommunicatorTest, AuthenticateWithUuidAndKey_FailureThrowsException) +TEST_F(CommunicatorTest, AuthenticateWithUuidAndKey_FailureThrowsException) { - auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); - - auto communicatorPtr = std::make_shared( - std::move(mockHttpClient), MOCK_CONFIG_PARSER, "uuid", "key", nullptr); - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - intStringTuple expectedResponse {401, R"({"message":"Invalid key"})"}; + const intStringTuple expectedResponse {http_client::HTTP_CODE_UNAUTHORIZED, R"({"message":"Invalid key"})"}; - EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); + EXPECT_CALL(*m_mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); - EXPECT_THROW(communicatorPtr->AuthenticateWithUuidAndKey(), std::runtime_error); + EXPECT_THROW(m_communicator->AuthenticateWithUuidAndKey(), std::runtime_error); } int main(int argc, char** argv) diff --git a/src/agent/configuration_parser/src/configuration_parser.cpp b/src/agent/configuration_parser/src/configuration_parser.cpp index 88ce734b40..fd5d4ed588 100644 --- a/src/agent/configuration_parser/src/configuration_parser.cpp +++ b/src/agent/configuration_parser/src/configuration_parser.cpp @@ -63,7 +63,7 @@ namespace configuration { try { - YAML::Node mapToValidte = YAML::LoadFile(configFile.string()); + const YAML::Node mapToValidte = YAML::LoadFile(configFile.string()); if (!mapToValidte.IsMap() && !mapToValidte.IsSequence()) { throw std::runtime_error("The file does not contain a valid YAML structure."); @@ -97,7 +97,7 @@ namespace configuration LogDebug("Loading group configuration file: {}.", groupFile.string()); - YAML::Node fileToAppend = YAML::LoadFile(groupFile.string()); + const YAML::Node fileToAppend = YAML::LoadFile(groupFile.string()); if (!tmpConfig.IsDefined() || tmpConfig.IsNull()) { diff --git a/src/agent/configuration_parser/src/yaml_utils.cpp b/src/agent/configuration_parser/src/yaml_utils.cpp index 5c5fff6b8f..14d30fa15c 100644 --- a/src/agent/configuration_parser/src/yaml_utils.cpp +++ b/src/agent/configuration_parser/src/yaml_utils.cpp @@ -20,7 +20,7 @@ void MergeYamlNodes(YAML::Node& baseYaml, const YAML::Node& additionalYaml) for (auto it = additionalNode.begin(); it != additionalNode.end(); ++it) { const auto key = it->first.as(); - YAML::Node value = it->second; + const YAML::Node value = it->second; if (baseNode[key]) { diff --git a/src/agent/configuration_parser/tests/configuration_parser_test.cpp b/src/agent/configuration_parser/tests/configuration_parser_test.cpp index 39ed6c74ff..3ad31534cc 100644 --- a/src/agent/configuration_parser/tests/configuration_parser_test.cpp +++ b/src/agent/configuration_parser/tests/configuration_parser_test.cpp @@ -89,7 +89,7 @@ class ConfigurationParserInvalidYamlFileTest : public ::testing::Test // NOLINTBEGIN(bugprone-unchecked-optional-access) TEST(ConfigurationParser, GetConfigOrDefaultString) { - std::string strConfig = R"( + const std::string strConfig = R"( agent: server_url: 192.168.0.11 string_conf: string @@ -101,7 +101,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultString) TEST(ConfigurationParser, GetConfigOrDefaultArrayString) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -116,7 +116,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultArrayString) TEST(ConfigurationParser, GetConfigOrDefaultInt) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -130,7 +130,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultInt) TEST(ConfigurationParser, GetConfigOrDefaultMilliseconds) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -144,7 +144,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultMilliseconds) TEST(ConfigurationParser, GetConfigOrDefaultSeconds) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -158,7 +158,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultSeconds) TEST(ConfigurationParser, GetConfigOrDefaultMinutes) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -172,7 +172,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultMinutes) TEST(ConfigurationParser, GetConfigOrDefaultHours) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -186,7 +186,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultHours) TEST(ConfigurationParser, GetConfigOrDefaultDays) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -200,7 +200,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultDays) TEST(ConfigurationParser, GetConfigOrDefaultTimeInvalid) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -213,7 +213,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultTimeInvalid) TEST(ConfigurationParser, GetConfigOrDefaultFloat) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -227,7 +227,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultFloat) TEST(ConfigurationParser, GetConfigOrDefaultNoKey) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -240,7 +240,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultNoKey) TEST(ConfigurationParser, GetConfigOrDefaultIntSubTable) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -256,7 +256,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultIntSubTable) TEST(ConfigurationParser, GetConfigOrDefaultBoolSubTable) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -273,7 +273,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultBoolSubTable) TEST(ConfigurationParser, GetConfigOrDefaultArrayMap) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -296,7 +296,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultArrayMap) TEST(ConfigurationParser, GetConfigOrDefaultMap) { - std::string strConfig = R"( + const std::string strConfig = R"( map_string: string_conf_1: string_1 string_conf_2: string_2 @@ -309,7 +309,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultMap) TEST(ConfigurationParser, GetConfigOrDefaultBadCast) { - std::string strConfig = R"( + const std::string strConfig = R"( bad_cast_array: string_conf_1: string_1 int_conf: 10 @@ -321,7 +321,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultBadCast) TEST(ConfigurationParser, GetConfigOrDefaultMultiNode) { - std::string strConfig = R"( + const std::string strConfig = R"( agent_array: array_manager_ip: - 192.168.0.0 @@ -351,7 +351,7 @@ TEST(ConfigurationParser, GetConfigOrDefaultMultiNode) TEST(ConfigurationParser, ConfigurationParserStringMisaligned) { - std::string strConfig = R"( + const std::string strConfig = R"( users: - name: Alice - name: Bob @@ -412,7 +412,7 @@ TEST_F(ConfigurationParserFileTest, isValidYamlFileValid) TEST(ConfigurationParser, GetConfigOrDefaultBytes) { // Config should contain batch_size string in order to apply parsing - std::string strConfig = R"( + const std::string strConfig = R"( batch_size: size_bytes: 500B size_KB: 45KB diff --git a/src/agent/configuration_parser/tests/yaml_utils_test.cpp b/src/agent/configuration_parser/tests/yaml_utils_test.cpp index 804a79fdf7..96830c8460 100644 --- a/src/agent/configuration_parser/tests/yaml_utils_test.cpp +++ b/src/agent/configuration_parser/tests/yaml_utils_test.cpp @@ -11,7 +11,7 @@ TEST(MergeYamlNodesTest, MergeSimpleMaps) key1: value1 key2: value2 )"); - YAML::Node additional = YAML::Load(R"( + const YAML::Node additional = YAML::Load(R"( key3: value3 key4: value4 )"); @@ -31,7 +31,7 @@ TEST(MergeYamlNodesTest, OverrideScalarValue) key1: value1 key2: value2 )"); - YAML::Node additional = YAML::Load(R"( + const YAML::Node additional = YAML::Load(R"( key2: new_value )"); @@ -49,7 +49,7 @@ TEST(MergeYamlNodesTest, MergeNestedMaps) child1: value1 child2: value2 )"); - YAML::Node additional = YAML::Load(R"( + const YAML::Node additional = YAML::Load(R"( parent: child2: new_value child3: value3 @@ -71,7 +71,7 @@ TEST(MergeYamlNodesTest, MergeSequences) - item1 - item2 )"); - YAML::Node additional = YAML::Load(R"( + const YAML::Node additional = YAML::Load(R"( key: - item2 - item3 @@ -93,7 +93,7 @@ TEST(MergeYamlNodesTest, AddNewKeysToNestedMap) parent: child1: value1 )"); - YAML::Node additional = YAML::Load(R"( + const YAML::Node additional = YAML::Load(R"( parent: child2: value2 )"); @@ -109,7 +109,7 @@ TEST(MergeYamlNodesTest, AddNewKeysToNestedMap) TEST(MergeYamlNodesTest, BaseYamlEmpty) { YAML::Node base = YAML::Load("{}"); - YAML::Node additional = YAML::Load(R"( + const YAML::Node additional = YAML::Load(R"( key1: value1 key2: value2 )"); @@ -127,7 +127,7 @@ TEST(MergeYamlNodesTest, AdditionalYamlEmpty) key1: value1 key2: value2 )"); - YAML::Node additional = YAML::Load("{}"); + const YAML::Node additional = YAML::Load("{}"); MergeYamlNodes(base, additional); @@ -141,7 +141,7 @@ TEST(MergeYamlNodesTest, ScalarsOverwriteCorrectly) YAML::Node base = YAML::Load(R"( key: old_value )"); - YAML::Node additional = YAML::Load(R"( + const YAML::Node additional = YAML::Load(R"( key: new_value )"); diff --git a/src/agent/http_client/include/http_request_params.hpp b/src/agent/http_client/include/http_request_params.hpp index 186c3af0e5..992c6b4d02 100644 --- a/src/agent/http_client/include/http_request_params.hpp +++ b/src/agent/http_client/include/http_request_params.hpp @@ -52,8 +52,8 @@ namespace http_client HttpRequestParams(MethodType method, const std::string& serverUrl, std::string endpoint, - std::string userAgent = "", - std::string verificationMode = "none", + std::string userAgent, + std::string verificationMode, std::string token = "", std::string userPass = "", std::string body = "", diff --git a/src/agent/http_client/src/certificate/https_socket_verify_utils_lin.cpp b/src/agent/http_client/src/certificate/https_socket_verify_utils_lin.cpp index de27af7a94..2f4bd6e543 100644 --- a/src/agent/http_client/src/certificate/https_socket_verify_utils_lin.cpp +++ b/src/agent/http_client/src/certificate/https_socket_verify_utils_lin.cpp @@ -16,7 +16,7 @@ namespace https_socket_verify_utils } else if (mode == "full") { - boost::asio::ssl::rfc2818_verification verifier(host); + const boost::asio::ssl::rfc2818_verification verifier(host); return verifier(preverified, ctx); } return false; diff --git a/src/agent/http_client/src/http_client.cpp b/src/agent/http_client/src/http_client.cpp index 1fd9da5474..df63b77771 100644 --- a/src/agent/http_client/src/http_client.cpp +++ b/src/agent/http_client/src/http_client.cpp @@ -162,7 +162,7 @@ namespace http_client LogDebug("Request {}: Status {}", params.Endpoint, res.result_int()); LogTrace("{}", ResponseToString(params.Endpoint, res)); } - catch (std::exception const& e) + catch (const std::exception& e) { LogError("Error: {}. Endpoint: {}.", e.what(), params.Endpoint); @@ -233,7 +233,7 @@ namespace http_client LogDebug("Request {}: Status {}", params.Endpoint, res.result_int()); LogTrace("{}", ResponseToString(params.Endpoint, res)); } - catch (std::exception const& e) + catch (const std::exception& e) { LogError("Error: {}. Endpoint: {}.", e.what(), params.Endpoint); diff --git a/src/agent/http_client/src/http_socket.hpp b/src/agent/http_client/src/http_socket.hpp index baf4b795e6..2c9c857d4c 100644 --- a/src/agent/http_client/src/http_socket.hpp +++ b/src/agent/http_client/src/http_socket.hpp @@ -75,6 +75,6 @@ namespace http_client std::shared_ptr m_socket; /// @brief Timeout in milliseconds used in every operation - std::chrono::milliseconds m_timeout {http_client::SOCKET_TIMEOUT_MSECS}; + std::chrono::milliseconds m_timeout {http_client::SOCKET_TIMEOUT}; }; } // namespace http_client diff --git a/src/agent/http_client/src/http_socket_wrapper.hpp b/src/agent/http_client/src/http_socket_wrapper.hpp index 92eaf67107..3b8b658794 100644 --- a/src/agent/http_client/src/http_socket_wrapper.hpp +++ b/src/agent/http_client/src/http_socket_wrapper.hpp @@ -35,7 +35,7 @@ namespace http_client void connect(const boost::asio::ip::tcp::resolver::results_type& endpoints, boost::system::error_code& ec) override { - m_socket.async_connect(endpoints, [&ec](boost::system::error_code const& code, auto const&) { ec = code; }); + m_socket.async_connect(endpoints, [&ec](const boost::system::error_code& code, const auto&) { ec = code; }); } boost::asio::awaitable async_connect(const boost::asio::ip::tcp::resolver::results_type& endpoints, diff --git a/src/agent/http_client/src/https_socket.hpp b/src/agent/http_client/src/https_socket.hpp index 97cd821ffd..bbb5c8ebe1 100644 --- a/src/agent/http_client/src/https_socket.hpp +++ b/src/agent/http_client/src/https_socket.hpp @@ -84,6 +84,6 @@ namespace http_client std::shared_ptr m_ssl_socket; /// @brief Timeout in milliseconds used in every operation - std::chrono::milliseconds m_timeout {http_client::SOCKET_TIMEOUT_MSECS}; + std::chrono::milliseconds m_timeout {http_client::SOCKET_TIMEOUT}; }; } // namespace http_client diff --git a/src/agent/http_client/src/https_socket_wrapper.hpp b/src/agent/http_client/src/https_socket_wrapper.hpp index 62419385e5..d159c62185 100644 --- a/src/agent/http_client/src/https_socket_wrapper.hpp +++ b/src/agent/http_client/src/https_socket_wrapper.hpp @@ -42,7 +42,7 @@ namespace http_client boost::system::error_code& ec) override { m_socket.next_layer().async_connect(endpoints, - [this, &ec](boost::system::error_code const& ecConnect, auto const&) + [this, &ec](const boost::system::error_code& ecConnect, const auto&) { ec = ecConnect; if (ec) diff --git a/src/agent/http_client/src/ihttp_socket.hpp b/src/agent/http_client/src/ihttp_socket.hpp index ad92eed32d..84712208a9 100644 --- a/src/agent/http_client/src/ihttp_socket.hpp +++ b/src/agent/http_client/src/ihttp_socket.hpp @@ -5,12 +5,13 @@ #include #include +#include #include namespace http_client { - /// @brief The socket timeout in milliseconds - constexpr int SOCKET_TIMEOUT_MSECS = 60000; + /// @brief The socket timeout + constexpr auto SOCKET_TIMEOUT = std::chrono::milliseconds {60 * 1000}; /// @brief Interface for HTTP sockets class IHttpSocket diff --git a/src/agent/http_client/tests/http_client_test.cpp b/src/agent/http_client/tests/http_client_test.cpp index 8185f322ee..760c47eb99 100644 --- a/src/agent/http_client/tests/http_client_test.cpp +++ b/src/agent/http_client/tests/http_client_test.cpp @@ -2,6 +2,7 @@ #include #include +#include #include "mocks/mock_http_resolver.hpp" #include "mocks/mock_http_resolver_factory.hpp" @@ -132,7 +133,7 @@ TEST_F(HttpClientTest, PerformHttpRequest_Success_verification_full) http_client::MethodType::GET, "https://localhost:80", "/", "Wazuh 5.0.0", "full"); const auto response = client->PerformHttpRequest(params); - EXPECT_EQ(std::get<0>(response), 200); + EXPECT_EQ(std::get<0>(response), http_client::HTTP_CODE_OK); } TEST_F(HttpClientTest, PerformHttpRequest_Success_verification_certificate) @@ -150,7 +151,7 @@ TEST_F(HttpClientTest, PerformHttpRequest_Success_verification_certificate) http_client::MethodType::GET, "https://localhost:80", "/", "Wazuh 5.0.0", "certificate"); const auto response = client->PerformHttpRequest(params); - EXPECT_EQ(std::get<0>(response), 200); + EXPECT_EQ(std::get<0>(response), http_client::HTTP_CODE_OK); } TEST_F(HttpClientTest, PerformHttpRequest_Success_verification_none) @@ -168,7 +169,7 @@ TEST_F(HttpClientTest, PerformHttpRequest_Success_verification_none) http_client::MethodType::GET, "https://localhost:80", "/", "Wazuh 5.0.0", "none"); const auto response = client->PerformHttpRequest(params); - EXPECT_EQ(std::get<0>(response), 200); + EXPECT_EQ(std::get<0>(response), http_client::HTTP_CODE_OK); } TEST_F(HttpClientTest, PerformHttpRequest_ExceptionThrown) @@ -181,7 +182,7 @@ TEST_F(HttpClientTest, PerformHttpRequest_ExceptionThrown) http_client::MethodType::GET, "https://localhost:80", "/", "Wazuh 5.0.0", "full"); const auto response = client->PerformHttpRequest(params); - EXPECT_EQ(std::get<0>(response), 500); + EXPECT_EQ(std::get<0>(response), http_client::HTTP_CODE_INTERNAL_SERVER_ERROR); EXPECT_TRUE(std::get<1>(response).find("Simulated resolution failure") != std::string::npos); } @@ -255,7 +256,7 @@ TEST_F(HttpClientTest, Co_PerformHttpRequest_CallbacksNotCalledIfCannotConnect) const auto res = response.get(); - EXPECT_EQ(std::get<0>(res), 500); + EXPECT_EQ(std::get<0>(res), http_client::HTTP_CODE_INTERNAL_SERVER_ERROR); EXPECT_EQ(std::get<1>(res), "Internal server error: Error connecting to host: Bad address"); } @@ -289,7 +290,7 @@ TEST_F(HttpClientTest, Co_PerformHttpRequest_OnSuccessNotCalledIfAsyncWriteFails const auto res = response.get(); - EXPECT_EQ(std::get<0>(res), 500); + EXPECT_EQ(std::get<0>(res), http_client::HTTP_CODE_INTERNAL_SERVER_ERROR); EXPECT_EQ(std::get<1>(res), "Internal server error: Error writing request: Bad address"); } @@ -325,7 +326,7 @@ TEST_F(HttpClientTest, Co_PerformHttpRequest_OnSuccessNotCalledIfAsyncReadFails) const auto res = response.get(); - EXPECT_EQ(std::get<0>(res), 500); + EXPECT_EQ(std::get<0>(res), http_client::HTTP_CODE_INTERNAL_SERVER_ERROR); EXPECT_EQ(std::get<1>(res), "Internal server error: Error handling response: Bad address"); } diff --git a/src/agent/http_client/tests/http_socket_test.cpp b/src/agent/http_client/tests/http_socket_test.cpp index 164dc10ad9..f4823954f5 100644 --- a/src/agent/http_client/tests/http_socket_test.cpp +++ b/src/agent/http_client/tests/http_socket_test.cpp @@ -329,7 +329,7 @@ TEST_F(HttpSocketTest, AsyncReadSuccess) boost::beast::http::response res; res.result(boost::beast::http::status::ok); - EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT_MSECS))).Times(1); + EXPECT_CALL(*m_mockHelper, expires_after(http_client::SOCKET_TIMEOUT)).Times(1); EXPECT_CALL(*m_mockHelper, async_read(testing::_, testing::_, testing::_)) .WillOnce( [](boost::beast::flat_buffer&, @@ -357,7 +357,7 @@ TEST_F(HttpSocketTest, AsyncReadFailure) boost::beast::http::response res; res.result(boost::beast::http::status::ok); - EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT_MSECS))).Times(1); + EXPECT_CALL(*m_mockHelper, expires_after(http_client::SOCKET_TIMEOUT)).Times(1); EXPECT_CALL(*m_mockHelper, async_read(testing::_, testing::_, testing::_)) .WillOnce( [](boost::beast::flat_buffer&, @@ -384,7 +384,7 @@ TEST_F(HttpSocketTest, AsyncReadException) boost::beast::http::response res; res.result(boost::beast::http::status::ok); - EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT_MSECS))).Times(1); + EXPECT_CALL(*m_mockHelper, expires_after(http_client::SOCKET_TIMEOUT)).Times(1); EXPECT_CALL(*m_mockHelper, async_read(testing::_, testing::_, testing::_)) .WillOnce([](boost::beast::flat_buffer&, boost::beast::http::response&, diff --git a/src/agent/http_client/tests/https_socket_test.cpp b/src/agent/http_client/tests/https_socket_test.cpp index d79a085cc1..6b9df77946 100644 --- a/src/agent/http_client/tests/https_socket_test.cpp +++ b/src/agent/http_client/tests/https_socket_test.cpp @@ -312,7 +312,7 @@ TEST_F(HttpsSocketTest, ReadException) boost::beast::http::response res; res.result(boost::beast::http::status::ok); - EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT_MSECS))).Times(1); + EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT))).Times(1); EXPECT_CALL(*m_mockHelper, read(_, _, _)) .WillOnce([](boost::beast::flat_buffer&, boost::beast::http::response&, @@ -329,7 +329,7 @@ TEST_F(HttpsSocketTest, AsyncReadSuccess) boost::beast::http::response res; res.result(boost::beast::http::status::ok); - EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT_MSECS))).Times(1); + EXPECT_CALL(*m_mockHelper, expires_after(http_client::SOCKET_TIMEOUT)).Times(1); EXPECT_CALL(*m_mockHelper, async_read(testing::_, testing::_, testing::_)) .WillOnce( [](boost::beast::flat_buffer&, @@ -357,7 +357,7 @@ TEST_F(HttpsSocketTest, AsyncReadFailure) boost::beast::http::response res; res.result(boost::beast::http::status::ok); - EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT_MSECS))).Times(1); + EXPECT_CALL(*m_mockHelper, expires_after(http_client::SOCKET_TIMEOUT)).Times(1); EXPECT_CALL(*m_mockHelper, async_read(testing::_, testing::_, testing::_)) .WillOnce( [](boost::beast::flat_buffer&, @@ -384,7 +384,7 @@ TEST_F(HttpsSocketTest, AsyncReadException) boost::beast::http::response res; res.result(boost::beast::http::status::ok); - EXPECT_CALL(*m_mockHelper, expires_after(std::chrono::milliseconds(http_client::SOCKET_TIMEOUT_MSECS))).Times(1); + EXPECT_CALL(*m_mockHelper, expires_after(http_client::SOCKET_TIMEOUT)).Times(1); EXPECT_CALL(*m_mockHelper, async_read(testing::_, testing::_, testing::_)) .WillOnce([](boost::beast::flat_buffer&, boost::beast::http::response&, diff --git a/src/agent/multitype_queue/src/storage.cpp b/src/agent/multitype_queue/src/storage.cpp index dc3787fe10..39b829c354 100644 --- a/src/agent/multitype_queue/src/storage.cpp +++ b/src/agent/multitype_queue/src/storage.cpp @@ -27,10 +27,10 @@ namespace for (const auto& row : rows) { - std::string moduleNameString = row[0].Value; - std::string moduleTypeString = row[1].Value; - std::string metadataString = row[2].Value; - std::string dataString = row[3].Value; + const std::string moduleNameString = row[0].Value; + const std::string moduleTypeString = row[1].Value; + const std::string metadataString = row[2].Value; + const std::string dataString = row[3].Value; nlohmann::json outputJson = {{"moduleName", ""}, {"moduleType", ""}, {"metadata", ""}, {"data", {}}}; @@ -57,8 +57,8 @@ namespace messages.push_back(outputJson); if (maxSize) { - size_t messageSize = moduleNameString.size() + moduleTypeString.size() + metadataString.size() + - outputJson["data"].dump().size(); + const size_t messageSize = moduleNameString.size() + moduleTypeString.size() + metadataString.size() + + outputJson["data"].dump().size(); if (sizeAccum + messageSize >= maxSize) { break; @@ -144,7 +144,7 @@ int Storage::Store(const nlohmann::json& message, int result = 0; - std::unique_lock lock(m_mutex); + const std::unique_lock lock(m_mutex); auto transaction = m_db->BeginTransaction(); @@ -199,7 +199,7 @@ int Storage::RemoveMultiple(int n, int result = 0; - std::unique_lock lock(m_mutex); + const std::unique_lock lock(m_mutex); auto transaction = m_db->BeginTransaction(); diff --git a/src/agent/multitype_queue/tests/multitype_queue_test.cpp b/src/agent/multitype_queue/tests/multitype_queue_test.cpp index 94f8d2f2aa..25ade9bfde 100644 --- a/src/agent/multitype_queue/tests/multitype_queue_test.cpp +++ b/src/agent/multitype_queue/tests/multitype_queue_test.cpp @@ -143,12 +143,12 @@ TEST_F(MultiTypeQueueTest, Constructor) { auto configurationParser = std::make_shared(); - EXPECT_NO_THROW(MultiTypeQueue multiTypeQueue(configurationParser)); + EXPECT_NO_THROW(const MultiTypeQueue multiTypeQueue(configurationParser)); } TEST_F(MultiTypeQueueTest, ConstructorNoConfigParser) { - EXPECT_THROW(MultiTypeQueue multiTypeQueue(nullptr), std::runtime_error); + EXPECT_THROW(const MultiTypeQueue multiTypeQueue(nullptr), std::runtime_error); } // Push, get and check the queue is not empty @@ -229,15 +229,15 @@ TEST_F(MultiTypeQueueTest, SinglePushPopFullWithTimeout) // complete the queue with messages const MessageType messageType {MessageType::COMMAND}; - int upperLimit = SMALL_QUEUE_CAPACITY + 1; - for (int i : std::views::iota(1, upperLimit)) + const int upperLimit = SMALL_QUEUE_CAPACITY + 1; + for (const int i : std::views::iota(1, upperLimit)) { const nlohmann::json dataContent = R"({"Data" : "for COMMAND)" + std::to_string(i) + R"("})"; EXPECT_EQ(multiTypeQueue.push({messageType, dataContent}), 1); } const nlohmann::json dataContent = R"({"Data" : "for COMMAND3"})"; - Message exampleMessage {messageType, dataContent}; + const Message exampleMessage {messageType, dataContent}; EXPECT_EQ(multiTypeQueue.push({messageType, dataContent}, true), 0); auto items = multiTypeQueue.storedItems(MessageType::COMMAND); @@ -384,7 +384,7 @@ TEST_F(MultiTypeQueueTest, PushMultipleSeveralSingleGets) EXPECT_EQ(3, multiTypeQueue.push(messageToSend)); - for (size_t i : {0u, 1u, 2u}) + for (const size_t i : {0u, 1u, 2u}) { auto messageResponse = multiTypeQueue.getNext(MessageType::STATELESS); auto responseData = messageResponse.data; @@ -402,7 +402,7 @@ TEST_F(MultiTypeQueueTest, PushMultipleWithMessageVector) std::vector messages; const MessageType messageType {MessageType::STATELESS}; - for (std::string i : {"0", "1", "2"}) + for (const std::string i : {"0", "1", "2"}) { const nlohmann::json multipleDataContent = {"content " + i}; messages.emplace_back(messageType, multipleDataContent); @@ -425,7 +425,7 @@ TEST_F(MultiTypeQueueTest, PushVectorWithAMultipleInside) messages.push_back(messageToSend); // triple message vector - for (std::string i : {"0", "1", "2"}) + for (const std::string i : {"0", "1", "2"}) { const nlohmann::json dataContent = {"content " + i}; messages.emplace_back(messageType, dataContent); @@ -454,8 +454,8 @@ TEST_F(MultiTypeQueueTest, PushAwaitable) MultiTypeQueue multiTypeQueue(MOCK_CONFIG_PARSER_SMALL_SIZE); boost::asio::io_context io_context; - int upperLimit = SMALL_QUEUE_CAPACITY + 1; - for (int i : std::views::iota(1, upperLimit)) + const int upperLimit = SMALL_QUEUE_CAPACITY + 1; + for (const int i : std::views::iota(1, upperLimit)) { const nlohmann::json dataContent = R"({"Data" : "for STATEFUL)" + std::to_string(i) + R"("})"; EXPECT_EQ(multiTypeQueue.push({MessageType::STATEFUL, dataContent}), 1); @@ -501,15 +501,14 @@ TEST_F(MultiTypeQueueTest, FifoOrderCheck) // complete the queue with messages const MessageType messageType {MessageType::STATEFUL}; size_t contentSize = 0; - for (int i : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) + for (const int i : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) { const nlohmann::json dataContent = {{"Data", "for STATEFUL" + std::to_string(i)}}; EXPECT_EQ(multiTypeQueue.push({messageType, dataContent}), 1); contentSize += dataContent.dump().size(); } - auto messageReceivedVector = - multiTypeQueue.getNextBytes(messageType, contentSize); // NOLINT(cppcoreguidelines-avoid-magic-numbers) + const auto messageReceivedVector = multiTypeQueue.getNextBytes(messageType, contentSize); EXPECT_EQ(messageReceivedVector.size(), 10); std::for_each(messageReceivedVector.begin(), @@ -519,7 +518,7 @@ TEST_F(MultiTypeQueueTest, FifoOrderCheck) }); // Keep the order of the message: FIFO - for (int i : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) + for (const int i : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) { auto messageReceived = multiTypeQueue.getNextBytes(messageType, 1); EXPECT_EQ(messageReceived[0].data, (nlohmann::json {{"Data", "for STATEFUL" + std::to_string(i)}})); @@ -546,7 +545,7 @@ TEST_F(MultiTypeQueueTest, GetBySizeAboveMax) // Duplicate to surpass the maximun sizeAsked *= 2; - auto messagesReceived = multiTypeQueue.getNextBytes(MessageType::STATELESS, sizeAsked); + const auto messagesReceived = multiTypeQueue.getNextBytes(MessageType::STATELESS, sizeAsked); int i = 0; for (const auto& singleMessage : messagesReceived) { @@ -571,6 +570,6 @@ TEST_F(MultiTypeQueueTest, GetByBelowMax) // Fetching less than a single message size sizeAsked -= 1; - auto messagesReceived = multiTypeQueue.getNextBytes(MessageType::STATELESS, sizeAsked); + const auto messagesReceived = multiTypeQueue.getNextBytes(MessageType::STATELESS, sizeAsked); EXPECT_EQ(1, messagesReceived.size()); } diff --git a/src/agent/multitype_queue/tests/storage_test.cpp b/src/agent/multitype_queue/tests/storage_test.cpp index 542edef9cc..c97c14caf2 100644 --- a/src/agent/multitype_queue/tests/storage_test.cpp +++ b/src/agent/multitype_queue/tests/storage_test.cpp @@ -119,14 +119,14 @@ TEST_F(StorageTest, RemoveMultipleMessagesWithModule) TEST_F(StorageTest, GetElementCount) { - nlohmann::json message = {{"key", "value"}}; + const nlohmann::json message = {{"key", "value"}}; EXPECT_EQ(storage->Store(message, tableName), 1); EXPECT_EQ(storage->GetElementCount(tableName), 1); } TEST_F(StorageTest, GetElementCountWithModule) { - nlohmann::json message = {{"key", "value"}}; + const nlohmann::json message = {{"key", "value"}}; EXPECT_EQ(storage->Store(message, tableName, moduleName), 1); EXPECT_EQ(storage->GetElementCount(tableName), 1); EXPECT_EQ(storage->GetElementCount(tableName, moduleName), 1); diff --git a/src/agent/persistence/src/sqlite_manager.cpp b/src/agent/persistence/src/sqlite_manager.cpp index 2c97eb15a5..8b78f5e012 100644 --- a/src/agent/persistence/src/sqlite_manager.cpp +++ b/src/agent/persistence/src/sqlite_manager.cpp @@ -51,7 +51,7 @@ bool SQLiteManager::TableExists(const std::string& table) { try { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); SQLite::Statement query(*m_db, "SELECT name FROM sqlite_master WHERE type='table' AND name='" + table + "';"); return query.executeStep(); } @@ -68,7 +68,7 @@ void SQLiteManager::CreateTable(const std::string& tableName, const Keys& cols) std::vector fields; for (const auto& col : cols) { - std::string field = fmt::format( + const std::string field = fmt::format( "{} {}{}", col.Name, MAP_COL_TYPE_STRING.at(col.Type), (col.Attributes & NOT_NULL) ? " NOT NULL" : ""); if (col.Attributes & PRIMARY_KEY) { @@ -78,7 +78,7 @@ void SQLiteManager::CreateTable(const std::string& tableName, const Keys& cols) } std::string primaryKey = pk.empty() ? "" : fmt::format(", PRIMARY KEY({})", fmt::join(pk, ", ")); - std::string queryString = fmt::format( + const std::string queryString = fmt::format( "CREATE TABLE IF NOT EXISTS {} ({}{})", tableName, fmt::format("{}", fmt::join(fields, ", ")), primaryKey); Execute(queryString); @@ -103,7 +103,7 @@ void SQLiteManager::Insert(const std::string& tableName, const Row& cols) } } - std::string queryString = + const std::string queryString = fmt::format("INSERT INTO {} ({}) VALUES ({})", tableName, fmt::join(names, ", "), fmt::join(values, ", ")); Execute(queryString); @@ -154,7 +154,7 @@ void SQLiteManager::Update(const std::string& tableName, whereClause = fmt::format(" WHERE {}", fmt::join(conditions, fmt::format(" {} ", MAP_LOGOP_STRING.at(logOp)))); } - std::string queryString = fmt::format("UPDATE {} SET {}{}", tableName, updateValues, whereClause); + const std::string queryString = fmt::format("UPDATE {} SET {}{}", tableName, updateValues, whereClause); Execute(queryString); } @@ -180,14 +180,14 @@ void SQLiteManager::Remove(const std::string& tableName, const Criteria& selCrit whereClause = fmt::format(" WHERE {}", fmt::join(critFields, fmt::format(" {} ", MAP_LOGOP_STRING.at(logOp)))); } - std::string queryString = fmt::format("DELETE FROM {}{}", tableName, whereClause); + const std::string queryString = fmt::format("DELETE FROM {}{}", tableName, whereClause); Execute(queryString); } void SQLiteManager::DropTable(const std::string& tableName) { - std::string queryString = fmt::format("DROP TABLE {}", tableName); + const std::string queryString = fmt::format("DROP TABLE {}", tableName); Execute(queryString); } @@ -196,7 +196,7 @@ void SQLiteManager::Execute(const std::string& query) { try { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); m_db->exec(query); } catch (const std::exception& e) @@ -267,17 +267,17 @@ std::vector SQLiteManager::Select(const std::string& tableName, condition += fmt::format(" LIMIT {}", limit); } - std::string queryString = fmt::format("SELECT {} FROM {} {}", selectedFields, tableName, condition); + const std::string queryString = fmt::format("SELECT {} FROM {} {}", selectedFields, tableName, condition); std::vector results; try { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); SQLite::Statement query(*m_db, queryString); while (query.executeStep()) { - int nColumns = query.getColumnCount(); + const int nColumns = query.getColumnCount(); Row queryFields; queryFields.reserve(static_cast(nColumns)); for (int i = 0; i < nColumns; i++) @@ -318,12 +318,12 @@ int SQLiteManager::GetCount(const std::string& tableName, const Criteria& selCri condition = fmt::format("WHERE {}", fmt::join(conditions, fmt::format(" {} ", MAP_LOGOP_STRING.at(logOp)))); } - std::string queryString = fmt::format("SELECT COUNT(*) FROM {} {}", tableName, condition); + const std::string queryString = fmt::format("SELECT COUNT(*) FROM {} {}", tableName, condition); int count = 0; try { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); SQLite::Statement query(*m_db, queryString); if (query.executeStep()) @@ -383,13 +383,13 @@ size_t SQLiteManager::GetSize(const std::string& tableName, condition = fmt::format("WHERE {}", fmt::join(conditions, fmt::format(" {} ", MAP_LOGOP_STRING.at(logOp)))); } - std::string queryString = + const std::string queryString = fmt::format("SELECT SUM({}) AS total_bytes FROM {} {}", selectedFields, tableName, condition); size_t count = 0; try { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); SQLite::Statement query(*m_db, queryString); if (query.executeStep()) diff --git a/src/agent/persistence/tests/sqlite_manager_test.cpp b/src/agent/persistence/tests/sqlite_manager_test.cpp index 754d17d1ff..fca59ab03e 100644 --- a/src/agent/persistence/tests/sqlite_manager_test.cpp +++ b/src/agent/persistence/tests/sqlite_manager_test.cpp @@ -56,30 +56,30 @@ class SQLiteManagerTest : public ::testing::Test TEST_F(SQLiteManagerTest, CreateTableTest) { - ColumnKey col1 {"Id", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY | AUTO_INCREMENT}; - ColumnKey col2 {"Name", ColumnType::TEXT, NOT_NULL}; - ColumnKey col3 {"Status", ColumnType::TEXT, NOT_NULL}; - ColumnKey col4 {"Module", ColumnType::TEXT}; - ColumnKey col5 {"Orden", ColumnType::INTEGER}; - ColumnKey col6 {"Amount", ColumnType::REAL}; + const ColumnKey col1 {"Id", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY | AUTO_INCREMENT}; + const ColumnKey col2 {"Name", ColumnType::TEXT, NOT_NULL}; + const ColumnKey col3 {"Status", ColumnType::TEXT, NOT_NULL}; + const ColumnKey col4 {"Module", ColumnType::TEXT}; + const ColumnKey col5 {"Orden", ColumnType::INTEGER}; + const ColumnKey col6 {"Amount", ColumnType::REAL}; EXPECT_NO_THROW(m_db->CreateTable(m_tableName, {col1, col2, col3, col4, col5, col6})); EXPECT_TRUE(m_db->TableExists(m_tableName)); - ColumnKey col21 {"Id", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY}; - ColumnKey col212 {"Id2", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY}; - ColumnKey col22 {"Name", ColumnType::TEXT, NOT_NULL | PRIMARY_KEY}; - ColumnKey col23 {"Status", ColumnType::TEXT, NOT_NULL}; - ColumnKey col24 {"Module", ColumnType::TEXT}; - ColumnKey col25 {"Orden", ColumnType::INTEGER}; - ColumnKey col26 {"Amount", ColumnType::REAL}; + const ColumnKey col21 {"Id", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY}; + const ColumnKey col212 {"Id2", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY}; + const ColumnKey col22 {"Name", ColumnType::TEXT, NOT_NULL | PRIMARY_KEY}; + const ColumnKey col23 {"Status", ColumnType::TEXT, NOT_NULL}; + const ColumnKey col24 {"Module", ColumnType::TEXT}; + const ColumnKey col25 {"Orden", ColumnType::INTEGER}; + const ColumnKey col26 {"Amount", ColumnType::REAL}; EXPECT_NO_THROW(m_db->CreateTable("TableTest2", {col21, col212, col22, col23, col24, col25, col26})); EXPECT_TRUE(m_db->TableExists("TableTest2")); } TEST_F(SQLiteManagerTest, InsertTest) { - ColumnValue col1 {"Name", ColumnType::TEXT, "ItemName1"}; - ColumnValue col2 {"Status", ColumnType::TEXT, "ItemStatus1"}; + const ColumnValue col1 {"Name", ColumnType::TEXT, "ItemName1"}; + const ColumnValue col2 {"Status", ColumnType::TEXT, "ItemStatus1"}; EXPECT_NO_THROW(m_db->Insert(m_tableName, {col1, col2})); EXPECT_NO_THROW(m_db->Insert( @@ -110,8 +110,8 @@ TEST_F(SQLiteManagerTest, GetCountTest) int count = m_db->GetCount(m_tableName); EXPECT_EQ(count, 0); - ColumnValue col1 {"Name", ColumnType::TEXT, "ItemName1"}; - ColumnValue col2 {"Status", ColumnType::TEXT, "ItemStatus1"}; + const ColumnValue col1 {"Name", ColumnType::TEXT, "ItemName1"}; + const ColumnValue col2 {"Status", ColumnType::TEXT, "ItemStatus1"}; EXPECT_NO_THROW(m_db->Insert(m_tableName, {col1, col2})); count = m_db->GetCount(m_tableName); @@ -126,11 +126,11 @@ TEST_F(SQLiteManagerTest, GetCountTest) TEST_F(SQLiteManagerTest, GetSizeTest) { EXPECT_NO_THROW(m_db->Remove(m_tableName)); - int count = m_db->GetCount(m_tableName); + const int count = m_db->GetCount(m_tableName); EXPECT_EQ(count, 0); - ColumnValue col1 {"Name", ColumnType::TEXT, "ItemName1"}; - ColumnValue col2 {"Status", ColumnType::TEXT, "ItemStatus1"}; + const ColumnValue col1 {"Name", ColumnType::TEXT, "ItemName1"}; + const ColumnValue col2 {"Status", ColumnType::TEXT, "ItemStatus1"}; EXPECT_NO_THROW(m_db->Insert(m_tableName, {col1, col2})); size_t size = m_db->GetSize(m_tableName, {ColumnName("Name", ColumnType::TEXT)}); @@ -284,7 +284,7 @@ TEST_F(SQLiteManagerTest, RemoveTest) { AddTestData(); - int initialCount = m_db->GetCount(m_tableName); + const int initialCount = m_db->GetCount(m_tableName); // Remove a single record EXPECT_NO_THROW(m_db->Remove( @@ -381,11 +381,11 @@ TEST_F(SQLiteManagerTest, TransactionTest) TEST_F(SQLiteManagerTest, DropTableTest) { - ColumnKey col1 {"Id", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY | AUTO_INCREMENT}; - ColumnKey col2 {"Name", ColumnType::TEXT, NOT_NULL}; - ColumnKey col3 {"Status", ColumnType::TEXT, NOT_NULL}; - ColumnKey col4 {"Module", ColumnType::TEXT}; - ColumnKey col5 {"Orden", ColumnType::INTEGER}; + const ColumnKey col1 {"Id", ColumnType::INTEGER, NOT_NULL | PRIMARY_KEY | AUTO_INCREMENT}; + const ColumnKey col2 {"Name", ColumnType::TEXT, NOT_NULL}; + const ColumnKey col3 {"Status", ColumnType::TEXT, NOT_NULL}; + const ColumnKey col4 {"Module", ColumnType::TEXT}; + const ColumnKey col5 {"Orden", ColumnType::INTEGER}; EXPECT_NO_THROW(m_db->CreateTable("DropMe", {col1, col2, col3, col4, col5})); EXPECT_TRUE(m_db->TableExists("DropMe")); diff --git a/src/agent/restart_handler/tests/restart_handler_tests.cpp b/src/agent/restart_handler/tests/restart_handler_tests.cpp index eee80b7da4..732b196711 100644 --- a/src/agent/restart_handler/tests/restart_handler_tests.cpp +++ b/src/agent/restart_handler/tests/restart_handler_tests.cpp @@ -62,7 +62,7 @@ TEST(StopAgentTest, GracefullyStop) testing::internal::CaptureStdout(); signal(SIGCHLD, SigchldHandler); - pid_t pid = fork(); + const pid_t pid = fork(); if (pid < 0) { @@ -81,7 +81,7 @@ TEST(StopAgentTest, GracefullyStop) const int timeout = 10; restart_handler::StopAgent(pid, timeout); - std::string stdout_logs = testing::internal::GetCapturedStdout(); + const std::string stdout_logs = testing::internal::GetCapturedStdout(); EXPECT_EQ(stdout_logs.find("Timeout reached! Forcing agent process termination."), std::string::npos); EXPECT_NE(stdout_logs.find("Agent stopped"), std::string::npos); } @@ -92,7 +92,7 @@ TEST(StopAgentTest, ForceStop) signal(SIGCHLD, SigchldHandler); signal(SIGTERM, SIG_IGN); // Ignore SIGTERM - pid_t pid = fork(); + const pid_t pid = fork(); if (pid < 0) { @@ -100,18 +100,18 @@ TEST(StopAgentTest, ForceStop) } if (pid == 0) { - // Child process (Simulate agent running) - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::this_thread::sleep_for(std::chrono::seconds(60)); + const auto sleepTime = std::chrono::seconds(60); + std::this_thread::sleep_for(sleepTime); } // Parent process - std::this_thread::sleep_for(std::chrono::seconds(1)); + const auto sleepTime = std::chrono::seconds(1); + std::this_thread::sleep_for(std::chrono::seconds(sleepTime)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - restart_handler::StopAgent(pid, 2); + const auto timeout = 2; + restart_handler::StopAgent(pid, timeout); - std::string stdout_logs = testing::internal::GetCapturedStdout(); + const auto stdout_logs = testing::internal::GetCapturedStdout(); EXPECT_NE(stdout_logs.find("Timeout reached! Forcing agent process termination."), std::string::npos); EXPECT_NE(stdout_logs.find("Agent stopped"), std::string::npos); } @@ -120,7 +120,7 @@ TEST(RestartWithForkTest, ShouldRestartUsingFork) { testing::internal::CaptureStdout(); - pid_t pid = fork(); + const pid_t pid = fork(); if (pid < 0) { @@ -153,7 +153,7 @@ TEST(RestartWithForkTest, ShouldRestartUsingFork) int status {}; waitpid(pid, &status, 0); - std::string stdout_logs = testing::internal::GetCapturedStdout(); + const std::string stdout_logs = testing::internal::GetCapturedStdout(); EXPECT_EQ(stdout_logs.find("Agent stopped"), std::string::npos); EXPECT_EQ(stdout_logs.find("Starting wazuh agent in a new process"), std::string::npos); } diff --git a/src/agent/src/agent.cpp b/src/agent/src/agent.cpp index 5e84f08bde..f19e1b2f9d 100644 --- a/src/agent/src/agent.cpp +++ b/src/agent/src/agent.cpp @@ -78,7 +78,7 @@ Agent::~Agent() void Agent::ReloadModules() { - std::lock_guard lock(m_reloadMutex); + const std::lock_guard lock(m_reloadMutex); if (m_running.load()) { @@ -168,14 +168,14 @@ void Agent::Run() "CommandsProcessing"); { - std::unique_lock lock(m_reloadMutex); + const std::unique_lock lock(m_reloadMutex); m_running.store(true); } m_signalHandler->WaitForSignal(); { - std::unique_lock lock(m_reloadMutex); + const std::unique_lock lock(m_reloadMutex); m_running.store(false); } diff --git a/src/agent/src/agent_registration.cpp b/src/agent/src/agent_registration.cpp index f372d94ed5..7f9f735101 100644 --- a/src/agent/src/agent_registration.cpp +++ b/src/agent/src/agent_registration.cpp @@ -64,12 +64,11 @@ namespace agent_registration "", m_agentInfo.GetMetadataInfo()); - const auto res = m_httpClient->PerformHttpRequest(reqParams); - const auto res_status = std::get<0>(res); + const auto [statusCode, statusMessage] = m_httpClient->PerformHttpRequest(reqParams); - if (res_status != http_client::HTTP_CODE_CREATED) + if (statusCode != http_client::HTTP_CODE_CREATED) { - std::cout << "Registration error: " << res_status << ".\n"; + std::cout << "Registration error: " << statusCode << ".\n"; return false; } @@ -87,19 +86,17 @@ namespace agent_registration "", m_user + ":" + m_password); - const auto res = m_httpClient->PerformHttpRequest(reqParams); - const auto res_status = std::get<0>(res); - const auto res_message = std::get<1>(res); + const auto [statusCode, statusMessage] = m_httpClient->PerformHttpRequest(reqParams); - if (res_status < http_client::HTTP_CODE_OK || res_status >= http_client::HTTP_CODE_MULTIPLE_CHOICES) + if (statusCode < http_client::HTTP_CODE_OK || statusCode >= http_client::HTTP_CODE_MULTIPLE_CHOICES) { - std::cout << "Error authenticating: " << res_status << ".\n"; + std::cout << "Error authenticating: " << statusCode << ".\n"; return std::nullopt; } try { - return nlohmann::json::parse(res_message).at("data").at("token").get_ref(); + return nlohmann::json::parse(statusMessage).at("data").at("token").get_ref(); } catch (const std::exception& e) { diff --git a/src/agent/src/command_handler_utils.cpp b/src/agent/src/command_handler_utils.cpp index 5e0cb02049..854e9866e9 100644 --- a/src/agent/src/command_handler_utils.cpp +++ b/src/agent/src/command_handler_utils.cpp @@ -123,6 +123,6 @@ void ReportCommandResult(const module_command::CommandEntry& commandEntry, resultJson["command"]["result"]["code"] = commandEntry.ExecutionResult.ErrorCode; resultJson["command"]["result"]["message"] = commandEntry.ExecutionResult.Message; - Message message {MessageType::STATEFUL, {resultJson}, metadata["module"], "", metadata.dump()}; + const Message message {MessageType::STATEFUL, {resultJson}, metadata["module"], "", metadata.dump()}; messageQueue->push(message); } diff --git a/src/agent/src/instance_handler_unix.cpp b/src/agent/src/instance_handler_unix.cpp index 3b1dd24889..2c12929f65 100644 --- a/src/agent/src/instance_handler_unix.cpp +++ b/src/agent/src/instance_handler_unix.cpp @@ -78,8 +78,8 @@ namespace instance_handler const std::string filename = fmt::format("{}/wazuh-agent.lock", m_lockFilePath); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg, cppcoreguidelines-avoid-magic-numbers) - int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) + const int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd == -1) { m_errno = errno; @@ -113,7 +113,7 @@ namespace instance_handler std::string GetAgentStatus(const std::string& configFilePath) { - InstanceHandler instanceHandler = GetInstanceHandler(configFilePath); + const InstanceHandler instanceHandler = GetInstanceHandler(configFilePath); if (!instanceHandler.isLockAcquired()) { diff --git a/src/agent/src/main.cpp b/src/agent/src/main.cpp index a8a1f8c085..d8faaecff5 100644 --- a/src/agent/src/main.cpp +++ b/src/agent/src/main.cpp @@ -32,7 +32,7 @@ static const auto OPT_RUN_SERVICE {"run-service"}; int main(int argc, char* argv[]) { - Logger logger; + const Logger logger; SSL_library_init(); SSL_load_error_strings(); diff --git a/src/agent/src/message_queue_utils.cpp b/src/agent/src/message_queue_utils.cpp index 92ea7d10f1..fe318b3db8 100644 --- a/src/agent/src/message_queue_utils.cpp +++ b/src/agent/src/message_queue_utils.cpp @@ -58,7 +58,7 @@ std::optional GetCommandFromQueue(std::shared_ptr< return std::nullopt; } - Message m = multiTypeQueue->getNext(MessageType::COMMAND); + const Message m = multiTypeQueue->getNext(MessageType::COMMAND); nlohmann::json jsonData = m.data; std::string id; diff --git a/src/agent/src/process_options_unix.cpp b/src/agent/src/process_options_unix.cpp index 856647b812..64cafcc36b 100644 --- a/src/agent/src/process_options_unix.cpp +++ b/src/agent/src/process_options_unix.cpp @@ -13,7 +13,7 @@ void StartAgent(const std::string& configFilePath) { - instance_handler::InstanceHandler instanceHandler = instance_handler::GetInstanceHandler(configFilePath); + const auto instanceHandler = instance_handler::GetInstanceHandler(configFilePath); if (!instanceHandler.isLockAcquired()) { diff --git a/src/agent/src/signal_handler_unix.cpp b/src/agent/src/signal_handler_unix.cpp index 7700309946..fcfc4c59e8 100644 --- a/src/agent/src/signal_handler_unix.cpp +++ b/src/agent/src/signal_handler_unix.cpp @@ -2,7 +2,7 @@ void SignalHandler::Initialize(const std::vector& signalsToHandle) { - for (int signal : signalsToHandle) + for (const int signal : signalsToHandle) { std::signal(signal, SignalHandler::HandleSignal); } diff --git a/src/agent/task_manager/src/task_manager.cpp b/src/agent/task_manager/src/task_manager.cpp index e6a01dd95d..d0fb9c7256 100644 --- a/src/agent/task_manager/src/task_manager.cpp +++ b/src/agent/task_manager/src/task_manager.cpp @@ -15,7 +15,7 @@ TaskManager::~TaskManager() void TaskManager::Start(size_t numThreads) { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); if (m_work || !m_threads.empty()) { @@ -34,7 +34,7 @@ void TaskManager::Start(size_t numThreads) void TaskManager::Stop() { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); if (m_work) { @@ -64,7 +64,7 @@ void TaskManager::Stop() void TaskManager::EnqueueTask(std::function task, const std::string& taskID) { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); if (++m_numEnqueuedThreads > m_threads.size()) { @@ -89,7 +89,7 @@ void TaskManager::EnqueueTask(std::function task, const std::string& tas void TaskManager::EnqueueTask(boost::asio::awaitable task, const std::string& taskID) { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); // NOLINTBEGIN(cppcoreguidelines-avoid-capturing-lambda-coroutines) boost::asio::co_spawn( diff --git a/src/agent/task_manager/tests/task_manager_test.cpp b/src/agent/task_manager/tests/task_manager_test.cpp index b2161d8ae8..dc93f2917e 100644 --- a/src/agent/task_manager/tests/task_manager_test.cpp +++ b/src/agent/task_manager/tests/task_manager_test.cpp @@ -30,7 +30,7 @@ TEST_F(TaskManagerTest, StartAndStop) TEST_F(TaskManagerTest, EnqueueFunctionTask) { - std::function task = [this]() + const std::function task = [this]() { taskExecuted = true; cv.notify_one(); @@ -76,7 +76,7 @@ TEST_F(TaskManagerTest, EnqueueFunctionTaskIncrementsCounter) { EXPECT_EQ(taskManager.GetNumEnqueuedThreads(), 0); - std::function task = [this]() + const std::function task = [this]() { EXPECT_EQ(taskManager.GetNumEnqueuedThreads(), 1); taskExecuted = true; diff --git a/src/agent/tests/agent_registration_test.cpp b/src/agent/tests/agent_registration_test.cpp index 213ff48439..2416e10b4f 100644 --- a/src/agent/tests/agent_registration_test.cpp +++ b/src/agent/tests/agent_registration_test.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include "../http_client/tests/mocks/mock_http_client.hpp" @@ -74,7 +75,7 @@ class RegisterTest : public ::testing::Test TEST_F(RegisterTest, RegistrationTestSuccess) { auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const auto mockHttpClientPtr = mockHttpClient.get(); m_registration = std::make_unique(std::move(mockHttpClient), "https://localhost:55000", @@ -86,19 +87,14 @@ TEST_F(RegisterTest, RegistrationTestSuccess) "full", std::move(*m_agentInfo)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse1 {200, R"({"data":{"token":"token"}})"}; - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse2 {201, ""}; + const std::tuple expectedResponse1 {http_client::HTTP_CODE_OK, R"({"data":{"token":"token"}})"}; + const std::tuple expectedResponse2 {http_client::HTTP_CODE_CREATED, ""}; EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) .Times(2) .WillOnce(testing::Return(expectedResponse1)) .WillOnce(testing::Return(expectedResponse2)); - // NOLINTNEXTLINE(cppcoreguidelines-init-variables) - SetAgentInfoSaveExpectCalls(); const bool res = m_registration->Register(); @@ -108,7 +104,7 @@ TEST_F(RegisterTest, RegistrationTestSuccess) TEST_F(RegisterTest, RegistrationFailsIfAuthenticationFails) { auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const auto mockHttpClientPtr = mockHttpClient.get(); m_registration = std::make_unique(std::move(mockHttpClient), "https://localhost:55000", @@ -120,12 +116,10 @@ TEST_F(RegisterTest, RegistrationFailsIfAuthenticationFails) "certificate", std::move(*m_agentInfo)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse {401, ""}; + const std::tuple expectedResponse {http_client::HTTP_CODE_UNAUTHORIZED, ""}; EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); - // NOLINTNEXTLINE(cppcoreguidelines-init-variables) const bool res = m_registration->Register(); ASSERT_FALSE(res); } @@ -133,7 +127,7 @@ TEST_F(RegisterTest, RegistrationFailsIfAuthenticationFails) TEST_F(RegisterTest, RegistrationFailsIfServerResponseIsNotOk) { auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const auto mockHttpClientPtr = mockHttpClient.get(); m_registration = std::make_unique(std::move(mockHttpClient), "https://localhost:55000", @@ -145,18 +139,14 @@ TEST_F(RegisterTest, RegistrationFailsIfServerResponseIsNotOk) "none", std::move(*m_agentInfo)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse1 {200, R"({"data":{"token":"token"}})"}; - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse2 {400, ""}; + const std::tuple expectedResponse1 {http_client::HTTP_CODE_OK, R"({"data":{"token":"token"}})"}; + const std::tuple expectedResponse2 {http_client::HTTP_CODE_BAD_REQUEST, ""}; EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) .Times(2) .WillOnce(testing::Return(expectedResponse1)) .WillOnce(testing::Return(expectedResponse2)); - // NOLINTNEXTLINE(cppcoreguidelines-init-variables) const bool res = m_registration->Register(); ASSERT_FALSE(res); } @@ -164,7 +154,7 @@ TEST_F(RegisterTest, RegistrationFailsIfServerResponseIsNotOk) TEST_F(RegisterTest, RegisteringWithoutAKeyGeneratesOneAutomatically) { auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const auto mockHttpClientPtr = mockHttpClient.get(); m_registration = std::make_unique(std::move(mockHttpClient), "https://localhost:55000", @@ -176,19 +166,14 @@ TEST_F(RegisterTest, RegisteringWithoutAKeyGeneratesOneAutomatically) "full", std::move(*m_agentInfo)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse1 {200, R"({"data":{"token":"token"}})"}; - - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse2 {201, ""}; + const std::tuple expectedResponse1 {http_client::HTTP_CODE_OK, R"({"data":{"token":"token"}})"}; + const std::tuple expectedResponse2 {http_client::HTTP_CODE_CREATED, ""}; EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)) .Times(2) .WillOnce(testing::Return(expectedResponse1)) .WillOnce(testing::Return(expectedResponse2)); - // NOLINTNEXTLINE(cppcoreguidelines-init-variables) - // Mock for: m_persistence->ResetToDefault(); EXPECT_CALL(*m_mockPersistence, DropTable("agent_info")).Times(1); EXPECT_CALL(*m_mockPersistence, DropTable("agent_group")).Times(1); @@ -197,7 +182,7 @@ TEST_F(RegisterTest, RegisteringWithoutAKeyGeneratesOneAutomatically) EXPECT_CALL(*m_mockPersistence, Insert(testing::_, testing::_)).Times(1); // Mock for: m_persistence->SetName(m_name); m_persistence->SetKey(m_key); m_persistence->SetUUID(m_uuid); - testing::InSequence seq; + const testing::InSequence seq; EXPECT_CALL(*m_mockPersistence, Update(testing::Eq("agent_info"), testing::AllOf( @@ -239,9 +224,7 @@ TEST_F(RegisterTest, RegisteringWithoutAKeyGeneratesOneAutomatically) TEST_F(RegisterTest, RegistrationTestFailWithBadKey) { - auto mockHttpClient = std::make_unique(); - - ASSERT_THROW(agent_registration::AgentRegistration(std::move(mockHttpClient), + ASSERT_THROW(agent_registration::AgentRegistration(std::make_unique(), "https://localhost:55000", "user", "password", @@ -270,7 +253,7 @@ TEST_F(RegisterTest, RegistrationTestFailWithHttpClientError) TEST_F(RegisterTest, AuthenticateWithUserPassword_Success) { auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const auto mockHttpClientPtr = mockHttpClient.get(); m_registration = std::make_unique(std::move(mockHttpClient), "https://localhost:55000", @@ -282,8 +265,8 @@ TEST_F(RegisterTest, AuthenticateWithUserPassword_Success) "full", std::move(*m_agentInfo)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse {200, R"({"data":{"token":"valid_token"}})"}; + const std::tuple expectedResponse {http_client::HTTP_CODE_OK, + R"({"data":{"token":"valid_token"}})"}; EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); @@ -298,7 +281,7 @@ TEST_F(RegisterTest, AuthenticateWithUserPassword_Success) TEST_F(RegisterTest, AuthenticateWithUserPassword_Failure) { auto mockHttpClient = std::make_unique(); - auto mockHttpClientPtr = mockHttpClient.get(); + const auto mockHttpClientPtr = mockHttpClient.get(); m_registration = std::make_unique(std::move(mockHttpClient), "https://localhost:55000", @@ -310,8 +293,7 @@ TEST_F(RegisterTest, AuthenticateWithUserPassword_Failure) "full", std::move(*m_agentInfo)); - // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) - std::tuple expectedResponse {401, ""}; + const std::tuple expectedResponse {http_client::HTTP_CODE_UNAUTHORIZED, ""}; EXPECT_CALL(*mockHttpClientPtr, PerformHttpRequest(testing::_)).WillOnce(testing::Return(expectedResponse)); diff --git a/src/agent/tests/agent_test.cpp b/src/agent/tests/agent_test.cpp index f447b8a07c..2132a9d7d0 100644 --- a/src/agent/tests/agent_test.cpp +++ b/src/agent/tests/agent_test.cpp @@ -101,11 +101,12 @@ class AgentTests : public ::testing::Test void SetConstructorPersistenceExpectCalls() { - std::vector mockRowName = {{column::ColumnValue("name", column::ColumnType::TEXT, "agent_name")}}; - std::vector mockRowKey = { + const std::vector mockRowName = { + {column::ColumnValue("name", column::ColumnType::TEXT, "agent_name")}}; + const std::vector mockRowKey = { {column::ColumnValue("key", column::ColumnType::TEXT, "4GhT7uFm1zQa9c2Vb7Lk8pYsX0WqZrNj")}}; - std::vector mockRowUUID = {{}}; - std::vector mockRowGroup = {{}}; + const std::vector mockRowUUID = {{}}; + const std::vector mockRowGroup = {{}}; EXPECT_CALL(*m_mockPersistence, TableExists("agent_info")).WillOnce(testing::Return(true)); EXPECT_CALL(*m_mockPersistence, TableExists("agent_group")).WillOnce(testing::Return(true)); @@ -114,7 +115,7 @@ class AgentTests : public ::testing::Test .WillOnce(testing::Return(0)); EXPECT_CALL(*m_mockPersistence, Insert("agent_info", testing::_)).Times(1); - testing::Sequence seq; + const testing::Sequence seq; EXPECT_CALL(*m_mockPersistence, Select("agent_info", testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .InSequence(seq) diff --git a/src/agent/tests/instance_handler_test.cpp b/src/agent/tests/instance_handler_test.cpp index 893a72b0af..d48fc77335 100644 --- a/src/agent/tests/instance_handler_test.cpp +++ b/src/agent/tests/instance_handler_test.cpp @@ -33,7 +33,7 @@ std::filesystem::path InstanceHandlerTest::m_tempConfigFilePath; TEST_F(InstanceHandlerTest, GetInstanceLock) { auto instanceHandler = instance_handler::GetInstanceHandler("./temp_wazuh-agent.yml"); - bool res = instanceHandler.isLockAcquired(); + const bool res = instanceHandler.isLockAcquired(); ASSERT_TRUE(res); } @@ -42,8 +42,8 @@ TEST_F(InstanceHandlerTest, GetInstanceLockTwice) auto instanceHandler = instance_handler::GetInstanceHandler("./temp_wazuh-agent.yml"); auto instanceHandler2 = instance_handler::GetInstanceHandler("./temp_wazuh-agent.yml"); - bool resinstanceHandler = instanceHandler.isLockAcquired(); - bool resinstanceHandler2 = instanceHandler2.isLockAcquired(); + const bool resinstanceHandler = instanceHandler.isLockAcquired(); + const bool resinstanceHandler2 = instanceHandler2.isLockAcquired(); ASSERT_TRUE(resinstanceHandler); ASSERT_FALSE(resinstanceHandler2); @@ -52,7 +52,7 @@ TEST_F(InstanceHandlerTest, GetInstanceLockTwice) TEST_F(InstanceHandlerTest, GetAgentStatusRunning) { auto instanceHandler = instance_handler::GetInstanceHandler("./temp_wazuh-agent.yml"); - std::string res = instance_handler::GetAgentStatus("./temp_wazuh-agent.yml"); + const std::string res = instance_handler::GetAgentStatus("./temp_wazuh-agent.yml"); ASSERT_EQ(res, "running"); } @@ -61,13 +61,13 @@ TEST_F(InstanceHandlerTest, GetAgentStatusStoppedPrevInstanceDestroyed) { auto instanceHandler = instance_handler::GetInstanceHandler("./temp_wazuh-agent.yml"); } - std::string res = instance_handler::GetAgentStatus("./temp_wazuh-agent.yml"); + const std::string res = instance_handler::GetAgentStatus("./temp_wazuh-agent.yml"); ASSERT_EQ(res, "stopped"); } TEST_F(InstanceHandlerTest, GetAgentStatusStoppedNoPrevInstance) { - std::string res = instance_handler::GetAgentStatus("./temp_wazuh-agent.yml"); + const std::string res = instance_handler::GetAgentStatus("./temp_wazuh-agent.yml"); ASSERT_EQ(res, "stopped"); } diff --git a/src/agent/tests/message_queue_utils_test.cpp b/src/agent/tests/message_queue_utils_test.cpp index 5cf39b2de6..bf51176298 100644 --- a/src/agent/tests/message_queue_utils_test.cpp +++ b/src/agent/tests/message_queue_utils_test.cpp @@ -67,8 +67,8 @@ class MessageQueueUtilsTest : public ::testing::Test TEST_F(MessageQueueUtilsTest, GetMessagesFromQueueTestBySize) { - std::vector data {R"({"event":{"original":"Testing message!"}})"}; - std::string metadata {R"({"module":"logcollector","type":"file"})"}; + const std::vector data {R"({"event":{"original":"Testing message!"}})"}; + const std::string metadata {R"({"module":"logcollector","type":"file"})"}; std::vector testMessages; testMessages.emplace_back(MessageType::STATELESS, data, "", "", metadata); @@ -90,16 +90,16 @@ TEST_F(MessageQueueUtilsTest, GetMessagesFromQueueTestBySize) const auto result = awaitableResult.get(); const auto jsonResult = std::get<1>(result); - std::string expectedString = std::string("\n") + R"({"module":"logcollector","type":"file"})" + std::string("\n") + - R"(["{\"event\":{\"original\":\"Testing message!\"}}"])"; + const std::string expectedString = std::string("\n") + R"({"module":"logcollector","type":"file"})" + + std::string("\n") + R"(["{\"event\":{\"original\":\"Testing message!\"}}"])"; ASSERT_EQ(jsonResult, expectedString); } TEST_F(MessageQueueUtilsTest, GetMessagesFromQueueMetadataTest) { - std::vector data {R"({"event":{"original":"Testing message!"}})"}; - std::string moduleMetadata {R"({"module":"logcollector","type":"file"})"}; + const std::vector data {R"({"event":{"original":"Testing message!"}})"}; + const std::string moduleMetadata {R"({"module":"logcollector","type":"file"})"}; std::vector testMessages; testMessages.emplace_back(MessageType::STATELESS, data, "", "", moduleMetadata); @@ -127,17 +127,17 @@ TEST_F(MessageQueueUtilsTest, GetMessagesFromQueueMetadataTest) const auto result = awaitableResult.get(); const auto jsonResult = std::get<1>(result); - std::string expectedString = R"({"agent":"test"})" + std::string("\n") + - R"({"module":"logcollector","type":"file"})" + std::string("\n") + - R"(["{\"event\":{\"original\":\"Testing message!\"}}"])"; + const std::string expectedString = R"({"agent":"test"})" + std::string("\n") + + R"({"module":"logcollector","type":"file"})" + std::string("\n") + + R"(["{\"event\":{\"original\":\"Testing message!\"}}"])"; ASSERT_EQ(jsonResult, expectedString); } TEST_F(MessageQueueUtilsTest, GetEmptyMessagesFromQueueTest) { - nlohmann::json data = nlohmann::json::object(); - std::string moduleMetadata {R"({"operation":"delete"})"}; + const nlohmann::json data = nlohmann::json::object(); + const std::string moduleMetadata {R"({"operation":"delete"})"}; std::vector testMessages; testMessages.emplace_back(MessageType::STATEFUL, data, "", "", moduleMetadata); @@ -165,7 +165,7 @@ TEST_F(MessageQueueUtilsTest, GetEmptyMessagesFromQueueTest) const auto result = awaitableResult.get(); const auto jsonResult = std::get<1>(result); - std::string expectedString = R"({"agent":"test"})" + std::string("\n") + R"({"operation":"delete"})"; + const std::string expectedString = R"({"agent":"test"})" + std::string("\n") + R"({"operation":"delete"})"; ASSERT_EQ(jsonResult, expectedString); } @@ -211,7 +211,7 @@ TEST_F(MessageQueueUtilsTest, GetCommandFromQueueEmptyTest) TEST_F(MessageQueueUtilsTest, GetCommandFromQueueTest) { - Message testMessage {MessageType::COMMAND, BASE_DATA_CONTENT}; + const Message testMessage {MessageType::COMMAND, BASE_DATA_CONTENT}; EXPECT_CALL(*mockQueue, isEmpty(MessageType::COMMAND, "", "")).WillOnce(testing::Return(false)); diff --git a/src/agent/tests/signal_handler_test.cpp b/src/agent/tests/signal_handler_test.cpp index efe94bf8c2..2bec7b6696 100644 --- a/src/agent/tests/signal_handler_test.cpp +++ b/src/agent/tests/signal_handler_test.cpp @@ -48,7 +48,7 @@ TEST_F(SignalHandlerTest, KeepRunningIsTheDefault) TEST_F(SignalHandlerTest, HandlesSignal) { std::promise readyPromise; - std::future readyFuture = readyPromise.get_future(); + const std::future readyFuture = readyPromise.get_future(); std::thread signalThread( [&]() { diff --git a/src/common/file_helper/file_io/src/file_io.cpp b/src/common/file_helper/file_io/src/file_io.cpp index 2e8ecc5f18..8e088721e8 100644 --- a/src/common/file_helper/file_io/src/file_io.cpp +++ b/src/common/file_helper/file_io/src/file_io.cpp @@ -49,7 +49,7 @@ namespace file_io std::string FileIO::getFileContent(const std::string& filePath) const { std::stringstream content; - std::ifstream file = create_ifstream(filePath); + const auto file = create_ifstream(filePath); if (is_open(file)) { diff --git a/src/common/file_helper/file_io/tests/file_io_test.cpp b/src/common/file_helper/file_io/tests/file_io_test.cpp index 153632f82c..257578171f 100644 --- a/src/common/file_helper/file_io/tests/file_io_test.cpp +++ b/src/common/file_helper/file_io/tests/file_io_test.cpp @@ -22,7 +22,7 @@ TEST(FileIOTest, ReadLineByLine_CallsCallbackForEachLine) { auto mockFileIO = std::make_unique(); - std::string fakePath = "fakepath.txt"; + std::string const fakePath = "fakepath.txt"; std::ifstream fakeStream; EXPECT_CALL(*mockFileIO, create_ifstream(fakePath, std::ios_base::in)) @@ -47,7 +47,7 @@ TEST(FileIOTest, ReadLineByLine_CallsCallbackForEachLine) TEST(FileIOTest, ReadLineByLine_FileNotOpen_ThrowsException) { auto mockFileIO = std::make_unique(); - std::string filePath = "fakepath.txt"; + std::string const filePath = "fakepath.txt"; std::ifstream fakeStream; EXPECT_CALL(*mockFileIO, create_ifstream(filePath, std::ios_base::in)) @@ -62,7 +62,7 @@ TEST(FileIOTest, ReadLineByLine_FileNotOpen_ThrowsException) TEST(FileIOTest, ReadLineByLine_EmptyFile_NoCallbackCalled) { auto mockFileIO = std::make_unique(); - std::string filePath = "fakepath.txt"; + std::string const filePath = "fakepath.txt"; std::ifstream fakeStream; EXPECT_CALL(*mockFileIO, create_ifstream(filePath, std::ios_base::in)) @@ -84,30 +84,30 @@ TEST(FileIOTest, ReadLineByLine_EmptyFile_NoCallbackCalled) TEST(FileIOTest, GetFileContent_FileNotOpen_ReturnsEmptyString) { auto mockFileIO = std::make_unique(); - std::string filePath = "fakepath.txt"; + std::string const filePath = "fakepath.txt"; std::ifstream fakeStream("fakepath.txt"); EXPECT_CALL(*mockFileIO, create_ifstream(filePath, std::ios_base::in)) .WillOnce(Return(ByMove(std::move(fakeStream)))); EXPECT_CALL(*mockFileIO, is_open(testing::_)).WillOnce(Return(false)); - std::string content = mockFileIO->getFileContent(filePath); + std::string const content = mockFileIO->getFileContent(filePath); EXPECT_EQ(content, ""); } TEST(FileIOTest, GetFileContent_FileIsOpen_ReturnsContent) { auto mockFileIO = std::make_unique(); - std::string filePath = "fakepath.txt"; - std::string fakeData = "fakepath content"; + std::string const filePath = "fakepath.txt"; + std::string const fakeData = "fakepath content"; std::ifstream fakeStream; EXPECT_CALL(*mockFileIO, create_ifstream(filePath, testing::_)).WillOnce(Return(ByMove(std::move(fakeStream)))); EXPECT_CALL(*mockFileIO, is_open(testing::_)).WillOnce(Return(true)); - std::istringstream iss(fakeData); + std::istringstream const iss(fakeData); std::streambuf* fakeBuf = iss.rdbuf(); EXPECT_CALL(*mockFileIO, get_rdbuf(testing::_)).WillOnce(Return(fakeBuf)); - std::string content = mockFileIO->getFileContent(filePath); + std::string const content = mockFileIO->getFileContent(filePath); EXPECT_EQ(content, fakeData); } diff --git a/src/common/file_helper/filesystem/src/filesystem_wrapper.cpp b/src/common/file_helper/filesystem/src/filesystem_wrapper.cpp index c911f97a68..e1341472df 100644 --- a/src/common/file_helper/filesystem/src/filesystem_wrapper.cpp +++ b/src/common/file_helper/filesystem/src/filesystem_wrapper.cpp @@ -66,7 +66,7 @@ namespace filesystem_wrapper void FileSystemWrapper::expand_absolute_path(const std::string& path, std::deque& output) const { // Find the first * or ? from path. - std::array wildcards {'*', '?'}; + const std::array wildcards {'*', '?'}; size_t wildcardPos = std::string::npos; for (const auto& wildcard : wildcards) diff --git a/src/common/hashHelper/tests/hashHelper_test.cpp b/src/common/hashHelper/tests/hashHelper_test.cpp index c14f3b3943..6cce6538ef 100644 --- a/src/common/hashHelper/tests/hashHelper_test.cpp +++ b/src/common/hashHelper/tests/hashHelper_test.cpp @@ -27,7 +27,7 @@ const std::filesystem::path TEST_FILE {INPUT_FILES_DIR / "test_file.xyz"}; TEST_F(HashHelperTest, UnsupportedHashType) { - EXPECT_THROW(HashData hash{static_cast(15)}, std::runtime_error); + EXPECT_THROW(const HashData hash{static_cast(15)}, std::runtime_error); } TEST_F(HashHelperTest, HashHelperHashBufferSha1) diff --git a/src/common/logger/tests/logger_test.cpp b/src/common/logger/tests/logger_test.cpp index b3db9c4343..ba9a763423 100644 --- a/src/common/logger/tests/logger_test.cpp +++ b/src/common/logger/tests/logger_test.cpp @@ -93,7 +93,7 @@ TEST_F(LoggerConstructorTest, UnixLoggerConstructorFail) TEST_F(LoggerMessageTest, LogsTraceMessage) { LogTrace("This is a trace message"); - std::string logged_message = oss.str(); + std::string const logged_message = oss.str(); EXPECT_TRUE(logged_message.find("[TRACE]") != std::string::npos); EXPECT_TRUE(logged_message.find("This is a trace message") != std::string::npos); } @@ -101,7 +101,7 @@ TEST_F(LoggerMessageTest, LogsTraceMessage) TEST_F(LoggerMessageTest, LogsDebugMessage) { LogDebug("This is a debug message"); - std::string logged_message = oss.str(); + std::string const logged_message = oss.str(); EXPECT_TRUE(logged_message.find("[DEBUG]") != std::string::npos); EXPECT_TRUE(logged_message.find("This is a debug message") != std::string::npos); } @@ -109,7 +109,7 @@ TEST_F(LoggerMessageTest, LogsDebugMessage) TEST_F(LoggerMessageTest, LogsInfoMessage) { LogInfo("This is an info message"); - std::string logged_message = oss.str(); + std::string const logged_message = oss.str(); EXPECT_TRUE(logged_message.find("[INFO]") != std::string::npos); EXPECT_TRUE(logged_message.find("This is an info message") != std::string::npos); } @@ -117,7 +117,7 @@ TEST_F(LoggerMessageTest, LogsInfoMessage) TEST_F(LoggerMessageTest, LogsWarnMessage) { LogWarn("This is a warning message"); - std::string logged_message = oss.str(); + std::string const logged_message = oss.str(); EXPECT_TRUE(logged_message.find("[WARN]") != std::string::npos); EXPECT_TRUE(logged_message.find("This is a warning message") != std::string::npos); } @@ -125,9 +125,9 @@ TEST_F(LoggerMessageTest, LogsWarnMessage) TEST_F(LoggerMessageTest, LogsErrorMessage) { std::string error_message = "Can't open database"; - std::exception e; + std::exception const e; LogError("{}: {}", error_message, e.what()); - std::string logged_message = oss.str(); + std::string const logged_message = oss.str(); EXPECT_TRUE(logged_message.find("[ERROR]") != std::string::npos); EXPECT_TRUE(logged_message.find("Can't open database") != std::string::npos); EXPECT_TRUE(logged_message.find(e.what()) != std::string::npos); @@ -136,7 +136,7 @@ TEST_F(LoggerMessageTest, LogsErrorMessage) TEST_F(LoggerMessageTest, LogsCriticalMessage) { LogCritical("This is a critical message"); - std::string logged_message = oss.str(); + std::string const logged_message = oss.str(); EXPECT_TRUE(logged_message.find("[CRITICAL]") != std::string::npos); EXPECT_TRUE(logged_message.find("This is a critical message") != std::string::npos); } diff --git a/src/common/pipelineHelper/tests/pipelineNodes_test.cpp b/src/common/pipelineHelper/tests/pipelineNodes_test.cpp index c11d5b866e..30279154da 100644 --- a/src/common/pipelineHelper/tests/pipelineNodes_test.cpp +++ b/src/common/pipelineHelper/tests/pipelineNodes_test.cpp @@ -126,8 +126,8 @@ TEST_F(PipelineNodesTest, ReadWriteNodeSync) TEST_F(PipelineNodesTest, ConnectInvalidPtrs1) { - std::shared_ptr> spReadNode; - std::shared_ptr>> spReadWriteNode; + std::shared_ptr> const spReadNode; + std::shared_ptr>> const spReadWriteNode; EXPECT_NO_THROW(Utils::connect(spReadWriteNode, spReadNode)); } @@ -137,13 +137,13 @@ TEST_F(PipelineNodesTest, ConnectInvalidPtrs2) { std::make_shared>([](const int&) {}) }; - std::shared_ptr>> spReadWriteNode; + std::shared_ptr>> const spReadWriteNode; EXPECT_NO_THROW(Utils::connect(spReadWriteNode, spReadNode)); } TEST_F(PipelineNodesTest, ConnectInvalidPtrs3) { - std::shared_ptr> spReadNode; + std::shared_ptr> const spReadNode; const auto spReadWriteNode { std::make_shared>>([](const int&) diff --git a/src/common/stringHelper/tests/stringHelper_test.cpp b/src/common/stringHelper/tests/stringHelper_test.cpp index 8132d1270d..0c4ca6fc30 100644 --- a/src/common/stringHelper/tests/stringHelper_test.cpp +++ b/src/common/stringHelper/tests/stringHelper_test.cpp @@ -198,7 +198,7 @@ TEST_F(StringUtilsTest, SplitDelimiterNullTerminated) TEST_F(StringUtilsTest, SplitMapKeyValue) { - std::string buffer("PRETTY_NAME=\"Ubuntu 22.04.1 LTS\"\n\ + std::string const buffer("PRETTY_NAME=\"Ubuntu 22.04.1 LTS\"\n\ NAME=\"Ubuntu\"\n\ VERSION_ID=\"22.04\"\n\ VERSION=\"22.04.1 LTS (Jammy Jellyfish)\"\n\ @@ -296,7 +296,7 @@ TEST_F(StringUtilsTest, substrOnFirstOccurrenceCorrectEscapeCharacterEmptyResult TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimple) { - std::string stringBase {"hello:world"}; + std::string const stringBase {"hello:world"}; const auto retVal {Utils::splitKeyValueNonEscapedDelimiter(stringBase, ':', '\\')}; EXPECT_EQ(retVal.first, "hello"); EXPECT_EQ(retVal.second, "world"); @@ -304,7 +304,7 @@ TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimple) TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleEnd) { - std::string stringBase {"hello:"}; + std::string const stringBase {"hello:"}; const auto retVal {Utils::splitKeyValueNonEscapedDelimiter(stringBase, ':', '\\')}; EXPECT_EQ(retVal.first, "hello"); EXPECT_EQ(retVal.second, ""); @@ -312,7 +312,7 @@ TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleEnd) TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleDoubleDelimiterEnd) { - std::string stringBase {"hello:world:"}; + std::string const stringBase {"hello:world:"}; const auto retVal {Utils::splitKeyValueNonEscapedDelimiter(stringBase, ':', '\\')}; EXPECT_EQ(retVal.first, "hello"); EXPECT_EQ(retVal.second, "world:"); @@ -320,7 +320,7 @@ TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleDoubleDelimiterEnd) TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleDoubleEnd) { - std::string stringBase {"hello::"}; + std::string const stringBase {"hello::"}; const auto retVal {Utils::splitKeyValueNonEscapedDelimiter(stringBase, ':', '\\')}; EXPECT_EQ(retVal.first, "hello"); EXPECT_EQ(retVal.second, ":"); @@ -328,7 +328,7 @@ TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleDoubleEnd) TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleEmptyDoubleEnd) { - std::string stringBase {"::"}; + std::string const stringBase {"::"}; const auto retVal {Utils::splitKeyValueNonEscapedDelimiter(stringBase, ':', '\\')}; EXPECT_EQ(retVal.first, ""); EXPECT_EQ(retVal.second, ":"); @@ -336,7 +336,7 @@ TEST_F(StringUtilsTest, splitKeyValueNonEscapedSimpleEmptyDoubleEnd) TEST_F(StringUtilsTest, splitKeyValueNonEscapedComplex) { - std::string stringBase {"he\\:llo:world"}; + std::string const stringBase {"he\\:llo:world"}; const auto retVal {Utils::splitKeyValueNonEscapedDelimiter(stringBase, ':', '\\')}; EXPECT_EQ(retVal.first, "he\\:llo"); EXPECT_EQ(retVal.second, "world"); @@ -344,7 +344,7 @@ TEST_F(StringUtilsTest, splitKeyValueNonEscapedComplex) TEST_F(StringUtilsTest, splitKeyValueNonEscapedComplexEnd) { - std::string stringBase {"he\\:llo:"}; + std::string const stringBase {"he\\:llo:"}; const auto retVal {Utils::splitKeyValueNonEscapedDelimiter(stringBase, ':', '\\')}; EXPECT_EQ(retVal.first, "he\\:llo"); EXPECT_EQ(retVal.second, ""); diff --git a/src/modules/inventory/src/inventoryImp.cpp b/src/modules/inventory/src/inventoryImp.cpp index 9a62a76683..ed8f699234 100644 --- a/src/modules/inventory/src/inventoryImp.cpp +++ b/src/modules/inventory/src/inventoryImp.cpp @@ -261,8 +261,8 @@ std::string Inventory::GetPrimaryKeys([[maybe_unused]] const nlohmann::json& dat std::string Inventory::CalculateHashId(const nlohmann::json& data, const std::string& table) { - std::string primaryKey = GetPrimaryKeys(data, table); - std::string baseId = AgentUUID() + ":" + primaryKey; + const std::string primaryKey = GetPrimaryKeys(data, table); + const std::string baseId = AgentUUID() + ":" + primaryKey; Utils::HashData hash(Utils::HashType::Sha1); hash.update(baseId.c_str(), baseId.size()); @@ -337,7 +337,7 @@ void Inventory::NotifyEvent(ReturnTypeCallback result, { if (!isFirstScan) { - nlohmann::json oldData = (result == MODIFIED) ? EcsData(item["old"], table, false) : nlohmann::json {}; + const nlohmann::json oldData = (result == MODIFIED) ? EcsData(item["old"], table, false) : nlohmann::json {}; nlohmann::json stateless = GenerateStatelessEvent(OPERATION_MAP.at(result), table, msg["data"]); nlohmann::json eventWithChanges = msg["data"]; @@ -364,7 +364,7 @@ void Inventory::UpdateChanges(const std::string& table, const nlohmann::json& va NotifyChange(result, data, table, isFirstScan); }}; - std::unique_lock lock {m_mutex}; + const std::unique_lock lock {m_mutex}; DBSyncTxn txn {m_spDBSync->handle(), nlohmann::json {table}, 0, QUEUE_SIZE, callback}; nlohmann::json input; input["table"] = table; @@ -446,7 +446,7 @@ void Inventory::Init(const std::shared_ptr& spInfo, m_reportDiffFunction = reportDiffFunction; { - std::unique_lock lock {m_mutex}; + const std::unique_lock lock {m_mutex}; m_stopping = false; m_spDBSync = std::make_unique( HostType::AGENT, DbEngineType::SQLITE3, dbPath, GetCreateStatement(), DbManagement::PERSISTENT); @@ -787,7 +787,7 @@ void Inventory::ScanPackages() NotifyChange(result, data, PACKAGES_TABLE, !m_packagesFirstScan); }}; - std::unique_lock lock {m_mutex}; + const std::unique_lock lock {m_mutex}; DBSyncTxn txn {m_spDBSync->handle(), nlohmann::json {PACKAGES_TABLE}, 0, QUEUE_SIZE, callback}; m_spInfo->packages( [this, &txn](nlohmann::json& rawData) @@ -933,7 +933,7 @@ void Inventory::ScanProcesses() { NotifyChange(result, data, PROCESSES_TABLE, !m_processesFirstScan); }}; - std::unique_lock lock {m_mutex}; + const std::unique_lock lock {m_mutex}; DBSyncTxn txn {m_spDBSync->handle(), nlohmann::json {PROCESSES_TABLE}, 0, QUEUE_SIZE, callback}; m_spInfo->processes(std::function( [this, &txn](nlohmann::json& rawData) @@ -1000,7 +1000,7 @@ void Inventory::SyncLoop() } Scan(); } - std::unique_lock lock {m_mutex}; + const std::unique_lock lock {m_mutex}; m_spDBSync.reset(nullptr); } @@ -1013,7 +1013,7 @@ void Inventory::WriteMetadata(const std::string& key, const std::string& value) std::string Inventory::ReadMetadata(const std::string& key) { std::string result; - std::string filter = "WHERE key = '" + key + "'"; + const std::string filter = "WHERE key = '" + key + "'"; auto selectQuery = SelectQuery::builder().table(MD_TABLE).columnList({"key", "value"}).rowFilter(filter).build(); auto callback = [&result](ReturnTypeCallback returnTypeCallback, const nlohmann::json& resultData) @@ -1043,7 +1043,7 @@ void Inventory::CleanMetadata() try { { - std::unique_lock lock {m_mutex}; + const std::unique_lock lock {m_mutex}; m_spDBSync = std::make_unique( HostType::AGENT, DbEngineType::SQLITE3, m_dbFilePath, GetCreateStatement(), DbManagement::PERSISTENT); for (const auto& key : TABLE_TO_KEY_MAP) @@ -1124,7 +1124,7 @@ void Inventory::SetJsonField(nlohmann::json& target, { if (createFields || source.contains(jsonKey)) { - nlohmann::json::json_pointer pointer(keyPath); + const nlohmann::json::json_pointer pointer(keyPath); if (source.contains(jsonKey) && source[jsonKey] != EMPTY_VALUE) { target[pointer] = source[jsonKey]; @@ -1148,7 +1148,7 @@ void Inventory::SetJsonFieldArray(nlohmann::json& target, { if (createFields || source.contains(sourceKey)) { - nlohmann::json::json_pointer destPointer(destPath); + const nlohmann::json::json_pointer destPointer(destPath); target[destPointer.parent_pointer()][destPointer.back()] = nlohmann::json::array(); nlohmann::json& destArray = target[destPointer]; diff --git a/src/modules/inventory/src/inventoryNormalizer.cpp b/src/modules/inventory/src/inventoryNormalizer.cpp index f5a9fba1fe..2f68a0f6d0 100644 --- a/src/modules/inventory/src/inventoryNormalizer.cpp +++ b/src/modules/inventory/src/inventoryNormalizer.cpp @@ -19,7 +19,7 @@ void InvNormalizer::RemoveExcluded(const std::string& type, nlohmann::json& data { try { - std::regex pattern {exclusionItem["pattern"].get_ref()}; + const std::regex pattern {exclusionItem["pattern"].get_ref()}; const auto& fieldName {exclusionItem["field_name"].get_ref()}; if (data.is_array()) @@ -68,7 +68,7 @@ static void NormalizeItem(const nlohmann::json& dictionary, nlohmann::json& item if (itFindPattern != dictItem.end() && itFindField != dictItem.end()) { const auto fieldIt {item.find(itFindField->get_ref())}; - std::regex pattern {itFindPattern->get_ref()}; + const std::regex pattern {itFindPattern->get_ref()}; if (fieldIt == item.end() || !std::regex_match(fieldIt->get_ref(), pattern)) { @@ -88,7 +88,7 @@ static void NormalizeItem(const nlohmann::json& dictionary, nlohmann::json& item if (itReplacePattern != dictItem.end() && itReplaceField != dictItem.end() && itReplaceValue != dictItem.end()) { - std::regex pattern {itReplacePattern->get_ref()}; + const std::regex pattern {itReplacePattern->get_ref()}; const auto fieldIt {item.find(itReplaceField->get_ref())}; if (fieldIt != item.end()) @@ -136,7 +136,6 @@ InvNormalizer::GetTypeValues(const std::string& configFile, const std::string& t try { std::ifstream config {configFile}; - nlohmann::json data; if (config.is_open()) { diff --git a/src/modules/inventory/src/statelessEvent.cpp b/src/modules/inventory/src/statelessEvent.cpp index c5f68f4c95..d4e5fca0c8 100644 --- a/src/modules/inventory/src/statelessEvent.cpp +++ b/src/modules/inventory/src/statelessEvent.cpp @@ -13,12 +13,12 @@ StatelessEvent::StatelessEvent(std::string op, std::string time, nlohmann::json nlohmann::json NetworkEvent::generate() const { - std::string interface = (data.contains("observer") && data["observer"].contains("ingress") && - data["observer"]["ingress"].contains("interface") && - data["observer"]["ingress"]["interface"].contains("name") && - !data["observer"]["ingress"]["interface"]["name"].is_null()) - ? data["observer"]["ingress"]["interface"]["name"].get() - : ""; + const std::string interface = (data.contains("observer") && data["observer"].contains("ingress") && + data["observer"]["ingress"].contains("interface") && + data["observer"]["ingress"]["interface"].contains("name") && + !data["observer"]["ingress"]["interface"]["name"].is_null()) + ? data["observer"]["ingress"]["interface"]["name"].get() + : ""; std::string action, reason; @@ -52,11 +52,11 @@ nlohmann::json NetworkEvent::generate() const nlohmann::json PackageEvent::generate() const { - std::string packageName = + const std::string packageName = (data.contains("package") && data["package"].contains("name") && !data["package"]["name"].is_null()) ? data["package"]["name"].get() : ""; - std::string version = + const std::string version = (data.contains("package") && data["package"].contains("version") && !data["package"]["version"].is_null()) ? data["package"]["version"].get() : ""; @@ -92,10 +92,11 @@ nlohmann::json PackageEvent::generate() const nlohmann::json HotfixEvent::generate() const { - std::string hotfixID = (data.contains("package") && data["package"].contains("hotfix") && - data["package"]["hotfix"].contains("name") && !data["package"]["hotfix"]["name"].is_null()) - ? data["package"]["hotfix"]["name"].get() - : ""; + const std::string hotfixID = + (data.contains("package") && data["package"].contains("hotfix") && data["package"]["hotfix"].contains("name") && + !data["package"]["hotfix"]["name"].is_null()) + ? data["package"]["hotfix"]["name"].get() + : ""; std::string action, reason; @@ -126,10 +127,11 @@ nlohmann::json HotfixEvent::generate() const nlohmann::json PortEvent::generate() const { - int srcPort = (data.contains("source") && data["source"].contains("port") && !data["source"]["port"].is_null()) - ? data["source"]["port"].get() - : 0; - int destPort = + const int srcPort = + (data.contains("source") && data["source"].contains("port") && !data["source"]["port"].is_null()) + ? data["source"]["port"].get() + : 0; + const int destPort = (data.contains("destination") && data["destination"].contains("port") && !data["destination"]["port"].is_null()) ? data["destination"]["port"].get() : 0; @@ -168,13 +170,14 @@ nlohmann::json PortEvent::generate() const nlohmann::json ProcessEvent::generate() const { - std::string processName = + const std::string processName = (data.contains("process") && data["process"].contains("name") && !data["process"]["name"].is_null()) ? data["process"]["name"].get() : ""; - std::string pid = (data.contains("process") && data["process"].contains("pid") && !data["process"]["pid"].is_null()) - ? data["process"]["name"].get() - : ""; + const std::string pid = + (data.contains("process") && data["process"].contains("pid") && !data["process"]["pid"].is_null()) + ? data["process"]["name"].get() + : ""; std::string action, reason; @@ -208,14 +211,14 @@ nlohmann::json ProcessEvent::generate() const nlohmann::json SystemEvent::generate() const { - std::string hostname = + const std::string hostname = (data.contains("host") && data["host"].contains("hostname") && !data["host"]["hostname"].is_null()) ? data["host"]["hostname"].get() : ""; - std::string osVersion = (data.contains("host") && data["host"].contains("os") && - data["host"]["os"].contains("version") && !data["host"]["os"]["version"].is_null()) - ? data["host"]["os"]["version"].get() - : ""; + const std::string osVersion = (data.contains("host") && data["host"].contains("os") && + data["host"]["os"].contains("version") && !data["host"]["os"]["version"].is_null()) + ? data["host"]["os"]["version"].get() + : ""; std::string action = (operation == "update") ? "system-updated" : "system-detected"; std::string reason = "System " + hostname + " is running OS version " + osVersion; @@ -231,18 +234,18 @@ nlohmann::json SystemEvent::generate() const nlohmann::json HardwareEvent::generate() const { - std::string cpuName = (data.contains("host") && data["host"].contains("cpu") && - data["host"]["cpu"].contains("name") && !data["host"]["cpu"]["name"].is_null()) - ? data["host"]["cpu"]["name"].get() - : ""; - int memoryTotalGB = (data.contains("host") && data["host"].contains("memory") && - data["host"]["memory"].contains("total") && !data["host"]["memory"]["total"].is_null()) - ? data["host"]["memory"]["total"].get() / BYTES_IN_MEGABYTE - : 0; - std::string serialNumber = (data.contains("observer") && data["observer"].contains("serial_number") && - !data["observer"]["serial_number"].is_null()) - ? data["observer"]["serial_number"].get() - : ""; + const std::string cpuName = (data.contains("host") && data["host"].contains("cpu") && + data["host"]["cpu"].contains("name") && !data["host"]["cpu"]["name"].is_null()) + ? data["host"]["cpu"]["name"].get() + : ""; + const int memoryTotalGB = (data.contains("host") && data["host"].contains("memory") && + data["host"]["memory"].contains("total") && !data["host"]["memory"]["total"].is_null()) + ? data["host"]["memory"]["total"].get() / BYTES_IN_MEGABYTE + : 0; + const std::string serialNumber = (data.contains("observer") && data["observer"].contains("serial_number") && + !data["observer"]["serial_number"].is_null()) + ? data["observer"]["serial_number"].get() + : ""; std::string action, reason; diff --git a/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp b/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp index 303fc624ac..abf6bb6e56 100644 --- a/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp +++ b/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp @@ -50,7 +50,7 @@ TEST_F(InvNormalizerTest, excludeSiriAndiTunes) { auto inputJson(nlohmann::json::parse(TEST_INPUT_DATA)); const auto size {inputJson.size()}; - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.RemoveExcluded("packages", inputJson); EXPECT_EQ(size, inputJson.size() + 2); } @@ -65,7 +65,7 @@ TEST_F(InvNormalizerTest, excludeSingleItemNoMatch) "version": "3.0" })")}; nlohmann::json normalized(origJson); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.RemoveExcluded("packages", normalized); EXPECT_EQ(normalized, origJson); } @@ -79,7 +79,7 @@ TEST_F(InvNormalizerTest, excludeSingleItemMatch) "name": "Siri", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.RemoveExcluded("packages", inputJson); EXPECT_TRUE(inputJson.empty()); } @@ -93,7 +93,7 @@ TEST_F(InvNormalizerTest, normalizeSingleMicosoft) "name": "Microsoft Defender", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "Microsoft"); @@ -108,7 +108,7 @@ TEST_F(InvNormalizerTest, normalizeSingleMcAfee1) "name": "McAfee Antivirus For Mac", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "McAfee"); @@ -124,7 +124,7 @@ TEST_F(InvNormalizerTest, normalizeSingleMcAfee2) "name": "McAfee Endpoint Protection For Mac", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "McAfee"); @@ -140,7 +140,7 @@ TEST_F(InvNormalizerTest, normalizeSingleTotalDefense1) "name": "TotalDefenseAntivirusforMac", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "TotalDefense"); @@ -156,7 +156,7 @@ TEST_F(InvNormalizerTest, normalizeSingleTotalDefense2) "name": "TotalDefenseOtherProductforMac", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "TotalDefense"); @@ -172,7 +172,7 @@ TEST_F(InvNormalizerTest, normalizeSingleAVG1) "name": "AVGAntivirus", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "AVG"); @@ -188,7 +188,7 @@ TEST_F(InvNormalizerTest, normalizeSingleAVG2) "name": "AVGOtherProduct", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "AVG"); @@ -204,7 +204,7 @@ TEST_F(InvNormalizerTest, normalizeSingleKaspersky1) "name": "Kaspersky Antivirus For Mac", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["name"], "Kaspersky Antivirus"); @@ -219,7 +219,7 @@ TEST_F(InvNormalizerTest, normalizeSingleKaspersky2) "name": "Kaspersky Internet Security For Mac", "version": "1.0" })")); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["name"], "Kaspersky Internet Security"); @@ -229,7 +229,7 @@ TEST_F(InvNormalizerTest, normalizeItemMatch) { auto inputJson(nlohmann::json::parse(TEST_INPUT_DATA)); const auto origJson(inputJson); - InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; + const InvNormalizer normalizer {TEST_CONFIG_FILE_NAME, "macos"}; normalizer.Normalize("packages", inputJson); EXPECT_EQ(inputJson.size(), origJson.size()); EXPECT_NE(inputJson, origJson); diff --git a/src/modules/inventory/tests/inventory/inventory_test.cpp b/src/modules/inventory/tests/inventory/inventory_test.cpp index 46c5ae0cf1..94a668c229 100644 --- a/src/modules/inventory/tests/inventory/inventory_test.cpp +++ b/src/modules/inventory/tests/inventory/inventory_test.cpp @@ -22,8 +22,9 @@ TEST_F(InventoryTest, SendUpdateEvent_Stateful) [](const Message& msg) { EXPECT_EQ(msg.type, MessageType::STATEFUL); - nlohmann::json expectedData = {{"key", "value"}}; - nlohmann::json expectedMetadata = {{"collector", "hardware"}, {"operation", "update"}, {"id", "123"}}; + const nlohmann::json expectedData = {{"key", "value"}}; + const nlohmann::json expectedMetadata = { + {"collector", "hardware"}, {"operation", "update"}, {"id", "123"}}; EXPECT_EQ(msg.data, expectedData); EXPECT_EQ(nlohmann::json::parse(msg.metaData), expectedMetadata); return 1; @@ -51,8 +52,9 @@ TEST_F(InventoryTest, SendDeleteEvent_Stateful) [](const Message& msg) { EXPECT_EQ(msg.type, MessageType::STATEFUL); - nlohmann::json expectedData = nlohmann::json::object(); - nlohmann::json expectedMetadata = {{"collector", "hardware"}, {"operation", "delete"}, {"id", "123"}}; + const auto expectedData = nlohmann::json::object(); + const nlohmann::json expectedMetadata = { + {"collector", "hardware"}, {"operation", "delete"}, {"id", "123"}}; EXPECT_EQ(msg.data, expectedData); EXPECT_EQ(nlohmann::json::parse(msg.metaData), expectedMetadata); return 1; @@ -81,7 +83,7 @@ TEST_F(InventoryTest, SendUpdateEvent_WithStateless) [](const Message& msg) { EXPECT_EQ(msg.type, MessageType::STATEFUL); - nlohmann::json expectedData = {{"key", "value"}}; + const nlohmann::json expectedData = {{"key", "value"}}; EXPECT_EQ(msg.data, expectedData); return 1; }) @@ -89,7 +91,7 @@ TEST_F(InventoryTest, SendUpdateEvent_WithStateless) [](const Message& msg) { EXPECT_EQ(msg.type, MessageType::STATELESS); - nlohmann::json expectedData = {{"alert", "high"}}; + const nlohmann::json expectedData = {{"alert", "high"}}; EXPECT_EQ(msg.data, expectedData); return 1; }); diff --git a/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp b/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp index 23abd8b369..6875764a62 100644 --- a/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp +++ b/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp @@ -160,7 +160,7 @@ TEST_F(InventoryImpTest, intervalSeconds) .WillRepeatedly(Return(nlohmann::json::parse( R"({"iface":[{"IPv4":[{"address":"172.17.0.1","broadcast":"172.17.255.255","dhcp":"unknown","metric":"0","netmask":"255.255.0.0"}],"adapter":"","gateway":"","mac":"02:42:1c:26:13:65","mtu":1500,"name":"docker0","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"state":"down","tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0,"type":"ethernet"}]})"))); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 1 @@ -204,7 +204,7 @@ TEST_F(InventoryImpTest, noScanOnStart) EXPECT_CALL(*spInfoWrapper, ports()).Times(0); EXPECT_CALL(*spInfoWrapper, hotfixes()).Times(0); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -292,7 +292,7 @@ TEST_F(InventoryImpTest, noHardware) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult6)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult7)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -380,7 +380,7 @@ TEST_F(InventoryImpTest, noOs) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult5)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult7)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -468,7 +468,7 @@ TEST_F(InventoryImpTest, noNetwork) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult5)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult6)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -555,7 +555,7 @@ TEST_F(InventoryImpTest, noPackages) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult5)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult7)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -643,7 +643,7 @@ TEST_F(InventoryImpTest, noPorts) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult5)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult7)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 5 @@ -739,7 +739,7 @@ TEST_F(InventoryImpTest, noPortsAll) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult7)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult8)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -827,7 +827,7 @@ TEST_F(InventoryImpTest, noProcesses) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult5)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult7)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -916,7 +916,7 @@ TEST_F(InventoryImpTest, noHotfixes) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult5)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult7)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -974,7 +974,7 @@ TEST_F(InventoryImpTest, scanInvalidData) .WillRepeatedly(Return(nlohmann::json::parse( R"({"iface":[{"IPv4":[{"address":"172.17.0.1","broadcast":"172.17.255.255","dhcp":"unknown","metric":"0","netmask":"255.255.0.0"}],"adapter":"","gateway":"","mac":"02:42:1c:26:13:65","mtu":1500,"name":"docker0","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"state":"down","tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0,"type":"ethernet"}]})"))); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 60 @@ -1103,7 +1103,7 @@ TEST_F(InventoryImpTest, portAllEnable) EXPECT_CALL(wrapper, callbackMock(expectedResult3)).Times(1); EXPECT_CALL(wrapper, callbackMock(expectedResult4)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -1229,7 +1229,7 @@ TEST_F(InventoryImpTest, portAllDisable) EXPECT_CALL(wrapper, callbackMock(expectedResult2)).Times(1); EXPECT_CALL(wrapper, callbackMock(expectedResult3)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -1288,7 +1288,7 @@ TEST_F(InventoryImpTest, PackagesDuplicated) EXPECT_CALL(wrapper, callbackMock(expectedResult1)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -1342,7 +1342,7 @@ TEST_F(InventoryImpTest, hashId) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult2)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 3600 @@ -1405,7 +1405,7 @@ TEST_F(InventoryImpTest, statelessMessage) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult1)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult2)).Times(1); - std::string inventoryConfig = R"( + const std::string inventoryConfig = R"( inventory: enabled: true interval: 1 diff --git a/src/modules/inventory/tests/statelessEvent/statelessEvent_test.cpp b/src/modules/inventory/tests/statelessEvent/statelessEvent_test.cpp index 7f17739639..cefa2efe55 100644 --- a/src/modules/inventory/tests/statelessEvent/statelessEvent_test.cpp +++ b/src/modules/inventory/tests/statelessEvent/statelessEvent_test.cpp @@ -3,10 +3,9 @@ TEST(PackageEventTest, CreatePackageEvent) { - nlohmann::json data = {{"package", {{"name", "nginx"}, {"version", "1.18.0"}}}}; - - PackageEvent event("create", "2024-01-16T00:00:00Z", data); - nlohmann::json result = event.generate(); + const nlohmann::json data = {{"package", {{"name", "nginx"}, {"version", "1.18.0"}}}}; + const PackageEvent event("create", "2024-01-16T00:00:00Z", data); + const nlohmann::json result = event.generate(); EXPECT_EQ(result["event"]["action"], "package-installed"); EXPECT_EQ(result["event"]["category"][0], "package"); @@ -15,10 +14,9 @@ TEST(PackageEventTest, CreatePackageEvent) TEST(NetworkEventTest, CreateNetworkEvent) { - nlohmann::json data = {{"observer", {{"ingress", {{"interface", {{"name", "eth0"}}}}}}}}; - - NetworkEvent event("create", "2024-01-16T00:00:00Z", data); - nlohmann::json result = event.generate(); + const nlohmann::json data = {{"observer", {{"ingress", {{"interface", {{"name", "eth0"}}}}}}}}; + const NetworkEvent event("create", "2024-01-16T00:00:00Z", data); + const nlohmann::json result = event.generate(); EXPECT_EQ(result["event"]["action"], "network-interface-detected"); EXPECT_EQ(result["event"]["category"][0], "network"); @@ -27,10 +25,9 @@ TEST(NetworkEventTest, CreateNetworkEvent) TEST(HotfixEventTest, RemoveHotfixEvent) { - nlohmann::json data = {{"package", {{"hotfix", {{"name", "KB123456"}}}}}}; - - HotfixEvent event("remove", "2024-01-16T00:00:00Z", data); - nlohmann::json result = event.generate(); + const nlohmann::json data = {{"package", {{"hotfix", {{"name", "KB123456"}}}}}}; + const HotfixEvent event("remove", "2024-01-16T00:00:00Z", data); + const nlohmann::json result = event.generate(); EXPECT_EQ(result["event"]["action"], "hotfix-removed"); EXPECT_EQ(result["event"]["category"][0], "hotfix"); @@ -39,15 +36,15 @@ TEST(HotfixEventTest, RemoveHotfixEvent) TEST(PortEventTest, UpdatePortEvent) { - nlohmann::json data = nlohmann::json::parse(R"( + const nlohmann::json data = nlohmann::json::parse(R"( { "source": { "port": 8080 }, "destination": { "port": 443 } } )"); - PortEvent event("update", "2024-01-16T00:00:00Z", data); - nlohmann::json result = event.generate(); + const PortEvent event("update", "2024-01-16T00:00:00Z", data); + const nlohmann::json result = event.generate(); EXPECT_EQ(result["event"]["action"], "port-updated"); EXPECT_EQ(result["event"]["category"][0], "network"); @@ -57,10 +54,9 @@ TEST(PortEventTest, UpdatePortEvent) TEST(SystemEventTest, CreateSystemEvent) { - nlohmann::json data = {{"host", {{"hostname", "server01"}, {"os", {{"version", "Ubuntu 22.04"}}}}}}; - - SystemEvent event("create", "2024-01-16T00:00:00Z", data); - nlohmann::json result = event.generate(); + const nlohmann::json data = {{"host", {{"hostname", "server01"}, {"os", {{"version", "Ubuntu 22.04"}}}}}}; + const SystemEvent event("create", "2024-01-16T00:00:00Z", data); + const nlohmann::json result = event.generate(); EXPECT_EQ(result["event"]["action"], "system-detected"); EXPECT_EQ(result["event"]["category"][0], "host"); diff --git a/src/modules/logcollector/src/file_reader/src/file_reader_unix.cpp b/src/modules/logcollector/src/file_reader/src/file_reader_unix.cpp index 2dcb72cfea..0c89a5476d 100644 --- a/src/modules/logcollector/src/file_reader/src/file_reader_unix.cpp +++ b/src/modules/logcollector/src/file_reader/src/file_reader_unix.cpp @@ -12,7 +12,7 @@ void FileReader::Reload(const std::function& callback) { glob_t globResult; - int ret = glob(m_filePattern.c_str(), 0, nullptr, &globResult); + const int ret = glob(m_filePattern.c_str(), 0, nullptr, &globResult); if (ret != 0) { diff --git a/src/modules/logcollector/src/journald_reader/src/journal_log.cpp b/src/modules/logcollector/src/journald_reader/src/journal_log.cpp index 4977443bf3..79af54b6a4 100644 --- a/src/modules/logcollector/src/journald_reader/src/journal_log.cpp +++ b/src/modules/logcollector/src/journald_reader/src/journal_log.cpp @@ -21,28 +21,28 @@ JournalLog::~JournalLog() void JournalLog::Open() { - int ret = sd_journal_open(&m_journal, SD_JOURNAL_LOCAL_ONLY); + const int ret = sd_journal_open(&m_journal, SD_JOURNAL_LOCAL_ONLY); ThrowIfError(ret, "open journal"); LogInfo("Journal opened successfully"); } bool JournalLog::Next() { - int ret = sd_journal_next(m_journal); + const int ret = sd_journal_next(m_journal); ThrowIfError(ret, "next entry"); return ret > 0; } bool JournalLog::Previous() { - int ret = sd_journal_previous(m_journal); + const int ret = sd_journal_previous(m_journal); ThrowIfError(ret, "previous entry"); return ret > 0; } bool JournalLog::SeekHead() { - int ret = sd_journal_seek_head(m_journal); + const int ret = sd_journal_seek_head(m_journal); ThrowIfError(ret, "seek head"); return ret >= 0; } @@ -65,7 +65,7 @@ bool JournalLog::SeekTail() bool JournalLog::SeekTimestamp(uint64_t timestamp) { - int ret = sd_journal_seek_realtime_usec(m_journal, timestamp); + const int ret = sd_journal_seek_realtime_usec(m_journal, timestamp); ThrowIfError(ret, "seek timestamp"); return ret >= 0; } @@ -74,7 +74,7 @@ std::string JournalLog::GetData(const std::string& field) const { const void* data = nullptr; size_t length = 0; - int ret = sd_journal_get_data(m_journal, field.c_str(), &data, &length); + const int ret = sd_journal_get_data(m_journal, field.c_str(), &data, &length); if (ret == -ENOENT) { throw JournalLogException("Field not present in current journal entry"); @@ -82,8 +82,8 @@ std::string JournalLog::GetData(const std::string& field) const ThrowIfError(ret, "get data"); const char* str = static_cast(data); - std::string_view full_str(str, length); - size_t prefix_len = field.length() + 1; + const std::string_view full_str(str, length); + const size_t prefix_len = field.length() + 1; return std::string(full_str.substr(prefix_len)); } @@ -91,7 +91,7 @@ std::string JournalLog::GetData(const std::string& field) const uint64_t JournalLog::GetTimestamp() const { uint64_t timestamp = 0; - int ret = sd_journal_get_realtime_usec(m_journal, ×tamp); + const int ret = sd_journal_get_realtime_usec(m_journal, ×tamp); ThrowIfError(ret, "get timestamp"); return timestamp; } @@ -99,7 +99,7 @@ uint64_t JournalLog::GetTimestamp() const uint64_t JournalLog::GetOldestTimestamp() const { uint64_t timestamp = 0; - int ret = sd_journal_get_cutoff_realtime_usec(m_journal, ×tamp, nullptr); + const int ret = sd_journal_get_cutoff_realtime_usec(m_journal, ×tamp, nullptr); ThrowIfError(ret, "get oldest timestamp"); return timestamp; } @@ -196,7 +196,7 @@ uint64_t JournalLog::GetEpochTime() std::string JournalLog::GetCursor() const { char* rawCursor = nullptr; - int ret = sd_journal_get_cursor(m_journal, &rawCursor); + const int ret = sd_journal_get_cursor(m_journal, &rawCursor); ThrowIfError(ret, "get cursor"); if (!rawCursor) @@ -210,7 +210,7 @@ std::string JournalLog::GetCursor() const bool JournalLog::SeekCursor(const std::string& cursor) { - int ret = sd_journal_seek_cursor(m_journal, cursor.c_str()); + const int ret = sd_journal_seek_cursor(m_journal, cursor.c_str()); if (ret < 0) { LogWarn("Failed to seek to cursor: {}", strerror(-ret)); @@ -221,7 +221,7 @@ bool JournalLog::SeekCursor(const std::string& cursor) bool JournalLog::CursorValid(const std::string& cursor) const { - int ret = sd_journal_test_cursor(m_journal, cursor.c_str()); + const int ret = sd_journal_test_cursor(m_journal, cursor.c_str()); return ret > 0; } @@ -246,7 +246,7 @@ void JournalLog::AddFilterGroup(const FilterGroup& group, bool ignoreIfMissing) std::string match = filter.field + (filter.exact_match ? "=" : "~") + std::string(value); LogDebug("Adding journal match: {}", match); - int ret = sd_journal_add_match(m_journal, match.c_str(), 0); + const int ret = sd_journal_add_match(m_journal, match.c_str(), 0); if (ret < 0) { if (!ignoreIfMissing) @@ -287,7 +287,7 @@ bool JournalLog::ApplyFilterGroup(const FilterGroup& group, bool ignoreIfMissing { try { - std::string fieldValue = GetData(filter.field); + const std::string fieldValue = GetData(filter.field); return filter.Matches(fieldValue); } catch (const JournalLogException&) diff --git a/src/modules/logcollector/src/logcollector.cpp b/src/modules/logcollector/src/logcollector.cpp index 632bd8d7d7..2e759ec0dd 100644 --- a/src/modules/logcollector/src/logcollector.cpp +++ b/src/modules/logcollector/src/logcollector.cpp @@ -79,7 +79,7 @@ void Logcollector::Setup(std::shared_ptr configurationParser) { const auto fileWait = configurationParser->GetTimeConfigOrDefault( - config::logcollector::DEFAULT_RELOAD_INTERVAL, "logcollector", "read_interval"); + config::logcollector::DEFAULT_FILE_WAIT, "logcollector", "read_interval"); const auto reloadInterval = configurationParser->GetTimeConfigOrDefault( config::logcollector::DEFAULT_RELOAD_INTERVAL, "logcollector", "reload_interval"); @@ -170,7 +170,7 @@ void Logcollector::CleanAllReaders() } { - std::lock_guard lock(m_timersMutex); + const std::lock_guard lock(m_timersMutex); for (const auto& timer : m_timers) { timer->cancel(); diff --git a/src/modules/logcollector/src/logcollector_unix.cpp b/src/modules/logcollector/src/logcollector_unix.cpp index b9be67a1f6..16e2ea7906 100644 --- a/src/modules/logcollector/src/logcollector_unix.cpp +++ b/src/modules/logcollector/src/logcollector_unix.cpp @@ -42,9 +42,9 @@ namespace logcollector else { // Single condition case - FilterGroup filters {{config["field"].as(), - config["value"].as(), - config["exact_match"].as(true)}}; + const FilterGroup filters {{config["field"].as(), + config["value"].as(), + config["exact_match"].as(true)}}; AddReader(std::make_shared( *this, filters, config["ignore_if_missing"].as(false), fileWait)); diff --git a/src/modules/logcollector/tests/unit/journald_reader/journal_log_test.cpp b/src/modules/logcollector/tests/unit/journald_reader/journal_log_test.cpp index aa792574d2..a8d23ec22f 100644 --- a/src/modules/logcollector/tests/unit/journald_reader/journal_log_test.cpp +++ b/src/modules/logcollector/tests/unit/journald_reader/journal_log_test.cpp @@ -35,10 +35,10 @@ TEST_F(JournalLogTests, FilterValidation) bool expectedValid; }; - std::vector testCases = {{{"UNIT", "systemd-journald.service", true}, true}, - {{"", "value", true}, false}, - {{"field", "", true}, false}, - {{"field", "value", false}, true}}; + const std::vector testCases = {{{"UNIT", "systemd-journald.service", true}, true}, + {{"", "value", true}, false}, + {{"field", "", true}, false}, + {{"field", "value", false}, true}}; for (const auto& tc : testCases) { @@ -56,11 +56,11 @@ TEST_F(JournalLogTests, FilterMatching) bool expectedMatch; }; - std::vector testCases = {{{"UNIT", "test.service", true}, "test.service", true}, - {{"UNIT", "test", false}, "test.service", true}, - {{"UNIT", "service1|service2", true}, "service1", true}, - {{"UNIT", "service1|service2", true}, "service3", false}, - {{"UNIT", "sys|jour", false}, "system", true}}; + const std::vector testCases = {{{"UNIT", "test.service", true}, "test.service", true}, + {{"UNIT", "test", false}, "test.service", true}, + {{"UNIT", "service1|service2", true}, "service1", true}, + {{"UNIT", "service1|service2", true}, "service3", false}, + {{"UNIT", "sys|jour", false}, "system", true}}; for (const auto& tc : testCases) { @@ -101,7 +101,7 @@ TEST_F(JournalLogTests, MessageProcessing) auto group = CreateBasicFilterGroup(); journal->AddFilterGroup(group, true); - FilterSet filters {group}; + const FilterSet filters {group}; auto message = journal->GetNextFilteredMessage(filters, true); if (message) @@ -115,6 +115,6 @@ TEST_F(JournalLogTests, ErrorHandling) { EXPECT_THROW(journal->GetData("NONEXISTENT_FIELD"), JournalLogException); - FilterGroup invalidGroup {{"", "value", true}}; + const FilterGroup invalidGroup {{"", "value", true}}; EXPECT_THROW(journal->AddFilterGroup(invalidGroup, false), JournalLogException); } diff --git a/src/modules/logcollector/tests/unit/journald_reader/journald_reader_test.cpp b/src/modules/logcollector/tests/unit/journald_reader/journald_reader_test.cpp index 17e7996ab0..315cca93d9 100644 --- a/src/modules/logcollector/tests/unit/journald_reader/journald_reader_test.cpp +++ b/src/modules/logcollector/tests/unit/journald_reader/journald_reader_test.cpp @@ -54,13 +54,14 @@ TEST_F(JournaldReaderTests, FilterHandling) std::string expectedDesc; }; - std::vector testCases = {{{}, "0 conditions"}, - {{{"UNIT", "service1|service2", true}}, "1 conditions"}, - {{{"UNIT", "service1", true}, {"PRIORITY", "3|4|5", true}}, "2 conditions"}}; + const std::vector testCases = { + {{}, "0 conditions"}, + {{{"UNIT", "service1|service2", true}}, "1 conditions"}, + {{{"UNIT", "service1", true}, {"PRIORITY", "3|4|5", true}}, "2 conditions"}}; for (const auto& tc : testCases) { - JournaldReader reader(logcollector, tc.filters, ignoreIfMissing, fileWait); + const JournaldReader reader(logcollector, tc.filters, ignoreIfMissing, fileWait); EXPECT_THAT(reader.GetFilterDescription(), ::testing::HasSubstr(tc.expectedDesc)); } } diff --git a/src/modules/logcollector/tests/unit/macos_reader/macos_reader_test.cpp b/src/modules/logcollector/tests/unit/macos_reader/macos_reader_test.cpp index b9e3d6bea0..10fc2933e7 100644 --- a/src/modules/logcollector/tests/unit/macos_reader/macos_reader_test.cpp +++ b/src/modules/logcollector/tests/unit/macos_reader/macos_reader_test.cpp @@ -69,8 +69,8 @@ namespace macos_reader_tests boost::asio::post(ioContext, [&macOSReader]() -> void { - std::this_thread::sleep_for( - std::chrono::seconds(1)); // NOLINT(cppcoreguidelines-avoid-magic-numbers) + const auto sleepTime = std::chrono::seconds(1); + std::this_thread::sleep_for(std::chrono::seconds(sleepTime)); macOSReader.Stop(); }); @@ -119,8 +119,7 @@ namespace macos_reader_tests boost::asio::post(ioContext, [&macOSReader, &macOSReader2]() -> void { - std::this_thread::sleep_for( - std::chrono::seconds(1)); // NOLINT(cppcoreguidelines-avoid-magic-numbers) + std::this_thread::sleep_for(std::chrono::seconds(1)); macOSReader.Stop(); macOSReader2.Stop(); }); diff --git a/src/modules/src/moduleManager.cpp b/src/modules/src/moduleManager.cpp index 89dcdc6761..de856182c5 100644 --- a/src/modules/src/moduleManager.cpp +++ b/src/modules/src/moduleManager.cpp @@ -35,7 +35,7 @@ ModuleManager::ModuleManager(const std::function& pushMessage, void ModuleManager::AddModules() { { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); #ifdef ENABLE_INVENTORY Inventory& inventory = Inventory::Instance(); @@ -53,7 +53,7 @@ void ModuleManager::AddModules() std::shared_ptr ModuleManager::GetModule(const std::string& name) { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); if (auto it = m_modules.find(name); it != m_modules.end()) { return it->second; @@ -63,7 +63,7 @@ std::shared_ptr ModuleManager::GetModule(const std::string& name) void ModuleManager::Start() { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); m_taskManager.Start(m_modules.size()); @@ -92,7 +92,8 @@ void ModuleManager::Start() break; } - std::this_thread::sleep_for(std::chrono::milliseconds(10)); // NOLINT(cppcoreguidelines-avoid-magic-numbers) + const auto sleepTime = std::chrono::milliseconds(10); + std::this_thread::sleep_for(sleepTime); } if (m_started.load() != static_cast(m_modules.size())) @@ -103,7 +104,7 @@ void ModuleManager::Start() void ModuleManager::Setup() { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); for (const auto& [_, module] : m_modules) { @@ -113,7 +114,7 @@ void ModuleManager::Setup() void ModuleManager::Stop() { - std::lock_guard lock(m_mutex); + const std::lock_guard lock(m_mutex); for (const auto& [_, module] : m_modules) { diff --git a/src/modules/tests/moduleManager_test.cpp b/src/modules/tests/moduleManager_test.cpp index 13b508bddf..91cc5d6b3e 100644 --- a/src/modules/tests/moduleManager_test.cpp +++ b/src/modules/tests/moduleManager_test.cpp @@ -130,7 +130,7 @@ TEST_F(ModuleManagerTest, StartModules) [&]() { { - std::lock_guard lock(mtx); + const std::lock_guard lock(mtx); taskExecuted = true; } cv.notify_one(); @@ -163,7 +163,7 @@ TEST_F(ModuleManagerTest, StartMultipleModules) [&]() { { - std::lock_guard lock(mtx); + const std::lock_guard lock(mtx); taskExecuted = true; } cv.notify_one(); @@ -174,7 +174,7 @@ TEST_F(ModuleManagerTest, StartMultipleModules) [&]() { { - std::lock_guard lock(mtx); + const std::lock_guard lock(mtx); taskExecuted = true; } cv.notify_one();