File: extension_policy_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2639 lines) | stat: -rw-r--r-- 111,113 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
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
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
// Copyright 2019 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 "base/check_deref.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/callback_helpers.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/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/gtest_tags.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/test_future.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/chrome_content_verifier_delegate.h"
#include "chrome/browser/extensions/component_loader.h"
#include "chrome/browser/extensions/corrupted_extension_reinstaller.h"
#include "chrome/browser/extensions/crx_installer.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_management_constants.h"
#include "chrome/browser/extensions/extension_management_test_util.h"
#include "chrome/browser/extensions/forced_extensions/install_stage_tracker.h"
#include "chrome/browser/extensions/install_verifier.h"
#include "chrome/browser/extensions/load_error_waiter.h"
#include "chrome/browser/extensions/shared_module_service.h"
#include "chrome/browser/extensions/unpacked_installer.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/policy/extension_policy_test_base.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/browser/policy/profile_policy_connector_builder.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profile_test_util.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/extensions/extension_test_util.h"
#include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/policy_constants.h"
#include "components/version_info/channel.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_process_host_creation_observer.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/result_codes.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/download_test_observer.h"
#include "content/public/test/no_renderer_crashes_assertion.h"
#include "content/public/test/url_loader_interceptor.h"
#include "extensions/browser/content_verifier/test_utils.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_dialog_auto_confirm.h"
#include "extensions/browser/extension_host.h"
#include "extensions/browser/extension_host_test_helper.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/browser/scoped_ignore_content_verifier_for_test.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/browser/updater/extension_cache_fake.h"
#include "extensions/browser/updater/extension_downloader_test_helper.h"
#include "extensions/common/constants.h"
#include "extensions/common/feature_switch.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest.h"
#include "extensions/common/manifest_handlers/shared_module_info.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "extensions/common/permissions/permissions_data.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "third_party/blink/public/common/switches.h"

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/background/background_contents_service.h"
#include "chrome/browser/extensions/scoped_test_mv2_enabler.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/web_applications/os_integration/os_integration_manager.h"
#include "chrome/browser/web_applications/proto/web_app_install_state.pb.h"
#include "chrome/browser/web_applications/test/web_app_test_observers.h"
#include "chrome/browser/web_applications/test/web_app_test_utils.h"
#include "chrome/browser/web_applications/web_app_install_info.h"
#include "chrome/browser/web_applications/web_app_install_manager.h"
#include "chrome/browser/web_applications/web_app_management_type.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/webapps/browser/installable/installable_metrics.h"
#endif

#if BUILDFLAG(IS_WIN)
#include "base/win/win_util.h"
#endif

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/constants/ash_features.h"
#include "ash/constants/ash_switches.h"
#include "ash/constants/web_app_id_constants.h"
#include "chrome/browser/extensions/updater/local_extension_cache.h"
#endif

using base::test::TestFuture;
using extensions::CorruptedExtensionReinstaller;
using extensions::CrxInstallError;
using extensions::TestExtensionRegistryObserver;
using extensions::mojom::ManifestLocation;
using testing::AtLeast;
using testing::Sequence;

namespace policy {
namespace {

const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
const base::FilePath::CharType kSimpleWithIconCrxName[] =
    FILE_PATH_LITERAL("simple_with_icon.crx");

const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
const char kSimpleWithIconCrxId[] = "dehdlahnlebladnfleagmjdapdjdcnlp";

#if BUILDFLAG(ENABLE_EXTENSIONS)
const base::FilePath::CharType kHostedAppCrxName[] =
    FILE_PATH_LITERAL("hosted_app.crx");
const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
#endif

// Different versions of this extension Id at
// {DIR_TEST_DATA}/extensions/pinning/ are used in extension pinning tests.
const char kPinnedExtensionCrxId[] = "fdlpamochgodkfemfnickdlkabcfmbln";

const char kGoodCrxVersion[] = "1.0.0.1";

const base::FilePath::CharType kGoodV1CrxName[] =
    FILE_PATH_LITERAL("good_v1.crx");
const base::FilePath::CharType kSimpleWithPopupExt[] =
    FILE_PATH_LITERAL("simple_with_popup");
const base::FilePath::CharType kAppUnpackedExt[] = FILE_PATH_LITERAL("app");

// This is to enforce zero initial delay.
constexpr net::BackoffEntry::Policy kDefaultBackOffPolicyForTesting = {
    // Number of initial errors (in sequence) to ignore before applying
    // exponential back-off rules.
    0,

    // Initial delay for exponential back-off in ms.
    0,

    // Factor by which the waiting time will be multiplied.
    2,

    // Fuzzing percentage. ex: 10% will spread requests randomly
    // between 90%-100% of the calculated time.
    0.1,

    // Maximum amount of time we are willing to delay our request in ms.
    600000,  // Ten minutes.

    // Time to keep an entry from being discarded even when it
    // has no significant state, -1 to never discard.
    -1,

    // Don't use initial delay unless the last request was an error.
    false,
};

// Registers a handler to respond to requests whose path matches |match_path|.
// The response contents are generated from |template_file|, by replacing all
// "${URL_PLACEHOLDER}" substrings in the file with the request URL excluding
// filename, query values and fragment.
void RegisterURLReplacingHandler(net::EmbeddedTestServer* test_server,
                                 const std::string& match_path,
                                 const base::FilePath& template_file) {
  test_server->RegisterRequestHandler(base::BindRepeating(
      [](net::EmbeddedTestServer* test_server, const std::string& match_path,
         const base::FilePath& template_file,
         const net::test_server::HttpRequest& request)
          -> std::unique_ptr<net::test_server::HttpResponse> {
        GURL url = test_server->GetURL(request.relative_url);
        if (url.path() != match_path) {
          return nullptr;
        }

        std::string contents;
        CHECK(base::ReadFileToString(template_file, &contents));

        GURL url_base = url.GetWithoutFilename();
        base::ReplaceSubstringsAfterOffset(&contents, 0, "${URL_PLACEHOLDER}",
                                           url_base.spec());

        auto response = std::make_unique<net::test_server::BasicHttpResponse>();
        response->set_content(contents);
        response->set_content_type("text/plain");
        return response;
      },
      base::Unretained(test_server), match_path, template_file));
}

#if BUILDFLAG(ENABLE_EXTENSIONS)
// Sends a mouse click at the given coordinates to the current renderer.
void PerformClick(content::WebContents* contents, int x, int y) {
  blink::WebMouseEvent click_event(
      blink::WebInputEvent::Type::kMouseDown,
      blink::WebInputEvent::kNoModifiers,
      blink::WebInputEvent::GetStaticTimeStampForTests());
  click_event.button = blink::WebMouseEvent::Button::kLeft;
  click_event.click_count = 1;
  click_event.SetPositionInWidget(x, y);
  contents->GetPrimaryMainFrame()
      ->GetRenderViewHost()
      ->GetWidget()
      ->ForwardMouseEvent(click_event);
  click_event.SetType(blink::WebInputEvent::Type::kMouseUp);
  contents->GetPrimaryMainFrame()
      ->GetRenderViewHost()
      ->GetWidget()
      ->ForwardMouseEvent(click_event);
}
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

const extensions::Extension* InstallExtensionWithContext(
    const base::FilePath::StringType& name,
    content::BrowserContext* browser_context) {
  base::FilePath extension_path(GetTestFilePath(
      base::FilePath(kTestExtensionsDir), base::FilePath(name)));

  scoped_refptr<extensions::CrxInstaller> installer =
      extensions::CrxInstaller::CreateSilent(browser_context);
  installer->set_allow_silent_install(true);
  installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
  installer->set_off_store_install_allow_reason(
      extensions::CrxInstaller::OffStoreInstallAllowReason::
          OffStoreInstallAllowedInTest);

  TestFuture<std::optional<CrxInstallError>> installer_done_future;

  installer->AddInstallerCallback(
      installer_done_future
          .GetCallback<const std::optional<CrxInstallError>&>());
  installer->InstallCrx(extension_path);

  const std::optional<CrxInstallError>& error = installer_done_future.Get();
  if (error) {
    return nullptr;
  }

  return installer->extension();
}

class ExtensionPolicyTest : public ExtensionPolicyTestBase {
 public:
  ExtensionPolicyTest() = default;

 protected:
  void SetUp() override {
    // Set default verification mode for content verifier to be enabled.
    extensions::ChromeContentVerifierDelegate::SetDefaultModeForTesting(
        extensions::ChromeContentVerifierDelegate::VerifyInfo::Mode::
            ENFORCE_STRICT);
    ignore_content_verifier_ =
        std::make_unique<extensions::ScopedIgnoreContentVerifierForTest>();
    test_extension_cache_ = std::make_unique<extensions::ExtensionCacheFake>();
    // Base class SetUp() should be invoked at the end as it runs the test body.
    ExtensionPolicyTestBase::SetUp();
  }

  void SetUpOnMainThread() override {
    ExtensionPolicyTestBase::SetUpOnMainThread();
    if (extension_updater()->enabled()) {
      extension_updater()->SetExtensionCacheForTesting(
          test_extension_cache_.get());
    }
  }

  void TearDownOnMainThread() override {
    if (extension_updater()->enabled()) {
      extension_updater()->SetExtensionCacheForTesting(nullptr);
    }
    ExtensionPolicyTestBase::TearDownOnMainThread();
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    ExtensionPolicyTestBase::SetUpCommandLine(command_line);
    // Some bots are flaky due to slower loading interacting with
    // deferred commits.
    command_line->AppendSwitch(blink::switches::kAllowPreCommitInput);
  }

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

  extensions::ExtensionCacheFake* extension_cache() {
    return test_extension_cache_.get();
  }

  extensions::ExtensionRegistrar* extension_registrar() {
    return extensions::ExtensionRegistrar::Get(profile());
  }

  extensions::ExtensionRegistry* extension_registry() {
    return extensions::ExtensionRegistry::Get(profile());
  }

  extensions::ExtensionUpdater* extension_updater() {
    return extensions::ExtensionUpdater::Get(profile());
  }

  extensions::SharedModuleService* shared_module_service() {
    return extensions::SharedModuleService::Get(profile());
  }

#if BUILDFLAG(ENABLE_EXTENSIONS)
  web_app::WebAppProvider* web_app_provider() {
    return web_app::WebAppProvider::GetForTest(profile());
  }
#endif

  const extensions::Extension* InstallExtension(
      const base::FilePath::StringType& name) {
    return InstallExtensionWithContext(name, profile());
  }

  void UninstallExtension(const std::string& id, bool expect_success) {
    if (expect_success) {
      extensions::TestExtensionRegistryObserver observer(extension_registry());
      extension_registrar()->UninstallExtension(
          id, extensions::UNINSTALL_REASON_FOR_TESTING, nullptr);
      observer.WaitForExtensionUninstalled();
    } else {
      extensions::TestExtensionRegistryObserver observer(extension_registry());
      extension_registrar()->UninstallExtension(
          id, extensions::UNINSTALL_REASON_FOR_TESTING, nullptr);
      observer.WaitForExtensionUninstallationDenied();
    }
  }

  void DisableExtension(const std::string& id) {
    extensions::TestExtensionRegistryObserver observer(extension_registry());
    extension_registrar()->DisableExtension(
        id, {extensions::disable_reason::DISABLE_USER_ACTION});
    observer.WaitForExtensionUnloaded();
  }

  void AddExtensionToForceList(PolicyMap* policies,
                               const std::string& id,
                               const GURL& update_url) {
    // Setting the forcelist extension should install extension with ExtensionId
    // equal to id.
    base::Value::List forcelist;
    forcelist.Append(update_url.is_empty()
                         ? id
                         : base::StrCat({id, ";", update_url.spec()}));
    policies->Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
                  POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
                  base::Value(std::move(forcelist)), nullptr);
  }

  const extensions::Extension* InstallForceListExtension(
      const std::string& update_url_suffix,
      const std::string& id) {
    extensions::ExtensionRegistry* registry = extension_registry();
    if (registry->GetExtensionById(id,
                                   extensions::ExtensionRegistry::EVERYTHING)) {
      return nullptr;
    }

    GURL update_url = embedded_test_server()->GetURL(update_url_suffix);
    PolicyMap policies;
    AddExtensionToForceList(&policies, id, update_url);

    extensions::TestExtensionRegistryObserver observer(extension_registry());
    UpdateProviderPolicy(policies);
    observer.WaitForExtensionWillBeInstalled();

    return registry->enabled_extensions().GetByID(id);
  }

