File: site_isolation_policy_browsertest.cc

package info (click to toggle)
chromium 140.0.7339.127-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,192,880 kB
  • sloc: cpp: 35,093,808; ansic: 7,161,670; javascript: 4,199,694; python: 1,441,797; asm: 949,904; xml: 747,503; pascal: 187,748; perl: 88,691; sh: 88,248; objc: 79,953; sql: 52,714; cs: 44,599; fortran: 24,137; makefile: 22,114; tcl: 15,277; php: 13,980; yacc: 9,000; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (473 lines) | stat: -rw-r--r-- 19,841 bytes parent folder | download | duplicates (4)
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// Copyright 2017 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/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "content/public/browser/site_isolation_policy.h"

#include "base/command_line.h"
#include "base/containers/span.h"
#include "base/feature_list.h"
#include "base/test/scoped_amount_of_physical_memory_override.h"
#include "base/test/scoped_feature_list.h"
#include "build/android_buildflags.h"
#include "build/build_config.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "chrome/test/base/platform_browser_test.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/site_isolation/features.h"
#include "components/site_isolation/site_isolation_policy.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/site_instance.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_utils.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/default_handlers.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_ANDROID)
#include "chrome/browser/safe_browsing/android/advanced_protection_status_manager_test_util.h"
#endif

#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/ui_test_utils.h"
#endif

class SiteIsolationPolicyBrowserTest : public PlatformBrowserTest {
 public:
  SiteIsolationPolicyBrowserTest(const SiteIsolationPolicyBrowserTest&) =
      delete;
  SiteIsolationPolicyBrowserTest& operator=(
      const SiteIsolationPolicyBrowserTest&) = delete;

 protected:
  SiteIsolationPolicyBrowserTest() = default;

  struct Expectations {
    const char* url;
    bool isolated;
  };

  void CheckExpectations(base::span<Expectations> expectations,
                         size_t spanification_suspected_redundant_count) {
    // TODO(crbug.com/431824301): Remove unneeded parameter once validated to be
    // redundant in M143.
    CHECK(spanification_suspected_redundant_count == expectations.size(),
          base::NotFatalUntil::M143);
    content::BrowserContext* context = chrome_test_utils::GetProfile(this);
    for (size_t i = 0; i < spanification_suspected_redundant_count; ++i) {
      const GURL url(expectations[i].url);
      auto instance = content::SiteInstance::CreateForURL(context, url);
      EXPECT_EQ(expectations[i].isolated, instance->RequiresDedicatedProcess())
          << "; url = " << url;
    }
  }

  void CheckIsolatedOriginExpectations(
      base::span<Expectations> expectations,
      size_t spanification_suspected_redundant_count) {
    // TODO(crbug.com/431824301): Remove unneeded parameter once validated to be
    // redundant in M143.
    CHECK(spanification_suspected_redundant_count == expectations.size(),
          base::NotFatalUntil::M143);
    if (!content::AreAllSitesIsolatedForTesting()) {
      CheckExpectations(expectations, spanification_suspected_redundant_count);
    }

    auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
    for (size_t i = 0; i < spanification_suspected_redundant_count; ++i) {
      const GURL url(expectations[i].url);
      const url::Origin origin = url::Origin::Create(url);
      EXPECT_EQ(expectations[i].isolated,
                policy->IsGloballyIsolatedOriginForTesting(origin))
          << "; origin = " << origin;
    }
  }

  testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_;
};

template <bool policy_value>
class SitePerProcessPolicyBrowserTest : public SiteIsolationPolicyBrowserTest {
 public:
  SitePerProcessPolicyBrowserTest(const SitePerProcessPolicyBrowserTest&) =
      delete;
  SitePerProcessPolicyBrowserTest& operator=(
      const SitePerProcessPolicyBrowserTest&) = delete;

 protected:
  SitePerProcessPolicyBrowserTest() = default;

  void SetUpInProcessBrowserTestFixture() override {
    // We setup the policy here, because the policy must be 'live' before
    // the renderer is created, since the value for this policy is passed
    // to the renderer via a command-line. Setting the policy in the test
    // itself or in SetUpOnMainThread works for update-able policies, but
    // is too late for this one.
    provider_.SetDefaultReturns(
        true /* is_initialization_complete_return */,
        true /* is_first_policy_load_complete_return */);
    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);

    policy::PolicyMap values;

#if BUILDFLAG(IS_ANDROID)
    const char* kPolicyName = policy::key::kSitePerProcessAndroid;
#else
    const char* kPolicyName = policy::key::kSitePerProcess;
#endif
    values.Set(kPolicyName, policy::POLICY_LEVEL_MANDATORY,
               policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
               base::Value(policy_value), nullptr);
    provider_.UpdateChromePolicy(values);
  }
};

