File: chrome_file_system_access_permission_context.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; 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 (3249 lines) | stat: -rw-r--r-- 127,181 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
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/file_system_access/chrome_file_system_access_permission_context.h"

#include <algorithm>
#include <iterator>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>

#include "base/auto_reset.h"
#include "base/base_paths.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/values_util.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/task/bind_post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/types/expected.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/file_system_access/file_system_access_permission_request_manager.h"
#include "chrome/browser/permissions/one_time_permissions_tracker_factory.h"
#include "chrome/browser/permissions/one_time_permissions_tracker_observer.h"
#include "chrome/browser/permissions/permission_decision_auto_blocker_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/file_system_access/file_system_access_dangerous_file_dialog.h"
#include "chrome/browser/ui/file_system_access/file_system_access_dialogs.h"
#include "chrome/browser/ui/file_system_access/file_system_access_restricted_directory_dialog.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/grit/generated_resources.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/guest_view/buildflags/buildflags.h"
#include "components/pdf/common/pdf_util.h"
#include "components/permissions/features.h"
#include "components/permissions/object_permission_context_base.h"
#include "components/permissions/permission_decision_auto_blocker.h"
#include "components/permissions/permission_uma_util.h"
#include "components/permissions/permission_util.h"
#include "components/safe_browsing/buildflags.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/disallow_activation_reason.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
#include "extensions/buildflags/buildflags.h"
#include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"
#include "url/origin.h"

#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#include "base/strings/string_util.h"
#include "chrome/browser/ui/android/tab_model/tab_model.h"
#include "chrome/browser/ui/android/tab_model/tab_model_list.h"
#else
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/tabs/public/tab_features.h"
#include "chrome/browser/ui/views/file_system_access/file_system_access_page_action_controller.h"
#include "chrome/browser/web_applications/proto/web_app_install_state.pb.h"
#include "chrome/browser/web_applications/web_app_install_manager.h"
#include "chrome/browser/web_applications/web_app_install_manager_observer.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "components/tabs/public/tab_interface.h"
#if BUILDFLAG(ENABLE_PLATFORM_APPS)
#include "extensions/browser/extension_registry.h"  // nogncheck
#include "extensions/common/extension.h"
#endif  // BUILDFLAG(ENABLE_PLATFORM_APPS)
#endif  // BUILDFLAG(IS_ANDROID)

#if BUILDFLAG(SAFE_BROWSING_DOWNLOAD_PROTECTION)
#include "chrome/browser/safe_browsing/download_protection/download_protection_service.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#endif

#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
#include "chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.h"
#include "chrome/browser/safe_browsing/download_protection/download_protection_util.h"
#include "components/safe_browsing/content/common/file_type_policies.h"
#endif

#if BUILDFLAG(ENABLE_GUEST_VIEW)
#include "components/guest_view/browser/guest_view_base.h"
#include "extensions/browser/guest_view/web_view/web_view_guest.h"
#endif  // BUILDFLAG(ENABLE_GUEST_VIEW)

namespace {

using FileRequestData =
    FileSystemAccessPermissionRequestManager::FileRequestData;
using RequestAccess = FileSystemAccessPermissionRequestManager::Access;
using HandleType = content::FileSystemAccessPermissionContext::HandleType;
using PersistedGrantStatus =
    ChromeFileSystemAccessPermissionContext::PersistedGrantStatus;
using GrantType = ChromeFileSystemAccessPermissionContext::GrantType;
using blink::mojom::PermissionStatus;
using permissions::PermissionAction;

// This long after the last top-level tab or window for an origin is closed (or
// is navigated to another origin), all the permissions for that origin will be
// revoked.
constexpr base::TimeDelta kPermissionRevocationTimeout = base::Seconds(5);

// Dictionary keys for the FILE_SYSTEM_ACCESS_CHOOSER_DATA setting.
// `kPermissionPathKey[] = "path"` is defined in the header file.
const char kPermissionDisplayNameKey[] = "display-name";
const char kPermissionIsDirectoryKey[] = "is-directory";
const char kPermissionWritableKey[] = "writable";
const char kPermissionReadableKey[] = "readable";
const char kDeprecatedPermissionLastUsedTimeKey[] = "time";

// Dictionary keys for the FILE_SYSTEM_LAST_PICKED_DIRECTORY website setting.
// Schema (per origin):
// {
//  ...
//   {
//     "default-id" : { "path" : <path> , "path-type" : <type>}
//     "custom-id-fruit" : { "path" : <path> , "path-type" : <type> }
//     "custom-id-flower" : { "path" : <path> , "path-type" : <type> }
//     ...
//   }
//  ...
// }
const char kDefaultLastPickedDirectoryKey[] = "default-id";
const char kCustomLastPickedDirectoryKey[] = "custom-id";
const char kPathKey[] = "path";
const char kDisplayNameKey[] = "display-name";
const char kPathTypeKey[] = "path-type";
const char kTimestampKey[] = "timestamp";

constexpr char kDefaultNotAllowedMessage[] =
    "Showing a file picker is not allowed.";

void ShowFileSystemAccessRestrictedDirectoryDialogOnUIThread(
    content::GlobalRenderFrameHostId frame_id,
    const url::Origin& origin,
    HandleType handle_type,
    base::OnceCallback<
        void(ChromeFileSystemAccessPermissionContext::SensitiveEntryResult)>
        callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(frame_id);
  if (!rfh || !rfh->IsActive()) {
    // Requested from a no longer valid RenderFrameHost.
    std::move(callback).Run(
        ChromeFileSystemAccessPermissionContext::SensitiveEntryResult::kAbort);
    return;
  }

  content::WebContents* web_contents =
      content::WebContents::FromRenderFrameHost(rfh);
  if (!web_contents) {
    // Requested from a worker, or a no longer existing tab.
    std::move(callback).Run(
        ChromeFileSystemAccessPermissionContext::SensitiveEntryResult::kAbort);
    return;
  }

  ShowFileSystemAccessRestrictedDirectoryDialog(
      origin, handle_type, std::move(callback), web_contents);
}

#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
void ShowFileSystemAccessDangerousFileDialogOnUIThread(
    content::GlobalRenderFrameHostId frame_id,
    const url::Origin& origin,
    const content::PathInfo& path_info,
    base::OnceCallback<
        void(ChromeFileSystemAccessPermissionContext::SensitiveEntryResult)>
        callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(frame_id);
  if (!rfh || !rfh->IsActive()) {
    // Requested from a no longer valid RenderFrameHost.
    std::move(callback).Run(
        ChromeFileSystemAccessPermissionContext::SensitiveEntryResult::kAbort);
    return;
  }

  content::WebContents* web_contents =
      content::WebContents::FromRenderFrameHost(rfh);
  if (!web_contents) {
    // Requested from a worker, or a no longer existing tab.
    std::move(callback).Run(
        ChromeFileSystemAccessPermissionContext::SensitiveEntryResult::kAbort);
    return;
  }

  ShowFileSystemAccessDangerousFileDialog(origin, path_info,
                                          std::move(callback), web_contents);
}
#endif

#if BUILDFLAG(IS_WIN)
bool ContainsInvalidDNSCharacter(base::FilePath::StringType hostname) {
  for (base::FilePath::CharType c : hostname) {
    if (!((c >= L'A' && c <= L'Z') || (c >= L'a' && c <= L'z') ||
          (c >= L'0' && c <= L'9') || (c == L'.') || (c == L'-'))) {
      return true;
    }
  }
  return false;
}

bool MaybeIsLocalUNCPath(const base::FilePath& path) {
  if (!path.IsNetwork()) {
    return false;
  }

  const std::vector<base::FilePath::StringType> components =
      path.GetComponents();

  // Check for server name that could represent a local system. We only
  // check for a very short list, as it is impossible to cover all different
  // variants on Windows.
  if (components.size() >= 2 &&
      (base::FilePath::CompareEqualIgnoreCase(components[1],
                                              FILE_PATH_LITERAL("localhost")) ||
       components[1] == FILE_PATH_LITERAL("127.0.0.1") ||
       components[1] == FILE_PATH_LITERAL(".") ||
       components[1] == FILE_PATH_LITERAL("?") ||
       ContainsInvalidDNSCharacter(components[1]))) {
    return true;
  }

  // In case we missed the server name check above, we also check for shares
  // ending with '$' as they represent pre-defined shares, including the local
  // drives.
  for (size_t i = 2; i < components.size(); ++i) {
    if (components[i].back() == L'$') {
      return true;
    }
  }

  return false;
}
#endif

// Sentinel used to indicate that no PathService key is specified for a path in
// the struct below.
constexpr const int kNoBasePathKey = -1;

using BlockType = ChromeFileSystemAccessPermissionContext::BlockType;

std::vector<ChromeFileSystemAccessPermissionContext::BlockedPath>
GenerateBlockedPath() {
  return {
      // Don't allow users to share their entire home directory, entire desktop
      // or entire documents folder, but do allow sharing anything inside those
      // directories not otherwise blocked.
      {base::DIR_HOME, nullptr, BlockType::kDontBlockChildren},
      {base::DIR_USER_DESKTOP, nullptr, BlockType::kDontBlockChildren},
      {chrome::DIR_USER_DOCUMENTS, nullptr, BlockType::kDontBlockChildren},
      // Similar restrictions for the downloads directory.
      {chrome::DIR_DEFAULT_DOWNLOADS, nullptr, BlockType::kDontBlockChildren},
      {chrome::DIR_DEFAULT_DOWNLOADS_SAFE, nullptr,
       BlockType::kDontBlockChildren},
      // The Chrome installation itself should not be modified by the web.
      {base::DIR_EXE, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_MODULE, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_ASSETS, nullptr, BlockType::kBlockAllChildren},
      // And neither should the configuration of at least the currently running
      // Chrome instance (note that this does not take --user-data-dir command
      // line overrides into account).
      {chrome::DIR_USER_DATA, nullptr, BlockType::kBlockAllChildren},
      // ~/.ssh is pretty sensitive on all platforms, so block access to that.
      {base::DIR_HOME, FILE_PATH_LITERAL(".ssh"), BlockType::kBlockAllChildren},
      // And limit access to ~/.gnupg as well.
      {base::DIR_HOME, FILE_PATH_LITERAL(".gnupg"),
       BlockType::kBlockAllChildren},
#if BUILDFLAG(IS_WIN)
      // Some Windows specific directories to block, basically all apps, the
      // operating system itself, as well as configuration data for apps.
      {base::DIR_PROGRAM_FILES, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_PROGRAM_FILESX86, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_PROGRAM_FILES6432, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_WINDOWS, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_ROAMING_APP_DATA, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_LOCAL_APP_DATA, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_COMMON_APP_DATA, nullptr, BlockType::kBlockAllChildren},
      // Opening a file from an MTP device, such as a smartphone or a camera, is
      // implemented by Windows as opening a file in the temporary internet
      // files directory. To support that, allow opening files in that
      // directory, but not whole directories.
      {base::DIR_IE_INTERNET_CACHE, nullptr,
       BlockType::kBlockNestedDirectories},
#endif
#if BUILDFLAG(IS_MAC)
      // Similar Mac specific blocks.
      {base::DIR_APP_DATA, nullptr, BlockType::kBlockAllChildren},
      // Block access to the current bundle directory.
      {chrome::DIR_OUTER_BUNDLE, nullptr, BlockType::kBlockAllChildren},
      // Block access to the user's Applications directory.
      {base::DIR_HOME, FILE_PATH_LITERAL("Applications"),
       BlockType::kBlockAllChildren},
      // Block access to the root Applications directory.
      {kNoBasePathKey, FILE_PATH_LITERAL("/Applications"),
       BlockType::kBlockAllChildren},
      {base::DIR_HOME, FILE_PATH_LITERAL("Library"),
       BlockType::kBlockAllChildren},
      // Allow access to other cloud files, such as Google Drive.
      {base::DIR_HOME, FILE_PATH_LITERAL("Library/CloudStorage"),
       BlockType::kDontBlockChildren},
      // Allow the site to interact with data from its corresponding natively
      // installed (sandboxed) application. It would be nice to limit a site to
      // access only _its_ corresponding natively installed application, but
      // unfortunately there's no straightforward way to do that. See
      // https://crbug.com/984641#c22.
      {base::DIR_HOME, FILE_PATH_LITERAL("Library/Containers"),
       BlockType::kDontBlockChildren},
      // Allow access to iCloud files...
      {base::DIR_HOME, FILE_PATH_LITERAL("Library/Mobile Documents"),
       BlockType::kDontBlockChildren},
      // ... which may also appear at this directory.
      {base::DIR_HOME,
       FILE_PATH_LITERAL("Library/Mobile Documents/com~apple~CloudDocs"),
       BlockType::kDontBlockChildren},
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
      // On Linux also block access to devices via /dev.
      {kNoBasePathKey, FILE_PATH_LITERAL("/dev"), BlockType::kBlockAllChildren},
      // And security sensitive data in /proc and /sys.
      {kNoBasePathKey, FILE_PATH_LITERAL("/proc"),
       BlockType::kBlockAllChildren},
      {kNoBasePathKey, FILE_PATH_LITERAL("/sys"), BlockType::kBlockAllChildren},
      // And system files in /boot and /etc.
      {kNoBasePathKey, FILE_PATH_LITERAL("/boot"),
       BlockType::kBlockAllChildren},
      {kNoBasePathKey, FILE_PATH_LITERAL("/etc"), BlockType::kBlockAllChildren},
      // And block all of ~/.config, matching the similar restrictions on mac
      // and windows.
      {base::DIR_HOME, FILE_PATH_LITERAL(".config"),
       BlockType::kBlockAllChildren},
      // Block ~/.dbus as well, just in case, although there probably isn't much
      // a website can do with access to that directory and its contents.
      {base::DIR_HOME, FILE_PATH_LITERAL(".dbus"),
       BlockType::kBlockAllChildren},
#endif
#if BUILDFLAG(IS_ANDROID)
      {base::DIR_ANDROID_APP_DATA, nullptr, BlockType::kBlockAllChildren},
      {base::DIR_CACHE, nullptr, BlockType::kBlockAllChildren},
#endif
      // TODO(crbug.com/40095723): Refine this list, for example add
      // XDG_CONFIG_HOME when it is not set ~/.config?
  };
}

// A wrapper around `base::NormalizeFilePath` that returns its result instead of
// using an out parameter.
base::FilePath NormalizeFilePath(const base::FilePath& path) {
  CHECK(path.IsAbsolute());
  // TODO(crbug.com/368130513O): On Windows, this call will fail if the target
  // file path is greater than MAX_PATH. We should decide how to handle this
  // scenario.
  base::FilePath normalized_path;
  if (!base::NormalizeFilePath(path, &normalized_path)) {
    return path;
  }
  CHECK_EQ(path.empty(), normalized_path.empty());
  return normalized_path;
}

// Checks if `path` should be blocked by the `rules`.
// The BlockType of the nearest ancestor of a path to check is what
// ultimately determines if a path is blocked or not. If a blocked path is a
// descendent of another blocked path, then it may override the
// child-blocking policy of its ancestor. For example, if /home blocks all
// children, but /home/downloads does not, then /home/downloads/file.ext
// will *not* be blocked.
bool ShouldBlockAccessToPath(
    const base::FilePath& path,
    HandleType handle_type,
    std::vector<ChromeFileSystemAccessPermissionContext::BlockPathRule> rules,
    std::vector<ChromeFileSystemAccessPermissionContext::BlockedPath>
        blocked_paths,
    const base::FilePath& profile_path) {
  DCHECK(!path.empty());
#if BUILDFLAG(IS_ANDROID)
  // The only check for content-URIs is that they are not from an internal
  // FileProvider.
  if (path.IsContentUri()) {
    base::android::BuildInfo* info = base::android::BuildInfo::GetInstance();
    return base::StartsWith(
        path.value(), base::StrCat({"content://", info->package_name(), "."}),
        base::CompareCase::INSENSITIVE_ASCII);
  }
#endif
  DCHECK(path.IsAbsolute());

  bool normalize_file_paths = base::FeatureList::IsEnabled(
      features::kFileSystemAccessSymbolicLinkCheck);

  base::FilePath check_path =
      normalize_file_paths ? NormalizeFilePath(path) : path;

#if BUILDFLAG(IS_WIN)
  // On Windows, local UNC paths are rejected, as UNC path can be written in a
  // way that can bypass the blocklist.
  if (MaybeIsLocalUNCPath(check_path)) {
    return true;
  }
#endif

  // ChromeOS supports multi-user sign-in. base::DIR_HOME only returns the
  // profile path for the primary user, the first user to sign in. We want to
  // use the `profile_path` instead since that's associated with user that
  // initiated this blocklist check.
  //
  // TODO(crbug.com/375490221): Improve the ChromeOS blocklist logic.
  constexpr bool kUseProfilePathForDirHome = BUILDFLAG(IS_CHROMEOS);

  // Add the hard-coded rules to the dynamic rules.
  for (const auto& block : blocked_paths) {
    base::FilePath blocked_path;
    if (block.base_path_key != kNoBasePathKey) {
      if (kUseProfilePathForDirHome && block.base_path_key == base::DIR_HOME) {
        blocked_path = profile_path;
      } else if (!base::PathService::Get(block.base_path_key, &blocked_path)) {
        continue;
      }
      if (block.path) {
        blocked_path = blocked_path.Append(block.path);
      }
    } else {
      DCHECK(block.path);
      blocked_path = base::FilePath(block.path);
    }
    rules.emplace_back(blocked_path, block.type);
  }

  base::FilePath nearest_ancestor;
  BlockType nearest_ancestor_block_type = BlockType::kDontBlockChildren;
  for (const auto& block : rules) {
    base::FilePath blocked_path =
        normalize_file_paths ? NormalizeFilePath(block.path) : block.path;

    if (check_path == blocked_path || check_path.IsParent(blocked_path)) {
      VLOG(1) << "Blocking access to " << check_path
              << " because it is a parent of " << blocked_path;
      return true;
    }

    if (blocked_path.IsParent(check_path) &&
        (nearest_ancestor.empty() || nearest_ancestor.IsParent(blocked_path))) {
      nearest_ancestor = blocked_path;
      nearest_ancestor_block_type = block.type;
    }
  }

  // The path we're checking is not in a potentially blocked directory, or the
  // nearest ancestor does not block access to its children. Grant access.
  if (nearest_ancestor.empty() ||
      nearest_ancestor_block_type == BlockType::kDontBlockChildren) {
    return false;
  }

  // The path we're checking is a file, and the nearest ancestor only blocks
  // access to directories. Grant access.
  if (handle_type == HandleType::kFile &&
      nearest_ancestor_block_type == BlockType::kBlockNestedDirectories) {
    return false;
  }

  // The nearest ancestor blocks access to its children, so block access.
  VLOG(1) << "Blocking access to " << check_path << " because it is inside "
          << nearest_ancestor;
  return true;
}

#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
void DoSafeBrowsingCheckOnUIThread(
    content::GlobalRenderFrameHostId frame_id,
    std::unique_ptr<content::FileSystemAccessWriteItem> item,
    safe_browsing::CheckDownloadCallback callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
#if BUILDFLAG(SAFE_BROWSING_DOWNLOAD_PROTECTION)
  safe_browsing::SafeBrowsingService* sb_service =
      g_browser_process->safe_browsing_service();
  if (!sb_service || !sb_service->download_protection_service() ||
      !sb_service->download_protection_service()->enabled()) {
    std::move(callback).Run(safe_browsing::DownloadCheckResult::UNKNOWN);
    return;
  }

  if (!item->browser_context) {
    content::RenderProcessHost* rph =
        content::RenderProcessHost::FromID(frame_id.child_id);
    if (!rph) {
      std::move(callback).Run(safe_browsing::DownloadCheckResult::UNKNOWN);
      return;
    }
    item->browser_context = rph->GetBrowserContext();
  }

  if (!item->web_contents) {
    content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(frame_id);
    if (rfh) {
      DCHECK_NE(rfh->GetLifecycleState(),
                content::RenderFrameHost::LifecycleState::kPrerendering);
      item->web_contents =
          content::WebContents::FromRenderFrameHost(rfh)->GetWeakPtr();
    }
  }

  sb_service->download_protection_service()->CheckFileSystemAccessWrite(
      std::move(item), std::move(callback));
#else
  std::move(callback).Run(safe_browsing::DownloadCheckResult::UNKNOWN);
#endif  // BUILDFLAG(SAFE_BROWSING_DOWNLOAD_PROTECTION)
}

ChromeFileSystemAccessPermissionContext::AfterWriteCheckResult
InterpretSafeBrowsingResult(safe_browsing::DownloadCheckResult result) {
  using Result = safe_browsing::DownloadCheckResult;
  switch (result) {
    // Only allow downloads that are marked as SAFE or UNKNOWN by SafeBrowsing.
    // All other types are going to be blocked. UNKNOWN could be the result of a
    // failed safe browsing ping or if Safe Browsing is not enabled.
    case Result::UNKNOWN:
    case Result::SAFE:
    case Result::ALLOWLISTED_BY_POLICY:
    case Result::SENSITIVE_CONTENT_WARNING:
    case Result::DEEP_SCANNED_SAFE:
      return ChromeFileSystemAccessPermissionContext::AfterWriteCheckResult::
          kAllow;

    case Result::DANGEROUS:
    case Result::UNCOMMON:
    case Result::DANGEROUS_HOST:
    case Result::POTENTIALLY_UNWANTED:
    case Result::BLOCKED_PASSWORD_PROTECTED:
    case Result::BLOCKED_TOO_LARGE:
    case Result::DANGEROUS_ACCOUNT_COMPROMISE:
    case Result::BLOCKED_SCAN_FAILED:
    case Result::SENSITIVE_CONTENT_BLOCK:
      return ChromeFileSystemAccessPermissionContext::AfterWriteCheckResult::
          kBlock;

    // This shouldn't be returned for File System Access write checks.
    case Result::ASYNC_SCANNING:
    case Result::ASYNC_LOCAL_PASSWORD_SCANNING:
    case Result::PROMPT_FOR_SCANNING:
    case Result::PROMPT_FOR_LOCAL_PASSWORD_SCANNING:
    case Result::DEEP_SCANNED_FAILED:
    case Result::IMMEDIATE_DEEP_SCAN:
      NOTREACHED();
  }
  NOTREACHED();
}
#endif  // BUILDFLAG(SAFE_BROWSING_AVAILABLE)

std::string GenerateLastPickedDirectoryKey(const std::string& id) {
  return id.empty() ? kDefaultLastPickedDirectoryKey
                    : base::StrCat({kCustomLastPickedDirectoryKey, "-", id});
}

std::string_view PathAsPermissionKey(const base::FilePath& path) {
  return std::string_view(
      reinterpret_cast<const char*>(path.value().data()),
      path.value().size() * sizeof(base::FilePath::CharType));
}

std::string_view GetGrantKeyFromGrantType(GrantType type) {
  return type == GrantType::kWrite ? kPermissionWritableKey
                                   : kPermissionReadableKey;
}

#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
safe_browsing::DownloadFileType::DangerLevel GetFileTypeDangerLevel(
    const base::FilePath& path,
    const url::Origin& origin,
    Profile* profile) {
  return safe_browsing::FileTypePolicies::GetInstance()->GetFileDangerLevel(
      path, origin.GetURL(), profile->GetPrefs());
}
#endif

std::string StringOrEmpty(const std::string* s) {
  return s ? *s : std::string();
}

bool PathInfosContains(const std::vector<content::PathInfo>& path_infos,
                       const base::FilePath& path) {
  return std::ranges::any_of(path_infos,
                             [&path](const content::PathInfo& path_info) {
                               return path_info.path == path;
                             });
}

}  // namespace

