From a90a5cba08fdf6c0ceb95101c275108a152a3aed Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 12 Jun 2024 07:35:37 +0200 Subject: Merging upstream version 127.0. Signed-off-by: Daniel Baumann --- .../tests/gtest/TestContentAnalysis.cpp | 257 +++++++++++++++++++++ .../tests/gtest/TestContentAnalysisAgent.cpp | 39 +--- .../tests/gtest/TestContentAnalysisAgent.h | 24 -- .../tests/gtest/TestContentAnalysisMisbehaving.cpp | 87 ++----- .../tests/gtest/TestContentAnalysisUtils.cpp | 24 +- .../tests/gtest/TestContentAnalysisUtils.h | 32 +++ 6 files changed, 335 insertions(+), 128 deletions(-) delete mode 100644 toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.h create mode 100644 toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.h (limited to 'toolkit/components/contentanalysis/tests/gtest') diff --git a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysis.cpp b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysis.cpp index cd083a7779..d974ac78db 100644 --- a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysis.cpp +++ b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysis.cpp @@ -8,13 +8,25 @@ #include "mozilla/Assertions.h" #include "mozilla/Logging.h" #include "mozilla/Preferences.h" +#include "mozilla/SpinEventLoopUntil.h" +#include "nsComponentManagerUtils.h" #include "nsNetUtil.h" +#include "nsIFile.h" +#include "nsIObserverService.h" +#include "nsIURI.h" +#include "nsIURIMutator.h" #include "ContentAnalysis.h" +#include "SpecialSystemDirectory.h" +#include "TestContentAnalysisUtils.h" #include #include +#include const char* kAllowUrlPref = "browser.contentanalysis.allow_url_regex_list"; const char* kDenyUrlPref = "browser.contentanalysis.deny_url_regex_list"; +const char* kPipePathNamePref = "browser.contentanalysis.pipe_path_name"; +const char* kIsDLPEnabledPref = "browser.contentanalysis.enabled"; +const char* kTimeoutPref = "browser.contentanalysis.agent_timeout"; using namespace mozilla; using namespace mozilla::contentanalysis; @@ -24,6 +36,9 @@ class ContentAnalysisTest : public testing::Test { ContentAnalysisTest() { auto* logmodule = LogModule::Get("contentanalysis"); logmodule->SetLevel(LogLevel::Verbose); + MOZ_ALWAYS_SUCCEEDS( + Preferences::SetString(kPipePathNamePref, mPipeName.get())); + MOZ_ALWAYS_SUCCEEDS(Preferences::SetBool(kIsDLPEnabledPref, true)); nsCOMPtr caSvc = do_GetService("@mozilla.org/contentanalysis;1"); @@ -35,17 +50,39 @@ class ContentAnalysisTest : public testing::Test { mContentAnalysis->mAllowUrlList = {}; mContentAnalysis->mDenyUrlList = {}; + MOZ_ALWAYS_SUCCEEDS(mContentAnalysis->TestOnlySetCACmdLineArg(true)); + MOZ_ALWAYS_SUCCEEDS(Preferences::SetCString(kAllowUrlPref, "")); MOZ_ALWAYS_SUCCEEDS(Preferences::SetCString(kDenyUrlPref, "")); + + bool isActive = false; + MOZ_ALWAYS_SUCCEEDS(mContentAnalysis->GetIsActive(&isActive)); + EXPECT_TRUE(isActive); + } + + // Note that the constructor (and SetUp() method) get called once per test, + // not once for the whole fixture. Because Firefox does not currently + // reconnect to an agent after the DLP pipe is closed (bug 1888293), we only + // want to create the agent once and make sure the same process stays alive + // through all of these tests. + static void SetUpTestSuite() { + GeneratePipeName(L"contentanalysissdk-gtest-", mPipeName); + mAgentInfo = LaunchAgentNormal(L"block", mPipeName); } + static void TearDownTestSuite() { mAgentInfo.TerminateProcess(); } + void TearDown() override { mContentAnalysis->mParsedUrlLists = false; mContentAnalysis->mAllowUrlList = {}; mContentAnalysis->mDenyUrlList = {}; + MOZ_ALWAYS_SUCCEEDS(mContentAnalysis->TestOnlySetCACmdLineArg(false)); + MOZ_ALWAYS_SUCCEEDS(Preferences::SetCString(kAllowUrlPref, "")); MOZ_ALWAYS_SUCCEEDS(Preferences::SetCString(kDenyUrlPref, "")); + MOZ_ALWAYS_SUCCEEDS(Preferences::ClearUser(kPipePathNamePref)); + MOZ_ALWAYS_SUCCEEDS(Preferences::ClearUser(kIsDLPEnabledPref)); } already_AddRefed CreateRequest(const char* aUrl) { @@ -62,6 +99,8 @@ class ContentAnalysisTest : public testing::Test { } RefPtr mContentAnalysis; + static nsString mPipeName; + static MozAgentInfo mAgentInfo; // Proxies for private members of ContentAnalysis. TEST_F // creates new subclasses -- they do not inherit `friend`s. @@ -71,6 +110,8 @@ class ContentAnalysisTest : public testing::Test { return mContentAnalysis->FilterByUrlLists(aReq); } }; +nsString ContentAnalysisTest::mPipeName; +MozAgentInfo ContentAnalysisTest::mAgentInfo; TEST_F(ContentAnalysisTest, AllowUrlList) { MOZ_ALWAYS_SUCCEEDS( @@ -124,3 +165,219 @@ TEST_F(ContentAnalysisTest, DenyOverridesAllowUrlList) { CreateRequest("https://example.org/matchme/"); ASSERT_EQ(FilterByUrlLists(car), UrlFilterResult::eDeny); } + +nsCOMPtr GetExampleDotComURI() { + nsCOMPtr uri; + MOZ_ALWAYS_SUCCEEDS(NS_NewURI(getter_AddRefs(uri), "https://example.com")); + return uri; +} + +void SendRequestAndExpectResponse( + RefPtr contentAnalysis, + const nsCOMPtr& request, + Maybe expectedShouldAllow, + Maybe expectedAction) { + std::atomic gotResponse = false; + std::atomic timedOut = false; + auto callback = MakeRefPtr( + [&](nsIContentAnalysisResponse* response) { + if (expectedShouldAllow.isSome()) { + bool shouldAllow = false; + MOZ_ALWAYS_SUCCEEDS(response->GetShouldAllowContent(&shouldAllow)); + EXPECT_EQ(*expectedShouldAllow, shouldAllow); + } + if (expectedAction.isSome()) { + nsIContentAnalysisResponse::Action action; + MOZ_ALWAYS_SUCCEEDS(response->GetAction(&action)); + EXPECT_EQ(*expectedAction, action); + } + nsCString requestToken, originalRequestToken; + MOZ_ALWAYS_SUCCEEDS(response->GetRequestToken(requestToken)); + MOZ_ALWAYS_SUCCEEDS(request->GetRequestToken(originalRequestToken)); + EXPECT_EQ(originalRequestToken, requestToken); + gotResponse = true; + }, + [&gotResponse](nsresult error) { + EXPECT_EQ(NS_OK, error); + gotResponse = true; + // Make sure that we didn't somehow get passed NS_OK + FAIL() << "Got error response"; + }); + + MOZ_ALWAYS_SUCCEEDS( + contentAnalysis->AnalyzeContentRequestCallback(request, false, callback)); + RefPtr timer = + NS_NewCancelableRunnableFunction("Content Analysis timeout", [&] { + if (!gotResponse.load()) { + timedOut = true; + } + }); + NS_DelayedDispatchToCurrentThread(do_AddRef(timer), 10000); + mozilla::SpinEventLoopUntil("Waiting for ContentAnalysis result"_ns, [&]() { + return gotResponse.load() || timedOut.load(); + }); + timer->Cancel(); + EXPECT_TRUE(gotResponse); + EXPECT_FALSE(timedOut); +} + +TEST_F(ContentAnalysisTest, SendAllowedTextToAgent_GetAllowedResponse) { + nsCOMPtr uri = GetExampleDotComURI(); + nsString allow(L"allow"); + nsCOMPtr request = new ContentAnalysisRequest( + nsIContentAnalysisRequest::AnalysisType::eBulkDataEntry, std::move(allow), + false, EmptyCString(), uri, + nsIContentAnalysisRequest::OperationType::eClipboard, nullptr); + + SendRequestAndExpectResponse(mContentAnalysis, request, Some(true), + Some(nsIContentAnalysisResponse::eAllow)); +} + +TEST_F(ContentAnalysisTest, SendBlockedTextToAgent_GetBlockResponse) { + nsCOMPtr uri = GetExampleDotComURI(); + nsString block(L"block"); + nsCOMPtr request = new ContentAnalysisRequest( + nsIContentAnalysisRequest::AnalysisType::eBulkDataEntry, std::move(block), + false, EmptyCString(), uri, + nsIContentAnalysisRequest::OperationType::eClipboard, nullptr); + + SendRequestAndExpectResponse(mContentAnalysis, request, Some(false), + Some(nsIContentAnalysisResponse::eBlock)); +} + +class RawRequestObserver final : public nsIObserver { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSIOBSERVER + RawRequestObserver() {} + + const std::vector& + GetRequests() { + return mRequests; + } + + private: + ~RawRequestObserver() = default; + std::vector mRequests; +}; + +NS_IMPL_ISUPPORTS(RawRequestObserver, nsIObserver); + +NS_IMETHODIMP RawRequestObserver::Observe(nsISupports* aSubject, + const char* aTopic, + const char16_t* aData) { + std::wstring dataWideString(reinterpret_cast(aData)); + std::vector dataVector(dataWideString.size()); + for (size_t i = 0; i < dataWideString.size(); ++i) { + // Since this data is really bytes and not a null-terminated string, the + // calling code adds 0xFF00 to every member to ensure there are no 0 values. + dataVector[i] = static_cast(dataWideString[i] - 0xFF00); + } + content_analysis::sdk::ContentAnalysisRequest request; + EXPECT_TRUE(request.ParseFromArray(dataVector.data(), dataVector.size())); + mRequests.push_back(std::move(request)); + return NS_OK; +} + +TEST_F(ContentAnalysisTest, CheckRawRequestWithText) { + MOZ_ALWAYS_SUCCEEDS(Preferences::SetInt(kTimeoutPref, 65)); + nsCOMPtr uri = GetExampleDotComURI(); + nsString allow(L"allow"); + nsCOMPtr request = new ContentAnalysisRequest( + nsIContentAnalysisRequest::AnalysisType::eBulkDataEntry, std::move(allow), + false, EmptyCString(), uri, + nsIContentAnalysisRequest::OperationType::eClipboard, nullptr); + nsCOMPtr obsServ = + mozilla::services::GetObserverService(); + auto rawRequestObserver = MakeRefPtr(); + MOZ_ALWAYS_SUCCEEDS( + obsServ->AddObserver(rawRequestObserver, "dlp-request-sent-raw", false)); + time_t now = time(nullptr); + + SendRequestAndExpectResponse(mContentAnalysis, request, Nothing(), Nothing()); + auto requests = rawRequestObserver->GetRequests(); + EXPECT_EQ(static_cast(1), requests.size()); + time_t t = requests[0].expires_at(); + time_t secs_remaining = t - now; + // There should be around 65 seconds remaining + EXPECT_LE(abs(secs_remaining - 65), 2); + const auto& request_url = requests[0].request_data().url(); + EXPECT_EQ(uri->GetSpecOrDefault(), + nsCString(request_url.data(), request_url.size())); + nsCString request_user_action_id(requests[0].user_action_id().data(), + requests[0].user_action_id().size()); + // The user_action_id has a GUID appended to the end, just make sure the + // beginning is right. + request_user_action_id.Truncate(8); + EXPECT_EQ(nsCString("Firefox "), request_user_action_id); + const auto& request_text = requests[0].text_content(); + EXPECT_EQ(nsCString("allow"), + nsCString(request_text.data(), request_text.size())); + + MOZ_ALWAYS_SUCCEEDS( + obsServ->RemoveObserver(rawRequestObserver, "dlp-request-sent-raw")); + MOZ_ALWAYS_SUCCEEDS(Preferences::ClearUser(kTimeoutPref)); +} + +TEST_F(ContentAnalysisTest, CheckRawRequestWithFile) { + nsCOMPtr uri = GetExampleDotComURI(); + nsCOMPtr file; + MOZ_ALWAYS_SUCCEEDS(GetSpecialSystemDirectory(OS_CurrentWorkingDirectory, + getter_AddRefs(file))); + nsString allowRelativePath(L"allowedFile.txt"); + MOZ_ALWAYS_SUCCEEDS(file->AppendRelativePath(allowRelativePath)); + nsString allowPath; + MOZ_ALWAYS_SUCCEEDS(file->GetPath(allowPath)); + + nsCOMPtr request = new ContentAnalysisRequest( + nsIContentAnalysisRequest::AnalysisType::eBulkDataEntry, allowPath, true, + EmptyCString(), uri, nsIContentAnalysisRequest::OperationType::eClipboard, + nullptr); + nsCOMPtr obsServ = + mozilla::services::GetObserverService(); + auto rawRequestObserver = MakeRefPtr(); + MOZ_ALWAYS_SUCCEEDS( + obsServ->AddObserver(rawRequestObserver, "dlp-request-sent-raw", false)); + + SendRequestAndExpectResponse(mContentAnalysis, request, Nothing(), Nothing()); + auto requests = rawRequestObserver->GetRequests(); + EXPECT_EQ(static_cast(1), requests.size()); + const auto& request_url = requests[0].request_data().url(); + EXPECT_EQ(uri->GetSpecOrDefault(), + nsCString(request_url.data(), request_url.size())); + nsCString request_user_action_id(requests[0].user_action_id().data(), + requests[0].user_action_id().size()); + // The user_action_id has a GUID appended to the end, just make sure the + // beginning is right. + request_user_action_id.Truncate(8); + EXPECT_EQ(nsCString("Firefox "), request_user_action_id); + const auto& request_file_path = requests[0].file_path(); + EXPECT_EQ(NS_ConvertUTF16toUTF8(allowPath), + nsCString(request_file_path.data(), request_file_path.size())); + + MOZ_ALWAYS_SUCCEEDS( + obsServ->RemoveObserver(rawRequestObserver, "dlp-request-sent-raw")); +} + +TEST_F(ContentAnalysisTest, CheckTwoRequestsHaveSameUserActionId) { + nsCOMPtr uri = GetExampleDotComURI(); + nsString allow(L"allow"); + nsCOMPtr request = new ContentAnalysisRequest( + nsIContentAnalysisRequest::AnalysisType::eBulkDataEntry, std::move(allow), + false, EmptyCString(), uri, + nsIContentAnalysisRequest::OperationType::eClipboard, nullptr); + nsCOMPtr obsServ = + mozilla::services::GetObserverService(); + auto rawRequestObserver = MakeRefPtr(); + MOZ_ALWAYS_SUCCEEDS( + obsServ->AddObserver(rawRequestObserver, "dlp-request-sent-raw", false)); + + SendRequestAndExpectResponse(mContentAnalysis, request, Nothing(), Nothing()); + SendRequestAndExpectResponse(mContentAnalysis, request, Nothing(), Nothing()); + auto requests = rawRequestObserver->GetRequests(); + EXPECT_EQ(static_cast(2), requests.size()); + EXPECT_EQ(requests[0].user_action_id(), requests[1].user_action_id()); + + MOZ_ALWAYS_SUCCEEDS( + obsServ->RemoveObserver(rawRequestObserver, "dlp-request-sent-raw")); +} diff --git a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.cpp b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.cpp index 5b2b76b963..d7a41cc5ff 100644 --- a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.cpp +++ b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.cpp @@ -8,29 +8,12 @@ #include "mozilla/Assertions.h" #include "mozilla/CmdLineAndEnvUtils.h" #include "content_analysis/sdk/analysis_client.h" -#include "TestContentAnalysisAgent.h" +#include "TestContentAnalysisUtils.h" #include #include using namespace content_analysis::sdk; -MozAgentInfo LaunchAgentNormal(const wchar_t* aToBlock) { - nsString cmdLineArguments; - if (aToBlock && aToBlock[0] != 0) { - cmdLineArguments.Append(L" --toblock=.*"); - cmdLineArguments.Append(aToBlock); - cmdLineArguments.Append(L".*"); - } - cmdLineArguments.Append(L" --user"); - cmdLineArguments.Append(L" --path="); - nsString pipeName; - GeneratePipeName(L"contentanalysissdk-gtest-", pipeName); - cmdLineArguments.Append(pipeName); - MozAgentInfo agentInfo; - LaunchAgentWithCommandLineArguments(cmdLineArguments, pipeName, agentInfo); - return agentInfo; -} - TEST(ContentAnalysisAgent, TextShouldNotBeBlocked) { auto MozAgentInfo = LaunchAgentNormal(L"block"); @@ -49,10 +32,7 @@ TEST(ContentAnalysisAgent, TextShouldNotBeBlocked) response.results().Get(0).status()); ASSERT_EQ(0, response.results().Get(0).triggered_rules_size()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisAgent, TextShouldBeBlocked) @@ -75,10 +55,7 @@ TEST(ContentAnalysisAgent, TextShouldBeBlocked) ASSERT_EQ(ContentAnalysisResponse_Result_TriggeredRule_Action_BLOCK, response.results().Get(0).triggered_rules(0).action()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisAgent, FileShouldNotBeBlocked) @@ -99,10 +76,7 @@ TEST(ContentAnalysisAgent, FileShouldNotBeBlocked) response.results().Get(0).status()); ASSERT_EQ(0, response.results().Get(0).triggered_rules_size()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisAgent, FileShouldBeBlocked) @@ -125,8 +99,5 @@ TEST(ContentAnalysisAgent, FileShouldBeBlocked) ASSERT_EQ(ContentAnalysisResponse_Result_TriggeredRule_Action_BLOCK, response.results().Get(0).triggered_rules(0).action()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } diff --git a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.h b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.h deleted file mode 100644 index 9e31036262..0000000000 --- a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisAgent.h +++ /dev/null @@ -1,24 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef mozilla_testcontentanalysis_h -#define mozilla_testcontentanalysis_h - -#include - -#include "content_analysis/sdk/analysis_client.h" -#include "gtest/gtest.h" -#include "nsString.h" - -struct MozAgentInfo { - PROCESS_INFORMATION processInfo; - std::unique_ptr client; -}; - -void GeneratePipeName(const wchar_t* prefix, nsString& pipeName); -void LaunchAgentWithCommandLineArguments(const nsString& cmdLineArguments, - const nsString& pipeName, - MozAgentInfo& agentInfo); -#endif diff --git a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisMisbehaving.cpp b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisMisbehaving.cpp index 7c944ed6e3..a120a82f7c 100644 --- a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisMisbehaving.cpp +++ b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisMisbehaving.cpp @@ -8,7 +8,7 @@ #include "mozilla/Assertions.h" #include "mozilla/CmdLineAndEnvUtils.h" #include "content_analysis/sdk/analysis_client.h" -#include "TestContentAnalysisAgent.h" +#include "TestContentAnalysisUtils.h" #include #include #include @@ -70,10 +70,7 @@ TEST(ContentAnalysisMisbehaving, InvalidUtf8StringStartByteIsContinuationByte) // or invalid memory access or something. ASSERT_STREQ("\x80\x41\x41\x41", response.request_token().c_str()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, @@ -95,10 +92,7 @@ TEST(ContentAnalysisMisbehaving, // or invalid memory access or something. ASSERT_STREQ("\x41\xf0\x90\x8d", response.request_token().c_str()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, InvalidUtf8StringMultibyteSequenceTooShort) @@ -119,10 +113,7 @@ TEST(ContentAnalysisMisbehaving, InvalidUtf8StringMultibyteSequenceTooShort) // or invalid memory access or something. ASSERT_STREQ("\xf0\x90\x8d\x41", response.request_token().c_str()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, InvalidUtf8StringDecodesToInvalidCodePoint) @@ -143,10 +134,7 @@ TEST(ContentAnalysisMisbehaving, InvalidUtf8StringDecodesToInvalidCodePoint) // or invalid memory access or something. ASSERT_STREQ("\xf7\xbf\xbf\xbf", response.request_token().c_str()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, InvalidUtf8StringOverlongEncoding) @@ -167,10 +155,7 @@ TEST(ContentAnalysisMisbehaving, InvalidUtf8StringOverlongEncoding) // or invalid memory access or something. ASSERT_STREQ("\xf0\x82\x82\xac", response.request_token().c_str()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, StringWithEmbeddedNull) @@ -188,10 +173,7 @@ TEST(ContentAnalysisMisbehaving, StringWithEmbeddedNull) std::string expected("\x41\x00\x41"); ASSERT_EQ(expected, response.request_token()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, ZeroResults) @@ -208,10 +190,7 @@ TEST(ContentAnalysisMisbehaving, ZeroResults) ASSERT_EQ(0, MozAgentInfo.client->Send(request, &response)); ASSERT_EQ(0, response.results().size()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, ResultWithInvalidStatus) @@ -232,10 +211,7 @@ TEST(ContentAnalysisMisbehaving, ResultWithInvalidStatus) // just make sure we can get the value without throwing ASSERT_GE(static_cast(response.results(0).status()), 0); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageTruncatedInMiddleOfString) @@ -252,10 +228,7 @@ TEST(ContentAnalysisMisbehaving, MessageTruncatedInMiddleOfString) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageWithInvalidWireType) @@ -271,10 +244,7 @@ TEST(ContentAnalysisMisbehaving, MessageWithInvalidWireType) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageWithUnusedFieldNumber) @@ -292,10 +262,7 @@ TEST(ContentAnalysisMisbehaving, MessageWithUnusedFieldNumber) // just make sure we can get a value without throwing ASSERT_STREQ("", response.request_token().c_str()); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageWithWrongStringWireType) @@ -311,10 +278,7 @@ TEST(ContentAnalysisMisbehaving, MessageWithWrongStringWireType) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageWithZeroTag) @@ -330,10 +294,7 @@ TEST(ContentAnalysisMisbehaving, MessageWithZeroTag) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageWithZeroFieldButNonzeroWireType) @@ -350,10 +311,7 @@ TEST(ContentAnalysisMisbehaving, MessageWithZeroFieldButNonzeroWireType) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageWithGroupEnd) @@ -370,10 +328,7 @@ TEST(ContentAnalysisMisbehaving, MessageWithGroupEnd) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageTruncatedInMiddleOfVarint) @@ -390,10 +345,7 @@ TEST(ContentAnalysisMisbehaving, MessageTruncatedInMiddleOfVarint) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } TEST(ContentAnalysisMisbehaving, MessageTruncatedInMiddleOfTag) @@ -409,8 +361,5 @@ TEST(ContentAnalysisMisbehaving, MessageTruncatedInMiddleOfTag) // The response is an invalid serialization of protobuf, so this should fail ASSERT_EQ(-1, MozAgentInfo.client->Send(request, &response)); - BOOL terminateResult = - ::TerminateProcess(MozAgentInfo.processInfo.hProcess, 0); - ASSERT_NE(FALSE, terminateResult) - << "Failed to terminate content_analysis_sdk_agent process"; + MozAgentInfo.TerminateProcess(); } diff --git a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.cpp b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.cpp index 0e14de6b81..8bcfe018ee 100644 --- a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.cpp +++ b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.cpp @@ -3,13 +3,35 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ -#include "TestContentAnalysisAgent.h" +#include "TestContentAnalysisUtils.h" #include #include #include #include #include +MozAgentInfo LaunchAgentNormal(const wchar_t* aToBlock) { + nsString pipeName; + GeneratePipeName(L"contentanalysissdk-gtest-", pipeName); + return LaunchAgentNormal(aToBlock, pipeName); +} + +MozAgentInfo LaunchAgentNormal(const wchar_t* aToBlock, + const nsString& pipeName) { + nsString cmdLineArguments; + if (aToBlock && aToBlock[0] != 0) { + cmdLineArguments.Append(L" --toblock=.*"); + cmdLineArguments.Append(aToBlock); + cmdLineArguments.Append(L".*"); + } + cmdLineArguments.Append(L" --user"); + cmdLineArguments.Append(L" --path="); + cmdLineArguments.Append(pipeName); + MozAgentInfo agentInfo; + LaunchAgentWithCommandLineArguments(cmdLineArguments, pipeName, agentInfo); + return agentInfo; +} + void GeneratePipeName(const wchar_t* prefix, nsString& pipeName) { pipeName = u""_ns; pipeName.Append(prefix); diff --git a/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.h b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.h new file mode 100644 index 0000000000..fd437de3f7 --- /dev/null +++ b/toolkit/components/contentanalysis/tests/gtest/TestContentAnalysisUtils.h @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +#ifndef mozilla_testcontentanalysis_h +#define mozilla_testcontentanalysis_h + +#include + +#include "content_analysis/sdk/analysis_client.h" +#include "gtest/gtest.h" +#include "nsString.h" + +struct MozAgentInfo { + PROCESS_INFORMATION processInfo; + std::unique_ptr client; + void TerminateProcess() { + BOOL terminateResult = ::TerminateProcess(processInfo.hProcess, 0); + ASSERT_NE(FALSE, terminateResult) + << "Failed to terminate content_analysis_sdk_agent process"; + } +}; + +void GeneratePipeName(const wchar_t* prefix, nsString& pipeName); +void LaunchAgentWithCommandLineArguments(const nsString& cmdLineArguments, + const nsString& pipeName, + MozAgentInfo& agentInfo); +MozAgentInfo LaunchAgentNormal(const wchar_t* aToBlock); +MozAgentInfo LaunchAgentNormal(const wchar_t* aToBlock, + const nsString& pipeName); +#endif -- cgit v1.2.3