File: supervised_user_navigation_throttle_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 (1417 lines) | stat: -rw-r--r-- 57,363 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
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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <string>
#include <tuple>
#include <vector>

#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/supervised_user/supervised_user_navigation_observer.h"
#include "chrome/browser/supervised_user/supervised_user_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_test_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/mixin_based_in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chrome/test/supervised_user/supervision_mixin.h"
#include "components/supervised_user/core/browser/permission_request_creator_mock.h"
#include "components/supervised_user/core/browser/supervised_user_interstitial.h"
#include "components/supervised_user/core/browser/supervised_user_service.h"
#include "components/supervised_user/core/browser/supervised_user_settings_service.h"
#include "components/supervised_user/core/browser/supervised_user_url_filter.h"
#include "components/supervised_user/core/browser/supervised_user_utils.h"
#include "components/supervised_user/core/common/features.h"
#include "components/supervised_user/core/common/features_testutils.h"
#include "components/supervised_user/core/common/supervised_user_constants.h"
#include "components/supervised_user/test_support/kids_management_api_server_mock.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/page_type.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/shell.h"
#include "chrome/browser/ui/webui/ash/parent_access/parent_access_dialog.h"
#include "ui/events/event_constants.h"
#include "ui/events/test/event_generator.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

namespace {

using content::NavigationController;
using content::WebContents;

static const char* kExampleHost = "www.example.com";
static const char* kExampleHost2 = "www.example2.com";
static const char* kStrippedExampleHost = "example.com";
static const char* kFamiliesHost = "families.google.com";
static const char* kIframeHost1 = "www.iframe1.com";
static const char* kIframeHost2 = "www.iframe2.com";

#if BUILDFLAG(IS_CHROMEOS)
constexpr char kLocalUrlAccessCommand[] = "requestUrlAccessLocal";
#endif
constexpr char kRemoteUrlAccessCommand[] = "requestUrlAccessRemote";

// Class to keep track of iframes created and destroyed.
// TODO(crbug.com/40173416): Can be replaced with
// WebContents::UnsafeFindFrameByFrameTreeNodeId.
class RenderFrameTracker : public content::WebContentsObserver {
 public:
  explicit RenderFrameTracker(content::WebContents* web_contents)
      : content::WebContentsObserver(web_contents) {}
  ~RenderFrameTracker() override = default;

  // content::WebContentsObserver:
  void RenderFrameHostChanged(content::RenderFrameHost* old_host,
                              content::RenderFrameHost* new_host) override;
  void FrameDeleted(content::FrameTreeNodeId frame_tree_node_id) override;

  content::RenderFrameHost* GetHost(content::FrameTreeNodeId frame_id) {
    if (!base::Contains(render_frame_hosts_, frame_id)) {
      return nullptr;
    }
    return render_frame_hosts_[frame_id];
  }

 private:
  std::map<content::FrameTreeNodeId,
           raw_ptr<content::RenderFrameHost, CtnExperimental>>

      render_frame_hosts_;
};

void RenderFrameTracker::RenderFrameHostChanged(
    content::RenderFrameHost* old_host,
    content::RenderFrameHost* new_host) {
  render_frame_hosts_[new_host->GetFrameTreeNodeId()] = new_host;
}

void RenderFrameTracker::FrameDeleted(
    content::FrameTreeNodeId frame_tree_node_id) {
  if (!base::Contains(render_frame_hosts_, frame_tree_node_id)) {
    return;
  }

  render_frame_hosts_.erase(frame_tree_node_id);
}

// Helper class to wait for a particular navigation in a particular render
// frame in tests.
class NavigationFinishedWaiter : public content::WebContentsObserver {
 public:
  NavigationFinishedWaiter(content::WebContents* web_contents,
                           content::FrameTreeNodeId frame_id,
                           const GURL& url);
  NavigationFinishedWaiter(const NavigationFinishedWaiter&) = delete;
  NavigationFinishedWaiter& operator=(const NavigationFinishedWaiter&) = delete;
  ~NavigationFinishedWaiter() override = default;

  void Wait();

  // content::WebContentsObserver:
  void DidFinishNavigation(
      content::NavigationHandle* navigation_handle) override;

 private:
  content::FrameTreeNodeId frame_id_;
  GURL url_;
  bool did_finish_ = false;
  base::RunLoop run_loop_{base::RunLoop::Type::kNestableTasksAllowed};
};

NavigationFinishedWaiter::NavigationFinishedWaiter(
    content::WebContents* web_contents,
    content::FrameTreeNodeId frame_id,
    const GURL& url)
    : content::WebContentsObserver(web_contents),
      frame_id_(frame_id),
      url_(url) {}

void NavigationFinishedWaiter::Wait() {
  if (did_finish_) {
    return;
  }
  run_loop_.Run();
}

void NavigationFinishedWaiter::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  if (!navigation_handle->HasCommitted()) {
    return;
  }

  if (navigation_handle->GetFrameTreeNodeId() != frame_id_ ||
      navigation_handle->GetURL() != url_) {
    return;
  }

  did_finish_ = true;
  run_loop_.Quit();
}

class SupervisedUserNavigationThrottleTestBase
    : public MixinBasedInProcessBrowserTest {
 protected:
  explicit SupervisedUserNavigationThrottleTestBase(
      supervised_user::SupervisionMixin::SignInMode sign_in_mode)
      : supervision_mixin_(mixin_host_,
                           this,
                           embedded_test_server(),
                           {
                               .sign_in_mode = sign_in_mode,
                               .embedded_test_server_options =
                                   {.resolver_rules_map_host_list =
                                        "*.example.com, *.example2.com, "
                                        "example.com, example2.com, "
                                        "*.families.google.com, "
                                        "*.iframe1.com, *.iframe2.com, "
                                        "iframe1.com, iframe2.com"},
                           }),
        prerender_helper_(base::BindRepeating(
            &SupervisedUserNavigationThrottleTestBase::web_contents,
            base::Unretained(this))) {}
  ~SupervisedUserNavigationThrottleTestBase() override = default;

  void SetUp() override;
  void SetUpOnMainThread() override;

  void BlockHost(const std::string& host) {
    supervised_user_test_util::SetManualFilterForHost(browser()->profile(),
                                                      host,
                                                      /*allowlist=*/false);
  }

  void AllowlistHost(const std::string& host) {
    supervised_user_test_util::SetManualFilterForHost(browser()->profile(),
                                                      host, /*allowlist=*/true);
  }

  bool IsInterstitialBeingShownInMainFrame(Browser* browser);

  content::test::PrerenderTestHelper& prerender_helper() {
    return prerender_helper_;
  }

  content::WebContents* web_contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

  supervised_user::KidsManagementApiServerMock& kids_management_api_mock() {
    return supervision_mixin_.api_mock_setup_mixin().api_mock();
  }

 private:
  supervised_user::SupervisionMixin supervision_mixin_;
  content::test::PrerenderTestHelper prerender_helper_;
};

