1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#include "chrome/browser/enterprise/connectors/common.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/strings/to_string.h"
#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/enterprise/connectors/connectors_service.h"
#include "chrome/browser/enterprise/connectors/test/deep_scanning_test_utils.h"
#include "chrome/browser/policy/dm_token_utils.h"
#include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_utils.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/mock_download_item.h"
#include "components/enterprise/common/proto/connectors.pb.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/fake_download_item.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_renderer_host.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace enterprise_connectors {
namespace {
#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
struct CustomMessageTestCase {
TriggeredRule::Action action;
std::string message;
};
constexpr char kDmToken[] = "dm_token";
constexpr char kTestUrl[] = "http://example.com/";
constexpr char kTestInvalidUrl[] = "example.com";
constexpr char kTestMessage[] = "test";
constexpr char16_t kU16TestMessage[] = u"test";
constexpr char kTestMessage2[] = "test2";
constexpr char kGoogleServiceProvider[] = R"(
{
"service_provider": "google",
"enable": [
{
"url_list": ["*"],
"tags": ["dlp"]
}
],
"block_large_files": 1
})";
constexpr char kTestEscapedHtmlMessage[] = "<>&"'";
constexpr char16_t kTestUnescapedHtmlMessage[] = u"<>&\"'";
// Offset to first placeholder index for
// IDS_DEEP_SCANNING_DIALOG_CUSTOM_MESSAGE.
constexpr size_t kRuleMessageOffset = 26;
constexpr char kTestLinkedMessage[] = "Learn More";
constexpr char16_t kU16TestLinkedMessage[] = u"Learn More";
ContentAnalysisResponse CreateContentAnalysisResponse(
const std::vector<CustomMessageTestCase>& triggered_rules,
const std::string& url) {
ContentAnalysisResponse response;
auto* result = response.add_results();
result->set_tag("dlp");
result->set_status(
enterprise_connectors::ContentAnalysisResponse::Result::SUCCESS);
for (const auto& triggered_rule : triggered_rules) {
auto* rule = result->add_triggered_rules();
rule->set_action(triggered_rule.action);
if (!triggered_rule.message.empty()) {
ContentAnalysisResponse::Result::TriggeredRule::CustomRuleMessage
custom_message;
auto* custom_segment = custom_message.add_message_segments();
custom_segment->set_text(triggered_rule.message);
auto* custom_linked_segment = custom_message.add_message_segments();
custom_linked_segment->set_text(kTestLinkedMessage);
custom_linked_segment->set_link(url);
*rule->mutable_custom_rule_message() = custom_message;
}
}
return response;
}
class BaseTest : public testing::Test {
public:
BaseTest() : profile_manager_(TestingBrowserProcess::GetGlobal()) {
EXPECT_TRUE(profile_manager_.SetUp());
profile_ = profile_manager_.CreateTestingProfile("test-user");
}
void EnableFeatures() { scoped_feature_list_.Reset(); }
Profile* profile() { return profile_; }
protected:
content::BrowserTaskEnvironment task_environment_;
base::test::ScopedFeatureList scoped_feature_list_;
TestingProfileManager profile_manager_;
raw_ptr<TestingProfile> profile_;
};
#endif // BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
} // namespace
#if BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
class EnterpriseConnectorsResultShouldAllowDataUseTest
: public BaseTest,
public testing::WithParamInterface<bool> {
public:
EnterpriseConnectorsResultShouldAllowDataUseTest() = default;
void SetUp() override {
BaseTest::SetUp();
EnableFeatures();
// Settings can't be returned if no DM token exists.
SetDMTokenForTesting(policy::DMToken::CreateValidToken(kDmToken));
}
bool allowed() const { return !GetParam(); }
std::string bool_setting() const { return base::ToString(GetParam()); }
const char* default_action_setting() const {
return GetParam() ? "block" : "allow";
}
AnalysisSettings settings() {
std::optional<AnalysisSettings> settings =
ConnectorsServiceFactory::GetForBrowserContext(profile())
->GetAnalysisSettings(GURL(kTestUrl), FILE_ATTACHED);
EXPECT_TRUE(settings.has_value());
return std::move(settings.value());
}
};
INSTANTIATE_TEST_SUITE_P(,
EnterpriseConnectorsResultShouldAllowDataUseTest,
testing::Bool());
TEST_P(EnterpriseConnectorsResultShouldAllowDataUseTest, BlockLargeFile) {
auto pref = base::StringPrintf(R"(
{
"service_provider": "google",
"enable": [{"url_list": ["*"], "tags": ["dlp"]}],
"block_large_files": %s
})",
bool_setting());
test::SetAnalysisConnector(profile()->GetPrefs(), FILE_ATTACHED, pref);
EXPECT_EQ(allowed(),
ResultShouldAllowDataUse(
settings(),
safe_browsing::BinaryUploadService::Result::FILE_TOO_LARGE));
}
TEST_P(EnterpriseConnectorsResultShouldAllowDataUseTest,
BlockPasswordProtected) {
auto pref = base::StringPrintf(R"(
{
"service_provider": "google",
"enable": [{"url_list": ["*"], "tags": ["dlp"]}],
"block_password_protected": %s
})",
bool_setting());
test::SetAnalysisConnector(profile()->GetPrefs(), FILE_ATTACHED, pref);
EXPECT_EQ(allowed(),
ResultShouldAllowDataUse(
settings(),
safe_browsing::BinaryUploadService::Result::FILE_ENCRYPTED));
}
TEST_P(EnterpriseConnectorsResultShouldAllowDataUseTest, BlockUploadFailure) {
auto pref = base::StringPrintf(R"(
{
"service_provider": "google",
"enable": [{"url_list": ["*"], "tags": ["dlp"]}],
"default_action": "%s"
})",
default_action_setting());
test::SetAnalysisConnector(profile()->GetPrefs(), FILE_ATTACHED, pref);
EXPECT_EQ(allowed(),
ResultShouldAllowDataUse(
settings(),
safe_browsing::BinaryUploadService::Result::UPLOAD_FAILURE));
}
class ContentAnalysisResponseCustomMessageTest
: public BaseTest,
public testing::WithParamInterface<
std::tuple<std::vector<CustomMessageTestCase>, std::u16string>> {
public:
ContentAnalysisResponseCustomMessageTest() = default;
void SetUp() override {
BaseTest::SetUp();
EnableFeatures();
// Settings can't be returned if no DM token exists.
SetDMTokenForTesting(policy::DMToken::CreateValidToken(kDmToken));
}
std::vector<CustomMessageTestCase> triggered_rules() const {
return std::get<0>(GetParam());
}
std::u16string expected_message() const { return std::get<1>(GetParam()); }
AnalysisSettings settings() {
std::optional<AnalysisSettings> settings =
ConnectorsServiceFactory::GetForBrowserContext(profile())
->GetAnalysisSettings(GURL(kTestUrl), FILE_ATTACHED);
EXPECT_TRUE(settings.has_value());
return std::move(settings.value());
}
};
TEST_P(ContentAnalysisResponseCustomMessageTest, ValidUrlCustomMessage) {
test::SetAnalysisConnector(profile()->GetPrefs(), FILE_ATTACHED,
kGoogleServiceProvider);
ContentAnalysisResponse response =
CreateContentAnalysisResponse(triggered_rules(), kTestUrl);
RequestHandlerResult result = CalculateRequestHandlerResult(
settings(), safe_browsing::BinaryUploadService::Result::SUCCESS,
response);
std::u16string custom_message =
GetCustomRuleString(result.custom_rule_message);
std::vector<std::pair<gfx::Range, GURL>> custom_ranges =
GetCustomRuleStyles(result.custom_rule_message, kRuleMessageOffset);
EXPECT_EQ(custom_message,
custom_message.empty()
? std::u16string{}
: base::StrCat({expected_message(), kU16TestLinkedMessage}));
if (custom_message.empty()) {
EXPECT_TRUE(custom_ranges.empty());
} else {
EXPECT_EQ(1u, custom_ranges.size());
EXPECT_EQ(strlen(kTestLinkedMessage),
custom_ranges.begin()->first.length());
EXPECT_EQ(custom_ranges.begin()->first.start(),
expected_message().length() + kRuleMessageOffset);
}
}
TEST_P(ContentAnalysisResponseCustomMessageTest, InvalidUrlCustomMessage) {
test::SetAnalysisConnector(profile()->GetPrefs(), FILE_ATTACHED,
kGoogleServiceProvider);
ContentAnalysisResponse response =
CreateContentAnalysisResponse(triggered_rules(), kTestInvalidUrl);
RequestHandlerResult result = CalculateRequestHandlerResult(
settings(), safe_browsing::BinaryUploadService::Result::SUCCESS,
response);
std::u16string custom_message =
GetCustomRuleString(result.custom_rule_message);
std::vector<std::pair<gfx::Range, GURL>> custom_ranges =
GetCustomRuleStyles(result.custom_rule_message, kRuleMessageOffset);
EXPECT_EQ(custom_message,
custom_message.empty()
? std::u16string{}
: base::StrCat({expected_message(), kU16TestLinkedMessage}));
EXPECT_TRUE(custom_ranges.empty());
}
TEST_P(ContentAnalysisResponseCustomMessageTest, DownloadsItemCustomMessage) {
ContentAnalysisResponse response =
CreateContentAnalysisResponse(triggered_rules(), kTestUrl);
download::DownloadDangerType danger_type;
TriggeredRule::Action action = GetHighestPrecedenceAction(response, nullptr);
if (action == TriggeredRule::WARN) {
danger_type = download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING;
} else {
danger_type = download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_BLOCK;
}
// Create download item
testing::NiceMock<download::MockDownloadItem> item;
enterprise_connectors::FileMetadata file_metadata(
"examplename", "12345678", "fake/mimetype", 1234, response);
auto scan_result = std::make_unique<enterprise_connectors::ScanResult>(
std::move(file_metadata));
item.SetUserData(enterprise_connectors::ScanResult::kKey,
std::move(scan_result));
auto custom_rule_message = GetDownloadsCustomRuleMessage(&item, danger_type);
if (custom_rule_message.has_value()) {
EXPECT_EQ(GetCustomRuleString(custom_rule_message.value()),
base::StrCat({expected_message(), kU16TestLinkedMessage}));
} else {
EXPECT_EQ(std::u16string{}, expected_message());
}
}
INSTANTIATE_TEST_SUITE_P(
,
ContentAnalysisResponseCustomMessageTest,
testing::Values(
std::make_tuple(std::vector<CustomMessageTestCase>(),
/*expected_message=*/std::u16string{}),
std::make_tuple(
std::vector<CustomMessageTestCase>{
{.action = TriggeredRule::WARN, .message = ""}},
/*expected_message=*/std::u16string{}),
std::make_tuple(
std::vector<CustomMessageTestCase>{
{.action = TriggeredRule::WARN, .message = kTestMessage}},
/*expected_message=*/kU16TestMessage),
std::make_tuple(
std::vector<CustomMessageTestCase>{
{.action = TriggeredRule::BLOCK, .message = ""},
{.action = TriggeredRule::WARN, .message = kTestMessage}},
/*expected_message=*/std::u16string{}),
std::make_tuple(
std::vector<CustomMessageTestCase>{
{.action = TriggeredRule::BLOCK, .message = ""},
{.action = TriggeredRule::BLOCK, .message = kTestMessage}},
/*expected_message=*/kU16TestMessage),
std::make_tuple(
std::vector<CustomMessageTestCase>{
{.action = TriggeredRule::BLOCK, .message = kTestMessage},
{.action = TriggeredRule::WARN, .message = kTestMessage2}},
/*expected_message=*/kU16TestMessage),
std::make_tuple(
std::vector<CustomMessageTestCase>{
{.action = TriggeredRule::BLOCK,
.message = kTestEscapedHtmlMessage}},
/*expected_message=*/kTestUnescapedHtmlMessage)));
class CollectFrameUrlsTest : public BaseTest {
public:
CollectFrameUrlsTest() = default;
protected:
void SetUp() override {
BaseTest::SetUp();
// Create test web contents as we need to navigate to a URL to get a valid
// frame chain.
web_contents_ = content::WebContentsTester::CreateTestWebContents(
profile(), content::SiteInstance::Create(profile()));
content::WebContentsTester::For(web_contents_.get())
->NavigateAndCommit(GURL(kTestUrl));
}
void TearDown() override {
// `WebContentsTester` needs to be destroyed before the
// `RenderViewHostTestEnabler`.
if (web_contents_) {
web_contents_.reset();
}
BaseTest::TearDown();
}
content::WebContents* web_contents() { return web_contents_.get(); }
private:
std::unique_ptr<content::WebContents> web_contents_;
// Needed for frame tree and navigation operations.
content::RenderViewHostTestEnabler rvh_test_enabler_;
};
TEST_F(CollectFrameUrlsTest, NestedFramesWithUninterestingUrl) {
base::HistogramTester histogram_tester;
// Create test URLs.
const GURL child_frame_url1("http://child1.example.com/");
const GURL child_frame_url2("http://child2.example.com/");
const GURL uninteresting_url("about:blank");
// Create main frame.
content::RenderFrameHost* main_frame = web_contents()->GetPrimaryMainFrame();
content::RenderFrameHostTester* main_frame_tester =
content::RenderFrameHostTester::For(main_frame);
// Create and navigate the first child frame.
content::RenderFrameHost* child_frame1 =
main_frame_tester->AppendChild("child1");
content::NavigationSimulator::NavigateAndCommitFromDocument(child_frame_url1,
child_frame1);
// Create and navigate the second (nested) child frame.
content::RenderFrameHostTester* child_frame1_tester =
content::RenderFrameHostTester::For(child_frame1);
content::RenderFrameHost* child_frame2 =
child_frame1_tester->AppendChild("child2");
content::NavigationSimulator::NavigateAndCommitFromDocument(child_frame_url2,
child_frame2);
// Create and navigate the third (nested) child frame with uninteresting URL.
content::RenderFrameHostTester* child_frame2_tester =
content::RenderFrameHostTester::For(child_frame2);
content::RenderFrameHost* child_frame3 =
child_frame2_tester->AppendChild("child3");
content::NavigationSimulator::NavigateAndCommitFromDocument(uninteresting_url,
child_frame3);
// Set focus on the innermost frame.
content::FocusWebContentsOnFrame(web_contents(), child_frame3);
google::protobuf::RepeatedPtrField<std::string> frame_urls =
CollectFrameUrls(web_contents(), DeepScanAccessPoint::DOWNLOAD);
// Verify that the URL chain is listed in the right order and chain size
// histogram is recorded properly.
ASSERT_EQ(3, frame_urls.size());
EXPECT_EQ(child_frame_url2.spec(), frame_urls[0]);
EXPECT_EQ(child_frame_url1.spec(), frame_urls[1]);
EXPECT_EQ(kTestUrl, frame_urls[2]);
histogram_tester.ExpectTotalCount(
"Enterprise.IframeDlpRulesSupport.Download.UrlChainSize", 1);
histogram_tester.ExpectBucketCount(
"Enterprise.IframeDlpRulesSupport.Download.UrlChainSize", 3, 1);
}
#endif // BUILDFLAG(ENTERPRISE_CONTENT_ANALYSIS)
} // namespace enterprise_connectors
|