File: file_system_access_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1457 lines) | stat: -rw-r--r-- 61,769 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/test/bind.h"
#include "base/test/scoped_path_override.h"
#include "base/test/test_file_util.h"
#include "base/test/test_future.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/file_system_access/chrome_file_system_access_permission_context.h"
#include "chrome/browser/file_system_access/file_system_access_permission_context_factory.h"
#include "chrome/browser/file_system_access/file_system_access_permission_request_manager.h"
#include "chrome/browser/safe_browsing/download_protection/download_protection_service.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/ui/actions/chrome_action_id.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_actions.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/file_system_access/file_system_access_test_utils.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/toolbar_button_provider.h"
#include "chrome/browser/ui/views/page_action/page_action_icon_view.h"
#include "chrome/browser/ui/views/page_action/page_action_view.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "components/permissions/permission_util.h"
#include "components/safe_browsing/buildflags.h"
#include "components/safe_browsing/content/common/file_type_policies_test_util.h"
#include "content/public/browser/file_system_access_permission_context.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/back_forward_cache_util.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/fenced_frame_test_util.h"
#include "content/public/test/prerender_test_util.h"
#include "content/public/test/scoped_web_ui_controller_factory_registration.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/web_ui_browsertest_util.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/controllable_http_response.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "third_party/blink/public/common/features.h"
#include "ui/webui/webui_allowlist.h"

using safe_browsing::ClientDownloadRequest;

namespace {
// Function to generate the test name suffix based on the boolean parameter
std::string ParamInfoToString(const testing::TestParamInfo<bool>& info) {
  return info.param ? "MigrationEnabled" : "MigrationDisabled";
}

}  // namespace
// End-to-end tests for the File System Access API. Among other things, these
// test the integration between usage of the File System Access API and the
// various bits of UI and permissions checks implemented in the chrome layer.
class FileSystemAccessBrowserTest : public InProcessBrowserTest,
                                    public ::testing::WithParamInterface<bool> {
 public:
  FileSystemAccessBrowserTest() {
    if (IsMigrationEnabled()) {
      scoped_feature_list_.InitWithFeaturesAndParameters(
          {{::features::kPageActionsMigration,
            {{::features::kPageActionsMigrationFileSystemAccess.name,
              "true"}}}},
          {});
    } else {
      scoped_feature_list_.InitWithFeaturesAndParameters(
          {}, {::features::kPageActionsMigration});
    }
  }

  void SetUp() override {
    // Create a scoped directory under %TEMP% instead of using
    // `base::ScopedTempDir::CreateUniqueTempDir`.
    // `base::ScopedTempDir::CreateUniqueTempDir` creates a path under
    // %ProgramFiles% on Windows when running as Admin, which is a blocked path
    // (`kBlockedPaths`). This can fail some of the tests.
    ASSERT_TRUE(
        temp_dir_.CreateUniqueTempDirUnderPath(base::GetTempDirForTesting()));
    InProcessBrowserTest::SetUp();
  }

  void SetUpOnMainThread() override {
    content::SetupCrossSiteRedirector(embedded_test_server());
    host_resolver()->AddRule("*", "127.0.0.1");
    ASSERT_TRUE(embedded_test_server()->Start());
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    // Ignore cert errors so that URLs can be loaded from a site
    // other than localhost (the EmbeddedTestServer serves a certificate that
    // is valid for localhost).
    command_line->AppendSwitch(switches::kIgnoreCertificateErrors);

    command_line->AppendSwitch(
        switches::kEnableExperimentalWebPlatformFeatures);
  }

  void TearDown() override {
    InProcessBrowserTest::TearDown();
    ASSERT_TRUE(temp_dir_.Delete());
    ui::SelectFileDialog::SetFactory(nullptr);
  }

  bool IsFullscreen() {
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    return web_contents->IsFullscreen();
  }

  base::FilePath CreateTestFile(const std::string& contents) {
    base::ScopedAllowBlockingForTesting allow_blocking;
    base::FilePath result;
    EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &result));
    EXPECT_TRUE(base::WriteFile(result, contents));
    return result;
  }

  bool IsUsageIndicatorVisible(Browser* browser) {
    auto* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
    auto* icon_view =
        browser_view->toolbar_button_provider()->GetPageActionIconView(
            PageActionIconType::kFileSystemAccess);
    if (IsMigrationEnabled()) {
      page_actions::PageActionView* page_action_icon_view =
          browser_view->toolbar_button_provider()->GetPageActionView(
              kActionShowFileSystemAccess);
      return page_action_icon_view && page_action_icon_view->GetVisible();
    }
    return icon_view && icon_view->GetVisible();
  }

  bool IsMigrationEnabled() const { return GetParam(); }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;

 protected:
  base::ScopedTempDir temp_dir_;
};

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTest, SaveFile) {
  const base::FilePath test_file = CreateTestFile("");
  const std::string file_contents = "file contents to write";

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("/title1.html")));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  EXPECT_FALSE(IsUsageIndicatorVisible(browser()));

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let e = await self.showSaveFilePicker();"
                            "  self.entry = e;"
                            "  return e.name; })()"));

  EXPECT_TRUE(IsUsageIndicatorVisible(browser()))
      << "A save file dialog implicitly grants write access, so usage "
         "indicator should be visible.";

  EXPECT_EQ(
      static_cast<int>(file_contents.size()),
      content::EvalJs(
          web_contents,
          content::JsReplace("(async () => {"
                             "  const w = await self.entry.createWritable();"
                             "  await w.write(new Blob([$1]));"
                             "  await w.close();"
                             "  return (await self.entry.getFile()).size; })()",
                             file_contents)));

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    std::string read_contents;
    EXPECT_TRUE(base::ReadFileToString(test_file, &read_contents));
    EXPECT_EQ(file_contents, read_contents);
  }
}

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTest, OpenFile) {
  const base::FilePath test_file = CreateTestFile("");
  const std::string file_contents = "file contents to write";

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("/title1.html")));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  EXPECT_FALSE(IsUsageIndicatorVisible(browser()));

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let [e] = await self.showOpenFilePicker();"
                            "  self.entry = e;"
                            "  return e.name; })()"));

  // Even read-only access should show a usage indicator.
  EXPECT_TRUE(IsUsageIndicatorVisible(browser()));

  EXPECT_EQ(
      static_cast<int>(file_contents.size()),
      content::EvalJs(
          web_contents,
          content::JsReplace("(async () => {"
                             "  const w = await self.entry.createWritable();"
                             "  await w.write(new Blob([$1]));"
                             "  await w.close();"
                             "  return (await self.entry.getFile()).size; })()",
                             file_contents)));

  // Should have prompted for and received write access, so usage indicator
  // should still be visible.
  EXPECT_TRUE(IsUsageIndicatorVisible(browser()));

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    std::string read_contents;
    EXPECT_TRUE(base::ReadFileToString(test_file, &read_contents));
    EXPECT_EQ(file_contents, read_contents);
  }
}

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTest, FullscreenOpenFile) {
  const base::FilePath test_file = CreateTestFile("");
  const std::string file_contents = "file contents to write";
  GURL frame_url = embedded_test_server()->GetURL("/title1.html");

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("/title1.html")));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let [e] = await self.showOpenFilePicker();"
                            "  self.entry = e;"
                            "  return e.name; })()"));

  EXPECT_TRUE(content::ExecJs(web_contents,
                              "(async () => {"
                              "  await document.body.requestFullscreen();"
                              "})()",
                              content::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));

  // Wait until the fullscreen operation completes.
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(IsFullscreen());

  EXPECT_TRUE(
      content::ExecJs(web_contents,
                      "(async () => {"
                      "  let fsChangePromise = new Promise((resolve) => {"
                      "    document.onfullscreenchange = resolve;"
                      "  });"
                      "  const w = await self.entry.createWritable();"
                      "  await fsChangePromise;"
                      "  return; })()",
                      content::EXECUTE_SCRIPT_NO_RESOLVE_PROMISES));

  // Wait until the fullscreen exit operation completes.
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(IsFullscreen());
}
INSTANTIATE_TEST_SUITE_P(,
                         FileSystemAccessBrowserTest,
                         testing::Bool(),
                         &ParamInfoToString);

