File: policy_ui_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 (1228 lines) | stat: -rw-r--r-- 49,202 bytes parent folder | download | duplicates (5)
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>

#include <memory>
#include <utility>
#include <vector>

#include "base/cfi_buildflags.h"
#include "base/containers/flat_map.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/callback.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_clock.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/android_buildflags.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/enterprise/browser_management/management_service_factory.h"
#include "chrome/browser/policy/profile_policy_connector_builder.h"
#include "chrome/browser/policy/schema_registry_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/url_constants.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/browser/webui/policy_status_provider.h"
#include "components/policy/core/common/cloud/cloud_policy_refresh_scheduler.h"
#include "components/policy/core/common/cloud/enterprise_metrics.h"
#include "components/policy/core/common/external_data_fetcher.h"
#include "components/policy/core/common/management/scoped_management_service_override_for_testing.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_pref_names.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/core/common/schema.h"
#include "components/policy/policy_constants.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/login/test/device_state_mixin.h"
#include "chrome/browser/ash/login/test/logged_in_user_mixin.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

#if !BUILDFLAG(IS_ANDROID)
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/extensions/install_verifier.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/account_id/account_id.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/features/simple_feature.h"
#endif  // !BUILDFLAG(IS_ANDROID)

using testing::_;
using testing::Return;

namespace {

// Allows waiting until the policy schema for a |PolicyNamespace| has been made
// available by a |Profile|'s |SchemaRegistry|.
class PolicySchemaAvailableWaiter : public policy::SchemaRegistry::Observer {
 public:
  PolicySchemaAvailableWaiter(Profile* profile,
                              const policy::PolicyNamespace& policy_namespace)
      : registry_(profile->GetPolicySchemaRegistryService()->registry()),
        policy_namespace_(policy_namespace) {}

  PolicySchemaAvailableWaiter(const PolicySchemaAvailableWaiter&) = delete;
  PolicySchemaAvailableWaiter& operator=(const PolicySchemaAvailableWaiter&) =
      delete;

  ~PolicySchemaAvailableWaiter() override { registry_->RemoveObserver(this); }

  // Starts waiting for a policy schema to be available for the
  // |policy_namespace_| that has been passed to the constructor. Returns
  // immediately if the policy schema is already available.
  void Wait() {
    if (RegistryHasSchemaForNamespace()) {
      return;
    }
    registry_->AddObserver(this);
    run_loop_.Run();
  }

 private:
  bool RegistryHasSchemaForNamespace() {
    const policy::ComponentMap* map =
        registry_->schema_map()->GetComponents(policy_namespace_.domain);
    if (!map) {
      return false;
    }
    return map->find(policy_namespace_.component_id) != map->end();
  }

  // policy::SchemaRegistry::Observer:
  void OnSchemaRegistryUpdated(bool has_new_schemas) override {
    if (RegistryHasSchemaForNamespace()) {
      run_loop_.Quit();
    }
  }

  const raw_ptr<policy::SchemaRegistry> registry_;
  const policy::PolicyNamespace policy_namespace_;
  base::RunLoop run_loop_;
};

std::vector<std::string> PopulateExpectedPolicy(
    const std::string& name,
    const std::string& value,
    const std::string& source,
    const policy::PolicyMap::Entry* policy_map_entry,
    bool unknown) {
  std::vector<std::string> expected_policy;

  // Populate expected policy name.
  expected_policy.push_back(name);

  // Populate expected policy value.
  expected_policy.push_back(value);

  // Populate expected source name.
  expected_policy.push_back(source);

  // Populate expected scope.
  if (policy_map_entry) {
    expected_policy.push_back(l10n_util::GetStringUTF8(
        policy_map_entry->scope == policy::POLICY_SCOPE_MACHINE
            ? IDS_POLICY_SCOPE_DEVICE
            : IDS_POLICY_SCOPE_USER));
  } else {
    expected_policy.emplace_back();
  }

  // Populate expected level.
  if (policy_map_entry) {
    expected_policy.push_back(l10n_util::GetStringUTF8(
        policy_map_entry->level == policy::POLICY_LEVEL_RECOMMENDED
            ? IDS_POLICY_LEVEL_RECOMMENDED
            : IDS_POLICY_LEVEL_MANDATORY));
  } else {
    expected_policy.emplace_back();
  }

  // Populate expected status.
  if (unknown) {
    expected_policy.push_back(l10n_util::GetStringUTF8(IDS_POLICY_LABEL_ERROR));
  } else if (!policy_map_entry) {
    expected_policy.push_back(l10n_util::GetStringUTF8(IDS_POLICY_UNSET));
  } else {
    expected_policy.push_back(l10n_util::GetStringUTF8(IDS_POLICY_OK));
  }
  return expected_policy;
}
}  // namespace

class PolicyUITest : public PlatformBrowserTest {
 public:
  PolicyUITest();

  PolicyUITest(const PolicyUITest&) = delete;
  PolicyUITest& operator=(const PolicyUITest&) = delete;

  ~PolicyUITest() override;

 protected:
  // PlatformBrowserTest implementation.
  void SetUpInProcessBrowserTestFixture() override;

  // Uses the |MockConfiguratonPolicyProvider| installed for testing to publish
  // |policy| for |policy_namespace|.
  void UpdateProviderPolicyForNamespace(
      const policy::PolicyNamespace& policy_namespace,
      const policy::PolicyMap& policy);

  void VerifyPolicies(const std::vector<std::vector<std::string>>& expected);

  void VerifyReportButton(bool visible);