typedef SitePerProcessPolicyBrowserTest<true>
    SitePerProcessPolicyBrowserTestEnabled;
typedef SitePerProcessPolicyBrowserTest<false>
    SitePerProcessPolicyBrowserTestDisabled;

// Ensure that --disable-site-isolation-trials and/or
// --disable-site-isolation-for-enterprise-policy do not override policies.
class NoOverrideSitePerProcessPolicyBrowserTest
    : public SitePerProcessPolicyBrowserTestEnabled {
 public:
  NoOverrideSitePerProcessPolicyBrowserTest(
      const NoOverrideSitePerProcessPolicyBrowserTest&) = delete;
  NoOverrideSitePerProcessPolicyBrowserTest& operator=(
      const NoOverrideSitePerProcessPolicyBrowserTest&) = delete;

 protected:
  NoOverrideSitePerProcessPolicyBrowserTest() = default;
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kDisableSiteIsolation);
#if BUILDFLAG(IS_ANDROID)
    command_line->AppendSwitch(switches::kDisableSiteIsolationForPolicy);
#endif
  }
};

IN_PROC_BROWSER_TEST_F(SitePerProcessPolicyBrowserTestEnabled, Simple) {
  Expectations expectations[] = {
      {"https://foo.com/noodles.html", true},
      {"http://foo.com/", true},
      {"http://example.org/pumpkins.html", true},
  };
  CheckExpectations(expectations, std::size(expectations));
}

#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
// The policy is not supported on Android
class IsolateOriginsPolicyBrowserTest : public SiteIsolationPolicyBrowserTest {
 public:
  IsolateOriginsPolicyBrowserTest(const IsolateOriginsPolicyBrowserTest&) =
      delete;
  IsolateOriginsPolicyBrowserTest& operator=(
      const IsolateOriginsPolicyBrowserTest&) = delete;

 protected:
  IsolateOriginsPolicyBrowserTest() = default;

  void SetUpInProcessBrowserTestFixture() override {
    // We setup the policy here, because the policy must be 'live' before
    // the renderer is created, since the value for this policy is passed
    // to the renderer via a command-line. Setting the policy in the test
    // itself or in SetUpOnMainThread works for update-able policies, but
    // is too late for this one.
    provider_.SetDefaultReturns(
        true /* is_initialization_complete_return */,
        true /* is_first_policy_load_complete_return */);
    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);

    policy::PolicyMap values;
    values.Set(
        policy::key::kIsolateOrigins, policy::POLICY_LEVEL_MANDATORY,
        policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
        base::Value("https://policy1.example.org/,http://policy2.example.com"),
        nullptr);
    provider_.UpdateChromePolicy(values);
  }
};

IN_PROC_BROWSER_TEST_F(IsolateOriginsPolicyBrowserTest, Simple) {
  // Verify that the policy present at browser startup is correctly applied.
  Expectations expectations[] = {
      {"https://foo.com/noodles.html", false},
      {"http://foo.com/", false},
      {"https://policy1.example.org/pumpkins.html", true},
      {"http://policy2.example.com/index.php", true},
  };
  CheckIsolatedOriginExpectations(expectations, std::size(expectations));

  // Simulate updating the policy at "browser runtime".
  policy::PolicyMap values;
  values.Set(
      policy::key::kIsolateOrigins, policy::POLICY_LEVEL_MANDATORY,
      policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
      base::Value("https://policy3.example.org/,http://policy4.example.com"),
      nullptr);
  provider_.UpdateChromePolicy(values);

  // Verify that the policy update above has taken effect:
  // - policy3 and policy4 origins should become isolated
  // - policy1 and policy2 origins will remain isolated, even though they were
  //   removed from the policy (this is an artifact caused by limitations of
  //   the current implementation, not something that is a hard requirement).
  Expectations expectations2[] = {
      {"https://foo.com/noodles.html", false},
      {"http://foo.com/", false},
      {"https://policy1.example.org/pumpkins.html", true},
      {"http://policy2.example.com/index.php", true},
      {"https://policy3.example.org/pumpkins.html", true},
      {"http://policy4.example.com/index.php", true},
  };
  CheckIsolatedOriginExpectations(expectations2, std::size(expectations2));
}
#endif

IN_PROC_BROWSER_TEST_F(NoOverrideSitePerProcessPolicyBrowserTest, Simple) {
  Expectations expectations[] = {
      {"https://foo.com/noodles.html", true},
      {"http://example.org/pumpkins.html", true},
  };
  CheckExpectations(expectations, std::size(expectations));
}