class FileSystemAccessBrowserSlowLoadTest : public FileSystemAccessBrowserTest {
 public:
  FileSystemAccessBrowserSlowLoadTest() = default;
  ~FileSystemAccessBrowserSlowLoadTest() override = default;

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

  void SetUpOnMainThread() override {
    main_document_response_ =
        std::make_unique<net::test_server::ControllableHttpResponse>(
            embedded_test_server(), "/main_document");
    FileSystemAccessBrowserTest::SetUpOnMainThread();
  }

 protected:
  std::unique_ptr<net::test_server::ControllableHttpResponse>
      main_document_response_;
};

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserSlowLoadTest, WaitUntilLoaded) {
  const base::FilePath test_file = CreateTestFile("");
  const std::string file_contents = "file contents to write";

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("/title1.html")));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  web_contents->GetController().LoadURL(
      embedded_test_server()->GetURL("/main_document"), content::Referrer(),
      ui::PAGE_TRANSITION_LINK, std::string());

  content::TestNavigationObserver load_observer(web_contents);

  main_document_response_->WaitForRequest();
  main_document_response_->Send(
      "HTTP/1.1 200 OK\r\n"
      "Connection: close\r\n"
      "Content-Type: text/html; charset=utf-8\r\n"
      "\r\n"
      "<body>\n"
      "<script>\n"
      "self.createWritableFinished = false;\n"
      "self.createWritableFinishedWhenDocumentLoad = \n"
      "    new Promise((resolve) => {\n"
      "      window.addEventListener('load', () => {\n"
      "        resolve(self.createWritableFinished);\n"
      "      });\n"
      "    });\n"
      "</script>"
      "</body>");

  load_observer.WaitForNavigationFinished();

  EXPECT_FALSE(IsUsageIndicatorVisible(browser()));

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let [e] = await self.showOpenFilePicker();"
                            "  self.entry = e;"
                            "  return e.name; })()"));

  // Even read-only access should show a usage indicator.
  EXPECT_TRUE(IsUsageIndicatorVisible(browser()));

  EXPECT_EQ("done",
            content::EvalJs(
                web_contents,
                "(() => {"
                "  self.createWritablePromise = self.entry.createWritable();"
                "  self.createWritablePromise.then((result) => {"
                "        self.createWritableFinished = true;"
                "      });"
                "  return 'done';})()"));

  // Finish the response. This will triger the load event handler.
  main_document_response_->Done();

  // The promise of createWritable() must not have been resolved when the
  // load event handler was called.
  EXPECT_EQ(false,
            content::EvalJs(web_contents,
                            "self.createWritableFinishedWhenDocumentLoad"));

  // The FileSystemWritableFileStream must work correctly.
  EXPECT_EQ(
      static_cast<int>(file_contents.size()),
      content::EvalJs(
          web_contents,
          content::JsReplace("(async () => {"
                             "  const w = await self.createWritablePromise;"
                             "  await w.write(new Blob([$1]));"
                             "  await w.close();"
                             "  return (await self.entry.getFile()).size; })()",
                             file_contents)));

  // The usage indicator should still be visible.
  EXPECT_TRUE(IsUsageIndicatorVisible(browser()));
}

