File: cloud_policy_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (638 lines) | stat: -rw-r--r-- 26,167 bytes parent folder | download | duplicates (3)
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdint.h>

#include <memory>
#include <utility>

#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
#include "chrome/browser/policy/chrome_browser_policy_connector.h"
#include "chrome/browser/policy/cloud/cloud_policy_test_utils.h"
#include "chrome/browser/policy/policy_util.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "chrome/test/base/platform_browser_test.h"
#include "components/invalidation/impl/fake_invalidation_service.h"
#include "components/invalidation/impl/profile_identity_provider.h"
#include "components/invalidation/invalidation_factory.h"
#include "components/invalidation/profile_invalidation_provider.h"
#include "components/invalidation/public/invalidation.h"
#include "components/invalidation/public/invalidation_service.h"
#include "components/invalidation/public/invalidation_util.h"
#include "components/invalidation/test_support/fake_invalidation_listener.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/browser/cloud/user_policy_signin_service_base.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h"
#include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
#include "components/policy/core/common/cloud/user_cloud_policy_store.h"
#include "components/policy/core/common/external_data_fetcher.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/core/common/policy_switches.h"
#include "components/policy/core/common/policy_test_utils.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "components/policy/proto/chrome_settings.pb.h"
#include "components/policy/proto/cloud_policy.pb.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "components/policy/test_support/embedded_policy_test_server.h"
#include "components/policy/test_support/policy_storage.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/identity_manager/identity_test_environment.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/functional/overload.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/policy/core/user_cloud_policy_manager_ash.h"
#include "chromeos/ash/components/cryptohome/cryptohome_parameters.h"
#include "chromeos/ash/components/dbus/userdataauth/userdataauth_client.h"
#include "chromeos/dbus/constants/dbus_paths.h"  // nogncheck
#include "components/account_id/account_id.h"
#include "components/user_manager/user_names.h"
#else
#include "chrome/browser/net/system_network_context_manager.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#endif

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

using testing::_;
using testing::AnyNumber;
using testing::InvokeWithoutArgs;
using testing::Mock;
using testing::Return;

namespace content {
class BrowserContext;
}

namespace em = enterprise_management;