bool SupervisedUserNavigationThrottleTestBase::
    IsInterstitialBeingShownInMainFrame(Browser* browser) {
  WebContents* tab = browser->tab_strip_model()->GetActiveWebContents();
  std::u16string title;
  ui_test_utils::GetCurrentTabTitle(browser, &title);
  return tab->GetController().GetLastCommittedEntry()->GetPageType() ==
             content::PAGE_TYPE_ERROR &&
         title == u"Site blocked";
}

void SupervisedUserNavigationThrottleTestBase::SetUp() {
  prerender_helper_.RegisterServerRequestMonitor(embedded_test_server());
  MixinBasedInProcessBrowserTest::SetUp();
}

void SupervisedUserNavigationThrottleTestBase::SetUpOnMainThread() {
  MixinBasedInProcessBrowserTest::SetUpOnMainThread();

  ASSERT_TRUE(embedded_test_server()->Started());
}

class SupervisedUserNavigationThrottleTest
    : public SupervisedUserNavigationThrottleTestBase {
 protected:
  SupervisedUserNavigationThrottleTest()
      : SupervisedUserNavigationThrottleTestBase(
            supervised_user::SupervisionMixin::SignInMode::kSupervised) {}
  ~SupervisedUserNavigationThrottleTest() override = default;
};

class SupervisedUserNavigationThrottleWithPrerenderingTest
    : public SupervisedUserNavigationThrottleTestBase,
      public testing::WithParamInterface<std::string> {
 protected:
  SupervisedUserNavigationThrottleWithPrerenderingTest()
      : SupervisedUserNavigationThrottleTestBase(
            supervised_user::SupervisionMixin::SignInMode::kSupervised) {}
  ~SupervisedUserNavigationThrottleWithPrerenderingTest() override = default;

  static std::string GetTargetHint() { return GetParam(); }
};

INSTANTIATE_TEST_SUITE_P(,
                         SupervisedUserNavigationThrottleWithPrerenderingTest,
                         testing::Values("_self", "_blank"),
                         [](const testing::TestParamInfo<std::string>& info) {
                           return base::StrCat({"WithTargetHint", info.param});
                         });

// Tests that prerendering fails in supervised user mode.
#if BUILDFLAG(IS_CHROMEOS)
// TODO(crbug.com/40201321): Flaky on ChromeOS.
#define MAYBE_DisallowPrerendering DISABLED_DisallowPrerendering
#else
#define MAYBE_DisallowPrerendering DisallowPrerendering
#endif
IN_PROC_BROWSER_TEST_P(SupervisedUserNavigationThrottleWithPrerenderingTest,
                       MAYBE_DisallowPrerendering) {
  const GURL initial_url = embedded_test_server()->GetURL("/simple.html");
  const GURL allowed_url =
      embedded_test_server()->GetURL("/supervised_user/simple.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  prerender_helper().NavigatePrimaryPage(initial_url);

  // If throttled, the prerendered navigation should not have started and we
  // should not be requesting corresponding resources.
  content::test::PrerenderHostCreationWaiter host_creation_waiter;
  prerender_helper().AddPrerendersAsync(
      {allowed_url}, /*eagerness=*/std::nullopt, GetTargetHint());
  content::FrameTreeNodeId host_id = host_creation_waiter.Wait();
  auto* prerender_web_contents =
      content::WebContents::FromFrameTreeNodeId(host_id);
  content::test::PrerenderHostObserver host_observer(*prerender_web_contents,
                                                     host_id);
  host_observer.WaitForDestroyed();
  EXPECT_EQ(0, prerender_helper().GetRequestCount(allowed_url));

  // Regular navigation should proceed, however.
  content::TestNavigationObserver observer(
      web_contents(), content::MessageLoopRunner::QuitMode::IMMEDIATE,
      /*ignore_uncommitted_navigations*/ false);
  prerender_helper().NavigatePrimaryPage(allowed_url);
  observer.WaitForNavigationFinished();
  EXPECT_TRUE(observer.last_navigation_succeeded());
  EXPECT_EQ(allowed_url, observer.last_navigation_url());
  EXPECT_EQ(1, prerender_helper().GetRequestCount(allowed_url));
}

// Tests that navigating to a blocked page simply fails if there is no
// SupervisedUserNavigationObserver.
IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleTest,
                       NoNavigationObserverBlock) {
  Profile* profile = browser()->profile();
  supervised_user_test_util::SetWebFilterType(
      profile, supervised_user::WebFilterType::kCertainSites);

  std::unique_ptr<WebContents> web_contents(
      WebContents::Create(WebContents::CreateParams(profile)));
  NavigationController& controller = web_contents->GetController();
  content::TestNavigationObserver observer(web_contents.get());
  controller.LoadURL(GURL("http://www.example.com"), content::Referrer(),
                     ui::PAGE_TRANSITION_TYPED, std::string());
  observer.Wait();
  content::NavigationEntry* entry = controller.GetVisibleEntry();
  ASSERT_TRUE(entry);
  EXPECT_EQ(content::PAGE_TYPE_NORMAL, entry->GetPageType());
  EXPECT_FALSE(observer.last_navigation_succeeded());
}

IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleTest,
                       BlockMainFrameWithInterstitial) {
  BlockHost(kExampleHost2);

  GURL allowed_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/simple.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), allowed_url));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost2, "/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));
}

IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleTest,
                       DontBlockSubFrame) {
  BlockHost(kExampleHost2);
  BlockHost(kIframeHost2);

  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();

  GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  // Both iframes (from allowed host iframe1.com as well as from blocked host
  // iframe2.com) should be loaded normally, since we don't filter iframes
  // (yet) - see crbug.com/651115.
  EXPECT_TRUE(content::EvalJs(tab, "loaded1()").ExtractBool());
  EXPECT_TRUE(content::EvalJs(tab, "loaded2()").ExtractBool());
}

IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleTest,
                       AllowFamiliesDotGoogleDotComAccess) {
  // Simulate families.google.com being set in the blocklist.
  BlockHost(kFamiliesHost);

  // A production endpoint is used here because a Tast test would be too
  // expensive to be used for this specific case.
  const GURL kFamiliesDotGoogleDotComUrl =
      GURL("https://families.google.com/families");

  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), kFamiliesDotGoogleDotComUrl));

  // Get the top level WebContents.
  content::WebContents* contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  EXPECT_EQ(contents->GetLastCommittedURL(), kFamiliesDotGoogleDotComUrl);

  // families.google.com should not be blocked.
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));
}