#if BUILDFLAG(SAFE_BROWSING_DOWNLOAD_PROTECTION)
IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTest,
                       SafeBrowsing) {  // change this to p
  safe_browsing::FileTypePoliciesTestOverlay policies;
  std::unique_ptr<safe_browsing::DownloadFileTypeConfig> file_type_config =
      std::make_unique<safe_browsing::DownloadFileTypeConfig>();
  auto* file_type = file_type_config->mutable_default_file_type();
  file_type->set_uma_value(-1);
  file_type->set_ping_setting(safe_browsing::DownloadFileType::FULL_PING);
  auto* platform_settings = file_type->add_platform_settings();
  platform_settings->set_danger_level(
      safe_browsing::DownloadFileType::NOT_DANGEROUS);
  platform_settings->set_auto_open_hint(
      safe_browsing::DownloadFileType::ALLOW_AUTO_OPEN);
  policies.SwapConfig(file_type_config);

  const std::string file_name("test.pdf");
  const base::FilePath test_file = temp_dir_.GetPath().AppendASCII(file_name);

  std::string expected_hash;
  ASSERT_TRUE(base::HexStringToString(
      "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD",
      &expected_hash));
  std::string expected_url =
      "blob:" + embedded_test_server()->base_url().spec() +
      "file-system-access-write";
  GURL frame_url = embedded_test_server()->GetURL("/title1.html");

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), frame_url));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  bool invoked_safe_browsing = false;

  safe_browsing::SafeBrowsingService* sb_service =
      g_browser_process->safe_browsing_service();
  base::CallbackListSubscription subscription =
      sb_service->download_protection_service()
          ->RegisterFileSystemAccessWriteRequestCallback(
              base::BindLambdaForTesting(
                  [&](const ClientDownloadRequest* request) {
                    invoked_safe_browsing = true;

                    EXPECT_EQ(request->url(), expected_url);
                    EXPECT_EQ(request->digests().sha256(), expected_hash);
                    EXPECT_EQ(request->length(), 3);
                    EXPECT_EQ(request->file_basename(), file_name);
                    EXPECT_EQ(request->download_type(),
                              ClientDownloadRequest::DOCUMENT);

                    ASSERT_GE(request->resources_size(), 2);

                    EXPECT_EQ(request->resources(0).type(),
                              ClientDownloadRequest::DOWNLOAD_URL);
                    EXPECT_EQ(request->resources(0).url(), expected_url);
                    EXPECT_EQ(request->resources(0).referrer(), frame_url);

                    // TODO(mek): Change test so that frame url and tab url are
                    // not the same.
                    EXPECT_EQ(request->resources(1).type(),
                              ClientDownloadRequest::TAB_URL);
                    EXPECT_EQ(request->resources(1).url(), frame_url);
                    EXPECT_EQ(request->resources(1).referrer(), "");
                  }));

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let e = await self.showSaveFilePicker();"
                            "  const w = await e.createWritable();"
                            "  await w.write('abc');"
                            "  await w.close();"
                            "  return e.name; })()"));

  EXPECT_TRUE(invoked_safe_browsing);
}
#endif

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTest,
                       OpenFileWithContentSettingAllow) {
  const base::FilePath test_file = CreateTestFile("");
  const std::string file_contents = "file contents to write";

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));

  auto url = embedded_test_server()->GetURL("/title1.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Grant write permission.
  HostContentSettingsMap* host_content_settings_map =
      HostContentSettingsMapFactory::GetForProfile(browser()->profile());
  host_content_settings_map->SetContentSettingDefaultScope(
      url, url, ContentSettingsType::FILE_SYSTEM_WRITE_GUARD,
      CONTENT_SETTING_ALLOW);

  // If a prompt shows up, deny it.
  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::DENIED);

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let [e] = await self.showOpenFilePicker();"
                            "  self.entry = e;"
                            "  return e.name; })()"));

  // Write should succeed. If a prompt shows up, it would be denied and we will
  // get a JavaScript error.
  EXPECT_EQ(
      static_cast<int>(file_contents.size()),
      content::EvalJs(
          web_contents,
          content::JsReplace("(async () => {"
                             "  const w = await self.entry.createWritable();"
                             "  await w.write(new Blob([$1]));"
                             "  await w.close();"
                             "  return (await self.entry.getFile()).size; })()",
                             file_contents)));

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    std::string read_contents;
    EXPECT_TRUE(base::ReadFileToString(test_file, &read_contents));
    EXPECT_EQ(file_contents, read_contents);
  }
}

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTest,
                       SaveFileWithContentSettingAllow) {
  const base::FilePath test_file = CreateTestFile("");
  const std::string file_contents = "file contents to write";

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));

  auto url = embedded_test_server()->GetURL("/title1.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Grant write permission.
  HostContentSettingsMap* host_content_settings_map =
      HostContentSettingsMapFactory::GetForProfile(browser()->profile());
  host_content_settings_map->SetContentSettingDefaultScope(
      url, url, ContentSettingsType::FILE_SYSTEM_WRITE_GUARD,
      CONTENT_SETTING_ALLOW);

  // If a prompt shows up, deny it.
  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::DENIED);

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let e = await self.showSaveFilePicker();"
                            "  self.entry = e;"
                            "  return e.name; })()"));

  // Write should succeed. If a prompt shows up, it would be denied and we will
  // get a JavaScript error.
  EXPECT_EQ(
      static_cast<int>(file_contents.size()),
      content::EvalJs(
          web_contents,
          content::JsReplace("(async () => {"
                             "  const w = await self.entry.createWritable();"
                             "  await w.write(new Blob([$1]));"
                             "  await w.close();"
                             "  return (await self.entry.getFile()).size; })()",
                             file_contents)));

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    std::string read_contents;
    EXPECT_TRUE(base::ReadFileToString(test_file, &read_contents));
    EXPECT_EQ(file_contents, read_contents);
  }
}
INSTANTIATE_TEST_SUITE_P(,
                         FileSystemAccessBrowserSlowLoadTest,
                         testing::Bool(),
                         &ParamInfoToString);