// After https://crbug.com/910273 was fixed, enterprise policy can only be used
// to disable Site Isolation on Android - the
// SitePerProcessPolicyBrowserTestFieldTrialTest tests should not be run on any
// other platform.  Note that browser_tests won't run on Android until
// https://crbug.com/611756 is fixed.
#if BUILDFLAG(IS_ANDROID)
class SitePerProcessPolicyBrowserTestFieldTrialTest
    : public SitePerProcessPolicyBrowserTestDisabled {
 public:
  SitePerProcessPolicyBrowserTestFieldTrialTest() {
    scoped_feature_list_.InitAndEnableFeature(features::kSitePerProcess);
  }
  SitePerProcessPolicyBrowserTestFieldTrialTest(
      const SitePerProcessPolicyBrowserTestFieldTrialTest&) = delete;
  SitePerProcessPolicyBrowserTestFieldTrialTest& operator=(
      const SitePerProcessPolicyBrowserTestFieldTrialTest&) = delete;
  ~SitePerProcessPolicyBrowserTestFieldTrialTest() override = default;

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_F(SitePerProcessPolicyBrowserTestFieldTrialTest, Simple) {
  // Skip this test if the --site-per-process switch is present (e.g. on Site
  // Isolation Android chromium.fyi bot).  The test is still valid if
  // SitePerProcess is the default (e.g. via ContentBrowserClient's
  // ShouldEnableStrictSiteIsolation method) - don't skip the test in such case.
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kSitePerProcess)) {
    return;
  }

  // Policy should inject kDisableSiteIsolationForPolicy rather than
  // kDisableSiteIsolation switch.
  EXPECT_FALSE(base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableSiteIsolation));
  ASSERT_TRUE(base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableSiteIsolationForPolicy));
  EXPECT_FALSE(
      content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites());

  Expectations expectations[] = {
      {"https://foo.com/noodles.html", false},
      {"http://example.org/pumpkins.html", false},
  };
  CheckExpectations(expectations, std::size(expectations));
}
#endif

#if BUILDFLAG(IS_ANDROID)
namespace {
bool CheckUseDedicatedProcessesForAllSitesWithAndroidState(
    bool is_under_advanced_protection,
    uint64_t ram_kb) {
  safe_browsing::SetAdvancedProtectionStateForTesting(
      is_under_advanced_protection);
  ChromeContentBrowserClient::DisableAdvancedProtectionCachingForTests();

  base::test::ScopedAmountOfPhysicalMemoryOverride memory_override(ram_kb);
  site_isolation::SiteIsolationPolicy::
      SetDisallowMemoryThresholdCachingForTesting(true);
  return content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites();
}
}  // anonymous namespace
#endif  // BUILDFLAG(IS_ANDROID)

IN_PROC_BROWSER_TEST_F(SiteIsolationPolicyBrowserTest,
                       NoPolicyNoTrialsFlags_NoAdvancedProtection_HighRam) {
  // The switch to disable Site Isolation should be missing by default (i.e.
  // without an explicit enterprise policy).
  EXPECT_FALSE(base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableSiteIsolation));
#if BUILDFLAG(IS_ANDROID) && !BUILDFLAG(ENABLE_ANDROID_SITE_ISOLATION)
  EXPECT_FALSE(base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableSiteIsolationForPolicy));
  EXPECT_EQ(CheckUseDedicatedProcessesForAllSitesWithAndroidState(
                /*is_under_advanced_protection=*/false,
                /*ram_kb=*/8000),
            base::FeatureList::IsEnabled(features::kSitePerProcess));
#else
  EXPECT_TRUE(content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites());
#endif  // BUILDFLAG(IS_ANDROID) && !BUILDFLAG(ENABLE_ANDROID_SITE_ISOLATION)
}

#if BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(SiteIsolationPolicyBrowserTest,
                       NoPolicy_AdvancedProtection_HighRam) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  EXPECT_FALSE(command_line->HasSwitch(switches::kDisableSiteIsolation));
  EXPECT_FALSE(
      command_line->HasSwitch(switches::kDisableSiteIsolationForPolicy));
  EXPECT_TRUE(CheckUseDedicatedProcessesForAllSitesWithAndroidState(
      /*is_under_advanced_protection=*/true,
      /*ram_kb=*/8000));
}

IN_PROC_BROWSER_TEST_F(SiteIsolationPolicyBrowserTest,
                       NoPolicy_AdvancedProtection_LowRam) {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  // Skip this test if the --site-per-process switch is present (e.g. on Site
  // Isolation Android chromium.fyi bot).
  if (command_line->HasSwitch(switches::kSitePerProcess)) {
    return;
  }

  EXPECT_FALSE(command_line->HasSwitch(switches::kDisableSiteIsolation));
  EXPECT_FALSE(
      command_line->HasSwitch(switches::kDisableSiteIsolationForPolicy));
  EXPECT_FALSE(CheckUseDedicatedProcessesForAllSitesWithAndroidState(
      /*is_under_advanced_protection=*/true,
      /*ram_kb=*/1000));
}
#endif