class SupervisedUserIframeFilterTest
    : public SupervisedUserNavigationThrottleTestBase,
      public testing::WithParamInterface<
          supervised_user::testing::LocalWebApprovalsTestCase> {
 protected:
  SupervisedUserIframeFilterTest()
      : SupervisedUserNavigationThrottleTestBase(
            supervised_user::SupervisionMixin::SignInMode::kSupervised) {
  }

  ~SupervisedUserIframeFilterTest() override = default;

  void SetUpOnMainThread() override;
  void TearDownOnMainThread() override;

  std::vector<content::FrameTreeNodeId> GetBlockedFrames();
  const GURL& GetBlockedFrameURL(content::FrameTreeNodeId frame_id);
  bool IsInterstitialBeingShownInFrame(content::FrameTreeNodeId frame_id);
  bool IsRemoteApprovalsButtonBeingShown(content::FrameTreeNodeId frame_id);
  bool IsLocalApprovalsButtonBeingShown(content::FrameTreeNodeId frame_id);
  bool IsBlockReasonBeingShown(content::FrameTreeNodeId frame_id);
  bool IsDetailsLinkBeingShown(content::FrameTreeNodeId frame_id);
  void CheckPreferredApprovalButton(content::FrameTreeNodeId frame_id);
  bool IsLocalApprovalsInsteadButtonBeingShown(
      content::FrameTreeNodeId frame_id);
  void SendCommandToFrame(const std::string& command_name,
                          content::FrameTreeNodeId frame_id);
  void WaitForNavigationFinished(content::FrameTreeNodeId frame_id,
                                 const GURL& url);
  bool IsLocalWebApprovalsEnabled() const;

  supervised_user::PermissionRequestCreatorMock* permission_creator() {
    return permission_creator_;
  }

  RenderFrameTracker* tracker() { return tracker_.get(); }

 private:
  static supervised_user::testing::LocalWebApprovalsTestCase
  GetLocalWebApprovalsSupportTestParam() {
    return GetParam();
  }

 private:
  bool RunCommandAndGetBooleanFromFrame(content::FrameTreeNodeId frame_id,
                                        const std::string& command);

  std::unique_ptr<RenderFrameTracker> tracker_;
  raw_ptr<supervised_user::PermissionRequestCreatorMock, DanglingUntriaged>
      permission_creator_;

  // Each feature is enabled within its own feature list.
  std::unique_ptr<base::test::ScopedFeatureList>
      local_web_approvals_test_support_{
          GetLocalWebApprovalsSupportTestParam().MakeFeatureList()};
};

void SupervisedUserIframeFilterTest::SetUpOnMainThread() {
  SupervisedUserNavigationThrottleTestBase::SetUpOnMainThread();

  supervised_user::SupervisedUserService* service =
      SupervisedUserServiceFactory::GetForProfile(browser()->profile());
  supervised_user::SupervisedUserSettingsService* settings_service =
      SupervisedUserSettingsServiceFactory::GetForKey(
          browser()->profile()->GetProfileKey());
  CHECK(settings_service);
  std::unique_ptr<supervised_user::PermissionRequestCreator> creator =
      std::make_unique<supervised_user::PermissionRequestCreatorMock>(
          *settings_service);
  permission_creator_ =
      static_cast<supervised_user::PermissionRequestCreatorMock*>(
          creator.get());
  permission_creator_->SetEnabled();
  service->remote_web_approvals_manager().ClearApprovalRequestsCreators();
  service->remote_web_approvals_manager().AddApprovalRequestCreator(
      std::move(creator));

  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  tracker_ = std::make_unique<RenderFrameTracker>(tab);
}

void SupervisedUserIframeFilterTest::TearDownOnMainThread() {
  tracker_.reset();
  SupervisedUserNavigationThrottleTestBase::TearDownOnMainThread();
}

std::vector<content::FrameTreeNodeId>
SupervisedUserIframeFilterTest::GetBlockedFrames() {
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  auto* navigation_observer =
      SupervisedUserNavigationObserver::FromWebContents(tab);
  const auto& interstitials = navigation_observer->interstitials_for_test();

  std::vector<content::FrameTreeNodeId> blocked_frames;
  blocked_frames.reserve(interstitials.size());

  for (const auto& elem : interstitials) {
    blocked_frames.push_back(elem.first);
  }

  return blocked_frames;
}

const GURL& SupervisedUserIframeFilterTest::GetBlockedFrameURL(
    content::FrameTreeNodeId frame_id) {
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  auto* navigation_observer =
      SupervisedUserNavigationObserver::FromWebContents(tab);
  const auto& interstitials = navigation_observer->interstitials_for_test();
  DCHECK(base::Contains(interstitials, frame_id));
  return interstitials.at(frame_id)->url();
}

bool SupervisedUserIframeFilterTest::IsInterstitialBeingShownInFrame(
    content::FrameTreeNodeId frame_id) {
  std::string command =
      "document.querySelector('.supervised-user-block') != null";
  return RunCommandAndGetBooleanFromFrame(frame_id, command);
}

bool SupervisedUserIframeFilterTest::IsBlockReasonBeingShown(
    content::FrameTreeNodeId frame_id) {
  std::string command =
      "getComputedStyle(document.getElementById('block-reason')).display !== "
      "\"none\"";
  return RunCommandAndGetBooleanFromFrame(frame_id, command);
}

bool SupervisedUserIframeFilterTest::IsDetailsLinkBeingShown(
    content::FrameTreeNodeId frame_id) {
  std::string command =
      "getComputedStyle(document.getElementById('block-reason-show-details-"
      "link')).display !== \"none\"";
  return RunCommandAndGetBooleanFromFrame(frame_id, command);
}

bool SupervisedUserIframeFilterTest::IsRemoteApprovalsButtonBeingShown(
    content::FrameTreeNodeId frame_id) {
  std::string command =
      "!document.getElementById('remote-approvals-button').hidden";
  return RunCommandAndGetBooleanFromFrame(frame_id, command);
}

bool SupervisedUserIframeFilterTest::IsLocalApprovalsButtonBeingShown(
    content::FrameTreeNodeId frame_id) {
  std::string command =
      "!document.getElementById('local-approvals-button').hidden";
  return RunCommandAndGetBooleanFromFrame(frame_id, command);
}

