File: external_filesystem_apitest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (827 lines) | stat: -rw-r--r-- 33,368 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <string_view>

#include "ash/constants/ash_switches.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_base.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "chrome/browser/apps/app_service/chrome_app_deprecation/chrome_app_deprecation.h"
#include "chrome/browser/ash/drive/drive_integration_service.h"
#include "chrome/browser/ash/drive/drive_integration_service_factory.h"
#include "chrome/browser/ash/drive/drivefs_test_support.h"
#include "chrome/browser/ash/extensions/file_manager/event_router.h"
#include "chrome/browser/ash/extensions/file_manager/event_router_factory.h"
#include "chrome/browser/ash/file_manager/file_manager_test_util.h"
#include "chrome/browser/ash/file_manager/mount_test_util.h"
#include "chrome/browser/ash/file_manager/volume_manager.h"
#include "chrome/browser/ash/system_web_apps/system_web_app_manager.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/ash/cast_config/cast_config_controller_media_router.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_helper.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_types.h"
#include "components/media_router/browser/test/mock_media_router.h"
#include "components/session_manager/core/session_manager.h"
#include "components/user_manager/test_helper.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/file_system_chooser_test_helpers.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "extensions/browser/extension_host_test_helper.h"
#include "extensions/browser/process_manager.h"
#include "extensions/common/mojom/view_type.mojom.h"
#include "extensions/test/result_catcher.h"
#include "google_apis/common/test_util.h"
#include "google_apis/gaia/gaia_id.h"
#include "storage/browser/file_system/external_mount_points.h"
#include "ui/shell_dialogs/select_file_dialog_factory.h"
#include "ui/shell_dialogs/select_file_policy.h"

// Tests for access to external file systems (as defined in
// storage/common/file_system/file_system_types.h) from extensions with
// fileManagerPrivate and fileBrowserHandler extension permissions.
// The tests cover following external file system types:
// - local (kFileSystemTypeLocalNative): a local file system on which files are
//   accessed using native local path.
//
// The tests cover following scenarios:
// - Performing file system operations on external file systems from an
//   app with fileManagerPrivate permission (i.e. The Files app).
// - Performing read/write operations from file handler extensions. These
//   extensions need a file browser extension to give them permissions to access
//   files. This also includes file handler extensions in filesystem API.
// - Observing directory changes from a file browser extension (using
//   fileManagerPrivate API).
// - Doing searches on drive file system from file browser extension (using
//   fileManagerPrivate API).

using drive::DriveIntegrationServiceFactory;
using extensions::Extension;

namespace file_manager {
namespace {

// Root dirs for file systems expected by the test extensions.
// NOTE: Root dir for drive file system is set by Chrome's drive implementation,
// but the test will have to make sure the mount point is added before
// starting a test extension using WaitUntilDriveMountPointIsAdded().
constexpr char kLocalMountPointName[] = "local";

// Default file content for the test files.
constexpr char kTestFileContent[] = "This is some test content.";

// User account email and directory hash for secondary account for multi-profile
// sensitive test cases.
constexpr char kSecondProfileAccount[] = "profile2@test.com";
constexpr GaiaId::Literal kSecondProfileGaiaId("9876543210");
constexpr char kSecondProfileHash[] = "fileBrowserApiTestProfile2";

// Waits for a WebContents of the background page of the extension under test
// to load, then injects some javascript into it to trigger a particular test.
class JSTestStarter : public content::TestNavigationObserver {
 public:
  explicit JSTestStarter(const std::string& test_name)
      : TestNavigationObserver(GetUrlToWatch()), test_name_(test_name) {
    WatchExistingWebContents();
    StartWatchingNewWebContents();
  }

  static GURL GetUrlToWatch() {
    // Use the chrome-extension:// ID corresponding to the key used in the app
    // manifests for tests in this file. An improvement to this would use the ID
    // of the extension from LoadExtensionAsComponentWithManifest(), but that's
    // potentially racy.
    return GURL(
        "chrome-extension://pkplfbidichfdicaijlchgnapepdginl/"
        "_generated_background_page.html");
  }