  content::WebContents* web_contents() {
    return chrome_test_utils::GetActiveWebContents(this);
  }

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

PolicyUITest::PolicyUITest() = default;

PolicyUITest::~PolicyUITest() = default;

void PolicyUITest::SetUpInProcessBrowserTestFixture() {
  provider_.SetDefaultReturns(/*is_initialization_complete_return=*/true,
                              /*is_first_policy_load_complete_return=*/true);
  policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
  policy::PushProfilePolicyConnectorProviderForTesting(&provider_);
}

void PolicyUITest::UpdateProviderPolicyForNamespace(
    const policy::PolicyNamespace& policy_namespace,
    const policy::PolicyMap& policy) {
  policy::PolicyBundle bundle;
  bundle.Get(policy_namespace) = policy.Clone();
  provider_.UpdatePolicy(std::move(bundle));
}

void PolicyUITest::VerifyPolicies(
    const std::vector<std::vector<std::string>>& expected_policies) {
  ASSERT_TRUE(
      content::NavigateToURL(web_contents(), GURL(chrome::kChromeUIPolicyURL)));

  // Retrieve the text contents of the policy table cells for all policies.
  const std::string javascript =
      "var entries = getAllPolicyTables();"
      "var policies = [];"
      "for (var i = 0; i < entries.length; ++i) {"
      "  var items = getAllPolicyRows(entries[i]);"
      "  for (var j = 0; j < items.length; ++j) {"
      "    var children = getAllPolicyRowDivs(items[j]);"
      "    var values = [];"
      "    for(var k = 0; k < children.length - 1; ++k) {"
      "      values.push(children[k].textContent.trim());"
      "    }"
      "    policies.push(values);"
      "  }"
      "}"
      "JSON.stringify(policies);";
  std::string json =
      content::EvalJs(web_contents(), javascript).ExtractString();
  std::optional<base::Value> value_ptr = base::JSONReader::Read(json);
  ASSERT_TRUE(value_ptr);
  ASSERT_TRUE(value_ptr->is_list());
  const base::Value::List& actual_policies = value_ptr->GetList();

  // Verify that the cells contain the expected strings for all policies.
  ASSERT_EQ(expected_policies.size(), actual_policies.size());
  for (size_t i = 0; i < expected_policies.size(); ++i) {
    const std::vector<std::string> expected_policy = expected_policies[i];
    ASSERT_TRUE(actual_policies[i].is_list());
    const base::Value::List& actual_policy = actual_policies[i].GetList();
    ASSERT_EQ(expected_policy.size(), actual_policy.size());
    for (size_t j = 0; j < expected_policy.size(); ++j) {
      const std::string* value = actual_policy[j].GetIfString();
      ASSERT_TRUE(value);
      if (expected_policy[j] != *value) {
        EXPECT_EQ(expected_policy[j], *value);
      }
    }
  }
}

void PolicyUITest::VerifyReportButton(bool visible) {
  const std::string kJavaScript = "getReportButtonVisibility();";
  std::string ret =
      content::EvalJs(web_contents(), kJavaScript).ExtractString();

#if !BUILDFLAG(IS_CHROMEOS)
  EXPECT_EQ(visible, ret != "none");
#else
  EXPECT_FALSE(ret != "none");
#endif
}

#if BUILDFLAG(IS_CHROMEOS)
class PolicyUIStatusTest : public MixinBasedInProcessBrowserTest {
 public:
  void SetUpOnMainThread() override {
    MixinBasedInProcessBrowserTest::SetUpOnMainThread();
    logged_in_user_mixin_.LogInUser();
    // By default DeviceStateMixin sets public key version to 17 whereas policy
    // test server inside LoggedInUserMixin has only one version. By setting
    // public_key_version to 1, we make device policy requests succeed and thus
    // device policy timestamp set.
    device_state_.RequestDevicePolicyUpdate()
        ->policy_data()
        ->set_public_key_version(1);
  }

  bool ReadStatusFor(const std::string& policy_legend,
                     base::flat_map<std::string, std::string>* policy_status);
  bool ReloadPolicies();
  bool ReloadPolicies(content::WebContents* contents);

 protected:
  ash::DeviceStateMixin device_state_{
      &mixin_host_,
      ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED};
  ash::LoggedInUserMixin logged_in_user_mixin_{
      &mixin_host_, /*test_base=*/this, embedded_test_server(),
      ash::LoggedInUserMixin::LogInType::kManaged};
};

bool PolicyUIStatusTest::ReadStatusFor(
    const std::string& policy_legend,
    base::flat_map<std::string, std::string>* policy_status) {
  // Retrieve the text contents of the status table with specified heading.
  const std::string javascript = R"JS(
    (function() {
      function readStatus() {
        // Wait for the status box to appear in case page just loaded.
        const statusSection = document.getElementById('status-section');
        if (statusSection.hidden) {
          return new Promise(resolve => {
            window.requestIdleCallback(resolve);
          }).then(readStatus);
        }

        const policies = getPolicyFieldsets();
        const statuses = {};
        for (let i = 0; i < policies.length; ++i) {
          const statusHeading = policies[i]
            .querySelector('.status-box-heading').textContent;
          const entries = {};
          const rows = policies[i]
            .querySelectorAll('.status-entry div:nth-child(2)');
          for (let j = 0; j < rows.length; ++j) {
            entries[rows[j].className.split(' ')[0]] = rows[j].textContent
              .trim();
          }
          statuses[statusHeading.trim()] = entries;
        }
        return JSON.stringify(statuses);
      };
      return new Promise(resolve => {
        window.requestIdleCallback(resolve);
      }).then(readStatus);
    })();
  )JS";
  content::WebContents* contents =
      chrome_test_utils::GetActiveWebContents(this);
  std::string json = content::EvalJs(contents, javascript).ExtractString();
  std::optional<base::Value> statuses = base::JSONReader::Read(json);
  if (!statuses.has_value() || !statuses->is_dict()) {
    return false;
  }
  const base::Value::Dict& status_dict = statuses->GetDict();
  const base::Value::Dict* actual_entries = status_dict.FindDict(policy_legend);
  if (!actual_entries) {
    return false;
  }
  for (const auto entry : *actual_entries) {
    policy_status->insert_or_assign(entry.first, entry.second.GetString());
  }
  return true;
}