class PersistedPermissionsFileSystemAccessBrowserTest
    : public FileSystemAccessBrowserTest {
 public:
  PersistedPermissionsFileSystemAccessBrowserTest() {
    feature_list_.InitAndEnableFeature(
        features::kFileSystemAccessPersistentPermissions);
  }

  void SetUpOnMainThread() override {
    FileSystemAccessBrowserTest::SetUpOnMainThread();
  }

  ~PersistedPermissionsFileSystemAccessBrowserTest() override = default;

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

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

// Tests that permissions are revoked after all top-level frames have navigated
// away to a different origin.
IN_PROC_BROWSER_TEST_P(PersistedPermissionsFileSystemAccessBrowserTest,
                       RevokePermissionAfterNavigation) {
  const base::FilePath test_file = CreateTestFile("");
  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));

  net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
  https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
  https_server.AddDefaultHandlers(GetChromeTestDataDir());
  content::SetupCrossSiteRedirector(&https_server);
  ASSERT_TRUE(https_server.Start());

  Profile* profile = browser()->profile();

  // Create three separate windows:

  // 1. Showing https://b.com/title1.html
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), https_server.GetURL("b.com", "/title1.html")));
  content::WebContents* first_party_web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  FileSystemAccessPermissionRequestManager::FromWebContents(
      first_party_web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  // 2. Showing https://a.com/iframe_cross_site.html, with an iframe for
  // https://b.com/title1.html. This should be opened by the first window to
  // facilitate communication between the two.
  content::TestNavigationObserver popup_observer(nullptr);
  popup_observer.StartWatchingNewWebContents();
  auto iframe_url = https_server.GetURL("a.com", "/iframe_cross_site.html");
  EXPECT_TRUE(ExecJs(
      first_party_web_contents,
      "self.third_party_window = window.open('" + iframe_url.spec() + "');"));
  popup_observer.Wait();
  ASSERT_EQ(2, browser()->tab_strip_model()->count());
  content::WebContents* third_party_web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_NE(first_party_web_contents, third_party_web_contents);
  content::RenderFrameHost* third_party_iframe =
      ChildFrameAt(third_party_web_contents, 0);
  ASSERT_TRUE(third_party_iframe);
  ASSERT_EQ(third_party_iframe->GetLastCommittedOrigin(),
            first_party_web_contents->GetPrimaryMainFrame()
                ->GetLastCommittedOrigin());

  // 3. Also showing https://b.com/title1.html
  Browser* third_window = CreateBrowser(profile);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      third_window, https_server.GetURL("b.com", "/title1.html")));

  // Set up a MessageChannel between the first two b.com contexts. This will
  // allow us to pass a FileSystemFileHandle between the two later in the test
  // since we can't postMessage the FileSystemFileHandle to a.com and then to
  // the b.com iframe since a.com is cross-origin. Also, this approach avoids
  // using BroadcastChannel which doesn't work when third-party storage
  // partitioning is enabled.
  EXPECT_EQ(nullptr,
            content::EvalJs(third_party_iframe,
                            "self.message_promise = new Promise(resolve => {\n"
                            "  self.onmessage = resolve;\n"
                            "}); null;"));

  EXPECT_EQ(nullptr,
            content::EvalJs(
                third_party_web_contents,
                "self.onmessage = (e) => {\n"
                "  iframe = document.getElementsByTagName('iframe')[0];\n"
                "  iframe.contentWindow.postMessage('😀', '*', [e.ports[0]]);\n"
                "}; null;"));

  EXPECT_EQ(nullptr,
            content::EvalJs(first_party_web_contents,
                            "let message_channel = new MessageChannel();\n"
                            "self.message_port = message_channel.port1;\n"
                            "self.third_party_window.postMessage('🚀', '*', "
                            "[message_channel.port2]);\n"
                            "null;"));

  EXPECT_EQ(
      nullptr,
      content::EvalJs(third_party_iframe,
                      "(async () => {\n"
                      "  let e = await self.message_promise;\n"
                      "  self.message_port = e.ports[0];\n"
                      "  self.message_port_promise = new Promise(resolve => {\n"
                      "    self.message_port.onmessage = resolve;\n"
                      "  })})();"));

  // Top-level page in first window picks files and sends it to iframe.
  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(first_party_web_contents,
                            "(async () => {"
                            "  let [e] = await self.showOpenFilePicker();"
                            "  self.entry = e;"
                            "  self.message_port.postMessage({entry: e});"
                            "  return e.name; })()"));

  // Verify iframe received handle.
  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(third_party_iframe,
                            "(async () => {"
                            "  let e = await self.message_port_promise;"
                            "  self.entry = e.data.entry;"
                            "  return self.entry.name; })()"));

  // Try to request permission in iframe, should reject.
  EXPECT_EQ("SecurityError",
            content::EvalJs(third_party_iframe,
                            "self.entry.requestPermission({mode: "
                            "'readwrite'}).catch(e => e.name)"));

  // Have top-level page in first window request write permission.
  EXPECT_EQ(
      "granted",
      content::EvalJs(first_party_web_contents,
                      "self.entry.requestPermission({mode: 'readwrite'})"));

  // And write to file from iframe.
  const std::string initial_file_contents = "file contents to write";
  EXPECT_EQ(
      static_cast<int>(initial_file_contents.size()),
      content::EvalJs(
          third_party_iframe,
          content::JsReplace("(async () => {"
                             "  const w = await self.entry.createWritable();"
                             "  await w.write(new Blob([$1]));"
                             "  await w.close();"
                             "  return (await self.entry.getFile()).size; })()",
                             initial_file_contents)));

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    std::string read_contents;
    EXPECT_TRUE(base::ReadFileToString(test_file, &read_contents));
    EXPECT_EQ(initial_file_contents, read_contents);
  }

  // Now navigate away from b.com in first window.
  browser()->tab_strip_model()->ActivateTabAt(0);
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), https_server.GetURL("c.com", "/title1.html")));

  // Permission should still be granted in iframe.
  browser()->tab_strip_model()->ActivateTabAt(1);
  EXPECT_EQ("granted",
            content::EvalJs(third_party_iframe,
                            "self.entry.queryPermission({mode: 'readwrite'})"));

  // Now navigate away from b.com in third window as well.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      third_window, https_server.GetURL("a.com", "/title1.html")));

  // On some platforms, permission revocation from the tab closure is
  // triggered by timer, so manually invoke it.
  FileSystemAccessPermissionContextFactory::GetForProfile(profile)
      ->TriggerTimersForTesting();

  // Permission should have been revoked.
  EXPECT_EQ("prompt",
            content::EvalJs(third_party_iframe,
                            "self.entry.queryPermission({mode: 'readwrite'})"));
  EXPECT_EQ("prompt",
            content::EvalJs(third_party_iframe,
                            "self.entry.queryPermission({mode: 'read'})"));
}