  // TestNavigationObserver:
  void OnDidFinishNavigation(
      content::NavigationHandle* navigation_handle) override {
    // If the background page scripts have run, the test will exist, so just run
    // it. Otherwise, schedule the test to be run at the end of the background
    // page script.
    constexpr char kScript[] = R"(
        if (self.$1) {
          chrome.test.runTests([$1])
        } else {
          self.testNameToRun = '$1';
        }
    )";
    ASSERT_TRUE(content::ExecJs(
        navigation_handle->GetRenderFrameHost(),
        base::ReplaceStringPlaceholders(kScript, {test_name_}, nullptr)));

    TestNavigationObserver::OnDidFinishNavigation(navigation_handle);
  }

 private:
  const std::string test_name_;
};

bool TouchFile(const base::FilePath& path,
               std::string_view mtime_string,
               std::string_view atime_string) {
  base::Time mtime, atime;
  auto result =
      base::Time::FromString(std::string(mtime_string).c_str(), &mtime) &&
      base::Time::FromString(std::string(atime_string).c_str(), &atime) &&
      base::TouchFile(path, atime, mtime);
  return result;
}

// Configuration of a file residing in a "test_dir" of a created volume.
// If contents is null, creates a subdirectory.
struct TestDirConfig {
  const char* mtime;
  const char* atime;
  const char* name;
  const char* contents = kTestFileContent;
};

// An arbitrary time, for tests that don't care.
constexpr const char kArbitraryTime[] = "2011-04-03T11:11:10.000Z";

// The default configuration of entries in "test_dir" used in test harnesses.
constexpr const TestDirConfig kDefaultDirConfig[] = {
    {"2011-11-02T04:00:00.000Z", "2011-11-02T04:00:00.000Z", "empty_dir",
     nullptr},
    {"2011-04-01T18:34:08.234Z", "2012-01-02T00:00:01.000Z", "subdir", nullptr},
    {"2011-12-14T00:40:47.330Z", "2012-01-02T00:00:00.000Z", "test_file.xul"},
    {"2012-01-01T10:00:30.000Z", "2012-01-01T00:00:00.000Z",
     "test_file.xul.foo"},
    {"2011-04-03T11:11:10.000Z", "2012-01-02T00:00:00.000Z", "test_file.tiff"},
    {"2011-12-14T00:40:47.330Z", "2010-01-02T00:00:00.000Z",
     "test_file.tiff.foo"},
    {"2011-12-14T00:40:47.330Z", "2011-12-14T00:40:47.330Z", "empty_file.foo",
     ""},
};

// Sets up the initial file system state for native local file systems. The
// hierarchy is the same as for the drive file system.
// The directory is created at unique_temp_dir/|mount_point_name| path.
bool InitializeLocalFileSystem(std::string mount_point_name,
                               base::ScopedTempDir* tmp_dir,
                               base::FilePath* mount_point_dir,
                               const std::vector<TestDirConfig>& dir_contents) {
  if (!tmp_dir->CreateUniqueTempDir()) {
    return false;
  }

  *mount_point_dir = tmp_dir->GetPath().AppendASCII(mount_point_name);
  // Create the mount point.
  if (!base::CreateDirectory(*mount_point_dir)) {
    return false;
  }

  constexpr TestDirConfig kTestDir = {"2012-01-02T00:00:00.000Z",
                                      "2012-01-02T00:00:01.000Z", "test_dir",
                                      nullptr};

  const base::FilePath test_dir = mount_point_dir->AppendASCII(kTestDir.name);
  if (!base::CreateDirectory(test_dir)) {
    return false;
  }

  for (const auto& file : dir_contents) {
    const base::FilePath test_path = test_dir.AppendASCII(file.name);
    if (file.contents) {
      if (!google_apis::test_util::WriteStringToFile(test_path,
                                                     file.contents)) {
        return false;
      }
    } else {
      if (!base::CreateDirectory(test_path)) {
        return false;
      }
    }
  }

  for (const auto& file : dir_contents) {
    if (!TouchFile(test_dir.Append(file.name), file.mtime, file.atime)) {
      return false;
    }
  }

  // Touch the directory holding all the contents last.
  return TouchFile(test_dir, kTestDir.mtime, kTestDir.atime);
}

// Base class for FileSystemExtensionApi tests.
class FileSystemExtensionApiTestBase : public extensions::ExtensionApiTest {
 public:
  enum Flags {
    FLAGS_NONE = 0,
    FLAGS_USE_FILE_HANDLER = 1 << 1,
    FLAGS_LAZY_FILE_HANDLER = 1 << 2,
    FLAGS_CHROME_APP = 1 << 3
  };