ChromeFileSystemAccessPermissionContext::Grants::Grants() = default;
ChromeFileSystemAccessPermissionContext::Grants::~Grants() = default;
ChromeFileSystemAccessPermissionContext::Grants::Grants(Grants&&) = default;
ChromeFileSystemAccessPermissionContext::Grants&
ChromeFileSystemAccessPermissionContext::Grants::operator=(Grants&&) = default;

class ChromeFileSystemAccessPermissionContext::PermissionGrantImpl
    : public content::FileSystemAccessPermissionGrant {
 public:
  PermissionGrantImpl(
      base::WeakPtr<ChromeFileSystemAccessPermissionContext> context,
      const url::Origin& origin,
      const content::PathInfo& path_info,
      HandleType handle_type,
      GrantType type,
      UserAction user_action)
      : context_(std::move(context)),
        origin_(origin),
        handle_type_(handle_type),
        type_(type),
        path_info_(path_info),
        user_action_(user_action) {}

  // FileSystemAccessPermissionGrant:
  PermissionStatus GetStatus() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    // TODO(crbug.com/40101962): Determine if this should return denied for
    // guard block, and how ancestor permission should be handled.
    if (status_ == PermissionStatus::ASK &&
        context_->CanAutoGrantViaPersistentPermission(origin_, path_info_.path,
                                                      handle_type_, type_)) {
      return PermissionStatus::GRANTED;
    }
    return status_;
  }

  PermissionStatus GetActivePermissionStatus() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return status_;
  }

  base::FilePath GetPath() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return path_info_.path;
  }

  std::string GetDisplayName() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return path_info_.display_name;
  }

  void RequestPermission(
      content::GlobalRenderFrameHostId frame_id,
      UserActivationState user_activation_state,
      base::OnceCallback<void(PermissionRequestOutcome)> callback) override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    // Check if a permission request has already been processed previously. This
    // check is done first because we don't want to reset the status of a
    // permission if it has already been granted.
    if (GetActivePermissionStatus() != PermissionStatus::ASK || !context_) {
      if (GetActivePermissionStatus() == PermissionStatus::GRANTED) {
        SetStatus(PermissionStatus::GRANTED,
                  PersistedPermissionOptions::kUpdatePersistedPermission);
      }
      std::move(callback).Run(PermissionRequestOutcome::kRequestAborted);
      return;
    }

    if (type_ == GrantType::kWrite) {
      ContentSetting content_setting =
          context_->GetWriteGuardContentSetting(origin_);

      // Content setting grants write permission without asking.
      if (content_setting == CONTENT_SETTING_ALLOW) {
        PermissionRequestOutcome outcome =
            PermissionRequestOutcome::kGrantedByContentSetting;
        RecordPermissionRequestOutcome(outcome);
        // May destroy `this`.
        SetStatus(PermissionStatus::GRANTED,
                  PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
        std::move(callback).Run(outcome);
        return;
      }

      // Content setting blocks write permission.
      if (content_setting == CONTENT_SETTING_BLOCK) {
        PermissionRequestOutcome outcome =
            PermissionRequestOutcome::kBlockedByContentSetting;
        RecordPermissionRequestOutcome(outcome);
        // May destroy `this`.
        SetStatus(PermissionStatus::DENIED,
                  PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
        std::move(callback).Run(outcome);
        return;
      }
    }

    if (context_->CanAutoGrantViaPersistentPermission(origin_, path_info_.path,
                                                      handle_type_, type_)) {
      PermissionRequestOutcome outcome =
          PermissionRequestOutcome::kGrantedByPersistentPermission;
      RecordPermissionRequestOutcome(outcome);
      // May destroy `this`.
      SetStatus(PermissionStatus::GRANTED,
                PersistedPermissionOptions::kUpdatePersistedPermission);
      std::move(callback).Run(outcome);
      return;
    }

    if (context_->CanAutoGrantViaAncestorPersistentPermission(
            origin_, path_info_.path, type_)) {
      PermissionRequestOutcome outcome =
          PermissionRequestOutcome::kGrantedByAncestorPersistentPermission;
      RecordPermissionRequestOutcome(outcome);
      // May destroy `this`.
      SetStatus(PermissionStatus::GRANTED,
                PersistedPermissionOptions::kUpdatePersistedPermission);
      std::move(callback).Run(outcome);
      return;
    }

    // Otherwise, perform checks and ask the user for permission.

    content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(frame_id);
    if (!rfh) {
      // Requested from a no longer valid RenderFrameHost.
      RunCallbackAndRecordPermissionRequestOutcome(
          std::move(callback), PermissionRequestOutcome::kInvalidFrame);
      return;
    }

    // Don't show request permission UI for an inactive RenderFrameHost as the
    // page might not distinguish properly between user denying the permission
    // and automatic rejection, leading to an inconsistent UX once the page
    // becomes active again.
    // - If this is called when RenderFrameHost is in BackForwardCache, evict
    //   the document from the cache.
    // - If this is called when RenderFrameHost is in prerendering, cancel
    //   prerendering.
    if (rfh->IsInactiveAndDisallowActivation(
            content::DisallowActivationReasonId::
                kFileSystemAccessPermissionRequest)) {
      RunCallbackAndRecordPermissionRequestOutcome(
          std::move(callback), PermissionRequestOutcome::kInvalidFrame);
      return;
    }
    // We don't allow file system access from fenced frames.
    if (rfh->IsNestedWithinFencedFrame()) {
      RunCallbackAndRecordPermissionRequestOutcome(
          std::move(callback), PermissionRequestOutcome::kInvalidFrame);
      return;
    }

    if (user_activation_state == UserActivationState::kRequired &&
        !rfh->HasTransientUserActivation()) {
      // No permission prompts without user activation.
      RunCallbackAndRecordPermissionRequestOutcome(
          std::move(callback), PermissionRequestOutcome::kNoUserActivation);
      return;
    }

    content::WebContents* web_contents =
        content::WebContents::FromRenderFrameHost(rfh);
    if (!web_contents) {
      // Requested from a worker, or a no longer existing tab.
      RunCallbackAndRecordPermissionRequestOutcome(
          std::move(callback), PermissionRequestOutcome::kInvalidFrame);
      return;
    }

    url::Origin embedding_origin = url::Origin::Create(
        permissions::PermissionUtil::GetLastCommittedOriginAsURL(
            rfh->GetMainFrame()));
    if (embedding_origin != origin_) {
      // Third party iframes are not allowed to request more permissions.
      RunCallbackAndRecordPermissionRequestOutcome(
          std::move(callback), PermissionRequestOutcome::kThirdPartyContext);
      return;
    }

#if BUILDFLAG(ENABLE_GUEST_VIEW)
    // A permission request from a webview is normally delegated to its embedder
    // without showing a prompt. However, filesystem permissions are known to be
    // broken:
    // TODO(crbug.com/352520731): Remove this once the bug is fixed.
    // Until that's fixed, we auto-grant for WebUI embedders to enable use cases
    // that need this capability: crbug.com/391586357.
    if (auto* guest = extensions::WebViewGuest::FromRenderFrameHost(rfh);
        guest != nullptr && guest->IsOwnedByWebUI()) {
      PermissionRequestOutcome outcome =
          PermissionRequestOutcome::kGrantedByAncestorPersistentPermission;
      RecordPermissionRequestOutcome(outcome);
      // May destroy `this`.
      SetStatus(PermissionStatus::GRANTED,
                PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
      std::move(callback).Run(outcome);
      return;
    }
#endif

    auto* request_manager =
        FileSystemAccessPermissionRequestManager::FromWebContents(web_contents);
    if (!request_manager) {
      RunCallbackAndRecordPermissionRequestOutcome(
          std::move(callback), PermissionRequestOutcome::kRequestAborted);
      return;
    }

    // Drop fullscreen mode so that the user sees the URL bar.
    base::ScopedClosureRunner fullscreen_block =
        web_contents->ForSecurityDropFullscreen(
            /*display_id=*/display::kInvalidDisplayId);

    if (context_->IsEligibleToUpgradePermissionRequestToRestorePrompt(
            origin_, path_info_.path, handle_type_, user_action_, type_)) {
      std::vector<FileRequestData> request_data_list =
          context_->GetFileRequestDataForRestorePermissionPrompt(origin_);
      request_manager->AddRequest(
          {FileSystemAccessPermissionRequestManager::RequestType::
               kRestorePermissions,
           origin_, request_data_list},
          base::BindOnce(&PermissionGrantImpl::OnRestorePermissionRequestResult,
                         this, std::move(callback)),
          std::move(fullscreen_block));
      return;
    }

    // If a website wants both read and write access, code in content will
    // request those as two separate requests. The |request_manager| will then
    // detect this and combine the two requests into one prompt. As such this
    // code does not have to have any way to request Access::kReadWrite.
    FileRequestData file_request_data = {path_info_, handle_type_,
                                         type_ == GrantType::kRead
                                             ? RequestAccess::kRead
                                             : RequestAccess::kWrite};
    request_manager->AddRequest(
        {FileSystemAccessPermissionRequestManager::RequestType::kNewPermission,
         origin_,
         {file_request_data}},
        base::BindOnce(&PermissionGrantImpl::OnPermissionRequestResult, this,
                       std::move(callback)),
        std::move(fullscreen_block));
  }

  const url::Origin& origin() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return origin_;
  }

  HandleType handle_type() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return handle_type_;
  }

  GrantType type() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return type_;
  }

  // `this` may be destroyed. A `FileSystemAccessPermissionGrant::Observer` may
  // destroy `this` when notified of this the status change.
  void SetStatus(PermissionStatus new_status,
                 PersistedPermissionOptions update_options) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    auto permission_changed = status_ != new_status;
    status_ = new_status;

    if (context_ &&
        update_options ==
            PersistedPermissionOptions::kUpdatePersistedPermission &&
        base::FeatureList::IsEnabled(
            features::kFileSystemAccessPersistentPermissions)) {
      const std::unique_ptr<Object> object = context_->GetGrantedObject(
          origin_, PathAsPermissionKey(path_info_.path));
      auto opposite_type =
          type_ == GrantType::kRead ? GrantType::kWrite : GrantType::kRead;
      if (new_status == PermissionStatus::GRANTED) {
        if (object) {
          // Persisted permissions include both read and write information in
          // one object. Figure out if the other grant type is already
          // persisted and update the existing one.
          auto type_exists =
              object->value.FindBool(GetGrantKeyFromGrantType(type_))
                  .value_or(false);
          auto opposite_type_exists =
              object->value.FindBool(GetGrantKeyFromGrantType(opposite_type))
                  .value_or(false);
          if (!type_exists && opposite_type_exists) {
            base::Value::Dict new_object = object->value.Clone();
            new_object.Set(GetGrantKeyFromGrantType(type_), true);
            context_->UpdateObjectPermission(origin_, object->value,
                                             std::move(new_object));
          }
        } else {
          base::Value::Dict grant = AsValue();
          context_->GrantObjectPermission(origin_, std::move(grant));
        }
      } else if (object) {
        // Permission is not granted anymore. Remove the grant object entirely
        // if only this grant type exists in the grant object; otherwise, remove
        // the grant type key from the grant object.
        auto type_exists =
            object->value.FindBool(GetGrantKeyFromGrantType(type_))
                .value_or(false);
        auto opposite_type_exists =
            object->value.FindBool(GetGrantKeyFromGrantType(opposite_type))
                .value_or(false);
        if (type_exists) {
          if (opposite_type_exists) {
            base::Value::Dict new_object = object->value.Clone();
            new_object.Remove(GetGrantKeyFromGrantType(type_));
            context_->UpdateObjectPermission(origin_, object->value,
                                             std::move(new_object));
          } else {
            context_->RevokeObjectPermission(origin_, GetKey());
          }
        }
      }
    }

    if (permission_changed) {
      // May destroy `this`.
      NotifyPermissionStatusChanged();
    }
  }

  base::Value::Dict AsValue() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    base::Value::Dict value;
    value.Set(kPermissionPathKey, base::FilePathToValue(path_info_.path));
    value.Set(kPermissionDisplayNameKey, path_info_.display_name);
    value.Set(kPermissionIsDirectoryKey,
              handle_type_ == HandleType::kDirectory);
    value.Set(GetGrantKeyFromGrantType(type_), true);
    return value;
  }

  static void UpdateGrantPath(
      std::map<base::FilePath, raw_ptr<PermissionGrantImpl, CtnExperimental>>&
          grants,
      const content::PathInfo& old_path,
      const content::PathInfo& new_path) {
    DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
    auto entry_it =
        std::ranges::find_if(grants, [&old_path](const auto& entry) {
          return entry.first == old_path.path;
        });

    if (entry_it == grants.end()) {
      // There must be an entry for an ancestor of this entry. Nothing to do
      // here.
      //
      // TODO(crbug.com/40245144): Consolidate superfluous child grants
      // to support directory moves.
      return;
    }

    DCHECK_EQ(entry_it->second->GetActivePermissionStatus(),
              PermissionStatus::GRANTED);

    auto* const grant_impl = entry_it->second.get();
    grant_impl->SetPath(new_path);

    // Update the permission grant's key in the map of active permissions.
    grants.erase(entry_it);
    grants.emplace(new_path.path, grant_impl);
  }

 protected:
  ~PermissionGrantImpl() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (context_) {
      context_->PermissionGrantDestroyed(this);
    }
  }

 private:
  void OnPermissionRequestResult(
      base::OnceCallback<void(PermissionRequestOutcome)> callback,
      PermissionAction result) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    if (context_) {
      context_->UpdateGrantsOnPermissionRequestResult(origin_);
    }

    switch (result) {
      case PermissionAction::GRANTED: {
        PermissionRequestOutcome outcome =
            PermissionRequestOutcome::kUserGranted;
        RecordPermissionRequestOutcome(outcome);
        // May destroy `this`.
        SetStatus(PermissionStatus::GRANTED,
                  PersistedPermissionOptions::kUpdatePersistedPermission);
        std::move(callback).Run(outcome);
        break;
      }
      case PermissionAction::DENIED: {
        PermissionRequestOutcome outcome =
            PermissionRequestOutcome::kUserDenied;
        RecordPermissionRequestOutcome(outcome);
        // May destroy `this`.
        SetStatus(PermissionStatus::DENIED,
                  PersistedPermissionOptions::kUpdatePersistedPermission);
        std::move(callback).Run(outcome);
        break;
      }
      case PermissionAction::DISMISSED:
      case PermissionAction::IGNORED:
        RunCallbackAndRecordPermissionRequestOutcome(
            std::move(callback), PermissionRequestOutcome::kUserDismissed);
        break;
      case PermissionAction::REVOKED:
      case PermissionAction::GRANTED_ONCE:
      case PermissionAction::NUM:
        NOTREACHED();
    }
  }

  void OnRestorePermissionRequestResult(
      base::OnceCallback<void(PermissionRequestOutcome)> callback,
      PermissionAction result) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    if (!context_) {
      std::move(callback).Run(PermissionRequestOutcome::kRequestAborted);
      return;
    }

    // TODO(crbug.com/40101962): Consider adding more `PermissionRequestOutcome`
    // types to account for "restore every time" case and invalid state case.

    if (context_->GetPersistedGrantType(origin_) !=
        PersistedGrantType::kDormant) {
      // User may have enabled the extended permission, or the persisted grant
      // status is changed while the prompt is shown.
      std::move(callback).Run(PermissionRequestOutcome::kRequestAborted);
      return;
    }

    switch (result) {
      case PermissionAction::GRANTED:
        context_->OnRestorePermissionAllowedEveryTime(origin_);
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.RestorePermissionPromptOutcome",
            RestorePermissionPromptOutcome::kAllowed);
        RunCallbackAndRecordPermissionRequestOutcome(
            std::move(callback),
            PermissionRequestOutcome::kGrantedByRestorePrompt);
        break;
      case PermissionAction::GRANTED_ONCE:
        context_->OnRestorePermissionAllowedOnce(origin_);
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.RestorePermissionPromptOutcome",
            RestorePermissionPromptOutcome::kAllowedOnce);
        RunCallbackAndRecordPermissionRequestOutcome(
            std::move(callback),
            PermissionRequestOutcome::kGrantedByRestorePrompt);
        break;
      case PermissionAction::DENIED:
        context_->OnRestorePermissionDeniedOrDismissed(origin_);
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.RestorePermissionPromptOutcome",
            RestorePermissionPromptOutcome::kRejected);
        RunCallbackAndRecordPermissionRequestOutcome(
            std::move(callback), PermissionRequestOutcome::kUserDenied);
        break;
      case PermissionAction::DISMISSED:
        context_->OnRestorePermissionDeniedOrDismissed(origin_);
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.RestorePermissionPromptOutcome",
            RestorePermissionPromptOutcome::kDismissed);
        RunCallbackAndRecordPermissionRequestOutcome(
            std::move(callback), PermissionRequestOutcome::kUserDismissed);
        break;
      case PermissionAction::IGNORED:
        // TODO(crbug.com/40101962): This action is not user-detectable,
        // consider replacing `PermissionRequestOutcome` with a more
        // appropriate type.
        context_->OnRestorePermissionIgnored(origin_);
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.RestorePermissionPromptOutcome",
            RestorePermissionPromptOutcome::kIgnored);
        RunCallbackAndRecordPermissionRequestOutcome(
            std::move(callback), PermissionRequestOutcome::kRequestAborted);
        break;
      case PermissionAction::REVOKED:
      case PermissionAction::NUM:
        NOTREACHED();
    }
  }

  void RecordPermissionRequestOutcome(PermissionRequestOutcome outcome) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (context_ &&
        (outcome ==
             PermissionRequestOutcome::kGrantedByAncestorPersistentPermission ||
         outcome == PermissionRequestOutcome::kGrantedByPersistentPermission ||
         outcome == PermissionRequestOutcome::kGrantedByRestorePrompt)) {
      context_->ScheduleUsageIconUpdate();
    }
    if (type_ == GrantType::kWrite) {
      base::UmaHistogramEnumeration(
          "Storage.FileSystemAccess.WritePermissionRequestOutcome", outcome);
      if (handle_type_ == HandleType::kDirectory) {
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.WritePermissionRequestOutcome.Directory",
            outcome);
      } else {
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.WritePermissionRequestOutcome.File",
            outcome);
      }
    } else {
      base::UmaHistogramEnumeration(
          "Storage.FileSystemAccess.ReadPermissionRequestOutcome", outcome);
      if (handle_type_ == HandleType::kDirectory) {
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.ReadPermissionRequestOutcome.Directory",
            outcome);
      } else {
        base::UmaHistogramEnumeration(
            "Storage.FileSystemAccess.ReadPermissionRequestOutcome.File",
            outcome);
      }
    }
  }

  void RunCallbackAndRecordPermissionRequestOutcome(
      base::OnceCallback<void(PermissionRequestOutcome)> callback,
      PermissionRequestOutcome outcome) {
    RecordPermissionRequestOutcome(outcome);

    std::move(callback).Run(outcome);
  }

  std::string_view GetKey() const {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    return PathAsPermissionKey(path_info_.path);
  }

  void SetPath(const content::PathInfo& new_path) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    if (path_info_ == new_path) {
      return;
    }

    path_info_ = new_path;

    if (base::FeatureList::IsEnabled(
            features::kFileSystemAccessPersistentPermissions)) {
      const std::unique_ptr<Object> object = context_->GetGrantedObject(
          origin_, PathAsPermissionKey(path_info_.path));
      if (object) {
        base::Value::Dict new_object = object->value.Clone();
        new_object.Set(kPermissionPathKey,
                       base::FilePathToValue(new_path.path));
        new_object.Set(kPermissionDisplayNameKey, new_path.display_name);
        context_->UpdateObjectPermission(origin_, object->value,
                                         std::move(new_object));
      }
    }

    // May destroy `this`.
    NotifyPermissionStatusChanged();
  }

  SEQUENCE_CHECKER(sequence_checker_);

  base::WeakPtr<ChromeFileSystemAccessPermissionContext> const context_;
  const url::Origin origin_;
  const HandleType handle_type_;
  const GrantType type_;
  // `path_info_.path` can be updated if the entry is moved.
  content::PathInfo path_info_;
  const UserAction user_action_;

  // This member should only be updated via SetStatus(), to make sure
  // observers are properly notified about any change in status.
  PermissionStatus status_ = PermissionStatus::ASK;
};