bool PolicyUIStatusTest::ReloadPolicies() {
  content::WebContents* contents =
      chrome_test_utils::GetActiveWebContents(this);
  return ReloadPolicies(contents);
}

bool PolicyUIStatusTest::ReloadPolicies(content::WebContents* contents) {
  const std::string javascript = R"JS(
    (function() {
      const reloadPoliciesBtn = document.getElementById('reload-policies');
      reloadPoliciesBtn.click();
      // Wait until reload button becomes enabled again, i.e. policies reloaded.
      function waitForPoliciesToReload() {
        if (reloadPoliciesBtn.disabled) {
          return new Promise(resolve => {
            window.requestIdleCallback(resolve);
          }).then(waitForPoliciesToReload);
        } else {
          return true;
        }
      }
      return new Promise(resolve => {
        window.requestIdleCallback(resolve);
      }).then(waitForPoliciesToReload);
    })();
  )JS";
  return content::ExecJs(contents, javascript);
}

#if !BUILDFLAG(IS_ANDROID)
IN_PROC_BROWSER_TEST_F(PolicyUIStatusTest, CheckPolicyUiInGuestProfile) {
  // Verifies that the page opens in guest session.
  const Browser* policy_browser = OpenURLOffTheRecord(
      browser()->profile(), GURL(chrome::kChromeUIPolicyURL));
  ASSERT_TRUE(policy_browser);
  content::WebContents* contents =
      policy_browser->tab_strip_model()->GetActiveWebContents();
  ASSERT_TRUE(ReloadPolicies(contents));
}
#endif  // !BUILDFLAG(IS_ANDROID)

IN_PROC_BROWSER_TEST_F(PolicyUIStatusTest,
                       ShowsZeroSecondsSinceRefreshAfterReloadingPolicies) {
  // Verifies that the time since refresh of a policy set is set to 0 seconds
  // after "Reload policies" button is pressed and policies are reloaded.

  // Mock time in policy server and classes used by refresh logic.
  base::Time now = base::Time::Now();
  logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin()
      ->UpdatePolicyTimestamp(now);
  base::SimpleTestClock status_provider_clock_mock;
  status_provider_clock_mock.SetNow(now);
  auto status_provider_clock_mock_closure =
      policy::PolicyStatusProvider::OverrideClockForTesting(
          &status_provider_clock_mock);
  base::SimpleTestClock policy_refresher_clock_mock;
  policy_refresher_clock_mock.SetNow(now);
  auto policy_refresher_clock_mock_closure =
      policy::CloudPolicyRefreshScheduler::OverrideClockForTesting(
          &policy_refresher_clock_mock);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));
  ASSERT_TRUE(ReloadPolicies());

  base::flat_map<std::string, std::string> status;
  ASSERT_TRUE(ReadStatusFor("User policies", &status));
  EXPECT_EQ(status["time-since-last-refresh"], "0 secs ago");
  EXPECT_EQ(status["time-since-last-fetch-attempt"], "0 secs ago");
  ASSERT_TRUE(ReadStatusFor("Device policies", &status));
  EXPECT_EQ(status["time-since-last-refresh"], "0 secs ago");
  EXPECT_EQ(status["time-since-last-fetch-attempt"], "0 secs ago");
}

IN_PROC_BROWSER_TEST_F(PolicyUIStatusTest, ShowsCorrectTimesSinceRefresh) {
  // Verifies that the time since refresh of a policy set is correctly computed.

  // Mock time in policy server and classes used by refresh logic.
  base::Time now = base::Time::Now();
  logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin()
      ->UpdatePolicyTimestamp(now);
  base::SimpleTestClock status_provider_clock_mock;
  status_provider_clock_mock.SetNow(now);
  auto status_provider_clock_mock_closure =
      policy::PolicyStatusProvider::OverrideClockForTesting(
          &status_provider_clock_mock);
  base::SimpleTestClock policy_refresher_clock_mock;
  policy_refresher_clock_mock.SetNow(now);
  auto policy_refresher_clock_mock_closure =
      policy::CloudPolicyRefreshScheduler::OverrideClockForTesting(
          &policy_refresher_clock_mock);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));
  ASSERT_TRUE(ReloadPolicies());
  status_provider_clock_mock.Advance(base::Hours(1));
  policy_refresher_clock_mock.Advance(base::Hours(1));
  // Refresh the page without reloading policies.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));
  base::RunLoop().RunUntilIdle();  // Ensure status request has been processed.

  base::flat_map<std::string, std::string> status;
  ASSERT_TRUE(ReadStatusFor("User policies", &status));
  EXPECT_EQ(status["time-since-last-refresh"], "1 hour ago");
  EXPECT_EQ(status["time-since-last-fetch-attempt"], "1 hour ago");
  ASSERT_TRUE(ReadStatusFor("Device policies", &status));
  EXPECT_EQ(status["time-since-last-refresh"], "1 hour ago");
  EXPECT_EQ(status["time-since-last-fetch-attempt"], "1 hour ago");
}