  void NavigateToURL(const GURL& url) {
    auto* web_contents = chrome_test_utils::GetActiveWebContents(this);
    ASSERT_TRUE(content::NavigateToURL(web_contents, url));
    ASSERT_TRUE(content::WaitForLoadStop(web_contents));
  }

  std::unique_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
  std::unique_ptr<extensions::ScopedIgnoreContentVerifierForTest>
      ignore_content_verifier_;
  extensions::ExtensionUpdater::ScopedSkipScheduledCheckForTest
      skip_scheduled_extension_checks_;

 private:
#if BUILDFLAG(ENABLE_EXTENSIONS)
  web_app::OsIntegrationManager::ScopedSuppressForTesting os_hooks_suppress_;

  // TODO(https://crbug.com/40804030): Remove this when updated to use MV3.
  extensions::ScopedTestMV2Enabler mv2_enabler_;
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)
};

}  // namespace

#if BUILDFLAG(IS_CHROMEOS)
// Check that component extension can't be blocklisted.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionInstallBlocklistComponentApps) {
  // Load all component extensions.
  extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();
  auto* loader = extensions::ComponentLoader::Get(browser()->profile());
  loader->AddDefaultComponentExtensions(false);
  base::RunLoop().RunUntilIdle();

  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_TRUE(
      registry->enabled_extensions().GetByID(extensions::kWebStoreAppId));

  base::Value::List blocklist;
  blocklist.Append(extensions::kWebStoreAppId);
  PolicyMap policies;
  policies.Set(key::kExtensionInstallBlocklist, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(blocklist)), nullptr);
  UpdateProviderPolicy(policies);
  ASSERT_TRUE(
      registry->enabled_extensions().GetByID(extensions::kWebStoreAppId));
}
#endif  // BUILDFLAG(IS_CHROMEOS)

IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionInstallBlocklistSelective) {
  // Verifies that blocklisted extensions can't be installed.
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_FALSE(registry->GetExtensionById(
      kSimpleWithIconCrxId, extensions::ExtensionRegistry::EVERYTHING));
  base::Value::List blocklist;
  blocklist.Append(kGoodCrxId);
  PolicyMap policies;
  policies.Set(key::kExtensionInstallBlocklist, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(blocklist)), nullptr);
  UpdateProviderPolicy(policies);

  // "good.crx" is blocklisted.
  EXPECT_FALSE(InstallExtension(kGoodCrxName));
  EXPECT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // "simple_with_icon.crx" is not.
  const extensions::Extension* simple_with_icon =
      InstallExtension(kSimpleWithIconCrxName);
  ASSERT_TRUE(simple_with_icon);
  EXPECT_EQ(kSimpleWithIconCrxId, simple_with_icon->id());
  EXPECT_EQ(simple_with_icon,
            registry->enabled_extensions().GetByID(kSimpleWithIconCrxId));
}

// Ensure that when INSTALLATION_REMOVED is set
// that blocklisted extensions are removed from the device.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionInstallRemovedPolicy) {
  EXPECT_TRUE(InstallExtension(kGoodCrxName));

  extensions::ExtensionRegistry* registry = extension_registry();
  EXPECT_TRUE(registry->GetInstalledExtension(kGoodCrxId));

  // Should uninstall good_v1.crx.
  base::Value::Dict dict_value;
  dict_value.SetByDottedPath(
      std::string(kGoodCrxId) + "." +
          extensions::schema_constants::kInstallationMode,
      extensions::schema_constants::kRemoved);
  PolicyMap policies;
  policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(dict_value)), nullptr);
  extensions::TestExtensionRegistryObserver observer(registry);
  UpdateProviderPolicy(policies);
  observer.WaitForExtensionUnloaded();

  EXPECT_FALSE(registry->GetInstalledExtension(kGoodCrxId));
}

// Ensure that when INSTALLATION_REMOVED is set for wildcard
// that blocklisted extensions are removed from the device.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionWildcardRemovedPolicy) {
  EXPECT_TRUE(InstallExtension(kGoodCrxName));

  extensions::ExtensionRegistry* registry = extension_registry();
  EXPECT_TRUE(registry->GetInstalledExtension(kGoodCrxId));

  // Should uninstall good_v1.crx.
  base::Value::Dict dict;
  dict.SetByDottedPath(
      std::string("*") + "." + extensions::schema_constants::kInstallationMode,
      extensions::schema_constants::kRemoved);
  PolicyMap policies;
  policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(dict)), nullptr);
  extensions::TestExtensionRegistryObserver observer(registry);
  UpdateProviderPolicy(policies);
  observer.WaitForExtensionUnloaded();

  EXPECT_FALSE(registry->GetInstalledExtension(kGoodCrxId));
}

IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionInstallBlocklistWildcard) {
  // Verify that a wildcard blocklist takes effect.
  EXPECT_TRUE(InstallExtension(kSimpleWithIconCrxName));
  extensions::ExtensionRegistrar* registrar = extension_registrar();
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_TRUE(registry->enabled_extensions().GetByID(kSimpleWithIconCrxId));
  base::Value::List blocklist;
  blocklist.Append("*");
  PolicyMap policies;
  policies.Set(key::kExtensionInstallBlocklist, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(blocklist)), nullptr);
  UpdateProviderPolicy(policies);

  // "simple_with_icon" should be disabled.
  EXPECT_TRUE(registry->disabled_extensions().GetByID(kSimpleWithIconCrxId));
  EXPECT_FALSE(registrar->IsExtensionEnabled(kSimpleWithIconCrxId));

  // It shouldn't be possible to re-enable "simple_with_icon", until it
  // satisfies management policy.
  registrar->EnableExtension(kSimpleWithIconCrxId);
  EXPECT_FALSE(registrar->IsExtensionEnabled(kSimpleWithIconCrxId));

  // It shouldn't be possible to install good.crx.
  EXPECT_FALSE(InstallExtension(kGoodCrxName));
  EXPECT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
}

IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionInstallBlocklistSharedModules) {
  // Verifies that shared_modules are not affected by the blocklist.

  base::FilePath base_path;
  GetTestDataDirectory(&base_path);
  base::FilePath update_xml_template_path =
      base_path.Append(kTestExtensionsDir)
          .AppendASCII("policy_shared_module")
          .AppendASCII("update_template.xml");

  std::string update_xml_path =
      "/" + base::FilePath(kTestExtensionsDir).MaybeAsASCII() +
      "/policy_shared_module/gen_update.xml";
  RegisterURLReplacingHandler(embedded_test_server(), update_xml_path,
                              update_xml_template_path);
  ASSERT_TRUE(embedded_test_server()->Start());

  const char kImporterId[] = "pchakhniekfaeoddkifplhnfbffomabh";
  const char kSharedModuleId[] = "nfgclafboonjbiafbllihiailjlhelpm";

  // Make sure that "import" and "export" are available to these extension IDs
  // by mocking the release channel.
  extensions::ScopedCurrentChannel channel(version_info::Channel::DEV);

  // Verify that the extensions are not installed initially.
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kImporterId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_FALSE(registry->GetExtensionById(
      kSharedModuleId, extensions::ExtensionRegistry::EVERYTHING));

  // Mock the webstore update URL. This is where the shared module extension
  // will be installed from.
  GURL update_xml_url = embedded_test_server()->GetURL(update_xml_path);
  extension_test_util::SetGalleryUpdateURL(update_xml_url);
  NavigateToURL(update_xml_url);

  // Blocklist "*" but force-install the importer extension. The shared module
  // should be automatically installed too.
  base::Value::List blocklist;
  blocklist.Append("*");
  PolicyMap policies;
  AddExtensionToForceList(&policies, kImporterId, update_xml_url);
  policies.Set(key::kExtensionInstallBlocklist, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(blocklist)), nullptr);

  extensions::TestExtensionRegistryObserver observe_importer(registry,
                                                             kImporterId);
  extensions::TestExtensionRegistryObserver observe_shared_module(
      registry, kSharedModuleId);
  UpdateProviderPolicy(policies);
  observe_importer.WaitForExtensionLoaded();
  observe_shared_module.WaitForExtensionLoaded();

  // Verify that both extensions got installed.
  const extensions::Extension* importer =
      registry->enabled_extensions().GetByID(kImporterId);
  ASSERT_TRUE(importer);
  EXPECT_EQ(kImporterId, importer->id());
  const extensions::Extension* shared_module =
      registry->enabled_extensions().GetByID(kSharedModuleId);
  ASSERT_TRUE(shared_module);
  EXPECT_EQ(kSharedModuleId, shared_module->id());
  EXPECT_TRUE(shared_module->is_shared_module());

  // Verify the dependency.
  std::unique_ptr<extensions::ExtensionSet> set =
      shared_module_service()->GetDependentExtensions(shared_module);
  ASSERT_TRUE(set);
  EXPECT_EQ(1u, set->size());
  EXPECT_TRUE(set->Contains(importer->id()));

  std::vector<extensions::SharedModuleInfo::ImportInfo> imports =
      extensions::SharedModuleInfo::GetImports(importer);
  ASSERT_EQ(1u, imports.size());
  EXPECT_EQ(kSharedModuleId, imports[0].extension_id);
}

IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionInstallAllowlist) {
  // Verifies that the allowlist can open exceptions to the blocklist.
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_FALSE(registry->GetExtensionById(
      kSimpleWithIconCrxId, extensions::ExtensionRegistry::EVERYTHING));
  base::Value::List blocklist;
  blocklist.Append("*");
  base::Value::List allowlist;
  allowlist.Append(kGoodCrxId);
  PolicyMap policies;
  policies.Set(key::kExtensionInstallBlocklist, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(blocklist)), nullptr);
  policies.Set(key::kExtensionInstallAllowlist, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(allowlist)), nullptr);
  UpdateProviderPolicy(policies);
  // "simple_with_icon.crx" is blocklisted.
  EXPECT_FALSE(InstallExtension(kSimpleWithIconCrxName));
  EXPECT_FALSE(registry->GetExtensionById(
      kSimpleWithIconCrxId, extensions::ExtensionRegistry::EVERYTHING));
  // "good.crx" has a allowlist exception.
  const extensions::Extension* good = InstallExtension(kGoodCrxName);
  ASSERT_TRUE(good);
  EXPECT_EQ(kGoodCrxId, good->id());
  EXPECT_EQ(good, registry->enabled_extensions().GetByID(kGoodCrxId));
  // The user can also remove this extension.
  UninstallExtension(kGoodCrxId, true);
}

namespace {

class ExtensionRequestInterceptor {
 public:
  ExtensionRequestInterceptor()
      : interceptor_(
            base::BindRepeating(&ExtensionRequestInterceptor::OnRequest,
                                base::Unretained(this))) {}

  void set_interceptor_hook(
      content::URLLoaderInterceptor::InterceptCallback callback) {
    callback_ = std::move(callback);
  }

 private:
  bool OnRequest(content::URLLoaderInterceptor::RequestParams* params) {
    if (callback_ && callback_.Run(params)) {
      return true;
    }
    // Mock out requests to the Web Store.
    if (params->url_request.url.host() == "clients2.google.com" &&
        params->url_request.url.path() == "/service/update2/crx") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good2_update_manifest.xml",
          params->client.get());
      return true;
    }

    if (params->url_request.url.path() == "/good_update_manifest.xml") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good2_update_manifest.xml",
          params->client.get());
      return true;
    }

    if (params->url_request.url.path() ==
        "/good_prodversionmin_update_manifest.xml") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good_prodversionmin_update_manifest.xml",
          params->client.get());
      return true;
    }

    if (params->url_request.url.path() == "/extensions/good_v1.crx") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good_v1.crx", params->client.get());
      return true;
    }
    if (params->url_request.url.path() == "/extensions/good2.crx") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good2.crx", params->client.get());
      return true;
    }
    if (params->url_request.url.path() == "/extensions/good3.crx") {
      content::URLLoaderInterceptor::WriteResponse(
          "chrome/test/data/extensions/good3.crx", params->client.get());
      return true;
    }

    return false;
  }

  content::URLLoaderInterceptor::InterceptCallback callback_;
  content::URLLoaderInterceptor interceptor_;
};