  FileSystemExtensionApiTestBase() = default;

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

  ~FileSystemExtensionApiTestBase() override = default;

  virtual std::vector<TestDirConfig> GetTestDirContents() {
    return {std::begin(kDefaultDirConfig), std::end(kDefaultDirConfig)};
  }

  bool SetUpUserDataDirectory() override {
    return drive::SetUpUserDataDirectoryForDriveFsTest();
  }

  void SetUp() override {
    InitTestFileSystem();
    extensions::ExtensionApiTest::SetUp();
  }

  void SetUpOnMainThread() override {
    AddTestMountPoint();

    // Mock the Media Router in extension api tests. Dispatches to the message
    // loop now try to handle mojo messages that will call back into Profile
    // creation through the media router, which then confuse the drive code.
    media_router_ = std::make_unique<media_router::MockMediaRouter>();
    ON_CALL(*media_router_, RegisterMediaSinksObserver(testing::_))
        .WillByDefault(testing::Return(true));
    CastConfigControllerMediaRouter::SetMediaRouterForTest(media_router_.get());

    extensions::ExtensionApiTest::SetUpOnMainThread();
  }

  void TearDownOnMainThread() override {
    CastConfigControllerMediaRouter::SetMediaRouterForTest(nullptr);
    extensions::ExtensionApiTest::TearDownOnMainThread();
  }

  // Runs a file system extension API test.
  // It loads test component extension at |filebrowser_path| with manifest
  // at |filebrowser_manifest|. The |filebrowser_manifest| should be a path
  // relative to |filebrowser_path|. The method waits until the test extension
  // sends test succeed or fail message. It returns true if the test succeeds.
  // If |FLAGS_USE_FILE_HANDLER| flag is set, the file handler extension at path
  // |filehandler_path| will be loaded before the file browser extension.
  // If the flag FLAGS_LAZY_FILE_HANDLER is set, the file handler extension must
  // not have persistent background page. The test will wait until the file
  // handler's background page is closed after initial load before the file
  // browser extension is loaded.
  // If |RunFileSystemExtensionApiTest| fails, |message_| will contain a failure
  // message.
  bool RunFileSystemExtensionApiTest(
      const std::string& filebrowser_path,
      const base::FilePath::CharType* filebrowser_manifest,
      const std::string& filehandler_path,
      int flags) {
    std::unique_ptr<
        apps::chrome_app_deprecation::ScopedAddAppToAllowlistForTesting>
        allowlist;

    if (flags & FLAGS_USE_FILE_HANDLER) {
      if (filehandler_path.empty()) {
        message_ = "Missing file handler path.";
        return false;
      }

      if (flags & FLAGS_LAZY_FILE_HANDLER) {
        // Ensures the file handler extension's background page closes in a
        // timely manner to avoid test timeouts.
        extensions::ProcessManager::SetEventPageIdleTimeForTesting(1);
      }

      extensions::ExtensionHostTestHelper host_helper(profile());
      host_helper.RestrictToType(
          extensions::mojom::ViewType::kExtensionBackgroundPage);
      const Extension* file_handler =
          LoadExtension(test_data_dir_.AppendASCII(filehandler_path));
      if (!file_handler) {
        message_ = "Error loading file handler extension";
        return false;
      }

      if (flags & FLAGS_CHROME_APP) {
        allowlist = std::make_unique<
            apps::chrome_app_deprecation::ScopedAddAppToAllowlistForTesting>(
            file_handler->id());
      }

      if (flags & FLAGS_LAZY_FILE_HANDLER) {
        host_helper.WaitForHostDestroyed();
      } else {
        host_helper.WaitForDocumentElementAvailable();
      }
    }

    extensions::ResultCatcher catcher;

    const Extension* file_browser = LoadExtensionAsComponentWithManifest(
        test_data_dir_.AppendASCII(filebrowser_path), filebrowser_manifest);

    if (!file_browser) {
      message_ = "Could not create file browser";
      return false;
    }

    if (!catcher.GetNextResult()) {
      message_ = catcher.message();
      return false;
    }

    return true;
  }