void SupervisedUserIframeFilterTest::CheckPreferredApprovalButton(
    content::FrameTreeNodeId frame_id) {
  std::string command =
      "document.getElementById('local-approvals-button').classList.contains("
      "'primary-button') &&"
      " !document.getElementById('local-approvals-button').classList."
      "contains('secondary-button') &&"
      " document.getElementById('remote-approvals-button').classList."
      "contains('secondary-button') &&"
      " !document.getElementById('remote-approvals-button').classList."
      "contains('primary-button');";
  ASSERT_TRUE(RunCommandAndGetBooleanFromFrame(frame_id, command));
}

bool SupervisedUserIframeFilterTest::IsLocalApprovalsInsteadButtonBeingShown(
    content::FrameTreeNodeId frame_id) {
  std::string command =
      "!document.getElementById('local-approvals-remote-request-sent-button')."
      "hidden";
  return RunCommandAndGetBooleanFromFrame(frame_id, command);
}

void SupervisedUserIframeFilterTest::SendCommandToFrame(
    const std::string& command_name,
    content::FrameTreeNodeId frame_id) {
  auto* render_frame_host = tracker()->GetHost(frame_id);
  DCHECK(render_frame_host);
  DCHECK(render_frame_host->IsRenderFrameLive());
  std::string command = base::StrCat({"sendCommand(\'", command_name, "\')"});
  ASSERT_TRUE(
      content::ExecJs(content::ToRenderFrameHost(render_frame_host), command));
}

void SupervisedUserIframeFilterTest::WaitForNavigationFinished(
    content::FrameTreeNodeId frame_id,
    const GURL& url) {
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  NavigationFinishedWaiter waiter(tab, frame_id, url);
  waiter.Wait();
}

bool SupervisedUserIframeFilterTest::RunCommandAndGetBooleanFromFrame(
    content::FrameTreeNodeId frame_id,
    const std::string& command) {
  // First check that SupervisedUserNavigationObserver believes that there is
  // an error page in the frame with frame tree node id |frame_id|.
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  auto* navigation_observer =
      SupervisedUserNavigationObserver::FromWebContents(tab);
  auto& interstitials = navigation_observer->interstitials_for_test();

  if (!base::Contains(interstitials, frame_id)) {
    return false;
  }

  auto* render_frame_host = tracker()->GetHost(frame_id);
  DCHECK(render_frame_host->IsRenderFrameLive());

  auto target = content::ToRenderFrameHost(render_frame_host);
  return content::EvalJs(target, command,
                         content::EXECUTE_SCRIPT_NO_USER_GESTURE)
      .ExtractBool();
}

// Returns whether the feature is in fact enabled, rather that was requested to
// be enabled.
bool SupervisedUserIframeFilterTest::IsLocalWebApprovalsEnabled() const {
  return supervised_user::IsLocalWebApprovalsEnabled();
}

INSTANTIATE_TEST_SUITE_P(
    LocalWebApprovalsEnabled,
    SupervisedUserIframeFilterTest,
    supervised_user::testing::LocalWebApprovalsTestCase::Values(),
    [](const testing::TestParamInfo<
        supervised_user::testing::LocalWebApprovalsTestCase>& info) {
      return base::StrCat({"WithLocalWebApprovalsTestCase",
                           static_cast<std::string>(info.param)});
    });

IN_PROC_BROWSER_TEST_P(SupervisedUserIframeFilterTest, BlockSubFrame) {
  base::HistogramTester histogram_tester;

  BlockHost(kIframeHost2);
  GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  // The first iframe's source is |kIframeHost1| and it is not blocked. It will
  // successfully load.
  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 1u);

  content::FrameTreeNodeId blocked_frame_id = blocked[0];

  EXPECT_TRUE(IsInterstitialBeingShownInFrame(blocked_frame_id));

  permission_creator()->SetPermissionResult(true);
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frame_id);
  EXPECT_EQ(permission_creator()->url_requests().size(), 1u);
  std::string requested_host = permission_creator()->url_requests()[0].host();

  EXPECT_EQ(requested_host, kIframeHost2);

  WaitForNavigationFinished(blocked[0],
                            permission_creator()->url_requests()[0]);

  EXPECT_FALSE(IsInterstitialBeingShownInFrame(blocked_frame_id));

  histogram_tester.ExpectUniqueSample(
      supervised_user::SupervisedUserInterstitial::
          kInterstitialCommandHistogramName,
      supervised_user::SupervisedUserInterstitial::Commands::
          REMOTE_ACCESS_REQUEST,
      1);
  histogram_tester.ExpectUniqueSample(
      supervised_user::SupervisedUserInterstitial::
          kInterstitialPermissionSourceHistogramName,
      supervised_user::SupervisedUserInterstitial::RequestPermissionSource::
          SUB_FRAME,
      1);
}

IN_PROC_BROWSER_TEST_P(SupervisedUserIframeFilterTest, BlockMultipleSubFrames) {
  BlockHost(kIframeHost1);
  BlockHost(kIframeHost2);

  GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 2u);

  content::FrameTreeNodeId blocked_frame_id_1 = blocked[0];
  GURL blocked_frame_url_1 = GetBlockedFrameURL(blocked_frame_id_1);

  content::FrameTreeNodeId blocked_frame_id_2 = blocked[1];
  GURL blocked_frame_url_2 = GetBlockedFrameURL(blocked_frame_id_2);

  EXPECT_TRUE(IsInterstitialBeingShownInFrame(blocked_frame_id_1));

  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();

  permission_creator()->SetPermissionResult(true);
  permission_creator()->DelayHandlingForNextRequests();

  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frame_id_1);
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frame_id_2);

  EXPECT_EQ(permission_creator()->url_requests().size(), 2u);
  EXPECT_EQ(permission_creator()->url_requests()[0], GURL(blocked_frame_url_1));
  EXPECT_EQ(permission_creator()->url_requests()[1], GURL(blocked_frame_url_2));

  NavigationFinishedWaiter waiter1(tab, blocked_frame_id_1,
                                   blocked_frame_url_1);
  NavigationFinishedWaiter waiter2(tab, blocked_frame_id_2,
                                   blocked_frame_url_2);

  permission_creator()->HandleDelayedRequests();

  waiter1.Wait();
  waiter2.Wait();

  DCHECK_EQ(GetBlockedFrames().size(), 0u);
}

IN_PROC_BROWSER_TEST_P(SupervisedUserIframeFilterTest, TestBackButton) {
  BlockHost(kIframeHost1);

  GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 1u);

  permission_creator()->SetPermissionResult(true);
  permission_creator()->DelayHandlingForNextRequests();

  SendCommandToFrame(kRemoteUrlAccessCommand, blocked[0]);

  std::string command = "document.getElementById('back-button').hidden;";

  auto* render_frame_host = tracker()->GetHost(blocked[0]);
  DCHECK(render_frame_host->IsRenderFrameLive());
  auto target = content::ToRenderFrameHost(render_frame_host);
  // Back button should be hidden in iframes.
  EXPECT_EQ(true, content::EvalJs(target, command,
                                  content::EXECUTE_SCRIPT_NO_USER_GESTURE));
}

