File: seccomp_broker_process_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (2891 lines) | stat: -rw-r--r-- 101,441 bytes parent folder | download | duplicates (6)
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
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include <errno.h>
#include <fcntl.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <memory>
#include <tuple>
#include <type_traits>
#include <vector>

#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_path_watcher.h"
#include "base/files/file_path_watcher_inotify.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/notreached.h"
#include "base/posix/eintr_wrapper.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
#include "sandbox/linux/bpf_dsl/policy.h"
#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
#include "sandbox/linux/seccomp-bpf/bpf_tests.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.h"
#include "sandbox/linux/syscall_broker/broker_client.h"
#include "sandbox/linux/syscall_broker/broker_command.h"
#include "sandbox/linux/syscall_broker/broker_file_permission.h"
#include "sandbox/linux/syscall_broker/broker_process.h"
#include "sandbox/linux/system_headers/linux_seccomp.h"
#include "sandbox/linux/system_headers/linux_stat.h"
#include "sandbox/linux/system_headers/linux_syscalls.h"
#include "sandbox/linux/tests/scoped_temporary_file.h"
#include "sandbox/linux/tests/test_utils.h"
#include "sandbox/linux/tests/unit_tests.h"
#include "testing/gtest/include/gtest/gtest-param-test.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace sandbox {

using bpf_dsl::Allow;
using bpf_dsl::Arg;
using bpf_dsl::Error;
using bpf_dsl::If;
using bpf_dsl::ResultExpr;
using bpf_dsl::Trap;

using BrokerProcess = syscall_broker::BrokerProcess;
using BrokerType = syscall_broker::BrokerProcess::BrokerType;
using BrokerCommandSet = syscall_broker::BrokerCommandSet;
using BrokerFilePermission = syscall_broker::BrokerFilePermission;

// Test a trap handler that makes use of a broker process to open().

class InitializedOpenBroker {
 public:
  explicit InitializedOpenBroker(
      BrokerType broker_type = BrokerType::SIGNAL_BASED) {
    syscall_broker::BrokerCommandSet command_set;
    command_set.set(syscall_broker::COMMAND_OPEN);
    command_set.set(syscall_broker::COMMAND_ACCESS);
    std::vector<BrokerFilePermission> permissions = {
        BrokerFilePermission::ReadOnly("/proc/allowed"),
        BrokerFilePermission::ReadOnly("/proc/cpuinfo")};
    broker_process_ = std::make_unique<BrokerProcess>(
        syscall_broker::BrokerSandboxConfig(command_set, permissions, EPERM),
        broker_type);
    BPF_ASSERT(broker_process_->Fork(base::BindOnce(
        [](const syscall_broker::BrokerSandboxConfig&) { return true; })));
  }

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

  BrokerProcess* broker_process() const { return broker_process_.get(); }

 private:
  std::unique_ptr<BrokerProcess> broker_process_;
};

intptr_t BrokerOpenTrapHandler(const struct arch_seccomp_data& args,
                               void* aux) {
  BPF_ASSERT(aux);
  BrokerProcess* broker_process = static_cast<BrokerProcess*>(aux);
  switch (args.nr) {
    case __NR_faccessat:  // access is a wrapper of faccessat in android
    case __NR_faccessat2:
      BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
      return broker_process->GetBrokerClientSignalBased()->Access(
          reinterpret_cast<const char*>(args.args[1]),
          static_cast<int>(args.args[2]));
#if defined(__NR_access)
    case __NR_access:
      return broker_process->GetBrokerClientSignalBased()->Access(
          reinterpret_cast<const char*>(args.args[0]),
          static_cast<int>(args.args[1]));
#endif
#if defined(__NR_open)
    case __NR_open:
      return broker_process->GetBrokerClientSignalBased()->Open(
          reinterpret_cast<const char*>(args.args[0]),
          static_cast<int>(args.args[1]));
#endif
    case __NR_openat:
      // We only call open() so if we arrive here, it's because glibc uses
      // the openat() system call.
      BPF_ASSERT(static_cast<int>(args.args[0]) == AT_FDCWD);
      return broker_process->GetBrokerClientSignalBased()->Open(
          reinterpret_cast<const char*>(args.args[1]),
          static_cast<int>(args.args[2]));
    default:
      BPF_ASSERT(false);
      return -ENOSYS;
  }
}

class DenyOpenPolicy : public bpf_dsl::Policy {
 public:
  explicit DenyOpenPolicy(InitializedOpenBroker* iob) : iob_(iob) {}

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

  ~DenyOpenPolicy() override {}

  ResultExpr EvaluateSyscall(int sysno) const override {
    DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));

    switch (sysno) {
      case __NR_faccessat:
      case __NR_faccessat2:
#if defined(__NR_access)
      case __NR_access:
#endif
#if defined(__NR_open)
      case __NR_open:
#endif
      case __NR_openat:
        // We get a InitializedOpenBroker class, but our trap handler wants
        // the BrokerProcess object.
        return Trap(BrokerOpenTrapHandler, iob_->broker_process());
      default:
        return Allow();
    }
  }

 private:
  raw_ptr<InitializedOpenBroker> iob_;
};

// We use a InitializedOpenBroker class, so that we can run unsandboxed
// code in its constructor, which is the only way to do so in a BPF_TEST.
BPF_TEST(SandboxBPF,
         UseOpenBroker,
         DenyOpenPolicy,
         InitializedOpenBroker /* (*BPF_AUX) */) {
  BrokerProcess* broker_process = BPF_AUX->broker_process();
  BPF_ASSERT(broker_process != nullptr);

  // First, use the broker "manually"
  BPF_ASSERT(broker_process->GetBrokerClientSignalBased()->Open(
                 "/proc/denied", O_RDONLY) == -EPERM);
  BPF_ASSERT(broker_process->GetBrokerClientSignalBased()->Access(
                 "/proc/denied", R_OK) == -EPERM);
  BPF_ASSERT(broker_process->GetBrokerClientSignalBased()->Open(
                 "/proc/allowed", O_RDONLY) == -ENOENT);
  BPF_ASSERT(broker_process->GetBrokerClientSignalBased()->Access(
                 "/proc/allowed", R_OK) == -ENOENT);

  // Now use glibc's open() as an external library would.
  BPF_ASSERT(open("/proc/denied", O_RDONLY) == -1);
  BPF_ASSERT(errno == EPERM);

  BPF_ASSERT(open("/proc/allowed", O_RDONLY) == -1);
  BPF_ASSERT(errno == ENOENT);

  // Also test glibc's openat(), some versions of libc use it transparently
  // instead of open().
  BPF_ASSERT(openat(AT_FDCWD, "/proc/denied", O_RDONLY) == -1);
  BPF_ASSERT(errno == EPERM);

  BPF_ASSERT(openat(AT_FDCWD, "/proc/allowed", O_RDONLY) == -1);
  BPF_ASSERT(errno == ENOENT);

  // And test glibc's access().
  BPF_ASSERT(access("/proc/denied", R_OK) == -1);
  BPF_ASSERT(errno == EPERM);

  BPF_ASSERT(access("/proc/allowed", R_OK) == -1);
  BPF_ASSERT(errno == ENOENT);

  // This is also white listed and does exist.
  int cpu_info_access = access("/proc/cpuinfo", R_OK);
  BPF_ASSERT(cpu_info_access == 0);
  int cpu_info_fd = open("/proc/cpuinfo", O_RDONLY);
  BPF_ASSERT(cpu_info_fd >= 0);
  char buf[1024];
  BPF_ASSERT(HANDLE_EINTR(read(cpu_info_fd, buf, sizeof(buf))) > 0);
}

// The rest of the tests do not run under thread sanitizer, as TSAN starts up an
// extra thread which triggers a sandbox assertion. BPF_TESTs do not run under
// TSAN.
#if !defined(THREAD_SANITIZER)

namespace {
// Our fake errno must be less than 255 or various libc implementations will
// not accept this as a valid error number. E.g. bionic accepts up to 255, glibc
// and musl up to 4096.
const int kFakeErrnoSentinel = 254;

void ConvertKernelStatToLibcStat(default_stat_struct& in_stat,
                                 struct stat& out_stat) {
  out_stat.st_dev = in_stat.st_dev;
  out_stat.st_ino = in_stat.st_ino;
  out_stat.st_mode = in_stat.st_mode;
  out_stat.st_nlink = in_stat.st_nlink;
  out_stat.st_uid = in_stat.st_uid;
  out_stat.st_gid = in_stat.st_gid;
  out_stat.st_rdev = in_stat.st_rdev;
  out_stat.st_size = in_stat.st_size;
  out_stat.st_blksize = in_stat.st_blksize;
  out_stat.st_blocks = in_stat.st_blocks;
  out_stat.st_atim.tv_sec = in_stat.st_atime_;
  out_stat.st_atim.tv_nsec = in_stat.st_atime_nsec_;
  out_stat.st_mtim.tv_sec = in_stat.st_mtime_;
  out_stat.st_mtim.tv_nsec = in_stat.st_mtime_nsec_;
  out_stat.st_ctim.tv_sec = in_stat.st_ctime_;
  out_stat.st_ctim.tv_nsec = in_stat.st_ctime_nsec_;
}
}  // namespace

// There are a variety of ways to make syscalls in a sandboxed process. One is
// to directly make the syscalls, one is to make the syscalls through libc
// (which oftens uses different underlying syscalls per platform and kernel
// version). With the signals-based broker, the sandboxed process can also make
// calls directly to the broker over the existing IPC channel.
// This interface encompasses the available syscalls so we can test every method
// of making syscalls.
class Syscaller {
 public:
  virtual ~Syscaller() = default;

  virtual int Open(const char* filepath, int flags) = 0;
  virtual int Access(const char* filepath, int mode) = 0;
  // NOTE: we use struct stat instead of default_stat_struct, to make the libc
  // syscaller simpler. Copying from default_stat_struct (the structure returned
  // from a stat sycall) to struct stat (the structure exposed by a libc to its
  // users) is simpler than going in the opposite direction.
  virtual int Stat(const char* filepath,
                   bool follow_links,
                   struct stat* statbuf) = 0;
  virtual int Rename(const char* oldpath, const char* newpath) = 0;
  virtual int Readlink(const char* path, char* buf, size_t bufsize) = 0;
  virtual int Mkdir(const char* pathname, mode_t mode) = 0;
  virtual int Rmdir(const char* path) = 0;
  virtual int Unlink(const char* path) = 0;
  virtual int InotifyAddWatch(int fd, const char* path, uint32_t mask) = 0;
};

