File: developer_private_api_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (3861 lines) | stat: -rw-r--r-- 160,865 bytes parent folder | download | duplicates (2)
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
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
// Copyright 2015 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 <optional>
#include <string_view>
#include <utility>

#include "base/base_paths.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/json/json_writer.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "base/path_service.h"
#include "base/scoped_observation.h"
#include "base/stl_util.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/values_test_util.h"
#include "base/values.h"
#include "chrome/browser/extensions/account_extension_tracker.h"
#include "chrome/browser/extensions/api/developer_private/developer_private_functions.h"
#include "chrome/browser/extensions/api/developer_private/extension_info_generator.h"
#include "chrome/browser/extensions/api/developer_private/profile_info_generator.h"
#include "chrome/browser/extensions/chrome_test_extension_loader.h"
#include "chrome/browser/extensions/error_console/error_console.h"
#include "chrome/browser/extensions/extension_action_test_util.h"
#include "chrome/browser/extensions/extension_install_prompt_show_params.h"
#include "chrome/browser/extensions/extension_management.h"
#include "chrome/browser/extensions/extension_management_test_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_service_test_with_install.h"
#include "chrome/browser/extensions/extension_sync_data.h"
#include "chrome/browser/extensions/extension_sync_service.h"
#include "chrome/browser/extensions/extension_sync_util.h"
#include "chrome/browser/extensions/extension_util.h"
#include "chrome/browser/extensions/external_provider_manager.h"
#include "chrome/browser/extensions/manifest_v2_experiment_manager.h"
#include "chrome/browser/extensions/permissions/permissions_test_util.h"
#include "chrome/browser/extensions/permissions/permissions_updater.h"
#include "chrome/browser/extensions/permissions/scripting_permissions_modifier.h"
#include "chrome/browser/extensions/permissions/site_permissions_helper.h"
#include "chrome/browser/extensions/signin_test_util.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h"
#include "chrome/browser/supervised_user/supervised_user_browser_utils.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/extension_install_ui.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_model.h"
#include "chrome/common/extensions/api/developer_private.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/test_browser_window.h"
#include "components/crx_file/id_util.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "components/signin/public/base/signin_pref_names.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/supervised_user/core/common/features.h"
#include "components/sync/test/fake_sync_change_processor.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/test/mock_render_process_host.h"
#include "content/public/test/web_contents_tester.h"
#include "extensions/browser/api_test_utils.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/extension_dialog_auto_confirm.h"
#include "extensions/browser/extension_error_test_util.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
#include "extensions/browser/extension_util.h"
#include "extensions/browser/mock_external_provider.h"
#include "extensions/browser/permissions_manager.h"
#include "extensions/browser/test_event_router_observer.h"
#include "extensions/browser/test_extension_registry_observer.h"
#include "extensions/browser/user_script_manager.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "extensions/common/extension_features.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/extension_urls.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/mojom/context_type.mojom.h"
#include "extensions/common/permissions/permission_set.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/test/test_extension_dir.h"
#include "services/data_decoder/data_decoder_service.h"
#include "services/service_manager/public/cpp/test/test_connector_factory.h"
#include "ui/shell_dialogs/selected_file_info.h"

namespace extensions {

namespace {

const char kGoodCrx[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
const char kGoogleOnlyCrx[] = "jjlcocfpfbknlbgijblaapbcpbdglkhf";
constexpr char kInvalidHost[] = "invalid host";
constexpr char kInvalidHostError[] = "Invalid host.";

std::unique_ptr<KeyedService> BuildAPI(content::BrowserContext* context) {
  return std::make_unique<DeveloperPrivateAPI>(context);
}

std::unique_ptr<KeyedService> BuildEventRouter(
    content::BrowserContext* profile) {
  return std::make_unique<EventRouter>(profile, ExtensionPrefs::Get(profile));
}

bool HasPrefsPermission(bool (*has_pref)(const ExtensionId&,
                                         content::BrowserContext*),
                        content::BrowserContext* context,
                        const ExtensionId& id) {
  return has_pref(id, context);
}

bool DoesItemChangedEventMatch(
    const Event& event,
    const ExtensionId& extension_id,
    const api::developer_private::EventType event_type,
    api::developer_private::ExtensionInfo* info_from_event) {
  CHECK_GE(1u, event.event_args.size());
  std::optional<api::developer_private::EventData> event_data =
      api::developer_private::EventData::FromValue(event.event_args[0]);
  if (!event_data) {
    return false;
  }

  if (event_data->item_id != extension_id ||
      event_data->event_type != event_type) {
    return false;
  }

  if (event_data->extension_info) {
    CHECK_EQ(extension_id, event_data->extension_info->id);
    *info_from_event = std::move(*event_data->extension_info);
  }

  return true;
}

bool WasItemChangedEventDispatched(
    const TestEventRouterObserver& observer,
    const ExtensionId& extension_id,
    const api::developer_private::EventType event_type) {
  const std::string kEventName =
      api::developer_private::OnItemStateChanged::kEventName;
  const auto& event_map = observer.events();
  auto iter = event_map.find(kEventName);
  if (iter == event_map.end()) {
    return false;
  }

  api::developer_private::ExtensionInfo info;
  return DoesItemChangedEventMatch(*iter->second, extension_id, event_type,
                                   &info);
}

bool WasUserSiteSettingsChangedEventDispatched(
    const TestEventRouterObserver& observer,
    api::developer_private::UserSiteSettings* settings) {
  const std::string kEventName =
      api::developer_private::OnUserSiteSettingsChanged::kEventName;
  const auto& event_map = observer.events();
  auto iter = event_map.find(kEventName);
  if (iter == event_map.end()) {
    return false;
  }

  const Event& event = *iter->second;
  CHECK_GE(1u, event.event_args.size());
  auto site_settings =
      api::developer_private::UserSiteSettings::FromValue(event.event_args[0]);
  if (!site_settings) {
    return false;
  }

  *settings = std::move(*site_settings);
  return true;
}

void AddUserSpecifiedSites(Profile* profile,
                           const std::string& hosts,
                           bool restricted) {
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateAddUserSpecifiedSitesFunction>();
  std::string args = base::StringPrintf(
      R"([{"siteSet":"%s","hosts":%s}])",
      restricted ? "USER_RESTRICTED" : "USER_PERMITTED", hosts.c_str());
  EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile))
      << function->GetError();
}

void RemoveUserSpecifiedSites(Profile* profile,
                              const std::string& hosts,
                              bool restricted) {
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateRemoveUserSpecifiedSitesFunction>();
  std::string args = base::StringPrintf(
      R"([{"siteSet":"%s","hosts":%s}])",
      restricted ? "USER_RESTRICTED" : "USER_PERMITTED", hosts.c_str());
  EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile))
      << function->GetError();
}

void AddExtensionAndGrantPermissions(Profile* profile,
                                     ExtensionRegistrar* registrar,
                                     const Extension& extension) {
  PermissionsUpdater updater(profile);
  updater.InitializePermissions(&extension);
  updater.GrantActivePermissions(&extension);
  registrar->AddExtension(&extension);
}

void RunAddHostPermission(Profile* profile,
                          const Extension& extension,
                          std::string_view host,
                          bool should_succeed,
                          const char* expected_error) {
  SCOPED_TRACE(host);
  auto function =
      base::MakeRefCounted<api::DeveloperPrivateAddHostPermissionFunction>();

  std::string args = base::StringPrintf(
      R"(["%s", "%s"])", extension.id().c_str(), std::string(host).c_str());
  if (should_succeed) {
    EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile))
        << function->GetError();
  } else {
    EXPECT_EQ(expected_error, api_test_utils::RunFunctionAndReturnError(
                                  function.get(), args, profile));
  }
}

void GetMatchingExtensionsForSite(
    Profile* profile,
    const std::string& site,
    std::vector<api::developer_private::MatchingExtensionInfo>* infos) {
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateGetMatchingExtensionsForSiteFunction>();
  EXPECT_TRUE(api_test_utils::RunFunction(
      function.get(), base::StringPrintf(R"(["%s"])", site.c_str()), profile))
      << function->GetError();
  const base::Value::List* results = function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());
  ASSERT_TRUE((*results)[0].is_list());

  infos->clear();
  for (const auto& value : (*results)[0].GetList()) {
    ASSERT_TRUE(value.is_dict());
    infos->push_back(std::move(
        *api::developer_private::MatchingExtensionInfo::FromValue(value)));
  }
}

auto MatchMatchingExtensionInfo(
    const ExtensionId& extension_id,
    const api::developer_private::HostAccess& host_access,
    bool can_request_all_sites) {
  return testing::AllOf(
      testing::Field(&api::developer_private::MatchingExtensionInfo::id,
                     extension_id),
      testing::Field(
          &api::developer_private::MatchingExtensionInfo::site_access,
          host_access),
      testing::Field(
          &api::developer_private::MatchingExtensionInfo::can_request_all_sites,
          can_request_all_sites));
}

api::developer_private::ExtensionSiteAccessUpdate CreateSiteAccessUpdate(
    const ExtensionId& id,
    api::developer_private::HostAccess access) {
  api::developer_private::ExtensionSiteAccessUpdate update;
  update.id = id;
  update.site_access = access;
  return update;
}

void UpdateSiteAccess(
    Profile* profile,
    const std::string& site,
    const std::vector<api::developer_private::ExtensionSiteAccessUpdate>&
        updates) {
  base::Value::List update_entries;
  update_entries.reserve(updates.size());
  for (const auto& update : updates) {
    update_entries.Append(update.ToValue());
  }
  std::string updates_arg;
  EXPECT_TRUE(base::JSONWriter::Write(update_entries, &updates_arg));

  scoped_refptr<ExtensionFunction> function =
      base::MakeRefCounted<api::DeveloperPrivateUpdateSiteAccessFunction>();
  EXPECT_TRUE(api_test_utils::RunFunction(
      function.get(),
      base::StringPrintf(R"(["%s", %s])", site.c_str(), updates_arg.c_str()),
      profile))
      << function->GetError();
}

// A more targeted version of TestEventRouterObserver to pick up a prefs changed
// event for a given extension.
class ItemStatePrefsChangedObserver : public EventRouter::TestObserver {
 public:
  ItemStatePrefsChangedObserver(EventRouter* event_router,
                                const ExtensionId& extension_id);

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

  ~ItemStatePrefsChangedObserver() override;

  // Waits until a matching prefs changed event is dispatched for the
  // `extension_id_`.
  void WaitForEvent();

  // Resets the `event_info_` so the observer can wait for another matching
  // event.
  void Reset();

  bool WasEventDispatched() { return event_info_.has_value(); }

  api::developer_private::ExtensionInfo event_info() {
    return event_info_.has_value() ? event_info_->Clone()
                                   : api::developer_private::ExtensionInfo();
  }

 private:
  // EventRouter::TestObserver:
  void OnWillDispatchEvent(const Event& event) override;
  void OnDidDispatchEventToProcess(const Event& event,
                                   int process_id) override {}

  // The event info from the prefs changed event. Null if a matching event has
  // not yet been dispatched.
  std::optional<api::developer_private::ExtensionInfo> event_info_;
  std::unique_ptr<base::RunLoop> run_loop_;

  raw_ptr<EventRouter> event_router_;
  const ExtensionId extension_id_;
};

ItemStatePrefsChangedObserver::ItemStatePrefsChangedObserver(
    EventRouter* event_router,
    const ExtensionId& extension_id)
    : event_router_(event_router), extension_id_(extension_id) {
  event_router_->AddObserverForTesting(this);
}

ItemStatePrefsChangedObserver::~ItemStatePrefsChangedObserver() {
  // Note: can't use ScopedObserver<> here because the method is
  // RemoveObserverForTesting() instead of RemoveObserver().
  event_router_->RemoveObserverForTesting(this);
}

void ItemStatePrefsChangedObserver::WaitForEvent() {
  while (!event_info_.has_value()) {
    // Create a new `RunLoop` since reuse is not supported.
    run_loop_ = std::make_unique<base::RunLoop>();
    run_loop_->Run();
    run_loop_.reset();
  }
}

void ItemStatePrefsChangedObserver::Reset() {
  event_info_ = std::nullopt;
}

void ItemStatePrefsChangedObserver::OnWillDispatchEvent(const Event& event) {
  CHECK(!event.event_name.empty());

  api::developer_private::ExtensionInfo info;
  bool does_event_match = DoesItemChangedEventMatch(
      event, extension_id_, api::developer_private::EventType::kPrefsChanged,
      &info);

  if (does_event_match) {
    event_info_ = std::move(info);
    if (run_loop_) {
      run_loop_->Quit();
    }
  }
}

}  // namespace

// TODO(crbug.com/408458901): Port these tests to desktop Android when we have
// a testing base class for extensions that doesn't use ExtensionService.
class DeveloperPrivateApiUnitTest : public ExtensionServiceTestWithInstall {
 public:
  DeveloperPrivateApiUnitTest(const DeveloperPrivateApiUnitTest&) = delete;
  DeveloperPrivateApiUnitTest& operator=(const DeveloperPrivateApiUnitTest&) =
      delete;

 protected:
  DeveloperPrivateApiUnitTest() = default;
  ~DeveloperPrivateApiUnitTest() override = default;

  // ExtensionServiceTestBase:
  void SetUp() override;
  void TearDown() override;

  ExternalProviderManager* external_provider_manager() {
    return ExternalProviderManager::Get(profile());
  }

  void AddMockExternalProvider(
      std::unique_ptr<ExternalProviderInterface> provider) {
    external_provider_manager()->AddProviderForTesting(std::move(provider));
  }

  // A wrapper around api_test_utils::RunFunction that runs with
  // the associated browser, no flags, and can take stack-allocated arguments.
  bool RunFunction(const scoped_refptr<ExtensionFunction>& function,
                   const base::Value::List& args);

  // Loads an unpacked extension that is backed by a real directory, allowing
  // it to be reloaded.
  const Extension* LoadUnpackedExtension();

  // Loads an extension with no real directory; this is faster, but means the
  // extension can't be reloaded.
  const Extension* LoadSimpleExtension();

  // Tests modifying the extension's configuration.
  void TestExtensionPrefSetting(const base::RepeatingCallback<bool()>& has_pref,
                                const std::string& key,
                                const ExtensionId& extension_id,
                                bool expected_default_value);

  testing::AssertionResult TestPackExtensionFunction(
      const base::Value::List& args,
      api::developer_private::PackStatus expected_status,
      int expected_flags);

  // Execute the updateProfileConfiguration API call with a specified
  // dev_mode. This is done from the webui when the user checks the
  // "Developer Mode" checkbox.
  void UpdateProfileConfigurationDevMode(bool dev_mode);

  // Execute the getProfileConfiguration API and parse its result into a
  // ProfileInfo structure for further verification in the calling test.
  // Will reset the profile_info unique_ptr.
  // Uses ASSERT_* inside - callers should use ASSERT_NO_FATAL_FAILURE.
  void GetProfileConfiguration(
      std::optional<api::developer_private::ProfileInfo>* profile_info);

  // Runs the API function to update host access for the given |extension| to
  // |new_access|.
  void RunUpdateHostAccess(const Extension& extension,
                           std::string_view new_access);

  virtual bool ProfileIsSupervised() const { return false; }

  Browser* browser() { return browser_.get(); }

  content::RenderProcessHost* render_process_host() const {
    return render_process_host_.get();
  }

 private:
  base::test::ScopedFeatureList feature_list_;
  // This test does not create a root window. Because of this,
  // ScopedDisableRootChecking needs to be used (which disables the root window
  // check).
  test::ScopedDisableRootChecking disable_root_checking_;

  // The browser (and accompanying window).
  std::unique_ptr<TestBrowserWindow> browser_window_;
  std::unique_ptr<Browser> browser_;
  std::unique_ptr<content::RenderProcessHost> render_process_host_;

  std::vector<TestExtensionDir> test_extension_dirs_;
};

bool DeveloperPrivateApiUnitTest::RunFunction(
    const scoped_refptr<ExtensionFunction>& function,
    const base::Value::List& args) {
  return api_test_utils::RunFunction(function.get(), args.Clone(), profile(),
                                     api_test_utils::FunctionMode::kNone);
}

const Extension* DeveloperPrivateApiUnitTest::LoadUnpackedExtension() {
  constexpr char kManifest[] =
      R"({
           "name": "foo",
           "version": "1.0",
           "manifest_version": 3,
           "permissions": ["userScripts"],
           "host_permissions": ["*://*/*"]
         })";

  test_extension_dirs_.emplace_back();
  TestExtensionDir& dir = test_extension_dirs_.back();
  dir.WriteManifest(kManifest);

  ChromeTestExtensionLoader loader(profile());
  // The fact that unpacked extensions get file access by default is an
  // irrelevant detail to these tests. Disable it.
  loader.set_allow_file_access(false);

  return loader.LoadExtension(dir.UnpackedPath()).get();
}

const Extension* DeveloperPrivateApiUnitTest::LoadSimpleExtension() {
  const char kName[] = "extension name";
  const char kVersion[] = "1.0.0.1";
  ExtensionId id = crx_file::id_util::GenerateId(kName);
  auto manifest = base::Value::Dict()
                      .Set("name", kName)
                      .Set("version", kVersion)
                      .Set("manifest_version", 2)
                      .Set("description", "an extension");
  scoped_refptr<const Extension> extension =
      ExtensionBuilder()
          .SetManifest(std::move(manifest))
          .SetLocation(mojom::ManifestLocation::kInternal)
          .SetID(id)
          .Build();
  registrar()->AddExtension(extension.get());
  return extension.get();
}