struct ChromeFileSystemAccessPermissionContext::OriginState {
  // Raw pointers, owned collectively by all the handles that reference this
  // grant. When last reference goes away this state is cleared as well by
  // PermissionGrantDestroyed().
  std::map<base::FilePath, raw_ptr<PermissionGrantImpl, CtnExperimental>>
      read_grants;
  std::map<base::FilePath, raw_ptr<PermissionGrantImpl, CtnExperimental>>
      write_grants;

  PersistedGrantStatus persisted_grant_status = PersistedGrantStatus::kLoaded;

  // Cached data about whether this origin has an actively installed web app.
  // This is used to determine the origin's extended permission eligibility.
  WebAppInstallStatus web_app_install_status = WebAppInstallStatus::kUnknown;

  // Timer that is triggered whenever the user navigates away from this origin.
  // This is used to give a website a little bit of time for background work
  // before revoking all permissions for the origin.
  std::unique_ptr<base::RetainingOneShotTimer> cleanup_timer;
};

ChromeFileSystemAccessPermissionContext::
    ChromeFileSystemAccessPermissionContext(content::BrowserContext* context,
                                            const base::Clock* clock)
    : ObjectPermissionContextBase(
          ContentSettingsType::FILE_SYSTEM_WRITE_GUARD,
          ContentSettingsType::FILE_SYSTEM_ACCESS_CHOOSER_DATA,
          HostContentSettingsMapFactory::GetForProfile(context)),
      profile_(context),
      clock_(clock) {
  DETACH_FROM_SEQUENCE(sequence_checker_);
  content_settings_ = base::WrapRefCounted(
      HostContentSettingsMapFactory::GetForProfile(profile_));

#if BUILDFLAG(IS_ANDROID)
  one_time_permissions_tracker_.Observe(
      OneTimePermissionsTrackerFactory::GetForBrowserContext(context));
#else
  auto* provider = web_app::WebAppProvider::GetForWebApps(
      Profile::FromBrowserContext(profile_));
  if (provider) {
    install_manager_observation_.Observe(&provider->install_manager());
  }
  if (base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    one_time_permissions_tracker_.Observe(
        OneTimePermissionsTrackerFactory::GetForBrowserContext(context));

    // Deprecated persisted permission objects contains a timestamp key, used
    // in old implementation. Revoke them so that the state is reset for the new
    // persisted permission implementation.
    std::set<url::Origin> origins =
        ObjectPermissionContextBase::GetOriginsWithGrants();
    for (auto& origin : origins) {
      for (auto& object :
           ObjectPermissionContextBase::GetGrantedObjects(origin)) {
        if (object->value.contains(kDeprecatedPermissionLastUsedTimeKey)) {
          RevokeObjectPermission(origin, GetKeyForObject(object->value));
        }
      }
    }
  }
#endif

  blocked_paths_ = GenerateBlockedPath();
}