class IPCSyscaller : public Syscaller {
 public:
  explicit IPCSyscaller(BrokerProcess* broker) : broker_(broker) {}
  ~IPCSyscaller() override = default;

  int Open(const char* filepath, int flags) override {
    return broker_->GetBrokerClientSignalBased()->Open(filepath, flags);
  }

  int Access(const char* filepath, int mode) override {
    return broker_->GetBrokerClientSignalBased()->Access(filepath, mode);
  }

  int Stat(const char* filepath,
           bool follow_links,
           struct stat* statbuf) override {
    default_stat_struct buf;
    int ret = broker_->GetBrokerClientSignalBased()->DefaultStatForTesting(
        filepath, follow_links, &buf);
    if (ret >= 0)
      ConvertKernelStatToLibcStat(buf, *statbuf);
    return ret;
  }

  int Rename(const char* oldpath, const char* newpath) override {
    return broker_->GetBrokerClientSignalBased()->Rename(oldpath, newpath);
  }

  int Readlink(const char* path, char* buf, size_t bufsize) override {
    return broker_->GetBrokerClientSignalBased()->Readlink(path, buf, bufsize);
  }

  int Mkdir(const char* pathname, mode_t mode) override {
    return broker_->GetBrokerClientSignalBased()->Mkdir(pathname, mode);
  }

  int Rmdir(const char* path) override {
    return broker_->GetBrokerClientSignalBased()->Rmdir(path);
  }

  int Unlink(const char* path) override {
    return broker_->GetBrokerClientSignalBased()->Unlink(path);
  }

  int InotifyAddWatch(int fd, const char* path, uint32_t mask) override {
    return broker_->GetBrokerClientSignalBased()->InotifyAddWatch(fd, path,
                                                                  mask);
  }

 private:
  raw_ptr<BrokerProcess> broker_;
};

// Only use syscall(...) on x64 to avoid having to reimplement a libc-like
// layer that uses different syscalls on different architectures.
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
     BUILDFLAG(IS_ANDROID)) &&                        \
    defined(__x86_64__)
#define DIRECT_SYSCALLER_ENABLED
#endif

#if defined(DIRECT_SYSCALLER_ENABLED)
class DirectSyscaller : public Syscaller {
 public:
  ~DirectSyscaller() override = default;