void DeveloperPrivateApiUnitTest::TestExtensionPrefSetting(
    const base::RepeatingCallback<bool()>& has_pref,
    const std::string& key,
    const ExtensionId& extension_id,
    bool expected_default_value) {
  EXPECT_EQ(expected_default_value, has_pref.Run()) << key;

  {
    base::Value::Dict parameters;
    parameters.Set("extensionId", extension_id);
    parameters.Set(key, true);

    base::Value::List args;
    args.Append(std::move(parameters));
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateUpdateExtensionConfigurationFunction>();
    EXPECT_FALSE(RunFunction(function, args)) << key;
    EXPECT_EQ("This action requires a user gesture.", function->GetError());

    function = base::MakeRefCounted<
        api::DeveloperPrivateUpdateExtensionConfigurationFunction>();
    function->set_source_context_type(mojom::ContextType::kWebUi);
    EXPECT_TRUE(RunFunction(function, args)) << key;
    EXPECT_TRUE(has_pref.Run()) << key;
  }

  {
    base::Value::Dict parameters;
    parameters.Set("extensionId", extension_id);
    parameters.Set(key, false);

    base::Value::List args;
    args.Append(std::move(parameters));

    ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture;
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateUpdateExtensionConfigurationFunction>();
    EXPECT_TRUE(RunFunction(function, args)) << key;
    EXPECT_FALSE(has_pref.Run()) << key;
  }

  {
    base::Value::Dict parameters;
    parameters.Set("extensionId", extension_id);
    parameters.Set(key, true);

    base::Value::List args;
    args.Append(std::move(parameters));

    ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture;
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateUpdateExtensionConfigurationFunction>();
    EXPECT_TRUE(RunFunction(function, args)) << key;
    EXPECT_TRUE(has_pref.Run()) << key;
  }
}

testing::AssertionResult DeveloperPrivateApiUnitTest::TestPackExtensionFunction(
    const base::Value::List& args,
    api::developer_private::PackStatus expected_status,
    int expected_flags) {
  auto function =
      base::MakeRefCounted<api::DeveloperPrivatePackDirectoryFunction>();
  if (!RunFunction(function, args)) {
    return testing::AssertionFailure() << "Could not run function.";
  }

  // Extract the result. We don't have to test this here, since it's verified as
  // part of the general extension api system.
  const base::Value& response_value = (*function->GetResultListForTest())[0];
  std::optional<api::developer_private::PackDirectoryResponse> response =
      api::developer_private::PackDirectoryResponse::FromValue(response_value);
  CHECK(response);

  if (response->status != expected_status) {
    return testing::AssertionFailure()
           << "Expected status: "
           << api::developer_private::ToString(expected_status)
           << ", found status: "
           << api::developer_private::ToString(response->status)
           << ", message: " << response->message;
  }

  if (response->override_flags != expected_flags) {
    return testing::AssertionFailure()
           << "Expected flags: " << expected_flags
           << ", found flags: " << response->override_flags;
  }

  return testing::AssertionSuccess();
}

void DeveloperPrivateApiUnitTest::UpdateProfileConfigurationDevMode(
    bool dev_mode) {
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateUpdateProfileConfigurationFunction>();
  base::Value::List args = base::Value::List().Append(
      base::Value::Dict().Set("inDeveloperMode", dev_mode));
  EXPECT_TRUE(RunFunction(function, args)) << function->GetError();
}

void DeveloperPrivateApiUnitTest::GetProfileConfiguration(
    std::optional<api::developer_private::ProfileInfo>* profile_info) {
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateGetProfileConfigurationFunction>();
  base::Value::List args;
  EXPECT_TRUE(RunFunction(function, args)) << function->GetError();

  ASSERT_TRUE(function->GetResultListForTest());
  ASSERT_EQ(1u, function->GetResultListForTest()->size());
  const base::Value& response_value = (*function->GetResultListForTest())[0];
  *profile_info =
      api::developer_private::ProfileInfo::FromValue(response_value);
}

void DeveloperPrivateApiUnitTest::RunUpdateHostAccess(
    const Extension& extension,
    std::string_view new_access) {
  SCOPED_TRACE(new_access);
  ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture;
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateUpdateExtensionConfigurationFunction>();
  std::string args =
      base::StringPrintf(R"([{"extensionId": "%s", "hostAccess": "%s"}])",
                         extension.id().c_str(), new_access.data());
  EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile()))
      << function->GetError();
}

void DeveloperPrivateApiUnitTest::SetUp() {
  ExtensionServiceTestBase::SetUp();

  ExtensionServiceInitParams init_params;
  init_params.profile_is_supervised = ProfileIsSupervised();
  InitializeExtensionService(std::move(init_params));
  extension_action_test_util::CreateToolbarModelForProfile(profile());

  browser_window_ = std::make_unique<TestBrowserWindow>();
  Browser::CreateParams params(profile(), true);
  params.type = Browser::TYPE_NORMAL;
  params.window = browser_window_.get();
  browser_.reset(Browser::Create(params));

  // Allow the API to be created.
  EventRouterFactory::GetInstance()->SetTestingFactory(
      profile(), base::BindRepeating(&BuildEventRouter));

  DeveloperPrivateAPI::GetFactoryInstance()->SetTestingFactory(
      profile(), base::BindRepeating(&BuildAPI));

  // Loading unpacked extensions through the developerPrivate API requires
  // developer mode to be enabled.
  profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);
  render_process_host_ =
      std::make_unique<content::MockRenderProcessHost>(profile());
}

void DeveloperPrivateApiUnitTest::TearDown() {
  test_extension_dirs_.clear();
  browser_.reset();
  browser_window_.reset();
  render_process_host_.reset();
  ExtensionServiceTestBase::TearDown();
}

// Test developerPrivate.updateExtensionConfiguration.
TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateUpdateExtensionConfiguration) {
  // Sadly, we need a "real" directory here, because toggling prefs causes
  // a reload (which needs a path).
  const Extension* extension = LoadUnpackedExtension();
  const ExtensionId& id = extension->id();

  ScriptingPermissionsModifier(profile(), base::WrapRefCounted(extension))
      .SetWithholdHostPermissions(true);

  // Test pinning to toolbar first as this needs the extension to be enabled.
  // The other pref settings tested below may disable the extension so it will
  // not have an action in the toolbar.
  auto pinned_to_toolbar = [&]() {
    ToolbarActionsModel* toolbar_actions_model =
        ToolbarActionsModel::Get(profile());
    return toolbar_actions_model->HasAction(id) &&
           toolbar_actions_model->IsActionPinned(id);
  };
  TestExtensionPrefSetting(base::BindLambdaForTesting(pinned_to_toolbar),
                           "pinnedToToolbar", id,
                           /*expected_default_value=*/false);

  TestExtensionPrefSetting(
      base::BindRepeating(&HasPrefsPermission, &util::IsIncognitoEnabled,
                          profile(), id),
      "incognitoAccess", id, /*expected_default_value=*/false);
  TestExtensionPrefSetting(
      base::BindRepeating(&HasPrefsPermission, &util::AllowFileAccess,
                          profile(), id),
      "fileAccess", id, /*expected_default_value=*/false);

  // Test userScriptsAccess pref.
  auto* extension_system =
      static_cast<TestExtensionSystem*>(ExtensionSystem::Get(profile()));
  ASSERT_TRUE(extension_system);
  extension_system->CreateUserScriptManager();
  UserScriptManager* user_script_manager =
      extension_system->user_script_manager();
  ASSERT_TRUE(user_script_manager);
  auto user_scripts_enabled = [&]() {
    return user_script_manager->IsUserScriptPrefEnabledForTesting(id);
  };
  TestExtensionPrefSetting(base::BindLambdaForTesting(user_scripts_enabled),
                           "userScriptsAccess", id,
                           /*expected_default_value=*/false);

  SitePermissionsHelper helper(profile());
  TestExtensionPrefSetting(
      base::BindRepeating(&SitePermissionsHelper::ShowAccessRequestsInToolbar,
                          base::Unretained(&helper), id),
      "showAccessRequestsInToolbar", id, /*expected_default_value=*/true);

  // Check to ensure the `kPrefAcknowledgeSafetyCheckWarningReason` is not
  // set yet.
  int warning_reason = 0;
  ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile());
  EXPECT_FALSE(extension_prefs->ReadPrefAsInteger(
      id, extensions::kPrefAcknowledgeSafetyCheckWarningReason,
      &warning_reason));

  // Test `acknowledgeSafetyCheckWarningReason` pref.
  base::Value::List args;
  args.Append(base::Value::Dict()
                  .Set("extensionId", id)
                  .Set("acknowledgeSafetyCheckWarningReason", "MALWARE"));

  ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture;
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateUpdateExtensionConfigurationFunction>();
  EXPECT_TRUE(RunFunction(function, args));

  extension_prefs->ReadPrefAsInteger(
      id, extensions::kPrefAcknowledgeSafetyCheckWarningReason,
      &warning_reason);
  api::developer_private::SafetyCheckWarningReason warning_reason_enum =
      static_cast<api::developer_private::SafetyCheckWarningReason>(
          warning_reason);
  EXPECT_EQ(warning_reason_enum,
            api::developer_private::SafetyCheckWarningReason::kMalware);
}

// Test developerPrivate.reload.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateReload) {
  const Extension* extension = LoadUnpackedExtension();
  ExtensionId extension_id = extension->id();
  auto function = base::MakeRefCounted<api::DeveloperPrivateReloadFunction>();
  base::Value::List reload_args;
  reload_args.Append(extension_id);

  TestExtensionRegistryObserver registry_observer(registry());
  EXPECT_TRUE(RunFunction(function, reload_args));
  scoped_refptr<const Extension> unloaded_extension =
      registry_observer.WaitForExtensionUnloaded();
  EXPECT_EQ(extension, unloaded_extension);
  scoped_refptr<const Extension> reloaded_extension =
      registry_observer.WaitForExtensionLoaded();
  EXPECT_EQ(extension_id, reloaded_extension->id());
}

// Test developerPrivate.packDirectory.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivatePackFunction) {
  // Use a temp dir isolating the extension dir and its generated files.
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  base::FilePath root_path = data_dir().AppendASCII("simple_with_popup");
  ASSERT_TRUE(base::CopyDirectory(root_path, temp_dir.GetPath(), true));

  base::FilePath temp_root_path =
      temp_dir.GetPath().Append(root_path.BaseName());
  base::FilePath crx_path =
      temp_dir.GetPath().AppendASCII("simple_with_popup.crx");
  base::FilePath pem_path =
      temp_dir.GetPath().AppendASCII("simple_with_popup.pem");

  EXPECT_FALSE(base::PathExists(crx_path))
      << "crx should not exist before the test is run!";
  EXPECT_FALSE(base::PathExists(pem_path))
      << "pem should not exist before the test is run!";

  // First, test a directory that should pack properly.
  base::Value::List pack_args;
  pack_args.Append(temp_root_path.AsUTF8Unsafe());
  EXPECT_TRUE(TestPackExtensionFunction(
      pack_args, api::developer_private::PackStatus::kSuccess, 0));

  // Should have created crx file and pem file.
  EXPECT_TRUE(base::PathExists(crx_path));
  EXPECT_TRUE(base::PathExists(pem_path));

  // Deliberately don't cleanup the files, and append the pem path.
  pack_args.Append(pem_path.AsUTF8Unsafe());

  // Try to pack again - we should get a warning abot overwriting the crx.
  EXPECT_TRUE(TestPackExtensionFunction(
      pack_args, api::developer_private::PackStatus::kWarning,
      ExtensionCreator::kOverwriteCRX));

  // Try to pack again, with the overwrite flag; this should succeed.
  pack_args.Append(ExtensionCreator::kOverwriteCRX);
  EXPECT_TRUE(TestPackExtensionFunction(
      pack_args, api::developer_private::PackStatus::kSuccess, 0));

  // Try to pack a final time when omitting (an existing) pem file. We should
  // get an error.
  base::DeleteFile(crx_path);
  // Remove the pem key and flags arguments.
  pack_args.erase(pack_args.begin() + 1, pack_args.begin() + 3);
  EXPECT_TRUE(TestPackExtensionFunction(
      pack_args, api::developer_private::PackStatus::kError, 0));
}

// Test developerPrivate.choosePath.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateChoosePath) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  base::FilePath expected_dir_path =
      data_dir().AppendASCII("simple_with_popup");
  base::FilePath expected_file_path =
      data_dir().AppendASCII("simple_with_popup.pem");

  // Try selecting a directory.
  auto function =
      base::MakeRefCounted<api::DeveloperPrivateChoosePathFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
  function->set_accept_dialog_for_testing(true);
  function->set_selected_file_for_testing(
      ui::SelectedFileInfo(expected_dir_path));
  base::Value::List choose_args;
  choose_args.Append("FOLDER");
  choose_args.Append("LOAD");
  EXPECT_TRUE(RunFunction(function, choose_args)) << function->GetError();

  // Verify directory was properly chosen.
  std::string path;
  const base::Value::List* result_list = function->GetResultListForTest();
  ASSERT_TRUE(result_list);
  ASSERT_GT(result_list->size(), 0u);
  ASSERT_TRUE((*result_list)[0].is_string());
  path = (*result_list)[0].GetString();
  EXPECT_EQ(path, expected_dir_path.AsUTF8Unsafe());

  // Try selecting a pem file.
  function = base::MakeRefCounted<api::DeveloperPrivateChoosePathFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
  function->set_accept_dialog_for_testing(true);
  function->set_selected_file_for_testing(
      ui::SelectedFileInfo(expected_file_path));
  choose_args.clear();
  choose_args.Append("FILE");
  choose_args.Append("PEM");
  EXPECT_TRUE(RunFunction(function, choose_args)) << function->GetError();

  // Verify pem file was properly chosen.
  result_list = function->GetResultListForTest();
  ASSERT_TRUE(result_list);
  ASSERT_GT(result_list->size(), 0u);
  ASSERT_TRUE((*result_list)[0].is_string());
  path = (*result_list)[0].GetString();
  EXPECT_EQ(path, expected_file_path.AsUTF8Unsafe());

  // Try canceling the file dialog.
  function = base::MakeRefCounted<api::DeveloperPrivateChoosePathFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
  function->set_accept_dialog_for_testing(false);
  EXPECT_FALSE(RunFunction(function, choose_args));

  // Verify function returns an error.
  EXPECT_EQ(std::string("File selection was canceled."), function->GetError());
}

// Test developerPrivate.loadUnpacked.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpacked) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  ExtensionIdSet current_ids = registry()->enabled_extensions().GetIDs();

  // Try loading an extension and canceling the dialog.
  auto function =
      base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
  function->set_accept_dialog_for_testing(false);
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
  EXPECT_FALSE(RunFunction(function, base::Value::List()));

  // Function should fail and no new extensions are installed.
  // NOTE: This isn't really an error, but we kept it like this for backward
  // compatibility.
  EXPECT_EQ("File selection was canceled.", function->GetError());
  EXPECT_EQ(0u, base::STLSetDifference<ExtensionIdSet>(
                    registry()->enabled_extensions().GetIDs(), current_ids)
                    .size());

  // Try loading a good extension and accepting the dialog.
  function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
  base::FilePath path = data_dir().AppendASCII("simple_with_popup");
  function->set_accept_dialog_for_testing(true);
  function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

  // Function should succeed and extension is added.
  EXPECT_TRUE(RunFunction(function, base::Value::List()))
      << function->GetError();
  ExtensionIdSet id_difference = base::STLSetDifference<ExtensionIdSet>(
      registry()->enabled_extensions().GetIDs(), current_ids);
  ASSERT_EQ(1u, id_difference.size());
  // The new extension should have the same path.
  EXPECT_EQ(
      path,
      registry()->enabled_extensions().GetByID(*id_difference.begin())->path());

  // Try loading a bad extension and accepting the dialog.
  function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
  path = data_dir().AppendASCII("empty_manifest");
  function->set_accept_dialog_for_testing(true);
  function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
  base::Value::List unpacked_args;
  base::Value::Dict options;
  options.Set("failQuietly", true);
  unpacked_args.Append(std::move(options));
  current_ids = registry()->enabled_extensions().GetIDs();
  EXPECT_FALSE(RunFunction(function, unpacked_args));

  // Function should fail and no new extensions are installed.
  EXPECT_EQ(manifest_errors::kManifestUnreadable, function->GetError());
  EXPECT_EQ(0u, base::STLSetDifference<ExtensionIdSet>(
                    registry()->enabled_extensions().GetIDs(), current_ids)
                    .size());
}

TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpackedLoadError) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  {
    // Load an extension with a clear manifest error ('version' is invalid).
    TestExtensionDir dir;
    dir.WriteManifest(
        R"({
             "name": "foo",
             "description": "bar",
             "version": 1,
             "manifest_version": 2
           })");
    base::FilePath path = dir.UnpackedPath();

    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(),
            "[{\"failQuietly\": true, \"populateError\": true}]", profile());

    // The loadError result should be populated.
    ASSERT_TRUE(result);
    std::optional<api::developer_private::LoadError> error =
        api::developer_private::LoadError::FromValue(*result);
    ASSERT_TRUE(error);
    ASSERT_TRUE(error->source);
    // The source should have *something* (rely on file highlighter tests for
    // the correct population).
    EXPECT_FALSE(error->source->before_highlight.empty());
    // The error should be appropriate (mentioning that version was invalid).
    EXPECT_TRUE(error->error.find("version") != std::string::npos)
        << error->error;
  }

  {
    // Load an extension with no manifest.
    TestExtensionDir dir;
    base::FilePath path = dir.UnpackedPath();

    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(),
            "[{\"failQuietly\": true, \"populateError\": true}]", profile());
    // The load error should be populated.
    ASSERT_TRUE(result);
    std::optional<api::developer_private::LoadError> error =
        api::developer_private::LoadError::FromValue(*result);
    ASSERT_TRUE(error);
    // The file source should be empty.
    ASSERT_TRUE(error->source);
    EXPECT_TRUE(error->source->before_highlight.empty());
    EXPECT_TRUE(error->source->highlight.empty());
    EXPECT_TRUE(error->source->after_highlight.empty());
  }

  {
    // Load a valid extension.
    TestExtensionDir dir;
    dir.WriteManifest(
        R"({
             "name": "foo",
             "description": "bar",
             "version": "1.0",
             "manifest_version": 2
           })");
    base::FilePath path = dir.UnpackedPath();

    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(),
            "[{\"failQuietly\": true, \"populateError\": true}]", profile());
    // There should be no load error.
    ASSERT_FALSE(result);
  }
}

// Test that the retryGuid supplied by loadUnpacked works correctly.
TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  // Load an extension with a clear manifest error ('version' is invalid).
  TestExtensionDir dir;
  dir.WriteManifest(
      R"({
           "name": "foo",
           "description": "bar",
           "version": 1,
           "manifest_version": 2
         })");
  base::FilePath path = dir.UnpackedPath();

  DeveloperPrivateAPI::UnpackedRetryId retry_guid;
  {
    // Trying to load the extension should result in a load error with the
    // retry id populated.
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(),
            "[{\"failQuietly\": true, \"populateError\": true}]", profile());
    ASSERT_TRUE(result);
    std::optional<api::developer_private::LoadError> error =
        api::developer_private::LoadError::FromValue(*result);
    ASSERT_TRUE(error);
    EXPECT_FALSE(error->retry_guid.empty());
    retry_guid = error->retry_guid;
  }

  {
    // Trying to reload the same extension, again to fail, should result in the
    // same retry id.  This is somewhat an implementation detail, but is
    // important to ensure we don't allocate crazy numbers of ids if the user
    // just retries continuously.
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(),
            "[{\"failQuietly\": true, \"populateError\": true}]", profile());
    ASSERT_TRUE(result);
    std::optional<api::developer_private::LoadError> error =
        api::developer_private::LoadError::FromValue(*result);
    ASSERT_TRUE(error);
    EXPECT_EQ(retry_guid, error->retry_guid);
  }

  {
    // Try loading a different directory. The retry id should be different; this
    // also tests loading a second extension with one retry currently
    // "in-flight" (i.e., unresolved).
    TestExtensionDir second_dir;
    second_dir.WriteManifest(
        R"({
             "name": "foo",
             "description": "bar",
             "version": 1,
             "manifest_version": 2
           })");
    base::FilePath second_path = second_dir.UnpackedPath();

    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(second_path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(),
            "[{\"failQuietly\": true, \"populateError\": true}]", profile());
    // The loadError result should be populated.
    ASSERT_TRUE(result);
    std::optional<api::developer_private::LoadError> error =
        api::developer_private::LoadError::FromValue(*result);
    ASSERT_TRUE(error);
    EXPECT_NE(retry_guid, error->retry_guid);
  }

  // Correct the manifest to make the extension valid.
  dir.WriteManifest(
      R"({
           "name": "foo",
           "description": "bar",
           "version": "1.0",
           "manifest_version": 2
         })");

  // Set the picker to choose an invalid path (the picker should be skipped if
  // we supply a retry id).
  base::FilePath empty_path;

  {
    // Try reloading the extension by supplying the retry id. It should succeed.
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(empty_path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    TestExtensionRegistryObserver observer(registry());
    api_test_utils::RunFunction(function.get(),
                                base::StringPrintf("[{\"failQuietly\": true,"
                                                   "\"populateError\": true,"
                                                   "\"retryGuid\": \"%s\"}]",
                                                   retry_guid.c_str()),
                                profile());
    scoped_refptr<const Extension> extension =
        observer.WaitForExtensionLoaded();
    ASSERT_TRUE(extension);
    EXPECT_EQ(extension->path(), path);
  }

  {
    // Try supplying an invalid retry id. It should fail with an error.
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(empty_path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(),
        "[{\"failQuietly\": true,"
        "\"populateError\": true,"
        "\"retryGuid\": \"invalid id\"}]",
        profile());
    EXPECT_EQ("Invalid retry id", error);
  }
}

// Tests calling "reload" on an unpacked extension with a manifest error,
// resulting in the reload failing. The reload call should then respond with
// the load error, which includes a retry GUID to be passed to loadUnpacked().
TEST_F(DeveloperPrivateApiUnitTest, ReloadBadExtensionToLoadUnpackedRetry) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  // A broken manifest (version's value should be a string).
  constexpr const char kBadManifest[] =
      R"({
           "name": "foo",
           "description": "bar",
           "version": 1,
           "manifest_version": 2
         })";
  constexpr const char kGoodManifest[] =
      R"({
           "name": "foo",
           "description": "bar",
           "version": "1",
           "manifest_version": 2
         })";

  // Create a good unpacked extension.
  TestExtensionDir dir;
  dir.WriteManifest(kGoodManifest);
  base::FilePath path = dir.UnpackedPath();

  scoped_refptr<const Extension> extension;
  {
    ChromeTestExtensionLoader loader(profile());
    loader.set_pack_extension(false);
    extension = loader.LoadExtension(path);
  }
  ASSERT_TRUE(extension);
  const ExtensionId id = extension->id();

  std::string reload_args = base::StringPrintf(
      R"(["%s", {"failQuietly": true, "populateErrorForUnpacked":true}])",
      id.c_str());

  {
    // Try reloading while the manifest is still good. This should succeed, and
    // the extension should still be enabled. Additionally, the function should
    // wait for the reload to complete, so we should see an unload and reload.
    class UnloadedRegistryObserver : public ExtensionRegistryObserver {
     public:
      UnloadedRegistryObserver(const base::FilePath& expected_path,
                               ExtensionRegistry* registry)
          : expected_path_(expected_path) {
        observation_.Observe(registry);
      }

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

      void OnExtensionUnloaded(content::BrowserContext* browser_context,
                               const Extension* extension,
                               UnloadedExtensionReason reason) override {
        ASSERT_FALSE(saw_unload_);
        saw_unload_ = extension->path() == expected_path_;
      }

      bool saw_unload() const { return saw_unload_; }

     private:
      bool saw_unload_ = false;
      base::FilePath expected_path_;
      base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver>
          observation_{this};
    };

    UnloadedRegistryObserver unload_observer(path, registry());
    auto function = base::MakeRefCounted<api::DeveloperPrivateReloadFunction>();
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    api_test_utils::RunFunction(function.get(), reload_args, profile());
    // Note: no need to validate a saw_load()-type method because the presence
    // in enabled_extensions() indicates the extension was loaded.
    EXPECT_TRUE(unload_observer.saw_unload());
    EXPECT_TRUE(registry()->enabled_extensions().Contains(id));
  }

  dir.WriteManifest(kBadManifest);

  DeveloperPrivateAPI::UnpackedRetryId retry_guid;
  {
    // Trying to load the extension should result in a load error with the
    // retry GUID populated.
    auto function = base::MakeRefCounted<api::DeveloperPrivateReloadFunction>();
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(), reload_args, profile());
    ASSERT_TRUE(result);
    std::optional<api::developer_private::LoadError> error =
        api::developer_private::LoadError::FromValue(*result);
    ASSERT_TRUE(error);
    EXPECT_FALSE(error->retry_guid.empty());
    retry_guid = error->retry_guid;
    EXPECT_TRUE(registry()->disabled_extensions().Contains(id));
  }

  dir.WriteManifest(kGoodManifest);
  {
    // Try reloading the extension by supplying the retry id. It should succeed,
    // and the extension should be enabled again.
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    TestExtensionRegistryObserver observer(registry());
    std::string args =
        base::StringPrintf(R"([{"failQuietly": true, "populateError": true,
                                "retryGuid": "%s"}])",
                           retry_guid.c_str());
    api_test_utils::RunFunction(function.get(), args, profile());
    scoped_refptr<const Extension> reloaded_extension =
        observer.WaitForExtensionLoaded();
    ASSERT_TRUE(reloaded_extension);
    EXPECT_EQ(reloaded_extension->path(), path);
    EXPECT_TRUE(registry()->enabled_extensions().Contains(id));
  }
}

TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateNotifyDragInstallInProgress) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  TestExtensionDir dir;
  dir.WriteManifest(
      R"({
           "name": "foo",
           "description": "bar",
           "version": "1",
           "manifest_version": 2
         })");
  base::FilePath path = dir.UnpackedPath();
  ui::FileInfo file(path, path.BaseName());
  api::DeveloperPrivateNotifyDragInstallInProgressFunction::
      SetDropFileForTesting(&file);

  {
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateNotifyDragInstallInProgressFunction>();
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    api_test_utils::RunFunction(function.get(), "[]", profile());
  }

  constexpr char kLoadUnpackedArgs[] =
      R"([{"failQuietly": true,
           "populateError": true,
           "useDraggedPath": true}])";

  {
    // Try reloading the extension by supplying the retry id. It should succeed.
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    // Set file picker dialog to be accepted with an invalid path (the dialog
    // should be skipped if we supply a retry id).
    base::FilePath empty_path;
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(empty_path));
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

    TestExtensionRegistryObserver observer(registry());
    api_test_utils::RunFunction(function.get(), kLoadUnpackedArgs, profile());
    scoped_refptr<const Extension> extension =
        observer.WaitForExtensionLoaded();
    ASSERT_TRUE(extension);
    EXPECT_EQ(extension->path(), path);
  }

  // Next, ensure that nothing catastrophic happens if the file that was dropped
  // was not a directory. In theory, this shouldn't happen (the JS validates the
  // file), but it could in the case of a compromised renderer, JS bug, etc.
  base::FilePath invalid_path = path.AppendASCII("manifest.json");
  ui::FileInfo invalid_file(invalid_path, invalid_path.BaseName());
  api::DeveloperPrivateNotifyDragInstallInProgressFunction::
      SetDropFileForTesting(&invalid_file);
  {
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateNotifyDragInstallInProgressFunction>();
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(function.get(), "[]",
                                                         profile());
  }

  {
    // Trying to load the bad extension (the path points to the manifest, not
    // the directory) should result in a load error.
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    // Set file picker dialog to be accepted with an invalid path (the dialog
    // should be skipped if we supply a retry id).
    base::FilePath empty_path;
    function->set_accept_dialog_for_testing(true);
    function->set_selected_file_for_testing(ui::SelectedFileInfo(empty_path));
    TestExtensionRegistryObserver observer(registry());
    std::optional<base::Value> result =
        api_test_utils::RunFunctionAndReturnSingleResult(
            function.get(), kLoadUnpackedArgs, profile());
    ASSERT_TRUE(result);
    EXPECT_TRUE(api::developer_private::LoadError::FromValue(*result));
  }

  // Cleanup.
  api::DeveloperPrivateNotifyDragInstallInProgressFunction::
      SetDropFileForTesting(nullptr);
}

// Test developerPrivate.requestFileSource.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateRequestFileSource) {
  // Testing of this function seems light, but that's because it basically just
  // forwards to reading a file to a string, and highlighting it - both of which
  // are already tested separately.
  const Extension* extension = LoadUnpackedExtension();
  const char kErrorMessage[] = "Something went wrong";
  api::developer_private::RequestFileSourceProperties properties;
  properties.extension_id = extension->id();
  properties.path_suffix = "manifest.json";
  properties.message = kErrorMessage;
  properties.manifest_key = "name";

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateRequestFileSourceFunction>();
  base::Value::List file_source_args;
  file_source_args.Append(properties.ToValue());
  EXPECT_TRUE(RunFunction(function, file_source_args)) << function->GetError();

  const base::Value& response_value = (*function->GetResultListForTest())[0];
  std::optional<api::developer_private::RequestFileSourceResponse> response =
      api::developer_private::RequestFileSourceResponse::FromValue(
          response_value);
  EXPECT_FALSE(response->before_highlight.empty());
  EXPECT_EQ("\"name\": \"foo\"", response->highlight);
  EXPECT_FALSE(response->after_highlight.empty());
  EXPECT_EQ("foo: manifest.json", response->title);
  EXPECT_EQ(kErrorMessage, response->message);
}

// Test developerPrivate.getExtensionsInfo.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateGetExtensionsInfo) {
  LoadSimpleExtension();

  // The test here isn't so much about the generated value (that's tested in
  // ExtensionInfoGenerator's unittest), but rather just to make sure we can
  // serialize/deserialize the result - which implicity tests that everything
  // has a sane value.
  auto function =
      base::MakeRefCounted<api::DeveloperPrivateGetExtensionsInfoFunction>();
  EXPECT_TRUE(RunFunction(function, base::Value::List()))
      << function->GetError();
  const base::Value::List* results = function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());
  ASSERT_TRUE((*results)[0].is_list());
  const base::Value::List& list = (*results)[0].GetList();
  ASSERT_EQ(1u, list.size());
  std::optional<api::developer_private::ExtensionInfo> info =
      api::developer_private::ExtensionInfo::FromValue(list[0]);
  ASSERT_TRUE(info);
}

// Test developerPrivate.deleteExtensionErrors.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDeleteExtensionErrors) {
  profile()->GetPrefs()->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);
  const Extension* extension = LoadSimpleExtension();

  // Report some errors.
  ErrorConsole* error_console = ErrorConsole::Get(profile());
  error_console->SetReportingAllForExtension(extension->id(), true);
  error_console->ReportError(
      error_test_util::CreateNewRuntimeError(extension->id(), "foo"));
  error_console->ReportError(
      error_test_util::CreateNewRuntimeError(extension->id(), "bar"));
  error_console->ReportError(
      error_test_util::CreateNewManifestError(extension->id(), "baz"));
  EXPECT_EQ(3u, error_console->GetErrorsForExtension(extension->id()).size());

  // Start by removing all errors for the extension of a given type (manifest).
  std::string type_string = api::developer_private::ToString(
      api::developer_private::ErrorType::kManifest);
  base::Value::List args =
      base::Value::List().Append(base::Value::Dict()
                                     .Set("extensionId", extension->id())
                                     .Set("type", type_string));
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateDeleteExtensionErrorsFunction>();
  EXPECT_TRUE(RunFunction(function, args)) << function->GetError();
  // Two errors should remain.
  const ErrorList& error_list =
      error_console->GetErrorsForExtension(extension->id());
  ASSERT_EQ(2u, error_list.size());

  // Next remove errors by id.
  int error_id = error_list[0]->id();
  args = base::Value::List().Append(
      base::Value::Dict()
          .Set("extensionId", extension->id())
          .Set("errorIds", base::Value::List().Append(error_id)));
  function = base::MakeRefCounted<
      api::DeveloperPrivateDeleteExtensionErrorsFunction>();
  EXPECT_TRUE(RunFunction(function, args)) << function->GetError();
  // And then there was one.
  EXPECT_EQ(1u, error_console->GetErrorsForExtension(extension->id()).size());

  // Finally remove all errors for the extension.
  args = base::Value::List().Append(
      base::Value::Dict().Set("extensionId", extension->id()));
  function = base::MakeRefCounted<
      api::DeveloperPrivateDeleteExtensionErrorsFunction>();
  EXPECT_TRUE(RunFunction(function, args)) << function->GetError();
  // No more errors!
  EXPECT_TRUE(error_console->GetErrorsForExtension(extension->id()).empty());
}

// Tests that developerPrivate.repair does not succeed for a non-corrupted
// extension.
TEST_F(DeveloperPrivateApiUnitTest, RepairNotBrokenExtension) {
  base::FilePath extension_path = data_dir().AppendASCII("good.crx");
  const Extension* extension = InstallCRX(extension_path, INSTALL_NEW);

  // Attempt to repair the good extension, expect failure.
  base::Value::List args = base::Value::List().Append(extension->id());
  auto function =
      base::MakeRefCounted<api::DeveloperPrivateRepairExtensionFunction>();
  EXPECT_FALSE(RunFunction(function, args));
  EXPECT_EQ("Cannot repair a healthy extension.", function->GetError());
}