ChromeFileSystemAccessPermissionContext::
    ~ChromeFileSystemAccessPermissionContext() = default;

bool ChromeFileSystemAccessPermissionContext::RevokeActiveGrants(
    const url::Origin& origin,
    base::FilePath file_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  bool grant_revoked = false;

  auto origin_it = active_permissions_map_.find(origin);
  if (origin_it != active_permissions_map_.end()) {
    OriginState& origin_state = origin_it->second;
    for (auto grant_iter = origin_state.read_grants.begin(),
              grant_end = origin_state.read_grants.end();
         grant_iter != grant_end;) {
      // The grant may be removed from `read_grants`, so increase the iterator
      // before continuing.
      auto& grant = *(grant_iter++);
      if (file_path.empty() || grant.first == file_path) {
        if (grant.second) {
          grant.second->SetStatus(
              PermissionStatus::ASK,
              PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
          grant_revoked = true;
        }
      }
    }
    for (auto grant_iter = origin_state.write_grants.begin(),
              grant_end = origin_state.write_grants.end();
         grant_iter != grant_end;) {
      // The grant may be removed from `write_grants`, so increase the iterator
      // before continuing.
      auto& grant = *(grant_iter++);
      if (file_path.empty() || grant.first == file_path) {
        if (grant.second) {
          grant.second->SetStatus(
              PermissionStatus::ASK,
              PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
          grant_revoked = true;
        }
      }
    }
    // Only update `persisted_grant_status` if the state has not already been
    // set via tab backgrounding.
    if (file_path.empty() && origin_state.persisted_grant_status !=
                                 PersistedGrantStatus::kBackgrounded) {
      origin_state.persisted_grant_status = PersistedGrantStatus::kLoaded;
    }
  }
  return grant_revoked;
}

void ChromeFileSystemAccessPermissionContext::RevokeAllActiveGrants() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  for (auto& [origin, origin_state] : active_permissions_map_) {
    // Only update `persisted_grant_status` if the state has not already been
    // set via tab backgrounding. We do this before iterating over grants so
    // `FileSystemAccessPermissionGrant::Observer`s can update their state
    // correctly.
    if (origin_state.persisted_grant_status !=
        PersistedGrantStatus::kBackgrounded) {
      origin_state.persisted_grant_status = PersistedGrantStatus::kLoaded;
    }

    for (auto grant_iter = origin_state.read_grants.begin(),
              grant_end = origin_state.read_grants.end();
         grant_iter != grant_end;) {
      // The grant may be removed from `read_grants`, so increase the iterator
      // before continuing.
      auto& [_, grant] = *(grant_iter++);
      grant->SetStatus(
          PermissionStatus::ASK,
          PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
    }
    for (auto grant_iter = origin_state.write_grants.begin(),
              grant_end = origin_state.write_grants.end();
         grant_iter != grant_end;) {
      // The grant may be removed from `write_grants`, so increase the iterator
      // before continuing.
      auto& [_, grant] = *(grant_iter++);
      grant->SetStatus(
          PermissionStatus::ASK,
          PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
    }
  }
}

scoped_refptr<content::FileSystemAccessPermissionGrant>
ChromeFileSystemAccessPermissionContext::GetReadPermissionGrant(
    const url::Origin& origin,
    const content::PathInfo& path_info,
    HandleType handle_type,
    UserAction user_action) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // operator[] might insert a new OriginState in |active_permissions_map_|,
  // but that is exactly what we want.
  auto& origin_state = active_permissions_map_[origin];
  auto& existing_grant = origin_state.read_grants[path_info.path];
  scoped_refptr<PermissionGrantImpl> grant;

  if (existing_grant && existing_grant->handle_type() != handle_type) {
    // |path| changed from being a directory to being a file or vice versa,
    // don't just re-use the existing grant but revoke the old grant before
    // creating a new grant.
    existing_grant->SetStatus(
        PermissionStatus::DENIED,
        PersistedPermissionOptions::kUpdatePersistedPermission);
    existing_grant = nullptr;
  }

  bool creating_new_grant = !existing_grant;
  if (creating_new_grant) {
    grant = base::MakeRefCounted<PermissionGrantImpl>(
        weak_factory_.GetWeakPtr(), origin, path_info, handle_type,
        GrantType::kRead, user_action);
    existing_grant = grant.get();
  } else {
    grant = existing_grant;
  }

  const ContentSetting content_setting = GetReadGuardContentSetting(origin);
  switch (content_setting) {
    case CONTENT_SETTING_ALLOW:
      // Don't persist permissions when the origin is allowlisted.
      grant->SetStatus(
          PermissionStatus::GRANTED,
          PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
      break;
    case CONTENT_SETTING_ASK:
      // If a parent directory is already readable this new grant should also be
      // readable.
      if (creating_new_grant && AncestorHasActivePermission(
                                    origin, path_info.path, GrantType::kRead)) {
        grant->SetStatus(
            PermissionStatus::GRANTED,
            PersistedPermissionOptions::kUpdatePersistedPermission);
        break;
      }
      switch (user_action) {
        case UserAction::kOpen:
        case UserAction::kSave:
          // Open and Save dialog only grant read access for individual files.
          if (handle_type == HandleType::kDirectory) {
            break;
          }
          [[fallthrough]];
        case UserAction::kDragAndDrop:
          // Drag&drop grants read access for all handles.
          grant->SetStatus(
              PermissionStatus::GRANTED,
              PersistedPermissionOptions::kUpdatePersistedPermission);
          break;
        case UserAction::kLoadFromStorage:
        case UserAction::kNone:
          break;
      }
      break;
    case CONTENT_SETTING_BLOCK:
      // Don't bother revoking persisted permissions. If the permissions have
      // not yet expired when the ContentSettingValue is changed, they will
      // effectively be reinstated.
      if (creating_new_grant) {
        grant->SetStatus(
            PermissionStatus::DENIED,
            PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
      } else {
        // We won't revoke permission to an existing grant.
      }
      break;
    default:
      NOTREACHED();
  }

  if (HasGrantedActivePermissionStatus(grant.get())) {
    ScheduleUsageIconUpdate();
  }

  return grant;
}

scoped_refptr<content::FileSystemAccessPermissionGrant>
ChromeFileSystemAccessPermissionContext::GetWritePermissionGrant(
    const url::Origin& origin,
    const content::PathInfo& path_info,
    HandleType handle_type,
    UserAction user_action) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // operator[] might insert a new OriginState in |active_permissions_map_|,
  // but that is exactly what we want.
  auto& origin_state = active_permissions_map_[origin];
  auto& existing_grant = origin_state.write_grants[path_info.path];
  scoped_refptr<PermissionGrantImpl> grant;

  if (existing_grant && existing_grant->handle_type() != handle_type) {
    // |path| changed from being a directory to being a file or vice versa,
    // don't just re-use the existing grant but revoke the old grant before
    // creating a new grant.
    existing_grant->SetStatus(
        PermissionStatus::DENIED,
        PersistedPermissionOptions::kUpdatePersistedPermission);
    existing_grant = nullptr;
  }

  bool creating_new_grant = !existing_grant;
  if (creating_new_grant) {
    grant = base::MakeRefCounted<PermissionGrantImpl>(
        weak_factory_.GetWeakPtr(), origin, path_info, handle_type,
        GrantType::kWrite, user_action);
    existing_grant = grant.get();
  } else {
    grant = existing_grant;
  }

  const ContentSetting content_setting = GetWriteGuardContentSetting(origin);
  switch (content_setting) {
    case CONTENT_SETTING_ALLOW:
      // Don't persist permissions when the origin is allowlisted.
      grant->SetStatus(
          PermissionStatus::GRANTED,
          PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
      break;
    case CONTENT_SETTING_ASK:
      // If a parent directory is already writable this new grant should also be
      // writable.
      if (creating_new_grant &&
          AncestorHasActivePermission(origin, path_info.path,
                                      GrantType::kWrite)) {
        grant->SetStatus(
            PermissionStatus::GRANTED,
            PersistedPermissionOptions::kUpdatePersistedPermission);
        break;
      }
      switch (user_action) {
        case UserAction::kSave:
          // Only automatically grant write access for save dialogs.
          grant->SetStatus(
              PermissionStatus::GRANTED,
              PersistedPermissionOptions::kUpdatePersistedPermission);
          break;
        case UserAction::kOpen:
        case UserAction::kDragAndDrop:
        case UserAction::kLoadFromStorage:
        case UserAction::kNone:
          break;
      }
      break;
    case CONTENT_SETTING_BLOCK:
      // Don't bother revoking persisted permissions. If the permissions have
      // not yet expired when the ContentSettingValue is changed, they will
      // effectively be reinstated.
      if (creating_new_grant) {
        grant->SetStatus(
            PermissionStatus::DENIED,
            PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
      } else {
        // We won't revoke permission to an existing grant.
      }
      break;
    default:
      NOTREACHED();
  }

  if (HasGrantedActivePermissionStatus(grant.get())) {
    ScheduleUsageIconUpdate();
  }

  return grant;
}

// Return extended permission grants for an origin.
std::vector<std::unique_ptr<permissions::ObjectPermissionContextBase::Object>>
ChromeFileSystemAccessPermissionContext::GetExtendedPersistedObjects(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (GetPersistedGrantType(origin) == PersistedGrantType::kExtended) {
    // When the origin has extended permission enabled, all permissions objects
    // represent extended grants.
    return ObjectPermissionContextBase::GetGrantedObjects(origin);
  }

  return {};
}

// Returns extended grants or active grants for an origin.
std::vector<std::unique_ptr<permissions::ObjectPermissionContextBase::Object>>
ChromeFileSystemAccessPermissionContext::GetGrantedObjects(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  auto persisted_grant_type = GetPersistedGrantType(origin);
  if (persisted_grant_type == PersistedGrantType::kExtended ||
      persisted_grant_type == PersistedGrantType::kShadow) {
    // Objects stored in content settings map via `ObjectPermissionContextBase`
    // represent a valid set of grants, if origin has extended or shadow grants.
    // In the case of shadow grants, it should be matching the set of active
    // permission map, but it may not have `PermissionStatus::GRANTED`, if the
    // page is refreshed and `FileSystemAccessPermissionGrant` is
    // garbage-collected, hence returning shadow grant objects directly here.
    return ObjectPermissionContextBase::GetGrantedObjects(origin);
  }

  // Otherwise, a valid set of grants are stored in the in-memory map
  // |active_permissions_map_|.
  // TODO(crbug.com/40276567): Update iteration logic below to handle the case
  // of write-only permission grants.
  std::vector<std::unique_ptr<Object>> objects;
  auto it = active_permissions_map_.find(origin);
  if (it != active_permissions_map_.end()) {
    for (const auto& grant : it->second.read_grants) {
      if (HasGrantedActivePermissionStatus(grant.second)) {
        auto value = grant.second->AsValue();

        // Persisted permissions include both read and write information in
        // one object. If a write grant for this origin/path exists, then
        // update the value to store a writable key as well.
        auto file_path = grant.first;
        auto write_grant_it = it->second.write_grants.find(file_path);
        if (write_grant_it != it->second.write_grants.end() &&
            HasGrantedActivePermissionStatus(write_grant_it->second)) {
          value.Set(kPermissionWritableKey, true);
        }

        objects.push_back(std::make_unique<Object>(
            origin, base::Value(std::move(value)),
            content_settings::SettingSource::kUser, IsOffTheRecord()));
      }
    }
  }

  return objects;
}

// Returns all origins' extended grants or active grants.
std::vector<std::unique_ptr<permissions::ObjectPermissionContextBase::Object>>
ChromeFileSystemAccessPermissionContext::GetAllGrantedObjects() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  std::vector<std::unique_ptr<Object>> all_objects;
  for (const auto& origin : GetOriginsWithGrants()) {
    auto objects = GetGrantedObjects(origin);
    std::ranges::move(objects, std::back_inserter(all_objects));
  }

  return all_objects;
}

// Returns origins that have either extended grants or active grants.
std::set<url::Origin>
ChromeFileSystemAccessPermissionContext::GetOriginsWithGrants() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  std::set<url::Origin> origins;

  if (base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    // Get origins with extended permissions.
    for (const url::Origin& origin :
         ObjectPermissionContextBase::GetOriginsWithGrants()) {
      if (OriginHasExtendedPermission(origin)) {
        origins.insert(origin);
      }
    }
  }

  // Add origins that have active, granted permission grants.
  for (const auto& it : active_permissions_map_) {
    if (std::ranges::any_of(it.second.read_grants,
                            [&](const auto& grant) {
                              return HasGrantedActivePermissionStatus(
                                  grant.second);
                            }) ||
        std::ranges::any_of(it.second.write_grants, [&](const auto& grant) {
          return HasGrantedActivePermissionStatus(grant.second);
        })) {
      origins.insert(it.first);
    }
  }

  return origins;
}

std::string ChromeFileSystemAccessPermissionContext::GetKeyForObject(
    const base::Value::Dict& object) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  const auto optional_path =
      base::ValueToFilePath(object.Find(kPermissionPathKey));
  DCHECK(optional_path);
  return std::string(PathAsPermissionKey(optional_path.value()));
}

bool ChromeFileSystemAccessPermissionContext::IsValidObject(
    const base::Value::Dict& dict) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (dict.size() < 3 || dict.size() > 5) {
    return false;
  }

  // At least one of the readable/writable keys needs to be set.
  if (!dict.FindBool(kPermissionWritableKey) &&
      !dict.FindBool(kPermissionReadableKey)) {
    return false;
  }

  if (!dict.contains(kPermissionPathKey) ||
      !dict.FindBool(kPermissionIsDirectoryKey) ||
      dict.contains(kDeprecatedPermissionLastUsedTimeKey)) {
    return false;
  }

  return true;
}

std::u16string ChromeFileSystemAccessPermissionContext::GetObjectDisplayName(
    const base::Value::Dict& object) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  const auto optional_path =
      base::ValueToFilePath(object.Find(kPermissionPathKey));
  DCHECK(optional_path);
  return optional_path->LossyDisplayName();
}