IN_PROC_BROWSER_TEST_F(PolicyUIStatusTest,
                       ShowsCorrectRefreshTimesAfterFailedReload) {
  // Verifies that the time since refresh of a policy set is correctly updated
  // after a failed attempt to update policies.

  // Mock time in policy server and classes used by refresh logic.
  base::Time now = base::Time::Now();
  logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin()
      ->UpdatePolicyTimestamp(now);
  base::SimpleTestClock status_provider_clock_mock;
  status_provider_clock_mock.SetNow(now);
  auto status_provider_clock_mock_closure =
      policy::PolicyStatusProvider::OverrideClockForTesting(
          &status_provider_clock_mock);
  base::SimpleTestClock policy_refresher_clock_mock;
  policy_refresher_clock_mock.SetNow(now);
  auto policy_refresher_clock_mock_closure =
      policy::CloudPolicyRefreshScheduler::OverrideClockForTesting(
          &policy_refresher_clock_mock);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));
  ASSERT_TRUE(ReloadPolicies());
  logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin()->SetPolicyFetchError(
      500);
  status_provider_clock_mock.Advance(base::Hours(1));
  policy_refresher_clock_mock.Advance(base::Hours(1));
  ASSERT_TRUE(ReloadPolicies());

  base::flat_map<std::string, std::string> status;
  ASSERT_TRUE(ReadStatusFor("User policies", &status));
  EXPECT_EQ(status["time-since-last-refresh"], "1 hour ago");
  EXPECT_EQ(status["time-since-last-fetch-attempt"], "0 secs ago");
  ASSERT_TRUE(ReadStatusFor("Device policies", &status));
  EXPECT_EQ(status["time-since-last-refresh"], "1 hour ago");
  EXPECT_EQ(status["time-since-last-fetch-attempt"], "0 secs ago");
}
#endif  // BUILDFLAG(IS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(PolicyUITest, SendPolicyNames) {
  // Verifies that the names of known policies are sent to the UI and processed
  // there correctly by checking that the policy table contains all policies in
  // the correct order.

  // Expect that the policy table contains all known policies in alphabetical
  // order and none of the policies have a set value.
  std::vector<std::vector<std::string>> expected_policies;
  policy::Schema chrome_schema =
      policy::Schema::Wrap(policy::GetChromeSchemaData());
  ASSERT_TRUE(chrome_schema.valid());
  for (policy::Schema::Iterator it = chrome_schema.GetPropertiesIterator();
       !it.IsAtEnd(); it.Advance()) {
    expected_policies.push_back(PopulateExpectedPolicy(
        it.key(), std::string(), std::string(), nullptr, false));
  }

#if !BUILDFLAG(IS_CHROMEOS)
  // Add policies found in the Policy Precedence table.
  for (auto* policy : policy::metapolicy::kPrecedence) {
    expected_policies.push_back(PopulateExpectedPolicy(
        policy, std::string(), std::string(), nullptr, false));
  }
#endif  // !BUILDFLAG(IS_CHROMEOS)

  // Retrieve the contents of the policy table from the UI and verify that it
  // matches the expectation.
  VerifyPolicies(expected_policies);
}

// TODO(crbug.com/384989795): Fails on desktop android, see bug.
#if BUILDFLAG(IS_DESKTOP_ANDROID)
#define MAYBE_SendPolicyValues DISABLED_SendPolicyValues
#else
#define MAYBE_SendPolicyValues SendPolicyValues
#endif
IN_PROC_BROWSER_TEST_F(PolicyUITest, MAYBE_SendPolicyValues) {
  // Verifies that policy values are sent to the UI and processed there
  // correctly by setting the values of four known and one unknown policy and
  // checking that the policy table contains the policy names, values and
  // metadata in the correct order.
  policy::PolicyMap values;
  std::map<std::string, std::string> expected_values;

  // Set the values of four existing policies.
  base::Value::List blocked_urls;
  blocked_urls.Append("site1.com");
  blocked_urls.Append("site2.com");
  blocked_urls.Append("site3.com");
  values.Set(policy::key::kURLBlocklist, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value(std::move(blocked_urls)), nullptr);
  expected_values[policy::key::kURLBlocklist] =
      R"(["site1.com","site2.com","site3.com"])";
  values.Set(policy::key::kHomepageLocation, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD,
             base::Value("http://google.com"), nullptr);
  expected_values[policy::key::kHomepageLocation] = "http://google.com";
  values.Set(policy::key::kSafeBrowsingProtectionLevel,
             policy::POLICY_LEVEL_RECOMMENDED, policy::POLICY_SCOPE_USER,
             policy::POLICY_SOURCE_CLOUD, base::Value(1), nullptr);
  expected_values[policy::key::kSafeBrowsingProtectionLevel] = "1";
  values.Set(policy::key::kPasswordLeakDetectionEnabled,
             policy::POLICY_LEVEL_RECOMMENDED, policy::POLICY_SCOPE_MACHINE,
             policy::POLICY_SOURCE_CLOUD, base::Value(true), nullptr);
  expected_values[policy::key::kPasswordLeakDetectionEnabled] = "true";
  // Set the value of a policy that does not exist.
  const std::string kUnknownPolicy = "NoSuchThing";
  values.Set(kUnknownPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_PLATFORM,
             base::Value(true), nullptr);
  expected_values[kUnknownPolicy] = "true";
  const std::string kUnknownPolicyWithDots = "no.such.thing";
  values.Set(kUnknownPolicyWithDots, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_PLATFORM,
             base::Value("blub"), nullptr);
  expected_values[kUnknownPolicyWithDots] = "blub";

  provider_.UpdateChromePolicy(values);

  // Expect that the policy table contains, in order:
  // * All known policies whose value has been set, in alphabetical order.
  // * The unknown policy.
  // * All known policies whose value has not been set, in alphabetical order.
  std::vector<std::vector<std::string>> expected_policies;
  size_t first_unset_position = 0;
  policy::Schema chrome_schema =
      policy::Schema::Wrap(policy::GetChromeSchemaData());
  ASSERT_TRUE(chrome_schema.valid());
  for (policy::Schema::Iterator props = chrome_schema.GetPropertiesIterator();
       !props.IsAtEnd(); props.Advance()) {
    std::map<std::string, std::string>::const_iterator it =
        expected_values.find(props.key());
    const std::string value =
        it == expected_values.end() ? std::string() : it->second;
    const std::string source =
        it == expected_values.end() ? std::string() : "Cloud";
    const policy::PolicyMap::Entry* metadata = values.Get(props.key());
    expected_policies.insert(
        metadata ? expected_policies.begin() + first_unset_position++
                 : expected_policies.end(),
        PopulateExpectedPolicy(props.key(), value, source, metadata, false));
  }
  expected_policies.insert(
      expected_policies.begin() + first_unset_position++,
      PopulateExpectedPolicy(kUnknownPolicy, expected_values[kUnknownPolicy],
                             "Platform", values.Get(kUnknownPolicy), true));
  expected_policies.insert(
      expected_policies.begin() + first_unset_position++,
      PopulateExpectedPolicy(
          kUnknownPolicyWithDots, expected_values[kUnknownPolicyWithDots],
          "Platform", values.Get(kUnknownPolicyWithDots), true));

#if !BUILDFLAG(IS_CHROMEOS)
  // Add policies found in the Policy Precedence table.
  for (auto* policy : policy::metapolicy::kPrecedence) {
    expected_policies.push_back(PopulateExpectedPolicy(
        policy, std::string(), std::string(), values.Get(policy), false));
  }
#endif  // !BUILDFLAG(IS_CHROMEOS)

  // Retrieve the contents of the policy table from the UI and verify that it
  // matches the expectation.
  VerifyPolicies(expected_policies);
}