IN_PROC_BROWSER_TEST_P(SupervisedUserIframeFilterTest,
                       TestBackButtonMainFrame) {
  BlockHost(kExampleHost);

  GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 1u);

  permission_creator()->SetPermissionResult(true);
  permission_creator()->DelayHandlingForNextRequests();

  SendCommandToFrame(kRemoteUrlAccessCommand, blocked[0]);

  std::string command = "document.getElementById('back-button').hidden;";
  auto* render_frame_host = tracker()->GetHost(blocked[0]);
  DCHECK(render_frame_host->IsRenderFrameLive());

  auto target = content::ToRenderFrameHost(render_frame_host);
  bool value =
      content::EvalJs(target, command, content::EXECUTE_SCRIPT_NO_USER_GESTURE)
          .ExtractBool();

  // Back button should be hidden only when local web approvals is enabled due
  // to new UI for local web approvals.
  EXPECT_EQ(value, IsLocalWebApprovalsEnabled());
}

// Tests that the trivial www-subdomain stripping is applied on the url
// of the interstitial. Blocked urls without further conflicts will be
// unblocked by a remote approval.
IN_PROC_BROWSER_TEST_P(
    SupervisedUserIframeFilterTest,
    BlockedMainFrameFromClassifyUrlForUnstripedHostIsStrippedInRemoteApproval) {
  // Classify url blocks the navigation to the target url.
  // No matching blocklist entry exists for the host of the target url.
  kids_management_api_mock().RestrictSubsequentClassifyUrl();
  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 1u);
  content::FrameTreeNodeId blocked_frame_id = blocked[0];
  GURL blocked_frame_url = GetBlockedFrameURL(blocked_frame_id);
  EXPECT_TRUE(IsInterstitialBeingShownInFrame(blocked_frame_id));

  // Request remote approval.
  permission_creator()->SetPermissionResult(true);
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frame_id);
  EXPECT_EQ(permission_creator()->url_requests().size(), 1u);
  std::string requested_host = permission_creator()->url_requests()[0].host();

  // The trivial "www" subdomain is stripped for the url in the remote approval
  // request.
  EXPECT_EQ(requested_host, kStrippedExampleHost);

#if !BUILDFLAG(IS_CHROMEOS)
  // TODO(crbug.com/376229427): Unguard once flakiness removed.
  WaitForNavigationFinished(blocked_frame_id, blocked_url);
  // The unstriped url gets unblocked.
  EXPECT_FALSE(IsInterstitialBeingShownInFrame(blocked_frame_id));
#endif
}

// Tests that the url stripping is applied on the url on the interstitial, when
// there is no unstriped host entry in the blocklist.
IN_PROC_BROWSER_TEST_P(
    SupervisedUserIframeFilterTest,
    BlockedMainFrameFromBlockListIsStrippedInRemoteApproval) {
  // Manual parental blocklist entry blocks the navigation to the target url.
  BlockHost("*.example.*");
  kids_management_api_mock().AllowSubsequentClassifyUrl();
  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 1u);
  content::FrameTreeNodeId blocked_frame_id = blocked[0];
  GURL blocked_frame_url = GetBlockedFrameURL(blocked_frame_id);
  EXPECT_TRUE(IsInterstitialBeingShownInFrame(blocked_frame_id));

  // Request remote approval.
  permission_creator()->SetPermissionResult(true);
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frame_id);
  EXPECT_EQ(permission_creator()->url_requests().size(), 1u);
  std::string requested_host = permission_creator()->url_requests()[0].host();

  // The trivial "www" subdomain has been stripped from the host in the
  // interstitial, because the conflicting entry in the blocklist is not a
  // www-subdomain conflict.
  EXPECT_EQ(requested_host, kStrippedExampleHost);
}

// Tests that the url stripping is skipped on the url on the interstitial, when
// there is a unstriped host entry in the blocklist. Blocked urls without
// further conflicts will be unblocked by a remote approval.
IN_PROC_BROWSER_TEST_P(
    SupervisedUserIframeFilterTest,
    BlockedMainFrameFromBlockListForUnstripedHostSkipsStrippingInRemoteApproval) {
  // Manual parental blocklist entry for the unstriped url blocks the
  // navigation to the target url.
  BlockHost(kExampleHost);
  kids_management_api_mock().AllowSubsequentClassifyUrl();
  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 1u);
  content::FrameTreeNodeId blocked_frame_id = blocked[0];
  GURL blocked_frame_url = GetBlockedFrameURL(blocked_frame_id);
  EXPECT_TRUE(IsInterstitialBeingShownInFrame(blocked_frame_id));

  // Request remote approval.
  permission_creator()->SetPermissionResult(true);
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frame_id);
  EXPECT_EQ(permission_creator()->url_requests().size(), 1u);
  std::string requested_host = permission_creator()->url_requests()[0].host();

  // The stripping has been skipped for the url of the interstitial, because an
  // identical entry exists in the blocklist. The interstitial contains the full
  // url.
  EXPECT_EQ(requested_host, kExampleHost);
  // The navigation gets unblocked.
  WaitForNavigationFinished(blocked_frame_id, blocked_frame_url);
  EXPECT_FALSE(IsInterstitialBeingShownInFrame(blocked_frame_id));
}

IN_PROC_BROWSER_TEST_P(SupervisedUserIframeFilterTest,
                       AllowlistedMainFrameDenylistedIframe) {
  AllowlistHost(kExampleHost);
  BlockHost(kIframeHost1);

  GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));
  auto blocked = GetBlockedFrames();
  EXPECT_EQ(blocked.size(), 1u);
  EXPECT_EQ(kIframeHost1, GetBlockedFrameURL(blocked[0]).host());
}