ContentSetting
ChromeFileSystemAccessPermissionContext::GetReadGuardContentSetting(
    const url::Origin& origin) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return content_settings_->GetContentSetting(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_READ_GUARD);
}

ContentSetting
ChromeFileSystemAccessPermissionContext::GetWriteGuardContentSetting(
    const url::Origin& origin) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return content_settings_->GetContentSetting(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_WRITE_GUARD);
}

std::vector<base::FilePath>
ChromeFileSystemAccessPermissionContext::GetGrantedPaths(
    const url::Origin& origin) {
  std::vector<base::FilePath> granted_paths;
  auto granted_objects = GetGrantedObjects(origin);
  for (auto& granted_object : granted_objects) {
    auto* const optional_path = granted_object->value.Find(kPermissionPathKey);
    DCHECK(optional_path);
    granted_paths.push_back(base::ValueToFilePath(optional_path).value());
  }
  return granted_paths;
}

bool ChromeFileSystemAccessPermissionContext::CanObtainReadPermission(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return GetReadGuardContentSetting(origin) == CONTENT_SETTING_ASK ||
         GetReadGuardContentSetting(origin) == CONTENT_SETTING_ALLOW;
}

bool ChromeFileSystemAccessPermissionContext::CanObtainWritePermission(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  return GetWriteGuardContentSetting(origin) == CONTENT_SETTING_ASK ||
         GetWriteGuardContentSetting(origin) == CONTENT_SETTING_ALLOW;
}

bool ChromeFileSystemAccessPermissionContext::IsFileTypeDangerous(
    const base::FilePath& path,
    const url::Origin& origin) {
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  return GetFileTypeDangerLevel(path, origin,
                                Profile::FromBrowserContext(profile_)) ==
         safe_browsing::DownloadFileType::DANGEROUS;
#else
  return false;
#endif
}

void ChromeFileSystemAccessPermissionContext::ConfirmSensitiveEntryAccess(
    const url::Origin& origin,
    const content::PathInfo& path_info,
    HandleType handle_type,
    UserAction user_action,
    content::GlobalRenderFrameHostId frame_id,
    base::OnceCallback<void(SensitiveEntryResult)> callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const base::TimeTicks start_time = base::TimeTicks::Now();

  auto after_blocklist_check_callback = base::BindOnce(
      &ChromeFileSystemAccessPermissionContext::DidCheckPathAgainstBlocklist,
      GetWeakPtr(), origin, path_info, handle_type, user_action, frame_id,
      start_time, std::move(callback));
  CheckPathAgainstBlocklist(path_info, handle_type,
                            std::move(after_blocklist_check_callback));
}

void ChromeFileSystemAccessPermissionContext::CheckPathsAgainstEnterprisePolicy(
    std::vector<content::PathInfo> entries,
    content::GlobalRenderFrameHostId frame_id,
    EntriesAllowedByEnterprisePolicyCallback callback) {
#if BUILDFLAG(ENTERPRISE_CLOUD_CONTENT_ANALYSIS)
  // Get WebContents pointer in order to perform enterprise content analysis.
  content::WebContents* web_contents = nullptr;
  if (!entries.empty()) {
    content::RenderFrameHost* rfh = content::RenderFrameHost::FromID(frame_id);
    if (rfh && rfh->IsActive()) {
      web_contents = content::WebContents::FromRenderFrameHost(rfh);
    }
  }

  if (!web_contents) {
    std::move(callback).Run(std::move(entries));
    return;
  }

  enterprise_connectors::ContentAnalysisDelegate::Data data;
  if (!enterprise_connectors::ContentAnalysisDelegate::IsEnabled(
          Profile::FromBrowserContext(profile()),
          web_contents->GetLastCommittedURL(), &data,
          enterprise_connectors::AnalysisConnector::FILE_ATTACHED)) {
    std::move(callback).Run(std::move(entries));
    return;
  }

  data.reason =
      enterprise_connectors::ContentAnalysisRequest::FILE_PICKER_DIALOG;

  // Move the paths from `entries` to `data.paths` to minimize memory copies.
  // Later the paths will be recombined with the type left in `entries` for
  // those files that pass enterprise policy checks.
  std::transform(
      std::make_move_iterator(entries.begin()),
      std::make_move_iterator(entries.end()), std::back_inserter(data.paths),
      [](content::PathInfo&& entry) { return std::move(entry.path); });

  // TODO: crbug.com/326618625 - Handle kExternal files correctly.
  // CreateForFilesInWebContents() only handles real OS files, so these entries
  // are ignored and passed directly to OnContentAnalysisComplete() unchanged.
  // kExternal files only exist in ChromeOS.
  enterprise_connectors::ContentAnalysisDelegate::CreateForFilesInWebContents(
      web_contents, std::move(data),
      base::BindOnce(
          &ChromeFileSystemAccessPermissionContext::OnContentAnalysisComplete,
          weak_factory_.GetWeakPtr(), std::move(entries), std::move(callback)),
      safe_browsing::DeepScanAccessPoint::UPLOAD);
#else
  std::move(callback).Run(std::move(entries));
#endif  // BUILDFLAG(ENTERPRISE_CLOUD_CONTENT_ANALYSIS)
}

#if BUILDFLAG(ENTERPRISE_CLOUD_CONTENT_ANALYSIS)

void ChromeFileSystemAccessPermissionContext::OnContentAnalysisComplete(
    std::vector<content::PathInfo> entries,
    EntriesAllowedByEnterprisePolicyCallback callback,
    std::vector<base::FilePath> paths,
    std::vector<bool> allowed) {
  CHECK_EQ(paths.size(), allowed.size());
  CHECK_EQ(paths.size(), entries.size());

  std::vector<content::PathInfo> result_entries;
  for (size_t i = 0; i < paths.size(); ++i) {
    if (allowed[i]) {
      result_entries.emplace_back(entries[i].type, std::move(paths[i]),
                                  entries[i].display_name);
    }
  }

  std::move(callback).Run(std::move(result_entries));
}

#endif  // BUILDFLAG(ENTERPRISE_CLOUD_CONTENT_ANALYSIS)

void ChromeFileSystemAccessPermissionContext::CheckPathAgainstBlocklist(
    const content::PathInfo& path_info,
    HandleType handle_type,
    base::OnceCallback<void(bool)> callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // TODO(crbug.com/40101272): Figure out what external paths should be
  // blocked. We could resolve the external path to a local path, and check for
  // blocked directories based on that, but that doesn't work well. Instead we
  // should have a separate Chrome OS only code path to block for example the
  // root of certain external file systems.
  if (path_info.type == content::PathType::kExternal) {
    std::move(callback).Run(/*should_block=*/false);
    return;
  }

  // Unlike the DIR_USER_DATA check, this handles the --user-data-dir override.
  // We check for the user data dir in two different ways: directly, via the
  // profile manager, where it exists (it does not in unit tests), and via the
  // profile's directory, assuming the profile dir is a child of the user data
  // dir.
  std::vector<BlockPathRule> extra_rules;
  extra_rules.emplace_back(profile_->GetPath().DirName(),
                           BlockType::kBlockAllChildren);
  if (g_browser_process->profile_manager()) {
    extra_rules.emplace_back(
        g_browser_process->profile_manager()->user_data_dir(),
        BlockType::kBlockAllChildren);
  }

  base::ThreadPool::PostTaskAndReplyWithResult(
      FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
      base::BindOnce(&ShouldBlockAccessToPath, path_info.path, handle_type,
                     extra_rules, blocked_paths_,
                     profile_path_override_.value_or(profile_->GetPath())),
      std::move(callback));
}

void ChromeFileSystemAccessPermissionContext::PerformAfterWriteChecks(
    std::unique_ptr<content::FileSystemAccessWriteItem> item,
    content::GlobalRenderFrameHostId frame_id,
    base::OnceCallback<void(AfterWriteCheckResult)> callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(
          &DoSafeBrowsingCheckOnUIThread, frame_id, std::move(item),
          base::BindOnce(
              [](scoped_refptr<base::TaskRunner> task_runner,
                 base::OnceCallback<void(AfterWriteCheckResult result)>
                     callback,
                 safe_browsing::DownloadCheckResult result) {
                task_runner->PostTask(
                    FROM_HERE,
                    base::BindOnce(std::move(callback),
                                   InterpretSafeBrowsingResult(result)));
              },
              base::SequencedTaskRunner::GetCurrentDefault(),
              std::move(callback))));
#else
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(
          [](base::OnceCallback<void(AfterWriteCheckResult result)> callback) {
            std::move(callback).Run(AfterWriteCheckResult::kAllow);
          },
          std::move(callback)));
#endif
}

base::expected<void, std::string>
ChromeFileSystemAccessPermissionContext::CanShowFilePicker(
    content::RenderFrameHost* rfh) {
#if BUILDFLAG(ENABLE_GUEST_VIEW)
  // Because permission is scoped to profile, <webview> and <controlledframe>,
  // despite having isolated StoragePartition, will share File System Access
  // permission with the rest of the profile. Therefore, we want to disable FSA
  // for these contexts. However, <webview> is allowed to use FSA in avoidance
  // of breaking existing usage.
  if (auto* guest = extensions::WebViewGuest::FromRenderFrameHost(rfh);
      guest != nullptr) {
    // Disables file picker for <controlledframe> but allows <webview> to use
    // it.
    // TODO(crbug.com/40066989): Fix origin-keyed permission sharing between
    // <webview> and rest of profile.
    if (guest->IsOwnedByControlledFrameEmbedder()) {
      return base::unexpected(kDefaultNotAllowedMessage);
    }
    return base::ok();
  }
#endif  // BUILDFLAG(ENABLE_GUEST_VIEW)

  // Disable any other non-default StoragePartition contexts. However, unique
  // schemes (e.g. isolated-app://) are exempt here.
  if (rfh->GetStoragePartition() !=
          rfh->GetBrowserContext()->GetDefaultStoragePartition() &&
      rfh->GetLastCommittedURL().SchemeIsHTTPOrHTTPS()) {
    return base::unexpected(kDefaultNotAllowedMessage);
  }

  return base::ok();
}

void ChromeFileSystemAccessPermissionContext::DidCheckPathAgainstBlocklist(
    const url::Origin& origin,
    const content::PathInfo& path_info,
    HandleType handle_type,
    UserAction user_action,
    content::GlobalRenderFrameHostId frame_id,
    const base::TimeTicks start_time,
    base::OnceCallback<void(SensitiveEntryResult)> callback,
    bool should_block) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  base::UmaHistogramTimes(
      "Storage.FileSystemAccess.ConfirmSensitiveEntryAccessDuration",
      base::TimeTicks::Now() - start_time);

  if (user_action == UserAction::kNone) {
    std::move(callback).Run(should_block ? SensitiveEntryResult::kAbort
                                         : SensitiveEntryResult::kAllowed);
    return;
  }

  if (should_block) {
    auto result_callback =
        base::BindPostTaskToCurrentDefault(std::move(callback));
    content::GetUIThreadTaskRunner({})->PostTask(
        FROM_HERE,
        base::BindOnce(&ShowFileSystemAccessRestrictedDirectoryDialogOnUIThread,
                       frame_id, origin, handle_type,
                       std::move(result_callback)));
    return;
  }

#if BUILDFLAG(SAFE_BROWSING_AVAILABLE)
  // If attempting to save a file with a dangerous extension, prompt the user
  // to make them confirm they actually want to save the file.
  if (handle_type == HandleType::kFile && user_action == UserAction::kSave) {
    // See https://crbug.com/1320877#c4 for justification for why we show the
    // prompt if `danger_level` is ALLOW_ON_USER_GESTURE as well as DANGEROUS.
    auto danger_level = GetFileTypeDangerLevel(
        path_info.path, origin, Profile::FromBrowserContext(profile_));
    if (danger_level == safe_browsing::DownloadFileType::DANGEROUS ||
        danger_level ==
            safe_browsing::DownloadFileType::ALLOW_ON_USER_GESTURE) {
      auto result_callback =
          base::BindPostTaskToCurrentDefault(std::move(callback));
      content::GetUIThreadTaskRunner({})->PostTask(
          FROM_HERE,
          base::BindOnce(&ShowFileSystemAccessDangerousFileDialogOnUIThread,
                         frame_id, origin, path_info,
                         std::move(result_callback)));
      return;
    }
  }