  int Open(const char* filepath, int flags) override {
    int ret = syscall(__NR_open, filepath, flags);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Access(const char* filepath, int mode) override {
    int ret = syscall(__NR_access, filepath, mode);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Stat(const char* filepath,
           bool follow_links,
           struct stat* statbuf) override {
    struct kernel_stat buf;
    int ret = syscall(__NR_newfstatat, AT_FDCWD, filepath, &buf,
                      follow_links ? 0 : AT_SYMLINK_NOFOLLOW);
    if (ret < 0)
      return -errno;

    ConvertKernelStatToLibcStat(buf, *statbuf);
    return ret;
  }

  int Rename(const char* oldpath, const char* newpath) override {
    int ret = syscall(__NR_rename, oldpath, newpath);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Readlink(const char* path, char* buf, size_t bufsize) override {
    int ret = syscall(__NR_readlink, path, buf, bufsize);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Mkdir(const char* pathname, mode_t mode) override {
    int ret = syscall(__NR_mkdir, pathname, mode);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Rmdir(const char* path) override {
    int ret = syscall(__NR_rmdir, path);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Unlink(const char* path) override {
    int ret = syscall(__NR_unlink, path);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int InotifyAddWatch(int fd, const char* path, uint32_t mask) override {
    int ret = syscall(__NR_inotify_add_watch, fd, path, mask);
    if (ret < 0)
      return -errno;
    return ret;
  }
};
#endif  // defined(DIRECT_SYSCALLER_ENABLED)

class LibcSyscaller : public Syscaller {
 public:
  ~LibcSyscaller() override = default;

  int Open(const char* filepath, int flags) override {
    int ret = HANDLE_EINTR(open(filepath, flags, 0600));
    if (ret < 0)
      return -errno;
    return ret;
  }
  int Access(const char* filepath, int mode) override {
    int ret = access(filepath, mode);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Stat(const char* filepath,
           bool follow_links,
           struct stat* statbuf) override {
    int ret = follow_links ? stat(filepath, statbuf) : lstat(filepath, statbuf);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Rename(const char* oldpath, const char* newpath) override {
    int ret = rename(oldpath, newpath);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Readlink(const char* path, char* buf, size_t bufsize) override {
    int ret = readlink(path, buf, bufsize);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Mkdir(const char* pathname, mode_t mode) override {
    int ret = mkdir(pathname, mode);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Rmdir(const char* path) override {
    int ret = rmdir(path);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int Unlink(const char* path) override {
    int ret = unlink(path);
    if (ret < 0)
      return -errno;
    return ret;
  }

  int InotifyAddWatch(int fd, const char* path, uint32_t mask) override {
    int ret = inotify_add_watch(fd, path, mask);
    if (ret < 0)
      return -errno;
    return ret;
  }
};

enum class SyscallerType {
  IPCSyscaller = 0,
  DirectSyscaller,
  LibcSyscaller,
  NoSyscaller
};

// The testing infrastructure for the broker integration tests is built on the
// same infrastructure that BPF_TEST or SANDBOX_TEST uses. Each individual test
// starts up a child process, which itself starts up a broker process and
// sandboxes itself. To create a test, implement this delegate and call
// RunAllBrokerTests() in a TEST(). The bulk of the test body will be in
// RunTestInSandboxedChild().
class BrokerTestDelegate {
 public:
  struct BrokerParams {
    int denied_errno = kFakeErrnoSentinel;
    syscall_broker::BrokerCommandSet allowed_command_set;
    std::vector<BrokerFilePermission> permissions;
  };

  virtual ~BrokerTestDelegate() = default;

  // Called in the parent test process before starting the child process. Should
  // use GTEST's ASSERT macros.
  virtual void ParentSetUp() {}

  // Sets up the test in the child process before applying the sandbox.
  // |allowed_command_set| and |permissions| should be filled in with the
  // desired commands and permissions the broker should allow. Should use
  // BPF_ASSERT.
  virtual BrokerParams ChildSetUpPreSandbox() = 0;

  // Gets called in the sandboxed process with the pid of the newly started
  // broker.
  virtual void OnBrokerStarted(pid_t broker_pid) {}

  // Runs the test after setting up the sandbox in the forked process.
  // Assertions should use BPF_ASSERT.
  virtual void RunTestInSandboxedChild(Syscaller* syscaller) = 0;

  // Called in the parent test process after the child dies. Should perform
  // cleanup, and can also ASSERT like a normal GTEST. Note that modifications
  // of class state in the above two functions will not be visible here, as they
  // ran in the forked child.
  virtual void ParentTearDown() {
    ASSERT_FALSE(TestUtils::CurrentProcessHasChildren());
  }
};

namespace syscall_broker {
// A BPF policy for our BPF_TEST that defers to the broker for syscalls that
// take paths, and allows everything else.
class HandleFilesystemViaBrokerPolicy : public bpf_dsl::Policy {
 public:
  explicit HandleFilesystemViaBrokerPolicy(BrokerProcess* broker_process,
                                           int denied_errno)
      : broker_process_(broker_process), denied_errno_(denied_errno) {}

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

  ~HandleFilesystemViaBrokerPolicy() override = default;

  ResultExpr EvaluateSyscall(int sysno) const override {
    DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
    // Broker everything that we're supposed to broker.
    if (broker_process_->IsSyscallAllowed(sysno)) {
      return Trap(BrokerClient::SIGSYS_Handler,
                  broker_process_->GetBrokerClientSignalBased());
    }

    // Otherwise, if this is a syscall that takes a pathname but isn't an
    // allowed command, deny it.
    if (broker_process_->IsSyscallBrokerable(sysno,
                                             /*fast_check_in_client=*/false)) {
      return Error(denied_errno_);
    }

    if (sysno == __NR_statx) {
      const Arg<int> mask(3);
      return If(mask == STATX_BASIC_STATS, Error(ENOSYS))
          .Else(Error(denied_errno_));
    }

    // Allow everything else that doesn't take a pathname.
    return Allow();
  }

 private:
  raw_ptr<BrokerProcess> broker_process_;
  int denied_errno_;
};
}  // namespace syscall_broker

// This implements BPFTesterDelegate to layer the broker integration tests on
// top of BPF_TEST infrastructure.
class BPFTesterBrokerDelegate : public BPFTesterDelegate {
 public:
  explicit BPFTesterBrokerDelegate(bool fast_check_in_client,
                                   BrokerTestDelegate* broker_test_delegate,
                                   SyscallerType syscaller_type,
                                   BrokerType broker_type)
      : fast_check_in_client_(fast_check_in_client),
        broker_test_delegate_(broker_test_delegate),
        syscaller_type_(syscaller_type),
        broker_type_(broker_type) {}
  ~BPFTesterBrokerDelegate() override = default;

  std::unique_ptr<bpf_dsl::Policy> GetSandboxBPFPolicy() override {
    BrokerTestDelegate::BrokerParams broker_params =
        broker_test_delegate_->ChildSetUpPreSandbox();

    auto policy = std::make_optional<syscall_broker::BrokerSandboxConfig>(
        broker_params.allowed_command_set, broker_params.permissions,
        broker_params.denied_errno);
    broker_process_ = std::make_unique<BrokerProcess>(
        std::move(policy), broker_type_, fast_check_in_client_);
    BPF_ASSERT(broker_process_->Fork(base::BindOnce(
        [](const syscall_broker::BrokerSandboxConfig&) { return true; })));
    broker_test_delegate_->OnBrokerStarted(broker_process_->broker_pid());

    BPF_ASSERT(TestUtils::CurrentProcessHasChildren());

    CreateSyscaller();

    return std::unique_ptr<bpf_dsl::Policy>(
        new syscall_broker::HandleFilesystemViaBrokerPolicy(
            broker_process_.get(), broker_params.denied_errno));
  }

  void RunTestFunction() override {
    broker_test_delegate_->RunTestInSandboxedChild(syscaller_.get());
  }

  void CreateSyscaller() {
    BPF_ASSERT(broker_process_->GetBrokerClientSignalBased());
    switch (syscaller_type_) {
      case SyscallerType::IPCSyscaller:
        syscaller_ = std::make_unique<IPCSyscaller>(broker_process_.get());
        break;
      case SyscallerType::DirectSyscaller:
#if defined(DIRECT_SYSCALLER_ENABLED)
        syscaller_ = std::make_unique<DirectSyscaller>();
        break;
#else
        NOTREACHED() << "Requested instantiation of DirectSyscaller on a "
                        "platform that doesn't support it";
#endif
      case SyscallerType::LibcSyscaller:
        syscaller_ = std::make_unique<LibcSyscaller>();
        break;
      case SyscallerType::NoSyscaller:
        syscaller_ = nullptr;
        break;
    }
  }

 private:
  bool fast_check_in_client_;
  raw_ptr<BrokerTestDelegate> broker_test_delegate_;
  SyscallerType syscaller_type_;
  BrokerType broker_type_;

  std::unique_ptr<BrokerProcess> broker_process_;
  std::unique_ptr<Syscaller> syscaller_;
};

namespace {
struct BrokerTestConfiguration {
  std::string test_name;
  bool fast_check_in_client;
  SyscallerType syscaller_type;
  BrokerType broker_type;
};

// Lists out all the broker configurations we want to test.
const std::vector<BrokerTestConfiguration> broker_test_configs = {
    {"FastCheckInClient_IPCSyscaller", true, SyscallerType::IPCSyscaller,
     BrokerType::SIGNAL_BASED},
#if defined(DIRECT_SYSCALLER_ENABLED)
    {"FastCheckInClient_DirectSyscaller", true, SyscallerType::DirectSyscaller,
     BrokerType::SIGNAL_BASED},
#endif
    {"FastCheckInClient_LibcSyscaller", true, SyscallerType::LibcSyscaller,
     BrokerType::SIGNAL_BASED},
    {"NoFastCheckInClient_IPCSyscaller", false, SyscallerType::IPCSyscaller,
     BrokerType::SIGNAL_BASED},
#if defined(DIRECT_SYSCALLER_ENABLED)
    {"NoFastCheckInClient_DirectSyscaller", false,
     SyscallerType::DirectSyscaller, BrokerType::SIGNAL_BASED},
#endif
    {"NoFastCheckInClient_LibcSyscaller", false, SyscallerType::LibcSyscaller,
     BrokerType::SIGNAL_BASED}};
}  // namespace

void RunSingleBrokerTest(BrokerTestDelegate* test_delegate,
                         const BrokerTestConfiguration& test_config) {
  test_delegate->ParentSetUp();
  sandbox::SandboxBPFTestRunner bpf_test_runner(new BPFTesterBrokerDelegate(
      test_config.fast_check_in_client, test_delegate,
      test_config.syscaller_type, test_config.broker_type));
  sandbox::UnitTests::RunTestInProcess(&bpf_test_runner, DEATH_SUCCESS());
  test_delegate->ParentTearDown();
}

template <typename T>
void RunAllBrokerTests() {
  for (const BrokerTestConfiguration& test_config : broker_test_configs) {
    SCOPED_TRACE(test_config.test_name);
    auto test_delegate = std::make_unique<T>();
    RunSingleBrokerTest(test_delegate.get(), test_config);
  }
}

template <typename T>
void RunIPCBrokerTests() {
  for (const BrokerTestConfiguration& test_config : broker_test_configs) {
    if (test_config.syscaller_type != SyscallerType::IPCSyscaller)
      continue;

    SCOPED_TRACE(test_config.test_name);
    auto test_delegate = std::make_unique<T>();
    RunSingleBrokerTest(test_delegate.get(), test_config);
  }
}

// Tests that a SIGNALS_BASED broker responds with -EFAULT when open() or
// access() are called with nullptr.
class TestOpenAccessNullDelegate final : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    int fd = syscaller->Open(nullptr, O_RDONLY);
    BPF_ASSERT_EQ(fd, -EFAULT);

    int ret = syscaller->Access(nullptr, F_OK);
    BPF_ASSERT_EQ(ret, -EFAULT);
  }
};

TEST(BrokerProcessIntegrationTest, TestOpenAccessNull) {
  RunIPCBrokerTests<TestOpenAccessNullDelegate>();
}

// Tests open()/access() for files that do not exist, are not allowed by
// allowlist, and are allowed by allowlist but not accessible.
template <int DENIED_ERRNO>
class TestOpenFilePermsDelegate final : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.denied_errno = DENIED_ERRNO;

    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});

    params.permissions = {
        BrokerFilePermission::ReadOnly(kR_AllowListed),
        BrokerFilePermission::ReadOnly(kR_AllowListedButDenied),
        BrokerFilePermission::WriteOnly(kW_AllowListed),
        BrokerFilePermission::ReadWrite(kRW_AllowListed)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    int fd = -1;
    fd = syscaller->Open(kR_AllowListed, O_RDONLY);
    BPF_ASSERT_EQ(fd, -ENOENT);
    fd = syscaller->Open(kR_AllowListed, O_WRONLY);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
    fd = syscaller->Open(kR_AllowListed, O_RDWR);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
    int ret = -1;
    ret = syscaller->Access(kR_AllowListed, F_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kR_AllowListed, R_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kR_AllowListed, W_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(kR_AllowListed, R_OK | W_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(kR_AllowListed, X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(kR_AllowListed, R_OK | X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);

    // Android sometimes runs tests as root.
    // This part of the test requires a process that doesn't have
    // CAP_DAC_OVERRIDE. We check against a root euid as a proxy for that.
    if (geteuid()) {
      fd = syscaller->Open(kR_AllowListedButDenied, O_RDONLY);
      // The broker process will allow this, but the normal permission system
      // won't.
      BPF_ASSERT_EQ(fd, -EACCES);
      fd = syscaller->Open(kR_AllowListedButDenied, O_WRONLY);
      BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
      fd = syscaller->Open(kR_AllowListedButDenied, O_RDWR);
      BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
      ret = syscaller->Access(kR_AllowListedButDenied, F_OK);
      // The normal permission system will let us check that the file exists.
      BPF_ASSERT_EQ(ret, 0);
      ret = syscaller->Access(kR_AllowListedButDenied, R_OK);
      BPF_ASSERT_EQ(ret, -EACCES);
      ret = syscaller->Access(kR_AllowListedButDenied, W_OK);
      BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
      ret = syscaller->Access(kR_AllowListedButDenied, R_OK | W_OK);
      BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
      ret = syscaller->Access(kR_AllowListedButDenied, X_OK);
      BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
      ret = syscaller->Access(kR_AllowListedButDenied, R_OK | X_OK);
      BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    }

    fd = syscaller->Open(kW_AllowListed, O_RDONLY);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
    fd = syscaller->Open(kW_AllowListed, O_WRONLY);
    BPF_ASSERT_EQ(fd, -ENOENT);
    fd = syscaller->Open(kW_AllowListed, O_RDWR);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
    ret = syscaller->Access(kW_AllowListed, F_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kW_AllowListed, R_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(kW_AllowListed, W_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kW_AllowListed, R_OK | W_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(kW_AllowListed, X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(kW_AllowListed, R_OK | X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);

    fd = syscaller->Open(kRW_AllowListed, O_RDONLY);
    BPF_ASSERT_EQ(fd, -ENOENT);
    fd = syscaller->Open(kRW_AllowListed, O_WRONLY);
    BPF_ASSERT_EQ(fd, -ENOENT);
    fd = syscaller->Open(kRW_AllowListed, O_RDWR);
    BPF_ASSERT_EQ(fd, -ENOENT);
    ret = syscaller->Access(kRW_AllowListed, F_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kRW_AllowListed, R_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kRW_AllowListed, W_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kRW_AllowListed, R_OK | W_OK);
    BPF_ASSERT_EQ(ret, -ENOENT);
    ret = syscaller->Access(kRW_AllowListed, X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(kRW_AllowListed, R_OK | X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);

    fd = syscaller->Open(k_NotAllowlisted, O_RDONLY);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
    fd = syscaller->Open(k_NotAllowlisted, O_WRONLY);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
    fd = syscaller->Open(k_NotAllowlisted, O_RDWR);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
    ret = syscaller->Access(k_NotAllowlisted, F_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(k_NotAllowlisted, R_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(k_NotAllowlisted, W_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(k_NotAllowlisted, R_OK | W_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(k_NotAllowlisted, X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);
    ret = syscaller->Access(k_NotAllowlisted, R_OK | X_OK);
    BPF_ASSERT_EQ(ret, -DENIED_ERRNO);

    // We have some extra sanity check for clearly wrong values.
    fd = syscaller->Open(kRW_AllowListed, O_RDONLY | O_WRONLY | O_RDWR);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);

    // It makes no sense to allow O_CREAT in a 2-parameters open. Ensure this
    // is denied.
    fd = syscaller->Open(kRW_AllowListed, O_RDWR | O_CREAT);
    BPF_ASSERT_EQ(fd, -DENIED_ERRNO);
  }

 private:
  const char* const kR_AllowListed = "/proc/DOESNOTEXIST1";
  // We can't debug the init process, and shouldn't be able to access
  // its auxv file.
  const char* kR_AllowListedButDenied = "/proc/1/auxv";
  const char* kW_AllowListed = "/proc/DOESNOTEXIST2";
  const char* kRW_AllowListed = "/proc/DOESNOTEXIST3";
  const char* k_NotAllowlisted = "/proc/DOESNOTEXIST4";
};

TEST(BrokerProcessIntegrationTest, TestOpenFilePermsEPERM) {
  RunAllBrokerTests<TestOpenFilePermsDelegate<EPERM>>();
}

TEST(BrokerProcessIntegrationTest, TestOpenFilePermsENOENT) {
  RunAllBrokerTests<TestOpenFilePermsDelegate<ENOENT>>();
}

class BadPathsDelegate final : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    params.permissions = {BrokerFilePermission::ReadOnlyRecursive("/proc/")};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    // Open cpuinfo via the broker.
    int cpuinfo_fd = syscaller->Open(kFileCpuInfo, O_RDONLY);
    base::ScopedFD cpuinfo_fd_closer(cpuinfo_fd);
    BPF_ASSERT_GE(cpuinfo_fd, 0);

    int fd = -1;
    int can_access;

    can_access = syscaller->Access(kNotAbsPath, R_OK);
    BPF_ASSERT_EQ(can_access, -kFakeErrnoSentinel);
    fd = syscaller->Open(kNotAbsPath, O_RDONLY);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);

    can_access = syscaller->Access(kDotDotStart, R_OK);
    BPF_ASSERT_EQ(can_access, -kFakeErrnoSentinel);
    fd = syscaller->Open(kDotDotStart, O_RDONLY);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);

    can_access = syscaller->Access(kDotDotMiddle, R_OK);
    BPF_ASSERT_EQ(can_access, -kFakeErrnoSentinel);
    fd = syscaller->Open(kDotDotMiddle, O_RDONLY);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);

    can_access = syscaller->Access(kDotDotEnd, R_OK);
    BPF_ASSERT_EQ(can_access, -kFakeErrnoSentinel);
    fd = syscaller->Open(kDotDotEnd, O_RDONLY);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);

    can_access = syscaller->Access(kTrailingSlash, R_OK);
    BPF_ASSERT_EQ(can_access, -kFakeErrnoSentinel);
    fd = syscaller->Open(kTrailingSlash, O_RDONLY);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);
  }

 private:
  const char* const kFileCpuInfo = "/proc/cpuinfo";
  const char* const kNotAbsPath = "proc/cpuinfo";
  const char* const kDotDotStart = "/../proc/cpuinfo";
  const char* const kDotDotMiddle = "/proc/self/../cpuinfo";
  const char* const kDotDotEnd = "/proc/..";
  const char* const kTrailingSlash = "/proc/";
};

TEST(BrokerProcessIntegrationTest, BadPaths) {
  RunAllBrokerTests<BadPathsDelegate>();
}

template <bool recursive>
class OpenCpuinfoDelegate final : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    // Open cpuinfo directly.
    int cpu_info_fd = HANDLE_EINTR(open(kFileCpuInfo, O_RDONLY));
    BPF_ASSERT_GE(cpu_info_fd, 0);
    memset(cpuinfo_buf_, 1, sizeof(cpuinfo_buf_));
    read_len_unsandboxed_ =
        HANDLE_EINTR(read(cpu_info_fd, cpuinfo_buf_, sizeof(cpuinfo_buf_)));
    BPF_ASSERT_GT(read_len_unsandboxed_, 0);

    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    params.permissions.push_back(
        recursive ? BrokerFilePermission::ReadOnlyRecursive(kDirProc)
                  : BrokerFilePermission::ReadOnly(kFileCpuInfo));
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    int fd = syscaller->Open(kFileCpuInfo, O_RDWR);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);

    // Check we can read /proc/cpuinfo.
    int can_access = syscaller->Access(kFileCpuInfo, R_OK);
    BPF_ASSERT_EQ(can_access, 0);
    can_access = syscaller->Access(kFileCpuInfo, W_OK);
    BPF_ASSERT_EQ(can_access, -kFakeErrnoSentinel);
    // Check we can not write /proc/cpuinfo.

    // Open cpuinfo via the broker.
    int cpuinfo_fd = syscaller->Open(kFileCpuInfo, O_RDONLY);
    base::ScopedFD cpuinfo_fd_closer(cpuinfo_fd);
    BPF_ASSERT_GE(cpuinfo_fd, 0);
    char buf[3];
    memset(buf, 0, sizeof(buf));
    int read_len_sandboxed = HANDLE_EINTR(read(cpuinfo_fd, buf, sizeof(buf)));
    BPF_ASSERT_GT(read_len_sandboxed, 0);

    // The following is not guaranteed true, but will be in practice.
    BPF_ASSERT_EQ(read_len_sandboxed, read_len_unsandboxed_);
    // Compare the cpuinfo as returned by the broker with the one we opened
    // ourselves.
    BPF_ASSERT_EQ(memcmp(buf, cpuinfo_buf_, read_len_sandboxed), 0);
  }

 private:
  const char* const kFileCpuInfo = "/proc/cpuinfo";
  const char* const kDirProc = "/proc/";

  int read_len_unsandboxed_ = -1;
  char cpuinfo_buf_[3];
};

TEST(BrokerProcessIntegrationTest, OpenCpuinfoRecursive) {
  RunAllBrokerTests<OpenCpuinfoDelegate</*recursive=*/true>>();
}

TEST(BrokerProcessIntegrationTest, OpenCpuinfoNonRecursive) {
  RunAllBrokerTests<OpenCpuinfoDelegate</*recursive=*/false>>();
}

class OpenFileRWDelegate final : public BrokerTestDelegate {
 public:
  OpenFileRWDelegate() : tempfile_name_(tempfile.full_file_name()) {}

  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    params.permissions = {BrokerFilePermission::ReadWrite(tempfile_name_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    // Check we can access that file with read or write.
    int can_access = syscaller->Access(tempfile_name_, R_OK | W_OK);
    BPF_ASSERT_EQ(can_access, 0);

    int tempfile2 = -1;
    tempfile2 = syscaller->Open(tempfile_name_, O_RDWR);
    BPF_ASSERT_GE(tempfile2, 0);

    // Write to the descriptor opened by the broker.
    char test_text[] = "TESTTESTTEST";

    ssize_t len = HANDLE_EINTR(write(tempfile2, test_text, sizeof(test_text)));
    BPF_ASSERT_EQ(len, static_cast<ssize_t>(sizeof(test_text)));

    // Read back from the original file descriptor what we wrote through
    // the descriptor provided by the broker.
    char buf[1024];
    len = HANDLE_EINTR(read(tempfile.fd(), buf, sizeof(buf)));

    BPF_ASSERT_EQ(len, static_cast<ssize_t>(sizeof(test_text)));
    BPF_ASSERT_EQ(memcmp(test_text, buf, sizeof(test_text)), 0);

    BPF_ASSERT_EQ(close(tempfile2), 0);
  }

 private:
  ScopedTemporaryFile tempfile;
  const char* const tempfile_name_;
};

TEST(BrokerProcessIntegrationTest, OpenFileRW) {
  RunAllBrokerTests<OpenFileRWDelegate>();
}

class BrokerDiedDelegate final : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    params.permissions = {BrokerFilePermission::ReadOnly(kCpuInfo)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_GT(broker_pid_, 0);

    // Kill our own broker and check that we get ENOSYS or ENOMEM for our
    // syscalls.
    BPF_ASSERT_EQ(kill(broker_pid_, SIGKILL), 0);

    int ret = syscaller->Access(kCpuInfo, O_RDONLY);
    BPF_ASSERT(ret == -ENOSYS || ret == -ENOMEM);

    ret = syscaller->Open(kCpuInfo, O_RDONLY);
    BPF_ASSERT(ret == -ENOSYS || ret == -ENOMEM);
  }

  void OnBrokerStarted(pid_t pid) override { broker_pid_ = pid; }

 private:
  const char* const kCpuInfo = "/proc/cpuinfo";

  pid_t broker_pid_ = -1;
};

TEST(BrokerProcessIntegrationTest, BrokerDied) {
  RunAllBrokerTests<BrokerDiedDelegate>();
}

class OpenComplexFlagsDelegate final : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    params.permissions = {BrokerFilePermission::ReadOnly(kCpuInfo)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    // Tests that files opened without O_CLOEXEC (resp. O_NONBLOCK) do not have
    // O_CLOEXEC (resp. O_NONBLOCK) on their file description, and vice versa.
    int fd = -1;
    int ret = 0;
    fd = syscaller->Open(kCpuInfo, O_RDONLY);
    BPF_ASSERT_GE(fd, 0);
    ret = fcntl(fd, F_GETFL);
    BPF_ASSERT_NE(-1, ret);
    // The description shouldn't have the O_CLOEXEC attribute, nor O_NONBLOCK.
    BPF_ASSERT_EQ(0, ret & (O_CLOEXEC | O_NONBLOCK));
    ret = fcntl(fd, F_GETFD);
    BPF_ASSERT_NE(-1, ret);
    // The descriptor also should not have FD_CLOEXEC.
    BPF_ASSERT_EQ(FD_CLOEXEC & ret, 0);
    BPF_ASSERT_EQ(0, close(fd));

    fd = syscaller->Open(kCpuInfo, O_RDONLY | O_CLOEXEC);
    BPF_ASSERT_GE(fd, 0);
    ret = fcntl(fd, F_GETFD);
    BPF_ASSERT_NE(-1, ret);
    // Important: use F_GETFD, not F_GETFL. The O_CLOEXEC flag in F_GETFL
    // is actually not used by the kernel.
    BPF_ASSERT(FD_CLOEXEC & ret);
    BPF_ASSERT_EQ(0, close(fd));

    fd = syscaller->Open(kCpuInfo, O_RDONLY | O_NONBLOCK);
    BPF_ASSERT_GE(fd, 0);
    ret = fcntl(fd, F_GETFL);
    BPF_ASSERT_NE(-1, ret);
    BPF_ASSERT(O_NONBLOCK & ret);
    BPF_ASSERT_EQ(0, close(fd));
  }

 private:
  const char* const kCpuInfo = "/proc/cpuinfo";
};

TEST(BrokerProcessIntegrationTest, OpenComplexFlags) {
  RunAllBrokerTests<OpenComplexFlagsDelegate>();
}

class RewriteProcSelfDelegate final : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    pre_sandbox_status_fd_.reset(HANDLE_EINTR(open(kProcSelfStatus, O_RDONLY)));
    BPF_ASSERT(pre_sandbox_status_fd_.is_valid());

    struct stat sb;
    BPF_ASSERT_GE(fstat(pre_sandbox_status_fd_.get(), &sb), 0);
    pre_sandbox_status_ino_ = sb.st_ino;

    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    params.permissions.push_back(
        BrokerFilePermission::ReadOnly(kProcSelfStatus));
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    base::ScopedFD status_fd(syscaller->Open(kProcSelfStatus, O_RDONLY));
    BPF_ASSERT(status_fd.is_valid());

    // The fd opened by the broker should have the same inode number as the fd
    // opened in this process pre-sandbox.
    struct stat sb;
    BPF_ASSERT_GE(fstat(status_fd.get(), &sb), 0);
    BPF_ASSERT_EQ(pre_sandbox_status_ino_, sb.st_ino);
  }

 private:
  static constexpr char kProcSelfStatus[] = "/proc/self/status";

  ino_t pre_sandbox_status_ino_ = 0;
  base::ScopedFD pre_sandbox_status_fd_;
};

TEST(BrokerProcessIntegrationTest, RewriteProcSelf) {
  RunAllBrokerTests<RewriteProcSelfDelegate>();
}

class CreateFileDelegate final : public BrokerTestDelegate {
 public:
  void ParentSetUp() override {
    // Create two temporary files and delete them, but store their file paths
    // for later usage.
    ScopedTemporaryFile temp_file;
    ScopedTemporaryFile perm_file;
    temp_str_ = temp_file.full_file_name();
    perm_str_ = perm_file.full_file_name();
    tempfile_name_ = temp_str_.c_str();
    permfile_name_ = perm_str_.c_str();

    {
      ScopedTemporaryFile tempfile;
      existing_temp_file_str_ = tempfile.full_file_name();
    }
    // Create a conflict for the temp filename.
    base::ScopedFD fd(
        open(existing_temp_file_str_.c_str(), O_RDWR | O_CREAT, 0600));
    ASSERT_GE(fd.get(), 0);
  }

  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_ACCESS, syscall_broker::COMMAND_OPEN});
    // Note that "temporariness" is determined by the permissions given below.
    params.permissions = {
        BrokerFilePermission::ReadWriteCreateTemporary(existing_temp_file_str_),
        BrokerFilePermission::ReadWriteCreateTemporary(tempfile_name_),
        BrokerFilePermission::ReadWriteCreate(permfile_name_),
    };
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    int fd = -1;

    // Opening a temp file using O_CREAT but not O_EXCL must not be allowed
    // by the broker so as to prevent spying on any pre-existing files.
    fd = syscaller->Open(tempfile_name_, O_RDWR | O_CREAT);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);

    // Opening a temp file in a normal way must not be allowed by the broker,
    // either.
    fd = syscaller->Open(tempfile_name_, O_RDWR);
    BPF_ASSERT_EQ(fd, -kFakeErrnoSentinel);

    // Opening a temp file with both O_CREAT and O_EXCL is allowed since the
    // file is known not to exist outside the scope of ScopedTemporaryFile.
    fd = syscaller->Open(tempfile_name_, O_RDWR | O_CREAT | O_EXCL);
    BPF_ASSERT_GE(fd, 0);
    close(fd);

    // Opening a temp file with both O_CREAT and O_EXCL is allowed but fails
    // per the OS when there is a conflict with a pre-existing file.
    fd = syscaller->Open(existing_temp_file_str_.c_str(),
                         O_RDWR | O_CREAT | O_EXCL);
    BPF_ASSERT_EQ(fd, -EEXIST);

    // Opening a new permanent file without specifying O_EXCL is allowed.
    fd = syscaller->Open(permfile_name_, O_RDWR | O_CREAT);
    BPF_ASSERT_GE(fd, 0);
    close(fd);

    // Opening an existing permanent file without specifying O_EXCL is allowed.
    fd = syscaller->Open(permfile_name_, O_RDWR | O_CREAT);
    BPF_ASSERT_GE(fd, 0);
    close(fd);

    // Opening an existing file with O_EXCL is allowed but fails per the OS.
    fd = syscaller->Open(permfile_name_, O_RDWR | O_CREAT | O_EXCL);
    BPF_ASSERT_EQ(fd, -EEXIST);

    const char kTestText[] = "TESTTESTTEST";

    fd = syscaller->Open(permfile_name_, O_RDWR);
    BPF_ASSERT_GE(fd, 0);
    {
      // Write to the descriptor opened by the broker and close.
      base::ScopedFD scoped_fd(fd);
      ssize_t len = HANDLE_EINTR(write(fd, kTestText, sizeof(kTestText)));
      BPF_ASSERT_EQ(len, static_cast<ssize_t>(sizeof(kTestText)));
    }

    int fd_check = open(permfile_name_, O_RDONLY);
    BPF_ASSERT_GE(fd_check, 0);
    {
      base::ScopedFD scoped_fd(fd_check);
      char buf[1024];
      ssize_t len = HANDLE_EINTR(read(fd_check, buf, sizeof(buf)));
      BPF_ASSERT_EQ(len, static_cast<ssize_t>(sizeof(kTestText)));
      BPF_ASSERT_EQ(memcmp(kTestText, buf, sizeof(kTestText)), 0);
    }
  }

  void ParentTearDown() override {
    // Cleanup.
    unlink(existing_temp_file_str_.c_str());
    unlink(tempfile_name_);
    unlink(permfile_name_);
    BrokerTestDelegate::ParentTearDown();
  }

 private:
  std::string existing_temp_file_str_;
  std::string temp_str_;
  std::string perm_str_;
  const char* tempfile_name_;
  const char* permfile_name_;
};

TEST(BrokerProcessIntegrationTest, CreateFile) {
  RunAllBrokerTests<CreateFileDelegate>();
}

// StatFileDelegate is the base class for all the Stat() tests.
class StatFileDelegate : public BrokerTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BPF_ASSERT_EQ(12, HANDLE_EINTR(write(tmp_file_.fd(), "blahblahblah", 12)));
    memset(&sb_, 0, sizeof(sb_));
    return BrokerParams();
  }

 protected:
  ScopedTemporaryFile tmp_file_;

  std::string temp_str_ = tmp_file_.full_file_name();
  const char* const tempfile_name_ = temp_str_.c_str();

  const char* const nonesuch_name = "/mbogo/fictitious/nonesuch";
  const char* const leading_path1 = "/mbogo/fictitious";
  const char* const leading_path2 = "/mbogo";
  const char* const leading_path3 = "/";
  const char* const bad_leading_path1 = "/mbog";
  const char* const bad_leading_path2 = "/mboga";
  const char* const bad_leading_path3 = "/mbogos";
  const char* const bad_leading_path4 = "/mbogo/fictitiou";
  const char* const bad_leading_path5 = "/mbogo/fictitioux";
  const char* const bad_leading_path6 = "/mbogo/fictitiousa";

  struct stat sb_;
};