// Tests that developerPrivate.private cannot repair a policy-installed
// extension.
// Regression test for https://crbug.com/577959.
TEST_F(DeveloperPrivateApiUnitTest, RepairPolicyExtension) {
  ExtensionId extension_id(kGoodCrx);

  // Set up a mock provider with a policy extension.
  std::unique_ptr<MockExternalProvider> mock_provider =
      std::make_unique<MockExternalProvider>(
          external_provider_manager(),
          mojom::ManifestLocation::kExternalPolicyDownload);
  MockExternalProvider* mock_provider_ptr = mock_provider.get();
  AddMockExternalProvider(std::move(mock_provider));
  mock_provider_ptr->UpdateOrAddExtension(extension_id, "1.0.0.0",
                                          data_dir().AppendASCII("good.crx"));
  // Reloading extensions should find our externally registered extension
  // and install it.
  {
    TestExtensionRegistryObserver observer(registry());
    external_provider_manager()->CheckForExternalUpdates();
    EXPECT_EQ(extension_id, observer.WaitForExtensionLoaded()->id());
  }

  // Attempt to repair the good extension, expect failure.
  base::Value::List args = base::Value::List().Append(extension_id);
  auto function =
      base::MakeRefCounted<api::DeveloperPrivateRepairExtensionFunction>();
  EXPECT_FALSE(RunFunction(function, args));
  EXPECT_EQ("Cannot repair a healthy extension.", function->GetError());

  // Corrupt the extension, still expect repair failure because this is a
  // policy extension.
  registrar()->DisableExtension(extension_id,
                                {disable_reason::DISABLE_CORRUPTED});
  args = base::Value::List().Append(extension_id);
  function =
      base::MakeRefCounted<api::DeveloperPrivateRepairExtensionFunction>();
  EXPECT_FALSE(RunFunction(function, args));
  EXPECT_EQ("Cannot repair a policy-installed extension.",
            function->GetError());
}

// Tests that developerPrivate.repair does not succeed for an extension not from
// the Chrome Web Store.
TEST_F(DeveloperPrivateApiUnitTest, RepairNonCWSExtension) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  base::FilePath extension_path = data_dir().AppendASCII("good.crx");
  const Extension* extension = InstallCRX(extension_path, INSTALL_NEW);

  // Corrupt the extension, still expect repair failure because `good.crx` does
  // not update from the web store.
  registrar()->DisableExtension(extension->id(),
                                {disable_reason::DISABLE_CORRUPTED});

  base::Value::List args = base::Value::List().Append(extension->id());
  auto function =
      base::MakeRefCounted<api::DeveloperPrivateRepairExtensionFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
  EXPECT_FALSE(RunFunction(function, args));
  EXPECT_EQ(
      "Cannot repair an extension that is not installed from the Chrome Web "
      "Store.",
      function->GetError());
}

// Test developerPrivate.updateProfileConfiguration: Try to turn on devMode
// when DeveloperToolsAvailability policy disallows developer tools.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDevModeDisabledPolicy) {
  testing_pref_service()->SetManagedPref(prefs::kExtensionsUIDeveloperMode,
                                         std::make_unique<base::Value>(false));

  UpdateProfileConfigurationDevMode(true);

  EXPECT_FALSE(
      profile()->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode));

  std::optional<api::developer_private::ProfileInfo> profile_info;
  ASSERT_NO_FATAL_FAILURE(GetProfileConfiguration(&profile_info));
  EXPECT_FALSE(profile_info->in_developer_mode);
  EXPECT_TRUE(profile_info->is_developer_mode_controlled_by_policy);
}

// Test developerPrivate.updateProfileConfiguration: Try to turn on devMode
// (without DeveloperToolsAvailability policy).
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDevMode) {
  UpdateProfileConfigurationDevMode(false);
  EXPECT_FALSE(
      profile()->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode));
  {
    std::optional<api::developer_private::ProfileInfo> profile_info;
    ASSERT_NO_FATAL_FAILURE(GetProfileConfiguration(&profile_info));
    EXPECT_FALSE(profile_info->in_developer_mode);
    EXPECT_FALSE(profile_info->is_developer_mode_controlled_by_policy);
  }

  UpdateProfileConfigurationDevMode(true);
  EXPECT_TRUE(
      profile()->GetPrefs()->GetBoolean(prefs::kExtensionsUIDeveloperMode));
  {
    std::optional<api::developer_private::ProfileInfo> profile_info;
    ASSERT_NO_FATAL_FAILURE(GetProfileConfiguration(&profile_info));
    EXPECT_TRUE(profile_info->in_developer_mode);
    EXPECT_FALSE(profile_info->is_developer_mode_controlled_by_policy);
  }
}

TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedFailsWithoutDevMode) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  PrefService* prefs = profile()->GetPrefs();
  prefs->SetBoolean(prefs::kExtensionsUIDeveloperMode, false);

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), "[]", profile());
  EXPECT_THAT(error, testing::HasSubstr("developer mode"));
  prefs->SetBoolean(prefs::kExtensionsUIDeveloperMode, true);
}

TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedFailsWithBlocklistingPolicy) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  {
    ExtensionManagementPrefUpdater<sync_preferences::TestingPrefServiceSyncable>
        pref_updater(testing_pref_service());
    pref_updater.SetBlocklistedByDefault(true);
  }

  auto* extension_management =
      ExtensionManagementFactory::GetForBrowserContext(browser_context());
  EXPECT_TRUE(extension_management->BlocklistedByDefault());
  EXPECT_FALSE(extension_management->HasAllowlistedExtension());

  auto info = CreateProfileInfo(profile());
  EXPECT_FALSE(info.can_load_unpacked);

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

  std::string error = api_test_utils::RunFunctionAndReturnError(
      function.get(), "[]", profile());
  EXPECT_THAT(error, testing::HasSubstr("policy"));
}

TEST_F(DeveloperPrivateApiUnitTest,
       LoadUnpackedWorksWithBlocklistingPolicyAlongAllowlistingPolicy) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  {
    ExtensionManagementPrefUpdater<sync_preferences::TestingPrefServiceSyncable>
        pref_updater(testing_pref_service());
    pref_updater.SetBlocklistedByDefault(true);
    pref_updater.SetIndividualExtensionInstallationAllowed(kGoodCrx, true);
  }

  EXPECT_TRUE(
      ExtensionManagementFactory::GetForBrowserContext(browser_context())
          ->BlocklistedByDefault());

  EXPECT_TRUE(
      ExtensionManagementFactory::GetForBrowserContext(browser_context())
          ->HasAllowlistedExtension());

  auto info = CreateProfileInfo(profile());

  EXPECT_TRUE(info.can_load_unpacked);
}

TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileNoDraggedPath) {
  base::AutoReset<bool> disable_ui =
      ExtensionInstallUI::disable_ui_for_tests(true);
  ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);

  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

  TestExtensionRegistryObserver observer(registry());
  EXPECT_EQ("No dragged path", api_test_utils::RunFunctionAndReturnError(
                                   function.get(), "[]", profile()));
}

TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileCrx) {
  TestExtensionDir test_dir;
  test_dir.WriteManifest(
      R"({
           "name": "foo",
           "version": "1.0",
           "manifest_version": 2
         })");
  base::FilePath crx_path = test_dir.Pack();
  base::AutoReset<bool> disable_ui =
      ExtensionInstallUI::disable_ui_for_tests(true);
  ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);

  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  DeveloperPrivateAPI::Get(profile())->SetDraggedFile(
      web_contents.get(), ui::FileInfo(crx_path, crx_path.BaseName()));

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

  TestExtensionRegistryObserver observer(registry());
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), "[]", profile()))
      << function->GetError();
  scoped_refptr<const Extension> extension =
      observer.WaitForExtensionInstalled();
  ASSERT_TRUE(extension);
  EXPECT_EQ("foo", extension->name());
}

TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileUserScript) {
  base::FilePath script_path =
      data_dir().AppendASCII("user_script_basic.user.js");
  base::AutoReset<bool> disable_ui =
      ExtensionInstallUI::disable_ui_for_tests(true);
  ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);

  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  DeveloperPrivateAPI::Get(profile())->SetDraggedFile(
      web_contents.get(), ui::FileInfo(script_path, script_path.BaseName()));

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

  TestExtensionRegistryObserver observer(registry());
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), "[]", profile()))
      << function->GetError();
  scoped_refptr<const Extension> extension =
      observer.WaitForExtensionInstalled();
  ASSERT_TRUE(extension);
  EXPECT_EQ("My user script", extension->name());
}

TEST_F(DeveloperPrivateApiUnitTest, GrantHostPermission) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("<all_urls>").Build();
  registrar()->AddExtension(extension.get());

  PermissionsManager* permissions_manager = PermissionsManager::Get(profile());
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));

  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  const GURL kExampleCom("https://example.com/");
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));
  RunAddHostPermission(profile(), *extension, "https://example.com/*",
                       /*should_succeed=*/true, nullptr);
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));

  const GURL kGoogleCom("https://google.com");
  const GURL kMapsGoogleCom("https://maps.google.com/");
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_FALSE(permissions_manager->HasGrantedHostPermission(*extension,
                                                             kMapsGoogleCom));
  RunAddHostPermission(profile(), *extension, "https://*.google.com/*",
                       /*should_succeed=*/true, nullptr);
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension,
                                                            kMapsGoogleCom));

  RunAddHostPermission(profile(), *extension, kInvalidHost,
                       /*should_succeed=*/false, kInvalidHostError);
  // Path of the pattern must exactly match "/*".
  RunAddHostPermission(profile(), *extension, "https://example.com/",
                       /*should_succeed=*/false, kInvalidHostError);
  RunAddHostPermission(profile(), *extension, "https://example.com/foobar",
                       /*should_succeed=*/false, kInvalidHostError);
  RunAddHostPermission(profile(), *extension, "https://example.com/#foobar",
                       /*should_succeed=*/false, kInvalidHostError);
  RunAddHostPermission(profile(), *extension, "https://example.com/*foobar",
                       /*should_succeed=*/false, kInvalidHostError);

  // Cannot grant chrome:-scheme URLs.
  GURL chrome_host("chrome://settings/*");
  RunAddHostPermission(profile(), *extension, chrome_host.spec(),
                       /*should_succeed=*/false, kInvalidHostError);

  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, chrome_host));
}

TEST_F(DeveloperPrivateApiUnitTest, RemoveHostPermission) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("<all_urls>").Build();
  registrar()->AddExtension(extension.get());

  PermissionsManager* permissions_manager = PermissionsManager::Get(profile());
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));

  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  auto run_remove_host_permission = [this, extension](
                                        std::string_view host,
                                        bool should_succeed,
                                        const char* expected_error) {
    SCOPED_TRACE(host);
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateRemoveHostPermissionFunction>();
    std::string args = base::StringPrintf(R"(["%s", "%s"])",
                                          extension->id().c_str(), host.data());
    if (should_succeed) {
      EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile()))
          << function->GetError();
    } else {
      EXPECT_EQ(expected_error, api_test_utils::RunFunctionAndReturnError(
                                    function.get(), args, profile()));
    }
  };

  run_remove_host_permission("https://example.com/*", false,
                             "Cannot remove a host that hasn't been granted.");

  const GURL kExampleCom("https://example.com");
  modifier.GrantHostPermission(kExampleCom);
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));

  // Path of the pattern must exactly match "/*".
  run_remove_host_permission("https://example.com/", false, kInvalidHostError);
  run_remove_host_permission("https://example.com/foobar", false,
                             kInvalidHostError);
  run_remove_host_permission("https://example.com/#foobar", false,
                             kInvalidHostError);
  run_remove_host_permission("https://example.com/*foobar", false,
                             kInvalidHostError);
  run_remove_host_permission(kInvalidHost, false, kInvalidHostError);
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));

  run_remove_host_permission("https://example.com/*", true, nullptr);
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));

  URLPattern new_pattern(Extension::kValidHostPermissionSchemes,
                         "https://*.google.com/*");
  permissions_test_util::GrantRuntimePermissionsAndWaitForCompletion(
      profile(), *extension,
      PermissionSet(APIPermissionSet(), ManifestPermissionSet(),
                    URLPatternSet({new_pattern}), URLPatternSet()));

  const GURL kGoogleCom("https://google.com/");
  const GURL kMapsGoogleCom("https://maps.google.com/");
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension,
                                                            kMapsGoogleCom));

  run_remove_host_permission("https://*.google.com/*", true, nullptr);
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_FALSE(permissions_manager->HasGrantedHostPermission(*extension,
                                                             kMapsGoogleCom));
}

TEST_F(DeveloperPrivateApiUnitTest, UpdateHostAccess) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("<all_urls>").Build();
  registrar()->AddExtension(extension.get());

  PermissionsManager* permissions_manager =
      PermissionsManager::Get(browser()->profile());
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));

  RunUpdateHostAccess(*extension, "ON_CLICK");
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));

  RunUpdateHostAccess(*extension, "ON_ALL_SITES");
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));

  RunUpdateHostAccess(*extension, "ON_SPECIFIC_SITES");
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
}

TEST_F(DeveloperPrivateApiUnitTest,
       UpdateHostAccess_SpecificSitesRemovedOnTransitionToOnClick) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("<all_urls>").Build();
  registrar()->AddExtension(extension.get());
  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  const GURL example_com("https://example.com");
  modifier.GrantHostPermission(example_com);
  PermissionsManager* permissions_manager =
      PermissionsManager::Get(browser()->profile());

  RunUpdateHostAccess(*extension, "ON_SPECIFIC_SITES");
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, example_com));

  RunUpdateHostAccess(*extension, "ON_CLICK");
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, example_com));

  // NOTE(devlin): It's a bit unfortunate that by cycling between host access
  // settings, a user loses any stored state. This would be painful if the user
  // had set "always run on foo" for a dozen or so sites, and accidentally
  // changed the setting.
  // There are ways we could address this, such as introducing a tri-state for
  // the preference and keeping a stored set of any granted host permissions,
  // but this then results in a funny edge case:
  // - User has "on specific sites" set, with access to example.com and
  //   chromium.org granted.
  // - User changes to "on click" -> no sites are granted.
  // - User visits google.com, and says "always run on this site." This changes
  //   the setting back to "on specific sites", and will implicitly re-grant
  //   example.com and chromium.org permissions, without any additional
  //   prompting.
  // To avoid this, we just clear any granted permissions when the user
  // transitions between states. Since this is definitely a power-user surface,
  // this is likely okay.
  RunUpdateHostAccess(*extension, "ON_SPECIFIC_SITES");
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, example_com));
}

TEST_F(DeveloperPrivateApiUnitTest,
       UpdateHostAccess_SpecificSitesRemovedOnTransitionToAllSites) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("<all_urls>").Build();
  registrar()->AddExtension(extension.get());
  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  PermissionsManager* permissions_manager =
      PermissionsManager::Get(browser()->profile());
  const GURL example_com("https://example.com");

  RunUpdateHostAccess(*extension, "ON_SPECIFIC_SITES");
  modifier.GrantHostPermission(example_com);
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, example_com));

  RunUpdateHostAccess(*extension, "ON_ALL_SITES");
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, example_com));

  RunUpdateHostAccess(*extension, "ON_SPECIFIC_SITES");
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, example_com));
}

TEST_F(DeveloperPrivateApiUnitTest,
       UpdateHostAccess_BroadPermissionsRemovedOnTransitionToSpecificSites) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("<all_urls>").Build();
  registrar()->AddExtension(extension.get());
  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  const GURL kGoogleCom("https://google.com/");
  const GURL kChromiumCom("https://chromium.com");

  // Request <all_urls> and google.com so they are both in the runtime granted
  // list. We use the util function to specifically add the <all_urls> pattern
  // here, similar to if it was requested through the chrome.permissions.request
  // API.
  URLPattern all_url_pattern(Extension::kValidHostPermissionSchemes,
                             "<all_urls>");
  permissions_test_util::GrantRuntimePermissionsAndWaitForCompletion(
      profile(), *extension,
      PermissionSet(APIPermissionSet(), ManifestPermissionSet(),
                    URLPatternSet({all_url_pattern}),
                    URLPatternSet({all_url_pattern})));
  modifier.GrantHostPermission(kGoogleCom);

  // Even though <all_urls> has been granted, it was granted as a runtime host
  // pattern, so the extension is still is considered to have withheld host
  // permissions.
  PermissionsManager* permissions_manager =
      PermissionsManager::Get(browser()->profile());
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kChromiumCom));

  // Changing to specific sites should now remove the broad pattern, leaving
  // only the google match pattern.
  RunUpdateHostAccess(*extension, "ON_SPECIFIC_SITES");
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, kChromiumCom));
}

TEST_F(DeveloperPrivateApiUnitTest,
       UpdateHostAccess_GrantScopeGreaterThanRequestedScope) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("http://*/*").Build();
  registrar()->AddExtension(extension.get());
  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile());
  EXPECT_EQ(PermissionSet(),
            extension->permissions_data()->active_permissions());
  EXPECT_EQ(PermissionSet(),
            *extension_prefs->GetRuntimeGrantedPermissions(extension->id()));

  {
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateAddHostPermissionFunction>();
    std::string args = base::StringPrintf(
        R"(["%s", "%s"])", extension->id().c_str(), "*://chromium.org/*");
    EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile()))
        << function->GetError();
  }

  // The active permissions (which are given to the extension process) should
  // only include the intersection of what was requested by the extension and
  // the runtime granted permissions - which is http://chromium.org/*.
  URLPattern http_chromium(Extension::kValidHostPermissionSchemes,
                           "http://chromium.org/*");
  const PermissionSet http_chromium_set(
      APIPermissionSet(), ManifestPermissionSet(),
      URLPatternSet({http_chromium}), URLPatternSet());
  EXPECT_EQ(http_chromium_set,
            extension->permissions_data()->active_permissions());

  // The runtime granted permissions should include all of what was approved by
  // the user, which is *://chromium.org/*, and should be present in both the
  // scriptable and explicit hosts.
  URLPattern all_chromium(Extension::kValidHostPermissionSchemes,
                          "*://chromium.org/*");
  const PermissionSet all_chromium_set(
      APIPermissionSet(), ManifestPermissionSet(),
      URLPatternSet({all_chromium}), URLPatternSet({all_chromium}));
  EXPECT_EQ(all_chromium_set,
            *extension_prefs->GetRuntimeGrantedPermissions(extension->id()));

  {
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateRemoveHostPermissionFunction>();
    std::string args = base::StringPrintf(
        R"(["%s", "%s"])", extension->id().c_str(), "*://chromium.org/*");
    EXPECT_TRUE(api_test_utils::RunFunction(function.get(), args, profile()))
        << function->GetError();
  }

  // Removing the granted permission should remove it entirely from both
  // the active and the stored permissions.
  EXPECT_EQ(PermissionSet(),
            extension->permissions_data()->active_permissions());
  EXPECT_EQ(PermissionSet(),
            *extension_prefs->GetRuntimeGrantedPermissions(extension->id()));
}