class MockedInstallationCollectorObserver
    : public extensions::InstallStageTracker::Observer {
 public:
  explicit MockedInstallationCollectorObserver(
      const content::BrowserContext* context)
      : context_(context) {}
  ~MockedInstallationCollectorObserver() override = default;

  MOCK_METHOD1(ExtensionStageChanged,
               void(extensions::InstallStageTracker::Stage));
  MOCK_METHOD2(OnExtensionInstallationFailed,
               void(const extensions::ExtensionId&,
                    extensions::InstallStageTracker::FailureReason));

  void OnExtensionDataChangedForTesting(
      const extensions::ExtensionId& id,
      const content::BrowserContext* context,
      const extensions::InstallStageTracker::InstallationData& data) override {
    // For simplicity policies are pushed into all profiles, so we need to track
    // only one here.
    if (context != context_) {
      return;
    }
    if (data.install_stage && stage_ != data.install_stage.value()) {
      stage_ = data.install_stage.value();
      ExtensionStageChanged(stage_);
    }
  }

 private:
  extensions::InstallStageTracker::Stage stage_ =
      extensions::InstallStageTracker::Stage::CREATED;
  raw_ptr<const content::BrowserContext> context_ = nullptr;
};

std::string GetUpdateManifestBody(const std::string& id,
                                  const std::string& crx_name,
                                  const std::string& version) {
  // "example.com" is a  placeholder that gets substituted with the test
  // server address at runtime.
  std::string crx_path = "http://example.com/" + crx_name;
  return extensions::CreateUpdateManifest({extensions::UpdateManifestItem(id)
                                               .version(version)
                                               .status("ok")
                                               .codebase(crx_path)});
}

std::string GetUpdateManifestHeader() {
  return "HTTP/1.1 200 OK\nContent-Type: application/json; "
         "charset=utf-8\n";
}

bool WriteManifestResponse(content::URLLoaderInterceptor::RequestParams* params,
                           const std::string& id,
                           const std::string& update_manifest_name,
                           const std::string& crx_name,
                           const std::string& version,
                           const base::FilePath& install_crx_path) {
  if (params->url_request.url.path() == update_manifest_name) {
    content::URLLoaderInterceptor::WriteResponse(
        GetUpdateManifestHeader(), GetUpdateManifestBody(id, crx_name, version),
        params->client.get());
    return true;
  }

  if (params->url_request.url.path() == "/" + crx_name) {
    content::URLLoaderInterceptor::WriteResponse(install_crx_path,
                                                 params->client.get());
    return true;
  }
  return false;
}

}  // namespace

// Verifies that if extension is installed manually by user and then added to
// force-installed policy, it can't be uninstalled. And then if it removed
// from the force installed list, it should be uninstalled.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionAddedAndRemovedFromForceInstalledList) {
  ExtensionRequestInterceptor interceptor;

  ASSERT_FALSE(extension_registry()->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  ASSERT_TRUE(InstallExtension(kGoodCrxName));
  EXPECT_TRUE(extension_registry()->enabled_extensions().GetByID(kGoodCrxId));

  EXPECT_EQ(extension_registry()
                ->enabled_extensions()
                .GetByID(kGoodCrxId)
                ->location(),
            ManifestLocation::kInternal);

  // The user is allowed to disable the added extension.
  EXPECT_TRUE(extension_registrar()->IsExtensionEnabled(kGoodCrxId));
  DisableExtension(kGoodCrxId);
  EXPECT_FALSE(extension_registrar()->IsExtensionEnabled(kGoodCrxId));

  // Explicitly re-enable the extension.
  extension_registrar()->EnableExtension(kGoodCrxId);
  // Extensions that are force-installed come from an update URL, which defaults
  // to the webstore. Use a test URL for this test with an update manifest
  // that includes "good_v1.crx".
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");

  PolicyMap policies;
  AddExtensionToForceList(&policies, kGoodCrxId, url);
  UpdateProviderPolicy(policies);
  const extensions::Extension* extension =
      extension_registry()->enabled_extensions().GetByID(kGoodCrxId);
  EXPECT_TRUE(extension);

  // The user is not allowed to uninstall force-installed extensions.
  UninstallExtension(kGoodCrxId, /*expect_success=*/false);
  EXPECT_EQ(extension->location(), ManifestLocation::kExternalPolicyDownload);

  // Remove the force installed policy.
  policies.Erase(policy::key::kExtensionInstallForcelist);
  UpdateProviderPolicy(policies);

  // TODO(crbug.com/40668351)
  // Extension should be uninstalled now. It would be better to keep it, but it
  // doesn't happen for now.
  ASSERT_FALSE(extension_registry()->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
}

// Verifies that extension is not installed if its version does not match
// with that in the update manifest.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       CrxVersionInconsistencyFromManifest) {
  // Intercepts the call to download the crx file and responds with the test crx
  // file.
  ExtensionRequestInterceptor interceptor;
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Allow caching for the extension in case it is inserted in the cache.
  extension_cache()->AllowCaching(kGoodCrxId);

  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url = embedded_test_server()->GetURL(
      "/extensions/good_v1_wrong_version_update_manifest.xml");
  PolicyMap policies;

  TestFuture<std::optional<CrxInstallError>> installer_done_future;
  extension_updater()->SetCrxInstallerResultCallbackForTesting(
      installer_done_future
          .GetCallback<const std::optional<CrxInstallError>&>());

  // Add an entry in the extension force list policy.
  AddExtensionToForceList(&policies, kGoodCrxId, url);

  // Updating the policy triggers the extension installation process.
  UpdateProviderPolicy(policies);
  // Wait till the installer has finished.
  const std::optional<CrxInstallError>& install_error =
      installer_done_future.Get();
  // Check the extension is not installed.
  EXPECT_TRUE(install_error);
  EXPECT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  // Check the extension in not inserted in the cache.
  EXPECT_FALSE(
      extension_cache()->GetExtension(kGoodCrxId, "", nullptr, nullptr));
}

#if BUILDFLAG(IS_CHROMEOS)
// Verifies that if the cache entry contains inconsistent extension version,
// the crx installation fails and download of a new crx file is attempted.
//
// TODO(crbug.com/40236711): Fix this test. It doesn't always pass.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       DISABLED_CrxVersionInconsistencyInCache) {
  base::ScopedAllowBlockingForTesting allow_io;
  // Intercepts the call to download the crx file and responds with the test crx
  // file.
  ExtensionRequestInterceptor interceptor;
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Override the fake extension cache set in SetUpOnMainThread() as the test
  // requires real extension cache to retry download of crx file when
  // installation fails due to version mismatch.
  extensions::ExtensionCache* cache =
      extensions::ExtensionsBrowserClient::Get()->GetExtensionCache();
  extension_updater()->SetExtensionCacheForTesting(cache);

  base::FilePath extension_path(ui_test_utils::GetTestFilePath(
      base::FilePath(kTestExtensionsDir), base::FilePath(kGoodCrxName)));
  cache->AllowCaching(kGoodCrxId);

  // Copy the crx file to a temp directory so that the test file is not deleted
  // when cache entry is removed on version mismatch.
  base::ScopedTempDir tmp_dir;
  ASSERT_TRUE(tmp_dir.CreateUniqueTempDir());
  const base::FilePath tmp_path = tmp_dir.GetPath();
  const base::FilePath filename =
      tmp_path.Append(extensions::LocalExtensionCache::ExtensionFileName(
          kGoodCrxId, kGoodCrxVersion, "" /* hash */));
  EXPECT_TRUE(CopyFile(extension_path, filename));

  // Wait for the extension cache to get ready.
  base::RunLoop cache_init_run_loop;
  cache->Start(cache_init_run_loop.QuitClosure());
  cache_init_run_loop.Run();

  base::RunLoop put_extension_run_loop;
  // Insert a cache entry with version "1.0.0.1" while the crx file it points to
  // belongs to version "1.0.0.0".
  cache->PutExtension(
      kGoodCrxId, "" /* expected hash */, filename, kGoodCrxVersion,
      base::BindLambdaForTesting(
          [&put_extension_run_loop](const base::FilePath& file_path,
                                    bool file_ownership_passed) {
            put_extension_run_loop.Quit();
          }));
  put_extension_run_loop.Run();
  EXPECT_TRUE(cache->GetExtension(kGoodCrxId, "", nullptr, nullptr));

  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good2_update_manifest.xml");
  PolicyMap policies;

  TestFuture<std::optional<CrxInstallError>> installer_done_future;
  extension_updater()->SetCrxInstallerResultCallbackForTesting(
      installer_done_future
          .GetCallback<const std::optional<CrxInstallError>&>());

  // Add an entry in the extension force list policy.
  AddExtensionToForceList(&policies, kGoodCrxId, url);

  TestExtensionRegistryObserver registry_observer(extension_registry());

  // Updating the policy triggers the extension installation process.
  UpdateProviderPolicy(policies);
  // Wait till extension entry is found in the cache and installation fails due
  // to version mismatch as the cache entry informs extension version as
  // "1.0.0.1" while the crx file it points to belongs to "1.0.0.0".
  const std::optional<CrxInstallError>& install_error =
      installer_done_future.Get();
  EXPECT_TRUE(install_error);

  // Wait till extension is freshly downloaded from the server and installation
  // succeeds.
  ASSERT_TRUE(registry_observer.WaitForExtensionLoaded());

  EXPECT_TRUE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  std::string version;
  base::FilePath file_path;
  // Check extension is inserted in the cache with a new filepath to the
  // downloaded correct crx.
  EXPECT_TRUE(cache->GetExtension(kGoodCrxId, "", &file_path, &version));
  EXPECT_EQ(version, kGoodCrxVersion);
  EXPECT_NE(file_path, filename);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

// Verifies that extensions that are force-installed by policies are
// installed and can't be uninstalled.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionInstallForcelist) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  ExtensionRequestInterceptor interceptor;
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Extensions that are force-installed come from an update URL, which defaults
  // to the webstore. Use a test URL for this test with an update manifest
  // that includes "good_v1.crx".
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");

  PolicyMap policies;
  AddExtensionToForceList(&policies, kGoodCrxId, url);
  extension_cache()->AllowCaching(kGoodCrxId);
  EXPECT_FALSE(
      extension_cache()->GetExtension(kGoodCrxId, "", nullptr, nullptr));

  extensions::TestExtensionRegistryObserver registry_observer(
      extension_registry());
  MockedInstallationCollectorObserver collector_observer(profile());
  // CREATED is the default stage in MockedInstallationCollectorObserver, so it
  // wouldn't be reported here.
  Sequence sequence;
  EXPECT_CALL(
      collector_observer,
      ExtensionStageChanged(extensions::InstallStageTracker::Stage::PENDING))
      .InSequence(sequence);
  EXPECT_CALL(collector_observer,
              ExtensionStageChanged(
                  extensions::InstallStageTracker::Stage::DOWNLOADING))
      .InSequence(sequence);
  EXPECT_CALL(
      collector_observer,
      ExtensionStageChanged(extensions::InstallStageTracker::Stage::INSTALLING))
      .InSequence(sequence);
  EXPECT_CALL(
      collector_observer,
      ExtensionStageChanged(extensions::InstallStageTracker::Stage::COMPLETE))
      .InSequence(sequence);

  extensions::InstallStageTracker* install_stage_tracker =
      extensions::InstallStageTracker::Get(profile());
  install_stage_tracker->AddObserver(&collector_observer);
  UpdateProviderPolicy(policies);
  registry_observer.WaitForExtensionWillBeInstalled();
  install_stage_tracker->RemoveObserver(&collector_observer);
  // Note: Cannot check that the notification details match the expected
  // exception, since the details object has already been freed prior to
  // the completion of registry_observer.WaitForExtensionWillBeInstalled().
  EXPECT_TRUE(
      extension_cache()->GetExtension(kGoodCrxId, "", nullptr, nullptr));
  EXPECT_TRUE(registry->enabled_extensions().GetByID(kGoodCrxId));

  // The user is not allowed to uninstall force-installed extensions.
  UninstallExtension(kGoodCrxId, false);

  scoped_refptr<extensions::UnpackedInstaller> installer =
      extensions::UnpackedInstaller::Create(profile());

  // The user is not allowed to load an unpacked extension with the
  // same ID as a force-installed extension.
  base::FilePath good_extension_path(GetTestFilePath(
      base::FilePath(kTestExtensionsDir), base::FilePath(kSimpleWithPopupExt)));
  extensions::LoadErrorWaiter waiter;
  installer->Load(good_extension_path);
  waiter.Wait();

  // Loading other unpacked extensions are not blocked.
  scoped_refptr<const extensions::Extension> extension =
      LoadUnpackedExtension(kAppUnpackedExt);
  ASSERT_TRUE(extension);

  const std::string old_version_number =
      registry->enabled_extensions().GetByID(kGoodCrxId)->version().GetString();

  extensions::ExtensionHostTestHelper extension_ready_observer(profile(),
                                                               kGoodCrxId);

  extensions::ExtensionHostTestHelper background_loaded_observer(profile(),
                                                                 kGoodCrxId);
  background_loaded_observer.RestrictToType(
      extensions::mojom::ViewType::kExtensionBackgroundPage);

  // Updating the force-installed extension.
  extensions::ExtensionUpdater* updater = extension_updater();
  extensions::ExtensionUpdater::CheckParams params;
  params.install_immediately = true;
  extensions::TestExtensionRegistryObserver update_observer(
      extension_registry());
  updater->CheckNow(std::move(params));
  update_observer.WaitForExtensionWillBeInstalled();

  const base::Version& new_version =
      registry->enabled_extensions().GetByID(kGoodCrxId)->version();
  ASSERT_TRUE(new_version.IsValid());
  base::Version old_version(old_version_number);
  ASSERT_TRUE(old_version.IsValid());

  EXPECT_EQ(1, new_version.CompareTo(old_version));

  // Wait for the new extension process to launch.
  extension_ready_observer.WaitForRenderProcessReady();

  // Wait until the background page for the new extension has properly loaded.
  ASSERT_TRUE(background_loaded_observer.WaitForHostCompletedFirstLoad());