namespace policy {

namespace {

constexpr char kPolicyInvalidationTopic[] = "test_policy_topic";
constexpr char kPolicyInvalidationType[] = "USER_POLICY_FETCH";

struct FeaturesTestParam {
  std::vector<base::test::FeatureRef> enabled_features;
  std::vector<base::test::FeatureRef> disabled_features;
};

std::variant<std::unique_ptr<invalidation::InvalidationService>,
             std::unique_ptr<invalidation::InvalidationListener>>
CreateInvalidationServiceForSenderId(int64_t project_number,
                                     std::string /*log_prefix*/) {
  if (invalidation::IsInvalidationListenerSupported(project_number)) {
    return std::make_unique<invalidation::FakeInvalidationListener>(
        std::move(project_number));
  }
  return std::make_unique<invalidation::FakeInvalidationService>();
}

std::unique_ptr<KeyedService> BuildFakeProfileInvalidationProvider(
    content::BrowserContext* context) {
  Profile* profile = static_cast<Profile*>(context);
  return std::make_unique<invalidation::ProfileInvalidationProvider>(
      std::make_unique<invalidation::ProfileIdentityProvider>(
          IdentityManagerFactory::GetForProfile(profile)),
      base::BindRepeating(&CreateInvalidationServiceForSenderId));
}

const char* GetTestUser() {
#if BUILDFLAG(IS_CHROMEOS)
  return user_manager::kStubUserEmail;
#else
  return "user@example.com";
#endif
}

em::CloudPolicySettings GetTestPolicy(const char* homepage) {
  em::CloudPolicySettings settings;

  em::BooleanPolicyProto* saving_browser_history_disabled =
      settings.mutable_savingbrowserhistorydisabled();
  saving_browser_history_disabled->mutable_policy_options()->set_mode(
      em::PolicyOptions::MANDATORY);
  saving_browser_history_disabled->set_value(true);

  em::IntegerPolicyProto* default_popups_setting =
      settings.mutable_defaultpopupssetting();
  default_popups_setting->mutable_policy_options()->set_mode(
      em::PolicyOptions::MANDATORY);
  default_popups_setting->set_value(4);

  em::StringListPolicyProto* url_blocklist = settings.mutable_urlblocklist();
  url_blocklist->mutable_policy_options()->set_mode(
      em::PolicyOptions::MANDATORY);
  url_blocklist->mutable_value()->add_entries("dev.chromium.org");
  url_blocklist->mutable_value()->add_entries("youtube.com");

  em::StringPolicyProto* default_search_provider_name =
      settings.mutable_defaultsearchprovidername();
  default_search_provider_name->mutable_policy_options()->set_mode(
      em::PolicyOptions::MANDATORY);
  default_search_provider_name->set_value("MyDefaultSearchEngine");

  em::StringPolicyProto* homepage_location =
      settings.mutable_homepagelocation();
  homepage_location->mutable_policy_options()->set_mode(
      em::PolicyOptions::RECOMMENDED);
  homepage_location->set_value(homepage);

  return settings;
}

void GetExpectedTestPolicy(PolicyMap* expected, const char* homepage) {
  GetExpectedDefaultPolicy(expected);

  expected->Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
                POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(true),
                nullptr);
  expected->Set(key::kDefaultPopupsSetting, POLICY_LEVEL_MANDATORY,
                POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(4),
                nullptr);
  base::Value::List list;
  list.Append("dev.chromium.org");
  list.Append("youtube.com");
  expected->Set(key::kURLBlocklist, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
                POLICY_SOURCE_CLOUD, base::Value(std::move(list)), nullptr);
  expected->Set(key::kDefaultSearchProviderName, POLICY_LEVEL_MANDATORY,
                POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
                base::Value("MyDefaultSearchEngine"), nullptr);
  expected->Set(key::kHomepageLocation, POLICY_LEVEL_RECOMMENDED,
                POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(homepage),
                nullptr);
}

}  // namespace