#if !BUILDFLAG(IS_ANDROID)
// Parameterized test class to check that an enterprise policy can set the
// origin-keyed processes by default feature, but a user can override the value
// that was set by the enterprise policy (via either the command-line flags or
// about:flags).
class OriginKeyedProcessesEnabledPolicyBrowserTest
    : public SiteIsolationPolicyBrowserTest,
      public testing::WithParamInterface<bool> {
 public:
  OriginKeyedProcessesEnabledPolicyBrowserTest(
      const OriginKeyedProcessesEnabledPolicyBrowserTest&) = delete;
  OriginKeyedProcessesEnabledPolicyBrowserTest& operator=(
      const OriginKeyedProcessesEnabledPolicyBrowserTest&) = delete;

  net::EmbeddedTestServer* https_server() { return &https_server_; }

 protected:
  OriginKeyedProcessesEnabledPolicyBrowserTest()
      : https_server_(net::EmbeddedTestServer::TYPE_HTTPS) {
    if (GetParam()) {
      // Turn off the origin-keyed processes feature via user intervention. This
      // will override the enterprise setting which will have it set to be
      // enabled.
      scoped_feature_list_.InitWithFeaturesAndParameters(
          {/*enabled_features*/},
          {/*disabled_features=*/features::kOriginKeyedProcessesByDefault});
    } else {
      // Without user override, set the memory threshold to a high value that
      // would not be reached, normally causing the feature to remain disabled.
      // This will check that overrides will ignore memory threshold limits.
      scoped_feature_list_.InitWithFeaturesAndParameters(
          {{site_isolation::features::kOriginIsolationMemoryThreshold,
            {{site_isolation::features::
                  kOriginIsolationMemoryThresholdParamName,
              std::string("524288")}}}},
          {/*disabled_features*/});
    }
  }

  void SetUpInProcessBrowserTestFixture() override {
    // We setup the policy here, because the policy must be 'live' before
    // the renderer is created, since the value for this policy is passed
    // to the renderer via a command-line. Setting the policy in the test
    // itself or in SetUpOnMainThread works for update-able policies, but
    // is too late for this one.
    provider_.SetDefaultReturns(
        true /* is_initialization_complete_return */,
        true /* is_first_policy_load_complete_return */);
    policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);

    policy::PolicyMap values;
    values.Set(policy::key::kOriginKeyedProcessesEnabled,
               policy::POLICY_LEVEL_RECOMMENDED, policy::POLICY_SCOPE_MACHINE,
               policy::POLICY_SOURCE_CLOUD, base::Value(true), nullptr);
    provider_.UpdateChromePolicy(values);
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    https_server()->ServeFilesFromSourceDirectory(GetChromeTestDataDir());
    https_server()->SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES);
    content::SetupCrossSiteRedirector(https_server());
    net::test_server::RegisterDefaultHandlers(https_server());
    ASSERT_TRUE(https_server()->Start());
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
  net::EmbeddedTestServer https_server_;
};

INSTANTIATE_TEST_SUITE_P(All,
                         OriginKeyedProcessesEnabledPolicyBrowserTest,
                         testing::Bool(),
                         [](auto& info) {
                           return info.param ? "WithUserOverride"
                                             : "WithoutUserOverride";
                         });

IN_PROC_BROWSER_TEST_P(OriginKeyedProcessesEnabledPolicyBrowserTest, Simple) {
  GURL start_url(https_server()->GetURL("a.test", "/iframe.html"));
  GURL cross_origin_url(
      https_server()->GetURL("crossorigin.a.test", "/simple.html"));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), start_url));
  EXPECT_TRUE(NavigateIframeToURL(web_contents, "test", cross_origin_url));

  content::RenderFrameHost* root_rfh = web_contents->GetPrimaryMainFrame();
  content::RenderFrameHost* child_rfh = ChildFrameAt(root_rfh, 0);

  if (GetParam()) {
    // The user overrode the enterprise policy to turn the feature off.
    EXPECT_EQ(root_rfh->GetProcess(), child_rfh->GetProcess())
        << "The root frame and child iframe should be in the same process.";
  } else {
    // There is no user override. The enterprise policy has highest priority and
    // turns the feature on, even if the memory threshold is higher than this
    // machine's physical memory.
    EXPECT_NE(root_rfh->GetProcess(), child_rfh->GetProcess())
        << "The root frame and child iframe should be in separate processes.";
  }
}
#endif  // !BUILDFLAG(IS_ANDROID)