#if BUILDFLAG(ENABLE_EXTENSIONS)
  // Test policy-installed extensions are reloaded when killed.
  // TODO(crbug.com/414879019): Enable when BackgroundContentsService is ported
  // to desktop Android.
  {
    BackgroundContentsService::
        SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(1);
    extensions::ExtensionHostTestHelper extension_crashed_observer(profile(),
                                                                   kGoodCrxId);
    extensions::TestExtensionRegistryObserver extension_loaded_observer(
        extension_registry(), kGoodCrxId);
    extensions::ExtensionHost* extension_host =
        extensions::ProcessManager::Get(profile())
            ->GetBackgroundHostForExtension(kGoodCrxId);
    content::RenderProcessHost* process = extension_host->render_process_host();
    content::ScopedAllowRendererCrashes allow_renderer_crashes(process);
    process->Shutdown(content::RESULT_CODE_KILLED);
    extension_crashed_observer.WaitForRenderProcessGone();
    extension_loaded_observer.WaitForExtensionLoaded();
  }
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)
}

// Verifies that "prodversionmin" attribute in update manifest is used to
// select the version to which an already installed extension should be updated.
// "Prodversionmin" specifies the minimum browser version which supports the
// corresponding extension version.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, UpdateExtensionWithProdversionmin) {
  ExtensionRequestInterceptor interceptor;
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Install the extension with an older version. The extension manifest of this
  // extension points to an update manifest which contains multiple <app> tags
  // with different values of "prodversionmin" attribute.
  const extensions::Extension* extension =
      InstallExtension(FILE_PATH_LITERAL("good_prodversion_v1.crx"));
  ASSERT_TRUE(extension);
  EXPECT_EQ(kGoodCrxId, extension->id());
  ASSERT_TRUE(registry->enabled_extensions().GetByID(kGoodCrxId));
  auto installed_version =
      registry->enabled_extensions().GetByID(kGoodCrxId)->version();
  EXPECT_EQ(installed_version.CompareTo(base::Version("1.0.0.0")), 0);

  // Update the extension and verify the version according to "prodversionmin"
  // in the update manifest.
  extensions::ExtensionUpdater* updater = extension_updater();
  extensions::ExtensionUpdater::CheckParams params;
  params.install_immediately = true;
  extensions::TestExtensionRegistryObserver update_observer(
      extension_registry());
  updater->CheckNow(std::move(params));
  update_observer.WaitForExtensionWillBeInstalled();

  ASSERT_TRUE(registry->enabled_extensions().GetByID(kGoodCrxId));
  auto updated_version =
      registry->enabled_extensions().GetByID(kGoodCrxId)->version();
  EXPECT_EQ(updated_version.CompareTo(base::Version("1.0.0.1")), 0);
}

// Verifies that "prodversionmin" attribute in update manifest is used to
// select the extension version which should be installed. "Prodversionmin"
// specifies the minimum browser version which supports the corresponding
// extension version.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       InstallExtensionWithProdversionmin) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  ExtensionRequestInterceptor interceptor;
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Extensions that are force-installed come from an update URL, which defaults
  // to the webstore. Use a custom URL for this test for the update manifest.
  ASSERT_TRUE(embedded_test_server()->Start());
  const extensions::Extension* extension = InstallForceListExtension(
      "/extensions/good_prodversionmin_update_manifest.xml", kGoodCrxId);
  ASSERT_TRUE(extension);

  auto installed_version = extension->version();
  EXPECT_EQ(installed_version.CompareTo(base::Version("1.0.0.1")), 0);
}

class ExtensionPinningTest : public extensions::ExtensionBrowserTest {
 public:
  ExtensionPinningTest() = default;
  ~ExtensionPinningTest() override = default;

 protected:
  // Sets the ExtensionSettings policy so that extension |id| will be
  // force-installed from update URL pointing to test server's file
  // |update_url_suffix|. It also sets |override_update_url| flag as true for
  // the |id|.
  void SetExtensionSettingsPolicy(const std::string& update_url_suffix,
                                  const std::string& id) {
#if BUILDFLAG(IS_WIN)
    // Unless enterprise managed, policy handler only allows extensions from the
    // Chrome Webstore to be force installed. Mark enterprise managed for
    // windows.
    base::win::ScopedDomainStateForTesting scoped_domain(true);
#endif

    ASSERT_TRUE(embedded_test_server()->Started());
    GURL update_url = embedded_test_server()->GetURL(update_url_suffix);

    PolicyMap policies;
    base::Value::Dict dict, key_dict;
    key_dict.Set(extensions::schema_constants::kInstallationMode,
                 extensions::schema_constants::kForceInstalled);
    key_dict.Set(extensions::schema_constants::kUpdateUrl, update_url.spec());
    key_dict.Set(extensions::schema_constants::kOverrideUpdateUrl, true);
    dict.Set(id, std::move(key_dict));
    policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
                 POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
                 base::Value(std::move(dict)), nullptr);
    provider_.UpdateChromePolicy(policies);
  }

  // Triggers extension update process and waits for either extension
  // installation success if |expected_install_success| is true or else
  // extension installation failure.
  const extensions::Extension* TriggerExtensionUpdate(
      const std::string& id,
      bool expected_install_success) {
    extensions::ExtensionRegistry* registry = extension_registry();
    if (registry->GetExtensionById(
            id, extensions::ExtensionRegistry::EVERYTHING) == nullptr) {
      return nullptr;
    }

    extensions::ExtensionUpdater* updater =
        extensions::ExtensionUpdater::Get(profile());
    extensions::ExtensionUpdater::CheckParams params;
    params.install_immediately = true;

    if (expected_install_success) {
      extensions::TestExtensionRegistryObserver update_observer(
          extension_registry());
      updater->CheckNow(std::move(params));
      update_observer.WaitForExtensionWillBeInstalled();
    } else {
      base::RunLoop run_loop;
      MockedInstallationCollectorObserver collector_observer(profile());
      extensions::InstallStageTracker* install_stage_tracker =
          extensions::InstallStageTracker::Get(profile());
      install_stage_tracker->AddObserver(&collector_observer);

      // We expect install failure only due to no update for the extension.
      EXPECT_CALL(
          collector_observer,
          OnExtensionInstallationFailed(
              testing::_,
              extensions::InstallStageTracker::FailureReason::NO_UPDATE))
          .WillOnce(testing::Invoke([&]() { run_loop.Quit(); }));
      updater->CheckNow(std::move(params));
      run_loop.Run();
    }

    return registry->enabled_extensions().GetByID(id);
  }

  void SetUpInProcessBrowserTestFixture() override {
    ExtensionBrowserTest::SetUpInProcessBrowserTestFixture();

    provider_.SetDefaultReturns(
        true /* is_initialization_complete_return */,
        true /* is_first_policy_load_complete_return */);
    BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
  }

  base::FilePath PackLocalExtension(const std::string& relative_dir_path,
                                    const std::string& relative_pem_path,
                                    const base::FilePath& crx_path) {
    base::FilePath base_path;
    GetTestDataDirectory(&base_path);
    auto extension_path =
        base_path.Append(kTestExtensionsDir).AppendASCII(relative_dir_path);
    base::FilePath pem_path =
        base_path.Append(kTestExtensionsDir).AppendASCII(relative_pem_path);
    return PackExtensionWithOptions(extension_path, crx_path, pem_path,
                                    base::FilePath());
  }

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

// Extension without update_url in manifest gets updated through update_url in
// policy.
IN_PROC_BROWSER_TEST_F(ExtensionPinningTest,
                       UpdateExtensionWithNoUrlInManifest) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::ScopedTempDir scoped_temp_dir;
  EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  base::FilePath install_crx_path =
      scoped_temp_dir.GetPath().AppendASCII("v1.crx");
  ASSERT_EQ(
      PackLocalExtension("pinning/no_update_url/v1",
                         "pinning/no_update_url/key.pem", install_crx_path),
      install_crx_path);

  // Intercept requests to install the extension and return false for any
  // unexpected request.
  ExtensionRequestInterceptor interceptor;
  ASSERT_TRUE(embedded_test_server()->Start());
  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        return WriteManifestResponse(params, kPinnedExtensionCrxId,
                                     "/update_manifest_v1.xml", "v1.crx",
                                     /*version=*/"1", install_crx_path);
      }));

  extensions::TestExtensionRegistryObserver observer(extension_registry(),
                                                     kPinnedExtensionCrxId);
  SetExtensionSettingsPolicy("/update_manifest_v1.xml", kPinnedExtensionCrxId);
  auto installed_extension = observer.WaitForExtensionWillBeInstalled();
  ASSERT_TRUE(installed_extension);
  EXPECT_EQ(installed_extension->version().CompareTo(base::Version("1")), 0);

  base::FilePath updated_crx_path =
      scoped_temp_dir.GetPath().AppendASCII("v2.crx");
  ASSERT_EQ(
      PackLocalExtension("pinning/no_update_url/v2",
                         "pinning/no_update_url/key.pem", updated_crx_path),
      updated_crx_path);

  // Override the interceptor hook to only accept new requests for updated
  // extension.
  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        return WriteManifestResponse(params, kPinnedExtensionCrxId,
                                     "/update_manifest_v2.xml", "v2.crx",
                                     /*version=*/"2", updated_crx_path);
      }));
  // Change |update_url| to point to version 2 of the extension.
  SetExtensionSettingsPolicy("/update_manifest_v2.xml", kPinnedExtensionCrxId);

  // Extension is updated from |update_url| in the policy.
  const extensions::Extension* updated_extension = TriggerExtensionUpdate(
      kPinnedExtensionCrxId, /*expected_install_success=*/true);
  ASSERT_TRUE(updated_extension);
  EXPECT_EQ(updated_extension->version().CompareTo(base::Version("2")), 0);
}