// Tests that permissions are revoked after all top-level frames have been
// closed.
IN_PROC_BROWSER_TEST_P(PersistedPermissionsFileSystemAccessBrowserTest,
                       RevokePermissionAfterClosingTab) {
  const base::FilePath test_file = CreateTestFile("");
  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));

  net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS);
  https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK);
  https_server.AddDefaultHandlers(GetChromeTestDataDir());
  content::SetupCrossSiteRedirector(&https_server);
  ASSERT_TRUE(https_server.Start());

  Profile* profile = browser()->profile();

  // Create two separate windows:

  // 1. Showing https://b.com/title1.html
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), https_server.GetURL("b.com", "/title1.html")));
  content::WebContents* first_party_web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  FileSystemAccessPermissionRequestManager::FromWebContents(
      first_party_web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  // 2. Showing https://a.com/iframe_cross_site.html, with an iframe for
  // https://b.com/title1.html. This should be opened by the first window to
  // facilitate communication between the two.
  content::TestNavigationObserver popup_observer(nullptr);
  popup_observer.StartWatchingNewWebContents();
  auto iframe_url = https_server.GetURL("a.com", "/iframe_cross_site.html");
  EXPECT_TRUE(ExecJs(
      first_party_web_contents,
      "self.third_party_window = window.open('" + iframe_url.spec() + "');"));
  popup_observer.Wait();
  ASSERT_EQ(2, browser()->tab_strip_model()->count());
  content::WebContents* third_party_web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  ASSERT_NE(first_party_web_contents, third_party_web_contents);
  content::RenderFrameHost* third_party_iframe =
      ChildFrameAt(third_party_web_contents, 0);
  ASSERT_TRUE(third_party_iframe);
  ASSERT_EQ(third_party_iframe->GetLastCommittedOrigin(),
            first_party_web_contents->GetPrimaryMainFrame()
                ->GetLastCommittedOrigin());

  // Set up a MessageChannel between the two b.com contexts. This will allow us
  // to pass a FileSystemFileHandle between the two later in the test since we
  // can't postMessage the FileSystemFileHandle to a.com and then to the b.com
  // iframe since a.com is cross-origin. Also, this approach avoids using
  // BroadcastChannel which doesn't work when third-party storage partitioning
  // is enabled.
  EXPECT_EQ(nullptr,
            content::EvalJs(third_party_iframe,
                            "self.message_promise = new Promise(resolve => {\n"
                            "  self.onmessage = resolve;\n"
                            "}); null;"));

  EXPECT_EQ(nullptr,
            content::EvalJs(
                third_party_web_contents,
                "self.onmessage = (e) => {\n"
                "  iframe = document.getElementsByTagName('iframe')[0];\n"
                "  iframe.contentWindow.postMessage('😀', '*', [e.ports[0]]);\n"
                "}; null;"));

  EXPECT_EQ(nullptr,
            content::EvalJs(first_party_web_contents,
                            "let message_channel = new MessageChannel();\n"
                            "self.message_port = message_channel.port1;\n"
                            "self.third_party_window.postMessage('🚀', '*', "
                            "[message_channel.port2]);\n"
                            "null;"));

  EXPECT_EQ(
      nullptr,
      content::EvalJs(third_party_iframe,
                      "(async () => {\n"
                      "  let e = await self.message_promise;\n"
                      "  self.message_port = e.ports[0];\n"
                      "  self.message_port_promise = new Promise(resolve => {\n"
                      "    self.message_port.onmessage = resolve;\n"
                      "  })})();"));

  // Top-level page in first window picks files and sends it to iframe.
  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(first_party_web_contents,
                            "(async () => {"
                            "  let [e] = await self.showOpenFilePicker();"
                            "  self.entry = e;"
                            "  self.message_port.postMessage({entry: e});"
                            "  return e.name; })()"));

  // Verify iframe received handle.
  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(third_party_iframe,
                            "(async () => {"
                            "  let e = await self.message_port_promise;"
                            "  self.entry = e.data.entry;"
                            "  return self.entry.name; })()"));

  // Try to request permission in iframe, should reject.
  EXPECT_EQ("SecurityError",
            content::EvalJs(third_party_iframe,
                            "self.entry.requestPermission({mode: "
                            "'readwrite'}).catch(e => e.name)"));

  // Have top-level page in first window request write permission.
  EXPECT_EQ(
      "granted",
      content::EvalJs(first_party_web_contents,
                      "self.entry.requestPermission({mode: 'readwrite'})"));

  // Permission should also be granted in iframe.
  EXPECT_EQ("granted",
            content::EvalJs(third_party_iframe,
                            "self.entry.queryPermission({mode: 'readwrite'})"));

  // Now close first window.
  browser()->tab_strip_model()->CloseWebContentsAt(
      0, TabCloseTypes::CLOSE_CREATE_HISTORICAL_TAB);
  ASSERT_EQ(1, browser()->tab_strip_model()->count());
  ASSERT_EQ(browser()->tab_strip_model()->GetActiveWebContents(),
            third_party_web_contents);

  // On some platforms, permission revocation from the tab closure is
  // triggered by timer, so manually invoke it.
  FileSystemAccessPermissionContextFactory::GetForProfile(profile)
      ->TriggerTimersForTesting();

  // Permission should have been revoked.
  EXPECT_EQ("prompt",
            content::EvalJs(third_party_iframe,
                            "self.entry.queryPermission({mode: 'readwrite'})"));
  EXPECT_EQ("prompt",
            content::EvalJs(third_party_iframe,
                            "self.entry.queryPermission({mode: 'read'})"));
}