IN_PROC_BROWSER_TEST_F(PolicyUITest, ReportButton) {
  ASSERT_TRUE(
      content::NavigateToURL(web_contents(), GURL(chrome::kChromeUIPolicyURL)));

  // Hide by default.
  VerifyReportButton(/*visible=*/false);

  // Turn on with the policy
  policy::PolicyMap policy_map;
  policy_map.Set(policy::key::kCloudReportingEnabled,
                 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
                 policy::POLICY_SOURCE_CLOUD, base::Value(true), nullptr);
  provider_.UpdateChromePolicy(policy_map);
  VerifyReportButton(/*visible=*/true);

  // Hide while policy is off.
  policy_map.Set(policy::key::kCloudReportingEnabled,
                 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
                 policy::POLICY_SOURCE_CLOUD, base::Value(false), nullptr);
  provider_.UpdateChromePolicy(policy_map);
  VerifyReportButton(/*visible=*/false);
}

IN_PROC_BROWSER_TEST_F(PolicyUITest, ReportButtonWithProfileReporting) {
  ASSERT_TRUE(
      content::NavigateToURL(web_contents(), GURL(chrome::kChromeUIPolicyURL)));

  // Hide by default.
  VerifyReportButton(/*visible=*/false);

  // Turn on with the policy
  policy::PolicyMap policy_map;
  policy_map.Set(policy::key::kCloudProfileReportingEnabled,
                 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
                 policy::POLICY_SOURCE_CLOUD, base::Value(true), nullptr);
  provider_.UpdateChromePolicy(policy_map);
  VerifyReportButton(/*visible=*/true);

  // Hide while policy is off.
  policy_map.Set(policy::key::kCloudProfileReportingEnabled,
                 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
                 policy::POLICY_SOURCE_CLOUD, base::Value(false), nullptr);
  provider_.UpdateChromePolicy(policy_map);
  VerifyReportButton(/*visible=*/false);
}

#if !BUILDFLAG(IS_CHROMEOS)
class PolicyPrecedenceUITest
    : public PolicyUITest,
      public ::testing::WithParamInterface<std::tuple<
          /*cloud_policy_overrides_platform_policy=*/bool,
          /*cloud_user_policy_overrides_cloud_machine_policy=*/bool,
          /*is_user_affiliated=*/bool>> {
 public:
  bool CloudPolicyOverridesPlatformPolicy() { return std::get<0>(GetParam()); }

  bool CloudUserPolicyOverridesCloudMachinePolicy() {
    return std::get<1>(GetParam());
  }

  bool IsUserAffiliated() { return std::get<2>(GetParam()); }

  void ValidatePrecedenceValue(const std::string& precedence_row_value) {
    if (CloudPolicyOverridesPlatformPolicy() &&
        CloudUserPolicyOverridesCloudMachinePolicy() && IsUserAffiliated()) {
      EXPECT_EQ(precedence_row_value,
                "Cloud user > Cloud machine > Platform machine > "
                "Platform user");
    } else if (CloudPolicyOverridesPlatformPolicy()) {
      EXPECT_EQ(precedence_row_value,
                "Cloud machine > Platform machine > Platform user > "
                "Cloud user");
    } else if (CloudUserPolicyOverridesCloudMachinePolicy() &&
               IsUserAffiliated()) {
      EXPECT_EQ(precedence_row_value,
                "Platform machine > Cloud user > Cloud machine > "
                "Platform user");
    } else {
      EXPECT_EQ(precedence_row_value,
                "Platform machine > Cloud machine > Platform user > "
                "Cloud user");
    }
  }

  // Used to retrieve the contents of the policy precedence rows.
  const std::string kJavaScript =
      "var precedence_row = getPrecedenceRowValue();"
      "precedence_row.textContent;";
};

// Verify that the precedence order displayed in the Policy Precedence table is
// correct.
IN_PROC_BROWSER_TEST_P(PolicyPrecedenceUITest, PrecedenceOrder) {
  // Set precedence policies.
  policy::PolicyMap policy_map;

  if (IsUserAffiliated()) {
    base::flat_set<std::string> affiliation_ids;
    affiliation_ids.insert("12345");
    // Treat user as affiliated by setting identical user and device IDs.
    policy_map.SetUserAffiliationIds(affiliation_ids);
    policy_map.SetDeviceAffiliationIds(affiliation_ids);
  }

  policy_map.Set(policy::key::kCloudPolicyOverridesPlatformPolicy,
                 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
                 policy::POLICY_SOURCE_PLATFORM,
                 base::Value(CloudPolicyOverridesPlatformPolicy()), nullptr);
  policy_map.Set(policy::key::kCloudUserPolicyOverridesCloudMachinePolicy,
                 policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
                 policy::POLICY_SOURCE_PLATFORM,
                 base::Value(CloudUserPolicyOverridesCloudMachinePolicy()),
                 nullptr);
  provider_.UpdateChromePolicy(policy_map);

  // Retrieve the contents of the policy precedence rows.
  ASSERT_TRUE(
      content::NavigateToURL(web_contents(), GURL(chrome::kChromeUIPolicyURL)));
  std::string precedence_row_value =
      content::EvalJs(web_contents(), kJavaScript).ExtractString();

  ValidatePrecedenceValue(precedence_row_value);
}