TEST_F(DeveloperPrivateApiUnitTest,
       UpdateHostAccess_UnrequestedHostsDispatchUpdateEvents) {
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("http://google.com/*").Build();
  registrar()->AddExtension(extension.get());
  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  // We need to call DeveloperPrivateAPI::Get() in order to instantiate the
  // keyed service, since it's not created by default in unit tests.
  DeveloperPrivateAPI::Get(profile());
  const ExtensionId listener_id = crx_file::id_util::GenerateId("listener");
  EventRouter* event_router = EventRouter::Get(profile());

  // The DeveloperPrivateEventRouter will only dispatch events if there's at
  // least one listener to dispatch to. Create one.
  const char* kEventName =
      api::developer_private::OnItemStateChanged::kEventName;
  event_router->AddEventListener(kEventName, render_process_host(),
                                 listener_id);

  TestEventRouterObserver test_observer(event_router);
  EXPECT_FALSE(WasItemChangedEventDispatched(
      test_observer, extension->id(),
      api::developer_private::EventType::kPermissionsChanged));

  URLPatternSet hosts({URLPattern(Extension::kValidHostPermissionSchemes,
                                  "https://example.com/*")});
  PermissionSet permissions(APIPermissionSet(), ManifestPermissionSet(),
                            hosts.Clone(), hosts.Clone());
  permissions_test_util::GrantRuntimePermissionsAndWaitForCompletion(
      profile(), *extension, permissions);

  // The event router fetches icons from a blocking thread when sending the
  // update event; allow it to finish before verifying the event was dispatched.
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(WasItemChangedEventDispatched(
      test_observer, extension->id(),
      api::developer_private::EventType::kPermissionsChanged));

  test_observer.ClearEvents();

  permissions_test_util::RevokeRuntimePermissionsAndWaitForCompletion(
      profile(), *extension, permissions);
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(WasItemChangedEventDispatched(
      test_observer, extension->id(),
      api::developer_private::EventType::kPermissionsChanged));
}

TEST_F(DeveloperPrivateApiUnitTest, ExtensionUpdatedEventOnPermissionsChange) {
  // We need to call DeveloperPrivateAPI::Get() in order to instantiate the
  // keyed service, since it's not created by default in unit tests.
  DeveloperPrivateAPI::Get(profile());
  const ExtensionId listener_id = crx_file::id_util::GenerateId("listener");
  EventRouter* event_router = EventRouter::Get(profile());

  // The DeveloperPrivateEventRouter will only dispatch events if there's at
  // least one listener to dispatch to. Create one.
  const char* kEventName =
      api::developer_private::OnItemStateChanged::kEventName;
  event_router->AddEventListener(kEventName, render_process_host(),
                                 listener_id);

  scoped_refptr<const Extension> dummy_extension =
      ExtensionBuilder("dummy")
          .SetManifestKey("optional_permissions",
                          base::Value::List().Append("tabs"))
          .Build();

  TestEventRouterObserver test_observer(event_router);
  EXPECT_FALSE(WasItemChangedEventDispatched(
      test_observer, dummy_extension->id(),
      api::developer_private::EventType::kPermissionsChanged));

  APIPermissionSet apis;
  apis.insert(extensions::mojom::APIPermissionID::kTab);
  PermissionSet permissions(std::move(apis), ManifestPermissionSet(),
                            URLPatternSet(), URLPatternSet());
  permissions_test_util::GrantOptionalPermissionsAndWaitForCompletion(
      profile(), *dummy_extension, permissions);

  // The event router fetches icons from a blocking thread when sending the
  // update event; allow it to finish before verifying the event was dispatched.
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(WasItemChangedEventDispatched(
      test_observer, dummy_extension->id(),
      api::developer_private::EventType::kPermissionsChanged));

  test_observer.ClearEvents();

  permissions_test_util::RevokeOptionalPermissionsAndWaitForCompletion(
      profile(), *dummy_extension, permissions,
      PermissionsUpdater::REMOVE_HARD);
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(WasItemChangedEventDispatched(
      test_observer, dummy_extension->id(),
      api::developer_private::EventType::kPermissionsChanged));
}

class DeveloperPrivateApiZipFileUnitTest
    : public DeveloperPrivateApiUnitTest,
      public testing::WithParamInterface<bool> {
 public:
  void SetUp() override {
    DeveloperPrivateApiUnitTest::SetUp();
    expected_extension_install_directory_ =
        registrar()->unpacked_install_directory();
  }

 protected:
  base::FilePath expected_extension_install_directory_;
};

TEST_F(DeveloperPrivateApiZipFileUnitTest, InstallDroppedFileZip) {
  base::FilePath zip_path = data_dir().AppendASCII("simple_empty.zip");
  base::AutoReset<bool> disable_ui =
      ExtensionInstallUI::disable_ui_for_tests(true);
  ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT);

  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  DeveloperPrivateAPI::Get(profile())->SetDraggedFile(
      web_contents.get(), ui::FileInfo(zip_path, zip_path.BaseName()));

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>();
  function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());

  TestExtensionRegistryObserver observer(registry());
  ASSERT_TRUE(api_test_utils::RunFunction(function.get(), "[]", profile()))
      << function->GetError();
  scoped_refptr<const Extension> extension =
      observer.WaitForExtensionInstalled();
  ASSERT_TRUE(extension);
  EXPECT_EQ("Simple Empty Extension", extension->name());

  // Expect extension install directory to be immediate subdir of expected
  // unpacked install directory. E.g. /a/b/c/d == /a/b/c + /d.
  //
  // Make sure we're comparing absolute paths to avoid failures like
  // https://crbug.com/1453671 on macOS 14.
  base::FilePath absolute_extension_path =
      base::MakeAbsoluteFilePath(extension->path());
  base::FilePath absolute_expected_extension_install_directory =
      base::MakeAbsoluteFilePath(expected_extension_install_directory_.Append(
          extension->path().BaseName()));
  EXPECT_EQ(absolute_extension_path,
            absolute_expected_extension_install_directory);

  // Expect extension install directory to exist and be named with the right
  // prefix.
  EXPECT_TRUE(base::PathExists(extension->path()));
  EXPECT_TRUE(
      extension->path().BaseName().AsUTF8Unsafe().starts_with("simple_empty"));
}

// Test developerPrivate.getUserSiteSettings.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateGetUserSiteSettings) {
  PermissionsManager* manager = PermissionsManager::Get(browser_context());
  const url::Origin restricted_url =
      url::Origin::Create(GURL("http://example.com"));

  manager->AddUserRestrictedSite(restricted_url);

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateGetUserSiteSettingsFunction>();

  std::optional<base::Value> result =
      api_test_utils::RunFunctionAndReturnSingleResult(
          function.get(), /*args=*/"[]", profile());
  ASSERT_TRUE(result.has_value());
  std::optional<api::developer_private::UserSiteSettings> settings =
      api::developer_private::UserSiteSettings::FromValue(result.value());

  ASSERT_TRUE(settings);
  EXPECT_THAT(settings->permitted_sites, testing::IsEmpty());
  EXPECT_THAT(settings->restricted_sites,
              testing::UnorderedElementsAre("http://example.com"));
}

// Test developerPrivate.addUserSpecifiedSite and removeUserSpecifiedSite for
// restricted sites.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateModifyUserSiteSettings) {
  static constexpr char kExample[] = "http://example.com";
  static constexpr char kChromium[] = "http://chromium.org";

  const url::Origin example_url = url::Origin::Create(GURL(kExample));
  const url::Origin chromium_url = url::Origin::Create(GURL(kChromium));

  // Add restricted sites, and check that these sites are stored in the manager.
  EXPECT_NO_FATAL_FAILURE(AddUserSpecifiedSites(
      profile(), base::StringPrintf(R"(["%s","%s"])", kExample, kChromium),
      /*restricted=*/true));

  PermissionsManager* manager = PermissionsManager::Get(browser_context());
  EXPECT_THAT(manager->GetUserPermissionsSettings().permitted_sites,
              testing::IsEmpty());
  EXPECT_THAT(manager->GetUserPermissionsSettings().restricted_sites,
              testing::UnorderedElementsAre(example_url, chromium_url));

  // Remove restricted site, and check that the site was removed in the manager.
  EXPECT_NO_FATAL_FAILURE(RemoveUserSpecifiedSites(
      profile(), base::StringPrintf(R"(["%s"])", kExample),
      /*restricted=*/true));

  EXPECT_THAT(manager->GetUserPermissionsSettings().permitted_sites,
              testing::IsEmpty());
  EXPECT_THAT(manager->GetUserPermissionsSettings().restricted_sites,
              testing::UnorderedElementsAre(chromium_url));
}

// Test that the OnUserSiteSettingsChanged event is fired whenever the user
// defined site settings update.
TEST_F(DeveloperPrivateApiUnitTest, OnUserSiteSettingsChanged) {
  static constexpr char kExample[] = "http://example.com";

  // We need to call DeveloperPrivateAPI::Get() in order to instantiate the
  // keyed service, since it's not created by default in unit tests.
  DeveloperPrivateAPI::Get(profile());
  EventRouter* event_router = EventRouter::Get(profile());

  // The DeveloperPrivateEventRouter will only dispatch events if there's at
  // least one listener to dispatch to. Create one.
  const char* kEventName =
      api::developer_private::OnUserSiteSettingsChanged::kEventName;
  event_router->AddEventListener(kEventName, render_process_host(),
                                 crx_file::id_util::GenerateId("listener"));

  TestEventRouterObserver test_observer(event_router);

  api::developer_private::UserSiteSettings settings;
  EXPECT_FALSE(
      WasUserSiteSettingsChangedEventDispatched(test_observer, &settings));

  // Add a restricted site, and check the event that it's
  // only contained in the restricted list.
  const std::string kExampleArg = base::StringPrintf(R"(["%s"])", kExample);
  EXPECT_NO_FATAL_FAILURE(
      AddUserSpecifiedSites(profile(), kExampleArg, /*restricted=*/true));
  EXPECT_TRUE(
      WasUserSiteSettingsChangedEventDispatched(test_observer, &settings));
  EXPECT_THAT(settings.permitted_sites, testing::IsEmpty());
  EXPECT_THAT(settings.restricted_sites,
              testing::UnorderedElementsAre(kExample));

  // Remove the site, and check the event that both lists are empty.
  EXPECT_NO_FATAL_FAILURE(
      RemoveUserSpecifiedSites(profile(), kExampleArg, /*restricted=*/true));
  EXPECT_TRUE(
      WasUserSiteSettingsChangedEventDispatched(test_observer, &settings));
  EXPECT_THAT(settings.permitted_sites, testing::IsEmpty());
  EXPECT_THAT(settings.restricted_sites, testing::IsEmpty());
}

class DeveloperPrivateApiWithPermittedSitesUnitTest
    : public DeveloperPrivateApiUnitTest {
 public:
  DeveloperPrivateApiWithPermittedSitesUnitTest();
  DeveloperPrivateApiWithPermittedSitesUnitTest(
      const DeveloperPrivateApiWithPermittedSitesUnitTest&) = delete;
  const DeveloperPrivateApiWithPermittedSitesUnitTest& operator=(
      const DeveloperPrivateApiWithPermittedSitesUnitTest&) = delete;
  ~DeveloperPrivateApiWithPermittedSitesUnitTest() override = default;

 private:
  base::test::ScopedFeatureList feature_list_;
};

DeveloperPrivateApiWithPermittedSitesUnitTest::
    DeveloperPrivateApiWithPermittedSitesUnitTest() {
  feature_list_.InitAndEnableFeature(
      extensions_features::kExtensionsMenuAccessControlWithPermittedSites);
}

// Test developerPrivate.getUserSiteSettings.
TEST_F(DeveloperPrivateApiWithPermittedSitesUnitTest,
       DeveloperPrivateGetUserSiteSettings) {
  PermissionsManager* manager = PermissionsManager::Get(browser_context());
  const url::Origin permitted_url =
      url::Origin::Create(GURL("http://a.example.com"));
  const url::Origin restricted_url =
      url::Origin::Create(GURL("http://b.example.com"));

  manager->AddUserPermittedSite(permitted_url);
  manager->AddUserRestrictedSite(restricted_url);

  auto function =
      base::MakeRefCounted<api::DeveloperPrivateGetUserSiteSettingsFunction>();

  base::Value::List args;
  EXPECT_TRUE(RunFunction(function, args)) << function->GetError();
  ASSERT_TRUE(function->GetResultListForTest());
  ASSERT_EQ(1u, function->GetResultListForTest()->size());
  const base::Value& response_value = (*function->GetResultListForTest())[0];
  std::optional<api::developer_private::UserSiteSettings> settings =
      api::developer_private::UserSiteSettings::FromValue(response_value);

  ASSERT_TRUE(settings);
  EXPECT_THAT(settings->permitted_sites,
              testing::UnorderedElementsAre("http://a.example.com"));
  EXPECT_THAT(settings->restricted_sites,
              testing::UnorderedElementsAre("http://b.example.com"));
}

// Test developerPrivate.addUserSpecifiedSite and removeUserSpecifiedSite.
TEST_F(DeveloperPrivateApiWithPermittedSitesUnitTest,
       DeveloperPrivateModifyUserSiteSettings) {
  static constexpr char kExample[] = "http://example.com";
  static constexpr char kChromium[] = "http://chromium.org";
  static constexpr char kGoogle[] = "http://google.com";

  const url::Origin example_url = url::Origin::Create(GURL(kExample));
  const url::Origin chromium_url = url::Origin::Create(GURL(kChromium));
  const url::Origin google_url = url::Origin::Create(GURL(kGoogle));

  auto get_hosts_arg = [](const char* host) {
    return base::StringPrintf(R"(["%s"])", host);
  };

  // First, add some permitted and restricted sites, and check that these sites
  // are stored in the manager.
  EXPECT_NO_FATAL_FAILURE(AddUserSpecifiedSites(
      profile(), base::StringPrintf(R"(["%s","%s"])", kExample, kChromium),
      /*restricted=*/false));
  EXPECT_NO_FATAL_FAILURE(AddUserSpecifiedSites(
      profile(), get_hosts_arg(kGoogle), /*restricted=*/true));

  PermissionsManager* manager = PermissionsManager::Get(browser_context());
  EXPECT_THAT(manager->GetUserPermissionsSettings().permitted_sites,
              testing::UnorderedElementsAre(example_url, chromium_url));
  EXPECT_THAT(manager->GetUserPermissionsSettings().restricted_sites,
              testing::UnorderedElementsAre(google_url));

  // Attempting to add a restricted site should remove it as a permitted site.
  EXPECT_NO_FATAL_FAILURE(AddUserSpecifiedSites(
      profile(), get_hosts_arg(kChromium), /*restricted=*/true));
  EXPECT_NO_FATAL_FAILURE(RemoveUserSpecifiedSites(
      profile(), get_hosts_arg(kExample), /*restricted=*/false));

  EXPECT_TRUE(manager->GetUserPermissionsSettings().permitted_sites.empty());
  EXPECT_THAT(manager->GetUserPermissionsSettings().restricted_sites,
              testing::UnorderedElementsAre(chromium_url, google_url));

  EXPECT_NO_FATAL_FAILURE(RemoveUserSpecifiedSites(
      profile(), base::StringPrintf(R"(["%s","%s"])", kGoogle, kChromium),
      /*restricted=*/true));
  EXPECT_TRUE(manager->GetUserPermissionsSettings().restricted_sites.empty());
}

TEST_F(DeveloperPrivateApiWithPermittedSitesUnitTest,
       DeveloperPrivateGetUserAndExtensionSitesByEtld_UserSites) {
  PermissionsManager* manager = PermissionsManager::Get(browser_context());

  // Add two sites under the eTLD+1 example.com, and one under eTLD+1 google.ca.
  manager->AddUserPermittedSite(
      url::Origin::Create(GURL("http://a.example.com")));
  manager->AddUserRestrictedSite(
      url::Origin::Create(GURL("http://b.example.com")));
  manager->AddUserRestrictedSite(url::Origin::Create(GURL("http://google.ca")));

  auto function = base::MakeRefCounted<
      api::DeveloperPrivateGetUserAndExtensionSitesByEtldFunction>();
  EXPECT_TRUE(RunFunction(function, base::Value::List()))
      << function->GetError();
  const base::Value::List* results = function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());

  EXPECT_THAT((*results)[0], base::test::IsJson(R"([{
    "etldPlusOne": "example.com",
    "numExtensions": 0,
    "sites": [{
      "siteSet": "USER_PERMITTED",
      "numExtensions": 0,
      "site": "a.example.com",
    }, {
      "siteSet": "USER_RESTRICTED",
      "numExtensions": 0,
      "site": "b.example.com",
    }]
  }, {
    "etldPlusOne": "google.ca",
    "numExtensions": 0,
    "sites": [{
      "siteSet": "USER_RESTRICTED",
      "numExtensions": 0,
      "site": "google.ca",
    }]
  }])"));
}