// Actual file with permissions to see file but command not allowed.
template <bool follow_links>
class StatFileNoCommandDelegate final : public StatFileDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params = StatFileDelegate::ChildSetUpPreSandbox();
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet({});
    params.permissions = {BrokerFilePermission::ReadOnly(tempfile_name_)};
    return params;
  }
  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    int ret = syscaller->Stat(tempfile_name_, follow_links, &sb_);
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, ret);
  }
};

TEST(BrokerProcessIntegrationTest, StatFileNoCommandFollowLinks) {
  RunAllBrokerTests<StatFileNoCommandDelegate</*follow_links=*/true>>();
}

TEST(BrokerProcessIntegrationTest, StatFileNoCommandNoFollowLinks) {
  RunAllBrokerTests<StatFileNoCommandDelegate</*follow_links=*/false>>();
}

// Allows the STAT command without any file permissions.
template <bool follow_links>
class StatFilesNoPermissionDelegate final : public StatFileDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params = StatFileDelegate::ChildSetUpPreSandbox();
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_STAT});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    // Nonexistent file with no permissions to see file.
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(nonesuch_name, follow_links, &sb_));
    // Actual file with no permission to see file.
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(tempfile_name_, follow_links, &sb_));
  }
};

TEST(BrokerProcessIntegrationTest, StatFilesNoPermissionFollowLinks) {
  RunAllBrokerTests<StatFilesNoPermissionDelegate</*follow_links=*/true>>();
}