INSTANTIATE_TEST_SUITE_P(PolicyPrecedenceUITestInstance,
                         PolicyPrecedenceUITest,
                         testing::Combine(testing::Values(false, true),
                                          testing::Values(false, true),
                                          testing::Values(false, true)));
#endif  // !BUILDFLAG(IS_CHROMEOS)

#if !BUILDFLAG(IS_ANDROID)
// TODO(https://crbug.com/1027135) Add tests to verify extension policies are
// exported correctly.
class ExtensionPolicyUITest : public PolicyUITest,
                              public ::testing::WithParamInterface<bool> {
 public:
  ExtensionPolicyUITest() = default;

  bool UseSigninProfile() const { return GetParam(); }

  Profile* extension_profile() {
#if BUILDFLAG(IS_CHROMEOS)
    if (UseSigninProfile()) {
      return ash::ProfileHelper::GetSigninProfile();
    }
#endif  // BUILDFLAG(IS_CHROMEOS)
    return chrome_test_utils::GetProfile(this);
  }
};

// TODO(crbug.com/41429868) Flaky time outs on Linux Chromium OS ASan
// LSan bot.
#if defined(ADDRESS_SANITIZER)
#define MAYBE_ExtensionLoadAndSendPolicy DISABLED_ExtensionLoadAndSendPolicy
#else
#define MAYBE_ExtensionLoadAndSendPolicy ExtensionLoadAndSendPolicy
#endif
IN_PROC_BROWSER_TEST_P(ExtensionPolicyUITest,
                       MAYBE_ExtensionLoadAndSendPolicy) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::ScopedTempDir temp_dir_;
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

  const std::string kNormalBooleanPolicy = "normal_boolean";
  const std::string kSensitiveBooleanPolicy = "sensitive_boolean";
  const std::string kSensitiveStringPolicy = "sensitive_string";
  const std::string kSensitiveObjectPolicy = "sensitive_object";
  const std::string kSensitiveArrayPolicy = "sensitive_array";
  const std::string kSensitiveIntegerPolicy = "sensitive_integer";
  const std::string kSensitiveNumberPolicy = "sensitive_number";
  std::string json_data = R"({
    "type": "object",
    "properties": {
      "normal_boolean": {
        "type": "boolean"
      },
      "sensitive_boolean": {
        "type": "boolean",
        "sensitiveValue": true
      },
      "sensitive_string": {
        "type": "string",
        "sensitiveValue": true
      },
      "sensitive_object": {
        "type": "object",
        "additionalProperties": {
          "type": "boolean"
        },
        "sensitiveValue": true
      },
      "sensitive_array": {
        "type": "array",
        "items": {
          "type": "boolean"
        },
        "sensitiveValue": true
      },
      "sensitive_integer": {
        "type": "integer",
        "sensitiveValue": true
      },
      "sensitive_number": {
        "type": "number",
        "sensitiveValue": true
      }
    }
  })";

  const std::string schema_file = "schema.json";
  base::FilePath schema_path = temp_dir_.GetPath().AppendASCII(schema_file);
  base::WriteFile(schema_path, json_data);

  // Build extension that contains the policy schema.
  auto storage = base::Value::Dict().Set("managed_schema", schema_file);

  auto manifest = base::Value::Dict()
                      .Set("name", "test")
                      .Set("version", "1")
                      .Set("manifest_version", 2)
                      .Set("storage", std::move(storage));

  extensions::ExtensionBuilder builder;
  builder.SetPath(temp_dir_.GetPath());
  builder.SetManifest(std::move(manifest));
  builder.SetLocation(
      extensions::mojom::ManifestLocation::kExternalPolicyDownload);

  // Install extension.
  scoped_refptr<const extensions::Extension> extension = builder.Build();

  // Bypass "signin_screen" feature only enabled for allowlisted extensions.
  extensions::SimpleFeature::ScopedThreadUnsafeAllowlistForTest allowlist(
      extension->id());
  // Disable extension install verification.
  extensions::ScopedInstallVerifierBypassForTest ignore_install_verification_;

  extensions::ExtensionRegistrar::Get(extension_profile())
      ->OnExtensionInstalled(extension.get(), syncer::StringOrdinal(), 0);

  policy::PolicyDomain policy_domain =
      UseSigninProfile() ? policy::POLICY_DOMAIN_SIGNIN_EXTENSIONS
                         : policy::POLICY_DOMAIN_EXTENSIONS;
  const policy::PolicyNamespace extension_policy_namespace(policy_domain,
                                                           extension->id());
  PolicySchemaAvailableWaiter(extension_profile()->GetOriginalProfile(),
                              extension_policy_namespace)
      .Wait();

  std::vector<std::vector<std::string>> expected_chrome_policies;
  policy::Schema chrome_schema =
      policy::Schema::Wrap(policy::GetChromeSchemaData());
  ASSERT_TRUE(chrome_schema.valid());

  for (policy::Schema::Iterator it = chrome_schema.GetPropertiesIterator();
       !it.IsAtEnd(); it.Advance()) {
    expected_chrome_policies.push_back(PopulateExpectedPolicy(
        it.key(), std::string(), std::string(), nullptr, false));
  }

#if !BUILDFLAG(IS_CHROMEOS)
  // Add policies found in the precedence policy table.
  for (auto* policy : policy::metapolicy::kPrecedence) {
    expected_chrome_policies.push_back(PopulateExpectedPolicy(
        policy, std::string(), std::string(), nullptr, false));
  }