#endif

  std::move(callback).Run(SensitiveEntryResult::kAllowed);
}

void ChromeFileSystemAccessPermissionContext::MaybeEvictEntries(
    base::Value::Dict& dict) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  std::vector<std::pair<base::Time, std::string>> entries;
  entries.reserve(dict.size());
  for (auto entry : dict) {
    // Don't evict the default ID.
    if (entry.first == kDefaultLastPickedDirectoryKey) {
      continue;
    }
    // If the data is corrupted and `entry.second` is for some reason not a
    // dict, it should be first in line for eviction.
    auto timestamp = base::Time::Min();
    if (entry.second.is_dict()) {
      timestamp = base::ValueToTime(entry.second.GetDict().Find(kTimestampKey))
                      .value_or(base::Time::Min());
    }
    entries.emplace_back(timestamp, entry.first);
  }

  if (entries.size() <= max_ids_per_origin_) {
    return;
  }

  std::ranges::sort(entries);
  size_t entries_to_remove = entries.size() - max_ids_per_origin_;
  for (size_t i = 0; i < entries_to_remove; ++i) {
    bool did_remove_entry = dict.Remove(entries[i].second);
    DCHECK(did_remove_entry);
  }
}

void ChromeFileSystemAccessPermissionContext::SetLastPickedDirectory(
    const url::Origin& origin,
    const std::string& id,
    const content::PathInfo& path_info) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  base::Value value = content_settings()->GetWebsiteSetting(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_LAST_PICKED_DIRECTORY,
      /*info=*/nullptr);
  if (!value.is_dict()) {
    value = base::Value(base::Value::Type::DICT);
  }

  base::Value::Dict& dict = value.GetDict();
  // Create an entry into the nested dictionary.
  base::Value::Dict entry;
  entry.Set(kPathKey, base::FilePathToValue(path_info.path));
  entry.Set(kPathTypeKey, static_cast<int>(path_info.type));
  entry.Set(kDisplayNameKey, path_info.display_name);
  entry.Set(kTimestampKey, base::TimeToValue(clock_->Now()));

  dict.Set(GenerateLastPickedDirectoryKey(id), std::move(entry));

  MaybeEvictEntries(dict);

  content_settings_->SetWebsiteSettingDefaultScope(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_LAST_PICKED_DIRECTORY,
      base::Value(std::move(dict)));
}

content::PathInfo
ChromeFileSystemAccessPermissionContext::GetLastPickedDirectory(
    const url::Origin& origin,
    const std::string& id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  base::Value value = content_settings()->GetWebsiteSetting(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_LAST_PICKED_DIRECTORY,
      /*info=*/nullptr);

  content::PathInfo path_info;
  if (!value.is_dict()) {
    return path_info;
  }

  auto* entry = value.GetDict().FindDict(GenerateLastPickedDirectoryKey(id));
  if (!entry) {
    return path_info;
  }

  auto type_int = entry->FindInt(kPathTypeKey)
                      .value_or(static_cast<int>(content::PathType::kLocal));
  path_info.type = type_int == static_cast<int>(content::PathType::kExternal)
                       ? content::PathType::kExternal
                       : content::PathType::kLocal;
  path_info.path =
      base::ValueToFilePath(entry->Find(kPathKey)).value_or(base::FilePath());
  path_info.display_name = StringOrEmpty(entry->FindString(kDisplayNameKey));
  return path_info;
}

base::FilePath
ChromeFileSystemAccessPermissionContext::GetWellKnownDirectoryPath(
    blink::mojom::WellKnownDirectory directory,
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // PDF viewer uses the default Download directory set in browser, if possible.
  if (directory == blink::mojom::WellKnownDirectory::kDirDownloads &&
      IsPdfExtensionOrigin(origin)) {
    base::FilePath profile_download_path =
        DownloadPrefs::FromBrowserContext(profile())->DownloadPath();
    if (!profile_download_path.empty()) {
      return profile_download_path;
    }
  }

  int key = base::PATH_START;
  switch (directory) {
    case blink::mojom::WellKnownDirectory::kDirDesktop:
      key = base::DIR_USER_DESKTOP;
      break;
    case blink::mojom::WellKnownDirectory::kDirDocuments:
      key = chrome::DIR_USER_DOCUMENTS;
      break;
    case blink::mojom::WellKnownDirectory::kDirDownloads:
      key = chrome::DIR_DEFAULT_DOWNLOADS;
      break;
    case blink::mojom::WellKnownDirectory::kDirMusic:
      key = chrome::DIR_USER_MUSIC;
      break;
    case blink::mojom::WellKnownDirectory::kDirPictures:
      key = chrome::DIR_USER_PICTURES;
      break;
    case blink::mojom::WellKnownDirectory::kDirVideos:
      key = chrome::DIR_USER_VIDEOS;
      break;
  }
  base::FilePath directory_path;
  base::PathService::Get(key, &directory_path);
  return directory_path;
}

std::u16string ChromeFileSystemAccessPermissionContext::GetPickerTitle(
    const blink::mojom::FilePickerOptionsPtr& options) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // TODO(asully): Consider adding custom strings for invocations of the file
  // picker, as well. Returning the empty string will fall back to the platform
  // default for the given picker type.
  std::u16string title;
  switch (options->type_specific_options->which()) {
    case blink::mojom::TypeSpecificFilePickerOptionsUnion::Tag::
        kDirectoryPickerOptions:
      title = l10n_util::GetStringUTF16(
          options->type_specific_options->get_directory_picker_options()
                  ->request_writable
              ? IDS_FILE_SYSTEM_ACCESS_CHOOSER_OPEN_WRITABLE_DIRECTORY_TITLE
              : IDS_FILE_SYSTEM_ACCESS_CHOOSER_OPEN_READABLE_DIRECTORY_TITLE);
      break;
    case blink::mojom::TypeSpecificFilePickerOptionsUnion::Tag::
        kSaveFilePickerOptions:
      title = l10n_util::GetStringUTF16(
          IDS_FILE_SYSTEM_ACCESS_CHOOSER_OPEN_SAVE_FILE_TITLE);
      break;
    case blink::mojom::TypeSpecificFilePickerOptionsUnion::Tag::
        kOpenFilePickerOptions:
      break;
  }
  return title;
}

void ChromeFileSystemAccessPermissionContext::NotifyEntryMoved(
    const url::Origin& origin,
    const content::PathInfo& old_path,
    const content::PathInfo& new_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (old_path == new_path) {
    return;
  }

  bool updated = false;
  auto it = active_permissions_map_.find(origin);
  if (it != active_permissions_map_.end()) {
    // TODO(crbug.com/40245144): Consolidate superfluous child grants.
    PermissionGrantImpl::UpdateGrantPath(it->second.write_grants, old_path,
                                         new_path);
    PermissionGrantImpl::UpdateGrantPath(it->second.read_grants, old_path,
                                         new_path);
    updated = true;
  }
  if (base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    // Active grants are a subset of persisted grants, so we also need to update
    // persisted grants, in case it's not covered by `UpdateGrantPath()` above.
    const std::unique_ptr<Object> object =
        GetGrantedObject(origin, PathAsPermissionKey(old_path.path));
    if (object) {
      base::Value::Dict new_object = object->value.Clone();
      new_object.Set(kPermissionPathKey, base::FilePathToValue(new_path.path));
      new_object.Set(kPermissionDisplayNameKey, new_path.display_name);
      UpdateObjectPermission(origin, object->value, std::move(new_object));
      updated = true;
    }
  }

  if (updated) {
    ScheduleUsageIconUpdate();
  }
}

void ChromeFileSystemAccessPermissionContext::
    OnFileCreatedFromShowSaveFilePicker(const GURL& file_picker_binding_context,
                                        const storage::FileSystemURL& url) {
  file_created_from_show_save_file_picker_callback_list_.Notify(
      file_picker_binding_context, url);
}

base::CallbackListSubscription ChromeFileSystemAccessPermissionContext::
    AddFileCreatedFromShowSaveFilePickerCallback(
        FileCreatedFromShowSaveFilePickerCallbackList::CallbackType callback) {
  return file_created_from_show_save_file_picker_callback_list_.Add(
      std::move(callback));
}

ChromeFileSystemAccessPermissionContext::Grants
ChromeFileSystemAccessPermissionContext::ConvertObjectsToGrants(
    std::vector<std::unique_ptr<Object>> objects) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  ChromeFileSystemAccessPermissionContext::Grants grants;

  for (const auto& object : objects) {
    if (!IsValidObject(object->value)) {
      continue;
    }

    const base::Value::Dict& object_dict = object->value;
    const base::FilePath path =
        base::ValueToFilePath(object_dict.Find(kPermissionPathKey)).value();
    std::string display_name =
        StringOrEmpty(object_dict.FindString(kPermissionDisplayNameKey));
    if (display_name.empty()) {
      display_name = path.BaseName().AsUTF8Unsafe();
    }
    if (path.empty() || display_name.empty()) {
      continue;
    }
    HandleType handle_type =
        object_dict.FindBool(kPermissionIsDirectoryKey).value()
            ? HandleType::kDirectory
            : HandleType::kFile;
    bool is_write_grant =
        object_dict.FindBool(kPermissionWritableKey).value_or(false);
    bool is_read_grant =
        object_dict.FindBool(kPermissionReadableKey).value_or(false);

    if (handle_type == HandleType::kDirectory) {
      if (is_write_grant &&
          !PathInfosContains(grants.directory_write_grants, path)) {
        grants.directory_write_grants.emplace_back(path, display_name);
      }
      if (is_read_grant &&
          !PathInfosContains(grants.directory_read_grants, path)) {
        grants.directory_read_grants.emplace_back(path, display_name);
      }
    }
    if (handle_type == HandleType::kFile) {
      if (is_write_grant &&
          !PathInfosContains(grants.file_write_grants, path)) {
        grants.file_write_grants.emplace_back(path, display_name);
      }
      if (is_read_grant && !PathInfosContains(grants.file_read_grants, path)) {
        grants.file_read_grants.emplace_back(path, display_name);
      }
    }
  }

  return grants;
}

void ChromeFileSystemAccessPermissionContext::
    CreatePersistedGrantsFromActiveGrants(const url::Origin& origin) {
  if (base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    auto origin_it = active_permissions_map_.find(origin);
    if (origin_it != active_permissions_map_.end()) {
      OriginState& origin_state = origin_it->second;
      for (auto& read_grant : origin_state.read_grants) {
        if (HasGrantedActivePermissionStatus(read_grant.second)) {
          read_grant.second->SetStatus(
              PermissionStatus::GRANTED,
              PersistedPermissionOptions::kUpdatePersistedPermission);
        }
      }
      for (auto& write_grant : origin_state.write_grants) {
        if (HasGrantedActivePermissionStatus(write_grant.second)) {
          write_grant.second->SetStatus(
              PermissionStatus::GRANTED,
              PersistedPermissionOptions::kUpdatePersistedPermission);
        }
      }
    }
  }
}

void ChromeFileSystemAccessPermissionContext::RevokeGrant(
    const url::Origin& origin,
    const base::FilePath& file_path) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  bool grant_revoked = false;
  if (base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    auto key = PathAsPermissionKey(file_path);
    const std::unique_ptr<Object> object = GetGrantedObject(origin, key);
    if (object) {
      RevokeObjectPermission(origin, key);
      grant_revoked = true;
    }
  }

  if (RevokeActiveGrants(origin, file_path)) {
    grant_revoked = true;
  }

  if (grant_revoked) {
    ScheduleUsageIconUpdate();
  }
}

void ChromeFileSystemAccessPermissionContext::RevokeGrants(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  bool grant_revoked = false;
  if (base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    grant_revoked =
        ObjectPermissionContextBase::RevokeObjectPermissions(origin);
    content_settings_->SetContentSettingDefaultScope(
        origin.GetURL(), origin.GetURL(),
        ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION,
        ContentSetting::CONTENT_SETTING_DEFAULT);
  }

  if (RevokeActiveGrants(origin)) {
    grant_revoked = true;
  }

  if (grant_revoked) {
    ScheduleUsageIconUpdate();
  }
}

bool ChromeFileSystemAccessPermissionContext::OriginHasReadAccess(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // First, check if an origin has read access granted via active permissions.
  auto it = active_permissions_map_.find(origin);
  if (it != active_permissions_map_.end()) {
    return std::ranges::any_of(it->second.read_grants, [&](const auto& grant) {
      return HasGrantedActivePermissionStatus(grant.second);
    });
  }
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return false;
  }

  // Check if an origin has read access granted via extended permissions.
  std::vector<std::unique_ptr<Object>> extended_grant_objects =
      GetExtendedPersistedObjects(origin);
  if (extended_grant_objects.empty()) {
    return false;
  }
  return std::ranges::any_of(extended_grant_objects, [&](const auto& grant) {
    return grant->value.FindBool(kPermissionReadableKey).value_or(false);
  });
}

bool ChromeFileSystemAccessPermissionContext::OriginHasWriteAccess(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // First, check if an origin has write access granted via active permissions.
  auto it = active_permissions_map_.find(origin);
  if (it != active_permissions_map_.end()) {
    return std::ranges::any_of(it->second.write_grants, [&](const auto& grant) {
      return HasGrantedActivePermissionStatus(grant.second);
    });
  }
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return false;
  }

  // Check if an origin has write access granted via extended permissions.
  std::vector<std::unique_ptr<Object>> extended_grant_objects =
      GetExtendedPersistedObjects(origin);
  if (extended_grant_objects.empty()) {
    return false;
  }
  return std::ranges::any_of(extended_grant_objects, [&](const auto& grant) {
    return grant->value.FindBool(kPermissionWritableKey).value_or(false);
  });
}

// All tabs for a given origin have been backgrounded or cleared in the past
// 16 hours. When this happens, we update the given origin's `OriginState` to
// note that all tabs were recently backgrounded.
void ChromeFileSystemAccessPermissionContext::OnAllTabsInBackgroundTimerExpired(
    const url::Origin& origin,
    const OneTimePermissionsTrackerObserver::BackgroundExpiryType&
        expiry_type) {
  if (
#if !BUILDFLAG(IS_ANDROID)
      !base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions) ||
#endif
      expiry_type != BackgroundExpiryType::kLongTimeout) {
    return;
  }
  SetPersistedGrantStatus(origin, PersistedGrantStatus::kBackgrounded);
  if (RevokeActiveGrants(origin)) {
    permissions::PermissionUmaUtil::RecordOneTimePermissionEvent(
        ContentSettingsType::FILE_SYSTEM_WRITE_GUARD,
        permissions::OneTimePermissionEvent::EXPIRED_IN_BACKGROUND);
    ScheduleUsageIconUpdate();
  }
}