IN_PROC_BROWSER_TEST_P(SupervisedUserIframeFilterTest,
                       RememberAlreadyRequestedHosts) {
  BlockHost(kExampleHost);

  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked_frames = GetBlockedFrames();
  EXPECT_EQ(blocked_frames.size(), 1u);

  // Expect that remote approvals button is shown.
  EXPECT_TRUE(IsRemoteApprovalsButtonBeingShown(blocked_frames[0]));
  // Expect that the local approvals button is shown if the flag is enabled.
  EXPECT_EQ(IsLocalWebApprovalsEnabled(),
            IsLocalApprovalsButtonBeingShown(blocked_frames[0]));
  // Expect that the "Block reason" is shown.
  EXPECT_TRUE(IsBlockReasonBeingShown(blocked_frames[0]));

  // Delay approval/denial by parent.
  permission_creator()->SetPermissionResult(true);
  permission_creator()->DelayHandlingForNextRequests();

  // Request permission.
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frames[0]);

  // Navigate to another allowed url.
  GURL allowed_url = embedded_test_server()->GetURL(
      kExampleHost2, "/supervised_user/with_iframes.html");
  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), allowed_url));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  // Navigate back to the blocked url.
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  // Error page is being shown, but "Ask Permission" button is not being shown.
  EXPECT_FALSE(IsRemoteApprovalsButtonBeingShown(blocked_frames[0]));
  // Expect that the local approvals instead button is shown on the page if the
  // flag is enabled.
  EXPECT_EQ(IsLocalWebApprovalsEnabled(),
            IsLocalApprovalsInsteadButtonBeingShown(blocked_frames[0]));
  // Expect that the "Block reason" is not shown.
  EXPECT_FALSE(IsBlockReasonBeingShown(blocked_frames[0]));

  content::WebContents* active_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  SupervisedUserNavigationObserver* navigation_observer =
      SupervisedUserNavigationObserver::FromWebContents(active_contents);
  ASSERT_NE(navigation_observer, nullptr);

  EXPECT_TRUE(base::Contains(navigation_observer->requested_hosts_for_test(),
                             kExampleHost));

  NavigationFinishedWaiter waiter(
      active_contents,
      active_contents->GetPrimaryMainFrame()->GetFrameTreeNodeId(),
      blocked_url);
  permission_creator()->HandleDelayedRequests();
  waiter.Wait();

  EXPECT_FALSE(base::Contains(navigation_observer->requested_hosts_for_test(),
                              kExampleHost));

  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));
}

IN_PROC_BROWSER_TEST_P(SupervisedUserIframeFilterTest,
                       IFramesWithSameDomainAsMainFrameAllowed) {
  supervised_user_test_util::SetWebFilterType(
      browser()->profile(), supervised_user::WebFilterType::kCertainSites);

  base::RunLoop().RunUntilIdle();

  // Allows |www.example.com|.
  AllowlistHost("*.example.*");

  // |with_frames_same_domain.html| contains subframes with "a.example.com" and
  // "b.example.com", and "c.example2.com" urls.
  GURL allowed_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes_same_domain.html");

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), allowed_url));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked_frames = GetBlockedFrames();
  EXPECT_EQ(blocked_frames.size(), 1u);
  EXPECT_EQ(GetBlockedFrameURL(blocked_frames[0]).host(), "www.c.example2.com");
}

// The switches::kHostWindowBounds commandline flag doesn't appear to work
// for tests on other platforms.
// TODO(b/300426225): enable these tests on Linux/Mac/Windows.
#if BUILDFLAG(IS_CHROMEOS)
class SupervisedUserNarrowWidthIframeFilterTest
    : public SupervisedUserIframeFilterTest {
 protected:
  SupervisedUserNarrowWidthIframeFilterTest() = default;
  ~SupervisedUserNarrowWidthIframeFilterTest() override = default;

  void SetUp() override;
};

void SupervisedUserNarrowWidthIframeFilterTest::SetUp() {
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      ::switches::kHostWindowBounds, "0+0-400x800");
  SupervisedUserIframeFilterTest::SetUp();
}

INSTANTIATE_TEST_SUITE_P(
    LocalWebApprovalsEnabledNarrowWidth,
    SupervisedUserNarrowWidthIframeFilterTest,
    supervised_user::testing::LocalWebApprovalsTestCase::OnlySupported(),
    [](const testing::TestParamInfo<
        supervised_user::testing::LocalWebApprovalsTestCase>& info) {
      return base::StrCat({"WithLocalWebApprovalsTestCase",
                           static_cast<std::string>(info.param)});
    });

IN_PROC_BROWSER_TEST_P(SupervisedUserNarrowWidthIframeFilterTest,
                       NarrowWidthWindow) {
  BlockHost(kExampleHost);

  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  auto blocked_frames = GetBlockedFrames();
  EXPECT_EQ(blocked_frames.size(), 1u);

  // Expect that remote approvals button is shown.
  EXPECT_TRUE(IsRemoteApprovalsButtonBeingShown(blocked_frames[0]));
  // Expect that the local approvals button is shown if the flag is enabled.
  EXPECT_EQ(IsLocalWebApprovalsEnabled(),
            IsLocalApprovalsButtonBeingShown(blocked_frames[0]));
  // Expect that the "Details" link is shown.
  EXPECT_TRUE(IsDetailsLinkBeingShown(blocked_frames[0]));

  // Delay approval/denial by parent.
  permission_creator()->SetPermissionResult(true);
  permission_creator()->DelayHandlingForNextRequests();

  // Request permission.
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frames[0]);

  // Navigate to another allowed url.
  GURL allowed_url = embedded_test_server()->GetURL(
      kExampleHost2, "/supervised_user/with_iframes.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), allowed_url));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  // Navigate back to the blocked url.
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  // Error page is being shown, but "Ask Permission" button is not being shown.
  EXPECT_FALSE(IsRemoteApprovalsButtonBeingShown(blocked_frames[0]));
  // Expect that the local approvals instead button is shown on the page if the
  // flag is enabled.
  EXPECT_EQ(IsLocalWebApprovalsEnabled(),
            IsLocalApprovalsInsteadButtonBeingShown(blocked_frames[0]));
  // "Details" link is not shown.
  EXPECT_FALSE(IsDetailsLinkBeingShown(blocked_frames[0]));

  content::WebContents* active_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  SupervisedUserNavigationObserver* navigation_observer =
      SupervisedUserNavigationObserver::FromWebContents(active_contents);
  ASSERT_NE(navigation_observer, nullptr);

  EXPECT_TRUE(base::Contains(navigation_observer->requested_hosts_for_test(),
                             kExampleHost));

  NavigationFinishedWaiter waiter(
      active_contents,
      active_contents->GetPrimaryMainFrame()->GetFrameTreeNodeId(),
      blocked_url);
  permission_creator()->HandleDelayedRequests();
  waiter.Wait();

  EXPECT_FALSE(base::Contains(navigation_observer->requested_hosts_for_test(),
                              kExampleHost));

  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));
}

// Tests Chrome OS local web approvals flow.
using ChromeOSLocalWebApprovalsTest = SupervisedUserIframeFilterTest;

