Remove ExtensionPrefs::SetDidExtensionEscalatePermissions.
[chromium-blink-merge.git] / chrome / browser / apps / ephemeral_app_browsertest.cc
blobde35c13fde5b5ce6a4e49522908a1b42eb8b866c
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/apps/ephemeral_app_browsertest.h"
7 #include <vector>
9 #include "apps/app_restore_service.h"
10 #include "apps/saved_files_service.h"
11 #include "base/files/scoped_temp_dir.h"
12 #include "base/scoped_observer.h"
13 #include "base/stl_util.h"
14 #include "chrome/browser/apps/app_browsertest_util.h"
15 #include "chrome/browser/apps/ephemeral_app_service.h"
16 #include "chrome/browser/extensions/api/file_system/file_system_api.h"
17 #include "chrome/browser/extensions/app_sync_data.h"
18 #include "chrome/browser/extensions/extension_service.h"
19 #include "chrome/browser/extensions/extension_sync_service.h"
20 #include "chrome/browser/extensions/extension_util.h"
21 #include "chrome/browser/notifications/desktop_notification_service.h"
22 #include "chrome/browser/notifications/desktop_notification_service_factory.h"
23 #include "content/public/browser/power_save_blocker.h"
24 #include "content/public/test/browser_test.h"
25 #include "content/public/test/test_utils.h"
26 #include "extensions/browser/api/power/power_api.h"
27 #include "extensions/browser/app_sorting.h"
28 #include "extensions/browser/event_router.h"
29 #include "extensions/browser/extension_prefs.h"
30 #include "extensions/browser/extension_registry.h"
31 #include "extensions/browser/extension_registry_observer.h"
32 #include "extensions/browser/extension_system.h"
33 #include "extensions/browser/extension_util.h"
34 #include "extensions/browser/process_manager.h"
35 #include "extensions/browser/test_extension_registry_observer.h"
36 #include "extensions/browser/uninstall_reason.h"
37 #include "extensions/common/api/alarms.h"
38 #include "extensions/common/extension.h"
39 #include "extensions/test/extension_test_message_listener.h"
40 #include "extensions/test/result_catcher.h"
41 #include "sync/api/fake_sync_change_processor.h"
42 #include "sync/api/sync_change_processor_wrapper_for_test.h"
43 #include "sync/api/sync_error_factory_mock.h"
44 #include "ui/app_list/app_list_switches.h"
45 #include "ui/message_center/message_center.h"
46 #include "ui/message_center/notifier_settings.h"
48 using extensions::AppSyncData;
49 using extensions::Event;
50 using extensions::EventRouter;
51 using extensions::Extension;
52 using extensions::ExtensionPrefs;
53 using extensions::ExtensionRegistry;
54 using extensions::ExtensionRegistryObserver;
55 using extensions::ExtensionSystem;
56 using extensions::Manifest;
57 using extensions::ResultCatcher;
59 namespace {
61 namespace alarms = extensions::core_api::alarms;
63 const char kPowerTestApp[] = "ephemeral_apps/power";
65 // Enabling sync causes these tests to be flaky on Windows. Disable sync so that
66 // everything else can be tested. See crbug.com/401028
67 #if defined(OS_WIN)
68 const bool kEnableSync = false;
69 #else
70 const bool kEnableSync = true;
71 #endif
73 typedef std::vector<message_center::Notifier*> NotifierList;
75 bool IsNotifierInList(const message_center::NotifierId& notifier_id,
76 const NotifierList& notifiers) {
77 for (NotifierList::const_iterator it = notifiers.begin();
78 it != notifiers.end(); ++it) {
79 const message_center::Notifier* notifier = *it;
80 if (notifier->notifier_id == notifier_id)
81 return true;
84 return false;
87 // Saves some parameters from the extension installed notification in order
88 // to verify them in tests.
89 class InstallObserver : public ExtensionRegistryObserver {
90 public:
91 struct InstallParameters {
92 std::string id;
93 bool is_update;
94 bool from_ephemeral;
96 InstallParameters(
97 const std::string& id,
98 bool is_update,
99 bool from_ephemeral)
100 : id(id), is_update(is_update), from_ephemeral(from_ephemeral) {}
103 explicit InstallObserver(Profile* profile) : registry_observer_(this) {
104 registry_observer_.Add(ExtensionRegistry::Get(profile));
107 ~InstallObserver() override {}
109 const InstallParameters& Last() {
110 CHECK(!install_params_.empty());
111 return install_params_.back();
114 private:
115 void OnExtensionWillBeInstalled(content::BrowserContext* browser_context,
116 const Extension* extension,
117 bool is_update,
118 bool from_ephemeral,
119 const std::string& old_name) override {
120 install_params_.push_back(
121 InstallParameters(extension->id(), is_update, from_ephemeral));
124 std::vector<InstallParameters> install_params_;
125 ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
126 registry_observer_;
129 // Instead of actually changing the system power settings, tests will just
130 // issue requests to this mock.
131 class PowerSettingsMock {
132 public:
133 PowerSettingsMock() : keep_awake_count_(0) {}
135 void request_keep_awake() { ++keep_awake_count_; }
137 void release_keep_awake() {
138 --keep_awake_count_;
139 ASSERT_GE(keep_awake_count_, 0);
142 int keep_awake_count() const { return keep_awake_count_; }
144 private:
145 int keep_awake_count_;
147 DISALLOW_COPY_AND_ASSIGN(PowerSettingsMock);
150 // Stub implementation of content::PowerSaveBlocker that updates the
151 // PowerSettingsMock.
152 class PowerSaveBlockerStub : public content::PowerSaveBlocker {
153 public:
154 explicit PowerSaveBlockerStub(PowerSettingsMock* power_settings)
155 : power_settings_(power_settings) {
156 power_settings_->request_keep_awake();
159 ~PowerSaveBlockerStub() override { power_settings_->release_keep_awake(); }
161 static scoped_ptr<PowerSaveBlocker> Create(PowerSettingsMock* power_settings,
162 PowerSaveBlockerType type,
163 Reason reason,
164 const std::string& description) {
165 return scoped_ptr<PowerSaveBlocker>(
166 new PowerSaveBlockerStub(power_settings));
169 private:
170 PowerSettingsMock* power_settings_; // Not owned.
172 DISALLOW_COPY_AND_ASSIGN(PowerSaveBlockerStub);
175 } // namespace
178 // EphemeralAppTestBase:
180 const char EphemeralAppTestBase::kMessagingReceiverApp[] =
181 "ephemeral_apps/messaging_receiver";
182 const char EphemeralAppTestBase::kMessagingReceiverAppV2[] =
183 "ephemeral_apps/messaging_receiver2";
184 const char EphemeralAppTestBase::kDispatchEventTestApp[] =
185 "ephemeral_apps/dispatch_event";
186 const char EphemeralAppTestBase::kNotificationsTestApp[] =
187 "ephemeral_apps/notification_settings";
188 const char EphemeralAppTestBase::kFileSystemTestApp[] =
189 "ephemeral_apps/filesystem_retain_entries";
191 EphemeralAppTestBase::EphemeralAppTestBase() {}
193 EphemeralAppTestBase::~EphemeralAppTestBase() {}
195 void EphemeralAppTestBase::SetUpCommandLine(base::CommandLine* command_line) {
196 // Skip PlatformAppBrowserTest, which sets different values for the switches
197 // below.
198 ExtensionBrowserTest::SetUpCommandLine(command_line);
200 // Make event pages get suspended immediately.
201 extensions::ProcessManager::SetEventPageIdleTimeForTesting(1);
202 extensions::ProcessManager::SetEventPageSuspendingTimeForTesting(1);
204 // Enable ephemeral apps, which are gated by the experimental app launcher
205 // flag.
206 command_line->AppendSwitch(app_list::switches::kEnableExperimentalAppList);
209 void EphemeralAppTestBase::SetUpOnMainThread() {
210 PlatformAppBrowserTest::SetUpOnMainThread();
212 // Disable ephemeral apps immediately after they stop running in tests.
213 EphemeralAppService::Get(profile())->set_disable_delay_for_test(0);
216 base::FilePath EphemeralAppTestBase::GetTestPath(const char* test_path) {
217 return test_data_dir_.AppendASCII("platform_apps").AppendASCII(test_path);
220 const Extension* EphemeralAppTestBase::InstallEphemeralApp(
221 const char* test_path, Manifest::Location manifest_location) {
222 const Extension* extension = InstallEphemeralAppWithSourceAndFlags(
223 GetTestPath(test_path), 1, manifest_location, Extension::NO_FLAGS);
224 EXPECT_TRUE(extension);
225 if (extension)
226 EXPECT_TRUE(extensions::util::IsEphemeralApp(extension->id(), profile()));
227 return extension;
230 const Extension* EphemeralAppTestBase::InstallEphemeralApp(
231 const char* test_path) {
232 return InstallEphemeralApp(test_path, Manifest::INTERNAL);
235 const Extension* EphemeralAppTestBase::InstallAndLaunchEphemeralApp(
236 const char* test_path) {
237 ExtensionTestMessageListener launched_listener("launched", false);
238 const Extension* extension = InstallEphemeralApp(test_path);
239 EXPECT_TRUE(extension);
240 if (!extension)
241 return NULL;
243 LaunchPlatformApp(extension);
244 bool wait_result = launched_listener.WaitUntilSatisfied();
245 EXPECT_TRUE(wait_result);
246 if (!wait_result)
247 return NULL;
249 return extension;
252 const Extension* EphemeralAppTestBase::UpdateEphemeralApp(
253 const std::string& app_id,
254 const base::FilePath& test_dir,
255 const base::FilePath& pem_path) {
256 // Pack a new version of the app.
257 base::ScopedTempDir temp_dir;
258 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
260 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
261 if (!base::DeleteFile(crx_path, false)) {
262 ADD_FAILURE() << "Failed to delete existing crx: " << crx_path.value();
263 return NULL;
266 base::FilePath app_v2_path = PackExtensionWithOptions(
267 test_dir, crx_path, pem_path, base::FilePath());
268 EXPECT_FALSE(app_v2_path.empty());
270 // Update the ephemeral app and wait for the update to finish.
271 extensions::CrxInstaller* crx_installer = NULL;
272 content::WindowedNotificationObserver windowed_observer(
273 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
274 content::Source<extensions::CrxInstaller>(crx_installer));
275 ExtensionService* service =
276 ExtensionSystem::Get(profile())->extension_service();
277 EXPECT_TRUE(service->UpdateExtension(
278 extensions::CRXFileInfo(app_id, app_v2_path), true, &crx_installer));
279 windowed_observer.Wait();
281 return ExtensionRegistry::Get(profile())
282 ->GetExtensionById(app_id, ExtensionRegistry::EVERYTHING);
285 void EphemeralAppTestBase::PromoteEphemeralApp(
286 const extensions::Extension* app) {
287 ExtensionService* extension_service =
288 ExtensionSystem::Get(profile())->extension_service();
289 ASSERT_TRUE(extension_service);
290 extension_service->PromoteEphemeralApp(app, false);
293 void EphemeralAppTestBase::DisableEphemeralApp(
294 const Extension* app,
295 Extension::DisableReason disable_reason) {
296 ExtensionSystem::Get(profile())->extension_service()->DisableExtension(
297 app->id(), disable_reason);
299 ASSERT_TRUE(ExtensionRegistry::Get(profile())->disabled_extensions().Contains(
300 app->id()));
303 void EphemeralAppTestBase::CloseApp(const std::string& app_id) {
304 EXPECT_EQ(1U, GetAppWindowCountForApp(app_id));
305 extensions::AppWindow* app_window = GetFirstAppWindowForApp(app_id);
306 ASSERT_TRUE(app_window);
307 CloseAppWindow(app_window);
310 void EphemeralAppTestBase::CloseAppWaitForUnload(const std::string& app_id) {
311 // Ephemeral apps are unloaded from extension system after they stop running.
312 extensions::TestExtensionRegistryObserver observer(
313 ExtensionRegistry::Get(profile()), app_id);
314 CloseApp(app_id);
315 observer.WaitForExtensionUnloaded();
318 void EphemeralAppTestBase::EvictApp(const std::string& app_id) {
319 // Uninstall the app, which is what happens when ephemeral apps get evicted
320 // from the cache.
321 extensions::TestExtensionRegistryObserver observer(
322 ExtensionRegistry::Get(profile()), app_id);
324 ExtensionService* service =
325 ExtensionSystem::Get(profile())->extension_service();
326 ASSERT_TRUE(service);
327 service->UninstallExtension(
328 app_id,
329 extensions::UNINSTALL_REASON_ORPHANED_EPHEMERAL_EXTENSION,
330 base::Bind(&base::DoNothing),
331 NULL);
333 observer.WaitForExtensionUninstalled();
336 // EphemeralAppBrowserTest:
338 class EphemeralAppBrowserTest : public EphemeralAppTestBase {
339 protected:
340 bool LaunchAppAndRunTest(const Extension* app, const char* test_name) {
341 // Ephemeral apps are unloaded after they are closed. Ensure they are
342 // enabled before launch.
343 ExtensionService* service =
344 ExtensionSystem::Get(profile())->extension_service();
345 service->EnableExtension(app->id());
347 ExtensionTestMessageListener launched_listener("launched", true);
348 LaunchPlatformApp(app);
349 if (!launched_listener.WaitUntilSatisfied()) {
350 message_ = "Failed to receive launched message from test";
351 return false;
354 ResultCatcher catcher;
355 launched_listener.Reply(test_name);
357 bool result = catcher.GetNextResult();
358 message_ = catcher.message();
360 CloseAppWaitForUnload(app->id());
361 return result;
364 // Verify that the event page of the app has not been loaded.
365 void VerifyAppNotLoaded(const std::string& app_id) {
366 EXPECT_FALSE(extensions::ProcessManager::Get(profile())
367 ->GetBackgroundHostForExtension(app_id));
370 // Verify properties of ephemeral apps.
371 void VerifyEphemeralApp(const std::string& app_id) {
372 EXPECT_TRUE(extensions::util::IsEphemeralApp(app_id, profile()));
374 // Ephemeral apps should not be synced.
375 scoped_ptr<AppSyncData> sync_change = GetLastSyncChangeForApp(app_id);
376 EXPECT_FALSE(sync_change.get());
378 // Ephemeral apps should not be assigned ordinals.
379 extensions::AppSorting* app_sorting =
380 ExtensionPrefs::Get(profile())->app_sorting();
381 EXPECT_FALSE(app_sorting->GetAppLaunchOrdinal(app_id).IsValid());
382 EXPECT_FALSE(app_sorting->GetPageOrdinal(app_id).IsValid());
385 // Verify that after ephemeral apps stop running, they reside in extension
386 // system in a disabled and unloaded state.
387 void VerifyInactiveEphemeralApp(const std::string& app_id) {
388 EXPECT_TRUE(
389 ExtensionRegistry::Get(profile())->disabled_extensions().Contains(
390 app_id));
392 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
393 EXPECT_TRUE(prefs->IsExtensionDisabled(app_id));
394 EXPECT_NE(0,
395 prefs->GetDisableReasons(app_id) &
396 Extension::DISABLE_INACTIVE_EPHEMERAL_APP);
399 // Verify the state of an app that has been promoted from an ephemeral to a
400 // fully installed app.
401 void VerifyPromotedApp(const std::string& app_id,
402 ExtensionRegistry::IncludeFlag expected_set) {
403 const Extension* app = ExtensionRegistry::Get(profile())
404 ->GetExtensionById(app_id, expected_set);
405 ASSERT_TRUE(app) << "App not found in expected set: " << expected_set;
407 // The app should not be ephemeral.
408 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
409 ASSERT_TRUE(prefs);
410 EXPECT_FALSE(prefs->IsEphemeralApp(app_id));
411 EXPECT_EQ(0,
412 prefs->GetDisableReasons(app_id) &
413 Extension::DISABLE_INACTIVE_EPHEMERAL_APP);
415 // Check sort ordinals.
416 extensions::AppSorting* app_sorting = prefs->app_sorting();
417 EXPECT_TRUE(app_sorting->GetAppLaunchOrdinal(app_id).IsValid());
418 EXPECT_TRUE(app_sorting->GetPageOrdinal(app_id).IsValid());
421 // Dispatch a fake alarm event to the app.
422 void DispatchAlarmEvent(EventRouter* event_router,
423 const std::string& app_id) {
424 alarms::Alarm dummy_alarm;
425 dummy_alarm.name = "test_alarm";
427 scoped_ptr<base::ListValue> args(new base::ListValue());
428 args->Append(dummy_alarm.ToValue().release());
429 scoped_ptr<Event> event(new Event(alarms::OnAlarm::kEventName,
430 args.Pass()));
432 event_router->DispatchEventToExtension(app_id, event.Pass());
435 // Simulates the scenario where an app is installed, via the normal
436 // installation route, on top of an ephemeral app. This can occur due to race
437 // conditions.
438 const Extension* ReplaceEphemeralApp(const std::string& app_id,
439 const char* test_path,
440 int expected_enabled_change) {
441 return UpdateExtensionWaitForIdle(
442 app_id, GetTestPath(test_path), expected_enabled_change);
445 void PromoteEphemeralAppAndVerify(
446 const Extension* app,
447 ExtensionRegistry::IncludeFlag expected_set) {
448 ASSERT_TRUE(app);
450 // Ephemeral apps should not be synced.
451 scoped_ptr<AppSyncData> sync_change = GetLastSyncChangeForApp(app->id());
452 EXPECT_FALSE(sync_change.get());
454 // Promote the app to a regular installed app.
455 InstallObserver installed_observer(profile());
456 PromoteEphemeralApp(app);
457 VerifyPromotedApp(app->id(), expected_set);
459 // Check the notification parameters.
460 const InstallObserver::InstallParameters& params =
461 installed_observer.Last();
462 EXPECT_EQ(app->id(), params.id);
463 EXPECT_TRUE(params.is_update);
464 EXPECT_TRUE(params.from_ephemeral);
466 // The installation should now be synced.
467 sync_change = GetLastSyncChangeForApp(app->id());
468 VerifySyncChange(sync_change.get(),
469 expected_set == ExtensionRegistry::ENABLED);
472 void PromoteEphemeralAppFromSyncAndVerify(
473 const Extension* app,
474 bool enable_from_sync,
475 ExtensionRegistry::IncludeFlag expected_set) {
476 ASSERT_TRUE(app);
478 // Simulate an install from sync.
479 int disable_reasons = enable_from_sync ? 0 : Extension::DISABLE_USER_ACTION;
480 const syncer::StringOrdinal kAppLaunchOrdinal("x");
481 const syncer::StringOrdinal kPageOrdinal("y");
482 AppSyncData app_sync_data(*app,
483 enable_from_sync,
484 disable_reasons,
485 false /* incognito enabled */,
486 false /* remote install */,
487 extensions::ExtensionSyncData::BOOLEAN_UNSET,
488 kAppLaunchOrdinal,
489 kPageOrdinal,
490 extensions::LAUNCH_TYPE_REGULAR);
492 std::string app_id = app->id();
493 app = NULL;
495 ExtensionSyncService* sync_service = ExtensionSyncService::Get(profile());
496 sync_service->ProcessAppSyncData(app_sync_data);
498 // Verify the installation.
499 VerifyPromotedApp(app_id, expected_set);
501 // The sort ordinals from sync should not be overridden.
502 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
503 extensions::AppSorting* app_sorting = prefs->app_sorting();
504 EXPECT_TRUE(
505 app_sorting->GetAppLaunchOrdinal(app_id).Equals(kAppLaunchOrdinal));
506 EXPECT_TRUE(app_sorting->GetPageOrdinal(app_id).Equals(kPageOrdinal));
509 void InitSyncService() {
510 if (!kEnableSync)
511 return;
513 ExtensionSyncService* sync_service = ExtensionSyncService::Get(profile());
514 sync_service->MergeDataAndStartSyncing(
515 syncer::APPS,
516 syncer::SyncDataList(),
517 scoped_ptr<syncer::SyncChangeProcessor>(
518 new syncer::SyncChangeProcessorWrapperForTest(
519 &mock_sync_processor_)),
520 scoped_ptr<syncer::SyncErrorFactory>(
521 new syncer::SyncErrorFactoryMock()));
524 scoped_ptr<AppSyncData> GetLastSyncChangeForApp(const std::string& id) {
525 scoped_ptr<AppSyncData> sync_data;
526 for (syncer::SyncChangeList::iterator it =
527 mock_sync_processor_.changes().begin();
528 it != mock_sync_processor_.changes().end(); ++it) {
529 scoped_ptr<AppSyncData> data(AppSyncData::CreateFromSyncChange(*it));
530 if (data.get() && data->id() == id)
531 sync_data.reset(data.release());
534 return sync_data.Pass();
537 void VerifySyncChange(const AppSyncData* sync_change, bool expect_enabled) {
538 if (!kEnableSync)
539 return;
541 ASSERT_TRUE(sync_change);
542 EXPECT_TRUE(sync_change->page_ordinal().IsValid());
543 EXPECT_TRUE(sync_change->app_launch_ordinal().IsValid());
544 EXPECT_FALSE(sync_change->uninstalled());
545 EXPECT_EQ(expect_enabled, sync_change->extension_sync_data().enabled());
548 void TestInstallEvent(bool close_app) {
549 ExtensionTestMessageListener first_msg_listener(false);
550 const Extension* app = InstallAndLaunchEphemeralApp(kDispatchEventTestApp);
551 ASSERT_TRUE(app);
553 // When an ephemeral app is first added, it should not receive the
554 // onInstalled event, hence the first message received from the test should
555 // be "launched" and not "installed".
556 ASSERT_TRUE(first_msg_listener.WaitUntilSatisfied());
557 EXPECT_EQ(std::string("launched"), first_msg_listener.message());
559 if (close_app)
560 CloseAppWaitForUnload(app->id());
562 // When installed permanently, the app should receive the onInstalled event.
563 ExtensionTestMessageListener install_listener("installed", false);
564 PromoteEphemeralApp(app);
565 ASSERT_TRUE(install_listener.WaitUntilSatisfied());
568 private:
569 syncer::FakeSyncChangeProcessor mock_sync_processor_;
572 // Verify that ephemeral apps can be launched and receive system events when
573 // they are running. Once they are inactive they should not receive system
574 // events.
575 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, EventDispatchWhenLaunched) {
576 const Extension* extension =
577 InstallAndLaunchEphemeralApp(kDispatchEventTestApp);
578 ASSERT_TRUE(extension);
580 // Send a fake alarm event to the app and verify that a response is
581 // received.
582 EventRouter* event_router = EventRouter::Get(profile());
583 ASSERT_TRUE(event_router);
585 ExtensionTestMessageListener alarm_received_listener("alarm_received", false);
586 DispatchAlarmEvent(event_router, extension->id());
587 ASSERT_TRUE(alarm_received_listener.WaitUntilSatisfied());
589 CloseAppWaitForUnload(extension->id());
591 // Dispatch the alarm event again and verify that the event page did not get
592 // loaded for the app.
593 DispatchAlarmEvent(event_router, extension->id());
594 VerifyAppNotLoaded(extension->id());
597 // Verify that ephemeral apps will receive messages while they are running.
598 // Flaky test: crbug.com/394426
599 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
600 DISABLED_ReceiveMessagesWhenLaunched) {
601 const Extension* receiver =
602 InstallAndLaunchEphemeralApp(kMessagingReceiverApp);
603 ASSERT_TRUE(receiver);
605 // Verify that messages are received while the app is running.
606 ResultCatcher result_catcher;
607 LoadAndLaunchPlatformApp("ephemeral_apps/messaging_sender_success",
608 "Launched");
609 EXPECT_TRUE(result_catcher.GetNextResult());
611 CloseAppWaitForUnload(receiver->id());
613 // Verify that messages are not received while the app is inactive.
614 LoadAndLaunchPlatformApp("ephemeral_apps/messaging_sender_fail", "Launched");
615 EXPECT_TRUE(result_catcher.GetNextResult());
618 // Verifies that the chrome.runtime.onInstalled() event is received by a running
619 // ephemeral app only when it is promoted.
620 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
621 InstallEventReceivedWhileRunning) {
622 TestInstallEvent(false /* close app */);
625 // Verifies that when an idle ephemeral app is promoted, it will be loaded to
626 // receive the chrome.runtime.onInstalled() event.
627 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, InstallEventReceivedWhileIdle) {
628 TestInstallEvent(true /* close app */);
631 // Verifies that the chrome.runtime.onRestarted() event is received by an
632 // ephemeral app.
633 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, RestartEventReceived) {
634 const Extension* app = InstallAndLaunchEphemeralApp(kDispatchEventTestApp);
635 ASSERT_TRUE(app);
636 CloseAppWaitForUnload(app->id());
638 // Fake ephemeral app running before restart.
639 ExtensionSystem::Get(profile())->extension_service()->EnableExtension(
640 app->id());
641 ASSERT_TRUE(ExtensionRegistry::Get(profile())->enabled_extensions().Contains(
642 app->id()));
643 ExtensionPrefs::Get(profile())->SetExtensionRunning(app->id(), true);
645 ExtensionTestMessageListener restart_listener("restarted", false);
646 apps::AppRestoreService::Get(profile())->HandleStartup(true);
647 EXPECT_TRUE(restart_listener.WaitUntilSatisfied());
650 // Verify that an updated ephemeral app will still have its ephemeral flag
651 // enabled.
652 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, UpdateEphemeralApp) {
653 InitSyncService();
655 const Extension* app_v1 = InstallAndLaunchEphemeralApp(kMessagingReceiverApp);
656 ASSERT_TRUE(app_v1);
657 VerifyEphemeralApp(app_v1->id());
658 CloseAppWaitForUnload(app_v1->id());
659 VerifyInactiveEphemeralApp(app_v1->id());
661 std::string app_id = app_v1->id();
662 base::Version app_original_version = *app_v1->version();
664 // Update to version 2 of the app.
665 app_v1 = NULL; // The extension object will be destroyed during update.
666 InstallObserver installed_observer(profile());
667 const Extension* app_v2 =
668 UpdateEphemeralApp(app_id,
669 GetTestPath(kMessagingReceiverAppV2),
670 GetTestPath(kMessagingReceiverApp)
671 .ReplaceExtension(FILE_PATH_LITERAL(".pem")));
673 // Check the notification parameters.
674 const InstallObserver::InstallParameters& params = installed_observer.Last();
675 EXPECT_EQ(app_id, params.id);
676 EXPECT_TRUE(params.is_update);
677 EXPECT_FALSE(params.from_ephemeral);
679 // The ephemeral flag should still be set.
680 ASSERT_TRUE(app_v2);
681 EXPECT_GT(app_v2->version()->CompareTo(app_original_version), 0);
682 VerifyEphemeralApp(app_id);
684 // The app should still be disabled in extension system.
685 VerifyInactiveEphemeralApp(app_id);
688 // Verify that if notifications have been disabled for an ephemeral app, it will
689 // remain disabled even after being evicted from the cache.
690 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, StickyNotificationSettings) {
691 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
692 ASSERT_TRUE(app);
694 // Disable notifications for this app.
695 DesktopNotificationService* notification_service =
696 DesktopNotificationServiceFactory::GetForProfile(profile());
697 ASSERT_TRUE(notification_service);
699 message_center::NotifierId notifier_id(
700 message_center::NotifierId::APPLICATION, app->id());
701 EXPECT_TRUE(notification_service->IsNotifierEnabled(notifier_id));
702 notification_service->SetNotifierEnabled(notifier_id, false);
703 EXPECT_FALSE(notification_service->IsNotifierEnabled(notifier_id));
705 // Remove the app.
706 CloseAppWaitForUnload(app->id());
707 EvictApp(app->id());
709 // Reinstall the ephemeral app and verify that notifications remain disabled.
710 app = InstallEphemeralApp(kNotificationsTestApp);
711 ASSERT_TRUE(app);
712 message_center::NotifierId reinstalled_notifier_id(
713 message_center::NotifierId::APPLICATION, app->id());
714 EXPECT_FALSE(notification_service->IsNotifierEnabled(
715 reinstalled_notifier_id));
718 // Verify that only running ephemeral apps will appear in the Notification
719 // Settings UI. Inactive, cached ephemeral apps should not appear.
720 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
721 IncludeRunningEphemeralAppsInNotifiers) {
722 message_center::NotifierSettingsProvider* settings_provider =
723 message_center::MessageCenter::Get()->GetNotifierSettingsProvider();
724 DCHECK(settings_provider);
726 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
727 ASSERT_TRUE(app);
728 message_center::NotifierId notifier_id(
729 message_center::NotifierId::APPLICATION, app->id());
731 // Since the ephemeral app is running, it should be included in the list
732 // of notifiers to show in the UI.
733 NotifierList notifiers;
734 STLElementDeleter<NotifierList> notifier_deleter(&notifiers);
736 settings_provider->GetNotifierList(&notifiers);
737 EXPECT_TRUE(IsNotifierInList(notifier_id, notifiers));
738 STLDeleteElements(&notifiers);
740 // Close the ephemeral app.
741 CloseAppWaitForUnload(app->id());
743 // Inactive ephemeral apps should not be included in the list of notifiers to
744 // show in the UI.
745 settings_provider->GetNotifierList(&notifiers);
746 EXPECT_FALSE(IsNotifierInList(notifier_id, notifiers));
749 // Verify that ephemeral apps will have no ability to retain file entries after
750 // close. Normal retainEntry behavior for installed apps is tested in
751 // FileSystemApiTest.
752 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
753 DisableRetainFileSystemEntries) {
754 // Create a dummy file that we can just return to the test.
755 base::ScopedTempDir temp_dir;
756 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
757 base::FilePath temp_file;
758 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &temp_file));
760 using extensions::FileSystemChooseEntryFunction;
761 FileSystemChooseEntryFunction::SkipPickerAndAlwaysSelectPathForTest(
762 &temp_file);
763 // The temporary file needs to be registered for the tests to pass on
764 // ChromeOS.
765 FileSystemChooseEntryFunction::RegisterTempExternalFileSystemForTest(
766 "temp", temp_dir.path());
768 // The first test opens the file and writes the file handle to local storage.
769 const Extension* app = InstallEphemeralApp(kFileSystemTestApp,
770 Manifest::UNPACKED);
771 ASSERT_TRUE(LaunchAppAndRunTest(app, "OpenAndRetainFile")) << message_;
773 // Verify that after the app has been closed, all retained entries are
774 // flushed.
775 std::vector<apps::SavedFileEntry> file_entries =
776 apps::SavedFilesService::Get(profile())
777 ->GetAllFileEntries(app->id());
778 EXPECT_TRUE(file_entries.empty());
780 // The second test verifies that the file cannot be reopened.
781 ASSERT_TRUE(LaunchAppAndRunTest(app, "RestoreRetainedFile")) << message_;
784 // Checks the process of launching an ephemeral app and then promoting the app
785 // while it is running.
786 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, PromoteAppWhileRunning) {
787 InitSyncService();
789 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
790 ASSERT_TRUE(app);
792 PromoteEphemeralAppAndVerify(app, ExtensionRegistry::ENABLED);
794 // Ensure that the app is not unloaded and disabled after it is closed.
795 CloseApp(app->id());
796 VerifyPromotedApp(app->id(), ExtensionRegistry::ENABLED);
799 // Checks the process of launching an ephemeral app and then promoting the app
800 // while it is idle.
801 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, PromoteAppWhileIdle) {
802 InitSyncService();
804 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
805 ASSERT_TRUE(app);
806 CloseAppWaitForUnload(app->id());
807 VerifyInactiveEphemeralApp(app->id());
809 PromoteEphemeralAppAndVerify(app, ExtensionRegistry::ENABLED);
812 // Verifies that promoting an ephemeral app that was disabled due to a
813 // permissions increase will enable it.
814 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, PromoteAppAndGrantPermissions) {
815 InitSyncService();
817 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
818 ASSERT_TRUE(app);
819 CloseAppWaitForUnload(app->id());
820 DisableEphemeralApp(app, Extension::DISABLE_PERMISSIONS_INCREASE);
822 PromoteEphemeralAppAndVerify(app, ExtensionRegistry::ENABLED);
823 EXPECT_FALSE(ExtensionPrefs::Get(profile())
824 ->DidExtensionEscalatePermissions(app->id()));
827 // Verifies that promoting an ephemeral app that has unsupported requirements
828 // will not enable it.
829 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
830 PromoteUnsupportedEphemeralApp) {
831 InitSyncService();
833 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
834 ASSERT_TRUE(app);
835 CloseAppWaitForUnload(app->id());
836 DisableEphemeralApp(app, Extension::DISABLE_UNSUPPORTED_REQUIREMENT);
838 // When promoted to a regular installed app, it should remain disabled.
839 PromoteEphemeralAppAndVerify(app, ExtensionRegistry::DISABLED);
842 // Verifies that promoting an ephemeral app that is blacklisted will not enable
843 // it.
844 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
845 PromoteBlacklistedEphemeralApp) {
846 InitSyncService();
848 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
849 ASSERT_TRUE(app);
850 CloseAppWaitForUnload(app->id());
852 ExtensionService* service =
853 ExtensionSystem::Get(profile())->extension_service();
854 service->BlacklistExtensionForTest(app->id());
855 ASSERT_TRUE(
856 ExtensionRegistry::Get(profile())->blacklisted_extensions().Contains(
857 app->id()));
859 // When promoted to a regular installed app, it should remain blacklisted.
860 PromoteEphemeralAppAndVerify(app, ExtensionRegistry::BLACKLISTED);
862 // The app should be synced, but disabled.
863 scoped_ptr<AppSyncData> sync_change = GetLastSyncChangeForApp(app->id());
864 VerifySyncChange(sync_change.get(), false);
867 // Checks the process of promoting an ephemeral app from sync while the app is
868 // running.
869 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
870 PromoteAppFromSyncWhileRunning) {
871 InitSyncService();
873 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
874 ASSERT_TRUE(app);
876 PromoteEphemeralAppFromSyncAndVerify(app, true, ExtensionRegistry::ENABLED);
878 // Ensure that the app is not unloaded and disabled after it is closed.
879 CloseApp(app->id());
880 VerifyPromotedApp(app->id(), ExtensionRegistry::ENABLED);
883 // Checks the process of promoting an ephemeral app from sync while the app is
884 // idle.
885 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, PromoteAppFromSyncWhileIdle) {
886 InitSyncService();
888 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
889 ASSERT_TRUE(app);
890 CloseAppWaitForUnload(app->id());
891 VerifyInactiveEphemeralApp(app->id());
893 PromoteEphemeralAppFromSyncAndVerify(app, true, ExtensionRegistry::ENABLED);
896 // Checks the process of promoting an ephemeral app from sync, where the app
897 // from sync is disabled, and the ephemeral app is running.
898 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
899 PromoteDisabledAppFromSyncWhileRunning) {
900 InitSyncService();
902 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
903 ASSERT_TRUE(app);
905 PromoteEphemeralAppFromSyncAndVerify(app, false, ExtensionRegistry::DISABLED);
908 // Checks the process of promoting an ephemeral app from sync, where the app
909 // from sync is disabled, and the ephemeral app is idle.
910 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
911 PromoteDisabledAppFromSyncWhileIdle) {
912 InitSyncService();
914 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
915 ASSERT_TRUE(app);
916 CloseAppWaitForUnload(app->id());
917 VerifyInactiveEphemeralApp(app->id());
919 PromoteEphemeralAppFromSyncAndVerify(app, false, ExtensionRegistry::DISABLED);
922 // In most cases, ExtensionService::PromoteEphemeralApp() will be called to
923 // permanently install an ephemeral app. However, there may be cases where an
924 // install occurs through the usual route of installing from the Web Store (due
925 // to race conditions). Ensure that the app is still installed correctly.
926 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
927 ReplaceEphemeralAppWithInstalledApp) {
928 InitSyncService();
930 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
931 ASSERT_TRUE(app);
932 CloseAppWaitForUnload(app->id());
933 std::string app_id = app->id();
934 app = NULL;
936 InstallObserver installed_observer(profile());
937 ReplaceEphemeralApp(app_id, kNotificationsTestApp, 1);
938 VerifyPromotedApp(app_id, ExtensionRegistry::ENABLED);
940 // Check the notification parameters.
941 const InstallObserver::InstallParameters& params = installed_observer.Last();
942 EXPECT_EQ(app_id, params.id);
943 EXPECT_TRUE(params.is_update);
944 EXPECT_TRUE(params.from_ephemeral);
947 // This is similar to ReplaceEphemeralAppWithInstalledApp, but installs will
948 // be delayed until the app is idle.
949 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
950 ReplaceEphemeralAppWithDelayedInstalledApp) {
951 InitSyncService();
952 const Extension* app = InstallAndLaunchEphemeralApp(kNotificationsTestApp);
953 ASSERT_TRUE(app);
954 std::string app_id = app->id();
955 app = NULL;
957 // Initiate install.
958 ReplaceEphemeralApp(app_id, kNotificationsTestApp, 0);
960 // The delayed installation will occur when the ephemeral app is closed.
961 extensions::TestExtensionRegistryObserver observer(
962 ExtensionRegistry::Get(profile()), app_id);
963 InstallObserver installed_observer(profile());
964 CloseAppWaitForUnload(app_id);
965 observer.WaitForExtensionWillBeInstalled();
966 VerifyPromotedApp(app_id, ExtensionRegistry::ENABLED);
968 // Check the notification parameters.
969 const InstallObserver::InstallParameters& params = installed_observer.Last();
970 EXPECT_EQ(app_id, params.id);
971 EXPECT_TRUE(params.is_update);
972 EXPECT_TRUE(params.from_ephemeral);
975 // Verifies that an installed app cannot turn into an ephemeral app as result of
976 // race conditions, i.e. an ephemeral app can be promoted to an installed app,
977 // but not vice versa.
978 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
979 ReplaceInstalledAppWithEphemeralApp) {
980 const Extension* app = InstallPlatformApp(kNotificationsTestApp);
981 ASSERT_TRUE(app);
982 std::string app_id = app->id();
983 app = NULL;
985 EXPECT_FALSE(extensions::util::IsEphemeralApp(app_id, profile()));
986 app =
987 InstallEphemeralAppWithSourceAndFlags(GetTestPath(kNotificationsTestApp),
989 Manifest::INTERNAL,
990 Extension::NO_FLAGS);
991 EXPECT_FALSE(extensions::util::IsEphemeralApp(app_id, profile()));
994 // Ephemerality was previously encoded by the Extension::IS_EPHEMERAL creation
995 // flag. This was changed to an "ephemeral_app" property. Check that the prefs
996 // are handled correctly.
997 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest,
998 ExtensionPrefBackcompatibility) {
999 // Ensure that apps with the old prefs are recognized as ephemeral.
1000 const Extension* app =
1001 InstallExtensionWithSourceAndFlags(GetTestPath(kNotificationsTestApp),
1003 Manifest::INTERNAL,
1004 Extension::IS_EPHEMERAL);
1005 ASSERT_TRUE(app);
1006 EXPECT_TRUE(extensions::util::IsEphemeralApp(app->id(), profile()));
1008 // Ensure that when the app is promoted to an installed app, the bit in the
1009 // creation flags is cleared.
1010 PromoteEphemeralApp(app);
1011 EXPECT_FALSE(extensions::util::IsEphemeralApp(app->id(), profile()));
1013 int creation_flags =
1014 ExtensionPrefs::Get(profile())->GetCreationFlags(app->id());
1015 EXPECT_EQ(0, creation_flags & Extension::IS_EPHEMERAL);
1018 // Verifies that the power keep awake will be automatically released for
1019 // ephemeral apps that stop running. Well behaved apps should actually call
1020 // chrome.power.releaseKeepAwake() themselves.
1021 IN_PROC_BROWSER_TEST_F(EphemeralAppBrowserTest, ReleasePowerKeepAwake) {
1022 PowerSettingsMock power_settings;
1023 extensions::PowerAPI::Get(profile())->SetCreateBlockerFunctionForTesting(
1024 base::Bind(&PowerSaveBlockerStub::Create, &power_settings));
1026 const Extension* app = InstallAndLaunchEphemeralApp(kPowerTestApp);
1027 ASSERT_TRUE(app);
1028 EXPECT_EQ(1, power_settings.keep_awake_count());
1030 CloseAppWaitForUnload(app->id());
1032 EXPECT_EQ(0, power_settings.keep_awake_count());