void ChromeFileSystemAccessPermissionContext::OnLastPageFromOriginClosed(
    const url::Origin& origin) {
  CleanupPermissions(origin);
}

void ChromeFileSystemAccessPermissionContext::OnShutdown() {
  one_time_permissions_tracker_.Reset();
}

#if !BUILDFLAG(IS_ANDROID)
void ChromeFileSystemAccessPermissionContext::OnWebAppInstalled(
    const webapps::AppId& app_id) {
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return;
  }

  auto* provider = web_app::WebAppProvider::GetForWebApps(
      Profile::FromBrowserContext(profile()));
  const auto& registrar = provider->registrar_unsafe();
  // TODO(crbug.com/340952100): Evaluate call sites of IsInstallState for
  // correctness.
  if (registrar.GetInstallState(app_id) !=
      web_app::proto::InstallState::INSTALLED_WITH_OS_INTEGRATION) {
    return;
  }

  // TODO(crbug.com/40283362): Ensure that `GetAppScope` retrieves the correct
  // GURL when Scope Extensions is launched, which allows web apps to have more
  // than one origin as a scope.
  const auto gurl = registrar.GetAppScope(app_id);
  if (!gurl.is_valid()) {
    return;
  }
  const auto origin = url::Origin::Create(gurl);
  auto origin_it = active_permissions_map_.find(origin);
  if (origin_it == active_permissions_map_.end()) {
    // Ignore the origin if it does not have any active permissions.
    return;
  }

  // Update the cache value for web app state.
  OriginState& origin_state = origin_it->second;
  origin_state.web_app_install_status = WebAppInstallStatus::kInstalled;

  // Update the persisted grants, if needed.
  auto content_setting_value = content_settings_->GetContentSetting(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION);
  if (content_setting_value == ContentSetting::CONTENT_SETTING_ALLOW ||
      content_setting_value == ContentSetting::CONTENT_SETTING_BLOCK) {
    // The user has already enabled or disabled extended permissions from the
    // Restore Prompt or Page Info bubble. Installing a WebApp should not
    // change the extended permission state.
    return;
  }
  UpgradeToExtendedPermission(origin);
}

void ChromeFileSystemAccessPermissionContext::OnWebAppInstalledWithOsHooks(
    const webapps::AppId& app_id) {
  // TODO(crbug.com/340952100): Remove the method after the InstallState is
  // saved in the database & available from OnWebAppInstalled.
  OnWebAppInstalled(app_id);
}

void ChromeFileSystemAccessPermissionContext::OnWebAppWillBeUninstalled(
    const webapps::AppId& app_id) {
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return;
  }

  auto* provider = web_app::WebAppProvider::GetForWebApps(
      Profile::FromBrowserContext(profile()));
  const auto& registrar = provider->registrar_unsafe();
  auto gurl = registrar.GetAppScope(app_id);
  if (!gurl.is_valid()) {
    return;
  }
  const auto origin = url::Origin::Create(gurl);
  auto origin_it = active_permissions_map_.find(origin);
  if (origin_it == active_permissions_map_.end()) {
    // Ignore the origin if it does not have any active permission.
    return;
  }

  // Update the cache value for web app state.
  OriginState& origin_state = origin_it->second;
  origin_state.web_app_install_status = WebAppInstallStatus::kUninstalled;

  // Update the persisted grants, if needed.
  auto content_setting_value = content_settings_->GetContentSetting(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION);
  if (content_setting_value == ContentSetting::CONTENT_SETTING_ALLOW ||
      content_setting_value == ContentSetting::CONTENT_SETTING_BLOCK) {
    // The user has already enabled or disabled extended permissions from the
    // Restore Prompt or Page Info bubble. Uninstalling a WebApp should not
    // change the extended permission state.
    return;
  }
  RemoveExtendedPermission(origin);
}

void ChromeFileSystemAccessPermissionContext::
    OnWebAppInstallManagerDestroyed() {
  install_manager_observation_.Reset();
}
#endif

void ChromeFileSystemAccessPermissionContext::NavigatedAwayFromOrigin(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    auto it = active_permissions_map_.find(origin);
    // If we have no permissions for the origin, there is nothing to do.
    if (it == active_permissions_map_.end()) {
      return;
    }

    // Start a timer to possibly clean up permissions for this origin.
    if (!it->second.cleanup_timer) {
      it->second.cleanup_timer = std::make_unique<base::RetainingOneShotTimer>(
          FROM_HERE, kPermissionRevocationTimeout,
          base::BindRepeating(
              &ChromeFileSystemAccessPermissionContext::MaybeCleanupPermissions,
              base::Unretained(this), origin));
    }
    it->second.cleanup_timer->Reset();
  }
}

void ChromeFileSystemAccessPermissionContext::TriggerTimersForTesting() {
  for (const auto& it : active_permissions_map_) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
    if (it.second.cleanup_timer) {
      auto task = it.second.cleanup_timer->user_task();
      it.second.cleanup_timer->Stop();
      task.Run();
    }
  }
}

void ChromeFileSystemAccessPermissionContext::MaybeCleanupPermissions(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Iterate over all top-level frames by iterating over all tabs in all browser
  // windows. This also counts PWAs in windows without tab strips.
#if BUILDFLAG(IS_ANDROID)
  for (TabModel* tabs : TabModelList::models()) {
    if (tabs->GetProfile() != profile()) {
      continue;
    }
    int tab_count = tabs->GetTabCount();
#else
  for (Browser* browser : *BrowserList::GetInstance()) {
    if (browser->profile() != profile()) {
      continue;
    }
    TabStripModel* tabs = browser->tab_strip_model();
    int tab_count = tabs->count();
#endif
    for (int i = 0; i < tab_count; ++i) {
      content::WebContents* web_contents = tabs->GetWebContentsAt(i);
      if (!web_contents) {
        continue;
      }
      url::Origin tab_origin = url::Origin::Create(
          permissions::PermissionUtil::GetLastCommittedOriginAsURL(
              web_contents->GetPrimaryMainFrame()));
      // Found a tab for this origin, so early exit and don't revoke grants.
      if (tab_origin == origin) {
        return;
      }
    }
  }
  CleanupPermissions(origin);
}

void ChromeFileSystemAccessPermissionContext::CleanupPermissions(
    const url::Origin& origin) {
  // TODO(crbug.com/40101962): Remove this custom implementation to handle site
  // navigation, with the launch of Persistent Permissions.
  if (base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    // Clear the grants that should not be carried across sessions.
    if (!OriginHasExtendedPermission(origin) &&
        GetPersistedGrantStatus(origin) == PersistedGrantStatus::kLoaded) {
      RevokeObjectPermissions(origin);
    }
    // Reset the persisted grant status to the default state.
    SetPersistedGrantStatus(origin, PersistedGrantStatus::kLoaded);
  }
  // Revoke the active grants, setting the status to `ASK`.
  if (RevokeActiveGrants(origin)) {
    ScheduleUsageIconUpdate();
  }
}

void ChromeFileSystemAccessPermissionContext::
    OnRestorePermissionAllowedEveryTime(const url::Origin& origin) {
  UpdateGrantsOnRestorePermissionAllowed(origin);
  content_settings_->SetContentSettingDefaultScope(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION,
      ContentSetting::CONTENT_SETTING_ALLOW);
}

void ChromeFileSystemAccessPermissionContext::OnRestorePermissionAllowedOnce(
    const url::Origin& origin) {
  UpdateGrantsOnRestorePermissionAllowed(origin);
}

void ChromeFileSystemAccessPermissionContext::
    UpdateGrantsOnRestorePermissionAllowed(const url::Origin& origin) {
  // Set `PersistedGrantStatus::kCurrent` so that Persisted grants are now
  // updated from dormant grants to extended/shadow grants.
  SetPersistedGrantStatus(origin, PersistedGrantStatus::kCurrent);

  auto it = active_permissions_map_.find(origin);
  if (it == active_permissions_map_.end()) {
    return;
  }
  // Use the persisted grants to find the matching active permission, and
  // set it to `granted`.
  for (auto& dormant_grant :
       ObjectPermissionContextBase::GetGrantedObjects(origin)) {
    base::Value::Dict& object_dict = dormant_grant->value;
    base::FilePath path =
        base::ValueToFilePath(object_dict.Find(kPermissionPathKey)).value();
    auto handle_type = object_dict.FindBool(kPermissionIsDirectoryKey).value()
                           ? HandleType::kDirectory
                           : HandleType::kFile;
    if (object_dict.FindBool(kPermissionReadableKey).value_or(false)) {
      auto& read_grant = it->second.read_grants[path];
      if (read_grant && read_grant->handle_type() == handle_type) {
        read_grant->SetStatus(
            PermissionStatus::GRANTED,
            PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
      }
    }
    if (object_dict.FindBool(kPermissionWritableKey).value_or(false)) {
      auto& write_grant = it->second.write_grants[path];
      if (write_grant && write_grant->handle_type() == handle_type) {
        write_grant->SetStatus(
            PermissionStatus::GRANTED,
            PersistedPermissionOptions::kDoNotUpdatePersistedPermission);
      }
    }
  }
}

void ChromeFileSystemAccessPermissionContext::
    OnRestorePermissionDeniedOrDismissed(const url::Origin& origin) {
  // Both denying and dismissing the restore prompt count as a `dismiss`
  // action, for embargo purposes.
  PermissionDecisionAutoBlockerFactory::GetForProfile(
      Profile::FromBrowserContext(profile()))
      ->RecordDismissAndEmbargo(
          origin.GetURL(),
          ContentSettingsType::FILE_SYSTEM_ACCESS_RESTORE_PERMISSION, false);
  UpdateGrantsOnRestorePermissionNotAllowed(origin);
}

void ChromeFileSystemAccessPermissionContext::OnRestorePermissionIgnored(
    const url::Origin& origin) {
  PermissionDecisionAutoBlockerFactory::GetForProfile(
      Profile::FromBrowserContext(profile()))
      ->RecordIgnoreAndEmbargo(
          origin.GetURL(),
          ContentSettingsType::FILE_SYSTEM_ACCESS_RESTORE_PERMISSION, false);
  UpdateGrantsOnRestorePermissionNotAllowed(origin);
}

void ChromeFileSystemAccessPermissionContext::
    UpdateGrantsOnRestorePermissionNotAllowed(const url::Origin& origin) {
  SetPersistedGrantStatus(origin, PersistedGrantStatus::kCurrent);
  // Revoke all of the persistent permissions for the given origin.
  if (!OriginHasExtendedPermission(origin)) {
    ObjectPermissionContextBase::RevokeObjectPermissions(origin);
  }
}

void ChromeFileSystemAccessPermissionContext::
    UpdateGrantsOnPermissionRequestResult(const url::Origin& origin) {
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return;
  }

  if (GetPersistedGrantStatus(origin) != PersistedGrantStatus::kCurrent) {
    // Requesting permission triggered the regular permission prompt, not the
    // restore permission prompt. Clear persisted grants and reset the grant
    // status so that dormant grants are not carried over to the next session.
    SetPersistedGrantStatus(origin, PersistedGrantStatus::kCurrent);
    if (!OriginHasExtendedPermission(origin)) {
      ObjectPermissionContextBase::RevokeObjectPermissions(origin);
    }
  }
}

bool ChromeFileSystemAccessPermissionContext::AncestorHasActivePermission(
    const url::Origin& origin,
    const base::FilePath& path,
    GrantType grant_type) const {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto it = active_permissions_map_.find(origin);
  if (it == active_permissions_map_.end()) {
    return false;
  }
  const auto& relevant_grants = grant_type == GrantType::kWrite
                                    ? it->second.write_grants
                                    : it->second.read_grants;
  if (relevant_grants.empty()) {
    return false;
  }

  // Permissions are inherited from the closest ancestor.
  for (base::FilePath parent = path.DirName(); parent != parent.DirName();
       parent = parent.DirName()) {
    auto i = relevant_grants.find(parent);
    if (i != relevant_grants.end() && i->second &&
        HasGrantedActivePermissionStatus(i->second)) {
      return true;
    }
  }
  return false;
}

bool ChromeFileSystemAccessPermissionContext::HasGrantedActivePermissionStatus(
    PermissionGrantImpl* grant) const {
  return grant &&
         grant->GetActivePermissionStatus() == PermissionStatus::GRANTED;
}

bool ChromeFileSystemAccessPermissionContext::
    IsEligibleToUpgradePermissionRequestToRestorePrompt(
        const url::Origin& origin,
        const base::FilePath& file_path,
        HandleType handle_type,
        UserAction user_action,
        GrantType grant_type) {
#if BUILDFLAG(IS_ANDROID)
  // TODO(crbug.com/40101963): Enable when android persisted permissions are
  // implemented.
  return false;
#else
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return false;
  }
  const bool origin_is_embargoed =
      PermissionDecisionAutoBlockerFactory::GetForProfile(
          Profile::FromBrowserContext(profile()))
          ->IsEmbargoed(
              origin.GetURL(),
              ContentSettingsType::FILE_SYSTEM_ACCESS_RESTORE_PERMISSION);
  if (origin_is_embargoed) {
    return false;
  }

  if (GetPersistedGrantType(origin) != PersistedGrantType::kDormant) {
    return false;
  }

#if BUILDFLAG(ENABLE_PLATFORM_APPS)
  // The restore prompt is not displayed when there is a platform app installed,
  // because there is no valid UI element to display the restore prompt from.
  const extensions::ExtensionRegistry* registry =
      extensions::ExtensionRegistry::Get(profile());
  const extensions::Extension* app =
      registry ? registry->enabled_extensions().GetExtensionOrAppByURL(
                     origin.GetURL())
               : nullptr;
  if (app && app->is_platform_app()) {
    return false;
  }
#endif

  // While this method is called from `RequestPermission`, which implies that
  // a `PermissionGrantImpl` exists - we want to insert the origin into the
  // permissions map if it does not exist, in order to cover cases of shutdown
  // or page navigation.
  auto& origin_state = active_permissions_map_[origin];

  // If an origin's grants have been revoked from being backgrounded, or
  // the permission request is on a handle retrieved from IndexedDB, then
  // the restore prompt may be eligible if requesting a permission on a handle,
  // which is previously granted (i.e. dormant grant exists for this file path).
  if (origin_state.persisted_grant_status ==
          PersistedGrantStatus::kBackgrounded ||
      user_action == UserAction::kLoadFromStorage) {
    return HasPersistedGrantObject(origin, file_path, handle_type, grant_type);
  }

  return false;
#endif  // BUILDFLAG(IS_ANDROID)
}