TEST(BrokerProcessIntegrationTest, StatFilesNoPermissionNoFollowLinks) {
  RunAllBrokerTests<StatFilesNoPermissionDelegate</*follow_links=*/false>>();
}

// Nonexistent file with permissions to see file.
template <bool follow_links>
class StatNonexistentFileWithPermissionsDelegate final
    : public StatFileDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params = StatFileDelegate::ChildSetUpPreSandbox();
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_STAT});
    params.permissions = {BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-ENOENT, syscaller->Stat(nonesuch_name, follow_links, &sb_));

    // Gets denied all the way back to root since no create permission.
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(leading_path1, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(leading_path2, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(leading_path3, follow_links, &sb_));

    // Not fooled by substrings.
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path1, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path2, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path3, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path4, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path5, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path6, follow_links, &sb_));
  }
};

TEST(BrokerProcessIntegrationTest,
     StatNonexistentFileWithPermissionsFollowLinks) {
  RunAllBrokerTests<
      StatNonexistentFileWithPermissionsDelegate</*follow_links=*/true>>();
}

TEST(BrokerProcessIntegrationTest,
     StatNonexistentFileWithPermissionsNoFollowLinks) {
  RunAllBrokerTests<
      StatNonexistentFileWithPermissionsDelegate</*follow_links=*/false>>();
}

// Nonexistent file with permissions to create file.
template <bool follow_links>
class StatNonexistentFileWithCreatePermissionsDelegate final
    : public StatFileDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params = StatFileDelegate::ChildSetUpPreSandbox();
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_STAT});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-ENOENT, syscaller->Stat(nonesuch_name, follow_links, &sb_));

    // Gets ENOENT all the way back to root since it has create permission.
    BPF_ASSERT_EQ(-ENOENT, syscaller->Stat(leading_path1, follow_links, &sb_));
    BPF_ASSERT_EQ(-ENOENT, syscaller->Stat(leading_path2, follow_links, &sb_));

    // But can always get the root.
    BPF_ASSERT_EQ(0, syscaller->Stat(leading_path3, follow_links, &sb_));

    // Not fooled by substrings.
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path1, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path2, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path3, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path4, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path5, follow_links, &sb_));
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Stat(bad_leading_path6, follow_links, &sb_));
  }
};

TEST(BrokerProcessIntegrationTest,
     StatNonexistentFileWithCreatePermissionsFollowLinks) {
  RunAllBrokerTests<StatNonexistentFileWithCreatePermissionsDelegate<
      /*follow_links=*/true>>();
}

TEST(BrokerProcessIntegrationTest,
     StatNonexistentFileWithCreatePermissionsNoFollowLinks) {
  RunAllBrokerTests<StatNonexistentFileWithCreatePermissionsDelegate<
      /*follow_links=*/false>>();
}