#endif  // !BUILDFLAG(IS_CHROMEOS)

  // Add extension policy to expected policy list.
  std::vector<std::vector<std::string>> expected_policies =
      expected_chrome_policies;
  expected_policies.push_back(PopulateExpectedPolicy(
      kNormalBooleanPolicy, std::string(), std::string(), nullptr, false));
  expected_policies.push_back(PopulateExpectedPolicy(
      kSensitiveArrayPolicy, std::string(), std::string(), nullptr, false));
  expected_policies.push_back(PopulateExpectedPolicy(
      kSensitiveBooleanPolicy, std::string(), std::string(), nullptr, false));
  expected_policies.push_back(PopulateExpectedPolicy(
      kSensitiveIntegerPolicy, std::string(), std::string(), nullptr, false));
  expected_policies.push_back(PopulateExpectedPolicy(
      kSensitiveNumberPolicy, std::string(), std::string(), nullptr, false));
  expected_policies.push_back(PopulateExpectedPolicy(
      kSensitiveObjectPolicy, std::string(), std::string(), nullptr, false));
  expected_policies.push_back(PopulateExpectedPolicy(
      kSensitiveStringPolicy, std::string(), std::string(), nullptr, false));

  // Verify if policy UI includes policy that extension have.
  VerifyPolicies(expected_policies);

  base::Value::Dict object_value;
  object_value.Set("objectProperty", true);
  base::Value::List array_value;
  array_value.Append(true);

  policy::PolicyMap values;
  values.Set(kNormalBooleanPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value(true), nullptr);
  values.Set(kSensitiveArrayPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value(std::move(array_value)), nullptr);
  values.Set(kSensitiveBooleanPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value(true), nullptr);
  values.Set(kSensitiveIntegerPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value(42), nullptr);
  values.Set(kSensitiveNumberPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value(3.141), nullptr);
  values.Set(kSensitiveObjectPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value(std::move(object_value)), nullptr);
  values.Set(kSensitiveStringPolicy, policy::POLICY_LEVEL_MANDATORY,
             policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD,
             base::Value("value"), nullptr);
  UpdateProviderPolicyForNamespace(extension_policy_namespace, values);

  // Add extension policy with values to expected policy list.
  const std::string mask_value = "********";
  std::vector<std::vector<std::string>> expected_policies_with_values =
      expected_chrome_policies;
  expected_policies_with_values.push_back(
      PopulateExpectedPolicy(kNormalBooleanPolicy, "true", "Cloud",
                             values.Get(kNormalBooleanPolicy), false));
  expected_policies_with_values.push_back(
      PopulateExpectedPolicy(kSensitiveArrayPolicy, mask_value, "Cloud",
                             values.Get(kSensitiveArrayPolicy), false));
  expected_policies_with_values.push_back(
      PopulateExpectedPolicy(kSensitiveBooleanPolicy, mask_value, "Cloud",
                             values.Get(kSensitiveBooleanPolicy), false));
  expected_policies_with_values.push_back(
      PopulateExpectedPolicy(kSensitiveIntegerPolicy, mask_value, "Cloud",
                             values.Get(kSensitiveIntegerPolicy), false));
  expected_policies_with_values.push_back(
      PopulateExpectedPolicy(kSensitiveNumberPolicy, mask_value, "Cloud",
                             values.Get(kSensitiveNumberPolicy), false));
  expected_policies_with_values.push_back(
      PopulateExpectedPolicy(kSensitiveObjectPolicy, mask_value, "Cloud",
                             values.Get(kSensitiveObjectPolicy), false));
  expected_policies_with_values.push_back(
      PopulateExpectedPolicy(kSensitiveStringPolicy, mask_value, "Cloud",
                             values.Get(kSensitiveStringPolicy), false));
  VerifyPolicies(expected_policies_with_values);
}

INSTANTIATE_TEST_SUITE_P(All,
                         ExtensionPolicyUITest,
#if BUILDFLAG(IS_CHROMEOS)
                         ::testing::Values(false, true)
#else   // BUILDFLAG(IS_CHROMEOS)
                         ::testing::Values(false)
#endif  // BUILDFLAG(IS_CHROMEOS)
);

#endif  // !BUILDFLAG(IS_ANDROID)

#if !BUILDFLAG(IS_ANDROID)

class PolicyUIManagedStatusTest : public PolicyUITest,
                                  public ::testing::WithParamInterface<bool> {
 public:
  PolicyUIManagedStatusTest() {
    if (GetParam()) {
      scoped_feature_list_.InitAndEnableFeature(
          features::kEnablePolicyPromotionBanner);
    } else {
      scoped_feature_list_.InitAndDisableFeature(
          features::kEnablePolicyPromotionBanner);
    }
  }
  bool isFeatureEnabled() { return GetParam(); }
  PolicyUIManagedStatusTest(const PolicyUIManagedStatusTest&) = delete;
  PolicyUIManagedStatusTest& operator=(const PolicyUIManagedStatusTest&) =
      delete;

  ~PolicyUIManagedStatusTest() override = default;

  void SetUpOnMainThread() override { PolicyUITest::SetUpOnMainThread(); }

  static constexpr std::string_view kPromotionBannerVisibilityJavaScript = R"(
    (function () {
      const element =
        document.getElementsByTagName('promotion-banner-section-container')[0];
      return element ? 'visible' : 'hidden';
    })();
  )";

  static constexpr std::string_view kPromotionBannerDismissJavaScript = R"(
    const promotionContainer =
      document.getElementsByTagName('promotion-banner-section-container')[0];
    if (promotionContainer){
      const dismissButton =
        promotionContainer.shadowRoot.getElementById('promotion-dismiss-button');
      dismissButton.click();
    }
  )";

  static constexpr std::string_view kPromotionBannerRedirectJavaScript = R"(
    const promotionContainer =
      document.getElementsByTagName('promotion-banner-section-container')[0];
    if (promotionContainer){
      const redirectButton =
        promotionContainer.shadowRoot.getElementById(
          'promotion-redirect-button'
        );
      if (redirectButton){
        redirectButton.click();
      }
    }
  )";

  static constexpr std::string_view kBannerVisible = "visible";
  static constexpr std::string_view kBannerHidden = "hidden";

  // The browser's locale needs to be "en-US" to be able to see the banner
  static constexpr std::string_view kValidLocale = "en-US";
  static constexpr std::string_view kInvalidLocale = "en-AU";

 protected:
  void SetPromotionBannerDismissedPref(bool is_dismissed) {
    auto* prefs = browser()->profile()->GetPrefs();
    prefs->SetBoolean(
        policy::policy_prefs::kHasDismissedPolicyPagePromotionBanner,
        is_dismissed);
  }

  void SetBrowserLocale(std::string_view locale) {
    g_browser_process->SetApplicationLocale(std::string(locale));
  }

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