TEST_F(DeveloperPrivateApiWithPermittedSitesUnitTest,
       DeveloperPrivateGetUserAndExtensionSitesByEtld_UserAndExtensionSites) {
  PermissionsManager* manager = PermissionsManager::Get(browser_context());
  manager->AddUserPermittedSite(
      url::Origin::Create(GURL("http://images.google.com")));
  manager->AddUserRestrictedSite(
      url::Origin::Create(GURL("http://www.asdf.com")));

  scoped_refptr<const Extension> extension_1 =
      ExtensionBuilder("test")
          .AddHostPermission("https://*.google.com/")
          .AddHostPermission("http://www.google.com/")
          .AddHostPermission("http://images.google.com/")
          .AddHostPermission("https://example.com/")
          .AddHostPermission("*://localhost/")
          .Build();

  scoped_refptr<const Extension> extension_2 =
      ExtensionBuilder("test_2")
          .AddHostPermission("https://mail.google.com/")
          .AddHostPermission("http://www.google.com/")
          .AddHostPermission("http://www.asdf.com/")
          .AddHostPermission("http://localhost:8080/")
          .Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_1);
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_2);

  auto function = base::MakeRefCounted<
      api::DeveloperPrivateGetUserAndExtensionSitesByEtldFunction>();
  EXPECT_TRUE(RunFunction(function, base::Value::List()))
      << function->GetError();
  const base::Value::List* results = function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());

  // asdf.com and http://www.asdf.com should not have any extensions counted
  // because they are associated with user specified sites.
  EXPECT_THAT((*results)[0], base::test::IsJson(R"([{
    "etldPlusOne": "asdf.com",
    "numExtensions": 0,
    "sites": [{
      "siteSet": "USER_RESTRICTED",
      "numExtensions": 0,
      "site": "www.asdf.com",
    }]
  }, {
    "etldPlusOne": "example.com",
    "numExtensions": 1,
    "sites": [{
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 1,
      "site": "example.com",
    }]
  }, {
    "etldPlusOne": "google.com",
    "numExtensions": 2,
    "sites": [{
      "siteSet": "USER_PERMITTED",
      "numExtensions": 0,
      "site": "images.google.com",
    }, {
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 2,
      "site": "mail.google.com",
    }, {
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 2,
      "site": "www.google.com",
    }, {
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 1,
      "site": "*.google.com",
    },]
  }, {
    "etldPlusOne": "localhost",
    "numExtensions": 2,
    "sites": [{
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 2,
      "site": "localhost",
    }]
  }])"));
}

TEST_F(DeveloperPrivateApiWithPermittedSitesUnitTest,
       DeveloperPrivateGetUserAndExtensionSitesByEtld_EffectiveAllHosts) {
  PermissionsManager* manager = PermissionsManager::Get(browser_context());
  manager->AddUserPermittedSite(
      url::Origin::Create(GURL("http://images.google.ca")));
  manager->AddUserRestrictedSite(url::Origin::Create(GURL("https://yahoo.ca")));

  scoped_refptr<const Extension> extension_1 =
      ExtensionBuilder("specific_hosts")
          .AddHostPermission("https://*.google.ca/")
          .AddHostPermission("http://www.example.com/")
          .Build();

  scoped_refptr<const Extension> extension_2 =
      ExtensionBuilder("all_.com").AddHostPermission("*://*.com/*").Build();

  scoped_refptr<const Extension> extension_3 =
      ExtensionBuilder("all_urls").AddHostPermission("<all_urls>").Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_1);
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_2);
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_3);

  auto function = base::MakeRefCounted<
      api::DeveloperPrivateGetUserAndExtensionSitesByEtldFunction>();
  EXPECT_TRUE(RunFunction(function, base::Value::List()))
      << function->GetError();
  const base::Value::List* results = function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());

  // `extension_2` should not be counted for https://*.google.ca/* as it
  // cannot run on .ca sites.
  EXPECT_THAT((*results)[0], base::test::IsJson(R"([{
    "etldPlusOne": "example.com",
    "numExtensions": 3,
    "sites": [{
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 3,
      "site": "www.example.com",
    }, {
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 2,
      "site": "*.example.com",
    }]
  }, {
    "etldPlusOne": "google.ca",
    "numExtensions": 2,
    "sites": [{
      "siteSet": "USER_PERMITTED",
      "numExtensions": 0,
      "site": "images.google.ca",
    }, {
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 2,
      "site": "*.google.ca",
    }]
  }, {
    "etldPlusOne": "yahoo.ca",
    "numExtensions": 1,
    "sites": [{
      "siteSet": "USER_RESTRICTED",
      "numExtensions": 0,
      "site": "yahoo.ca",
    }, {
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 1,
      "site": "*.yahoo.ca",
    }]
  }])"));
}

TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateGetUserAndExtensionSitesByEtld_RuntimeGrantedHosts) {
  scoped_refptr<const Extension> extension_1 =
      ExtensionBuilder("runtime_hosts").AddHostPermission("<all_urls>").Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_1);

  auto get_user_and_extension_sites = [this](const std::string& expected_json) {
    auto function = base::MakeRefCounted<
        api::DeveloperPrivateGetUserAndExtensionSitesByEtldFunction>();
    EXPECT_TRUE(RunFunction(function, base::Value::List()))
        << function->GetError();
    const base::Value::List* results = function->GetResultListForTest();
    ASSERT_EQ(1u, results->size());
    EXPECT_THAT((*results)[0], base::test::IsJson(expected_json));
  };

  get_user_and_extension_sites(R"([])");

  EXPECT_FALSE(PermissionsManager::Get(browser()->profile())
                   ->HasWithheldHostPermissions(*extension_1));

  ScriptingPermissionsModifier modifier(profile(), extension_1.get());
  modifier.SetWithholdHostPermissions(true);

  get_user_and_extension_sites(R"([])");

  const std::string kExampleCom = "https://example.com/*";
  RunAddHostPermission(profile(), *extension_1, kExampleCom,
                       /*should_succeed=*/true, nullptr);

  get_user_and_extension_sites(R"([{
    "etldPlusOne": "example.com",
    "numExtensions": 1,
    "sites": [{
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 1,
      "site": "example.com",
    }]
  }])");

  scoped_refptr<const Extension> extension_2 =
      ExtensionBuilder("test").AddHostPermission(kExampleCom).Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_2);

  get_user_and_extension_sites(R"([{
    "etldPlusOne": "example.com",
    "numExtensions": 2,
    "sites": [{
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 2,
      "site": "example.com",
    }]
  }])");

  RunUpdateHostAccess(*extension_1, "ON_ALL_SITES");
  get_user_and_extension_sites(R"([{
    "etldPlusOne": "example.com",
    "numExtensions": 2,
    "sites": [{
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 2,
      "site": "example.com",
    }, {
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 1,
      "site": "*.example.com",
    }]
  }])");
}

// Test that host permissions from policy installed extensions are included in
// `getUserAndExtensionSitesByEtld` calls.
TEST_F(
    DeveloperPrivateApiUnitTest,
    DeveloperPrivateGetUserAndExtensionSitesByEtld_PolicyControlledExtensions) {
  ExtensionId extension_id(kGoogleOnlyCrx);

  // Set up a mock provider with a policy extension.
  std::unique_ptr<MockExternalProvider> mock_provider =
      std::make_unique<MockExternalProvider>(
          external_provider_manager(),
          mojom::ManifestLocation::kExternalPolicyDownload);
  MockExternalProvider* mock_provider_ptr = mock_provider.get();
  AddMockExternalProvider(std::move(mock_provider));

  // google_only.crx contains only a manifest.json file that requests
  // *://www.google.com/* as a permission.
  mock_provider_ptr->UpdateOrAddExtension(
      extension_id, "1", data_dir().AppendASCII("google_only.crx"));
  // Reloading extensions should find our externally registered extension
  // and install it.
  {
    TestExtensionRegistryObserver observer(registry());
    external_provider_manager()->CheckForExternalUpdates();
    EXPECT_EQ(extension_id, observer.WaitForExtensionLoaded()->id());
  }

  auto function = base::MakeRefCounted<
      api::DeveloperPrivateGetUserAndExtensionSitesByEtldFunction>();
  EXPECT_TRUE(RunFunction(function, base::Value::List()))
      << function->GetError();
  const base::Value::List* results = function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());

  EXPECT_THAT((*results)[0], base::test::IsJson(R"([{
    "etldPlusOne": "google.com",
    "numExtensions": 1,
    "sites": [{
      "siteSet": "EXTENSION_SPECIFIED",
      "numExtensions": 1,
      "site": "www.google.com",
    }]
  }])"));
}

TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateGetMatchingExtensionsForSite) {
  namespace developer = api::developer_private;

  scoped_refptr<const Extension> extension_1 =
      ExtensionBuilder("test")
          .AddHostPermission("*://mail.google.com/")
          .Build();

  scoped_refptr<const Extension> extension_2 =
      ExtensionBuilder("test_2")
          .AddHostPermission("*://images.google.com/")
          .Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_1);
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_2);

  std::vector<developer::MatchingExtensionInfo> infos;
  GetMatchingExtensionsForSite(profile(), "http://none.com/", &infos);
  EXPECT_TRUE(infos.empty());

  GetMatchingExtensionsForSite(profile(), "http://images.google.com/", &infos);

  // "http://images.google.com/" should only match with `extension_2`.
  EXPECT_THAT(infos,
              testing::UnorderedElementsAre(MatchMatchingExtensionInfo(
                  extension_2->id(), developer::HostAccess::kOnSpecificSites,
                  /*can_request_all_sites=*/false)));

  registrar()->DisableExtension(extension_2->id(),
                                {disable_reason::DISABLE_USER_ACTION});
  GetMatchingExtensionsForSite(profile(), "*://*.google.com/", &infos);

  // "*://*.google.com/" should match with `extension_1` but not `extension_2`
  // since it is disabled.
  EXPECT_THAT(infos,
              testing::UnorderedElementsAre(MatchMatchingExtensionInfo(
                  extension_1->id(), developer::HostAccess::kOnSpecificSites,
                  /*can_request_all_sites=*/false)));
}

// Test that the host access returned by GetMatchingExtensionsForSite reflects
// whether the extension has access to the queried site, or has withheld sites
// in general.
TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateGetMatchingExtensionsForSite_RuntimeGrantedHostAccess) {
  namespace developer = api::developer_private;

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test").AddHostPermission("<all_urls>").Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension);

  std::vector<developer::MatchingExtensionInfo> infos;
  GetMatchingExtensionsForSite(profile(), "http://example.com/", &infos);

  EXPECT_THAT(infos, testing::UnorderedElementsAre(MatchMatchingExtensionInfo(
                         extension->id(), developer::HostAccess::kOnAllSites,
                         /*can_request_all_sites=*/true)));
  EXPECT_FALSE(PermissionsManager::Get(browser()->profile())
                   ->HasWithheldHostPermissions(*extension));

  ScriptingPermissionsModifier modifier(profile(), extension.get());
  modifier.SetWithholdHostPermissions(true);

  GetMatchingExtensionsForSite(profile(), "http://example.com/", &infos);
  EXPECT_THAT(infos, testing::UnorderedElementsAre(MatchMatchingExtensionInfo(
                         extension->id(), developer::HostAccess::kOnClick,
                         /*can_request_all_sites=*/true)));

  RunAddHostPermission(profile(), *extension, "*://*.google.com/*",
                       /*should_succeed=*/true, nullptr);

  GetMatchingExtensionsForSite(profile(), "http://google.com/", &infos);
  EXPECT_THAT(infos,
              testing::UnorderedElementsAre(MatchMatchingExtensionInfo(
                  extension->id(), developer::HostAccess::kOnSpecificSites,
                  /*can_request_all_sites=*/true)));

  GetMatchingExtensionsForSite(profile(), "http://example.com/", &infos);
  EXPECT_THAT(infos, testing::UnorderedElementsAre(MatchMatchingExtensionInfo(
                         extension->id(), developer::HostAccess::kOnClick,
                         /*can_request_all_sites=*/true)));
}

// Tests the UpdateSiteAccess function when called on an extension with no
// withheld host permissions.
TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateUpdateSiteAccess_NoWithheldHostPermissions) {
  namespace developer = api::developer_private;

  ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile());

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test")
          .AddHostPermission("http://a.example.com/*")
          .AddHostPermission("*://b.example.com/*")
          .AddHostPermission("http://google.com/*")
          .Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension);

  PermissionsManager* permissions_manager = PermissionsManager::Get(profile());
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));

  // Change state from ON_ALL_SITES to ON_CLICK.
  std::vector<developer::ExtensionSiteAccessUpdate> updates;
  updates.push_back(
      CreateSiteAccessUpdate(extension->id(), developer::HostAccess::kOnClick));
  UpdateSiteAccess(profile(), "http://google.com/*", updates);

  // Check that all host permissions are withheld when the site access is
  // changed to ON_CLICK if there are no withheld host permissions.
  EXPECT_TRUE(permissions_manager->HasWithheldHostPermissions(*extension));
  EXPECT_EQ(PermissionSet(),
            *extension_prefs->GetRuntimeGrantedPermissions(extension->id()));

  // Change state from ON_CLICK to ON_ALL_SITES.
  updates.clear();
  updates.push_back(CreateSiteAccessUpdate(extension->id(),
                                           developer::HostAccess::kOnAllSites));
  UpdateSiteAccess(profile(), "http://google.com/*", updates);

  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));

  // Change state from ON_ALL_SITES to ON_SPECIFIC_SITES.
  updates.clear();
  updates.push_back(CreateSiteAccessUpdate(
      extension->id(), developer::HostAccess::kOnSpecificSites));
  UpdateSiteAccess(profile(), "*://*.example.com/*", updates);

  // Check that the pattern is added as-is to the extension's runtime granted
  // permissions when the site access is changed to ON_SPECIFIC_SITES if there
  // are no withheld host permissions.
  URLPattern example_pattern(Extension::kValidHostPermissionSchemes,
                             "*://*.example.com/*");
  EXPECT_EQ(URLPatternSet({example_pattern}),
            (*extension_prefs->GetRuntimeGrantedPermissions(extension->id()))
                .effective_hosts());

  // Check that the extension's actual active host permissions is an
  // intersection of their manifest and runtime granted hosts.
  URLPattern a_example_pattern(Extension::kValidHostPermissionSchemes,
                               "http://a.example.com/*");
  URLPattern b_example_pattern(Extension::kValidHostPermissionSchemes,
                               "*://b.example.com/*");
  EXPECT_EQ(
      URLPatternSet({a_example_pattern, b_example_pattern}),
      extension->permissions_data()->active_permissions().effective_hosts());
}

// Tests the UpdateSiteAccess function when called on an extension with withheld
// host permissions. In particular, test that if the site access is set to
// ON_CLICK, all host permissions that match the specified site will be revoked.
TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateUpdateSiteAccess_WitheldHostPermissions) {
  namespace developer = api::developer_private;

  scoped_refptr<const Extension> extension =
      ExtensionBuilder("test")
          .AddHostPermission("*://*.example.com/*")
          .AddHostPermission("*://*.google.com/*")
          .Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension);

  PermissionsManager* permissions_manager = PermissionsManager::Get(profile());
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension));

  // Change state from ON_ALL_SITES to ON_SPECIFIC_SITES.
  std::vector<developer::ExtensionSiteAccessUpdate> updates;
  updates.push_back(CreateSiteAccessUpdate(
      extension->id(), developer::HostAccess::kOnSpecificSites));
  UpdateSiteAccess(profile(), "http://google.com/*", updates);
  UpdateSiteAccess(profile(), "*://mail.google.com/*", updates);
  UpdateSiteAccess(profile(), "https://maps.google.com/*", updates);
  UpdateSiteAccess(profile(), "*://example.com/*", updates);

  // Confirm that all four sites have been added to runtime granted host
  // permissions.
  const GURL kGoogleCom("http://google.com");
  const GURL kMailGoogleCom("https://mail.google.com/");
  const GURL kMapsGoogleCom("https://maps.google.com/");
  const GURL kExampleCom("http://example.com/");
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension,
                                                            kMailGoogleCom));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension,
                                                            kMapsGoogleCom));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));

  // Change state from ON_SPECIFIC_SITES to ON_CLICK. This will revoke
  // "http://google.com/*", "https://maps.google.com/*", and
  // "*://mail.google.com/*" as they match the pattern "http://*.google.com/*"
  // that is being removed.
  updates.clear();
  updates.push_back(
      CreateSiteAccessUpdate(extension->id(), developer::HostAccess::kOnClick));
  UpdateSiteAccess(profile(), "http://*.google.com/*", updates);

  // The sites `kGoogleCom` and `kMailGoogleCom` match previously granted
  // patterns that were revoked when they matched "http://*.google.com/*" that
  // was called in UpdateSiteAccess. As such, they should no longer be granted.
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_FALSE(permissions_manager->HasGrantedHostPermission(*extension,
                                                             kMailGoogleCom));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension,
                                                            kMapsGoogleCom));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));

  // Change state from ON_CLICK to ON_SPECIFIC_SITES.
  updates.clear();
  updates.push_back(CreateSiteAccessUpdate(
      extension->id(), developer::HostAccess::kOnSpecificSites));
  UpdateSiteAccess(profile(), "*://mail.google.com/*", updates);
  // `kMailGoogleCom` matches the pattern "*://mail.google.com/*" that is being
  // added, so it should be granted again.
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension, kGoogleCom));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension,
                                                            kMailGoogleCom));
  EXPECT_TRUE(permissions_manager->HasGrantedHostPermission(*extension,
                                                            kMapsGoogleCom));
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension, kExampleCom));
}