  // Starts the app in |app_folder| then triggers the |test_name| on the
  // background page using JSTestStarter. Does not configure a file handler app.
  bool RunBackgroundPageTestCase(const std::string& app_folder,
                                 const std::string& test_name) {
    JSTestStarter starter(test_name);
    return RunFileSystemExtensionApiTest("file_browser/" + app_folder,
                                         FILE_PATH_LITERAL("manifest.json"),
                                         std::string(), FLAGS_NONE);
  }

 protected:
  // Sets up initial test file system hierarchy.
  virtual void InitTestFileSystem() = 0;
  // Registers mount point used in the test.
  virtual void AddTestMountPoint() = 0;

 private:
  std::unique_ptr<media_router::MockMediaRouter> media_router_;
};

// Tests for a native local file system.
class LocalFileSystemExtensionApiTest : public FileSystemExtensionApiTestBase {
 public:
  LocalFileSystemExtensionApiTest() = default;
  ~LocalFileSystemExtensionApiTest() override = default;

  // FileSystemExtensionApiTestBase override.
  void InitTestFileSystem() override {
    ASSERT_TRUE(InitializeLocalFileSystem(kLocalMountPointName, &tmp_dir_,
                                          &mount_point_dir_,
                                          GetTestDirContents()))
        << "Failed to initialize file system.";
  }

  // FileSystemExtensionApiTestBase override.
  void AddTestMountPoint() override {
    EXPECT_TRUE(profile()->GetMountPoints()->RegisterFileSystem(
        kLocalMountPointName, storage::kFileSystemTypeLocal,
        storage::FileSystemMountOption(), mount_point_dir_));
    VolumeManager::Get(profile())->AddVolumeForTesting(
        mount_point_dir_, VOLUME_TYPE_TESTING, ash::DeviceType::kUnknown,
        /*read_only*/ false, /*device_path*/ {}, /*drive_label*/ {},
        /*file_system_type*/ {}, /*hidden*/ false, /*watchable*/ true);
  }

 private:
  base::ScopedTempDir tmp_dir_;
  base::FilePath mount_point_dir_;
};

// Tests for a drive file system.
class DriveFileSystemExtensionApiTest : public FileSystemExtensionApiTestBase {
 public:
  DriveFileSystemExtensionApiTest() = default;
  ~DriveFileSystemExtensionApiTest() override = default;

  // FileSystemExtensionApiTestBase override.
  void InitTestFileSystem() override {
    // Set up cache root to be used by DriveIntegrationService. This has to be
    // done before the browser is created because the service instance is
    // initialized by EventRouter.
    ASSERT_TRUE(test_cache_root_.CreateUniqueTempDir());

    // This callback will get called during Profile creation.
    create_drive_integration_service_ = base::BindRepeating(
        &DriveFileSystemExtensionApiTest::CreateDriveIntegrationService,
        base::Unretained(this));
    service_factory_for_test_ =
        std::make_unique<DriveIntegrationServiceFactory::ScopedFactoryForTest>(
            &create_drive_integration_service_);
  }

  // FileSystemExtensionApiTestBase override.
  void AddTestMountPoint() override {
    test_util::WaitUntilDriveMountPointIsAdded(profile());
  }

  // FileSystemExtensionApiTestBase override.
  void TearDown() override {
    FileSystemExtensionApiTestBase::TearDown();
    ui::SelectFileDialog::SetFactory(nullptr);
  }