IN_PROC_BROWSER_TEST_P(PersistedPermissionsFileSystemAccessBrowserTest,
                       UsageIndicatorVisibleWithPersistedPermissionsEnabled) {
  const GURL test_url = embedded_test_server()->GetURL("/title1.html");
  auto kTestOrigin = url::Origin::Create(test_url);
  const base::FilePath test_file = CreateTestFile("");
  const std::string file_contents = "file contents to write";
  std::unique_ptr<ChromeFileSystemAccessPermissionContext> permission_context =
      std::make_unique<ChromeFileSystemAccessPermissionContext>(
          browser()->profile());

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_url));

  // The usage indicator is not initially visible.
  EXPECT_FALSE(IsUsageIndicatorVisible(browser()));

  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);
  permission_context->SetOriginHasExtendedPermissionForTesting(kTestOrigin);
  auto grant = permission_context->GetWritePermissionGrant(
      kTestOrigin, content::PathInfo(test_file),
      content::FileSystemAccessPermissionContext::HandleType::kFile,
      content::FileSystemAccessPermissionContext::UserAction::kSave);

  EXPECT_TRUE(permission_context->HasExtendedPermissionForTesting(
      kTestOrigin, content::PathInfo(test_file),
      content::FileSystemAccessPermissionContext::HandleType::kFile,
      ChromeFileSystemAccessPermissionContext::GrantType::kWrite));

  EXPECT_EQ(content::FileSystemAccessPermissionGrant::PermissionStatus::GRANTED,
            grant->GetStatus());

  EXPECT_EQ(test_file.BaseName().AsUTF8Unsafe(),
            content::EvalJs(web_contents,
                            "(async () => {"
                            "  let [e] = await self.showOpenFilePicker();"
                            "  self.entry = e;"
                            "  return e.name; })()"));
  EXPECT_EQ(
      static_cast<int>(file_contents.size()),
      content::EvalJs(
          web_contents,
          content::JsReplace("(async () => {"
                             "  const w = await self.entry.createWritable();"
                             "  await w.write(new Blob([$1]));"
                             "  await w.close();"
                             "  return (await self.entry.getFile()).size; })()",
                             file_contents)));

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    std::string read_contents;
    EXPECT_TRUE(base::ReadFileToString(test_file, &read_contents));
    EXPECT_EQ(file_contents, read_contents);
  }

  // The usage indicator is visible after opening and writing to a file.
  EXPECT_TRUE(IsUsageIndicatorVisible(browser()));

  // Navigate to another page.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("a.com", "/title2.html")));

  // The usage indicator is not visible after navigating to another page.
  EXPECT_FALSE(IsUsageIndicatorVisible(browser()));

  // TODO(crbug.com/40101962): Once Extended Permission UI is
  // implemented, mock user's response to the UI and assert that the usage
  // indicator is visible when the original page is visited again.
}

INSTANTIATE_TEST_SUITE_P(,
                         PersistedPermissionsFileSystemAccessBrowserTest,
                         testing::Bool(),
                         &ParamInfoToString);

class BackForwardCacheFileSystemAccessBrowserTest
    : public FileSystemAccessBrowserTest {
 public:
  BackForwardCacheFileSystemAccessBrowserTest() {
    // Enable BackForwardCache.
    feature_list_.InitWithFeaturesAndParameters(
        content::GetDefaultEnabledBackForwardCacheFeaturesForTesting(
            /*ignore_outstanding_network_request=*/false),
        content::GetDefaultDisabledBackForwardCacheFeaturesForTesting());
  }
  ~BackForwardCacheFileSystemAccessBrowserTest() override = default;

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

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

IN_PROC_BROWSER_TEST_P(BackForwardCacheFileSystemAccessBrowserTest,
                       RequestWriteAccess) {
  std::unique_ptr<ChromeFileSystemAccessPermissionContext> permission_context =
      std::make_unique<ChromeFileSystemAccessPermissionContext>(
          browser()->profile());

  const base::FilePath test_file = CreateTestFile("");

  const GURL initial_url =
      embedded_test_server()->GetURL("a.com", "/title1.html");
  // Navigate to the initial page.
  auto* initial_rfh = ui_test_utils::NavigateToURL(browser(), initial_url);
  ASSERT_TRUE(initial_rfh);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  content::RenderFrameDeletedObserver deleted_observer(initial_rfh);

  // Navigate to another page. The initial page goes to the back forward
  // cache.
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("b.com", "/title2.html")));
  EXPECT_FALSE(deleted_observer.deleted());

  auto grant = permission_context->GetWritePermissionGrant(
      url::Origin::Create(initial_url), content::PathInfo(test_file),
      content::FileSystemAccessPermissionContext::HandleType::kFile,
      content::FileSystemAccessPermissionContext::UserAction::kOpen);

  std::optional<
      content::FileSystemAccessPermissionGrant::PermissionRequestOutcome>
      result;

  // RequestPermission() for the initial page in the back forward cache must
  // fail.
  grant->RequestPermission(
      initial_rfh->GetGlobalId(),
      content::FileSystemAccessPermissionGrant::UserActivationState::kRequired,
      base::BindOnce(
          [](std::optional<content::FileSystemAccessPermissionGrant::
                               PermissionRequestOutcome>* result_out,
             content::FileSystemAccessPermissionGrant::PermissionRequestOutcome
                 result) { *result_out = result; },
          base::Unretained(&result)));
  // The initial page must be evicted from the back forward cache.
  deleted_observer.WaitUntilDeleted();
}

INSTANTIATE_TEST_SUITE_P(,
                         BackForwardCacheFileSystemAccessBrowserTest,
                         testing::Bool(),
                         &ParamInfoToString);
class PrerenderFileSystemAccessBrowserTest
    : public FileSystemAccessBrowserTest {
 public:
  PrerenderFileSystemAccessBrowserTest()
      : prerender_helper_(base::BindRepeating(
            &PrerenderFileSystemAccessBrowserTest::web_contents,
            base::Unretained(this))) {}
  ~PrerenderFileSystemAccessBrowserTest() override = default;

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

  void SetUp() override {
    prerender_helper_.RegisterServerRequestMonitor(embedded_test_server());
    FileSystemAccessBrowserTest::SetUp();
  }

 protected:
  content::test::PrerenderTestHelper prerender_helper_;

 private:
  content::WebContents* web_contents() const {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }
};