// Tests the cloud policy stack(s).
class CloudPolicyTest : public PlatformBrowserTest,
                        public PolicyService::Observer,
                        public testing::WithParamInterface<FeaturesTestParam> {
 protected:
  CloudPolicyTest() {
    scoped_feature_list_.InitWithFeatures(GetParam().enabled_features,
                                          GetParam().disabled_features);
  }
  ~CloudPolicyTest() override = default;

  void SetUpInProcessBrowserTestFixture() override {
    PlatformBrowserTest::SetUpOnMainThread();

    test_server_ = std::make_unique<EmbeddedPolicyTestServer>();
    ASSERT_TRUE(test_server_->Start());

    ASSERT_NO_FATAL_FAILURE(
        SetServerPolicy(em::CloudPolicySettings(), 1, std::string()));

    std::string url = test_server_->GetServiceURL().spec();

    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    command_line->AppendSwitchASCII(switches::kDeviceManagementUrl, url);
    ChromeBrowserPolicyConnector::EnableCommandLineSupportForTesting();
  }

  void CreatedBrowserMainParts(
      content::BrowserMainParts* browser_main_parts) override {
    PlatformBrowserTest::CreatedBrowserMainParts(browser_main_parts);
    invalidation::ProfileInvalidationProviderFactory::GetInstance()
        ->RegisterTestingFactory(
            base::BindRepeating(&BuildFakeProfileInvalidationProvider));
  }

  void SetUpOnMainThread() override {
    ASSERT_TRUE(PolicyServiceIsEmpty(g_browser_process->policy_service()))
        << "Pre-existing policies in this machine will make this test fail.";

    BrowserPolicyConnector* connector =
        g_browser_process->browser_policy_connector();
    connector->ScheduleServiceInitialization(0);

#if BUILDFLAG(IS_CHROMEOS)
    UserCloudPolicyManagerAsh* policy_manager =
        chrome_test_utils::GetProfile(this)->GetUserCloudPolicyManagerAsh();
    ASSERT_TRUE(policy_manager);
#else
    Profile* profile = chrome_test_utils::GetProfile(this);

    // Mock a signed-in user. This is used by the UserCloudPolicyStore to pass
    // the username to the UserCloudPolicyValidator.
    identity_test_env_ = std::make_unique<signin::IdentityTestEnvironment>();
    identity_test_env_->MakePrimaryAccountAvailable(
        GetTestUser(), signin::ConsentLevel::kSync);

    UserCloudPolicyManager* policy_manager =
        profile->GetUserCloudPolicyManager();
    ASSERT_TRUE(policy_manager);
    policy_manager->Connect(
        g_browser_process->local_state(),
        std::make_unique<CloudPolicyClient>(
            connector->device_management_service(),
            g_browser_process->shared_url_loader_factory()));
#endif  // BUILDFLAG(IS_CHROMEOS)

    ASSERT_TRUE(policy_manager->core()->client());

    // The registration below will trigger a policy refresh (see
    // CloudPolicyRefreshScheduler::OnRegistrationStateChanged). When the tests
    // below call RefreshPolicies(), the first policy request will be cancelled
    // (see CloudPolicyClient::FetchPolicy which will reset
    // |policy_fetch_request_job_|). When the URLLoader implementation sees the
    // SimpleURLLoader going away, it'll cancel it's request as well. This race
    // sometimes causes errors in the Python policy server (|test_server_|).
    // Work around this by removing the refresh scheduler as an observer
    // temporarily.
    policy_manager->core()->client()->RemoveObserver(
        policy_manager->core()->refresh_scheduler());

    base::RunLoop run_loop;
    MockCloudPolicyClientObserver observer;
    EXPECT_CALL(observer, OnRegistrationStateChanged(_))
        .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit));
    policy_manager->core()->client()->AddObserver(&observer);

    // Give a bogus OAuth token to the |policy_manager|. This should make its
    // CloudPolicyClient fetch the DMToken.
    ASSERT_FALSE(policy_manager->core()->client()->is_registered());
    CloudPolicyClient::RegistrationParameters parameters(
#if BUILDFLAG(IS_CHROMEOS)
        em::DeviceRegisterRequest::USER,
#else
        em::DeviceRegisterRequest::BROWSER,
#endif
        em::DeviceRegisterRequest::FLAVOR_USER_REGISTRATION);
    policy_manager->core()->client()->Register(
        parameters, std::string() /* client_id */,
        "oauth_token_unused" /* oauth_token */);
    run_loop.Run();
    Mock::VerifyAndClearExpectations(&observer);
    policy_manager->core()->client()->RemoveObserver(&observer);
    EXPECT_TRUE(policy_manager->core()->client()->is_registered());

    // Readd the refresh scheduler as an observer now that the first policy
    // fetch finished.
    policy_manager->core()->client()->AddObserver(
        policy_manager->core()->refresh_scheduler());

#if BUILDFLAG(IS_CHROMEOS)
    // Get the path to the user policy key file.
    base::FilePath user_policy_key_dir;
    ASSERT_TRUE(base::PathService::Get(
        chromeos::dbus_paths::DIR_USER_POLICY_KEYS, &user_policy_key_dir));
    std::string sanitized_username =
        ash::UserDataAuthClient::GetStubSanitizedUsername(
            cryptohome::CreateAccountIdentifierFromAccountId(
                AccountId::FromUserEmail(GetTestUser())));
    user_policy_key_file_ = user_policy_key_dir.AppendASCII(sanitized_username)
                                .AppendASCII("policy.pub");
#else
    user_policy_key_file_ =
        profile->GetPath().AppendASCII("Policy").AppendASCII("Signing Key");