// Test that the UpdateSiteAccess function can be applied to multiple
// extensions.
TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateUpdateSiteAccess_MultipleExtensions) {
  namespace developer = api::developer_private;

  scoped_refptr<const Extension> extension_1 =
      ExtensionBuilder("test_1").AddHostPermission("<all_urls>").Build();
  scoped_refptr<const Extension> extension_2 =
      ExtensionBuilder("test_2").AddHostPermission("<all_urls>").Build();
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_1);
  AddExtensionAndGrantPermissions(profile(), registrar(), *extension_2);

  PermissionsManager* permissions_manager = PermissionsManager::Get(profile());
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension_1));
  EXPECT_FALSE(permissions_manager->HasWithheldHostPermissions(*extension_2));

  std::vector<developer::ExtensionSiteAccessUpdate> updates;
  updates.push_back(CreateSiteAccessUpdate(
      extension_1->id(), developer::HostAccess::kOnSpecificSites));
  updates.push_back(CreateSiteAccessUpdate(extension_2->id(),
                                           developer::HostAccess::kOnClick));
  UpdateSiteAccess(profile(), "http://google.com/*", updates);

  // Confirm that `extension_1` can still access `kGoogleCom` but `extension_2`
  // cannot.
  const GURL kGoogleCom("http://google.com");
  EXPECT_TRUE(
      permissions_manager->HasGrantedHostPermission(*extension_1, kGoogleCom));
  EXPECT_FALSE(
      permissions_manager->HasGrantedHostPermission(*extension_2, kGoogleCom));
}

// Test uninstalling multiple extensions.
TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateRemoveMultipleExtensions) {
  scoped_refptr<const Extension> extension_1 =
      ExtensionBuilder("test_1").Build();
  scoped_refptr<const Extension> extension_2 =
      ExtensionBuilder("test_2").Build();
  registrar()->AddExtension(extension_1.get());
  registrar()->AddExtension(extension_2.get());
  EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_1->id()));
  EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_2->id()));

  std::string args = base::StrCat(
      {"[[\"", extension_1->id(), "\", \"", extension_2->id(), "\"]]"});

  auto function = base::MakeRefCounted<
      api::DeveloperPrivateRemoveMultipleExtensionsFunction>();

  // Accept the multiple extension uninstallation bubble by default in unit
  // tests.
  function->accept_bubble_for_testing(true);

  // Run the private api to remove the installed extensions.
  api_test_utils::RunFunction(function.get(), args, profile());

  EXPECT_FALSE(registry()->enabled_extensions().Contains(extension_1->id()));
  EXPECT_FALSE(registry()->enabled_extensions().Contains(extension_2->id()));
  EXPECT_EQ(registry()->enabled_extensions().size(), 0u);
}

// Test cancelling uninstall multiple extensions dialog.
TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateCancelRemoveMultipleExtensions) {
  scoped_refptr<const Extension> extension_1 =
      ExtensionBuilder("test_1").Build();
  scoped_refptr<const Extension> extension_2 =
      ExtensionBuilder("test_2").Build();
  registrar()->AddExtension(extension_1.get());
  registrar()->AddExtension(extension_2.get());
  EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_1->id()));
  EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_2->id()));

  std::string args = base::StrCat(
      {"[[\"", extension_1->id(), "\", \"", extension_2->id(), "\"]]"});

  auto function = base::MakeRefCounted<
      api::DeveloperPrivateRemoveMultipleExtensionsFunction>();

  // Cancel the multiple extension uninstallation bubble, the correct error
  // message is shown and extensions are not removed.
  function->accept_bubble_for_testing(false);
  EXPECT_EQ("User cancelled uninstall",
            api_test_utils::RunFunctionAndReturnError(function.get(), args,
                                                      profile()));
  EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_1->id()));
  EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_2->id()));
  EXPECT_EQ(registry()->enabled_extensions().size(), 2u);
}

TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateRemoveComponentExtensions) {
  // Create a component extension and a regular extension, then try to remove
  // them.
  scoped_refptr<const Extension> component_extension =
      ExtensionBuilder("component_extension")
          .SetLocation(mojom::ManifestLocation::kComponent)
          .Build();
  scoped_refptr<const Extension> test_extension =
      ExtensionBuilder("test_extension").Build();
  registrar()->AddExtension(component_extension.get());
  registrar()->AddExtension(test_extension.get());

  EXPECT_EQ(registry()->enabled_extensions().size(), 2u);

  // Create a list of extensions with a component extension in it.
  base::Value::List extensions_list;
  extensions_list.reserve(2u);
  extensions_list.Append(component_extension->id());
  extensions_list.Append(test_extension->id());
  std::string args;
  EXPECT_TRUE(base::JSONWriter::Write(extensions_list, &args));
  std::string component_args = base::StringPrintf(R"([%s])", args.c_str());
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateRemoveMultipleExtensionsFunction>();

  // Accept the multiple extension uninstallation bubble by default in unit
  // tests.
  function->accept_bubble_for_testing(true);
  // Verify the error message for uninstalling component and enterprise
  // extensions.
  EXPECT_EQ(
      "Cannot uninstall the enterprise or component extensions in your list.",
      api_test_utils::RunFunctionAndReturnError(function.get(), component_args,
                                                profile()));

  // Because there is a component extension in the list, the uninstallation is
  // canceled. The number of extensions remains the same.
  EXPECT_EQ(registry()->enabled_extensions().size(), 2u);
}

TEST_F(DeveloperPrivateApiUnitTest,
       DeveloperPrivateRemoveEnterpriseExtensions) {
  // Create an enterprise extension and a regular extension, then try to remove
  // them.
  scoped_refptr<const Extension> enterprise_extension =
      ExtensionBuilder("enterprise_extension")
          .SetLocation(mojom::ManifestLocation::kExternalPolicy)
          .Build();
  scoped_refptr<const Extension> test_extension =
      ExtensionBuilder("test_extension").Build();
  registrar()->AddExtension(enterprise_extension.get());
  registrar()->AddExtension(test_extension.get());

  EXPECT_EQ(registry()->enabled_extensions().size(), 2u);

  // Create a list of extensions with an enterprise extension in it.
  base::Value::List extensions_list;
  extensions_list.reserve(2u);
  extensions_list.Append(enterprise_extension->id());
  extensions_list.Append(test_extension->id());
  std::string args;
  EXPECT_TRUE(base::JSONWriter::Write(extensions_list, &args));
  std::string enterprise_args = base::StringPrintf(R"([%s])", args.c_str());
  auto function = base::MakeRefCounted<
      api::DeveloperPrivateRemoveMultipleExtensionsFunction>();

  // Accept the multiple extension uninstallation bubble by default in unit
  // tests.
  function->accept_bubble_for_testing(true);
  // Verify the error message for uninstalling component and enterprise
  // extensions.
  EXPECT_EQ(
      "Cannot uninstall the enterprise or component extensions in your list.",
      api_test_utils::RunFunctionAndReturnError(function.get(), enterprise_args,
                                                profile()));

  // Because there is an enterprise extension in the list, the uninstallation is
  // canceled. The number of extensions remains the same.
  EXPECT_EQ(registry()->enabled_extensions().size(), 2u);
}

// Test that an event is dispatched when the list of pinned extension actions
// has changed.
TEST_F(DeveloperPrivateApiUnitTest,
       ExtensionUpdatedEventOnPinnedActionsChange) {
  // We need to call DeveloperPrivateAPI::Get() in order to instantiate the
  // keyed service, since it's not created by default in unit tests.
  DeveloperPrivateAPI::Get(profile());
  EventRouter* event_router = EventRouter::Get(profile());

  // The DeveloperPrivateEventRouter will only dispatch events if there's at
  // least one listener to dispatch to. Create one.
  const char* kEventName =
      api::developer_private::OnItemStateChanged::kEventName;
  event_router->AddEventListener(kEventName, render_process_host(),
                                 crx_file::id_util::GenerateId("listener"));

  TestEventRouterObserver test_observer(event_router);

  scoped_refptr<const Extension> extension = ExtensionBuilder("test").Build();
  registrar()->AddExtension(extension.get());
  EXPECT_TRUE(registry()->enabled_extensions().Contains(extension->id()));

  // The event router fetches icons from a blocking thread when sending the
  // update event; allow it to finish before verifying the event was dispatched.
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(WasItemChangedEventDispatched(
      test_observer, extension->id(),
      api::developer_private::EventType::kPinnedActionsChanged));

  ToolbarActionsModel* toolbar_actions_model =
      ToolbarActionsModel::Get(profile());

  toolbar_actions_model->SetActionVisibility(
      extension->id(), !toolbar_actions_model->IsActionPinned(extension->id()));

  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(WasItemChangedEventDispatched(
      test_observer, extension->id(),
      api::developer_private::EventType::kPinnedActionsChanged));
}