IN_PROC_BROWSER_TEST_P(PrerenderFileSystemAccessBrowserTest,
                       RequestWriteAccess) {
  std::unique_ptr<ChromeFileSystemAccessPermissionContext> permission_context =
      std::make_unique<ChromeFileSystemAccessPermissionContext>(
          browser()->profile());
  const base::FilePath test_file = CreateTestFile("");

  // Navigate to the initial page.
  const GURL initial_url = embedded_test_server()->GetURL("/title1.html");
  ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), initial_url));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  // Load a page in the prerender.
  GURL prerender_url = embedded_test_server()->GetURL("/title2.html");
  content::FrameTreeNodeId host_id =
      prerender_helper_.AddPrerender(prerender_url);
  content::test::PrerenderHostObserver host_observer(*web_contents, host_id);
  EXPECT_FALSE(host_observer.was_activated());
  content::RenderFrameHost* prerender_frame =
      prerender_helper_.GetPrerenderedMainFrameHost(host_id);
  EXPECT_NE(prerender_frame, nullptr);
  content::RenderFrameDeletedObserver deleted_observer(prerender_frame);

  auto grant = permission_context->GetWritePermissionGrant(
      url::Origin::Create(initial_url), content::PathInfo(test_file),
      content::FileSystemAccessPermissionContext::HandleType::kFile,
      content::FileSystemAccessPermissionContext::UserAction::kOpen);

  std::optional<
      content::FileSystemAccessPermissionGrant::PermissionRequestOutcome>
      result;

  // RequestPermission() for the prerendering page must fail.
  grant->RequestPermission(
      prerender_frame->GetGlobalId(),
      content::FileSystemAccessPermissionGrant::UserActivationState::kRequired,
      base::BindOnce(
          [](std::optional<content::FileSystemAccessPermissionGrant::
                               PermissionRequestOutcome>* result_out,
             content::FileSystemAccessPermissionGrant::PermissionRequestOutcome
                 result) { *result_out = result; },
          base::Unretained(&result)));
  // The initial page must be evicted from the back forward cache.
  deleted_observer.WaitUntilDeleted();
}

INSTANTIATE_TEST_SUITE_P(,
                         PrerenderFileSystemAccessBrowserTest,
                         testing::Bool(),
                         &ParamInfoToString);

class FencedFrameFileSystemAccessBrowserTest
    : public FileSystemAccessBrowserTest {
 public:
  FencedFrameFileSystemAccessBrowserTest() {
    fenced_frame_helper_ =
        std::make_unique<content::test::FencedFrameTestHelper>();
  }

  void SetUpOnMainThread() override {
    FileSystemAccessBrowserTest::SetUpOnMainThread();
    https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir());
    ASSERT_TRUE(https_server_.Start());
  }

  ~FencedFrameFileSystemAccessBrowserTest() override = default;

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

 protected:
  content::RenderFrameHost* CreateFencedFrame(
      content::RenderFrameHost* fenced_frame_parent,
      const GURL& url) {
    if (fenced_frame_helper_) {
      return fenced_frame_helper_->CreateFencedFrame(fenced_frame_parent, url);
    }

    // FencedFrameTestHelper only supports the MPArch version of fenced
    // frames. So need to maually create a fenced frame for the ShadowDOM
    // version.
    content::TestNavigationManager navigation(
        browser()->tab_strip_model()->GetActiveWebContents(), url);
    constexpr char kAddFencedFrameScript[] = R"({
        const fenced_frame = document.createElement('fencedframe');
        fenced_frame.src = $1;
        document.body.appendChild(fenced_frame);
    })";
    EXPECT_TRUE(ExecJs(fenced_frame_parent,
                       content::JsReplace(kAddFencedFrameScript, url)));
    EXPECT_TRUE(navigation.WaitForNavigationFinished());

    content::RenderFrameHost* new_frame = ChildFrameAt(fenced_frame_parent, 0);

    return new_frame;
  }

 protected:
  net::EmbeddedTestServer& https_server() { return https_server_; }

 private:
  std::unique_ptr<content::test::FencedFrameTestHelper> fenced_frame_helper_;
  base::test::ScopedFeatureList feature_list_;
  net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS};
};

IN_PROC_BROWSER_TEST_P(FencedFrameFileSystemAccessBrowserTest,
                       RequestWriteAccess) {
  std::unique_ptr<ChromeFileSystemAccessPermissionContext> permission_context =
      std::make_unique<ChromeFileSystemAccessPermissionContext>(
          browser()->profile());

  const base::FilePath test_file = CreateTestFile("");

  ui::SelectFileDialog::SetFactory(
      std::make_unique<SelectPredeterminedFileDialogFactory>(
          std::vector<base::FilePath>{test_file}));
  ASSERT_TRUE(ui_test_utils::NavigateToURL(
      browser(), embedded_test_server()->GetURL("/title1.html")));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
      ->set_auto_response_for_test(permissions::PermissionAction::GRANTED);

  EXPECT_FALSE(IsUsageIndicatorVisible(browser()));

  // Load a fenced frame.
  GURL fenced_frame_url = https_server().GetURL("/fenced_frames/title1.html");
  content::RenderFrameHost* fenced_frame_host =
      CreateFencedFrame(web_contents->GetPrimaryMainFrame(), fenced_frame_url);
  ASSERT_TRUE(fenced_frame_host);

  // File system access is disabled for fenced frames.
  EXPECT_FALSE(content::ExecJs(fenced_frame_host,
                               "(async () => {"
                               "  let [e] = await self.showOpenFilePicker();"
                               "  self.entry = e;"
                               "  return e.name; })()"));

  // Even read-only access should show a usage indicator.
  EXPECT_FALSE(IsUsageIndicatorVisible(browser()));

  auto grant = permission_context->GetWritePermissionGrant(
      url::Origin::Create(fenced_frame_url), content::PathInfo(test_file),
      content::FileSystemAccessPermissionContext::HandleType::kFile,
      content::FileSystemAccessPermissionContext::UserAction::kOpen);

  base::test::TestFuture<
      content::FileSystemAccessPermissionGrant::PermissionRequestOutcome>
      future;

  // RequestPermission() for the fenced frame must fail.
  grant->RequestPermission(
      fenced_frame_host->GetGlobalId(),
      content::FileSystemAccessPermissionGrant::UserActivationState::kRequired,
      future.GetCallback());
  EXPECT_EQ(future.Get<>(), content::FileSystemAccessPermissionGrant::
                                PermissionRequestOutcome::kInvalidFrame);
}
INSTANTIATE_TEST_SUITE_P(,
                         FencedFrameFileSystemAccessBrowserTest,
                         testing::Bool(),
                         &ParamInfoToString);