#endif  // BUILDFLAG(IS_CHROMEOS)
  }

  void TearDownOnMainThread() override {
    identity_test_env_.reset();
  }

  Profile* profile() {
    return chrome_test_utils::GetProfile(this);
  }

  PolicyService* GetPolicyService() {
    return profile()->GetProfilePolicyConnector()->policy_service();
  }

  void FirePolicyInvalidation() {
    const base::TimeDelta now =
        base::Time::NowFromSystemTime() - base::Time::UnixEpoch();

    std::visit(
        absl::Overload{
            [now](invalidation::InvalidationService* service) {
              static_cast<invalidation::FakeInvalidationService*>(service)
                  ->EmitInvalidationForTest(invalidation::Invalidation(
                      kPolicyInvalidationTopic, now.InMicroseconds(),
                      "payload"));
            },
            [now](invalidation::InvalidationListener* listener) {
              static_cast<invalidation::FakeInvalidationListener*>(listener)
                  ->FireInvalidation(invalidation::DirectInvalidation(
                      kPolicyInvalidationType, now.InMicroseconds(),
                      "payload"));
            }},
        // Provider caches invalidation service and listener for sender id and
        // project id. To send an invalidation to the policy invalidator, it
        // must be sent to the correct project id.
        invalidation::ProfileInvalidationProviderFactory::GetInstance()
            ->GetForProfile(profile())
            ->GetInvalidationServiceOrListener(
                GetPolicyInvalidationProjectNumber(
                    PolicyInvalidationScope::kUser)));
  }

  void SetServerPolicy(const em::CloudPolicySettings& settings,
                       int key_version,
                       const std::string& policy_invalidation_topic) {
    test_server_->policy_storage()->SetPolicyPayload(
        dm_protocol::kChromeUserPolicyType, settings.SerializeAsString());

    test_server_->policy_storage()->add_managed_user("*");
    test_server_->policy_storage()->set_policy_user(GetTestUser());
    test_server_->policy_storage()
        ->signature_provider()
        ->set_current_key_version(key_version);
    test_server_->policy_storage()->set_policy_invalidation_topic(
        policy_invalidation_topic);
  }

  void OnPolicyUpdated(const PolicyNamespace& ns,
                       const PolicyMap& previous,
                       const PolicyMap& current) override {
    if (!on_policy_updated_.is_null()) {
      std::move(on_policy_updated_).Run();
    }
  }

  void OnPolicyServiceInitialized(PolicyDomain domain) override {}

  void FlushNonChromeOSStoreIOTasks() {
#if !BUILDFLAG(IS_CHROMEOS)
    base::RunLoop run_loop;
    profile()
        ->GetUserCloudPolicyManager()
        ->user_store()
        ->background_task_runner()
        ->PostDelayedTask(FROM_HERE, run_loop.QuitClosure(),
                          base::Milliseconds(0));
    run_loop.Run();
#endif  // !BUILDFLAG(IS_CHROMEOS)
  }

  std::unique_ptr<EmbeddedPolicyTestServer> test_server_;
  base::FilePath user_policy_key_file_;
  base::OnceClosure on_policy_updated_;

  std::unique_ptr<signin::IdentityTestEnvironment> identity_test_env_;

  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_P(CloudPolicyTest, FetchPolicy) {
  PolicyService* policy_service = GetPolicyService();
  {
    base::RunLoop run_loop;
    // This does the initial fetch and stores the initial key.
    policy_service->RefreshPolicies(run_loop.QuitClosure(),
                                    PolicyFetchReason::kTest);
    run_loop.Run();
  }

  PolicyMap default_policy;
  GetExpectedDefaultPolicy(&default_policy);
  EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));

  ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com"), 1,
                                          kPolicyInvalidationTopic));
  PolicyMap expected;
  GetExpectedTestPolicy(&expected, "google.com");
  {
    base::RunLoop run_loop;
    // This fetches the new policies, using the same key.
    policy_service->RefreshPolicies(run_loop.QuitClosure(),
                                    PolicyFetchReason::kTest);
    run_loop.Run();
  }
  EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
}