// Actual file with permissions to see file.
template <bool follow_links>
class StatFileWithPermissionsDelegate final : public StatFileDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params = StatFileDelegate::ChildSetUpPreSandbox();
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_STAT});
    params.permissions = {BrokerFilePermission::ReadOnly(tempfile_name_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(0, syscaller->Stat(tempfile_name_, follow_links, &sb_));

    // Following fields may never be consistent but should be non-zero.
    // Don't trust the platform to define fields with any particular
    // sign.
    BPF_ASSERT_NE(0u, static_cast<unsigned int>(sb_.st_dev));
    BPF_ASSERT_NE(0u, static_cast<unsigned int>(sb_.st_ino));
    BPF_ASSERT_NE(0u, static_cast<unsigned int>(sb_.st_mode));
    BPF_ASSERT_NE(0u, static_cast<unsigned int>(sb_.st_blksize));
    BPF_ASSERT_NE(0u, static_cast<unsigned int>(sb_.st_blocks));

    // We are the ones that made the file.
    BPF_ASSERT_EQ(geteuid(), sb_.st_uid);
    BPF_ASSERT_EQ(getegid(), sb_.st_gid);

    // Wrote 12 bytes above which should fit in one block.
    BPF_ASSERT_EQ(12, sb_.st_size);

    // Can't go backwards in time, 1500000000 was some time ago.
    BPF_ASSERT_LT(1500000000u, static_cast<unsigned int>(sb_.st_atime));
    BPF_ASSERT_LT(1500000000u, static_cast<unsigned int>(sb_.st_mtime));
    BPF_ASSERT_LT(1500000000u, static_cast<unsigned int>(sb_.st_ctime));
  }
};

TEST(BrokerProcessIntegrationTest, StatFileWithPermissionsFollowLinks) {
  RunAllBrokerTests<StatFileWithPermissionsDelegate</*follow_links=*/true>>();
}

TEST(BrokerProcessIntegrationTest, StatFileWithPermissionsNoFollowLinks) {
  RunAllBrokerTests<StatFileWithPermissionsDelegate</*follow_links=*/false>>();
}

class RenameTestDelegate : public BrokerTestDelegate {
 public:
  void ParentSetUp() override {
    {
      // Just to generate names and ensure they do not exist upon scope exit.
      ScopedTemporaryFile oldfile;
      ScopedTemporaryFile newfile;
      oldpath_ = oldfile.full_file_name();
      newpath_ = newfile.full_file_name();
    }

    // Now make a file using old path name.
    int fd = open(oldpath_.c_str(), O_RDWR | O_CREAT, 0600);
    EXPECT_TRUE(fd > 0);
    close(fd);

    EXPECT_TRUE(access(oldpath_.c_str(), F_OK) == 0);
    EXPECT_TRUE(access(newpath_.c_str(), F_OK) < 0);
  }

  void ParentTearDown() override {
    unlink(oldpath_.c_str());
    unlink(newpath_.c_str());
    BrokerTestDelegate::ParentTearDown();
  }

 protected:
  void ExpectRenamed() {
    EXPECT_TRUE(access(oldpath_.c_str(), 0) < 0);
    EXPECT_TRUE(access(newpath_.c_str(), 0) == 0);
  }

  void ExpectNotRenamed() {
    EXPECT_TRUE(access(oldpath_.c_str(), 0) == 0);
    EXPECT_TRUE(access(newpath_.c_str(), 0) < 0);
  }

  std::string oldpath_;
  std::string newpath_;
};

// Check rename fails with write permissions to both files but command
// itself is not allowed.
class RenameNoCommandDelegate final : public RenameTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet({});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(oldpath_),
                          BrokerFilePermission::ReadWriteCreate(newpath_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Rename(oldpath_.c_str(), newpath_.c_str()));
  }

  void ParentTearDown() override {
    ExpectNotRenamed();
    RenameTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RenameNoCommand) {
  RunAllBrokerTests<RenameNoCommandDelegate>();
}
// Check rename fails when no permission to new file.
class RenameNoPermNewDelegate final : public RenameTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RENAME});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(newpath_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Rename(oldpath_.c_str(), newpath_.c_str()));
  }

  void ParentTearDown() override {
    ExpectNotRenamed();
    RenameTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RenameNoPermNew) {
  RunAllBrokerTests<RenameNoPermNewDelegate>();
}
// Check rename fails when no permission to old file.
class RenameNoPermOldDelegate final : public RenameTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RENAME});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(oldpath_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Rename(oldpath_.c_str(), newpath_.c_str()));
  }

  void ParentTearDown() override {
    ExpectNotRenamed();
    RenameTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RenameNoPermOld) {
  RunAllBrokerTests<RenameNoPermOldDelegate>();
}

// Check rename fails when only read permission to first file.
class RenameReadPermNewDelegate final : public RenameTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RENAME});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(oldpath_),
                          BrokerFilePermission::ReadOnly(newpath_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Rename(oldpath_.c_str(), newpath_.c_str()));
  }

  void ParentTearDown() override {
    ExpectNotRenamed();
    RenameTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RenameReadPermNew) {
  RunAllBrokerTests<RenameReadPermNewDelegate>();
}

// Check rename fails when only read permission to second file.
class RenameReadPermOldDelegate final : public RenameTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RENAME});
    params.permissions = {BrokerFilePermission::ReadOnly(oldpath_),
                          BrokerFilePermission::ReadWriteCreate(newpath_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Rename(oldpath_.c_str(), newpath_.c_str()));
  }

  void ParentTearDown() override {
    ExpectNotRenamed();
    RenameTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RenameReadPermOld) {
  RunAllBrokerTests<RenameReadPermOldDelegate>();
}

// Check rename passes with write permissions to both files.
class RenameWritePermsBothDelegate final : public RenameTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RENAME});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(oldpath_),
                          BrokerFilePermission::ReadWriteCreate(newpath_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(0, syscaller->Rename(oldpath_.c_str(), newpath_.c_str()));
  }

  void ParentTearDown() override {
    ExpectRenamed();
    RenameTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RenameWritePermsBoth) {
  RunAllBrokerTests<RenameWritePermsBothDelegate>();
}

// The base class of all the Readlink() tests.
class ReadlinkTestDelegate : public BrokerTestDelegate {
 public:
  void ParentSetUp() override {
    {
      // Just to generate names and ensure they do not exist upon scope exit.
      ScopedTemporaryFile oldfile;
      ScopedTemporaryFile newfile;
      oldpath_ = oldfile.full_file_name();
      newpath_ = newfile.full_file_name();
    }

    // Now make a link from old to new path name.
    EXPECT_TRUE(symlink(oldpath_.c_str(), newpath_.c_str()) == 0);
  }

  void ParentTearDown() override {
    unlink(oldpath_.c_str());
    unlink(newpath_.c_str());
    BrokerTestDelegate::ParentTearDown();
  }

 protected:
  const char* const nonesuch_name = "/mbogo/nonesuch";

  std::string oldpath_;
  std::string newpath_;

  char readlink_buf_[1024];
};

// Actual file with permissions to see file but command itself not allowed.
class ReadlinkNoCommandDelegate final : public ReadlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet({});
    params.permissions = {BrokerFilePermission::ReadOnly(newpath_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override;
};

TEST(BrokerProcessIntegrationTest, ReadlinkNoCommand) {
  RunAllBrokerTests<ReadlinkNoCommandDelegate>();
}

void ReadlinkNoCommandDelegate::RunTestInSandboxedChild(Syscaller* syscaller) {
  BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                syscaller->Readlink(newpath_.c_str(), readlink_buf_,
                                    sizeof(readlink_buf_)));
}

// Nonexistent file with no permissions to see file.
class ReadlinkNonexistentNoPermissionsDelegate final
    : public ReadlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_READLINK});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Readlink(nonesuch_name, readlink_buf_,
                                      sizeof(readlink_buf_)));
  }
};

TEST(BrokerProcessIntegrationTest, ReadlinkNonexistentNoPermissions) {
  RunAllBrokerTests<ReadlinkNonexistentNoPermissionsDelegate>();
}

// Actual file with no permissions to see file.
class ReadlinkNoPermissionsDelegate final : public ReadlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_READLINK});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel,
                  syscaller->Readlink(newpath_.c_str(), readlink_buf_,
                                      sizeof(readlink_buf_)));
  }
};

TEST(BrokerProcessIntegrationTest, ReadlinkNoPermissions) {
  RunAllBrokerTests<ReadlinkNoPermissionsDelegate>();
}

// Nonexistent file with permissions to see file.
class ReadlinkNonexistentWithPermissionsDelegate final
    : public ReadlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_READLINK});
    params.permissions = {BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }
  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-ENOENT, syscaller->Readlink(nonesuch_name, readlink_buf_,
                                               sizeof(readlink_buf_)));
  }
};

TEST(BrokerProcessIntegrationTest, ReadlinkNonexistentWithPermissions) {
  RunAllBrokerTests<ReadlinkNonexistentWithPermissionsDelegate>();
}

// Actual file with permissions to see file.
class ReadlinkFileWithPermissionsDelegate final : public ReadlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_READLINK});
    params.permissions = {BrokerFilePermission::ReadOnly(newpath_)};
    return params;
  }
  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    ssize_t retlen = syscaller->Readlink(newpath_.c_str(), readlink_buf_,
                                         sizeof(readlink_buf_));
    BPF_ASSERT(retlen == static_cast<ssize_t>(oldpath_.length()));
    BPF_ASSERT_EQ(0, memcmp(oldpath_.c_str(), readlink_buf_, retlen));
  }
};

TEST(BrokerProcessIntegrationTest, ReadlinkFileWithPermissions) {
  RunAllBrokerTests<ReadlinkFileWithPermissionsDelegate>();
}

// Actual file with permissions to see file, but too small a buffer.
class ReadlinkFileWithPermissionsSmallBufferDelegate final
    : public ReadlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_READLINK});
    params.permissions = {BrokerFilePermission::ReadOnly(newpath_)};
    return params;
  }
  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(4, syscaller->Readlink(newpath_.c_str(), readlink_buf_, 4));
  }
};

TEST(BrokerProcessIntegrationTest, ReadlinkFileWithPermissionsSmallBuffer) {
  RunAllBrokerTests<ReadlinkFileWithPermissionsSmallBufferDelegate>();
}