IN_PROC_BROWSER_TEST_P(PolicyUIManagedStatusTest,
                       HandleGetShowPromotionTestShown) {
  policy::ScopedManagementServiceOverrideForTesting browser_management(
      policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  SetBrowserLocale(kValidLocale);

  SetPromotionBannerDismissedPref(false);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));

  auto result = EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
                       kPromotionBannerVisibilityJavaScript)
                    .ExtractString();

  if (isFeatureEnabled()) {
    EXPECT_EQ(result, kBannerHidden);
  } else {
    EXPECT_EQ(result, kBannerHidden);
  }
}

IN_PROC_BROWSER_TEST_P(PolicyUIManagedStatusTest,
                       HandleGetShowPromotionNotManagedHidden) {
  policy::ScopedManagementServiceOverrideForTesting browser_management(
      policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
      policy::EnterpriseManagementAuthority::NONE);

  SetBrowserLocale(kValidLocale);

  SetPromotionBannerDismissedPref(false);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));
  auto result = EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
                       kPromotionBannerVisibilityJavaScript)
                    .ExtractString();

  EXPECT_EQ(result, kBannerHidden);
}

IN_PROC_BROWSER_TEST_P(PolicyUIManagedStatusTest,
                       HandleGetShowPromotionDismisseddHidden) {
  policy::ScopedManagementServiceOverrideForTesting browser_management(
      policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  SetBrowserLocale(kValidLocale);

  SetPromotionBannerDismissedPref(true);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));
  auto result = EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
                       kPromotionBannerVisibilityJavaScript)
                    .ExtractString();

  EXPECT_EQ(result, kBannerHidden);
}

IN_PROC_BROWSER_TEST_P(PolicyUIManagedStatusTest,
                       HandleSetBannerDismissedHidden) {
  policy::ScopedManagementServiceOverrideForTesting browser_management(
      policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  SetBrowserLocale(kValidLocale);

  SetPromotionBannerDismissedPref(false);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));

  EXPECT_TRUE(ExecJs(browser()->tab_strip_model()->GetActiveWebContents(),
                     kPromotionBannerDismissJavaScript));

  auto result = EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
                       kPromotionBannerVisibilityJavaScript)
                    .ExtractString();
  EXPECT_EQ(result, kBannerHidden);
}

// Test is flaky on macOS. <https://crbug.com/394767577>
#if BUILDFLAG(IS_MAC)
#define MAYBE_HandleLocaleNotEnUSHidden DISABLED_HandleLocaleNotEnUSHidden
#else
#define MAYBE_HandleLocaleNotEnUSHidden HandleLocaleNotEnUSHidden
#endif

IN_PROC_BROWSER_TEST_P(PolicyUIManagedStatusTest,
                       MAYBE_HandleLocaleNotEnUSHidden) {
  policy::ScopedManagementServiceOverrideForTesting browser_management(
      policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  SetBrowserLocale(kInvalidLocale);

  SetPromotionBannerDismissedPref(false);

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));

  auto result = EvalJs(browser()->tab_strip_model()->GetActiveWebContents(),
                       kPromotionBannerVisibilityJavaScript)
                    .ExtractString();
  EXPECT_EQ(result, kBannerHidden);
}

IN_PROC_BROWSER_TEST_P(PolicyUIManagedStatusTest,
                       HistogramRecordedWhenBannerDisplayed) {
  policy::ScopedManagementServiceOverrideForTesting browser_management(
      policy::ManagementServiceFactory::GetForProfile(browser()->profile()),
      policy::EnterpriseManagementAuthority::CLOUD);

  SetBrowserLocale(kValidLocale);

  SetPromotionBannerDismissedPref(false);

  base::HistogramTester histogram_tester;

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           GURL(chrome::kChromeUIPolicyURL)));

    histogram_tester.ExpectBucketCount(
        "Enterprise.PolicyPromotionBannerDisplayed", false, 1);
}

IN_PROC_BROWSER_TEST_P(PolicyUIManagedStatusTest, PageLoadedInGuestMode) {
  // Verifies that the page opens in guest session.
  Browser* policy_browser = OpenURLOffTheRecord(
      browser()->profile(), GURL(chrome::kChromeUIPolicyURL));
  ASSERT_TRUE(policy_browser);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(policy_browser,
                               GURL(chrome::kChromeUIPolicyURL)));

  auto result =
      EvalJs(policy_browser->tab_strip_model()->GetActiveWebContents(),
             kPromotionBannerVisibilityJavaScript)
          .ExtractString();
  EXPECT_EQ(result, kBannerHidden);
}

INSTANTIATE_TEST_SUITE_P(PolicyManagedUITestInstance,
                         PolicyUIManagedStatusTest,
                         ::testing::Values(false, true));
#endif  // !BUILDFLAG(IS_ANDROID)