// Only test for the local web approvals feature enabled.
INSTANTIATE_TEST_SUITE_P(
    ,
    ChromeOSLocalWebApprovalsTest,
    supervised_user::testing::LocalWebApprovalsTestCase::OnlySupported(),
    [](const testing::TestParamInfo<
        supervised_user::testing::LocalWebApprovalsTestCase>& info) {
      return base::StrCat({"WithLocalWebApprovalsTestCase",
                           static_cast<std::string>(info.param)});
    });

IN_PROC_BROWSER_TEST_P(ChromeOSLocalWebApprovalsTest,
                       StartLocalWebApprovalsFromMainFrame) {
  base::HistogramTester histogram_tester;
  BlockHost(kExampleHost);

  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  const std::vector<content::FrameTreeNodeId> blocked_frames =
      GetBlockedFrames();
  ASSERT_EQ(blocked_frames.size(), 1u);
  const content::FrameTreeNodeId blocked_frame = blocked_frames[0];
  EXPECT_TRUE(IsLocalApprovalsButtonBeingShown(blocked_frame));
  EXPECT_TRUE(IsRemoteApprovalsButtonBeingShown(blocked_frame));
  CheckPreferredApprovalButton(blocked_frame);

  // Trigger local approval flow - native dialog should appear.
  SendCommandToFrame(kLocalUrlAccessCommand, blocked_frame);
  EXPECT_TRUE(ash::ParentAccessDialog::GetInstance());

  // Close the flow without approval - interstitial should be still shown.
  ui::test::EventGenerator generator(ash::Shell::Get()->GetPrimaryRootWindow());
  generator.PressKey(ui::VKEY_ESCAPE, ui::EF_NONE);

  EXPECT_FALSE(ash::ParentAccessDialog::GetInstance());
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));
  EXPECT_TRUE(IsLocalApprovalsButtonBeingShown(blocked_frame));
  EXPECT_TRUE(IsRemoteApprovalsButtonBeingShown(blocked_frame));
  CheckPreferredApprovalButton(blocked_frame);

  histogram_tester.ExpectUniqueSample(
      supervised_user::SupervisedUserInterstitial::
          kInterstitialCommandHistogramName,
      supervised_user::SupervisedUserInterstitial::Commands::
          LOCAL_ACCESS_REQUEST,
      1);
  histogram_tester.ExpectUniqueSample(
      supervised_user::SupervisedUserInterstitial::
          kInterstitialPermissionSourceHistogramName,
      supervised_user::SupervisedUserInterstitial::RequestPermissionSource::
          MAIN_FRAME,
      1);
}

IN_PROC_BROWSER_TEST_P(ChromeOSLocalWebApprovalsTest,
                       StartLocalWebApprovalsFromIframe) {
  base::HistogramTester histogram_tester;
  BlockHost(kIframeHost1);

  const GURL allowed_url_with_iframes = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/with_iframes.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(
      ui_test_utils::NavigateToURL(browser(), allowed_url_with_iframes));
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));

  const std::vector<content::FrameTreeNodeId> blocked_frames =
      GetBlockedFrames();
  ASSERT_EQ(blocked_frames.size(), 1u);
  const content::FrameTreeNodeId blocked_frame = blocked_frames[0];
  EXPECT_TRUE(IsInterstitialBeingShownInFrame(blocked_frame));
  EXPECT_TRUE(IsLocalApprovalsButtonBeingShown(blocked_frame));
  EXPECT_TRUE(IsRemoteApprovalsButtonBeingShown(blocked_frame));
  CheckPreferredApprovalButton(blocked_frame);

  // Trigger local approval flow - native dialog should appear.
  SendCommandToFrame(kLocalUrlAccessCommand, blocked_frame);
  EXPECT_TRUE(ash::ParentAccessDialog::GetInstance());

  // Close the flow without approval - interstitial should be still shown.
  ui::test::EventGenerator generator(ash::Shell::Get()->GetPrimaryRootWindow());
  generator.PressKey(ui::VKEY_ESCAPE, ui::EF_NONE);

  EXPECT_FALSE(ash::ParentAccessDialog::GetInstance());
  EXPECT_FALSE(IsInterstitialBeingShownInMainFrame(browser()));
  EXPECT_TRUE(IsInterstitialBeingShownInFrame(blocked_frame));
  EXPECT_TRUE(IsLocalApprovalsButtonBeingShown(blocked_frame));
  EXPECT_TRUE(IsRemoteApprovalsButtonBeingShown(blocked_frame));
  CheckPreferredApprovalButton(blocked_frame);

  histogram_tester.ExpectUniqueSample(
      supervised_user::SupervisedUserInterstitial::
          kInterstitialCommandHistogramName,
      supervised_user::SupervisedUserInterstitial::Commands::
          LOCAL_ACCESS_REQUEST,
      1);
  histogram_tester.ExpectUniqueSample(
      supervised_user::SupervisedUserInterstitial::
          kInterstitialPermissionSourceHistogramName,
      supervised_user::SupervisedUserInterstitial::RequestPermissionSource::
          SUB_FRAME,
      1);
}

IN_PROC_BROWSER_TEST_P(ChromeOSLocalWebApprovalsTest,
                       UpdateUIAfterRemoteRequestSent) {
  BlockHost(kExampleHost);

  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));
  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));

  const std::vector<content::FrameTreeNodeId> blocked_frames =
      GetBlockedFrames();
  ASSERT_EQ(blocked_frames.size(), 1u);
  const content::FrameTreeNodeId blocked_frame = blocked_frames[0];
  EXPECT_TRUE(IsLocalApprovalsButtonBeingShown(blocked_frame));
  EXPECT_TRUE(IsRemoteApprovalsButtonBeingShown(blocked_frame));

  // Trigger remote approval flow - ui should change.
  SendCommandToFrame(kRemoteUrlAccessCommand, blocked_frame);

  EXPECT_TRUE(IsInterstitialBeingShownInMainFrame(browser()));
  EXPECT_FALSE(IsLocalApprovalsButtonBeingShown(blocked_frame));
  EXPECT_FALSE(IsRemoteApprovalsButtonBeingShown(blocked_frame));
  EXPECT_TRUE(IsLocalApprovalsInsteadButtonBeingShown(blocked_frame));
}
#endif  // BUILDFLAG(IS_CHROMEOS)

class SupervisedUserNavigationThrottleOnlyEnabledForSupervisedUsers
    : public SupervisedUserNavigationThrottleTestBase,
      public testing::WithParamInterface<
          supervised_user::SupervisionMixin::SignInMode> {
 protected:
  static supervised_user::SupervisionMixin::SignInMode GetSignInMode() {
    return GetParam();
  }
  SupervisedUserNavigationThrottleOnlyEnabledForSupervisedUsers()
      : SupervisedUserNavigationThrottleTestBase(GetSignInMode()) {}
  ~SupervisedUserNavigationThrottleOnlyEnabledForSupervisedUsers() override =
      default;
};