// The base class of all the Mkdir() tests.
class MkdirTestDelegate : public BrokerTestDelegate {
 public:
  void ParentSetUp() override {
    ScopedTemporaryFile file;
    path_ = file.full_file_name();
  }

  void ParentTearDown() override {
    rmdir(path_.c_str());
    BrokerTestDelegate::ParentTearDown();
  }

 protected:
  const char* nonesuch_name = "/mbogo/nonesuch";

  std::string path_;
};

// Actual file with permissions to use but command itself not allowed.
class MkdirNoCommandDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet({});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Mkdir(path_.c_str(), 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirNoCommand) {
  RunAllBrokerTests<MkdirNoCommandDelegate>();
}

// Nonexistent file with no permissions to see file.
class MkdirNonexistentNoPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Mkdir(nonesuch_name, 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirNonexistentNoPermissions) {
  RunAllBrokerTests<MkdirNonexistentNoPermissionsDelegate>();
}

// Actual file with no permissions to see file.
class MkdirFileNoPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Mkdir(path_.c_str(), 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirFileNoPermissions) {
  RunAllBrokerTests<MkdirFileNoPermissionsDelegate>();
}

// Nonexistent file with insufficient permissions to see file.
class MkdirNonexistentROPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {BrokerFilePermission::ReadOnly(path_),
                          BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Mkdir(nonesuch_name, 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirNonexistentROPermissions) {
  RunAllBrokerTests<MkdirNonexistentROPermissionsDelegate>();
}

// Actual file with insufficient permissions to see file.
class MkdirFileROPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {BrokerFilePermission::ReadOnly(path_),
                          BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Mkdir(path_.c_str(), 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirFileROPermissions) {
  RunAllBrokerTests<MkdirFileROPermissionsDelegate>();
}

// Nonexistent file with insufficient permissions to see file, case 2.
class MkdirNonExistentRWPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Mkdir(nonesuch_name, 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirNonExistentRWPermissions) {
  RunAllBrokerTests<MkdirNonExistentRWPermissionsDelegate>();
}

// Actual file with insufficient permissions to see file, case 2.
class MkdirFileRWPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Mkdir(path_.c_str(), 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirFileRWPermissions) {
  RunAllBrokerTests<MkdirFileRWPermissionsDelegate>();
}

// Nonexistent file with permissions to see file.
class MkdirNonExistentRWCPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(path_),
                          BrokerFilePermission::ReadWriteCreate(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-2, syscaller->Mkdir(nonesuch_name, 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirNonExistentRWCPermissions) {
  RunAllBrokerTests<MkdirNonExistentRWCPermissionsDelegate>();
}

// Actual file with permissions to see file.
class MkdirFileRWCPermissionsDelegate final : public MkdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_MKDIR});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(path_),
                          BrokerFilePermission::ReadWriteCreate(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(0, syscaller->Mkdir(path_.c_str(), 0600));
  }
};

TEST(BrokerProcessIntegrationTest, MkdirFileRWCPermissions) {
  RunAllBrokerTests<MkdirFileRWCPermissionsDelegate>();
}

class RmdirTestDelegate : public BrokerTestDelegate {
 public:
  void ParentSetUp() override {
    {
      // Generate name and ensure it does not exist upon scope exit.
      ScopedTemporaryFile file;
      path_ = file.full_file_name();
    }

    const char* const path_name = path_.c_str();

    EXPECT_EQ(0, mkdir(path_name, 0600));
    EXPECT_EQ(0, access(path_name, F_OK));
  }

  void ParentTearDown() override {
    rmdir(path_.c_str());
    BrokerTestDelegate::ParentTearDown();
  }

 protected:
  const char* const nonesuch_name = "/mbogo/nonesuch";

  std::string path_;
};

// Actual file with permissions to use but command itself not allowed.
class RmdirNoCommandDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet({});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Rmdir(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirNoCommand) {
  RunAllBrokerTests<RmdirNoCommandDelegate>();
}

// Nonexistent file with no permissions to see file.
class RmdirNonexistentNoPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Rmdir(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirNonexistentNoPermissions) {
  RunAllBrokerTests<RmdirNonexistentNoPermissionsDelegate>();
}

// Actual file with no permissions to see file.
class RmdirFileNoPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Rmdir(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirFileNoPermissions) {
  RunAllBrokerTests<RmdirFileNoPermissionsDelegate>();
}

// Nonexistent file with insufficient permissions to see file.
class RmdirNonexistentROPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {BrokerFilePermission::ReadOnly(path_),
                          BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Rmdir(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirNonexistentROPermissions) {
  RunAllBrokerTests<RmdirNonexistentROPermissionsDelegate>();
}

// Actual file with insufficient permissions to see file.
class RmdirFileROPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {BrokerFilePermission::ReadOnly(path_),
                          BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Rmdir(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirFileROPermissions) {
  RunAllBrokerTests<RmdirFileROPermissionsDelegate>();
}

// Nonexistent file with insufficient permissions to see file, case 2.
class RmdirNonExistentRWPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Rmdir(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirNonExistentRWPermissions) {
  RunAllBrokerTests<RmdirNonExistentRWPermissionsDelegate>();
}

// Actual file with insufficient permissions to see file, case 2.
class RmdirFileRWPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Rmdir(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirFileRWPermissions) {
  RunAllBrokerTests<RmdirFileRWPermissionsDelegate>();
}

// Nonexistent file with permissions to see file.
class RmdirNonExistentRWCPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(path_),
                          BrokerFilePermission::ReadWriteCreate(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-2, syscaller->Rmdir(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirNonExistentRWCPermissions) {
  RunAllBrokerTests<RmdirNonExistentRWCPermissionsDelegate>();
}

// Actual file with permissions to see file.
class RmdirFileRWCPermissionsDelegate final : public RmdirTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_RMDIR});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(path_),
                          BrokerFilePermission::ReadWriteCreate(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(0, syscaller->Rmdir(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(-1, access(path_.c_str(), 0));
    RmdirTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, RmdirFileRWCPermissions) {
  RunAllBrokerTests<RmdirFileRWCPermissionsDelegate>();
}

// The base class for all the Unlink() tests.
class UnlinkTestDelegate : public BrokerTestDelegate {
 public:
  void ParentSetUp() override {
    {
      // Generate name and ensure it does not exist upon scope exit.
      ScopedTemporaryFile file;
      path_ = file.full_file_name();
    }

    int fd = open(path_.c_str(), O_RDWR | O_CREAT, 0600);
    EXPECT_TRUE(fd >= 0);
    close(fd);
    EXPECT_EQ(0, access(path_.c_str(), F_OK));
  }

  void ParentTearDown() override {
    unlink(path_.c_str());
    BrokerTestDelegate::ParentTearDown();
  }

 protected:
  const char* const nonesuch_name = "/mbogo/nonesuch";

  std::string path_;
};

// Actual file with permissions to use but command itself not allowed.
class UnlinkNoCommandDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet({});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Unlink(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkNoCommand) {
  RunAllBrokerTests<UnlinkNoCommandDelegate>();
}

// Nonexistent file with no permissions to see file.
class UnlinkNonexistentNoPermissionsDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Unlink(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkNonexistentNoPermissions) {
  RunAllBrokerTests<UnlinkNonexistentNoPermissionsDelegate>();
}

// Actual file with no permissions to see file.
class UnlinkFileNoPermissionsDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Unlink(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkFileNoPermissions) {
  RunAllBrokerTests<UnlinkFileNoPermissionsDelegate>();
}

// Nonexistent file with insufficient permissions to see file.
class UnlinkNonexistentROPermissionsDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {BrokerFilePermission::ReadOnly(path_),
                          BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Unlink(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkNonexistentROPermissions) {
  RunAllBrokerTests<UnlinkNonexistentROPermissionsDelegate>();
}

// Actual file with insufficient permissions to see file.
class UnlinkFileROPermissionsDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {BrokerFilePermission::ReadOnly(path_),
                          BrokerFilePermission::ReadOnly(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Unlink(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkFileROPermissions) {
  RunAllBrokerTests<UnlinkFileROPermissionsDelegate>();
}

// Nonexistent file with insufficient permissions to see file, case 2.
class UnlinkNonExistentRWPermissionsDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Unlink(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkNonExistentRWPermissions) {
  RunAllBrokerTests<UnlinkNonExistentRWPermissionsDelegate>();
}

// Actual file with insufficient permissions to see file, case 2.
class UnlinkFileRWPermissionsDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {BrokerFilePermission::ReadWrite(path_),
                          BrokerFilePermission::ReadWrite(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->Unlink(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkFileRWPermissions) {
  RunAllBrokerTests<UnlinkFileRWPermissionsDelegate>();
}

// Nonexistent file with permissions to see file.
class UnlinkNonExistentRWCPermissionsDelegate final
    : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(path_),
                          BrokerFilePermission::ReadWriteCreate(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(-2, syscaller->Unlink(nonesuch_name));
  }

  void ParentTearDown() override {
    EXPECT_EQ(0, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkNonExistentRWCPermissions) {
  RunAllBrokerTests<UnlinkNonExistentRWCPermissionsDelegate>();
}

// Actual file with permissions to see file.
class UnlinkFileRWCPermissionsDelegate final : public UnlinkTestDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set =
        syscall_broker::MakeBrokerCommandSet({syscall_broker::COMMAND_UNLINK});
    params.permissions = {BrokerFilePermission::ReadWriteCreate(path_),
                          BrokerFilePermission::ReadWriteCreate(nonesuch_name)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    BPF_ASSERT_EQ(0, syscaller->Unlink(path_.c_str()));
  }

  void ParentTearDown() override {
    EXPECT_EQ(-1, access(path_.c_str(), 0));
    UnlinkTestDelegate::ParentTearDown();
  }
};

TEST(BrokerProcessIntegrationTest, UnlinkFileRWCPermissions) {
  RunAllBrokerTests<UnlinkFileRWCPermissionsDelegate>();
}

// Parent class for the inotify_add_watch() tests.
class InotifyAddWatchDelegate : public BrokerTestDelegate {
 public:
  const uint32_t kBadMask =
      IN_CREATE | IN_DELETE | IN_CLOSE_WRITE | IN_MOVE | IN_ONLYDIR;
  const uint32_t kGoodMask = kBadMask | IN_ATTRIB;

  static constexpr char kNestedTempDirName[] = "nested_temp_dir";
  static constexpr char kBadPrefixName[] = "nested_t";

  void ParentSetUp() override {
    // Create two nested temp dirs.
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDirUnderPath(
        base::FilePath(kTempDirForTests)));
    temp_dir_str_ = temp_dir_.GetPath().MaybeAsASCII();
    ASSERT_FALSE(temp_dir_str_.empty());

    ASSERT_TRUE(nested_temp_dir_.Set(
        temp_dir_.GetPath().AppendASCII(kNestedTempDirName)));
    nested_temp_dir_str_ = nested_temp_dir_.GetPath().MaybeAsASCII();
    ASSERT_FALSE(nested_temp_dir_str_.empty());

    temp_file_ = base::CreateAndOpenTemporaryFileInDir(
        nested_temp_dir_.GetPath(), &temp_file_path_);
    temp_file_path_str_ = temp_file_path_.MaybeAsASCII();
    ASSERT_FALSE(temp_file_path_str_.empty());
  }

 protected:
  // Parent temp directory.
  base::ScopedTempDir temp_dir_;
  std::string temp_dir_str_;

  // A directory nested under |temp_dir_|.
  base::ScopedTempDir nested_temp_dir_;
  std::string nested_temp_dir_str_;

  // In |nested_temp_dir_|.
  base::FilePath temp_file_path_;
  std::string temp_file_path_str_;
  base::File temp_file_;
};

// Try inotify_add_watch() without the relevant broker command.
class InotifyAddWatchNoCommandDelegate final : public InotifyAddWatchDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet({});
    params.permissions = {
        BrokerFilePermission::InotifyAddWatchWithIntermediateDirs(
            temp_file_path_str_),
        BrokerFilePermission::ReadWriteCreateRecursive(nested_temp_dir_str_ +
                                                       "/")};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    base::ScopedFD inotify_instance(inotify_init());
    BPF_ASSERT(inotify_instance.is_valid());
    BPF_ASSERT_EQ(
        -kFakeErrnoSentinel,
        syscaller->InotifyAddWatch(inotify_instance.get(),
                                   nested_temp_dir_str_.c_str(), kGoodMask));
  }
};

TEST(BrokerProcessIntegrationTest, InotifyAddWatchNoCommand) {
  RunAllBrokerTests<InotifyAddWatchNoCommandDelegate>();
}

// Try inotify_add_watch() without the relevant permissions.
class InotifyAddWatchNoPermissionsDelegate final
    : public InotifyAddWatchDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_INOTIFY_ADD_WATCH});
    params.permissions = {};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    base::ScopedFD inotify_instance(inotify_init());
    BPF_ASSERT(inotify_instance.is_valid());
    BPF_ASSERT_EQ(
        -kFakeErrnoSentinel,
        syscaller->InotifyAddWatch(inotify_instance.get(),
                                   nested_temp_dir_str_.c_str(), kGoodMask));
  }
};

TEST(BrokerProcessIntegrationTest, InotifyAddWatchNoPermissions) {
  RunAllBrokerTests<InotifyAddWatchNoPermissionsDelegate>();
}

// Try inotify_add_watch() with a variety of bad arguments.
class InotifyAddWatchBadArgumentsDelegate final
    : public InotifyAddWatchDelegate {
 public:
  void ParentSetUp() override {
    InotifyAddWatchDelegate::ParentSetUp();

    ASSERT_TRUE(
        other_temp_dir_.Set(temp_dir_.GetPath().AppendASCII("other_temp_dir")));
    other_temp_dir_str_ = other_temp_dir_.GetPath().MaybeAsASCII();
    ASSERT_FALSE(other_temp_dir_str_.empty());

    base::FilePath bad_prefix = temp_dir_.GetPath().AppendASCII(kBadPrefixName);
    bad_prefix_str_ = bad_prefix.MaybeAsASCII();
    ASSERT_FALSE(bad_prefix_str_.empty());
  }

  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_INOTIFY_ADD_WATCH});
    params.permissions = {
        BrokerFilePermission::InotifyAddWatchWithIntermediateDirs(
            temp_file_path_str_)};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    base::ScopedFD inotify_instance(inotify_init());
    BPF_ASSERT(inotify_instance.is_valid());
    // Watch the correct directory with bad flags.
    BPF_ASSERT_EQ(
        -kFakeErrnoSentinel,
        syscaller->InotifyAddWatch(inotify_instance.get(),
                                   nested_temp_dir_str_.c_str(), kBadMask));

    // Try to watch an unintended directory, should fail.
    BPF_ASSERT_EQ(
        -kFakeErrnoSentinel,
        syscaller->InotifyAddWatch(inotify_instance.get(),
                                   other_temp_dir_str_.c_str(), kGoodMask));

    // Try to access a prefix that isn't a full directory.
    BPF_ASSERT_EQ(-kFakeErrnoSentinel, syscaller->InotifyAddWatch(
                                           inotify_instance.get(),
                                           bad_prefix_str_.c_str(), kGoodMask));
  }

 protected:
  // Another directory nested under |temp_dir_| with no sandbox permissions.
  base::ScopedTempDir other_temp_dir_;
  std::string other_temp_dir_str_;

  // A prefix of |nested_temp_dir_| that doesn't match a valid directory.
  std::string bad_prefix_str_;
};