 protected:
  // DriveIntegrationService factory function for this test.
  drive::DriveIntegrationService* CreateDriveIntegrationService(
      Profile* profile) {
    // Ignore signin and lock screen apps profile.
    if (ash::IsSigninBrowserContext(profile)) {
      return nullptr;
    }

    // DriveFileSystemExtensionApiTest doesn't expect that several user profiles
    // could exist simultaneously.
    base::FilePath drivefs_mount_point;
    InitializeLocalFileSystem("drive-user/root", &drivefs_root_,
                              &drivefs_mount_point, GetTestDirContents());
    fake_drivefs_helper_ = std::make_unique<drive::FakeDriveFsHelper>(
        profile, drivefs_mount_point.DirName());
    return new drive::DriveIntegrationService(
        g_browser_process->local_state(), profile, "",
        test_cache_root_.GetPath(),
        fake_drivefs_helper_->CreateFakeDriveFsListenerFactory());
  }

  base::ScopedTempDir test_cache_root_;
  base::ScopedTempDir drivefs_root_;
  std::unique_ptr<drive::FakeDriveFsHelper> fake_drivefs_helper_;
  DriveIntegrationServiceFactory::FactoryCallback
      create_drive_integration_service_;
  std::unique_ptr<DriveIntegrationServiceFactory::ScopedFactoryForTest>
      service_factory_for_test_;
};

// Tests for Drive file systems in multi-profile setting.
class MultiProfileDriveFileSystemExtensionApiTest
    : public FileSystemExtensionApiTestBase {
 public:
  MultiProfileDriveFileSystemExtensionApiTest() = default;

  void SetUpCommandLine(base::CommandLine* command_line) override {
    FileSystemExtensionApiTestBase::SetUpCommandLine(command_line);
    // Don't require policy for our sessions - this is required because
    // this test creates a secondary profile synchronously, so we need to
    // let the policy code know not to expect cached policy.
    command_line->AppendSwitchASCII(ash::switches::kProfileRequiresPolicy,
                                    "false");
  }

  void SetUpLocalStatePrefService(PrefService* local_state) override {
    InProcessBrowserTest::SetUpLocalStatePrefService(local_state);

    // Register persisted users.
    user_manager::TestHelper::RegisterPersistedUser(
        *local_state,
        AccountId::FromUserEmailGaiaId("testuser@gmail.com", GaiaId("123456")));
    user_manager::TestHelper::RegisterPersistedUser(
        *local_state, AccountId::FromUserEmailGaiaId(kSecondProfileAccount,
                                                     kSecondProfileGaiaId));
  }

  void SetUpOnMainThread() override {
    // Set up the secondary user session.
    base::FilePath user_data_directory;
    base::PathService::Get(chrome::DIR_USER_DATA, &user_data_directory);
    session_manager::SessionManager::Get()->CreateSession(
        AccountId::FromUserEmailGaiaId(kSecondProfileAccount,
                                       kSecondProfileGaiaId),
        kSecondProfileHash, /*new_user=*/false,
        /*has_active_session=*/false);
    base::FilePath profile_dir = user_data_directory.AppendASCII(
        ash::BrowserContextHelper::GetUserBrowserContextDirName(
            kSecondProfileHash));
    second_profile_ =
        g_browser_process->profile_manager()->GetProfile(profile_dir);

    FileSystemExtensionApiTestBase::SetUpOnMainThread();
  }

  void InitTestFileSystem() override {
    ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir());

    // This callback will get called during Profile creation.
    create_drive_integration_service_ =
        base::BindRepeating(&MultiProfileDriveFileSystemExtensionApiTest::
                                CreateDriveIntegrationService,
                            base::Unretained(this));
    service_factory_for_test_ =
        std::make_unique<DriveIntegrationServiceFactory::ScopedFactoryForTest>(
            &create_drive_integration_service_);
  }