// Extension with one update_url in manifest gets updated through another
// update_url in policy.
IN_PROC_BROWSER_TEST_F(ExtensionPinningTest, UpdateExtensionWithUrlInManifest) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::ScopedTempDir scoped_temp_dir;
  EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  base::FilePath install_crx_path =
      scoped_temp_dir.GetPath().AppendASCII("v1.crx");
  ASSERT_EQ(PackLocalExtension("pinning/update_url/v1",
                               "pinning/update_url/key.pem", install_crx_path),
            install_crx_path);

  // Intercept requests to update the extension and return false for any
  // unexpected request.
  ExtensionRequestInterceptor interceptor;
  ASSERT_TRUE(embedded_test_server()->Start());
  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        return WriteManifestResponse(params, kPinnedExtensionCrxId,
                                     "/update_manifest_v1.xml", "v1.crx",
                                     /*version=*/"1", install_crx_path);
      }));

  extensions::TestExtensionRegistryObserver observer(extension_registry(),
                                                     kPinnedExtensionCrxId);
  SetExtensionSettingsPolicy("/update_manifest_v1.xml", kPinnedExtensionCrxId);
  auto installed_extension = observer.WaitForExtensionWillBeInstalled();
  ASSERT_TRUE(installed_extension);
  EXPECT_EQ(installed_extension->version().CompareTo(base::Version("1")), 0);

  base::FilePath updated_crx_path =
      scoped_temp_dir.GetPath().AppendASCII("v2.crx");
  ASSERT_EQ(PackLocalExtension("pinning/update_url/v2",
                               "pinning/update_url/key.pem", updated_crx_path),
            updated_crx_path);

  // Override the interceptor hook to only accept new requests for updated
  // extension.
  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        return WriteManifestResponse(params, kPinnedExtensionCrxId,
                                     "/update_manifest_v2.xml", "v2.crx",
                                     /*version=*/"2", updated_crx_path);
      }));
  // Change |update_url| to point to version 2 of the extension.
  SetExtensionSettingsPolicy("/update_manifest_v2.xml", kPinnedExtensionCrxId);

  // Extension is updated from |update_url| in the policy.
  const extensions::Extension* updated_extension = TriggerExtensionUpdate(
      kPinnedExtensionCrxId, /*expected_install_success=*/true);
  ASSERT_TRUE(updated_extension);
  EXPECT_EQ(updated_extension->version().CompareTo(base::Version("2")), 0);
}

// Extension with one update_url in manifest is not updated through it.
IN_PROC_BROWSER_TEST_F(ExtensionPinningTest, IgnoreUpdateUrlInManifest) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  base::ScopedAllowBlockingForTesting allow_blocking;
  base::ScopedTempDir scoped_temp_dir;
  EXPECT_TRUE(scoped_temp_dir.CreateUniqueTempDir());

  base::FilePath install_crx_path =
      scoped_temp_dir.GetPath().AppendASCII("v1.crx");
  ASSERT_EQ(PackLocalExtension("pinning/update_url/v1",
                               "pinning/update_url/key.pem", install_crx_path),
            install_crx_path);

  // Intercept requests to update the extension and return false for any
  // unexpected request.
  ExtensionRequestInterceptor interceptor;
  ASSERT_TRUE(embedded_test_server()->Start());
  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        return WriteManifestResponse(params, kPinnedExtensionCrxId,
                                     "/update_manifest_v1.xml", "v1.crx",
                                     /*version=*/"1", install_crx_path);
      }));

  extensions::TestExtensionRegistryObserver observer(extension_registry(),
                                                     kPinnedExtensionCrxId);
  SetExtensionSettingsPolicy("/update_manifest_v1.xml", kPinnedExtensionCrxId);
  auto installed_extension = observer.WaitForExtensionWillBeInstalled();
  ASSERT_TRUE(installed_extension);
  EXPECT_EQ(installed_extension->version().CompareTo(base::Version("1")), 0);

  // Extension is not updated from |update_url| in extension manifest. The
  // installation fails due to no updates as |update_url| in the
  // ExtensionSettings policy is used for updates which points to the installed
  // version.
  const extensions::Extension* updated_extension = TriggerExtensionUpdate(
      kPinnedExtensionCrxId, /*expected_install_success=*/false);
  ASSERT_TRUE(updated_extension);
  EXPECT_EQ(updated_extension->version().CompareTo(base::Version("1")), 0);
}

// Self hosted extension from the Chrome Web Store is not updated through the
// update_url in it's manifest even though a new version is available on the
// Store.
IN_PROC_BROWSER_TEST_F(ExtensionPinningTest,
                       SelfHostedCWSExtensionNotUpdatedFromStore) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  // Sample Google calendar extension from Chrome Web Store, for which we have
  // an old CRX.
  const char kGoogleCalendarCrxId[] = "gmbgaklkmjakoegficnlkhebmhkjfich";
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoogleCalendarCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Intercept requests to update the extension and return false for any
  // unexpected request.
  ExtensionRequestInterceptor interceptor;
  ASSERT_TRUE(embedded_test_server()->Start());

  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        base::FilePath path;
        base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &path);
        path = path.AppendASCII(
            "chrome/test/data/extensions/pinning/calendar/"
            "gmbgaklkmjakoegficnlkhebmhkjfich-google-calendar-3.1.0.crx");
        return WriteManifestResponse(params, kGoogleCalendarCrxId,
                                     "/update_manifest.xml", "calendar.crx",
                                     "3.1.0", path);
      }));

  extensions::TestExtensionRegistryObserver observer(extension_registry(),
                                                     kGoogleCalendarCrxId);
  SetExtensionSettingsPolicy("/update_manifest.xml", kGoogleCalendarCrxId);
  auto installed_extension = observer.WaitForExtensionWillBeInstalled();
  ASSERT_TRUE(installed_extension);
  EXPECT_EQ(installed_extension->version().CompareTo(base::Version("3.1.0")),
            0);

  // Extension is not updated from |update_url| in extension manifest. The
  // installation fails due to no updates as |update_url| in the
  // ExtensionSettings policy is used for updates which points to the installed
  // version.
  const extensions::Extension* updated_extension = TriggerExtensionUpdate(
      kGoogleCalendarCrxId, /*expected_install_success=*/false);
  ASSERT_TRUE(updated_extension);
  EXPECT_EQ(updated_extension->version().CompareTo(base::Version("3.1.0")), 0);
}

// Verifies that if multiple <app> tags for an extension are specified in the
// update manifest, the first valid tag is selected for crx download. This
// test helps to notify of any change in this behaviour as there might be
// extensions relying on it.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, UpdateManifestOrderedAppTags) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  ExtensionRequestInterceptor interceptor;
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Extensions that are force-installed come from an update URL, which defaults
  // to the webstore. Use a custom URL for this test for the update manifest.
  ASSERT_TRUE(embedded_test_server()->Start());
  const extensions::Extension* extension = InstallForceListExtension(
      "/extensions/good_ordered_app_tags_update_manifest.xml", kGoodCrxId);
  ASSERT_TRUE(extension);

  auto installed_version = extension->version();
  EXPECT_EQ(installed_version.CompareTo(base::Version("1.0.0.0")), 0);
}

// Verifies that corrupted non-webstore policy-based extension is automatically
// repaired (reinstalled).
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       CorruptedNonWebstoreExtensionRepaired) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  ignore_content_verifier_.reset();
  ExtensionRequestInterceptor interceptor;
  ASSERT_TRUE(embedded_test_server()->Start());

  const base::FilePath kResourcePath(FILE_PATH_LITERAL("script1.js"));

  // Step 1: Setup a policy and force-install an extension.
  const extensions::Extension* extension = InstallForceListExtension(
      "/extensions/good_v1_update_manifest.xml", kGoodCrxId);
  ASSERT_TRUE(extension);

  // Step 2: Corrupt extension's resource.
  {
    base::FilePath resource_path = extension->path().Append(kResourcePath);
    base::ScopedAllowBlockingForTesting allow_blocking;
    // Temporarily disable extension, we don't want to tackle with resources of
    // enabled one. Not using command DISABLE_USER_ACTION reason since
    // force-installed extension may not be disabled by user action.
    extension_registrar()->DisableExtension(
        kGoodCrxId, {extensions::disable_reason::DISABLE_RELOAD});

    const std::string kCorruptedContent("// corrupted\n");
    ASSERT_TRUE(base::WriteFile(resource_path, kCorruptedContent));

    extension_registrar()->EnableExtension(kGoodCrxId);
  }

  extensions::TestContentVerifyJobObserver content_verify_job_observer;
  extensions::TestExtensionRegistryObserver registry_observer(
      extension_registry());

  // Step 3: Fetch resource to trigger corruption check and wait for content
  // verify job completion.
  {
    content_verify_job_observer.ExpectJobResult(
        kGoodCrxId, kResourcePath,
        extensions::TestContentVerifyJobObserver::Result::FAILURE);

    GURL resource_url = extension->ResolveExtensionURL("script1.js");
    FetchSubresource(chrome_test_utils::GetActiveWebContents(this),
                     resource_url);

    EXPECT_TRUE(content_verify_job_observer.WaitForExpectedJobs());
  }

  // Step 4: Check that we are going to reinstall the extension and wait for
  // extension reinstall.
  EXPECT_TRUE(CorruptedExtensionReinstaller::Get(profile())
                  ->IsReinstallForCorruptionExpected(kGoodCrxId));
  registry_observer.WaitForExtensionWillBeInstalled();

  // Extension was reloaded, old extension object is invalid.
  extension = extension_registry()->enabled_extensions().GetByID(kGoodCrxId);

  // Step 5: Check that resource has its original contents.
  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    base::FilePath resource_path = extension->path().Append(kResourcePath);
    std::string contents;
    ASSERT_TRUE(base::ReadFileToString(resource_path, &contents));
    EXPECT_EQ("// script1\n", contents);
  }
}

// Verifies that corrupted non-webstore policy-based extension is automatically
// repaired (reinstalled) even if hashes file is damaged too.
// crbug.com/1131634: flaky on win
#if BUILDFLAG(IS_WIN)
#define MAYBE_CorruptedNonWebstoreExtensionWithDamagedHashesRepaired \
  DISABLED_CorruptedNonWebstoreExtensionWithDamagedHashesRepaired
#else
#define MAYBE_CorruptedNonWebstoreExtensionWithDamagedHashesRepaired \
  CorruptedNonWebstoreExtensionWithDamagedHashesRepaired
#endif
IN_PROC_BROWSER_TEST_F(
    ExtensionPolicyTest,
    MAYBE_CorruptedNonWebstoreExtensionWithDamagedHashesRepaired) {
  ignore_content_verifier_.reset();
  ExtensionRequestInterceptor interceptor;
  ASSERT_TRUE(embedded_test_server()->Start());

  const base::FilePath kResourcePath(FILE_PATH_LITERAL("script1.js"));

  // Step 1: Setup a policy and force-install an extension.
  const extensions::Extension* extension = InstallForceListExtension(
      "/extensions/good_v1_update_manifest.xml", kGoodCrxId);
  ASSERT_TRUE(extension);

  // Step 2: Corrupt extension's resource and hashes file.
  {
    base::FilePath resource_path = extension->path().Append(kResourcePath);
    base::ScopedAllowBlockingForTesting allow_blocking;
    // Temporarily disable extension, we don't want to tackle with resources of
    // enabled one. Not using command DISABLE_USER_ACTION reason since
    // force-installed extension may not be disabled by user action.
    extension_registrar()->DisableExtension(
        kGoodCrxId, {extensions::disable_reason::DISABLE_RELOAD});

    const std::string kCorruptedContent("// corrupted\n");
    ASSERT_TRUE(base::WriteFile(resource_path, kCorruptedContent));

    const std::string kInvalidJson("not a json");
    ASSERT_TRUE(base::WriteFile(
        extensions::file_util::GetComputedHashesPath(extension->path()),
        kInvalidJson));

    extension_registrar()->EnableExtension(kGoodCrxId);
  }

  extensions::TestExtensionRegistryObserver observer(extension_registry());

  // Step 3: Fetch resource to trigger corruption check and wait for content
  // verify job completion.
  {
    extensions::TestContentVerifyJobObserver content_verify_job_observer;
    content_verify_job_observer.ExpectJobResult(
        kGoodCrxId, kResourcePath,
        extensions::TestContentVerifyJobObserver::Result::FAILURE);

    GURL resource_url = extension->ResolveExtensionURL("script1.js");
    FetchSubresource(chrome_test_utils::GetActiveWebContents(this),
                     resource_url);

    EXPECT_TRUE(content_verify_job_observer.WaitForExpectedJobs());
  }

  // Step 4: Check that we are going to reinstall the extension and wait for
  // extension reinstall.
  EXPECT_TRUE(CorruptedExtensionReinstaller::Get(profile())
                  ->IsReinstallForCorruptionExpected(kGoodCrxId));
  observer.WaitForExtensionWillBeInstalled();

  // Extension was reloaded, old extension object is invalid.
  extension = extension_registry()->enabled_extensions().GetByID(kGoodCrxId);

  // Step 5: Check that resource has its original contents.
  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    base::FilePath resource_path = extension->path().Append(kResourcePath);
    std::string contents;
    ASSERT_TRUE(base::ReadFileToString(resource_path, &contents));
    EXPECT_EQ("// script1\n", contents);
  }
}

