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
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
content / browser / renderer_host / render_frame_host_impl_unittest.cc [blame]
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/render_frame_host_impl.h"
#include <memory>
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "build/buildflag.h"
#include "components/input/timeout_monitor.h"
#include "content/browser/renderer_host/navigation_controller_impl.h"
#include "content/common/content_navigation_policy.h"
#include "content/common/features.h"
#include "content/public/browser/cors_origin_pattern_setter.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/content_features.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/fake_local_frame.h"
#include "content/public/test/test_utils.h"
#include "content/test/navigation_simulator_impl.h"
#include "content/test/test_render_frame_host.h"
#include "content/test/test_render_view_host.h"
#include "content/test/test_web_contents.h"
#include "net/base/features.h"
#include "net/base/isolation_info.h"
#include "net/cookies/site_for_cookies.h"
#include "services/network/public/cpp/cors/origin_access_list.h"
#include "services/network/public/mojom/cors.mojom.h"
#include "services/network/public/mojom/cors_origin_pattern.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_context.h"
#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_read_context.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/mojom/favicon/favicon_url.mojom.h"
#include "third_party/blink/public/mojom/webauthn/authenticator.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
#include "url/url_util.h"
namespace content {
namespace {
void AddHostPermissions(const std::string& host, RenderFrameHost* rfh) {
std::vector<network::mojom::CorsOriginPatternPtr> patterns;
base::RunLoop run_loop;
patterns.push_back(network::mojom::CorsOriginPattern::New(
"https", host, 0, network::mojom::CorsDomainMatchMode::kAllowSubdomains,
network::mojom::CorsPortMatchMode::kAllowAnyPort,
network::mojom::CorsOriginAccessMatchPriority::kDefaultPriority));
CorsOriginPatternSetter::Set(rfh->GetBrowserContext(),
rfh->GetLastCommittedOrigin(),
std::move(patterns), {}, run_loop.QuitClosure());
run_loop.Run();
}
} // namespace
class RenderFrameHostImplTest : public RenderViewHostImplTestHarness {
public:
void SetUp() override {
RenderViewHostImplTestHarness::SetUp();
contents()->GetPrimaryMainFrame()->InitializeRenderFrameIfNeeded();
}
};
// TODO(crbug.com/40260854): This set-up is temporary. Eventually, all
// tests that reference extensions will be moved to chrome/browser/ and this
// class can be deleted.
class FirstPartyOverrideContentBrowserClient : public ContentBrowserClient {
public:
FirstPartyOverrideContentBrowserClient() = default;
~FirstPartyOverrideContentBrowserClient() override = default;
private:
bool ShouldUseFirstPartyStorageKey(const url::Origin& origin) override {
return origin.scheme() == "chrome-extension";
}
};
// A test class that forces kOriginKeyedProcessesByDefault off for tests that
// require that same-site cross-origin navigations don't trigger a RFH swap.
class RenderFrameHostImplTest_NoOriginKeyedProcessesByDefault
: public RenderFrameHostImplTest {
public:
RenderFrameHostImplTest_NoOriginKeyedProcessesByDefault() {
feature_list_.InitAndDisableFeature(
features::kOriginKeyedProcessesByDefault);
}
private:
base::test::ScopedFeatureList feature_list_;
};
// Note: Since this test is predicate on not having a RFH swap for a
// cross-origin, same-site navigation, it only makes sense to run it with
// kOriginKeyedProcessesByDefault disabled.
TEST_F(RenderFrameHostImplTest_NoOriginKeyedProcessesByDefault,
ExpectedMainWorldOrigin) {
GURL initial_url = GURL("https://initial.example.test/");
GURL final_url = GURL("https://final.example.test/");
auto get_expected_main_world_origin = [](RenderFrameHost* rfh) {
NavigationRequest* in_flight_request =
static_cast<RenderFrameHostImpl*>(rfh)
->FindLatestNavigationRequestThatIsStillCommitting();
return in_flight_request ? in_flight_request->GetOriginToCommit()
: rfh->GetLastCommittedOrigin();
};
// Start the test with a simple navigation.
{
std::unique_ptr<NavigationSimulator> simulator =
NavigationSimulator::CreateRendererInitiated(initial_url, main_rfh());
simulator->Start();
simulator->Commit();
}
RenderFrameHostImpl* initial_rfh = main_test_rfh();
// This test is for a bug that only happens when there is no RFH swap on
// same-site navigations, so we should disable same-site proactive
// BrowsingInstance for |initial_rfh| before continiung.
DisableProactiveBrowsingInstanceSwapFor(initial_rfh);
if (ShouldCreateNewHostForAllFrames()) {
GTEST_SKIP();
}
// Verify expected main world origin in a steady state - after a commit it
// should be the same as the last committed origin.
EXPECT_EQ(url::Origin::Create(initial_url),
get_expected_main_world_origin(main_rfh()));
EXPECT_EQ(url::Origin::Create(initial_url),
main_rfh()->GetLastCommittedOrigin());
EXPECT_EQ(
blink::StorageKey::CreateFirstParty(url::Origin::Create(initial_url)),
main_test_rfh()->GetStorageKey());
// Verify expected main world origin when a pending navigation was started but
// hasn't yet reached the ready-to-commit state.
std::unique_ptr<NavigationSimulator> simulator2 =
NavigationSimulator::CreateRendererInitiated(final_url, main_rfh());
simulator2->Start();
EXPECT_EQ(url::Origin::Create(initial_url),
get_expected_main_world_origin(main_rfh()));
// Verify expected main world origin when a pending navigation has reached the
// ready-to-commit state. Note that the last committed origin shouldn't
// change yet at this point.
simulator2->ReadyToCommit();
simulator2->Wait();
EXPECT_EQ(url::Origin::Create(final_url),
get_expected_main_world_origin(main_rfh()));
EXPECT_EQ(url::Origin::Create(initial_url),
main_rfh()->GetLastCommittedOrigin());
EXPECT_EQ(
blink::StorageKey::CreateFirstParty(url::Origin::Create(initial_url)),
main_test_rfh()->GetStorageKey());
// Verify expected main world origin once we are again in a steady state -
// after a commit.
simulator2->Commit();
EXPECT_EQ(url::Origin::Create(final_url),
get_expected_main_world_origin(main_rfh()));
EXPECT_EQ(url::Origin::Create(final_url),
main_rfh()->GetLastCommittedOrigin());
EXPECT_EQ(blink::StorageKey::CreateFirstParty(url::Origin::Create(final_url)),
main_test_rfh()->GetStorageKey());
// As a test correctness check, verify that there was no RFH swap (the bug
// this test protects against would only happen if there is no swap). In
// fact, FindLatestNavigationRequestThatIsStillCommitting might possibly be
// removed entirely once we swap on all document changes.
EXPECT_EQ(initial_rfh, main_rfh());
}
// Test that navigating to an invalid URL (which creates an empty GURL) causes
// about:blank to commit.
TEST_F(RenderFrameHostImplTest, InvalidURL) {
// Start from a valid commit.
NavigateAndCommit(GURL("https://test.example.com"));
// Attempt to navigate to a non-empty invalid URL, which GURL treats as an
// empty invalid URL. Blink treats navigations to an empty URL as navigations
// to about:blank.
GURL invalid_url("invalidurl");
EXPECT_TRUE(invalid_url.is_empty());
EXPECT_FALSE(invalid_url.is_valid());
NavigateAndCommit(invalid_url);
EXPECT_EQ(GURL(url::kAboutBlankURL), main_rfh()->GetLastCommittedURL());
}
// Ensures that IsolationInfo's SiteForCookies is empty and
// that it correctly generates a StorageKey with a kCrossSite
// AncestorChainBit when frames are nested in an A->B->A
// configuration.
TEST_F(RenderFrameHostImplTest, CrossSiteAncestorInFrameTree) {
// Enable 3p partitioning to accurately test AncestorChainBit.
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(
net::features::kThirdPartyStoragePartitioning);
// Load site A into the main frame.
GURL parent_url = GURL("https://parent.example.test/");
NavigationSimulator::CreateRendererInitiated(parent_url, main_rfh())
->Commit();
// Create a child RenderFrameHost and navigate it to site B to establish A->B.
auto* child_rfh_1 = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child:a->b"));
GURL child_url_1 = GURL("https://child.example.com");
child_rfh_1 = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(child_url_1,
child_rfh_1));
// Create a child RenderFrameHost in the existing child RenderFrameHost and
// navigate it to site A to establish A->B->A.
auto* child_rfh_2 = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(child_rfh_1)
->AppendChild("child:a->b->a"));
child_rfh_2 = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(parent_url,
child_rfh_2));
// Constructing expected values.
url::Origin expected_final_origin = url::Origin::Create(parent_url);
blink::StorageKey expected_final_storage_key = blink::StorageKey::Create(
expected_final_origin, net::SchemefulSite(expected_final_origin),
blink::mojom::AncestorChainBit::kCrossSite);
net::IsolationInfo expected_final_isolation_info = net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kOther, expected_final_origin,
expected_final_origin, net::SiteForCookies());
EXPECT_EQ(expected_final_origin, child_rfh_2->GetLastCommittedOrigin());
EXPECT_EQ(expected_final_storage_key, child_rfh_2->GetStorageKey());
EXPECT_TRUE(expected_final_isolation_info.IsEqualForTesting(
child_rfh_2->GetIsolationInfoForSubresources()));
EXPECT_EQ(expected_final_isolation_info.network_isolation_key(),
child_rfh_2->GetNetworkIsolationKey());
EXPECT_TRUE(expected_final_isolation_info.site_for_cookies().IsEquivalent(
child_rfh_2->ComputeSiteForCookies()));
EXPECT_TRUE(expected_final_isolation_info.IsEqualForTesting(
child_rfh_2->GetPendingIsolationInfoForSubresources()));
}
// Test the IsolationInfo and related fields of a request during the various
// phases of a commit, when a RenderFrameHost is reused. Once RenderDocument
// ships, this test may no longer be needed.
// Note: Since this test is predicate on not having a RFH swap for a
// cross-origin, same-site navigation, it only makes sense to run it with
// kOriginKeyedProcessesByDefault disabled.
TEST_F(RenderFrameHostImplTest_NoOriginKeyedProcessesByDefault,
IsolationInfoDuringCommit) {
GURL initial_url = GURL("https://initial.example.test/");
url::Origin expected_initial_origin = url::Origin::Create(initial_url);
const blink::StorageKey expected_initial_storage_key =
blink::StorageKey::CreateFirstParty(expected_initial_origin);
net::IsolationInfo expected_initial_isolation_info =
net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kOther, expected_initial_origin,
expected_initial_origin,
net::SiteForCookies::FromOrigin(expected_initial_origin));
GURL final_url = GURL("https://final.example.test/");
url::Origin expected_final_origin = url::Origin::Create(final_url);
const blink::StorageKey expected_final_storage_key =
blink::StorageKey::CreateFirstParty(expected_final_origin);
net::IsolationInfo expected_final_isolation_info = net::IsolationInfo::Create(
net::IsolationInfo::RequestType::kOther, expected_final_origin,
expected_final_origin,
net::SiteForCookies::FromOrigin(expected_final_origin));
// Start the test with a simple navigation.
{
std::unique_ptr<NavigationSimulator> simulator =
NavigationSimulator::CreateRendererInitiated(initial_url, main_rfh());
simulator->Start();
simulator->Commit();
}
// This test is targetted at the case an RFH is reused between navigations.
RenderFrameHost* initial_rfh = main_rfh();
DisableProactiveBrowsingInstanceSwapFor(main_rfh());
if (ShouldCreateNewHostForAllFrames()) {
GTEST_SKIP();
}
// Check values for the initial commit.
EXPECT_EQ(expected_initial_origin, main_rfh()->GetLastCommittedOrigin());
EXPECT_EQ(expected_initial_storage_key, main_test_rfh()->GetStorageKey());
EXPECT_TRUE(expected_initial_isolation_info.IsEqualForTesting(
main_rfh()->GetIsolationInfoForSubresources()));
EXPECT_EQ(expected_initial_isolation_info.network_isolation_key(),
main_rfh()->GetNetworkIsolationKey());
EXPECT_TRUE(expected_initial_isolation_info.site_for_cookies().IsEquivalent(
static_cast<RenderFrameHostImpl*>(main_rfh())->ComputeSiteForCookies()));
EXPECT_TRUE(expected_initial_isolation_info.IsEqualForTesting(
main_rfh()->GetPendingIsolationInfoForSubresources()));
// Values should be the same when a pending navigation was started but
// hasn't yet reached the ready-to-commit state.
std::unique_ptr<NavigationSimulator> simulator2 =
NavigationSimulator::CreateRendererInitiated(final_url, main_rfh());
simulator2->Start();
EXPECT_EQ(expected_initial_origin, main_rfh()->GetLastCommittedOrigin());
EXPECT_EQ(expected_initial_storage_key, main_test_rfh()->GetStorageKey());
EXPECT_TRUE(expected_initial_isolation_info.IsEqualForTesting(
main_rfh()->GetIsolationInfoForSubresources()));
EXPECT_EQ(expected_initial_isolation_info.network_isolation_key(),
main_rfh()->GetNetworkIsolationKey());
EXPECT_TRUE(expected_initial_isolation_info.site_for_cookies().IsEquivalent(
static_cast<RenderFrameHostImpl*>(main_rfh())->ComputeSiteForCookies()));
EXPECT_TRUE(expected_initial_isolation_info.IsEqualForTesting(
main_rfh()->GetPendingIsolationInfoForSubresources()));
// Only the GetPendingIsolationInfoForSubresources() should change when a
// pending navigation has reached the ready-to-commit state.
simulator2->ReadyToCommit();
simulator2->Wait();
EXPECT_EQ(expected_initial_origin, main_rfh()->GetLastCommittedOrigin());
EXPECT_EQ(expected_initial_storage_key, main_test_rfh()->GetStorageKey());
EXPECT_TRUE(expected_initial_isolation_info.IsEqualForTesting(
main_rfh()->GetIsolationInfoForSubresources()));
EXPECT_EQ(expected_initial_isolation_info.network_isolation_key(),
main_rfh()->GetNetworkIsolationKey());
EXPECT_TRUE(expected_initial_isolation_info.site_for_cookies().IsEquivalent(
static_cast<RenderFrameHostImpl*>(main_rfh())->ComputeSiteForCookies()));
EXPECT_TRUE(expected_final_isolation_info.IsEqualForTesting(
main_rfh()->GetPendingIsolationInfoForSubresources()));
// Verify expected main world origin once we are again in a steady state -
// after a commit.
simulator2->Commit();
EXPECT_EQ(expected_final_origin, main_rfh()->GetLastCommittedOrigin());
EXPECT_EQ(expected_final_storage_key, main_test_rfh()->GetStorageKey());
EXPECT_TRUE(expected_final_isolation_info.IsEqualForTesting(
main_rfh()->GetIsolationInfoForSubresources()));
EXPECT_EQ(expected_final_isolation_info.network_isolation_key(),
main_rfh()->GetNetworkIsolationKey());
EXPECT_TRUE(expected_final_isolation_info.site_for_cookies().IsEquivalent(
static_cast<RenderFrameHostImpl*>(main_rfh())->ComputeSiteForCookies()));
EXPECT_TRUE(expected_final_isolation_info.IsEqualForTesting(
main_rfh()->GetPendingIsolationInfoForSubresources()));
// As a test correctness check, verify that there was no RFH swap. When
// there's always an RFH swap, this test will likely no longer be useful.
EXPECT_EQ(initial_rfh, main_rfh());
}
TEST_F(RenderFrameHostImplTest, PolicyContainerLifecycle) {
TestRenderFrameHost* main_rfh = contents()->GetPrimaryMainFrame();
ASSERT_NE(main_rfh->policy_container_host(), nullptr);
EXPECT_EQ(main_rfh->policy_container_host()->referrer_policy(),
network::mojom::ReferrerPolicy::kDefault);
static_cast<blink::mojom::PolicyContainerHost*>(
main_rfh->policy_container_host())
->SetReferrerPolicy(network::mojom::ReferrerPolicy::kAlways);
EXPECT_EQ(main_rfh->policy_container_host()->referrer_policy(),
network::mojom::ReferrerPolicy::kAlways);
// Create a child frame and check that it inherits the PolicyContainerHost
// from the parent frame.
auto* child_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child"));
ASSERT_NE(child_frame->policy_container_host(), nullptr);
EXPECT_EQ(child_frame->policy_container_host()->referrer_policy(),
network::mojom::ReferrerPolicy::kAlways);
// Create a new WebContents with opener and test that the new main frame
// inherits the PolicyContainerHost from the opener.
static_cast<blink::mojom::PolicyContainerHost*>(
child_frame->policy_container_host())
->SetReferrerPolicy(network::mojom::ReferrerPolicy::kNever);
WebContents::CreateParams params(browser_context());
std::unique_ptr<WebContentsImpl> new_contents(
WebContentsImpl::CreateWithOpener(params, child_frame));
RenderFrameHostImpl* new_frame =
new_contents->GetPrimaryFrameTree().root()->current_frame_host();
ASSERT_NE(new_frame->policy_container_host(), nullptr);
EXPECT_EQ(new_frame->policy_container_host()->referrer_policy(),
network::mojom::ReferrerPolicy::kNever);
}
TEST_F(RenderFrameHostImplTest, FaviconURLsSet) {
TestRenderFrameHost* main_rfh = contents()->GetPrimaryMainFrame();
const auto kFavicon = blink::mojom::FaviconURL(
GURL("https://example.com/favicon.ico"),
blink::mojom::FaviconIconType::kFavicon, {}, /*is_default_icon=*/false);
std::unique_ptr<NavigationSimulator> navigation =
NavigationSimulator::CreateBrowserInitiated(GURL("https://example.com"),
contents());
ui::PageTransition transition = ui::PAGE_TRANSITION_LINK;
navigation->SetTransition(transition);
navigation->Commit();
EXPECT_EQ(0u, contents()->GetFaviconURLs().size());
std::vector<blink::mojom::FaviconURLPtr> one_favicon_url;
one_favicon_url.push_back(blink::mojom::FaviconURL::New(kFavicon));
main_rfh->UpdateFaviconURL(std::move(one_favicon_url));
EXPECT_EQ(1u, contents()->GetFaviconURLs().size());
std::vector<blink::mojom::FaviconURLPtr> two_favicon_urls;
two_favicon_urls.push_back(blink::mojom::FaviconURL::New(kFavicon));
two_favicon_urls.push_back(blink::mojom::FaviconURL::New(kFavicon));
main_rfh->UpdateFaviconURL(std::move(two_favicon_urls));
EXPECT_EQ(2u, contents()->GetFaviconURLs().size());
std::vector<blink::mojom::FaviconURLPtr> another_one_favicon_url;
another_one_favicon_url.push_back(blink::mojom::FaviconURL::New(kFavicon));
main_rfh->UpdateFaviconURL(std::move(another_one_favicon_url));
EXPECT_EQ(1u, contents()->GetFaviconURLs().size());
}
TEST_F(RenderFrameHostImplTest, FaviconURLsResetWithNavigation) {
TestRenderFrameHost* main_rfh = contents()->GetPrimaryMainFrame();
std::vector<blink::mojom::FaviconURLPtr> favicon_urls;
favicon_urls.push_back(blink::mojom::FaviconURL::New(
GURL("https://example.com/favicon.ico"),
blink::mojom::FaviconIconType::kFavicon, std::vector<gfx::Size>(),
/*is_default_icon=*/false));
std::unique_ptr<NavigationSimulator> navigation =
NavigationSimulator::CreateBrowserInitiated(GURL("https://example.com"),
contents());
ui::PageTransition transition = ui::PAGE_TRANSITION_LINK;
navigation->SetTransition(transition);
navigation->Commit();
EXPECT_EQ(0u, contents()->GetFaviconURLs().size());
main_rfh->UpdateFaviconURL(std::move(favicon_urls));
EXPECT_EQ(1u, contents()->GetFaviconURLs().size());
navigation = NavigationSimulator::CreateBrowserInitiated(
GURL("https://example.com/navigation.html"), contents());
navigation->SetTransition(transition);
navigation->Commit();
EXPECT_EQ(0u, contents()->GetFaviconURLs().size());
}
TEST_F(RenderFrameHostImplTest, ChildOfCredentiallessIsCredentialless) {
EXPECT_FALSE(main_test_rfh()->IsCredentialless());
auto* child_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child"));
EXPECT_FALSE(child_frame->IsCredentialless());
EXPECT_FALSE(child_frame->GetStorageKey().nonce().has_value());
auto attributes = blink::mojom::IframeAttributes::New();
attributes->parsed_csp_attribute = std::move(
child_frame->frame_tree_node()->attributes_->parsed_csp_attribute);
attributes->id = child_frame->frame_tree_node()->html_id();
attributes->name = child_frame->frame_tree_node()->html_name();
attributes->src = child_frame->frame_tree_node()->html_src();
attributes->credentialless = true;
child_frame->frame_tree_node()->SetAttributes(std::move(attributes));
EXPECT_FALSE(child_frame->IsCredentialless());
EXPECT_FALSE(child_frame->GetStorageKey().nonce().has_value());
// A navigation in the credentialless iframe commits a credentialless RFH.
std::unique_ptr<NavigationSimulator> navigation =
NavigationSimulator::CreateRendererInitiated(
GURL("https://example.com/navigation.html"), child_frame);
navigation->Commit();
child_frame =
static_cast<TestRenderFrameHost*>(navigation->GetFinalRenderFrameHost());
EXPECT_TRUE(child_frame->IsCredentialless());
EXPECT_TRUE(child_frame->GetStorageKey().nonce().has_value());
// A credentialless document sets a nonce on its network isolation key.
EXPECT_TRUE(child_frame->GetNetworkIsolationKey().GetNonce().has_value());
EXPECT_EQ(main_test_rfh()->GetPage().credentialless_iframes_nonce(),
child_frame->GetNetworkIsolationKey().GetNonce().value());
// A child of a credentialless RFH is credentialless.
auto* grandchild_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(child_frame)
->AppendChild("grandchild"));
EXPECT_TRUE(grandchild_frame->IsCredentialless());
EXPECT_TRUE(grandchild_frame->GetStorageKey().nonce().has_value());
// The two credentialless RFH's storage keys should have the same nonce.
EXPECT_EQ(child_frame->GetStorageKey().nonce().value(),
grandchild_frame->GetStorageKey().nonce().value());
// Also the credentialless initial empty document sets a nonce on its network
// isolation key.
EXPECT_TRUE(
grandchild_frame->GetNetworkIsolationKey().GetNonce().has_value());
EXPECT_EQ(main_test_rfh()->GetPage().credentialless_iframes_nonce(),
grandchild_frame->GetNetworkIsolationKey().GetNonce().value());
}
// FakeLocalFrame implementation that records calls to BeforeUnload().
class FakeLocalFrameWithBeforeUnload : public content::FakeLocalFrame {
public:
explicit FakeLocalFrameWithBeforeUnload(TestRenderFrameHost* test_host) {
Init(test_host->GetRemoteAssociatedInterfaces());
}
bool was_before_unload_called() const { return was_before_unload_called_; }
void RunBeforeUnloadCallback() {
ASSERT_TRUE(before_unload_callback_);
std::move(before_unload_callback_)
.Run(true, base::TimeTicks::Now(), base::TimeTicks::Now());
}
// FakeLocalFrame:
void BeforeUnload(bool is_reload, BeforeUnloadCallback callback) override {
was_before_unload_called_ = true;
before_unload_callback_ = std::move(callback);
}
private:
bool was_before_unload_called_ = false;
BeforeUnloadCallback before_unload_callback_;
};
// Verifies BeforeUnload() is not sent to renderer if there is no before
// unload handler present.
TEST_F(RenderFrameHostImplTest, BeforeUnloadNotSentToRenderer) {
FakeLocalFrameWithBeforeUnload local_frame(contents()->GetPrimaryMainFrame());
auto simulator = NavigationSimulatorImpl::CreateBrowserInitiated(
GURL("https://example.com/simple.html"), contents());
simulator->set_block_invoking_before_unload_completed_callback(true);
simulator->Start();
EXPECT_TRUE(contents()
->GetPrimaryMainFrame()
->is_waiting_for_beforeunload_completion());
EXPECT_FALSE(local_frame.was_before_unload_called());
// This is necessary to trigger FakeLocalFrameWithBeforeUnload to be bound.
contents()->GetPrimaryMainFrame()->FlushLocalFrameMessages();
// This runs a MessageLoop, which also results in the PostTask() scheduled
// completing.
local_frame.FlushMessages();
EXPECT_FALSE(local_frame.was_before_unload_called());
// Because of the nested message loops run by the previous calls, the task
// that RenderFrameHostImpl will have also completed.
EXPECT_FALSE(contents()
->GetPrimaryMainFrame()
->is_waiting_for_beforeunload_completion());
}
class LoadingStateChangedDelegate : public WebContentsDelegate {
public:
void LoadingStateChanged(WebContents* source,
bool should_show_loading_ui) final {
should_show_loading_ui_ = should_show_loading_ui;
}
bool should_show_loading_ui() { return should_show_loading_ui_; }
private:
bool should_show_loading_ui_ = false;
};
TEST_F(RenderFrameHostImplTest, NavigationApiInterceptShowLoadingUi) {
// Initial commit.
const GURL url1("http://foo");
NavigationSimulator::NavigateAndCommitFromDocument(url1, main_test_rfh());
std::unique_ptr<LoadingStateChangedDelegate> delegate =
std::make_unique<LoadingStateChangedDelegate>();
contents()->SetDelegate(delegate.get());
ASSERT_FALSE(delegate->should_show_loading_ui());
ASSERT_FALSE(contents()->IsLoading());
ASSERT_FALSE(contents()->ShouldShowLoadingUI());
// Emulate navigateEvent.intercept().
const GURL url2("http://foo#a");
auto params = mojom::DidCommitProvisionalLoadParams::New();
params->did_create_new_entry = false;
params->url = url2;
params->origin = url::Origin::Create(url2);
params->referrer = blink::mojom::Referrer::New();
params->transition = ui::PAGE_TRANSITION_LINK;
params->should_update_history = true;
params->method = "GET";
params->page_state = blink::PageState::CreateFromURL(url2);
params->post_id = -1;
main_test_rfh()->SendDidCommitSameDocumentNavigation(
std::move(params),
blink::mojom::SameDocumentNavigationType::kNavigationApiIntercept,
/*should_replace_current_entry=*/false);
EXPECT_FALSE(delegate->should_show_loading_ui());
EXPECT_TRUE(contents()->IsLoading());
EXPECT_FALSE(contents()->ShouldShowLoadingUI());
// After a delay, the NavigationApi sends a message to start the loading UI.
// This delay is to prevent jitters due to short same-document navigations.
main_test_rfh()->SendStartLoadingForAsyncNavigationApiCommit();
// Once the delay has elapsed, navigateEvent.intercept() should leave
// WebContents in the loading state and showing loading UI, unlike other
// same-document navigations.
EXPECT_TRUE(delegate->should_show_loading_ui());
EXPECT_TRUE(contents()->IsLoading());
EXPECT_TRUE(contents()->ShouldShowLoadingUI());
}
TEST_F(RenderFrameHostImplTest, NavigationApiInterceptBrowserInitiated) {
// Initial commit.
const GURL url1("http://foo");
NavigationSimulator::NavigateAndCommitFromDocument(url1, main_test_rfh());
std::unique_ptr<LoadingStateChangedDelegate> delegate =
std::make_unique<LoadingStateChangedDelegate>();
contents()->SetDelegate(delegate.get());
ASSERT_FALSE(delegate->should_show_loading_ui());
ASSERT_FALSE(contents()->IsLoading());
ASSERT_FALSE(contents()->ShouldShowLoadingUI());
// Emulate navigateEvent.intercept().
const GURL url2("http://foo#a");
std::unique_ptr<NavigationSimulator> navigation =
NavigationSimulator::CreateBrowserInitiated(url2, contents());
navigation->Start();
ASSERT_TRUE(contents()->IsLoading());
ASSERT_FALSE(contents()->ShouldShowLoadingUI());
auto params = mojom::DidCommitProvisionalLoadParams::New();
params->did_create_new_entry = false;
params->url = url2;
params->origin = url::Origin::Create(url2);
params->referrer = blink::mojom::Referrer::New();
params->transition = ui::PAGE_TRANSITION_LINK;
params->should_update_history = true;
params->method = "GET";
params->page_state = blink::PageState::CreateFromURL(url2);
params->post_id = -1;
main_test_rfh()->SendDidCommitSameDocumentNavigation(
std::move(params),
blink::mojom::SameDocumentNavigationType::kNavigationApiIntercept, true);
EXPECT_FALSE(delegate->should_show_loading_ui());
EXPECT_TRUE(contents()->IsLoading());
EXPECT_FALSE(contents()->ShouldShowLoadingUI());
// After a delay, the NavigationApi sends a message to start the loading UI.
// This delay is to prevent jitters due to short same-document navigations.
main_test_rfh()->SendStartLoadingForAsyncNavigationApiCommit();
// Once the delay has elapsed, navigateEvent.intercept() should leave
// WebContents in the loading state and showing loading UI, unlike other
// same-document navigations.
EXPECT_TRUE(delegate->should_show_loading_ui());
EXPECT_TRUE(contents()->IsLoading());
EXPECT_TRUE(contents()->ShouldShowLoadingUI());
}
// TODO(crbug.com/40260854): This test should be migrated to //chrome.
TEST_F(RenderFrameHostImplTest, CalculateStorageKey) {
// Register extension scheme for testing.
url::ScopedSchemeRegistryForTests scoped_registry;
url::AddStandardScheme("chrome-extension", url::SCHEME_WITH_HOST);
GURL initial_url_ext = GURL("chrome-extension://initial.example.test/");
NavigationSimulator::CreateRendererInitiated(initial_url_ext, main_rfh())
->Commit();
// Create a child frame and navigate to `child_url`.
auto* child_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child"));
GURL child_url = GURL("https://childframe.com");
child_frame = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(child_url,
child_frame));
// Create a grandchild frame and navigate to `grandchild_url`.
auto* grandchild_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(child_frame)
->AppendChild("grandchild"));
GURL grandchild_url = GURL("https://grandchildframe.com/");
grandchild_frame = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(grandchild_url,
grandchild_frame));
// With no host permissions the grandchild document should have a cross-site
// storage key with the `initial_url_ext` as it's top level origin.
blink::StorageKey expected_grandchild_no_permissions_storage_key =
blink::StorageKey::Create(
grandchild_frame->GetLastCommittedOrigin(),
net::SchemefulSite(url::Origin::Create(initial_url_ext)),
blink::mojom::AncestorChainBit::kCrossSite);
EXPECT_EQ(expected_grandchild_no_permissions_storage_key,
grandchild_frame->CalculateStorageKey(
grandchild_frame->GetLastCommittedOrigin(), nullptr));
// Give extension host permissions to `grandchild_frame`. Since
// `grandchild_frame` is not the root non-extension frame
// `CalculateStorageKey` should still create a storage key that has the
// extension as the `top_level_site`.
AddHostPermissions("grandchildframe.com", main_rfh());
EXPECT_EQ(expected_grandchild_no_permissions_storage_key,
grandchild_frame->CalculateStorageKey(
grandchild_frame->GetLastCommittedOrigin(), nullptr));
// Now give extension host permissions to `child_frame`. Since the root
// extension rfh has host permissions to`child_frame` calling
// `CalculateStorageKey` should create a storage key with the `child_origin`
// as the `top_level_site`.
AddHostPermissions("childframe.com", main_rfh());
// Child host should now have a storage key that is same site and uses the
// `child_origin` as the `top_level_site`.
blink::StorageKey expected_child_with_permissions_storage_key =
blink::StorageKey::Create(
child_frame->GetLastCommittedOrigin(),
net::SchemefulSite(child_frame->GetLastCommittedOrigin()),
blink::mojom::AncestorChainBit::kSameSite);
EXPECT_EQ(expected_child_with_permissions_storage_key,
child_frame->CalculateStorageKey(
child_frame->GetLastCommittedOrigin(), nullptr));
blink::StorageKey expected_grandchild_with_permissions_storage_key =
blink::StorageKey::Create(
grandchild_frame->GetLastCommittedOrigin(),
net::SchemefulSite(child_frame->GetLastCommittedOrigin()),
blink::mojom::AncestorChainBit::kCrossSite);
EXPECT_EQ(expected_grandchild_with_permissions_storage_key,
grandchild_frame->CalculateStorageKey(
grandchild_frame->GetLastCommittedOrigin(), nullptr));
}
// TODO(crbug.com/41483148): Flaky on Linux.
#if BUILDFLAG(IS_LINUX)
#define MAYBE_CalculateStorageKeyFirstPartyOverride \
DISABLED_CalculateStorageKeyFirstPartyOverride
#else
#define MAYBE_CalculateStorageKeyFirstPartyOverride \
CalculateStorageKeyFirstPartyOverride
#endif
// TODO(crbug.com/40260854): Eventually, this test will be moved to
// chrome/browser/ so that we no longer need to override the
// ContentBrowserClient, and we can test using real extension URLs.
TEST_F(RenderFrameHostImplTest, MAYBE_CalculateStorageKeyFirstPartyOverride) {
// Enable third-party storage partitioning.
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(
net::features::kThirdPartyStoragePartitioning);
// Temporarily enable FirstPartyOverrideContentBrowserClient. This allows us
// to mock ShouldUseFirstPartyStorageKey() to check the origin scheme (as done
// in the ChromeContentBrowserClient) rather than indiscriminately return
// false (as written in the ContentBrowserClient implementation).
FirstPartyOverrideContentBrowserClient modified_client;
ContentBrowserClient* regular_client =
SetBrowserClientForTesting(&modified_client);
// Register extension scheme for testing.
url::ScopedSchemeRegistryForTests scoped_registry;
url::AddStandardScheme("chrome-extension", url::SCHEME_WITH_HOST);
// Navigate and commit to a non-extension URL.
GURL initial_url("https://initial.example.test");
NavigationSimulator::CreateRendererInitiated(initial_url, main_rfh())
->Commit();
// Create a child extension frame and navigate to it.
auto* child_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child"));
// TODO(crbug.com/40260854): once this test is moved to chrome/browser/
// replace with a legitimate chrome-extension URL. But for the purposes of
// this test, it is sufficient to check that it has a chrome-extension scheme.
GURL child_url = GURL("chrome-extension://childframeid");
child_frame = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(child_url,
child_frame));
// Subframes that contain extension URLs should have first-party StorageKeys.
EXPECT_EQ(child_frame->GetLastCommittedOrigin().GetURL(), child_url);
blink::StorageKey expected_storage_key = blink::StorageKey::CreateFirstParty(
child_frame->GetLastCommittedOrigin());
EXPECT_EQ(expected_storage_key,
child_frame->CalculateStorageKey(
child_frame->GetLastCommittedOrigin(), /*nonce=*/nullptr));
SetBrowserClientForTesting(regular_client);
}
TEST_F(RenderFrameHostImplTest,
CalculateStorageKeyWhenPassedOriginIsNotCurrentFrame) {
// Register extension scheme for testing.
url::ScopedSchemeRegistryForTests scoped_registry;
url::AddStandardScheme("chrome-extension", url::SCHEME_WITH_HOST);
GURL initial_url_ext = GURL("chrome-extension://initial.example.test/");
NavigationSimulator::CreateRendererInitiated(initial_url_ext, main_rfh())
->Commit();
// Create a child frame and navigate to `child_url`.
auto* child_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child"));
GURL child_url = GURL("https://childframe.com");
child_frame = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(child_url,
child_frame));
// Give extension host permissions to `child_url`.
AddHostPermissions("childframe.com", main_rfh());
// The top level document has host permssions to the child_url so the top
// level document should be excluded from storage key calculations and a first
// party, same-site storage key is expected.
blink::StorageKey expected_child_with_permissions_storage_key =
blink::StorageKey::Create(
child_frame->GetLastCommittedOrigin(),
net::SchemefulSite(child_frame->GetLastCommittedOrigin()),
blink::mojom::AncestorChainBit::kSameSite);
EXPECT_EQ(expected_child_with_permissions_storage_key,
child_frame->CalculateStorageKey(
child_frame->GetLastCommittedOrigin(), nullptr));
// CalculateStorageKey is called with an origin that the top level document
// does not have host permissions to. A cross-site storage key is expected and
// the top level document's site should be used in the storage key
// calculation.
GURL no_host_permissions_url = GURL("https://noHostPermissions.com/");
blink::StorageKey expected_storage_key_no_permissions =
blink::StorageKey::Create(
url::Origin::Create(no_host_permissions_url),
net::SchemefulSite(url::Origin::Create(initial_url_ext)),
blink::mojom::AncestorChainBit::kCrossSite);
EXPECT_EQ(expected_storage_key_no_permissions,
child_frame->CalculateStorageKey(
url::Origin::Create(no_host_permissions_url), nullptr));
}
// Test that the correct StorageKey is calculated when a RFH takes its document
// properties from a navigation.
// TODO(crbug.com/40092527): Once we are able to compute the origin to
// commit in the browser, `navigation_request->commit_params().storage_key`
// will contain the correct origin and it won't be necessary to override it
// with `param.origin` anymore. Meaning this test may be removed because we
// already check that the NavigationRequest calculates the correct key.
TEST_F(RenderFrameHostImplTest,
CalculateStorageKeyTakeNewDocumentPropertiesFromNavigation) {
base::test::ScopedFeatureList scoped_feature_list;
// Because the StorageKey's (and Storage Partitioning's) usage of
// RuntimeFeatureState is only meant to disable partitioning (i.e.:
// first-party only), we need the make sure the net::features is always
// enabled.
scoped_feature_list.InitAndEnableFeature(
net::features::kThirdPartyStoragePartitioning);
// This lamdba performs the navigation and disables Storage Partitioning for
// the navigation if `disable_sp` is true. It returns the new
// TestRenderFrameHost* to the navigated frame.
auto NavigateFrame = [](NavigationSimulator* navigation,
bool disable_sp = false) -> TestRenderFrameHost* {
navigation->Start();
if (disable_sp) {
NavigationRequest* request =
NavigationRequest::From(navigation->GetNavigationHandle());
// Disable Storage Partitioning by enabling the deprecation trial.
request->GetMutableRuntimeFeatureStateContext()
.SetDisableThirdPartyStoragePartitioning2Enabled(true);
}
navigation->Commit();
return static_cast<TestRenderFrameHost*>(
navigation->GetFinalRenderFrameHost());
};
// Throughout the test we'll be creating a frame tree with a main frame, a
// child frame, and a grandchild frame.
GURL main_url("https://main.com");
GURL b_url("https://b.com");
GURL c_url("https://c.com");
url::Origin main_origin = url::Origin::Create(main_url);
url::Origin b_origin = url::Origin::Create(b_url);
url::Origin c_origin = url::Origin::Create(c_url);
// Begin by testing with Storage Partitioning enabled.
auto main_navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(main_url, contents());
// By definition the main frame's StorageKey will always be first party
blink::StorageKey main_frame_key =
blink::StorageKey::CreateFirstParty(main_origin);
NavigateFrame(main_navigation.get());
EXPECT_EQ(main_frame_key, main_test_rfh()->GetStorageKey());
TestRenderFrameHost* child_frame = static_cast<TestRenderFrameHost*>(
RenderFrameHostTester::For(main_rfh())->AppendChild("child"));
auto child_navigation =
NavigationSimulatorImpl::CreateRendererInitiated(b_url, child_frame);
// The child and grandchild should both be third-party keys.
blink::StorageKey child_frame_key =
blink::StorageKey::Create(b_origin, net::SchemefulSite(main_origin),
blink::mojom::AncestorChainBit::kCrossSite);
child_frame = NavigateFrame(child_navigation.get());
EXPECT_EQ(child_frame_key, child_frame->GetStorageKey());
TestRenderFrameHost* grandchild_frame =
child_frame->AppendChild("grandchild");
auto grandchild_navigation =
NavigationSimulatorImpl::CreateRendererInitiated(c_url, grandchild_frame);
blink::StorageKey grandchild_frame_key =
blink::StorageKey::Create(c_origin, net::SchemefulSite(main_origin),
blink::mojom::AncestorChainBit::kCrossSite);
grandchild_frame = NavigateFrame(grandchild_navigation.get());
EXPECT_EQ(grandchild_frame_key, grandchild_frame->GetStorageKey());
// Only the RuntimeFeatureStateContext in the main frame's matters. So
// disabling Storage Partitioning in the child_frame shouldn't affect the
// child's or the grandchild's StorageKey.
child_navigation =
NavigationSimulatorImpl::CreateRendererInitiated(b_url, child_frame);
child_frame = NavigateFrame(child_navigation.get(),
/*disable_sp=*/true);
EXPECT_EQ(child_frame_key, child_frame->GetStorageKey());
grandchild_frame = child_frame->AppendChild("grandchild");
grandchild_navigation =
NavigationSimulatorImpl::CreateRendererInitiated(c_url, grandchild_frame);
grandchild_frame = NavigateFrame(grandchild_navigation.get());
EXPECT_EQ(grandchild_frame_key, grandchild_frame->GetStorageKey());
// Disabling Storage Partitioning on the main frame should cause the child's
// and grandchild's StorageKey to be first-party.
main_navigation =
NavigationSimulatorImpl::CreateBrowserInitiated(main_url, contents());
NavigateFrame(main_navigation.get(),
/*disable_sp=*/true);
child_frame = static_cast<TestRenderFrameHost*>(
RenderFrameHostTester::For(main_rfh())->AppendChild("child"));
child_navigation =
NavigationSimulatorImpl::CreateRendererInitiated(b_url, child_frame);
// The child and grandchild should both be first-party keys.
blink::StorageKey child_frame_key_1p =
blink::StorageKey::CreateFirstParty(b_origin);
child_frame = NavigateFrame(child_navigation.get());
EXPECT_EQ(child_frame_key_1p, child_frame->GetStorageKey());
grandchild_frame = child_frame->AppendChild("grandchild");
blink::StorageKey grandchild_frame_key_1p =
blink::StorageKey::CreateFirstParty(c_origin);
grandchild_navigation =
NavigationSimulatorImpl::CreateRendererInitiated(c_url, grandchild_frame);
grandchild_frame = NavigateFrame(grandchild_navigation.get());
EXPECT_EQ(grandchild_frame_key_1p, grandchild_frame->GetStorageKey());
}
// Tests that the StorageKey calculated for a frame under an extension main
// frame has storage partitioning enabled/disabled as expected via the
// RuntimeFeatureStateReadContext when the extension has host permissions.
// TODO(crbug.com/40260854): This test should be migrated to //chrome.
TEST_F(RenderFrameHostImplTest,
CalculateStorageKeyStoragePartitioningCorrectFrameWithExtension) {
base::test::ScopedFeatureList scoped_feature_list;
// Because the StorageKey's (and Storage Partitioning's) usage of
// RuntimeFeatureState is only meant to disable partitioning (i.e.:
// first-party only), we need the make sure the net::features is always
// enabled.
scoped_feature_list.InitAndEnableFeature(
net::features::kThirdPartyStoragePartitioning);
// Register extension scheme for testing.
url::ScopedSchemeRegistryForTests scoped_registry;
url::AddStandardScheme("chrome-extension", url::SCHEME_WITH_HOST);
GURL initial_url_ext = GURL("chrome-extension://initial.example.test/");
NavigationSimulator::CreateRendererInitiated(initial_url_ext, main_rfh())
->Commit();
// Create a child frame, disable Storage Partitioning, and navigate to
// `child_url`.
auto* child_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child"));
GURL child_url = GURL("https://childframe.com");
auto child_navigation =
NavigationSimulatorImpl::CreateRendererInitiated(child_url, child_frame);
// This lamdba performs the navigation and disables Storage Partitioning for
// the navigation if `disable_sp` is true. It returns the new
// TestRenderFrameHost* to the navigated frame.
auto NavigateFrame = [](NavigationSimulator* navigation,
bool disable_sp = false) -> TestRenderFrameHost* {
navigation->Start();
if (disable_sp) {
NavigationRequest* request =
NavigationRequest::From(navigation->GetNavigationHandle());
request->GetMutableRuntimeFeatureStateContext()
.SetDisableThirdPartyStoragePartitioning2Enabled(true);
}
navigation->Commit();
return static_cast<TestRenderFrameHost*>(
navigation->GetFinalRenderFrameHost());
};
child_frame = NavigateFrame(child_navigation.get(), /*disable_sp=*/true);
// Create a grandchild frame and navigate to `grandchild_url`.
auto* grandchild_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(child_frame)
->AppendChild("grandchild"));
GURL grandchild_url = GURL("https://grandchildframe.com/");
grandchild_frame = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(grandchild_url,
grandchild_frame));
// At this point the extension doesn't have host permissions for the
// child_frame, so the child_frame's RuntimeFeatureStateReadContext's state
// isn't used and therefore any StorageKeys created for the grandchild_frame
// will be third-party.
url::Origin grandchild_origin = url::Origin::Create(grandchild_url);
blink::StorageKey grandchild_frame_key = blink::StorageKey::Create(
grandchild_origin, net::SchemefulSite(initial_url_ext),
blink::mojom::AncestorChainBit::kCrossSite);
EXPECT_EQ(grandchild_frame_key,
grandchild_frame->CalculateStorageKey(
grandchild_frame->GetLastCommittedOrigin(), nullptr));
// Now give extension host permissions to `child_frame`. Since the root
// extension rfh has host permissions to`child_frame` calling
// `CalculateStorageKey` should use the RuntimeFeatureStateReadContext in
// child_frame thereby creating a first-party StorageKey in grandchild_frame
// (since we disabled storage partitioning).
AddHostPermissions("childframe.com", main_rfh());
blink::StorageKey grandchild_frame_key_1P =
blink::StorageKey::CreateFirstParty(grandchild_origin);
EXPECT_EQ(grandchild_frame_key_1P,
grandchild_frame->CalculateStorageKey(
grandchild_frame->GetLastCommittedOrigin(), nullptr));
}
// Test that CalculateStorageKey creates a first-party or third-party key
// depending on state of Storage Partitioning the main frame's
// RuntimeFeatureStateReadContext for a new unnavigated frame.
TEST_F(RenderFrameHostImplTest, CalculateStorageKeyOfUnnavigatedFrame) {
base::test::ScopedFeatureList scoped_feature_list;
// Because Storage partitioning's usage of RuntimeFeatureState is only meant
// to disable (i.e.: 1p only) partitioning, we need the make sure the feature
// is on first.
scoped_feature_list.InitAndEnableFeature(
net::features::kThirdPartyStoragePartitioning);
// This test will create a main frame that has Storage Partitioning disabled
// via its RuntimeFeatureStateReadContext. It will have a navigated child
// frame's whose RFSRC will be the default (i.e.: Storage Partitioning
// enabled) and that child will then spawn an unnavigated grandchild whose
// StorageKey should still depend upon the main frame's RFSRC.
GURL url = GURL("https://a.com");
GURL child_url = GURL("https://b.com");
// Start by giving the main frame a SP disabled
// RuntimeFeatureStateReadContext.
auto navigation =
NavigationSimulator::CreateRendererInitiated(url, main_rfh());
navigation->Start();
NavigationRequest* request =
NavigationRequest::From(navigation->GetNavigationHandle());
// Disable Storage Partitioning by enabling the deprecation trial.
request->GetMutableRuntimeFeatureStateContext()
.SetDisableThirdPartyStoragePartitioning2Enabled(true);
navigation->Commit();
EXPECT_TRUE(RuntimeFeatureStateDocumentData::GetForCurrentDocument(main_rfh())
->runtime_feature_state_read_context()
.IsDisableThirdPartyStoragePartitioning2Enabled());
// Create a child frame and navigate to `child_url`.
auto* child_frame = main_test_rfh()->AppendChild("child");
auto child_navigation =
NavigationSimulator::CreateRendererInitiated(child_url, child_frame);
child_navigation->Commit();
child_frame = static_cast<TestRenderFrameHost*>(
child_navigation->GetFinalRenderFrameHost());
// Create a grand child and check it's StorageKey.
auto* grandchild_frame = child_frame->AppendChild("grandchild");
// Since Storage Partitioning is disabled, the key should be first party.
blink::StorageKey grandchild_frame_key_1p =
blink::StorageKey::CreateFirstParty(url::Origin::Create(child_url));
EXPECT_EQ(grandchild_frame_key_1p, grandchild_frame->GetStorageKey());
// Now perform the same test, except the main frame also gets a default
// RuntimeFeatureStateReadContext. (I.e.: Storage Partitioning enabled).
NavigationSimulator::NavigateAndCommitFromDocument(url, main_rfh());
child_frame = main_test_rfh()->AppendChild("child");
child_navigation =
NavigationSimulator::CreateRendererInitiated(child_url, child_frame);
child_navigation->Commit();
child_frame = static_cast<TestRenderFrameHost*>(
child_navigation->GetFinalRenderFrameHost());
grandchild_frame = child_frame->AppendChild("grandchild");
blink::StorageKey grandchild_frame_key =
blink::StorageKey::Create(url::Origin::Create(child_url),
net::SchemefulSite(url::Origin::Create(url)),
blink::mojom::AncestorChainBit::kCrossSite);
EXPECT_EQ(grandchild_frame_key, grandchild_frame->GetStorageKey());
}
TEST_F(RenderFrameHostImplTest,
NewFrameInheritsRuntimeFeatureStateReadContext) {
GURL url = GURL("https://a.com");
GURL child_url = GURL("https://b.com");
// Start by giving the main frame a non-default
// RuntimeFeatureStateReadContext.
auto navigation =
NavigationSimulator::CreateRendererInitiated(url, main_rfh());
navigation->Start();
NavigationRequest* request =
NavigationRequest::From(navigation->GetNavigationHandle());
request->GetMutableRuntimeFeatureStateContext().SetTestFeatureEnabled(true);
navigation->Commit();
EXPECT_TRUE(RuntimeFeatureStateDocumentData::GetForCurrentDocument(main_rfh())
->runtime_feature_state_read_context()
.IsTestFeatureEnabled());
// Now add a child and check its RFSRC.
auto* child_frame = main_test_rfh()->AppendChild("child");
EXPECT_TRUE(
RuntimeFeatureStateDocumentData::GetForCurrentDocument(child_frame)
->runtime_feature_state_read_context()
.IsTestFeatureEnabled());
// Navigating the child away should change the RFSRC.
auto child_navigation =
NavigationSimulator::CreateRendererInitiated(child_url, child_frame);
child_navigation->Commit();
child_frame = static_cast<TestRenderFrameHost*>(
child_navigation->GetFinalRenderFrameHost());
EXPECT_FALSE(
RuntimeFeatureStateDocumentData::GetForCurrentDocument(child_frame)
->runtime_feature_state_read_context()
.IsTestFeatureEnabled());
}
#if BUILDFLAG(IS_ANDROID)
class TestWebAuthnContentBrowserClientImpl : public ContentBrowserClient {
public:
MOCK_METHOD(bool,
IsSecurityLevelAcceptableForWebAuthn,
(RenderFrameHost*, const url::Origin& origin),
());
};
class RenderFrameHostImplWebAuthnTest : public RenderFrameHostImplTest {
public:
void SetUp() override {
RenderFrameHostImplTest::SetUp();
old_browser_client_ = SetBrowserClientForTesting(browser_client_.get());
contents()->GetController().LoadURLWithParams(
NavigationController::LoadURLParams(
GURL("https://example.com/navigation.html")));
}
void TearDown() override {
RenderFrameHostImplTest::TearDown();
SetBrowserClientForTesting(old_browser_client_);
}
protected:
raw_ptr<ContentBrowserClient> old_browser_client_;
std::unique_ptr<TestWebAuthnContentBrowserClientImpl> browser_client_ =
std::make_unique<TestWebAuthnContentBrowserClientImpl>();
};
TEST_F(RenderFrameHostImplWebAuthnTest,
PerformGetAssertionWebAuthSecurityChecks_TLSError) {
GURL url("https://doofenshmirtz.evil");
const auto origin = url::Origin::Create(url);
EXPECT_CALL(*browser_client_,
IsSecurityLevelAcceptableForWebAuthn(main_test_rfh(), origin))
.WillOnce(testing::Return(false));
std::optional<blink::mojom::AuthenticatorStatus> status;
main_test_rfh()->PerformGetAssertionWebAuthSecurityChecks(
"doofenshmirtz.evil", url::Origin::Create(url),
/*is_payment_credential_get_assertion=*/false,
base::BindLambdaForTesting(
[&status](blink::mojom::AuthenticatorStatus s, bool is_cross_origin) {
status = s;
}));
EXPECT_EQ(status.value(),
blink::mojom::AuthenticatorStatus::CERTIFICATE_ERROR);
}
TEST_F(RenderFrameHostImplWebAuthnTest,
PerformMakeCredentialWebAuthSecurityChecks_TLSError) {
GURL url("https://doofenshmirtz.evil");
const auto origin = url::Origin::Create(url);
EXPECT_CALL(*browser_client_,
IsSecurityLevelAcceptableForWebAuthn(main_test_rfh(), origin))
.WillOnce(testing::Return(false));
std::optional<blink::mojom::AuthenticatorStatus> status;
main_test_rfh()->PerformMakeCredentialWebAuthSecurityChecks(
"doofenshmirtz.evil", url::Origin::Create(url),
/*is_payment_credential_creation=*/false,
base::BindLambdaForTesting(
[&status](blink::mojom::AuthenticatorStatus s, bool is_cross_origin) {
status = s;
}));
EXPECT_EQ(status.value(),
blink::mojom::AuthenticatorStatus::CERTIFICATE_ERROR);
}
TEST_F(RenderFrameHostImplWebAuthnTest,
PerformGetAssertionWebAuthSecurityChecks_Success) {
GURL url("https://owca.org");
const auto origin = url::Origin::Create(url);
EXPECT_CALL(*browser_client_,
IsSecurityLevelAcceptableForWebAuthn(main_test_rfh(), origin))
.WillOnce(testing::Return(true));
std::optional<blink::mojom::AuthenticatorStatus> status;
main_test_rfh()->PerformGetAssertionWebAuthSecurityChecks(
"owca.org", url::Origin::Create(url),
/*is_payment_credential_get_assertion=*/false,
base::BindLambdaForTesting(
[&status](blink::mojom::AuthenticatorStatus s, bool is_cross_origin) {
status = s;
}));
EXPECT_EQ(status.value(), blink::mojom::AuthenticatorStatus::SUCCESS);
}
TEST_F(RenderFrameHostImplWebAuthnTest,
PerformMakeCredentialWebAuthSecurityChecks_Success) {
GURL url("https://owca.org");
const auto origin = url::Origin::Create(url);
EXPECT_CALL(*browser_client_,
IsSecurityLevelAcceptableForWebAuthn(main_test_rfh(), origin))
.WillOnce(testing::Return(true));
std::optional<blink::mojom::AuthenticatorStatus> status;
main_test_rfh()->PerformMakeCredentialWebAuthSecurityChecks(
"owca.org", url::Origin::Create(url),
/*is_payment_credential_creation=*/false,
base::BindLambdaForTesting(
[&status](blink::mojom::AuthenticatorStatus s, bool is_cross_origin) {
status = s;
}));
EXPECT_EQ(status.value(), blink::mojom::AuthenticatorStatus::SUCCESS);
}
#endif // BUILDFLAG(IS_ANDROID)
class RenderFrameHostImplThirdPartyStorageTest
: public RenderViewHostImplTestHarness,
public testing::WithParamInterface<bool> {
public:
void SetUp() override {
RenderViewHostImplTestHarness::SetUp();
contents()->GetPrimaryMainFrame()->InitializeRenderFrameIfNeeded();
if (ThirdPartyStoragePartitioningEnabled()) {
scoped_feature_list_.InitAndEnableFeature(
net::features::kThirdPartyStoragePartitioning);
} else {
scoped_feature_list_.InitAndDisableFeature(
net::features::kThirdPartyStoragePartitioning);
}
}
bool ThirdPartyStoragePartitioningEnabled() { return GetParam(); }
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
INSTANTIATE_TEST_SUITE_P(
All,
RenderFrameHostImplThirdPartyStorageTest,
/*third_party_storage_partitioning_enabled*/ testing::Bool());
TEST_P(RenderFrameHostImplThirdPartyStorageTest,
ChildFramePartitionedByThirdPartyStorageKey) {
GURL initial_url = GURL("https://initial.example.test/");
NavigationSimulator::CreateRendererInitiated(initial_url, main_rfh())
->Commit();
// Create a child frame and check that it has the correct storage key.
auto* child_frame = static_cast<TestRenderFrameHost*>(
content::RenderFrameHostTester::For(main_test_rfh())
->AppendChild("child"));
GURL child_url = GURL("https://exampleChildSite.com");
child_frame = static_cast<TestRenderFrameHost*>(
NavigationSimulator::NavigateAndCommitFromDocument(child_url,
child_frame));
// Top level storage key should not change if third party partitioning is on
// or off
EXPECT_EQ(
blink::StorageKey::CreateFirstParty(url::Origin::Create(initial_url)),
main_test_rfh()->GetStorageKey());
if (ThirdPartyStoragePartitioningEnabled()) {
// child frame storage key should contain child_origin + top_level_origin if
// third party partitioning is on.
EXPECT_EQ(blink::StorageKey::Create(
url::Origin::Create(child_url),
net::SchemefulSite(url::Origin::Create(initial_url)),
blink::mojom::AncestorChainBit::kCrossSite),
child_frame->GetStorageKey());
} else {
// child frame storage key should only be partitioned by child origin if
// third party partitioning is off.
EXPECT_EQ(
blink::StorageKey::CreateFirstParty(url::Origin::Create(child_url)),
child_frame->GetStorageKey());
}
}
namespace {
class MockWebContentsDelegate : public WebContentsDelegate {
public:
MOCK_METHOD(void, CloseContents, (WebContents*));
MOCK_METHOD(void,
OnTextCopiedToClipboard,
(RenderFrameHost*, std::u16string));
};
} // namespace
// Ensure that a close request from the renderer process is ignored if a
// navigation causes a different RenderFrameHost to commit first. See
// https://crbug.com/1406023.
TEST_F(RenderFrameHostImplTest,
RendererInitiatedCloseIsCancelledIfPageIsntPrimary) {
MockWebContentsDelegate delegate;
contents()->SetDelegate(&delegate);
RenderFrameHostImpl* rfh = main_test_rfh();
EXPECT_CALL(delegate, CloseContents(contents())).Times(0);
// Have the renderer request to close the page.
rfh->ClosePage(RenderFrameHostImpl::ClosePageSource::kRenderer);
// The close timeout should be running.
EXPECT_TRUE(rfh->close_timeout_ && rfh->close_timeout_->IsRunning());
// Simulate the rfh going into the back-forward cache before the close timeout
// fires.
rfh->lifecycle_state_ =
RenderFrameHostImpl::LifecycleStateImpl::kInBackForwardCache;
// Simulate the close timer firing.
rfh->ClosePageTimeout(RenderFrameHostImpl::ClosePageSource::kRenderer);
// The page should not close since it's no longer the primary page.
testing::Mock::VerifyAndClearExpectations(&delegate);
}
// Ensure that a close request from the browser process cannot be ignored even
// if a navigation causes a different RenderFrameHost to commit first. See
// https://crbug.com/1406023.
TEST_F(RenderFrameHostImplTest,
BrowserInitiatedCloseIsNotCancelledIfPageIsntPrimary) {
MockWebContentsDelegate delegate;
contents()->SetDelegate(&delegate);
RenderFrameHostImpl* rfh = main_test_rfh();
EXPECT_CALL(delegate, CloseContents(contents()));
// Have the browser request to close the page.
rfh->ClosePage(RenderFrameHostImpl::ClosePageSource::kBrowser);
// The close timeout should be running.
EXPECT_TRUE(rfh->close_timeout_ && rfh->close_timeout_->IsRunning());
// Simulate the rfh going into the back-forward cache before the close timeout
// fires.
rfh->lifecycle_state_ =
RenderFrameHostImpl::LifecycleStateImpl::kInBackForwardCache;
// Simulate the close timer firing.
rfh->ClosePageTimeout(RenderFrameHostImpl::ClosePageSource::kBrowser);
// The page should close regardless of it not being primary since the browser
// requested it.
testing::Mock::VerifyAndClearExpectations(&delegate);
}
// A mock WebContentsObserver for listening to text copy events.
class TextCopiedEventObserver : public WebContentsObserver {
public:
explicit TextCopiedEventObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
MOCK_METHOD(void,
OnTextCopiedToClipboard,
(RenderFrameHost*, const std::u16string&),
(override));
};
// Test that the WebContentObserver is notified when text is copied to the
// clipboard for a RenderFrameHost.
TEST_F(RenderFrameHostImplTest, OnTextCopiedToClipboard) {
testing::StrictMock<TextCopiedEventObserver> observer(contents());
std::u16string copied_text = u"copied_text";
RenderFrameHostImpl* rfh = main_test_rfh();
EXPECT_CALL(observer, OnTextCopiedToClipboard(rfh, copied_text));
rfh->OnTextCopiedToClipboard(copied_text);
}
// Test if `LoadedWithCacheControlNoStoreHeader()` behaves
// as expected.
TEST_F(RenderFrameHostImplTest, LoadedWithCacheControlNoStoreHeader) {
TestRenderFrameHost* rfh = main_test_rfh();
// In the default state, `LoadedWithCacheControlNoStoreHeader()`
// will return false.
ASSERT_FALSE(rfh->LoadedWithCacheControlNoStoreHeader());
// Register the `kMainResourceHasCacheControlNoStore` feature and
// `LoadedWithCacheControlNoStoreHeader()` will return true.
rfh->OnBackForwardCacheDisablingStickyFeatureUsed(
blink::scheduler::WebSchedulerTrackedFeature::
kMainResourceHasCacheControlNoStore);
ASSERT_TRUE(rfh->LoadedWithCacheControlNoStoreHeader());
// Simulate a same RFH navigation and the
// `LoadedWithCacheControlNoStoreHeader()` should return false because the
// registered feature is reset.
NavigationSimulator::NavigateAndCommitFromDocument(GURL("http://foo"), rfh);
ASSERT_EQ(main_test_rfh(), rfh);
ASSERT_FALSE(main_test_rfh()->LoadedWithCacheControlNoStoreHeader());
}
class MediaStreamCaptureObserver : public WebContentsObserver {
public:
explicit MediaStreamCaptureObserver(WebContents* web_contents)
: WebContentsObserver(web_contents) {}
MOCK_METHOD(void,
OnFrameIsCapturingMediaStreamChanged,
(RenderFrameHost*, bool),
(override));
};
TEST_F(RenderFrameHostImplTest, CapturedMediaStreamAddedRemoved) {
testing::StrictMock<MediaStreamCaptureObserver> observer(contents());
TestRenderFrameHost* main_rfh = contents()->GetPrimaryMainFrame();
// Calling OnMediaStreamAdded for the first time will cause a notification.
EXPECT_CALL(observer, OnFrameIsCapturingMediaStreamChanged(main_rfh, true));
main_rfh->OnMediaStreamAdded(
RenderFrameHostImpl::MediaStreamType::kCapturingMediaStream);
// Calling it again will not result in a notification (verified by the
// StrictMock).
main_rfh->OnMediaStreamAdded(
RenderFrameHostImpl::MediaStreamType::kCapturingMediaStream);
// Calling OnMediaStreamRemoved to cancel out one of the OnMediaStreamAdded
// calls. Overall, the frame is still capturing at least one media stream so
// there is no notifications.
main_rfh->OnMediaStreamRemoved(
RenderFrameHostImpl::MediaStreamType::kCapturingMediaStream);
// Cancelling the first OnMediaStreamAdded call. This changes the state of the
// frame and thus cause a notification.
EXPECT_CALL(observer, OnFrameIsCapturingMediaStreamChanged(main_rfh, false));
main_rfh->OnMediaStreamRemoved(
RenderFrameHostImpl::MediaStreamType::kCapturingMediaStream);
}
} // namespace content