INSTANTIATE_TEST_SUITE_P(
    ,
    SupervisedUserNavigationThrottleOnlyEnabledForSupervisedUsers,

    testing::Values(supervised_user::SupervisionMixin::SignInMode::kRegular,
                    supervised_user::SupervisionMixin::SignInMode::kSupervised),
    [](const testing::TestParamInfo<
        supervised_user::SupervisionMixin::SignInMode>& info) {
      return base::StrCat({"WithSignInMode", SignInModeAsString(info.param)});
    });

IN_PROC_BROWSER_TEST_P(
    SupervisedUserNavigationThrottleOnlyEnabledForSupervisedUsers,
    CheckAgainstBlocklist) {
  BlockHost(kExampleHost2);

  // Classify url is never called - if ever, a static blocklist should be used.
  EXPECT_CALL(kids_management_api_mock().classify_url_mock(),
              ClassifyUrl(::testing::_))
      .Times(0);

  GURL blocked_url = embedded_test_server()->GetURL(
      kExampleHost2, "/supervised_user/simple.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), blocked_url));

  // Only supervised users should experience the interstitial
  EXPECT_EQ(IsInterstitialBeingShownInMainFrame(browser()),
            GetSignInMode() ==
                supervised_user::SupervisionMixin::SignInMode::kSupervised);
}

IN_PROC_BROWSER_TEST_P(
    SupervisedUserNavigationThrottleOnlyEnabledForSupervisedUsers,
    CheckAgainstClassifyUrlRPC) {
  kids_management_api_mock().RestrictSubsequentClassifyUrl();
  GURL url = embedded_test_server()->GetURL(kExampleHost2,
                                            "/supervised_user/simple.html");

  // Only supervised users should call the backend
  if (GetSignInMode() ==
      supervised_user::SupervisionMixin::SignInMode::kSupervised) {
    EXPECT_CALL(kids_management_api_mock().classify_url_mock(),
                ClassifyUrl(supervised_user::Classifies(url)))
        .Times(1);
  } else {
    EXPECT_CALL(kids_management_api_mock().classify_url_mock(),
                ClassifyUrl(::testing::_))
        .Times(0);
  }

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  // Only supervised users should experience the
  // interstitial
  EXPECT_EQ(IsInterstitialBeingShownInMainFrame(browser()),
            GetSignInMode() ==
                supervised_user::SupervisionMixin::SignInMode::kSupervised);
}

IN_PROC_BROWSER_TEST_P(
    SupervisedUserNavigationThrottleOnlyEnabledForSupervisedUsers,
    CheckSameDocumentNavigationAgainstClassifyUrlRPC) {
  kids_management_api_mock().RestrictSubsequentClassifyUrl();
  GURL url = embedded_test_server()->GetURL(kExampleHost2,
                                            "/supervised_user/simple.html");

  // Only supervised users should call the backend
  if (GetSignInMode() ==
      supervised_user::SupervisionMixin::SignInMode::kSupervised) {
    EXPECT_CALL(kids_management_api_mock().classify_url_mock(),
                ClassifyUrl(supervised_user::Classifies(url)))
        .Times(1);
  } else {
    EXPECT_CALL(kids_management_api_mock().classify_url_mock(),
                ClassifyUrl(::testing::_))
        .Times(0);
  }

  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

  // Only supervised users should experience the
  // interstitial
  EXPECT_EQ(IsInterstitialBeingShownInMainFrame(browser()),
            GetSignInMode() ==
                supervised_user::SupervisionMixin::SignInMode::kSupervised);

  // Simulate a same document navigation by navigating to #test.
  GURL::Replacements replace_ref;
  replace_ref.SetRefStr("test");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(),
                                           url.ReplaceComponents(replace_ref)));

  // Only supervised users should experience the
  // interstitial
  EXPECT_EQ(IsInterstitialBeingShownInMainFrame(browser()),
            GetSignInMode() ==
                supervised_user::SupervisionMixin::SignInMode::kSupervised);
}

class SupervisedUserNavigationThrottleFencedFramesTest
    : public SupervisedUserNavigationThrottleTestBase {
 public:
  SupervisedUserNavigationThrottleFencedFramesTest()
      : SupervisedUserNavigationThrottleTestBase(
            supervised_user::SupervisionMixin::SignInMode::kSupervised) {}
  ~SupervisedUserNavigationThrottleFencedFramesTest() override = default;
  SupervisedUserNavigationThrottleFencedFramesTest(
      const SupervisedUserNavigationThrottleFencedFramesTest&) = delete;

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

  content::test::FencedFrameTestHelper& fenced_frame_test_helper() {
    return fenced_frame_helper_;
  }

 private:
  content::test::FencedFrameTestHelper fenced_frame_helper_;
};

IN_PROC_BROWSER_TEST_F(SupervisedUserNavigationThrottleFencedFramesTest,
                       BlockFencedFrame) {
  BlockHost(kIframeHost2);
  const GURL kInitialUrl = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/simple.html");

  kids_management_api_mock().AllowSubsequentClassifyUrl();
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), kInitialUrl));

  // Same origin fenced frame is not blocked, and therefore must be allowed.
  const GURL kSameOriginFencedFrameUrl = embedded_test_server()->GetURL(
      kExampleHost, "/supervised_user/fenced_frame.html");
  content::RenderFrameHost* rfh_same_origin =
      fenced_frame_test_helper().CreateFencedFrame(
          web_contents()->GetPrimaryMainFrame(), kSameOriginFencedFrameUrl);
  EXPECT_TRUE(rfh_same_origin);

  // Host1 is not blocked, and therefore must be allowed.
  const GURL kHost1FencedFrameUrl = embedded_test_server()->GetURL(
      kIframeHost1, "/supervised_user/fenced_frame.html");
  content::RenderFrameHost* rfh_host1 =
      fenced_frame_test_helper().CreateFencedFrame(
          web_contents()->GetPrimaryMainFrame(), kHost1FencedFrameUrl);
  EXPECT_TRUE(rfh_host1);

  // Host2 is blocked, and therefore should result in a interstitial being
  // shown, which is validated by the expectation of net::Error::ERR_FAILED.
  const GURL kHost2FencedFrameUrl = embedded_test_server()->GetURL(
      kIframeHost2, "/supervised_user/fenced_frame.html");
  content::RenderFrameHost* rfh_host2 =
      fenced_frame_test_helper().CreateFencedFrame(
          web_contents()->GetPrimaryMainFrame(), kHost2FencedFrameUrl,
          net::Error::ERR_FAILED);
  EXPECT_TRUE(rfh_host2);
}

}  // namespace