std::vector<FileRequestData> ChromeFileSystemAccessPermissionContext::
    GetFileRequestDataForRestorePermissionPrompt(const url::Origin& origin) {
  std::vector<FileRequestData> file_request_data_list;
  auto dormant_grants = ObjectPermissionContextBase::GetGrantedObjects(origin);
  for (auto& dormant_grant : dormant_grants) {
    if (!IsValidObject(dormant_grant->value)) {
      continue;
    }
    const base::Value::Dict& object_dict = dormant_grant->value;
    base::FilePath path =
        base::ValueToFilePath(object_dict.Find(kPermissionPathKey)).value();
    std::string display_name =
        StringOrEmpty(object_dict.FindString(kPermissionDisplayNameKey));
    FileRequestData file_request_data = {
        content::PathInfo(path, !display_name.empty()
                                    ? display_name
                                    : path.BaseName().AsUTF8Unsafe()),
        object_dict.FindBool(kPermissionIsDirectoryKey).value_or(false)
            ? HandleType::kDirectory
            : HandleType::kFile,
        object_dict.FindBool(kPermissionWritableKey).value_or(false)
            ? RequestAccess::kWrite
            : RequestAccess::kRead};
    file_request_data_list.push_back(file_request_data);
  }
  return file_request_data_list;
}

bool ChromeFileSystemAccessPermissionContext::HasPersistedGrantObject(
    const url::Origin& origin,
    const base::FilePath& file_path,
    HandleType handle_type,
    GrantType grant_type) {
  auto persisted_grants =
      ObjectPermissionContextBase::GetGrantedObjects(origin);
  return std::ranges::any_of(persisted_grants, [&](const auto& object) {
    return HasMatchingValue(object->value, file_path, handle_type, grant_type);
  });
}

bool ChromeFileSystemAccessPermissionContext::HasMatchingValue(
    const base::Value::Dict& value,
    const base::FilePath& file_path,
    HandleType handle_type,
    GrantType grant_type) {
  return ValueToFilePath(value.Find(kPermissionPathKey)).value() == file_path &&
         value.FindBool(kPermissionIsDirectoryKey).value_or(false) ==
             (handle_type == HandleType::kDirectory) &&
         value.FindBool(GetGrantKeyFromGrantType(grant_type)).value_or(false);
}

void ChromeFileSystemAccessPermissionContext::
    SetOriginHasExtendedPermissionForTesting(const url::Origin& origin) {
  CHECK(base::FeatureList::IsEnabled(
      features::kFileSystemAccessPersistentPermissions));
  content_settings_->SetContentSettingDefaultScope(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION,
      ContentSetting::CONTENT_SETTING_ALLOW);
}

scoped_refptr<content::FileSystemAccessPermissionGrant>
ChromeFileSystemAccessPermissionContext::
    GetExtendedReadPermissionGrantForTesting(  // IN-TEST
        const url::Origin& origin,
        const content::PathInfo& path_info,
        HandleType handle_type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto grant =
      GetReadPermissionGrant(origin, path_info, handle_type, UserAction::kOpen);

  static_cast<PermissionGrantImpl*>(grant.get())
      ->SetStatus(PermissionStatus::GRANTED,
                  PersistedPermissionOptions::kUpdatePersistedPermission);
  return grant;
}

scoped_refptr<content::FileSystemAccessPermissionGrant>
ChromeFileSystemAccessPermissionContext::
    GetExtendedWritePermissionGrantForTesting(  // IN-TEST
        const url::Origin& origin,
        const content::PathInfo& path_info,
        HandleType handle_type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto grant = GetWritePermissionGrant(origin, path_info, handle_type,
                                       UserAction::kSave);

  static_cast<PermissionGrantImpl*>(grant.get())
      ->SetStatus(PermissionStatus::GRANTED,
                  PersistedPermissionOptions::kUpdatePersistedPermission);
  return grant;
}

base::AutoReset<std::optional<base::FilePath>>
ChromeFileSystemAccessPermissionContext::OverrideProfilePathForTesting(
    const base::FilePath& profile_path_override) {
  return base::AutoReset<std::optional<base::FilePath>>(&profile_path_override_,
                                                        profile_path_override);
}

void ChromeFileSystemAccessPermissionContext::Shutdown() {
  FlushScheduledSaveSettingsCalls();
  permissions::ObjectPermissionContextBase::Shutdown();
}

bool ChromeFileSystemAccessPermissionContext::
    CanAutoGrantViaPersistentPermission(const url::Origin& origin,
                                        const base::FilePath& path,
                                        HandleType handle_type,
                                        GrantType grant_type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return false;
  }

  auto persisted_grant_type = GetPersistedGrantType(origin);
  if (!(persisted_grant_type == PersistedGrantType::kExtended ||
        persisted_grant_type == PersistedGrantType::kShadow)) {
    // Only shadow or extended grants are auto-granted.
    return false;
  }

  auto object = GetGrantedObject(origin, PathAsPermissionKey(path));
  return object &&
         HasMatchingValue(object->value, path, handle_type, grant_type);
}

bool ChromeFileSystemAccessPermissionContext::
    CanAutoGrantViaAncestorPersistentPermission(const url::Origin& origin,
                                                const base::FilePath& path,
                                                GrantType grant_type) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return false;
  }

  auto persisted_grant_type = GetPersistedGrantType(origin);
  if (!(persisted_grant_type == PersistedGrantType::kExtended ||
        persisted_grant_type == PersistedGrantType::kShadow)) {
    // Only shadow or extended grants are auto-granted.
    return false;
  }

  if (GetGrantedObjects(origin).empty()) {
    // Return early if the origin does not have any grant objects.
    return false;
  }

  for (base::FilePath parent = path.DirName(); parent != parent.DirName();
       parent = parent.DirName()) {
    auto object = GetGrantedObject(origin, PathAsPermissionKey(parent));
    if (object && HasMatchingValue(object->value, parent,
                                   HandleType::kDirectory, grant_type)) {
      return true;
    }
  }
  return false;
}

bool ChromeFileSystemAccessPermissionContext::OriginHasExtendedPermission(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

#if BUILDFLAG(IS_ANDROID)
  // TODO(crbug.com/40101963): Enable when android persisted permissions are
  // implemented.
  return false;
#else
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return false;
  }

  auto content_setting_value = content_settings_->GetContentSetting(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION);
  if (content_setting_value == ContentSetting::CONTENT_SETTING_ALLOW) {
    return true;
  }
  if (content_setting_value == ContentSetting::CONTENT_SETTING_BLOCK) {
    return false;
  }

  // If user has not set the extended permission preference, the extended
  // permission state depends on whether the origin has an web app actively
  // installed. First, check the cached value.
  auto& origin_state = active_permissions_map_[origin];
  if (origin_state.web_app_install_status != WebAppInstallStatus::kUnknown) {
    return origin_state.web_app_install_status ==
           WebAppInstallStatus::kInstalled;
  }
  // No cached value for web app install status. Retrieve the install status.
  DCHECK(profile());
  auto* web_app_provider = web_app::WebAppProvider::GetForWebApps(
      Profile::FromBrowserContext(profile()));
  if (!web_app_provider) {
    return false;
  }
  auto app_id = web_app_provider->registrar_unsafe().FindBestAppWithUrlInScope(
      origin.GetURL(), web_app::WebAppFilter::InstalledInChrome());

  auto app_has_os_integration =
      app_id.has_value() &&
      web_app_provider->registrar_unsafe().GetInstallState(app_id.value()) ==
          web_app::proto::InstallState::INSTALLED_WITH_OS_INTEGRATION;
  // Update the cached value.
  origin_state.web_app_install_status = app_has_os_integration
                                            ? WebAppInstallStatus::kInstalled
                                            : WebAppInstallStatus::kUninstalled;
  return app_has_os_integration;
#endif  // BUILDFLAG(IS_ANDROID)
}

void ChromeFileSystemAccessPermissionContext::SetOriginExtendedPermissionByUser(
    const url::Origin& origin) {
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return;
  }
  const bool has_extended_permission = OriginHasExtendedPermission(origin);
  content_settings_->SetContentSettingDefaultScope(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION,
      ContentSetting::CONTENT_SETTING_ALLOW);
  // Only update object permissions in the case that the origin did not
  // already have extended permissions.
  if (!has_extended_permission) {
    UpgradeToExtendedPermission(origin);
  }
}

void ChromeFileSystemAccessPermissionContext::
    RemoveOriginExtendedPermissionByUser(const url::Origin& origin) {
  if (!base::FeatureList::IsEnabled(
          features::kFileSystemAccessPersistentPermissions)) {
    return;
  }
  const bool has_extended_permission = OriginHasExtendedPermission(origin);
  content_settings_->SetContentSettingDefaultScope(
      origin.GetURL(), origin.GetURL(),
      ContentSettingsType::FILE_SYSTEM_ACCESS_EXTENDED_PERMISSION,
      ContentSetting::CONTENT_SETTING_BLOCK);
  // Only update object permissions in the case that the origin already had
  // extended permissions.
  if (has_extended_permission) {
    RemoveExtendedPermission(origin);
  }
}

void ChromeFileSystemAccessPermissionContext::RemoveExtendedPermission(
    const url::Origin& origin) {
  auto origin_it = active_permissions_map_.find(origin);
  if (origin_it == active_permissions_map_.end()) {
    // Ignore the origin if it does not have any active permissions.
    return;
  }
  OriginState& origin_state = origin_it->second;
  // Re-create shadow grants based on active grants.
  RevokeObjectPermissions(origin);
  CreatePersistedGrantsFromActiveGrants(origin);
  ScheduleUsageIconUpdate();
  origin_state.persisted_grant_status = PersistedGrantStatus::kCurrent;
}

void ChromeFileSystemAccessPermissionContext::UpgradeToExtendedPermission(
    const url::Origin& origin) {
  auto origin_it = active_permissions_map_.find(origin);
  if (origin_it == active_permissions_map_.end()) {
    // Ignore the origin if it does not have any active permissions.
    return;
  }
  OriginState& origin_state = origin_it->second;
  if (origin_state.persisted_grant_status == PersistedGrantStatus::kCurrent) {
    // Previously, the given origin's persisted grants were shadow grants, and
    // installing a WebApp or enabling extended permissions from the Page Info
    // UI promotes these grants to extended grants.
    // The persisted grants are not affected, given that they are now
    // considered extended grants.
    return;
  }
  // Previously, the given origin's persisted grants were dormant grants and
  // therefore should not be promoted to extended grants. The dormant grants
  // are cleared so that they cannot be considered extended grants.
  RevokeObjectPermissions(origin);
  ScheduleUsageIconUpdate();
  origin_state.persisted_grant_status = PersistedGrantStatus::kCurrent;
}

ChromeFileSystemAccessPermissionContext::PersistedGrantType
ChromeFileSystemAccessPermissionContext::GetPersistedGrantType(
    const url::Origin& origin) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (OriginHasExtendedPermission(origin)) {
    return PersistedGrantType::kExtended;
  }

  switch (GetPersistedGrantStatus(origin)) {
    case PersistedGrantStatus::kBackgrounded:
    case PersistedGrantStatus::kLoaded:
      return PersistedGrantType::kDormant;
    case PersistedGrantStatus::kCurrent:
      return PersistedGrantType::kShadow;
  }
}

PersistedGrantStatus
ChromeFileSystemAccessPermissionContext::GetPersistedGrantStatus(
    const url::Origin& origin) const {
  auto origin_it = active_permissions_map_.find(origin);
  if (origin_it != active_permissions_map_.end()) {
    return origin_it->second.persisted_grant_status;
  }
  // Return the default persisted grant status in the case that the origin is
  // not found in the active permissions map.
  return PersistedGrantStatus::kLoaded;
}

void ChromeFileSystemAccessPermissionContext::SetPersistedGrantStatus(
    const url::Origin& origin,
    PersistedGrantStatus persisted_grant_status) {
  // Insert the origin into the permissions map if it does not exist.
  auto& origin_state = active_permissions_map_[origin];
  origin_state.persisted_grant_status = persisted_grant_status;
}

void ChromeFileSystemAccessPermissionContext::PermissionGrantDestroyed(
    PermissionGrantImpl* grant) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto it = active_permissions_map_.find(grant->origin());
  if (it == active_permissions_map_.end()) {
    return;
  }

  auto& grants = grant->type() == GrantType::kRead ? it->second.read_grants
                                                   : it->second.write_grants;
  auto grant_it = grants.find(grant->GetPath());
  // Any non-denied permission grants should have still been in our grants
  // list. If this invariant is violated we would have permissions that might
  // be granted but won't be visible in any UI because the permission context
  // isn't tracking them anymore.
  if (grant_it == grants.end()) {
    DCHECK_EQ(PermissionStatus::DENIED, grant->GetActivePermissionStatus());
    return;
  }

  // The grant in |grants| for this path might have been replaced with a
  // different grant. Only erase if it actually matches the grant that was
  // destroyed.
  if (grant_it->second == grant) {
    grants.erase(grant_it);
  }

  ScheduleUsageIconUpdate();
}

void ChromeFileSystemAccessPermissionContext::ScheduleUsageIconUpdate() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (usage_icon_update_scheduled_) {
    return;
  }
  usage_icon_update_scheduled_ = true;
  base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &ChromeFileSystemAccessPermissionContext::DoUsageIconUpdate,
          weak_factory_.GetWeakPtr()));
}

void ChromeFileSystemAccessPermissionContext::DoUsageIconUpdate() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  usage_icon_update_scheduled_ = false;
#if !BUILDFLAG(IS_ANDROID)
  for (Browser* browser : *BrowserList::GetInstance()) {
    if (browser->profile() != profile()) {
      continue;
    }
    if (IsPageActionMigrated(PageActionIconType::kFileSystemAccess)) {
      tabs::TabInterface* const tab_interface =
          browser->GetActiveTabInterface();
      // TODO(crbug.com/411109399): DoUsageIconUpdate() can be run during
      // browser destruction, and therefore we need to check for null here. This
      // should be updated to never run during browser destruction.
      if (!tab_interface) {
        continue;
      }
      auto* const tab_features = tab_interface->GetTabFeatures();
      CHECK(tab_features);
      UpdatePageAction(
          tab_features->file_system_access_page_action_controller());
    } else {
      browser->window()->UpdatePageActionIcon(
          PageActionIconType::kFileSystemAccess);
    }
  }
#endif
}

base::WeakPtr<ChromeFileSystemAccessPermissionContext>
ChromeFileSystemAccessPermissionContext::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

#if !BUILDFLAG(IS_ANDROID)
void ChromeFileSystemAccessPermissionContext::UpdatePageAction(
    FileSystemAccessPageActionController* controller) {
  CHECK(controller);
  controller->UpdateVisibility();
}
#endif