// Verifies that corrupted non-webstore policy-based extension is not repaired
// if there are no computed_hashes.json for it. Note that this behavior will
// change in the future.
// See https://crbug.com/958794#c22 for details.
// TODO(crbug.com/40669814): Change this test so extension without hashes
// will be also reinstalled.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       CorruptedNonWebstoreExtensionWithoutHashesRemained) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  ignore_content_verifier_.reset();
  ExtensionRequestInterceptor interceptor;
  ASSERT_TRUE(embedded_test_server()->Start());
  base::HistogramTester histogram_tester;

  const base::FilePath kResourcePath(FILE_PATH_LITERAL("script1.js"));

  // Step 1: Setup a policy and force-install an extension.
  const extensions::Extension* extension = InstallForceListExtension(
      "/extensions/good_v1_update_manifest.xml", kGoodCrxId);
  ASSERT_TRUE(extension);

  // Step 2: Corrupt extension's resource and remove hashes.
  {
    base::FilePath resource_path = extension->path().Append(kResourcePath);
    base::ScopedAllowBlockingForTesting allow_blocking;
    // Temporarily disable extension, we don't want to tackle with resources of
    // enabled one. Not using command DISABLE_USER_ACTION reason since
    // force-installed extension may not be disabled by user action.
    extension_registrar()->DisableExtension(
        kGoodCrxId, {extensions::disable_reason::DISABLE_RELOAD});

    const std::string kCorruptedContent("// corrupted\n");
    ASSERT_TRUE(base::WriteFile(resource_path, kCorruptedContent));
    ASSERT_TRUE(base::DeleteFile(
        extensions::file_util::GetComputedHashesPath(extension->path())));

    extension_registrar()->EnableExtension(kGoodCrxId);
  }

  extensions::TestContentVerifyJobObserver content_verify_job_observer;

  // Step 3: Fetch resource to trigger corruption check and wait for content
  // verify job completion.
  {
    content_verify_job_observer.ExpectJobResult(
        kGoodCrxId, kResourcePath,
        extensions::TestContentVerifyJobObserver::Result::FAILURE);

    GURL resource_url = extension->ResolveExtensionURL("script1.js");
    FetchSubresource(chrome_test_utils::GetActiveWebContents(this),
                     resource_url);

    EXPECT_TRUE(content_verify_job_observer.WaitForExpectedJobs());
  }

  // Step 4: Check that we are not going to reinstall the extension, but we have
  // detected a corruption.
  EXPECT_FALSE(CorruptedExtensionReinstaller::Get(profile())
                   ->IsReinstallForCorruptionExpected(kGoodCrxId));
  histogram_tester.ExpectUniqueSample(
      "Extensions.CorruptPolicyExtensionDetected3",
      extensions::CorruptedExtensionReinstaller::PolicyReinstallReason::
          NO_UNSIGNED_HASHES_FOR_NON_WEBSTORE_SKIP,
      1);
}

// Verifies that the extension is installed when the manifest is not fetched in
// case the remote update server is down.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionInstallForcelistServerShutDown) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  base::HistogramTester histogram_tester;
  ExtensionRequestInterceptor interceptor;

  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");

  extension_updater()->SetBackoffPolicyForTesting(
      kDefaultBackOffPolicyForTesting);

  base::FilePath extension_path(GetTestFilePath(
      base::FilePath(kTestExtensionsDir), base::FilePath(kGoodV1CrxName)));

  test_extension_cache_->AllowCaching(kGoodCrxId);
  test_extension_cache_->PutExtension(
      kGoodCrxId, "" /* expected hash, ignored by ExtensionCacheFake */,
      extension_path, "1.0", base::DoNothing());
  // Shut down test update server to make update manifest and CRX queries fail
  // with network error code net::ERR_CONNECTION_REFUSED.
  EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
  PolicyMap policies;
  AddExtensionToForceList(&policies, kGoodCrxId, url);
  extensions::TestExtensionRegistryObserver observer(registry);
  UpdateProviderPolicy(policies);

  observer.WaitForExtensionInstalled();

  EXPECT_TRUE(registry->enabled_extensions().GetByID(kGoodCrxId));

  histogram_tester.ExpectUniqueSample(
      "Extensions.ForceInstalledCacheStatus",
      extensions::ExtensionDownloaderDelegate::CacheStatus::
          CACHE_HIT_ON_MANIFEST_FETCH_FAILURE,
      1);
}

// Verifies that the extension is installed when the manifest is not fetched in
// case the device is offline. This test mimics a server providing
// ERR_INTERNET_DISCONNECTED response instead of actually having the device
// offline.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionInstallForcelistOffline) {
  // Mark as enterprise managed.
  policy::ScopedDomainEnterpriseManagement scoped_domain;
  base::HistogramTester histogram_tester;
  ExtensionRequestInterceptor interceptor;

  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");
  // This simulates inability to make network requests for fetching the
  // extension update manifest and CRX files.
  {
    interceptor.set_interceptor_hook(base::BindLambdaForTesting(
        [&](content::URLLoaderInterceptor::RequestParams* params) {
          if (params->url_request.url.path() !=
              "/extensions/good_v1_update_manifest.xml") {
            return false;
          }
          params->client->OnComplete(network::URLLoaderCompletionStatus(
              net::ERR_INTERNET_DISCONNECTED));
          return true;
        }));
  }
  extension_updater()->SetBackoffPolicyForTesting(
      kDefaultBackOffPolicyForTesting);

  base::FilePath extension_path(GetTestFilePath(
      base::FilePath(kTestExtensionsDir), base::FilePath(kGoodV1CrxName)));

  test_extension_cache_->AllowCaching(kGoodCrxId);
  test_extension_cache_->PutExtension(
      kGoodCrxId, "" /* expected hash, ignored by ExtensionCacheFake */,
      extension_path, "1.0", base::DoNothing());
  PolicyMap policies;
  AddExtensionToForceList(&policies, kGoodCrxId, url);

  extensions::TestExtensionRegistryObserver observer(registry);
  UpdateProviderPolicy(policies);
  observer.WaitForExtensionInstalled();

  EXPECT_TRUE(registry->enabled_extensions().GetByID(kGoodCrxId));

  histogram_tester.ExpectUniqueSample(
      "Extensions.ForceInstalledCacheStatus",
      extensions::ExtensionDownloaderDelegate::CacheStatus::
          CACHE_HIT_ON_MANIFEST_FETCH_FAILURE,
      1);
}

IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionInstallForcelist_DefaultedUpdateUrl) {
  // Verifies the ExtensionInstallForcelist policy with an empty (defaulted)
  // "update" URL.

  ExtensionRequestInterceptor interceptor;

  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  PolicyMap policies;
  AddExtensionToForceList(&policies, kGoodCrxId, GURL());
  extensions::TestExtensionRegistryObserver observer(registry);
  UpdateProviderPolicy(policies);
  observer.WaitForExtensionWillBeInstalled();

  EXPECT_TRUE(registry->enabled_extensions().GetByID(kGoodCrxId));
}

// Verifies that the browser doesn't crash on shutdown. If the extensions are
// being installed, and the browser is shutdown, it should not lead to a crash
// as in (crbug/1114191).
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionInstallForcelistShutdownBeforeInstall) {
  ExtensionRequestInterceptor interceptor;

  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");

  PolicyMap policies;
  AddExtensionToForceList(&policies, kGoodCrxId, url);
  UpdateProviderPolicy(policies);
  // The extension is not yet installed, shutdown the browser now and there
  // should be no crash.
}

IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionRecommendedInstallationMode) {
  // Verifies that extensions that are recommended-installed by policies are
  // installed, can be disabled but not uninstalled.

  // Recommended-installed extensions should auto-enable on install without a
  // user prompt.
  extensions::FeatureSwitch::ScopedOverride external_prompt_override(
      extensions::FeatureSwitch::prompt_for_external_extensions(), true);

  ExtensionRequestInterceptor interceptor;

  // Extensions that are force-installed come from an update URL, which defaults
  // to the webstore. Use a test URL for this test with an update manifest
  // that includes "good_v1.crx".
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");

// Mark as enterprise managed.
#if BUILDFLAG(IS_WIN)
  base::win::ScopedDomainStateForTesting scoped_domain(true);
#endif

  extensions::ExtensionRegistrar* registrar = extension_registrar();
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // Setting the forcelist extension should install "good_v1.crx".
  base::Value::Dict dict;
  dict.SetByDottedPath(std::string(kGoodCrxId) + "." +
                           extensions::schema_constants::kInstallationMode,
                       extensions::schema_constants::kNormalInstalled);
  dict.SetByDottedPath(
      std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
      url.spec());
  PolicyMap policies;
  policies.Set(key::kExtensionSettings, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(dict)), nullptr);
  extensions::TestExtensionRegistryObserver observer(registry);
  UpdateProviderPolicy(policies);
  observer.WaitForExtensionInstalled();
  EXPECT_TRUE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::ENABLED));

  // The user is not allowed to uninstall recommended-installed extensions.
  UninstallExtension(kGoodCrxId, false);

  // But the user is allowed to disable them.
  EXPECT_TRUE(registrar->IsExtensionEnabled(kGoodCrxId));
  DisableExtension(kGoodCrxId);
  EXPECT_FALSE(registrar->IsExtensionEnabled(kGoodCrxId));
}

#if BUILDFLAG(ENABLE_EXTENSIONS)
// TODO(crbug.com/394876083): Support ExtensionAllowedTypes policy on desktop
// Android.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionAllowedTypes) {
  // Verifies that extensions are blocked if policy specifies an allowed types
  // list and the extension's type is not on that list.
  extensions::ExtensionRegistry* registry = extension_registry();
  ASSERT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  ASSERT_FALSE(registry->GetExtensionById(
      kHostedAppCrxId, extensions::ExtensionRegistry::EVERYTHING));

  base::Value::List allowed_types;
  allowed_types.Append("hosted_app");
  PolicyMap policies;
  policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(allowed_types)), nullptr);
  UpdateProviderPolicy(policies);

  // "good.crx" is blocked.
  EXPECT_FALSE(InstallExtension(kGoodCrxName));
  EXPECT_FALSE(registry->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));

  // "hosted_app.crx" is of a allowlisted type.
  const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
  ASSERT_TRUE(hosted_app);
  EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
  EXPECT_EQ(hosted_app,
            registry->enabled_extensions().GetByID(kHostedAppCrxId));

  // The user can remove the extension.
  UninstallExtension(kHostedAppCrxId, true);
}

// Checks that a click on an extension CRX download triggers the extension
// installation prompt without further user interaction when the source is
// allowlisted by policy.
// TODO(crbug.com/394876083): Support ExtensionInstallSources policy on desktop
// Android.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionInstallSources) {
  extensions::ScopedTestDialogAutoConfirm auto_confirm(
      extensions::ScopedTestDialogAutoConfirm::ACCEPT);
  extensions::ScopedInstallVerifierBypassForTest install_verifier_bypass;

  ASSERT_TRUE(embedded_test_server()->Start());

  GURL download_page_url = embedded_test_server()->GetURL(
      "/policy/extension_install_sources_test.html");
  NavigateToURL(download_page_url);

  const GURL install_source_url(
      embedded_test_server()->GetURL("/extensions/*"));
  const GURL referrer_url(embedded_test_server()->GetURL("/policy/*"));

  // As long as the policy is not present, extensions are considered dangerous.
  content::DownloadTestObserverTerminal download_observer(
      profile()->GetDownloadManager(), 1,
      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
  PerformClick(chrome_test_utils::GetActiveWebContents(this), 0, 0);
  download_observer.WaitForFinished();

  // Install the policy and trigger another download.
  base::Value::List install_sources;
  install_sources.Append(install_source_url.spec());
  install_sources.Append(referrer_url.spec());
  PolicyMap policies;
  policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
               POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
               base::Value(std::move(install_sources)), nullptr);
  UpdateProviderPolicy(policies);

  extensions::TestExtensionRegistryObserver observer(extension_registry());
  PerformClick(browser()->tab_strip_model()->GetActiveWebContents(), 1, 0);
  observer.WaitForExtensionWillBeInstalled();
  // Note: Cannot check that the notification details match the expected
  // exception, since the details object has already been freed prior to
  // the completion of observer.WaitForExtensionWillBeInstalled().

  // The first extension shouldn't be present, the second should be there.
  EXPECT_FALSE(extension_registry()->GetExtensionById(
      kGoodCrxId, extensions::ExtensionRegistry::EVERYTHING));
  EXPECT_TRUE(
      extension_registry()->enabled_extensions().GetByID(kSimpleWithIconCrxId));
}
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

