-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
web_app_file_handling_browsertest.cc
775 lines (648 loc) · 30.3 KB
/
web_app_file_handling_browsertest.cc
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
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/apps/app_service/app_launch_params.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/browser_app_launcher.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/ui/web_applications/web_app_controller_browsertest.h"
#include "chrome/browser/web_applications/components/app_registrar.h"
#include "chrome/browser/web_applications/components/file_handler_manager.h"
#include "chrome/browser/web_applications/components/os_integration_manager.h"
#include "chrome/browser/web_applications/components/web_app_constants.h"
#include "chrome/browser/web_applications/components/web_app_prefs_utils.h"
#include "chrome/browser/web_applications/components/web_app_provider_base.h"
#include "chrome/browser/web_applications/components/web_application_info.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/embedder_support/switches.h"
#include "components/policy/core/browser/browser_policy_connector.h"
#include "components/policy/core/common/mock_configuration_policy_provider.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/url_loader_interceptor.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/web_launch/file_handling_expiry.mojom-test-utils.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/chromeos/file_manager/file_manager_test_util.h"
#endif
// A fake file handling expiry service. This service allows us to mock having an
// origin trial which expires having a certain time, without needing to manage
// actual origin trial tokens.
class FakeFileHandlingExpiryService
: public blink::mojom::FileHandlingExpiryInterceptorForTesting {
public:
FakeFileHandlingExpiryService()
: expiry_time_(base::Time::Now() + base::TimeDelta::FromDays(1)) {}
blink::mojom::FileHandlingExpiry* GetForwardingInterface() override {
NOTREACHED();
return nullptr;
}
void Bind(mojo::ScopedInterfaceEndpointHandle handle) {
receiver_.reset();
receiver_.Bind(
mojo::PendingAssociatedReceiver<blink::mojom::FileHandlingExpiry>(
std::move(handle)));
}
void SetExpiryTime(base::Time expiry_time) { expiry_time_ = expiry_time; }
void RequestOriginTrialExpiryTime(
RequestOriginTrialExpiryTimeCallback callback) override {
if (before_reply_callback_) {
std::move(before_reply_callback_).Run();
}
std::move(callback).Run(expiry_time_);
}
// Set a callback to be called before FileHandlingExpiry interface replies
// the expiry time. Useful for testing inflight IPC.
void SetBeforeReplyCallback(base::RepeatingClosure before_reply_callback) {
before_reply_callback_ = before_reply_callback;
}
private:
base::Time expiry_time_;
RequestOriginTrialExpiryTimeCallback callback_;
base::RepeatingClosure before_reply_callback_;
mojo::AssociatedReceiver<blink::mojom::FileHandlingExpiry> receiver_{this};
};
class WebAppFileHandlingTestBase : public web_app::WebAppControllerBrowserTest {
public:
web_app::WebAppProviderBase* provider() {
return web_app::WebAppProviderBase::GetProviderBase(profile());
}
web_app::FileHandlerManager& file_handler_manager() {
return provider()
->os_integration_manager()
.file_handler_manager_for_testing();
}
web_app::AppRegistrar& registrar() { return provider()->registrar(); }
GURL GetSecureAppURL() {
return https_server()->GetURL("app.com", "/ssl/google.html");
}
GURL GetTextFileHandlerActionURL() {
return https_server()->GetURL("app.com", "/ssl/blank_page.html");
}
GURL GetCSVFileHandlerActionURL() {
return https_server()->GetURL("app.com", "/ssl/page_with_refs.html");
}
GURL GetHTMLFileHandlerActionURL() {
return https_server()->GetURL("app.com", "/ssl/page_with_frame.html");
}
void InstallFileHandlingPWA() {
GURL url = GetSecureAppURL();
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->start_url = url;
web_app_info->scope = url.GetWithoutFilename();
web_app_info->title = u"A Hosted App";
// Basic plain text format.
blink::Manifest::FileHandler entry1;
entry1.action = GetTextFileHandlerActionURL();
entry1.name = u"text";
entry1.accept[u"text/*"].push_back(u".txt");
web_app_info->file_handlers.push_back(std::move(entry1));
// A format that the browser is also a handler for, to confirm that the
// browser doesn't override PWAs using File Handling for types that the
// browser also handles.
blink::Manifest::FileHandler entry2;
entry2.action = GetHTMLFileHandlerActionURL();
entry2.name = u"html";
entry2.accept[u"text/html"].push_back(u".html");
web_app_info->file_handlers.push_back(std::move(entry2));
// application/* format.
blink::Manifest::FileHandler entry3;
entry3.action = GetCSVFileHandlerActionURL();
entry3.name = u"csv";
entry3.accept[u"application/csv"].push_back(u".csv");
web_app_info->file_handlers.push_back(std::move(entry3));
app_id_ =
WebAppControllerBrowserTest::InstallWebApp(std::move(web_app_info));
}
protected:
void SetFileHandlingPermission(ContentSetting setting) {
auto* map =
HostContentSettingsMapFactory::GetForProfile(browser()->profile());
map->SetDefaultContentSetting(ContentSettingsType::FILE_HANDLING, setting);
}
const web_app::AppId& app_id() { return app_id_; }
private:
web_app::AppId app_id_;
};
namespace {
base::FilePath NewTestFilePath(const base::StringPiece extension) {
// CreateTemporaryFile blocks, temporarily allow blocking.
base::ScopedAllowBlockingForTesting allow_blocking;
// In order to test file handling, we need to be able to supply a file
// extension for the temp file.
base::FilePath test_file_path;
base::CreateTemporaryFile(&test_file_path);
base::FilePath new_file_path = test_file_path.AddExtensionASCII(extension);
EXPECT_TRUE(base::ReplaceFile(test_file_path, new_file_path, nullptr));
return new_file_path;
}
content::WebContents* LaunchApplication(
Profile* profile,
const std::string& app_id,
const GURL& expected_launch_url,
const apps::mojom::LaunchContainer launch_container =
apps::mojom::LaunchContainer::kLaunchContainerWindow,
const apps::mojom::AppLaunchSource launch_source =
apps::mojom::AppLaunchSource::kSourceTest,
const std::vector<base::FilePath>& files = std::vector<base::FilePath>()) {
apps::AppLaunchParams params(app_id, launch_container,
WindowOpenDisposition::NEW_WINDOW,
launch_source);
if (files.size())
params.launch_files = files;
content::TestNavigationObserver navigation_observer(expected_launch_url);
navigation_observer.StartWatchingNewWebContents();
content::WebContents* web_contents =
apps::AppServiceProxyFactory::GetForProfile(profile)
->BrowserAppLauncher()
->LaunchAppWithParams(std::move(params));
navigation_observer.Wait();
// Attach the launchParams to the window so we can inspect them easily.
auto result = content::EvalJs(web_contents,
"launchQueue.setConsumer(launchParams => {"
" window.launchParams = launchParams;"
"});");
return web_contents;
}
} // namespace
class WebAppFileHandlingBrowserTest : public WebAppFileHandlingTestBase {
public:
WebAppFileHandlingBrowserTest() {
scoped_feature_list_.InitWithFeatures({blink::features::kFileHandlingAPI},
{});
}
content::WebContents* LaunchWithFiles(
const std::string& app_id,
const GURL& expected_launch_url,
const std::vector<base::FilePath>& files,
const apps::mojom::LaunchContainer launch_container =
apps::mojom::LaunchContainer::kLaunchContainerWindow) {
return LaunchApplication(
profile(), app_id, expected_launch_url, launch_container,
apps::mojom::AppLaunchSource::kSourceFileHandler, files);
}
private:
base::test::ScopedFeatureList scoped_feature_list_;
};
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingBrowserTest,
LaunchConsumerIsNotTriggeredWithNoFiles) {
InstallFileHandlingPWA();
SetFileHandlingPermission(CONTENT_SETTING_ALLOW);
content::WebContents* web_contents =
LaunchWithFiles(app_id(), GetSecureAppURL(), {});
EXPECT_EQ(false, content::EvalJs(web_contents, "!!window.launchParams"));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingBrowserTest,
PWAsCanReceiveFileLaunchParams) {
InstallFileHandlingPWA();
SetFileHandlingPermission(CONTENT_SETTING_ALLOW);
base::FilePath test_file_path = NewTestFilePath("txt");
content::WebContents* web_contents = LaunchWithFiles(
app_id(), GetTextFileHandlerActionURL(), {test_file_path});
EXPECT_EQ(1,
content::EvalJs(web_contents, "window.launchParams.files.length"));
EXPECT_EQ(test_file_path.BaseName().AsUTF8Unsafe(),
content::EvalJs(web_contents, "window.launchParams.files[0].name"));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingBrowserTest,
LaunchConsumerIsNotTriggeredWithPermissionDenied) {
InstallFileHandlingPWA();
SetFileHandlingPermission(CONTENT_SETTING_BLOCK);
base::FilePath test_file_path = NewTestFilePath("txt");
content::WebContents* web_contents = LaunchWithFiles(
app_id(), GetTextFileHandlerActionURL(), {test_file_path});
EXPECT_EQ(false, content::EvalJs(web_contents, "!!window.launchParams"));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingBrowserTest,
PWAsCanReceiveFileLaunchParamsInTab) {
InstallFileHandlingPWA();
SetFileHandlingPermission(CONTENT_SETTING_ALLOW);
base::FilePath test_file_path = NewTestFilePath("txt");
content::WebContents* web_contents =
LaunchWithFiles(app_id(), GetTextFileHandlerActionURL(), {test_file_path},
apps::mojom::LaunchContainer::kLaunchContainerTab);
EXPECT_EQ(1,
content::EvalJs(web_contents, "window.launchParams.files.length"));
EXPECT_EQ(test_file_path.BaseName().AsUTF8Unsafe(),
content::EvalJs(web_contents, "window.launchParams.files[0].name"));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingBrowserTest,
PWAsDispatchOnCorrectFileHandlingURL) {
InstallFileHandlingPWA();
SetFileHandlingPermission(CONTENT_SETTING_ALLOW);
// Test that file handler dispatches correct URL based on file extension.
LaunchWithFiles(app_id(), GetSecureAppURL(), {});
LaunchWithFiles(app_id(), GetTextFileHandlerActionURL(),
{NewTestFilePath("txt")});
LaunchWithFiles(app_id(), GetHTMLFileHandlerActionURL(),
{NewTestFilePath("html")});
LaunchWithFiles(app_id(), GetCSVFileHandlerActionURL(),
{NewTestFilePath("csv")});
// Test as above in a tab.
LaunchWithFiles(app_id(), GetSecureAppURL(), {},
apps::mojom::LaunchContainer::kLaunchContainerTab);
LaunchWithFiles(app_id(), GetTextFileHandlerActionURL(),
{NewTestFilePath("txt")},
apps::mojom::LaunchContainer::kLaunchContainerTab);
LaunchWithFiles(app_id(), GetHTMLFileHandlerActionURL(),
{NewTestFilePath("html")},
apps::mojom::LaunchContainer::kLaunchContainerTab);
LaunchWithFiles(app_id(), GetCSVFileHandlerActionURL(),
{NewTestFilePath("csv")},
apps::mojom::LaunchContainer::kLaunchContainerTab);
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingBrowserTest,
UnlimitedFileHandlersForChrome) {
// We install more than |kMaxFileHandlers| file handlers.
const unsigned kNumHandlers = 2 * web_app::kMaxFileHandlers + 1;
auto action_url = [](unsigned index) {
return GURL(base::StringPrintf("chrome://interstitials/#a%u", index));
};
auto mime_type = [](unsigned index) {
return base::StringPrintf("application/x-%u", index);
};
auto extension = [](unsigned index) {
return base::StringPrintf(".e%u", index);
};
web_app::AppId app_id;
{
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->start_url = GURL("chrome://interstitials/");
web_app_info->scope = web_app_info->start_url;
web_app_info->title = u"Many File Handlers";
for (unsigned i = 0; i < kNumHandlers; ++i) {
const std::u16string name =
base::UTF8ToUTF16(base::StringPrintf("n%u", i));
std::map<std::u16string, std::vector<std::u16string>> accept;
accept[base::UTF8ToUTF16(mime_type(i))] = {
base::UTF8ToUTF16(extension(i))};
web_app_info->file_handlers.push_back(
{action_url(i), name, std::move(accept)});
}
app_id =
WebAppControllerBrowserTest::InstallWebApp(std::move(web_app_info));
}
EXPECT_EQ(registrar()
.AsWebAppRegistrar()
->GetAppById(app_id)
->file_handlers()
.size(),
kNumHandlers);
SetFileHandlingPermission(CONTENT_SETTING_ALLOW);
// Test that file handler dispatches correct URL based on file extension.
for (unsigned i = 0; i < kNumHandlers; ++i) {
LaunchWithFiles(app_id, action_url(i), {NewTestFilePath(extension(i))});
}
}
class WebAppFileHandlingOriginTrialBrowserTest
: public WebAppFileHandlingTestBase {
public:
WebAppFileHandlingOriginTrialBrowserTest() {
web_app::FileHandlerManager::DisableAutomaticFileHandlerCleanupForTesting();
}
content::WebContents* web_contents() {
return browser()->tab_strip_model()->GetActiveWebContents();
}
void SetUpOnMainThread() override {
WebAppFileHandlingTestBase::SetUpOnMainThread();
}
void SetUpInterceptorNavigateToAppAndMaybeWait() {
base::RunLoop loop;
file_handler_manager().SetOnFileHandlingExpiryUpdatedForTesting(
loop.QuitClosure());
web_contents()
->GetMainFrame()
->GetRemoteAssociatedInterfaces()
->OverrideBinderForTesting(
blink::mojom::FileHandlingExpiry::Name_,
base::BindRepeating(&FakeFileHandlingExpiryService::Bind,
base::Unretained(&file_handling_expiry_)));
NavigateInRenderer(web_contents(), GetSecureAppURL());
// The expiry time is only updated if the app is installed.
if (registrar().IsInstalled(app_id()))
loop.Run();
}
protected:
FakeFileHandlingExpiryService& file_handling_expiry() {
return file_handling_expiry_;
}
private:
FakeFileHandlingExpiryService file_handling_expiry_;
};
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
FileHandlingIsNotAvailableUntilOriginTrialIsChecked) {
InstallFileHandlingPWA();
// We haven't navigated to the app, so we don't know if it's allowed to handle
// files.
EXPECT_FALSE(file_handler_manager().IsFileHandlingAPIAvailable(app_id()));
EXPECT_FALSE(file_handler_manager().AreFileHandlersEnabled(app_id()));
// Navigating to the app should update the origin trial expiry (and allow it
// to handle files).
SetUpInterceptorNavigateToAppAndMaybeWait();
EXPECT_TRUE(file_handler_manager().IsFileHandlingAPIAvailable(app_id()));
EXPECT_TRUE(file_handler_manager().AreFileHandlersEnabled(app_id()));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
FileHandlingOriginTrialIsCheckedAtInstallation) {
// Navigate to the app's launch url, so the origin trial token can be checked.
SetUpInterceptorNavigateToAppAndMaybeWait();
base::RunLoop loop;
file_handler_manager().SetOnFileHandlingExpiryUpdatedForTesting(
loop.QuitClosure());
InstallFileHandlingPWA();
loop.Run();
EXPECT_TRUE(file_handler_manager().IsFileHandlingAPIAvailable(app_id()));
EXPECT_TRUE(file_handler_manager().AreFileHandlersEnabled(app_id()));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
WhenOriginTrialHasExpiredFileHandlersAreNotAvailable) {
InstallFileHandlingPWA();
SetUpInterceptorNavigateToAppAndMaybeWait();
EXPECT_TRUE(file_handler_manager().AreFileHandlersEnabled(app_id()));
// Set the token's expiry to some time in the past.
file_handling_expiry().SetExpiryTime(base::Time());
// Refresh the page, to receive the updated expiry time.
SetUpInterceptorNavigateToAppAndMaybeWait();
EXPECT_FALSE(file_handler_manager().AreFileHandlersEnabled(app_id()));
EXPECT_FALSE(file_handler_manager().GetEnabledFileHandlers(app_id()));
}
// Tests that expired file handlers are cleaned up.
// Part 1: Install a file handling app and set it's expiry time to some time in
// the past.
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
PRE_ExpiredTrialHandlersAreCleanedUpAtLaunch) {
InstallFileHandlingPWA();
SetUpInterceptorNavigateToAppAndMaybeWait();
EXPECT_TRUE(file_handler_manager().AreFileHandlersEnabled(app_id()));
// Update the expiry time to be in the past.
web_app::UpdateDoubleWebAppPref(profile()->GetPrefs(), app_id(),
web_app::kFileHandlingOriginTrialExpiryTime,
base::Time().ToDoubleT());
}
// Part 2: Test that expired file handlers for an app are cleaned up.
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
ExpiredTrialHandlersAreCleanedUpAtLaunch) {
EXPECT_EQ(1, file_handler_manager().TriggerFileHandlerCleanupForTesting());
}
// Tests that non expired file handlers are not cleaned up.
// Part 1: Install an app with valid file handlers.
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
PRE_ValidFileHandlerAreNotCleanedUpAtLaunch) {
InstallFileHandlingPWA();
SetUpInterceptorNavigateToAppAndMaybeWait();
EXPECT_TRUE(file_handler_manager().AreFileHandlersEnabled(app_id()));
}
// Part 2: Test that expired file handlers for an app are cleaned up.
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
ValidFileHandlerAreNotCleanedUpAtLaunch) {
EXPECT_EQ(0, file_handler_manager().TriggerFileHandlerCleanupForTesting());
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
DisableForceEnabledFileHandlingOriginTrial) {
InstallFileHandlingPWA();
SetUpInterceptorNavigateToAppAndMaybeWait();
ASSERT_TRUE(file_handler_manager().AreFileHandlersEnabled(app_id()));
ASSERT_TRUE(file_handler_manager().GetEnabledFileHandlers(app_id()));
// Calling this on non-force-enabled origin trial should have no effect.
file_handler_manager().DisableForceEnabledFileHandlingOriginTrial(app_id());
EXPECT_TRUE(file_handler_manager().AreFileHandlersEnabled(app_id()));
EXPECT_TRUE(file_handler_manager().GetEnabledFileHandlers(app_id()));
// Force enables file handling.
file_handler_manager().ForceEnableFileHandlingOriginTrial(app_id());
// Calling this on force enabled origin trial should remove file handlers.
file_handler_manager().DisableForceEnabledFileHandlingOriginTrial(app_id());
EXPECT_FALSE(file_handler_manager().AreFileHandlersEnabled(app_id()));
EXPECT_EQ(nullptr, file_handler_manager().GetEnabledFileHandlers(app_id()));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
ForceEnabledFileHandling_IgnoreExpiryTimeUpdate) {
InstallFileHandlingPWA();
SetUpInterceptorNavigateToAppAndMaybeWait();
EXPECT_FALSE(file_handler_manager().IsFileHandlingForceEnabled(app_id()));
// Force enables file handling.
file_handler_manager().ForceEnableFileHandlingOriginTrial(app_id());
EXPECT_TRUE(file_handler_manager().IsFileHandlingForceEnabled(app_id()));
// Update origin trial expiry time from the App's WebContents.
base::RunLoop loop;
file_handler_manager().SetOnFileHandlingExpiryUpdatedForTesting(
loop.QuitClosure());
file_handling_expiry().SetExpiryTime(base::Time());
file_handler_manager().MaybeUpdateFileHandlingOriginTrialExpiry(
web_contents(), app_id());
loop.Run();
// Force enabled file handling should not be updated by the expiry time in
// App's WebContents (i.e. origin trial token expiry).
EXPECT_TRUE(file_handler_manager().IsFileHandlingForceEnabled(app_id()));
EXPECT_TRUE(file_handler_manager().IsFileHandlingAPIAvailable(app_id()));
EXPECT_TRUE(file_handler_manager().GetEnabledFileHandlers(app_id()));
}
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialBrowserTest,
ForceEnabledFileHandling_IgnoreExpiryTimeInflightIPC) {
InstallFileHandlingPWA();
SetUpInterceptorNavigateToAppAndMaybeWait();
EXPECT_FALSE(file_handler_manager().IsFileHandlingForceEnabled(app_id()));
// Request to update origin trial expiry time from the App's WebContents, and
// force enables file handling origin trial before the expiry time reply is
// received.
base::RunLoop loop;
file_handler_manager().SetOnFileHandlingExpiryUpdatedForTesting(
loop.QuitClosure());
file_handling_expiry().SetExpiryTime(base::Time());
file_handling_expiry().SetBeforeReplyCallback(
base::BindLambdaForTesting([&]() {
EXPECT_FALSE(
file_handler_manager().IsFileHandlingForceEnabled(app_id()));
file_handler_manager().ForceEnableFileHandlingOriginTrial(app_id());
}));
EXPECT_FALSE(file_handler_manager().IsFileHandlingForceEnabled(app_id()));
file_handler_manager().MaybeUpdateFileHandlingOriginTrialExpiry(
web_contents(), app_id());
loop.Run();
// Force enabled file handling should not be updated by the inflight expiry
// time IPC.
EXPECT_TRUE(file_handler_manager().IsFileHandlingForceEnabled(app_id()));
EXPECT_TRUE(file_handler_manager().IsFileHandlingAPIAvailable(app_id()));
EXPECT_TRUE(file_handler_manager().GetEnabledFileHandlers(app_id()));
}
namespace {
constexpr char kBaseDataDir[] = "chrome/test/data/web_app_file_handling";
// This is the public key of tools/origin_trials/eftest.key, used to validate
// origin trial tokens generated by tools/origin_trials/generate_token.py.
constexpr char kOriginTrialPublicKeyForTesting[] =
"dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA=";
} // namespace
class WebAppFileHandlingOriginTrialTest
: public web_app::WebAppControllerBrowserTest {
public:
void SetUpCommandLine(base::CommandLine* command_line) override {
WebAppControllerBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(embedder_support::kOriginTrialPublicKey,
kOriginTrialPublicKeyForTesting);
}
void TearDownOnMainThread() override { interceptor_.reset(); }
protected:
void GrantFileHandlingPermission() {
auto* map =
HostContentSettingsMapFactory::GetForProfile(browser()->profile());
map->SetDefaultContentSetting(ContentSettingsType::FILE_HANDLING,
CONTENT_SETTING_ALLOW);
}
web_app::AppId InstallFileHandlingWebApp(GURL* start_url_out = nullptr) {
std::string origin = "https://file-handling-pwa";
// We need to use URLLoaderInterceptor (rather than a EmbeddedTestServer),
// because origin trial token is associated with a fixed origin, whereas
// EmbeddedTestServer serves content on a random port.
interceptor_ =
content::URLLoaderInterceptor::ServeFilesFromDirectoryAtOrigin(
kBaseDataDir, GURL(origin));
GURL start_url = GURL(origin + "/index.html");
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->start_url = start_url;
web_app_info->scope = start_url.GetWithoutFilename();
web_app_info->title = u"A Web App";
blink::Manifest::FileHandler entry1;
entry1.action = start_url;
entry1.name = u"text";
entry1.accept[u"text/*"].push_back(u".txt");
web_app_info->file_handlers.push_back(std::move(entry1));
web_app::AppId app_id =
WebAppControllerBrowserTest::InstallWebApp(std::move(web_app_info));
// Here we need first launch the App, so it can update the origin trial
// expiry time in prefs. This is needed because the above InstallWebApp
// invocation bypassed the normal Web App install pipeline.
content::WebContents* web_content =
LaunchApplication(profile(), app_id, start_url);
web_content->Close();
if (start_url_out)
*start_url_out = start_url;
return app_id;
}
private:
std::unique_ptr<content::URLLoaderInterceptor> interceptor_;
};
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialTest,
LaunchParamsArePassedCorrectly) {
GURL start_url;
const web_app::AppId app_id = InstallFileHandlingWebApp(&start_url);
GrantFileHandlingPermission();
base::FilePath test_file_path = NewTestFilePath("txt");
content::WebContents* web_content = LaunchApplication(
profile(), app_id, start_url,
apps::mojom::LaunchContainer::kLaunchContainerWindow,
apps::mojom::AppLaunchSource::kSourceFileHandler, {test_file_path});
EXPECT_EQ(1,
content::EvalJs(web_content, "window.launchParams.files.length"));
EXPECT_EQ(test_file_path.BaseName().AsUTF8Unsafe(),
content::EvalJs(web_content, "window.launchParams.files[0].name"));
}
class WebAppFileHandlingPolicyBrowserTest
: public WebAppFileHandlingBrowserTest {
public:
// Set the file handling policy to BLOCK the app between the PRE test and the
// actual test.
void SetUpInProcessBrowserTestFixture() override {
if (GetTestPreCount() == 0) {
SetFileHandlingBlockPolicy();
}
}
private:
void SetFileHandlingBlockPolicy() {
ON_CALL(provider_, IsInitializationComplete(testing::_))
.WillByDefault(testing::Return(true));
ON_CALL(provider_, IsFirstPolicyLoadComplete(testing::_))
.WillByDefault(testing::Return(true));
policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
policy::PolicyMap values;
base::Value list(base::Value::Type::LIST);
list.Append(base::Value("https://app.com"));
policy::PolicyMap::Entry entry_list(
policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE,
policy::POLICY_SOURCE_CLOUD, std::move(list), nullptr);
values.Set(policy::key::kFileHandlingBlockedForUrls, std::move(entry_list));
provider_.UpdateChromePolicy(values);
}
testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_;
};
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingPolicyBrowserTest,
PRE_PolicySettingsBlockedUrl) {
InstallFileHandlingPWA();
EXPECT_EQ(registrar().GetAppIds().size(), 1u);
EXPECT_FALSE(registrar()
.AsWebAppRegistrar()
->GetAppById(app_id())
->file_handler_permission_blocked());
}
// Test that the app's `file_handler_permission_blocked` state should be updated
// on WebAppProvider system setup based on current permission settings.
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingPolicyBrowserTest,
PolicySettingsBlockedUrl) {
auto* provider = web_app::WebAppProvider::Get(profile());
DCHECK(provider);
web_app::test::WaitUntilReady(provider);
std::vector<web_app::AppId> app_ids = registrar().GetAppIds();
EXPECT_EQ(app_ids.size(), 1u);
EXPECT_TRUE(registrar()
.AsWebAppRegistrar()
->GetAppById(app_ids[0])
->file_handler_permission_blocked());
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// End-to-end test to ensure the file handler is registered on ChromeOS when the
// extension system is initialized. Gives more coverage than the unit tests for
// web_file_tasks.cc.
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialTest,
IsFileHandlerOnChromeOS) {
const web_app::AppId app_id = InstallFileHandlingWebApp();
GrantFileHandlingPermission();
base::FilePath test_file_path = NewTestFilePath("txt");
std::vector<file_manager::file_tasks::FullTaskDescriptor> tasks =
file_manager::test::GetTasksForFile(profile(), test_file_path);
// Note that there are normally multiple tasks due to default-installed
// handlers (e.g. add to zip file). But those handlers are not installed by
// default in browser tests.
EXPECT_EQ(1u, tasks.size());
EXPECT_EQ(tasks[0].task_descriptor().app_id, app_id);
}
// Ensures correct behavior for files on "special volumes", such as file systems
// provided by extensions. These do not have local files (i.e. backed by
// inodes).
IN_PROC_BROWSER_TEST_F(WebAppFileHandlingOriginTrialTest,
NotHandlerForNonNativeFiles) {
const web_app::AppId app_id = InstallFileHandlingWebApp();
GrantFileHandlingPermission();
base::WeakPtr<file_manager::Volume> fsp_volume =
file_manager::test::InstallFileSystemProviderChromeApp(profile());
// File in chrome/test/data/extensions/api_test/file_browser/image_provider/.
base::FilePath test_file_path =
fsp_volume->mount_path().AppendASCII("readonly.txt");
std::vector<file_manager::file_tasks::FullTaskDescriptor> tasks =
file_manager::test::GetTasksForFile(profile(), test_file_path);
// Current expectation is for the task not to be found while the native
// filesystem API is still being built up. See https://crbug.com/1079065.
// When the "special file" check in file_manager::file_tasks::FindWebTasks()
// is removed, this test should work the same as IsFileHandlerOnChromeOS.
EXPECT_EQ(0u, tasks.size());
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)