class FileSystemAccessBrowserTestForWebUI
    : public InProcessBrowserTest,
      public ::testing::WithParamInterface<bool> {
 public:
  FileSystemAccessBrowserTestForWebUI() {
    if (IsMigrationEnabled()) {
      scoped_feature_list_.InitWithFeaturesAndParameters(
          {{::features::kPageActionsMigration,
            {{::features::kPageActionsMigrationFileSystemAccess.name,
              "true"}}}},
          {});
    } else {
      scoped_feature_list_.InitWithFeaturesAndParameters(
          {}, {::features::kPageActionsMigration});
    }
    base::ScopedAllowBlockingForTesting allow_blocking;

    // Create a scoped directory under %TEMP% instead of using
    // `base::ScopedTempDir::CreateUniqueTempDir`.
    // `base::ScopedTempDir::CreateUniqueTempDir` creates a path under
    // %ProgramFiles% on Windows when running as Admin, which is a blocked path
    // (`kBlockedPaths`). This can fail some of the tests.
    CHECK(temp_dir_.CreateUniqueTempDirUnderPath(base::GetTempDirForTesting()));
  }

  content::WebContents* SetUpAndNavigateToTestWebUI() {
    const GURL kWebUITestUrl = content::GetWebUIURL("webui/title1.html");
    WebUIAllowlist::GetOrCreate(browser()->profile())
        ->RegisterAutoGrantedPermissions(
            url::Origin::Create(kWebUITestUrl),
            {ContentSettingsType::FILE_SYSTEM_READ_GUARD,
             ContentSettingsType::FILE_SYSTEM_WRITE_GUARD});

    EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), kWebUITestUrl));
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

  void TestFilePermissionInDirectory(content::WebContents* web_contents,
                                     const base::FilePath& dir_path) {
    // Create a test file in the directory.
    base::FilePath test_file_path;
    {
      base::ScopedAllowBlockingForTesting allow_blocking;
      ASSERT_TRUE(base::CreateTemporaryFileInDir(dir_path, &test_file_path));
      ASSERT_TRUE(base::WriteFile(test_file_path, "test"));
    }

    // Write permissions are granted to the test WebUI with WebUIAllowlist in
    // SetUpAndNavigateToTestWebUI. Users should not get permission prompts.
    // We auto-deny them if they show up.
    FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
        ->set_auto_response_for_test(permissions::PermissionAction::DENIED);

    // Open the dialog and choose the file.
    ui::SelectFileDialog::SetFactory(
        std::make_unique<SelectPredeterminedFileDialogFactory>(
            std::vector<base::FilePath>{test_file_path}));
    EXPECT_TRUE(
        content::ExecJs(web_contents,
                        "window.showOpenFilePicker().then("
                        "  handles => { window.file_handle = handles[0]; })"));

    EXPECT_EQ("file", content::EvalJs(web_contents, "window.file_handle.kind"));

    // Check permission descriptors.
    EXPECT_EQ("granted",
              content::EvalJs(
                  web_contents,
                  "window.file_handle.queryPermission({ mode: 'read' })"));
    EXPECT_EQ("granted",
              content::EvalJs(
                  web_contents,
                  "window.file_handle.queryPermission({ mode: 'readwrite' })"));
  }

  void TestDirectoryPermission(content::WebContents* web_contents,
                               const base::FilePath& dir_path) {
    // Write permissions are granted to the test WebUI with WebUIAllowlist in
    // SetUpAndNavigateToTestWebUI. Users should not get permission prompts.
    // We auto-deny them if they show up.
    FileSystemAccessPermissionRequestManager::FromWebContents(web_contents)
        ->set_auto_response_for_test(permissions::PermissionAction::DENIED);

    // Open the dialog and choose the directory.
    ui::SelectFileDialog::SetFactory(
        std::make_unique<SelectPredeterminedFileDialogFactory>(
            std::vector<base::FilePath>{dir_path}));

    EXPECT_TRUE(
        content::ExecJs(web_contents,
                        "window.showDirectoryPicker().then("
                        "  handle => { window.dir_handle = handle; })"));

    EXPECT_EQ("directory",
              content::EvalJs(web_contents, "window.dir_handle.kind"));

    // Check permission descriptors.
    EXPECT_EQ(
        "granted",
        content::EvalJs(web_contents,
                        "window.dir_handle.queryPermission({ mode: 'read' })"));
    EXPECT_EQ("granted",
              content::EvalJs(
                  web_contents,
                  "window.dir_handle.queryPermission({ mode: 'readwrite' })"));
  }
  bool IsMigrationEnabled() const { return GetParam(); }

 protected:
  base::ScopedTempDir temp_dir_;

 private:
  content::TestWebUIControllerFactory factory_;
  content::ScopedWebUIControllerFactoryRegistration factory_registration_{
      &factory_};
  base::test::ScopedFeatureList scoped_feature_list_;
};

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTestForWebUI,
                       OpenFilePicker_NormalPath) {
  content::WebContents* web_contents = SetUpAndNavigateToTestWebUI();
  TestFilePermissionInDirectory(web_contents, temp_dir_.GetPath());
}

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTestForWebUI,
                       OpenFilePicker_FileInSensitivePath) {
  base::ScopedPathOverride downloads_override(chrome::DIR_DEFAULT_DOWNLOADS,
                                              temp_dir_.GetPath(),
                                              /*is_absolute*/ true,
                                              /*create*/ false);

  content::WebContents* web_contents = SetUpAndNavigateToTestWebUI();
  TestFilePermissionInDirectory(web_contents, temp_dir_.GetPath());
}

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTestForWebUI,
                       OpenDirectoryPicker_NormalPath) {
  content::WebContents* web_contents = SetUpAndNavigateToTestWebUI();
  TestDirectoryPermission(web_contents, temp_dir_.GetPath());
}

IN_PROC_BROWSER_TEST_P(FileSystemAccessBrowserTestForWebUI,
                       OpenDirectoryPicker_DirectoryInSensitivePath) {
  base::ScopedPathOverride downloads_override(chrome::DIR_DEFAULT_DOWNLOADS,
                                              temp_dir_.GetPath(),
                                              /*is_absolute*/ true,
                                              /*create*/ false);

  base::FilePath test_dir_path = temp_dir_.GetPath().AppendASCII("folder");
  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    ASSERT_TRUE(CreateDirectory(test_dir_path));
  }

  content::WebContents* web_contents = SetUpAndNavigateToTestWebUI();
  TestDirectoryPermission(web_contents, test_dir_path);
}

INSTANTIATE_TEST_SUITE_P(,
                         FileSystemAccessBrowserTestForWebUI,
                         testing::Bool(),
                         &ParamInfoToString);

// TODO(mek): Add more end-to-end test including other bits of UI.