// Verifies that extensions with version older than the minimum version required
// by policy will get disabled, and will be auto-updated and/or re-enabled upon
// policy changes as well as regular auto-updater scheduled updates.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionMinimumVersionRequired) {
  ExtensionRequestInterceptor interceptor;

  base::AtomicRefCount update_extension_count;
  base::RunLoop first_update_extension_runloop;
  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        if (params->url_request.url.host() != "update.extension") {
          return false;
        }

        if (!update_extension_count.IsZero() &&
            !update_extension_count.IsOne()) {
          return false;
        }

        if (update_extension_count.IsZero()) {
          content::URLLoaderInterceptor::WriteResponse(
              "400 Bad request", std::string(), params->client.get());
        } else {
          content::URLLoaderInterceptor::WriteResponse(
              "chrome/test/data/extensions/good2_update_manifest.xml",
              params->client.get());
        }
        if (update_extension_count.IsZero()) {
          first_update_extension_runloop.Quit();
        }
        update_extension_count.Increment();
        return true;
      }));

  extensions::ExtensionRegistry* registry = extension_registry();
  extensions::ExtensionPrefs* extension_prefs =
      extensions::ExtensionPrefs::Get(profile());

  // Install the extension.
  EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
  EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));

  // Update policy to set a minimum version of 1.0.0.0, the extension (with
  // version 1.0.0.0) should still be enabled.
  {
    extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
    management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.0");
  }
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));

  // Update policy to set a minimum version of 1.0.0.1, the extension (with
  // version 1.0.0.0) should now be disabled.
  EXPECT_TRUE(update_extension_count.IsZero());
  {
    extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
    management_policy.SetMinimumVersionRequired(kGoodCrxId, kGoodCrxVersion);
  }
  first_update_extension_runloop.Run();
  EXPECT_TRUE(update_extension_count.IsOne());

  EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
  EXPECT_THAT(
      extension_prefs->GetDisableReasons(kGoodCrxId),
      testing::UnorderedElementsAre(
          extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY));

  // Provide a new version (1.0.0.1) which is expected to be auto updated to
  // via the update URL in the manifest of the older version.
  EXPECT_TRUE(update_extension_count.IsOne());
  {
    extensions::TestExtensionRegistryObserver update_observer(registry);
    extension_updater()->CheckSoon();
    update_observer.WaitForExtensionWillBeInstalled();
  }
  EXPECT_EQ(2, update_extension_count.SubtleRefCountForDebug());

  // The extension should be auto-updated to newer version and re-enabled.
  EXPECT_EQ(kGoodCrxVersion,
            registry->GetInstalledExtension(kGoodCrxId)->version().GetString());
  EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
}

#if BUILDFLAG(ENABLE_EXTENSIONS)
// Similar to ExtensionMinimumVersionRequired test, but with different settings
// and orders.
// TODO: Flaky on desktop Android.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionMinimumVersionRequiredAlt) {
  ExtensionRequestInterceptor interceptor;

  base::AtomicRefCount update_extension_count;
  interceptor.set_interceptor_hook(base::BindLambdaForTesting(
      [&](content::URLLoaderInterceptor::RequestParams* params) {
        if (params->url_request.url.host() == "update.extension" &&
            update_extension_count.IsZero()) {
          content::URLLoaderInterceptor::WriteResponse(
              "chrome/test/data/extensions/good2_update_manifest.xml",
              params->client.get());
          update_extension_count.Increment();
          return true;
        }
        return false;
      }));

  extensions::ExtensionRegistry* registry = extension_registry();
  extensions::ExtensionPrefs* extension_prefs =
      extensions::ExtensionPrefs::Get(profile());

  // Set the policy to require an even higher minimum version this time.
  {
    extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
    management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.2");
  }
  base::RunLoop().RunUntilIdle();

  // Install the 1.0.0.0 version, it should be installed but disabled.
  EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
  EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
  EXPECT_THAT(
      extension_prefs->GetDisableReasons(kGoodCrxId),
      testing::UnorderedElementsAre(
          extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY));
  EXPECT_EQ("1.0.0.0",
            registry->GetInstalledExtension(kGoodCrxId)->version().GetString());

  // An extension management policy update should trigger an update as well.
  EXPECT_TRUE(update_extension_count.IsZero());
  {
    extensions::TestExtensionRegistryObserver update_observer(registry);
    {
      // Set a higher minimum version, just intend to trigger a policy update.
      extensions::ExtensionManagementPolicyUpdater management_policy(
          &provider_);
      management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.3");
    }
    base::RunLoop().RunUntilIdle();
    update_observer.WaitForExtensionWillBeInstalled();
  }
  EXPECT_TRUE(update_extension_count.IsOne());

  // It should be updated to 1.0.0.1 but remain disabled.
  EXPECT_EQ(kGoodCrxVersion,
            registry->GetInstalledExtension(kGoodCrxId)->version().GetString());
  EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
  EXPECT_THAT(
      extension_prefs->GetDisableReasons(kGoodCrxId),
      testing::UnorderedElementsAre(
          extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY));

  // Remove the minimum version requirement. The extension should be re-enabled.
  {
    extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
    management_policy.UnsetMinimumVersionRequired(kGoodCrxId);
  }
  base::RunLoop().RunUntilIdle();

  EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
  EXPECT_FALSE(extension_prefs->HasDisableReason(
      kGoodCrxId,
      extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY));
}
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

// Verifies that a force-installed extension which does not meet a subsequently
// set minimum version requirement is handled well.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest,
                       ExtensionMinimumVersionForceInstalled) {
  ExtensionRequestInterceptor interceptor;

// Mark as enterprise managed.
#if BUILDFLAG(IS_WIN)
  base::win::ScopedDomainStateForTesting scoped_domain(true);
#endif
  extensions::ExtensionRegistry* registry = extension_registry();
  extensions::ExtensionPrefs* extension_prefs =
      extensions::ExtensionPrefs::Get(profile());

  // Prepare the update URL for force installing.
  ASSERT_TRUE(embedded_test_server()->Start());
  GURL url =
      embedded_test_server()->GetURL("/extensions/good_v1_update_manifest.xml");

  // Set policy to force-install the extension, it should be installed and
  // enabled.
  extensions::TestExtensionRegistryObserver install_observer(registry);
  EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
  {
    extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
    management_policy.SetIndividualExtensionAutoInstalled(kGoodCrxId,
                                                          url.spec(), true);
  }
  base::RunLoop().RunUntilIdle();
  install_observer.WaitForExtensionWillBeInstalled();

  EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));

  // Set policy a minimum version of "1.0.0.1", the extension now should be
  // disabled.
  {
    extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
    management_policy.SetMinimumVersionRequired(kGoodCrxId, kGoodCrxVersion);
  }
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
  EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
  EXPECT_THAT(
      extension_prefs->GetDisableReasons(kGoodCrxId),
      testing::UnorderedElementsAre(
          extensions::disable_reason::DISABLE_UPDATE_REQUIRED_BY_POLICY));
}

// Verifies that policy host block/allow settings are applied even when
// extension is disabled.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest, ExtensionBlockedHostWhenDisabled) {
  GURL test_url = GURL("http://www.google.com");
  std::string* error = nullptr;
  int tab_id = 1;

  const extensions::Extension* extension = InstallExtension(kGoodCrxName);
  ASSERT_TRUE(extension);
  {
    extensions::URLPatternSet new_hosts;
    new_hosts.AddOrigin(URLPattern::SCHEME_ALL, test_url);
    extension->permissions_data()->UpdateTabSpecificPermissions(
        tab_id, extensions::PermissionSet(extensions::APIPermissionSet(),
                                          extensions::ManifestPermissionSet(),
                                          std::move(new_hosts),
                                          extensions::URLPatternSet()));
  }

  ASSERT_TRUE(extension_registrar()->IsExtensionEnabled(extension->id()));

  ASSERT_TRUE(
      extension->permissions_data()->CanAccessPage(test_url, tab_id, error));

  DisableExtension(extension->id());
  {
    extensions::ExtensionManagementPolicyUpdater pref(&provider_);
    pref.AddPolicyBlockedHost(extension->id(), "*://*.google.com");
  }
  extension_registrar()->EnableExtension(extension->id());

  EXPECT_FALSE(
      extension->permissions_data()->CanAccessPage(test_url, tab_id, error));
}

#if BUILDFLAG(ENABLE_EXTENSIONS)
// Similar to ExtensionPolicyTest but sets the WebAppInstallForceList policy
// before the browser is started.
class WebAppInstallForceListPolicyTest : public ExtensionPolicyTest {
 public:
  WebAppInstallForceListPolicyTest()
      : test_page_("/banners/manifest_test_page.html") {}
  ~WebAppInstallForceListPolicyTest() override = default;
  WebAppInstallForceListPolicyTest(const WebAppInstallForceListPolicyTest&) =
      delete;
  WebAppInstallForceListPolicyTest& operator=(
      const WebAppInstallForceListPolicyTest&) = delete;

  void SetUpInProcessBrowserTestFixture() override {
    ExtensionPolicyTest::SetUpInProcessBrowserTestFixture();
    ASSERT_TRUE(embedded_test_server()->Start());

    policy_app_url_ = embedded_test_server()->GetURL(test_page_);

    base::Value::Dict item;
    item.Set("url", policy_app_url_.spec());
    item.Set("default_launch_container", "window");
    if (fallback_app_name_.has_value()) {
      item.Set("fallback_app_name", fallback_app_name_.value());
    }

    base::Value::List list;
    list.Append(std::move(item));

    PolicyMap policies;
    SetPolicy(&policies, key::kWebAppInstallForceList,
              base::Value(std::move(list)));
    provider_.UpdateChromePolicy(policies);
  }

 protected:
  std::string test_page_;
  GURL policy_app_url_;
  std::optional<std::string> fallback_app_name_;
};

IN_PROC_BROWSER_TEST_F(WebAppInstallForceListPolicyTest, StartUpInstallation) {
  const web_app::WebAppRegistrar& registrar =
      web_app::WebAppProvider::GetForTest(browser()->profile())
          ->registrar_unsafe();
  web_app::WebAppTestInstallObserver install_observer(browser()->profile());
  std::optional<webapps::AppId> app_id = registrar.FindBestAppWithUrlInScope(
      policy_app_url_,
      web_app::WebAppFilter::InstalledInOperatingSystemForTesting());
  if (!app_id) {
    app_id = install_observer.BeginListeningAndWait();
  }
  EXPECT_EQ(policy_app_url_, registrar.GetAppStartUrl(*app_id));
}

class WebAppInstallForceListPolicyWithAppFallbackNameManifestTest
    : public WebAppInstallForceListPolicyTest {
 public:
  WebAppInstallForceListPolicyWithAppFallbackNameManifestTest() {
    test_page_ = "/banners/manifest_test_page.html";
    fallback_app_name_ = "fallback app name";
  }

  ~WebAppInstallForceListPolicyWithAppFallbackNameManifestTest() override =
      default;
  WebAppInstallForceListPolicyWithAppFallbackNameManifestTest(
      const WebAppInstallForceListPolicyWithAppFallbackNameManifestTest&) =
      delete;
  WebAppInstallForceListPolicyWithAppFallbackNameManifestTest& operator=(
      const WebAppInstallForceListPolicyWithAppFallbackNameManifestTest&) =
      delete;
};

IN_PROC_BROWSER_TEST_F(
    WebAppInstallForceListPolicyWithAppFallbackNameManifestTest,
    StartUpInstallationPWAFallbackName) {
  const web_app::WebAppRegistrar& registrar =
      web_app::WebAppProvider::GetForTest(browser()->profile())
          ->registrar_unsafe();
  web_app::WebAppTestInstallObserver install_observer(browser()->profile());
  std::optional<webapps::AppId> app_id = registrar.FindBestAppWithUrlInScope(
      policy_app_url_,
      web_app::WebAppFilter::InstalledInOperatingSystemForTesting());
  if (!app_id) {
    app_id = install_observer.BeginListeningAndWait();
  }
  EXPECT_EQ(policy_app_url_, registrar.GetAppStartUrl(*app_id));

  // We specifically don't expect the fallback name to be used for a PWA
  // except for the placeholder app.
  EXPECT_NE(fallback_app_name_, registrar.GetAppShortName(*app_id));
}