#if BUILDFLAG(IS_CHROMEOS)
// ENTERPRISE_DEFAULT policies only are supported on Chrome OS currently.
IN_PROC_BROWSER_TEST_P(CloudPolicyTest, EnsureDefaultPoliciesSet) {
  PolicyService* policy_service = GetPolicyService();
  {
    base::RunLoop run_loop;
    // This does the initial fetch and stores the initial key.
    policy_service->RefreshPolicies(run_loop.QuitClosure(),
                                    PolicyFetchReason::kTest);
    run_loop.Run();
  }

  PolicyMap default_policy;
  GetExpectedDefaultPolicy(&default_policy);
  // Make sure the expected policy has at least one of the policies we're
  // expecting.
  EXPECT_TRUE(default_policy.GetValue(key::kEasyUnlockAllowed,
                                      base::Value::Type::BOOLEAN));

  // Now make sure that these default policies are actually getting injected.
  EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
}
#endif

IN_PROC_BROWSER_TEST_P(CloudPolicyTest, InvalidatePolicy) {
  PolicyService* policy_service = GetPolicyService();
  policy_service->AddObserver(POLICY_DOMAIN_CHROME, this);

  // Perform the initial fetch.
  ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com"), 1,
                                          kPolicyInvalidationTopic));
  {
    base::RunLoop run_loop;
    policy_service->RefreshPolicies(run_loop.QuitClosure(),
                                    PolicyFetchReason::kTest);
    run_loop.Run();
  }

  // Update the homepage in the policy and trigger an invalidation.
  ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("youtube.com"), 1,
                                          kPolicyInvalidationTopic));

  FirePolicyInvalidation();

  {
    base::RunLoop run_loop;
    on_policy_updated_ = run_loop.QuitClosure();
    run_loop.Run();
  }

  // Check that the updated policy was fetched.
  PolicyMap expected;
  GetExpectedTestPolicy(&expected, "youtube.com");
  EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));

  policy_service->RemoveObserver(POLICY_DOMAIN_CHROME, this);
}

IN_PROC_BROWSER_TEST_P(CloudPolicyTest, FetchPolicyWithRotatedKey) {
  PolicyService* policy_service = GetPolicyService();
  {
    base::RunLoop run_loop;
    // This does the initial fetch and stores the initial key.
    policy_service->RefreshPolicies(run_loop.QuitClosure(),
                                    PolicyFetchReason::kTest);
    run_loop.Run();
  }
  // Non-ChromeOS policy stack persist policies in the background thread
  // The code path from RefreshPolicies does not wait for the persistence
  // to complete, unlike in the policy stack on ChromeOS.
  // Flush the tasks to persist the policies.
  FlushNonChromeOSStoreIOTasks();

  // Read the initial key.
  std::string initial_key;
  {
    base::ScopedAllowBlockingForTesting allow_io;
    ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &initial_key));
  }

  PolicyMap default_policy;
  GetExpectedDefaultPolicy(&default_policy);
  EXPECT_TRUE(default_policy.Equals(policy_service->GetPolicies(
      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));

  // Set the new policies and a new key at the server.
  ASSERT_NO_FATAL_FAILURE(SetServerPolicy(GetTestPolicy("google.com"), 2,
                                          kPolicyInvalidationTopic));
  PolicyMap expected;
  GetExpectedTestPolicy(&expected, "google.com");
  {
    base::RunLoop run_loop;
    // This fetches the new policies and does a key rotation.
    policy_service->RefreshPolicies(run_loop.QuitClosure(),
                                    PolicyFetchReason::kTest);
    run_loop.Run();
  }
  FlushNonChromeOSStoreIOTasks();
  EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));

  // Verify that the key was rotated.
  std::string rotated_key;
  {
    base::ScopedAllowBlockingForTesting allow_io;
    ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &rotated_key));
  }
  EXPECT_NE(rotated_key, initial_key);

  // Another refresh using the same key won't rotate it again.
  {
    base::RunLoop run_loop;
    policy_service->RefreshPolicies(run_loop.QuitClosure(),
                                    PolicyFetchReason::kTest);
    run_loop.Run();
  }
  FlushNonChromeOSStoreIOTasks();
  EXPECT_TRUE(expected.Equals(policy_service->GetPolicies(
      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))));
  std::string current_key;
  {
    base::ScopedAllowBlockingForTesting allow_io;
    ASSERT_TRUE(base::ReadFileToString(user_policy_key_file_, &current_key));
  }

  EXPECT_EQ(rotated_key, current_key);
}