TEST(BrokerProcessIntegrationTest, InotifyAddWatchBadArguments) {
  RunAllBrokerTests<InotifyAddWatchBadArgumentsDelegate>();
}

// Use inottify_add_watch() successfully and verify it actually works.
class InotifyAddWatchSuccessDelegate final : public InotifyAddWatchDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_INOTIFY_ADD_WATCH,
         syscall_broker::COMMAND_UNLINK});
    params.permissions = {
        BrokerFilePermission::InotifyAddWatchWithIntermediateDirs(
            temp_file_path_str_),
        BrokerFilePermission::ReadWriteCreateRecursive(nested_temp_dir_str_ +
                                                       "/")};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    base::ScopedFD inotify_instance(inotify_init());
    BPF_ASSERT(inotify_instance.is_valid());
    // This inotify_add_watch() call should succeed.
    int wd = syscaller->InotifyAddWatch(
        inotify_instance.get(), nested_temp_dir_str_.c_str(), kGoodMask);
    BPF_ASSERT_GE(wd, 0);

    // Unlinking the file generates an inotify notification.
    BPF_ASSERT_GE(unlink(temp_file_path_str_.c_str()), 0);

    // Read one inotify message and verify it names the correct watch descriptor
    // |wd|. The test will timeout if no inotify notifications are ever
    // generated.
    std::vector<char> buf(4096);
    BPF_ASSERT_GE(read(inotify_instance.get(), buf.data(), buf.size()), 0);
    struct inotify_event* event =
        reinterpret_cast<struct inotify_event*>(buf.data());
    BPF_ASSERT_EQ(event->wd, wd);

    // Removing the watch should succeed.
    BPF_ASSERT_GE(inotify_rm_watch(inotify_instance.get(), wd), 0);
  }
};

TEST(BrokerProcessIntegrationTest, InotifyAddWatchSuccess) {
  RunAllBrokerTests<InotifyAddWatchSuccessDelegate>();
}

// Tests base::FilePathWatcher which uses inotify on Linux.
// This is used in the network service sandbox.
class BaseFilePathWatcherDelegate final : public InotifyAddWatchDelegate {
 public:
  BrokerParams ChildSetUpPreSandbox() override {
    // Prewarm file accesses.
    base::GetMaxNumberOfInotifyWatches();

    BrokerParams params;
    params.allowed_command_set = syscall_broker::MakeBrokerCommandSet(
        {syscall_broker::COMMAND_INOTIFY_ADD_WATCH,
         syscall_broker::COMMAND_OPEN});
    params.permissions = {
        BrokerFilePermission::InotifyAddWatchWithIntermediateDirs(
            temp_file_path_str_),
        BrokerFilePermission::ReadWriteCreateRecursive(nested_temp_dir_str_ +
                                                       "/")};
    return params;
  }

  void RunTestInSandboxedChild(Syscaller* syscaller) override {
    base::test::SingleThreadTaskEnvironment task_environment(
        base::test::TaskEnvironment::MainThreadType::IO);

    // Watch the file and wait for a notification about that file from
    // FilePathWatcher.
    base::RunLoop run_loop;
    base::FilePathWatcher file_watcher_;
    BPF_ASSERT(file_watcher_.Watch(
        temp_file_path_, base::FilePathWatcher::Type::kNonRecursive,
        base::BindLambdaForTesting([&](const base::FilePath& path, bool error) {
          BPF_ASSERT_EQ(temp_file_path_, path);
          run_loop.Quit();
        })));

    // Our inotify file path watcher requires a file to be opened for writing
    // *after* adding the watch, and then closed, in order to generate a
    // notification. The actual call to Write() isn't even strictly necessary.
    // Another way to generate a notification is
    // base::DeleteFile(temp_file_path_).
    base::File temp_file_again(temp_file_path_, base::File::FLAG_OPEN |
                                                    base::File::FLAG_READ |
                                                    base::File::FLAG_WRITE);
    char buf2[] = "a";
    BPF_ASSERT_EQ(temp_file_again.Write(0, buf2, sizeof(buf2)), sizeof(buf2));
    temp_file_again.Flush();
    temp_file_again.Close();
    // Wait until we receive a notification about the file modification.
    // Failure results in a test timeout.
    run_loop.Run();
  }
};

TEST(BrokerProcessIntegrationTest, BaseFilePathWatcherInotifyTest) {
  const std::vector<BrokerTestConfiguration> inotify_test_configs = {
      {"FastCheckInClient_NoSyscaller", true, SyscallerType::NoSyscaller,
       BrokerType::SIGNAL_BASED},
      {"NoFastCheckInClient_NoSyscaller", false, SyscallerType::NoSyscaller,
       BrokerType::SIGNAL_BASED},
  };

  for (const BrokerTestConfiguration& test_config : inotify_test_configs) {
    SCOPED_TRACE(test_config.test_name);
    auto test_delegate = std::make_unique<BaseFilePathWatcherDelegate>();
    RunSingleBrokerTest(test_delegate.get(), test_config);
  }
}

#endif  // !defined(THREAD_SANITIZER)
}  // namespace sandbox