// SAA == Site as App (a non-PWA installed as an app)
class WebAppInstallForceListPolicySAATest
    : public WebAppInstallForceListPolicyTest {
 public:
  WebAppInstallForceListPolicySAATest() {
    test_page_ = "/banners/no_manifest_test_page.html";
  }

  ~WebAppInstallForceListPolicySAATest() override = default;
  WebAppInstallForceListPolicySAATest(
      const WebAppInstallForceListPolicySAATest&) = delete;
  WebAppInstallForceListPolicySAATest& operator=(
      const WebAppInstallForceListPolicySAATest&) = delete;
};

IN_PROC_BROWSER_TEST_F(WebAppInstallForceListPolicySAATest,
                       StartUpInstallationSAA) {
  const web_app::WebAppRegistrar& registrar =
      web_app::WebAppProvider::GetForTest(browser()->profile())
          ->registrar_unsafe();
  web_app::WebAppTestInstallObserver install_observer(browser()->profile());
  std::optional<webapps::AppId> app_id = registrar.FindBestAppWithUrlInScope(
      policy_app_url_,
      web_app::WebAppFilter::InstalledInOperatingSystemForTesting());
  if (!app_id) {
    app_id = install_observer.BeginListeningAndWait();
  }
  EXPECT_EQ(policy_app_url_, registrar.GetAppStartUrl(*app_id));
  EXPECT_NE(fallback_app_name_, registrar.GetAppShortName(*app_id));
}

class WebAppInstallForceListPolicyWithAppFallbackNameSAATest
    : public WebAppInstallForceListPolicyTest {
 public:
  WebAppInstallForceListPolicyWithAppFallbackNameSAATest() {
    test_page_ = "/banners/no_manifest_test_page.html";
    fallback_app_name_ = "fallback app name";
  }

  ~WebAppInstallForceListPolicyWithAppFallbackNameSAATest() override = default;
  WebAppInstallForceListPolicyWithAppFallbackNameSAATest(
      const WebAppInstallForceListPolicyWithAppFallbackNameSAATest&) = delete;
  WebAppInstallForceListPolicyWithAppFallbackNameSAATest& operator=(
      const WebAppInstallForceListPolicyWithAppFallbackNameSAATest&) = delete;
};

IN_PROC_BROWSER_TEST_F(WebAppInstallForceListPolicyWithAppFallbackNameSAATest,
                       StartUpInstallationSAAFallbackName) {
  const web_app::WebAppRegistrar& registrar =
      web_app::WebAppProvider::GetForTest(browser()->profile())
          ->registrar_unsafe();
  web_app::WebAppTestInstallObserver install_observer(browser()->profile());
  std::optional<webapps::AppId> app_id = registrar.FindBestAppWithUrlInScope(
      policy_app_url_,
      web_app::WebAppFilter::InstalledInOperatingSystemForTesting());
  if (!app_id) {
    app_id = install_observer.BeginListeningAndWait();
  }
  EXPECT_EQ(policy_app_url_, registrar.GetAppStartUrl(*app_id));
  EXPECT_EQ(fallback_app_name_, registrar.GetAppShortName(*app_id));
}

class WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest
    : public WebAppInstallForceListPolicyTest {
 public:
  WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest() {
    test_page_ = "/close-socket";
    fallback_app_name_ = "fallback app name";
  }

  ~WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest() override =
      default;
  WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest(
      const WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest&) =
      delete;
  WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest& operator=(
      const WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest&) =
      delete;
};

IN_PROC_BROWSER_TEST_F(
    WebAppInstallForceListPolicyPlaceholderWithAppFallbackNameTest,
    StartUpInstallationPlaceholderFallbackName) {
  const web_app::WebAppRegistrar& registrar =
      web_app::WebAppProvider::GetForTest(browser()->profile())
          ->registrar_unsafe();
  web_app::WebAppTestInstallWithOsHooksObserver install_observer(
      browser()->profile());
  std::optional<webapps::AppId> app_id = registrar.FindBestAppWithUrlInScope(
      policy_app_url_,
      web_app::WebAppFilter::InstalledInOperatingSystemForTesting());
  if (!app_id) {
    app_id = install_observer.BeginListeningAndWait();
  }
  EXPECT_EQ(policy_app_url_, registrar.GetAppStartUrl(*app_id));
  EXPECT_EQ(fallback_app_name_, registrar.GetAppShortName(*app_id));
  ASSERT_TRUE(registrar
                  .LookupPlaceholderAppId(policy_app_url_,
                                          web_app::WebAppManagement::kPolicy)
                  .has_value());
}

// Fixture for tests that have two profiles with a different policy for each.
// TODO(crbug.com/394876083): Add test when multiple profiles are supported on
// desktop Android.
class ExtensionPolicyTest2Contexts : public PolicyTest {
 public:
  ExtensionPolicyTest2Contexts() = default;
  ExtensionPolicyTest2Contexts(const ExtensionPolicyTest2Contexts& other) =
      delete;
  ~ExtensionPolicyTest2Contexts() override = default;

 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
#if BUILDFLAG(IS_CHROMEOS)
    command_line->AppendSwitch(
        ash::switches::kIgnoreUserProfileMappingForTests);
#endif
    PolicyTest::SetUpCommandLine(command_line);
  }

  void SetUp() override {
    PolicyTest::SetUp();
    test_extension_cache1_ = std::make_unique<extensions::ExtensionCacheFake>();
    test_extension_cache2_ = std::make_unique<extensions::ExtensionCacheFake>();
  }

  void TearDown() override {
    test_extension_cache1_.reset();
    test_extension_cache2_.reset();
    PolicyTest::TearDown();
  }

  void SetUpInProcessBrowserTestFixture() override {
    PolicyTest::SetUpInProcessBrowserTestFixture();
    ON_CALL(profile1_policy_, IsInitializationComplete(testing::_))
        .WillByDefault(testing::Return(true));
    ON_CALL(profile1_policy_, IsFirstPolicyLoadComplete(testing::_))
        .WillByDefault(testing::Return(true));
    policy::PushProfilePolicyConnectorProviderForTesting(&profile1_policy_);
  }

  void SetUpOnMainThread() override {
    PolicyTest::SetUpOnMainThread();
    profile1_ = chrome_test_utils::GetProfile(this);

    profile2_ = CreateProfile(&profile2_policy_);

    extensions::ExtensionUpdater::Get(profile1_)->SetExtensionCacheForTesting(
        test_extension_cache1_.get());
    extensions::ExtensionUpdater::Get(profile1_)->SetExtensionCacheForTesting(
        test_extension_cache2_.get());
    registrar1_ = extensions::ExtensionRegistrar::Get(profile1_);
    registrar2_ = extensions::ExtensionRegistrar::Get(profile2_);
    registry1_ = CreateExtensionRegistry(profile1_);
    registry2_ = CreateExtensionRegistry(profile2_);
  }

  void TearDownOnMainThread() override {
    registry2_ = nullptr;
    registry1_ = nullptr;
    registrar2_ = nullptr;
    registrar1_ = nullptr;
    profile2_ = nullptr;
    profile1_ = nullptr;
    PolicyTest::TearDownOnMainThread();
  }

 protected:
  void SetTabSpecificPermissionsForURL(const extensions::Extension* extension,
                                       int tab_id,
                                       const GURL& url,
                                       int url_scheme) {
    extensions::URLPatternSet new_hosts;
    new_hosts.AddOrigin(url_scheme, url);
    extension->permissions_data()->UpdateTabSpecificPermissions(
        tab_id, extensions::PermissionSet(extensions::APIPermissionSet(),
                                          extensions::ManifestPermissionSet(),
                                          std::move(new_hosts),
                                          extensions::URLPatternSet()));
  }

  MockConfigurationPolicyProvider* GetProfile1Policy() {
    return &profile1_policy_;
  }
  MockConfigurationPolicyProvider* GetProfile2Policy() {
    return &profile2_policy_;
  }
  Profile* GetProfile1() { return profile1_; }
  Profile* GetProfile2() { return profile2_; }
  extensions::ExtensionRegistrar* GetExtensionRegistrar1() {
    return registrar1_;
  }
  extensions::ExtensionRegistrar* GetExtensionRegistrar2() {
    return registrar2_;
  }
  extensions::ExtensionRegistry* GetExtensionRegistry1() { return registry1_; }
  extensions::ExtensionRegistry* GetExtensionRegistry2() { return registry2_; }

 private:
  // Creates a Profile for testing. The Profile is returned.
  // The policy for the profile has to be passed via policy_for_profile.
  // This method is called from SetUp and only from there.
  Profile* CreateProfile(MockConfigurationPolicyProvider* policy_for_profile) {
    ON_CALL(*policy_for_profile, IsInitializationComplete(testing::_))
        .WillByDefault(testing::Return(true));
    ON_CALL(*policy_for_profile, IsFirstPolicyLoadComplete(testing::_))
        .WillByDefault(testing::Return(true));
    policy::PushProfilePolicyConnectorProviderForTesting(policy_for_profile);

    ProfileManager* profile_manager = g_browser_process->profile_manager();
    base::FilePath path_profile =
        profile_manager->GenerateNextProfileDirectoryPath();
    // Create an additional profile.
    return &profiles::testing::CreateProfileSync(profile_manager, path_profile);
  }

  extensions::ExtensionRegistry* CreateExtensionRegistry(
      content::BrowserContext* context) {
    return extensions::ExtensionRegistry::Get(context);
  }

  std::unique_ptr<extensions::ExtensionCacheFake> test_extension_cache1_;
  std::unique_ptr<extensions::ExtensionCacheFake> test_extension_cache2_;
  extensions::ScopedIgnoreContentVerifierForTest ignore_content_verifier_;
  raw_ptr<Profile> profile1_ = nullptr;
  raw_ptr<Profile> profile2_ = nullptr;
  MockConfigurationPolicyProvider profile1_policy_;
  MockConfigurationPolicyProvider profile2_policy_;
  raw_ptr<extensions::ExtensionRegistrar> registrar1_ = nullptr;
  raw_ptr<extensions::ExtensionRegistrar> registrar2_ = nullptr;
  raw_ptr<extensions::ExtensionRegistry> registry1_ = nullptr;
  raw_ptr<extensions::ExtensionRegistry> registry2_ = nullptr;

  // TODO(https://crbug.com/40804030): Remove this when updated to use MV3.
  extensions::ScopedTestMV2Enabler mv2_enabler_;
};

// Verifies that default policy host block/allow settings are applied as
// expected.
IN_PROC_BROWSER_TEST_F(ExtensionPolicyTest2Contexts,
                       ExtensionDefaultPolicyBlockedHost) {
  GURL test_url = GURL("http://www.google.com");
  std::string* error = nullptr;
  int tab_id = 1;

  const extensions::Extension* app1 =
      InstallExtensionWithContext(kGoodCrxName, GetProfile1());
  ASSERT_TRUE(app1);
  const extensions::Extension* app2 =
      InstallExtensionWithContext(kGoodCrxName, GetProfile2());
  ASSERT_TRUE(app2);
  SetTabSpecificPermissionsForURL(app1, tab_id, test_url,
                                  URLPattern::SCHEME_ALL);
  SetTabSpecificPermissionsForURL(app2, tab_id, test_url,
                                  URLPattern::SCHEME_ALL);

  ASSERT_TRUE(GetExtensionRegistrar1()->IsExtensionEnabled(app1->id()));
  ASSERT_TRUE(GetExtensionRegistrar2()->IsExtensionEnabled(app2->id()));

  ASSERT_TRUE(app1->permissions_data()->CanAccessPage(test_url, tab_id, error));
  ASSERT_TRUE(app2->permissions_data()->CanAccessPage(test_url, tab_id, error));

  {
    extensions::ExtensionManagementPolicyUpdater pref(GetProfile1Policy());
    pref.AddPolicyBlockedHost("*", "*://*.google.com");
  }

  EXPECT_FALSE(
      app1->permissions_data()->CanAccessPage(test_url, tab_id, error));
  EXPECT_TRUE(app2->permissions_data()->CanAccessPage(test_url, tab_id, error));
}
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

}  // namespace policy