INSTANTIATE_TEST_SUITE_P(
    /* no prefix */,
    CloudPolicyTest,
    testing::Values(FeaturesTestParam{},
                    FeaturesTestParam{
                        .enabled_features =
                            {kUserPolicyInvalidationWithDirectMessagesEnabled}},
                    FeaturesTestParam{
                        .enabled_features = {policy::kPolicyFetchWithSha256}},
                    FeaturesTestParam{.disabled_features = {
                                          policy::kPolicyFetchWithSha256}}));

TEST(CloudPolicyProtoTest, VerifyProtobufEquivalence) {
  // There are 2 protobufs that can be used for user cloud policy:
  // cloud_policy.proto and chrome_settings.proto. chrome_settings.proto is the
  // version used by the server, but generates one proto message per policy; to
  // save binary size on the client, the other version shares proto messages for
  // policies of the same type. They generate the same bytes on the wire though,
  // so they are compatible. This test verifies that that stays true.

  // Build a ChromeSettingsProto message with one policy of each supported type.
  em::ChromeSettingsProto chrome_settings;
  chrome_settings.mutable_homepagelocation()->set_homepagelocation(
      "chromium.org");
  chrome_settings.mutable_savingbrowserhistorydisabled()
      ->set_savingbrowserhistorydisabled(true);
  chrome_settings.mutable_defaultjavascriptsetting()
      ->set_defaultjavascriptsetting(2);
  em::StringList* list = chrome_settings.mutable_synctypeslistdisabled()
                             ->mutable_synctypeslistdisabled();
  list->add_entries("bookmarks");
  list->add_entries("passwords");
  // Try explicitly setting a policy mode too.
  chrome_settings.mutable_searchsuggestenabled()->set_searchsuggestenabled(
      false);
  chrome_settings.mutable_searchsuggestenabled()
      ->mutable_policy_options()
      ->set_mode(em::PolicyOptions::MANDATORY);
  chrome_settings.mutable_syncdisabled()->set_syncdisabled(true);
  chrome_settings.mutable_syncdisabled()->mutable_policy_options()->set_mode(
      em::PolicyOptions::RECOMMENDED);

  // Build an equivalent CloudPolicySettings message.
  em::CloudPolicySettings cloud_policy;
  cloud_policy.mutable_homepagelocation()->set_value("chromium.org");
  cloud_policy.mutable_savingbrowserhistorydisabled()->set_value(true);
  cloud_policy.mutable_defaultjavascriptsetting()->set_value(2);
  list = cloud_policy.mutable_synctypeslistdisabled()->mutable_value();
  list->add_entries("bookmarks");
  list->add_entries("passwords");
  cloud_policy.mutable_searchsuggestenabled()->set_value(false);
  cloud_policy.mutable_searchsuggestenabled()
      ->mutable_policy_options()
      ->set_mode(em::PolicyOptions::MANDATORY);
  cloud_policy.mutable_syncdisabled()->set_value(true);
  cloud_policy.mutable_syncdisabled()->mutable_policy_options()->set_mode(
      em::PolicyOptions::RECOMMENDED);

  // They should now serialize to the same bytes.
  std::string chrome_settings_serialized;
  std::string cloud_policy_serialized;
  ASSERT_TRUE(chrome_settings.SerializeToString(&chrome_settings_serialized));
  ASSERT_TRUE(cloud_policy.SerializeToString(&cloud_policy_serialized));
  EXPECT_EQ(chrome_settings_serialized, cloud_policy_serialized);
}

}  // namespace policy