  void AddTestMountPoint() override {
    test_util::WaitUntilDriveMountPointIsAdded(profile());
    test_util::WaitUntilDriveMountPointIsAdded(second_profile_);
  }

 protected:
  // DriveIntegrationService factory function for this test.
  drive::DriveIntegrationService* CreateDriveIntegrationService(
      Profile* profile) {
    // Ignore signin and lock screen apps profile.
    if (ash::IsSigninBrowserContext(profile)) {
      return nullptr;
    }

    base::FilePath cache_dir;
    base::CreateTemporaryDirInDir(tmp_dir_.GetPath(),
                                  base::FilePath::StringType(), &cache_dir);

    base::FilePath drivefs_dir;
    base::CreateTemporaryDirInDir(tmp_dir_.GetPath(),
                                  base::FilePath::StringType(), &drivefs_dir);
    auto profile_name_storage = profile->GetBaseName().value();
    std::string_view profile_name = profile_name_storage;
    if (base::StartsWith(profile_name, "u-")) {
      profile_name = profile_name.substr(2);
    }
    drivefs_dir = drivefs_dir.Append(base::StrCat({"drive-", profile_name}));
    auto test_dir = drivefs_dir.Append("root/test_dir");
    CHECK(base::CreateDirectory(test_dir));
    CHECK(google_apis::test_util::WriteStringToFile(
        test_dir.AppendASCII("test_file.tiff"), kTestFileContent));
    CHECK(google_apis::test_util::WriteStringToFile(
        test_dir.AppendASCII("hosted_doc.gdoc"), kTestFileContent));

    const auto& drivefs_helper = fake_drivefs_helpers_[profile] =
        std::make_unique<drive::FakeDriveFsHelper>(profile, drivefs_dir);
    return new drive::DriveIntegrationService(
        g_browser_process->local_state(), profile, std::string(), cache_dir,
        drivefs_helper->CreateFakeDriveFsListenerFactory());
  }

  base::ScopedTempDir tmp_dir_;
  DriveIntegrationServiceFactory::FactoryCallback
      create_drive_integration_service_;
  std::unique_ptr<DriveIntegrationServiceFactory::ScopedFactoryForTest>
      service_factory_for_test_;
  raw_ptr<Profile, DanglingUntriaged> second_profile_ = nullptr;
  std::unordered_map<Profile*, std::unique_ptr<drive::FakeDriveFsHelper>>
      fake_drivefs_helpers_;
};

class LocalAndDriveFileSystemExtensionApiTest
    : public FileSystemExtensionApiTestBase {
 public:
  LocalAndDriveFileSystemExtensionApiTest() = default;
  ~LocalAndDriveFileSystemExtensionApiTest() override = default;

  // FileSystemExtensionApiTestBase override.
  void InitTestFileSystem() override {
    ASSERT_TRUE(InitializeLocalFileSystem(kLocalMountPointName, &local_tmp_dir_,
                                          &local_mount_point_dir_,
                                          GetTestDirContents()))
        << "Failed to initialize file system.";

    // Set up cache root to be used by DriveIntegrationService. This has to be
    // done before the browser is created because the service instance is
    // initialized by EventRouter.
    ASSERT_TRUE(test_cache_root_.CreateUniqueTempDir());

    // This callback will get called during Profile creation.
    create_drive_integration_service_ = base::BindRepeating(
        &LocalAndDriveFileSystemExtensionApiTest::CreateDriveIntegrationService,
        base::Unretained(this));
    service_factory_for_test_ =
        std::make_unique<DriveIntegrationServiceFactory::ScopedFactoryForTest>(
            &create_drive_integration_service_);
  }

  // FileSystemExtensionApiTestBase override.
  void AddTestMountPoint() override {
    EXPECT_TRUE(profile()->GetMountPoints()->RegisterFileSystem(
        kLocalMountPointName, storage::kFileSystemTypeLocal,
        storage::FileSystemMountOption(), local_mount_point_dir_));
    VolumeManager::Get(profile())->AddVolumeForTesting(
        local_mount_point_dir_, VOLUME_TYPE_TESTING, ash::DeviceType::kUnknown,
        false /* read_only */);
    test_util::WaitUntilDriveMountPointIsAdded(profile());
  }

 protected:
  // DriveIntegrationService factory function for this test.
  drive::DriveIntegrationService* CreateDriveIntegrationService(
      Profile* profile) {
    // Ignore signin and lock screen apps profile.
    if (ash::IsSigninBrowserContext(profile)) {
      return nullptr;
    }

    // LocalAndDriveFileSystemExtensionApiTest doesn't expect that several user
    // profiles could exist simultaneously.
    base::FilePath drivefs_mount_point;
    InitializeLocalFileSystem("drive-user/root", &drivefs_root_,
                              &drivefs_mount_point, GetTestDirContents());
    fake_drivefs_helper_ = std::make_unique<drive::FakeDriveFsHelper>(
        profile, drivefs_mount_point.DirName());
    return new drive::DriveIntegrationService(
        g_browser_process->local_state(), profile, "",
        test_cache_root_.GetPath(),
        fake_drivefs_helper_->CreateFakeDriveFsListenerFactory());
  }

 private:
  // For local volume.
  base::ScopedTempDir local_tmp_dir_;
  base::FilePath local_mount_point_dir_;

  // For drive volume.
  base::ScopedTempDir test_cache_root_;
  base::ScopedTempDir drivefs_root_;
  std::unique_ptr<drive::FakeDriveFsHelper> fake_drivefs_helper_;
  DriveIntegrationServiceFactory::FactoryCallback
      create_drive_integration_service_;
  std::unique_ptr<DriveIntegrationServiceFactory::ScopedFactoryForTest>
      service_factory_for_test_;
};