class DeveloperPrivateApiAllowlistUnitTest
    : public DeveloperPrivateApiUnitTest {
 public:
  DeveloperPrivateApiAllowlistUnitTest() {
    feature_list_.InitAndEnableFeature(
        extensions_features::kSafeBrowsingCrxAllowlistShowWarnings);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_F(DeveloperPrivateApiAllowlistUnitTest,
       ExtensionUpdatedEventOnAllowlistWarningChange) {
  // We need to call DeveloperPrivateAPI::Get() in order to instantiate the
  // keyed service, since it's not created by default in unit tests.
  DeveloperPrivateAPI::Get(profile());
  const ExtensionId listener_id = crx_file::id_util::GenerateId("listener");
  EventRouter* event_router = EventRouter::Get(profile());

  // The DeveloperPrivateEventRouter will only dispatch events if there's at
  // least one listener to dispatch to. Create one.
  const char* kEventName =
      api::developer_private::OnItemStateChanged::kEventName;
  event_router->AddEventListener(kEventName, render_process_host(),
                                 listener_id);

  scoped_refptr<const Extension> dummy_extension = LoadSimpleExtension();
  base::RunLoop().RunUntilIdle();

  TestEventRouterObserver test_observer(event_router);
  EXPECT_FALSE(WasItemChangedEventDispatched(
      test_observer, dummy_extension->id(),
      api::developer_private::EventType::kPrefsChanged));

  safe_browsing::SetSafeBrowsingState(
      profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION);

  base::RunLoop().RunUntilIdle();
  // The warning state should not have changed since the allowlist state is not
  // set yet.
  EXPECT_FALSE(WasItemChangedEventDispatched(
      test_observer, dummy_extension->id(),
      api::developer_private::EventType::kPrefsChanged));

  service()->allowlist()->SetExtensionAllowlistState(dummy_extension->id(),
                                                     ALLOWLIST_NOT_ALLOWLISTED);

  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(WasItemChangedEventDispatched(
      test_observer, dummy_extension->id(),
      api::developer_private::EventType::kPrefsChanged));

  test_observer.ClearEvents();

  safe_browsing::SetSafeBrowsingState(
      profile()->GetPrefs(),
      safe_browsing::SafeBrowsingState::STANDARD_PROTECTION);

  base::RunLoop().RunUntilIdle();
  // The warning is now hidden because the profile is no longer Enhanced
  // Protection.
  EXPECT_TRUE(WasItemChangedEventDispatched(
      test_observer, dummy_extension->id(),
      api::developer_private::EventType::kPrefsChanged));
}

class DeveloperPrivateApiSupervisedUserUnitTest
    : public DeveloperPrivateApiUnitTest {
 public:
  DeveloperPrivateApiSupervisedUserUnitTest() = default;
  DeveloperPrivateApiSupervisedUserUnitTest(
      const DeveloperPrivateApiSupervisedUserUnitTest&) = delete;
  DeveloperPrivateApiSupervisedUserUnitTest& operator=(
      const DeveloperPrivateApiSupervisedUserUnitTest&) = delete;

  ~DeveloperPrivateApiSupervisedUserUnitTest() override = default;

  bool ProfileIsSupervised() const override { return true; }
};

// Tests trying to call loadUnpacked when the profile shouldn't be allowed to.
TEST_F(DeveloperPrivateApiSupervisedUserUnitTest,
       LoadUnpackedFailsForSupervisedUsers) {
  std::unique_ptr<content::WebContents> web_contents(
      content::WebContentsTester::CreateTestWebContents(profile(), nullptr));
  base::FilePath path = data_dir().AppendASCII("simple_with_popup");

    EXPECT_TRUE(supervised_user::AreExtensionsPermissionsEnabled(profile()));
    auto function =
        base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>();
    function->SetRenderFrameHost(web_contents->GetPrimaryMainFrame());
    std::string error = api_test_utils::RunFunctionAndReturnError(
        function.get(), "[]", profile());
    EXPECT_THAT(error, testing::HasSubstr("Child account"));
}

// Test suite for cases where the user is in the  MV2 deprecation "warning"
// experiment phase.
class DeveloperPrivateApiWithMV2DeprecationWarningUnitTest
    : public DeveloperPrivateApiUnitTest {
 public:
  DeveloperPrivateApiWithMV2DeprecationWarningUnitTest() {
    feature_list_.InitWithFeatures(
        /*enabled_features=*/{extensions_features::
                                  kExtensionManifestV2DeprecationWarning},
        /*disabled_features=*/{
            extensions_features::kExtensionManifestV2Disabled,
            extensions_features::kExtensionManifestV2Unsupported});
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

// Test suite for cases where the user is in the  MV2 deprecation "disabled"
// experiment phase.
class DeveloperPrivateApiWithMV2DeprecationDisabledUnitTest
    : public DeveloperPrivateApiUnitTest {
 public:
  DeveloperPrivateApiWithMV2DeprecationDisabledUnitTest() {
    feature_list_.InitAndEnableFeature(
        extensions_features::kExtensionManifestV2Disabled);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_F(DeveloperPrivateApiWithMV2DeprecationWarningUnitTest,
       TestAcknowledgingAnExtension) {
  // Add an extension that is affected by the MV2 deprecation.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("ext").SetManifestVersion(2).Build();
  registrar()->AddExtension(extension.get());

  ManifestV2ExperimentManager* experiment_manager =
      ManifestV2ExperimentManager::Get(browser_context());
  EXPECT_TRUE(experiment_manager->IsExtensionAffected(*extension));
  EXPECT_FALSE(experiment_manager->DidUserAcknowledgeNotice(extension->id()));

  base::Value::List args;
  args.Append(extension->id());

  // Dismiss the extension's notice.
  auto dismiss_notice_function = base::MakeRefCounted<
      api::DeveloperPrivateDismissMv2DeprecationNoticeForExtensionFunction>();
  dismiss_notice_function->set_source_context_type(mojom::ContextType::kWebUi);
  EXPECT_TRUE(RunFunction(dismiss_notice_function, args));

  // Extension's notice should be marked as acknowledged.
  EXPECT_TRUE(experiment_manager->IsExtensionAffected(*extension));
  EXPECT_TRUE(experiment_manager->DidUserAcknowledgeNotice(extension->id()));
}

TEST_F(DeveloperPrivateApiWithMV2DeprecationWarningUnitTest,
       TestAcknowledgingANonAffectedExtension) {
  // Add an extension that is not affected by the MV2 deprecation.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("ext").SetManifestVersion(3).Build();
  registrar()->AddExtension(extension.get());

  std::string args = base::StringPrintf(R"(["%s"])", extension->id().c_str());
  auto dismiss_notice_function = base::MakeRefCounted<
      api::DeveloperPrivateDismissMv2DeprecationNoticeForExtensionFunction>();
  dismiss_notice_function->set_source_context_type(mojom::ContextType::kWebUi);

  // Cannot dismiss an extension's notice whe the extension is not affected by
  // the MV2 deprecation.
  std::string error = api_test_utils::RunFunctionAndReturnError(
      dismiss_notice_function, args, browser()->profile());
  EXPECT_EQ(error,
            ErrorUtils::FormatErrorMessage(
                "Extension with ID '*' is not affected by the MV2 deprecation.",
                extension->id()));

  // Extension notice should not be marked as acknowledged.
  ManifestV2ExperimentManager* experiment_manager =
      ManifestV2ExperimentManager::Get(browser_context());
  EXPECT_FALSE(experiment_manager->DidUserAcknowledgeNotice(extension->id()));
}

TEST_F(DeveloperPrivateApiWithMV2DeprecationWarningUnitTest,
       TestAcknowledgingNoticeGlobally) {
  ManifestV2ExperimentManager* experiment_manager =
      ManifestV2ExperimentManager::Get(browser_context());
  EXPECT_FALSE(experiment_manager->DidUserAcknowledgeNoticeGlobally());

  auto update_profile_function = base::MakeRefCounted<
      api::DeveloperPrivateUpdateProfileConfigurationFunction>();
  update_profile_function->set_source_context_type(mojom::ContextType::kWebUi);

  base::Value::List args;
  args.Append(base::Value::Dict().Set("isMv2DeprecationNoticeDismissed", true));
  EXPECT_TRUE(RunFunction(update_profile_function, args));

  EXPECT_TRUE(experiment_manager->DidUserAcknowledgeNoticeGlobally());
}

TEST_F(DeveloperPrivateApiWithMV2DeprecationDisabledUnitTest,
       TestAcknowledgingAnExtension) {
  // Add an extension that is affected by the MV2 deprecation.
  scoped_refptr<const Extension> extension =
      ExtensionBuilder("ext").SetManifestVersion(2).Build();
  registrar()->AddExtension(extension.get());

  ManifestV2ExperimentManager* experiment_manager =
      ManifestV2ExperimentManager::Get(browser_context());
  EXPECT_TRUE(experiment_manager->IsExtensionAffected(*extension));
  EXPECT_FALSE(experiment_manager->DidUserAcknowledgeNotice(extension->id()));

  base::Value::List args;
  args.Append(extension->id());

  // Call the dismiss notice function, and cancel the dismissal.
  auto dismiss_notice_function = base::MakeRefCounted<
      api::DeveloperPrivateDismissMv2DeprecationNoticeForExtensionFunction>();
  dismiss_notice_function->set_source_context_type(mojom::ContextType::kWebUi);
  dismiss_notice_function->accept_bubble_for_testing(false);
  EXPECT_TRUE(RunFunction(dismiss_notice_function, args));

  // Extension notice should NOT be marked as acknowledged.
  EXPECT_TRUE(experiment_manager->IsExtensionAffected(*extension));
  EXPECT_FALSE(experiment_manager->DidUserAcknowledgeNotice(extension->id()));

  // Call the dismiss notice function, and accept the dismissal.
  dismiss_notice_function = base::MakeRefCounted<
      api::DeveloperPrivateDismissMv2DeprecationNoticeForExtensionFunction>();
  dismiss_notice_function->set_source_context_type(mojom::ContextType::kWebUi);
  dismiss_notice_function->accept_bubble_for_testing(true);
  EXPECT_TRUE(RunFunction(dismiss_notice_function, args));

  // Extension's notice should be marked as acknowledged.
  EXPECT_TRUE(experiment_manager->IsExtensionAffected(*extension));
  EXPECT_TRUE(experiment_manager->DidUserAcknowledgeNotice(extension->id()));
}

class DeveloperPrivateApiTransportModeUnitTest
    : public DeveloperPrivateApiUnitTest {
 public:
  DeveloperPrivateApiTransportModeUnitTest() {
    scoped_feature_list_.InitWithFeatures(
        {switches::kEnableExtensionsExplicitBrowserSignin},
        /*disabled_features=*/{});
  }

  void SetUp() override {
    DeveloperPrivateApiUnitTest::SetUp();
    identity_test_env_profile_adaptor_ =
        std::make_unique<IdentityTestEnvironmentProfileAdaptor>(profile());
  }

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

 protected:
  signin::IdentityTestEnvironment* identity_test_env() {
    return identity_test_env_profile_adaptor_->identity_test_env();
  }

  AccountExtensionTracker::AccountExtensionType GetAccountExtensionType(
      const ExtensionId& extension_id) {
    return AccountExtensionTracker::Get(profile())->GetAccountExtensionType(
        extension_id);
  }

  bool CanUploadToAccount(const Extension& extension) {
    return AccountExtensionTracker::Get(profile())->CanUploadAsAccountExtension(
        extension);
  }

  // Loads and returns a syncable extension with the given `name`.
  const scoped_refptr<const Extension> LoadSyncableExtension(const char* name) {
    const scoped_refptr<const Extension> syncable_extension =
        ExtensionBuilder(name)
            .SetLocation(mojom::ManifestLocation::kInternal)
            .Build();
    EXPECT_TRUE(sync_util::ShouldSync(profile(), syncable_extension.get()));
    registrar()->AddExtension(syncable_extension.get());

    return syncable_extension;
  }

  // Set up a listener for the given `kEventName` and returns the test
  // observer.
  ItemStatePrefsChangedObserver StartListeningForEvent(
      const ExtensionId& extension_id) {
    // We need to call DeveloperPrivateAPI::Get() in order to instantiate the
    // keyed service, since it's not created by default in unit tests.
    DeveloperPrivateAPI::Get(profile());
    EventRouter* event_router = EventRouter::Get(profile());

    // The DeveloperPrivateEventRouter will only dispatch events if there's at
    // least one listener to dispatch to. Create one.
    GURL dummy_url("chrome-untrusted://one");
    event_router->AddEventListenerForURL(
        api::developer_private::OnItemStateChanged::kEventName,
        render_process_host(), dummy_url);

    return ItemStatePrefsChangedObserver(event_router, extension_id);
  }

  // Simulates an initial download of sync data with the given `extensions`
  // present.
  void SimulateInitialSync(const std::vector<const Extension*>& extensions) {
    syncer::SyncDataList sync_data;
    for (const auto* extension : extensions) {
      ExtensionSyncData data(
          *extension, true,
          /*disable_reasons=*/{}, /*incognito_enabled=*/false,
          /*remote_install=*/false, extension_urls::GetWebstoreUpdateUrl());

      sync_data.push_back(data.GetSyncData());
    }

    ExtensionSyncService::Get(profile())->MergeDataAndStartSyncing(
        syncer::EXTENSIONS, sync_data,
        std::make_unique<syncer::FakeSyncChangeProcessor>());
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;

  std::unique_ptr<IdentityTestEnvironmentProfileAdaptor>
      identity_test_env_profile_adaptor_;
};

// Test that extensions cannot be uploaded if the user is signed out.
TEST_F(DeveloperPrivateApiTransportModeUnitTest,
       UploadExtensionToAccount_SignedOut) {
  auto extension = LoadSyncableExtension("ext");

  std::string args = base::StringPrintf(R"(["%s"])", extension->id().c_str());
  auto upload_function = base::MakeRefCounted<
      api::DeveloperPrivateUploadExtensionToAccountFunction>();
  upload_function->set_source_context_type(mojom::ContextType::kWebUi);

  std::string error = api_test_utils::RunFunctionAndReturnError(
      upload_function, args, profile());
  EXPECT_EQ(error, "User is not signed in.");
}

TEST_F(DeveloperPrivateApiTransportModeUnitTest,
       UploadExtensionToAccount_UnsyncableExtension) {
  // Add an unsyncable (unpacked) extension.
  const scoped_refptr<const Extension> unsyncable_extension =
      ExtensionBuilder("unsync_ext")
          .SetLocation(mojom::ManifestLocation::kUnpacked)
          .Build();
  EXPECT_FALSE(sync_util::ShouldSync(profile(), unsyncable_extension.get()));
  registrar()->AddExtension(unsyncable_extension.get());

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());

  std::string args_str =
      base::StringPrintf(R"(["%s"])", unsyncable_extension->id().c_str());
  auto upload_function = base::MakeRefCounted<
      api::DeveloperPrivateUploadExtensionToAccountFunction>();
  upload_function->set_source_context_type(mojom::ContextType::kWebUi);

  // The unsyncable extension cannot be uploaded.
  std::string error = api_test_utils::RunFunctionAndReturnError(
      upload_function, args_str, profile());
  EXPECT_EQ(
      error,
      ErrorUtils::FormatErrorMessage(
          "Extension with ID '*' cannot be uploaded to the user's account.",
          unsyncable_extension->id()));
}

TEST_F(DeveloperPrivateApiTransportModeUnitTest,
       UploadExtensionToAccount_Cancelled) {
  // Add a syncable extension.
  auto syncable_extension = LoadSyncableExtension("ext");

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());

  // The syncable extension can be uploaded, but pretend we don't proceed with
  // the upload by simulating cancelling the dialog.
  base::Value::List args;
  args.Append(syncable_extension->id());
  auto upload_function = base::MakeRefCounted<
      api::DeveloperPrivateUploadExtensionToAccountFunction>();
  upload_function->set_source_context_type(mojom::ContextType::kWebUi);
  upload_function->accept_bubble_for_testing(false);

  // Check that the value returned indicates that the extension was not
  // uploaded.
  EXPECT_TRUE(RunFunction(upload_function, args));
  const base::Value::List* results = upload_function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());
  ASSERT_TRUE((*results)[0].is_bool());
  EXPECT_FALSE((*results)[0].GetBool());

  // Now pretend the extension is already associated with the user's account.
  AccountExtensionTracker::Get(profile())->SetAccountExtensionTypeForTesting(
      syncable_extension->id(),
      AccountExtensionTracker::AccountExtensionType::kAccountInstalledSignedIn);

  std::string args_str =
      base::StringPrintf(R"(["%s"])", syncable_extension->id().c_str());
  upload_function = base::MakeRefCounted<
      api::DeveloperPrivateUploadExtensionToAccountFunction>();
  upload_function->set_source_context_type(mojom::ContextType::kWebUi);

  // The extension shouldn't be able to be uploaded since it's now already
  // associated with the user's account and thus already "uploaded".
  std::string error = api_test_utils::RunFunctionAndReturnError(
      upload_function, args_str, profile());
  EXPECT_EQ(
      error,
      ErrorUtils::FormatErrorMessage(
          "Extension with ID '*' cannot be uploaded to the user's account.",
          syncable_extension->id()));
}

TEST_F(DeveloperPrivateApiTransportModeUnitTest,
       UploadExtensionToAccount_Accepted) {
  // Add a syncable extension.
  auto extension = LoadSyncableExtension("ext");
  ItemStatePrefsChangedObserver test_observer =
      StartListeningForEvent(extension->id());

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());

  // Now simulate an initial sync with no extensions in the user's account. This
  // is needed to spin up the sync service so uploaded extensions actually get
  // synced.
  SimulateInitialSync({});

  // Wait for the associated prefs changed event from the initial sync so the
  // event that gets emitted later from an extension upload can be properly
  // picked up.
  test_observer.WaitForEvent();

  // The syncable extension can be uploaded and should be a local extension.
  EXPECT_TRUE(CanUploadToAccount(*extension));
  EXPECT_EQ(AccountExtensionTracker::AccountExtensionType::kLocal,
            GetAccountExtensionType(extension->id()));

  // On this machine, there should be no extensions syncing.
  {
    syncer::SyncDataList list =
        ExtensionSyncService::Get(profile())->GetAllSyncDataForTesting(
            syncer::EXTENSIONS);
    EXPECT_TRUE(list.empty());
  }

  // Now upload the extension and accept the dialog to proceed with the upload.
  base::Value::List args;
  args.Append(extension->id());
  auto upload_function = base::MakeRefCounted<
      api::DeveloperPrivateUploadExtensionToAccountFunction>();
  upload_function->set_source_context_type(mojom::ContextType::kWebUi);
  upload_function->accept_bubble_for_testing(true);

  test_observer.Reset();

  // Check that the value returned indicates that the extension was uploaded.
  EXPECT_TRUE(RunFunction(upload_function, args));
  const base::Value::List* results = upload_function->GetResultListForTest();
  ASSERT_EQ(1u, results->size());
  ASSERT_TRUE((*results)[0].is_bool());
  EXPECT_TRUE((*results)[0].GetBool());

  // Wait for the prefs changed update and verify that the extension is no
  // longer uploadable after being uploaded.
  test_observer.WaitForEvent();
  auto info = test_observer.event_info();
  EXPECT_FALSE(info.can_upload_as_account_extension);
  EXPECT_FALSE(CanUploadToAccount(*extension));

  // Double check that the extension is now an account extension.
  EXPECT_EQ(
      AccountExtensionTracker::AccountExtensionType::kAccountInstalledSignedIn,
      GetAccountExtensionType(extension->id()));

  // Verify that the extension is now syncing from the sync service.
  {
    syncer::SyncDataList list =
        ExtensionSyncService::Get(profile())->GetAllSyncDataForTesting(
            syncer::EXTENSIONS);
    ASSERT_EQ(1u, list.size());
    std::unique_ptr<ExtensionSyncData> data =
        ExtensionSyncData::CreateFromSyncData(list[0]);
    ASSERT_TRUE(data.get());
    EXPECT_EQ(extension->id(), data->id());
    EXPECT_TRUE(data->enabled());
  }
}

// Test that an extension is uploadable when the user signs into transport mode
// and the extension is not in the user's sync data.
TEST_F(DeveloperPrivateApiTransportModeUnitTest, ExtensionUploadableOnSignIn) {
  auto extension = LoadSyncableExtension("ext");
  ItemStatePrefsChangedObserver test_observer =
      StartListeningForEvent(extension->id());

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());

  // While the extension technically can be uploaded to the user's account,
  // don't dispatch an update event if the initial sync data has not been
  // received yet.
  EXPECT_TRUE(CanUploadToAccount(*extension));
  EXPECT_FALSE(test_observer.WasEventDispatched());
  test_observer.Reset();

  // Now simulate an initial sync where no extensions are present in the user's
  // sync data.
  SimulateInitialSync({});
  test_observer.WaitForEvent();

  // Upon receiving the sync data, the API's event router should be notified.
  auto info = test_observer.event_info();

  // Verify that the update has alerted observers that the extension can now be
  // uploaded.
  EXPECT_TRUE(info.can_upload_as_account_extension);
  EXPECT_TRUE(CanUploadToAccount(*extension));
}

// Test that an extension is not uploadable when it's already present in the
// user's sync data.
TEST_F(DeveloperPrivateApiTransportModeUnitTest,
       ExtensionNotUploadableFromInitialSync) {
  auto extension = LoadSyncableExtension("ext");
  ItemStatePrefsChangedObserver test_observer =
      StartListeningForEvent(extension->id());

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());
  EXPECT_FALSE(test_observer.WasEventDispatched());
  test_observer.Reset();

  // Simulate an initial sync where the extension is already present in the
  // user's sync data.
  SimulateInitialSync({extension.get()});
  test_observer.WaitForEvent();

  // An update event should be dispatched but the extension should not be
  // uploadable since it's already present in sync data.
  auto info = test_observer.event_info();
  EXPECT_FALSE(info.can_upload_as_account_extension);
  EXPECT_FALSE(CanUploadToAccount(*extension));
}

// Sign outs are not supported for ChromeOS hence this test is not run for
// ChromeOS.
#if !BUILDFLAG(IS_CHROMEOS)
// Test that extensions can no longer be uploaded once the user signs out.
TEST_F(DeveloperPrivateApiTransportModeUnitTest, CannotUploadAfterSignOut) {
  // Test setup: Sign in and simulate an empty initial sync so the extension is
  // uploadavble.
  auto extension = LoadSyncableExtension("ext");
  ItemStatePrefsChangedObserver test_observer =
      StartListeningForEvent(extension->id());

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());

  SimulateInitialSync({});
  test_observer.WaitForEvent();

  auto info = test_observer.event_info();
  EXPECT_TRUE(info.can_upload_as_account_extension);
  test_observer.Reset();

  // Now sign out. An update should be dispatched indicating that the extension
  // is no longer syncable.
  identity_test_env()->ClearPrimaryAccount();
  test_observer.WaitForEvent();
  info = test_observer.event_info();
  EXPECT_FALSE(info.can_upload_as_account_extension);
  EXPECT_FALSE(CanUploadToAccount(*extension));
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

// Test that extensions can no longer be uploaded by the user if they sign into
// full sync mode.
TEST_F(DeveloperPrivateApiTransportModeUnitTest, CannotUploadWithFullSync) {
  // Test setup: Sign in and simulate an empty initial sync so the extension is
  // uploadavble.
  auto extension = LoadSyncableExtension("ext");
  ItemStatePrefsChangedObserver test_observer =
      StartListeningForEvent(extension->id());

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());

  SimulateInitialSync({});
  test_observer.WaitForEvent();

  auto info = test_observer.event_info();
  EXPECT_TRUE(info.can_upload_as_account_extension);
  test_observer.Reset();

  // Now sign into full sync. Since full sync mode automatically syncs any
  // syncable extension, the extension cannot be uploaded anymore.
  identity_test_env()->MakePrimaryAccountAvailable("testy@mctestface.com",
                                                   signin::ConsentLevel::kSync);
  test_observer.WaitForEvent();
  info = test_observer.event_info();
  EXPECT_FALSE(info.can_upload_as_account_extension);
  EXPECT_FALSE(CanUploadToAccount(*extension));
}

// Test that extensions can no longer be uploaded if an update comes in
// indicating that they're part of the user's sync data.
TEST_F(DeveloperPrivateApiTransportModeUnitTest,
       UploadUpdatedAfterIncomingSync) {
  // Test setup: Sign in and simulate an empty initial sync so the extension is
  // uploadavble.
  auto extension = LoadSyncableExtension("ext");
  ItemStatePrefsChangedObserver test_observer =
      StartListeningForEvent(extension->id());

  // Sign the user in without full sync.
  signin_test_util::SimulateExplicitSignIn(profile(), identity_test_env());

  SimulateInitialSync({});
  test_observer.WaitForEvent();

  auto info = test_observer.event_info();
  EXPECT_TRUE(info.can_upload_as_account_extension);
  test_observer.Reset();

  // Simulate a later sync update where the same extension was installed on
  // another device and the change is synced over.
  ExtensionSyncData extension_installed_elsewhere(
      *extension, true,
      /*disable_reasons=*/{}, /*incognito_enabled=*/false,
      /*remote_install=*/false, extension_urls::GetWebstoreUpdateUrl());
  ExtensionSyncService::Get(profile())->ProcessSyncChanges(
      FROM_HERE, {extension_installed_elsewhere.GetSyncChange(
                     syncer::SyncChange::ACTION_UPDATE)});
  test_observer.WaitForEvent();

  // The extension should no longer be uploadable since it is now part of the
  // user's sync data.
  info = test_observer.event_info();
  EXPECT_FALSE(info.can_upload_as_account_extension);
  EXPECT_FALSE(CanUploadToAccount(*extension));
}

}  // namespace extensions