// Mixin for starting one of the FileSystem test fixures with a specific app
// configuration, which may include default-installed apps. Currently set up
// to run with the chrome://media-app.
class FileSystemExtensionApiTestWithApps
    : public LocalFileSystemExtensionApiTest {
 public:
  FileSystemExtensionApiTestWithApps() = default;

  // FileManagerPrivateApiTest:
  void SetUpOnMainThread() override {
    Profile* profile = browser()->profile();
    file_manager::test::AddDefaultComponentExtensionsOnMainThread(profile);
    ash::SystemWebAppManager::GetForTest(profile)
        ->InstallSystemAppsForTesting();
    LocalFileSystemExtensionApiTest::SetUpOnMainThread();
  }

  std::vector<TestDirConfig> GetTestDirContents() override {
    return {{kArbitraryTime, kArbitraryTime, "test_file.png"},
            {kArbitraryTime, kArbitraryTime, "test_file.arw"}};
  }
};

namespace {

// Constants from app_service_metrics.cc.
constexpr int kGalleryUmaBucket = 13;
constexpr int kMediaAppUmaBucket = 19;

// Metric recorded as the result of the call to apps::RecordAppLaunch().
constexpr char kAppLaunchMetric[] = "Apps.DefaultAppLaunch.FromFileManager";

}  // namespace

// Check the interception of ExecuteTask calls to replace Gallery for PNGs. The
// Media App should always be used in this case.
// TODO(crbug.com/402514601): Test is flaky.
IN_PROC_BROWSER_TEST_F(FileSystemExtensionApiTestWithApps,
                       DISABLED_OpenGalleryForPng) {
  base::HistogramTester histogram_tester;
  EXPECT_TRUE(RunBackgroundPageTestCase("open_gallery",
                                        "testPngOpensGalleryReturnsOpened"))
      << message_;
  histogram_tester.ExpectBucketCount(kAppLaunchMetric, kGalleryUmaBucket, 0);
  histogram_tester.ExpectBucketCount(kAppLaunchMetric, kMediaAppUmaBucket, 1);
}

//
// LocalFileSystemExtensionApiTests.
//

IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, FileSystemOperations) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/filesystem_operations_test",
      FILE_PATH_LITERAL("manifest.json"), "", FLAGS_NONE))
      << message_;
}

IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, FileWatch) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest("file_browser/file_watcher_test",
                                            FILE_PATH_LITERAL("manifest.json"),
                                            "", FLAGS_NONE))
      << message_;
}

IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, FileBrowserHandlers) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/handler_test_runner", FILE_PATH_LITERAL("manifest.json"),
      "file_browser/file_browser_handler", FLAGS_USE_FILE_HANDLER))
      << message_;
}

IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest,
                       FileBrowserHandlersLazy) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/handler_test_runner", FILE_PATH_LITERAL("manifest.json"),
      "file_browser/file_browser_handler_lazy",
      FLAGS_USE_FILE_HANDLER | FLAGS_LAZY_FILE_HANDLER))
      << message_;
}

IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, AppFileHandler) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/handler_test_runner", FILE_PATH_LITERAL("manifest.json"),
      "file_browser/app_file_handler",
      FLAGS_USE_FILE_HANDLER | FLAGS_CHROME_APP))
      << message_;
}

IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, DefaultFileHandler) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest("file_browser/default_file_handler",
                                            FILE_PATH_LITERAL("manifest.json"),
                                            "", FLAGS_NONE))
      << message_;
}

//
// DriveFileSystemExtensionApiTests.
//
// This test is flaky. See https://crbug.com/1008880.
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest,
                       DISABLED_FileSystemOperations) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/filesystem_operations_test",
      FILE_PATH_LITERAL("manifest.json"), "", FLAGS_NONE))
      << message_;
}

IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, DISABLED_FileWatch) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest("file_browser/file_watcher_test",
                                            FILE_PATH_LITERAL("manifest.json"),
                                            "", FLAGS_NONE))
      << message_;
}

IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, FileBrowserHandlers) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/handler_test_runner", FILE_PATH_LITERAL("manifest.json"),
      "file_browser/file_browser_handler", FLAGS_USE_FILE_HANDLER))
      << message_;
}

IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, Search) {
  // Configure the drive service to return only one search result at a time
  // to simulate paginated searches.
  EXPECT_TRUE(RunFileSystemExtensionApiTest("file_browser/drive_search_test",
                                            FILE_PATH_LITERAL("manifest.json"),
                                            "", FLAGS_NONE))
      << message_;
}

IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, AppFileHandler) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/handler_test_runner", FILE_PATH_LITERAL("manifest.json"),
      "file_browser/app_file_handler",
      FLAGS_USE_FILE_HANDLER | FLAGS_CHROME_APP))
      << message_;
}

IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, RetainEntry) {
  ui::SelectFileDialog::SetFactory(
      std::make_unique<content::FakeSelectFileDialogFactory>(
          std::vector<base::FilePath>{
              drivefs_root_.GetPath().Append("drive-user/root/test_dir")}));
  EXPECT_TRUE(RunFileSystemExtensionApiTest("file_browser/retain_entry",
                                            FILE_PATH_LITERAL("manifest.json"),
                                            "", FLAGS_NONE))
      << message_;
}

IN_PROC_BROWSER_TEST_F(MultiProfileDriveFileSystemExtensionApiTest,
                       CrossProfileCopy) {
  // IOTask only sends progress update to JS/renderer when there is a Files app
  // window open, so we need to force it to send progress in the test.
  auto* event_router =
      file_manager::EventRouterFactory::GetForProfile(profile());
  event_router->ForceBroadcastingForTesting(true);
  EXPECT_TRUE(RunFileSystemExtensionApiTest("file_browser/multi_profile_copy",
                                            FILE_PATH_LITERAL("manifest.json"),
                                            "", FLAGS_NONE))
      << message_;
}

//
// LocalAndDriveFileSystemExtensionApiTests.
IN_PROC_BROWSER_TEST_F(LocalAndDriveFileSystemExtensionApiTest,
                       AppFileHandlerMulti) {
  EXPECT_TRUE(RunFileSystemExtensionApiTest(
      "file_browser/app_file_handler_multi", FILE_PATH_LITERAL("manifest.json"),
      "", FLAGS_NONE))
      << message_;
}
}  // namespace
}  // namespace file_manager