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/extensions/extension_gcm_app_handler.h"
10 #include "base/bind_helpers.h"
11 #include "base/command_line.h"
12 #include "base/files/file_path.h"
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_temp_dir.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/path_service.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/run_loop.h"
22 #include "base/values.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/extensions/api/gcm/gcm_api.h"
25 #include "chrome/browser/extensions/extension_service.h"
26 #include "chrome/browser/extensions/test_extension_service.h"
27 #include "chrome/browser/extensions/test_extension_system.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/services/gcm/fake_signin_manager.h"
30 #include "chrome/browser/services/gcm/gcm_profile_service.h"
31 #include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
32 #include "chrome/browser/signin/signin_manager_factory.h"
33 #include "chrome/common/chrome_paths.h"
34 #include "chrome/common/pref_names.h"
35 #include "chrome/test/base/testing_profile.h"
36 #include "components/gcm_driver/fake_gcm_app_handler.h"
37 #include "components/gcm_driver/fake_gcm_client.h"
38 #include "components/gcm_driver/fake_gcm_client_factory.h"
39 #include "components/gcm_driver/gcm_client_factory.h"
40 #include "components/gcm_driver/gcm_driver.h"
41 #include "components/keyed_service/core/keyed_service.h"
42 #include "content/public/browser/browser_context.h"
43 #include "content/public/browser/browser_thread.h"
44 #include "content/public/test/test_browser_thread_bundle.h"
45 #include "content/public/test/test_utils.h"
46 #include "extensions/browser/extension_system.h"
47 #include "extensions/browser/uninstall_reason.h"
48 #include "extensions/common/extension.h"
49 #include "extensions/common/manifest.h"
50 #include "extensions/common/manifest_constants.h"
51 #include "extensions/common/permissions/api_permission.h"
52 #include "extensions/common/permissions/permissions_data.h"
53 #include "testing/gtest/include/gtest/gtest.h"
55 #if defined(OS_CHROMEOS)
56 #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h"
57 #include "chrome/browser/chromeos/settings/cros_settings.h"
58 #include "chrome/browser/chromeos/settings/device_settings_service.h"
59 #include "chromeos/dbus/dbus_thread_manager.h"
62 namespace extensions {
66 const char kTestExtensionName[] = "FooBar";
67 const char kTestingUsername[] = "user1@example.com";
71 // Helper class for asynchronous waiting.
77 // Waits until the asynchronous operation finishes.
78 void WaitUntilCompleted() {
79 run_loop_.reset(new base::RunLoop);
83 // Signals that the asynchronous operation finishes.
84 void SignalCompleted() {
85 if (run_loop_ && run_loop_->running())
89 // Runs until UI loop becomes idle.
91 base::MessageLoop::current()->RunUntilIdle();
94 // Runs until IO loop becomes idle.
96 content::BrowserThread::PostTask(
97 content::BrowserThread::IO,
99 base::Bind(&Waiter::OnIOLoopPump, base::Unretained(this)));
101 WaitUntilCompleted();
105 void PumpIOLoopCompleted() {
106 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
111 void OnIOLoopPump() {
112 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
114 content::BrowserThread::PostTask(
115 content::BrowserThread::IO,
117 base::Bind(&Waiter::OnIOLoopPumpCompleted, base::Unretained(this)));
120 void OnIOLoopPumpCompleted() {
121 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));
123 content::BrowserThread::PostTask(
124 content::BrowserThread::UI,
126 base::Bind(&Waiter::PumpIOLoopCompleted, base::Unretained(this)));
129 scoped_ptr<base::RunLoop> run_loop_;
131 DISALLOW_COPY_AND_ASSIGN(Waiter);
134 class FakeExtensionGCMAppHandler : public ExtensionGCMAppHandler {
136 FakeExtensionGCMAppHandler(Profile* profile, Waiter* waiter)
137 : ExtensionGCMAppHandler(profile),
139 unregistration_result_(gcm::GCMClient::UNKNOWN_ERROR),
140 app_handler_count_drop_to_zero_(false) {
143 ~FakeExtensionGCMAppHandler() override {}
145 void OnMessage(const std::string& app_id,
146 const gcm::GCMClient::IncomingMessage& message) override {}
148 void OnMessagesDeleted(const std::string& app_id) override {}
151 const std::string& app_id,
152 const gcm::GCMClient::SendErrorDetails& send_error_details) override {}
154 void OnUnregisterCompleted(const std::string& app_id,
155 gcm::GCMClient::Result result) override {
156 unregistration_result_ = result;
157 waiter_->SignalCompleted();
160 void RemoveAppHandler(const std::string& app_id) override {
161 ExtensionGCMAppHandler::RemoveAppHandler(app_id);
162 if (!GetGCMDriver()->app_handlers().size())
163 app_handler_count_drop_to_zero_ = true;
166 gcm::GCMClient::Result unregistration_result() const {
167 return unregistration_result_;
169 bool app_handler_count_drop_to_zero() const {
170 return app_handler_count_drop_to_zero_;
175 gcm::GCMClient::Result unregistration_result_;
176 bool app_handler_count_drop_to_zero_;
178 DISALLOW_COPY_AND_ASSIGN(FakeExtensionGCMAppHandler);
181 class ExtensionGCMAppHandlerTest : public testing::Test {
183 static KeyedService* BuildGCMProfileService(
184 content::BrowserContext* context) {
185 return new gcm::GCMProfileService(
186 Profile::FromBrowserContext(context),
187 scoped_ptr<gcm::GCMClientFactory>(new gcm::FakeGCMClientFactory(
188 gcm::FakeGCMClient::NO_DELAY_START,
189 content::BrowserThread::GetMessageLoopProxyForThread(
190 content::BrowserThread::UI),
191 content::BrowserThread::GetMessageLoopProxyForThread(
192 content::BrowserThread::IO))));
195 ExtensionGCMAppHandlerTest()
196 : extension_service_(NULL),
197 registration_result_(gcm::GCMClient::UNKNOWN_ERROR),
198 unregistration_result_(gcm::GCMClient::UNKNOWN_ERROR) {
201 ~ExtensionGCMAppHandlerTest() override {}
203 // Overridden from test::Test:
204 void SetUp() override {
205 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
207 // Make BrowserThread work in unittest.
208 thread_bundle_.reset(new content::TestBrowserThreadBundle(
209 content::TestBrowserThreadBundle::REAL_IO_THREAD));
211 // Allow extension update to unpack crx in process.
212 in_process_utility_thread_helper_.reset(
213 new content::InProcessUtilityThreadHelper);
215 // This is needed to create extension service under CrOS.
216 #if defined(OS_CHROMEOS)
217 test_user_manager_.reset(new chromeos::ScopedTestUserManager());
218 // Creating a DBus thread manager setter has the side effect of
219 // creating a DBusThreadManager, which is needed for testing.
220 // We don't actually need the setter so we ignore the return value.
221 chromeos::DBusThreadManager::GetSetterForTesting();
224 // Create a new profile.
225 TestingProfile::Builder builder;
226 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
227 gcm::FakeSigninManager::Build);
228 profile_ = builder.Build();
229 signin_manager_ = static_cast<gcm::FakeSigninManager*>(
230 SigninManagerFactory::GetInstance()->GetForProfile(profile_.get()));
232 // Create extension service in order to uninstall the extension.
233 TestExtensionSystem* extension_system(
234 static_cast<TestExtensionSystem*>(ExtensionSystem::Get(profile())));
235 base::FilePath extensions_install_dir =
236 temp_dir_.path().Append(FILE_PATH_LITERAL("Extensions"));
237 extension_system->CreateExtensionService(
238 CommandLine::ForCurrentProcess(), extensions_install_dir, false);
239 extension_service_ = extension_system->Get(profile())->extension_service();
240 extension_service_->set_extensions_enabled(true);
241 extension_service_->set_show_extensions_prompts(false);
242 extension_service_->set_install_updates_when_idle_for_test(false);
244 // Enable GCM such that tests could be run on all channels.
245 profile()->GetPrefs()->SetBoolean(prefs::kGCMChannelEnabled, true);
247 // Create GCMProfileService that talks with fake GCMClient.
248 gcm::GCMProfileServiceFactory::GetInstance()->SetTestingFactoryAndUse(
249 profile(), &ExtensionGCMAppHandlerTest::BuildGCMProfileService);
251 // Create a fake version of ExtensionGCMAppHandler.
252 gcm_app_handler_.reset(new FakeExtensionGCMAppHandler(profile(), &waiter_));
255 void TearDown() override {
256 #if defined(OS_CHROMEOS)
257 test_user_manager_.reset();
260 waiter_.PumpUILoop();
263 // Returns a barebones test extension.
264 scoped_refptr<Extension> CreateExtension() {
265 base::DictionaryValue manifest;
266 manifest.SetString(manifest_keys::kVersion, "1.0.0.0");
267 manifest.SetString(manifest_keys::kName, kTestExtensionName);
268 base::ListValue* permission_list = new base::ListValue;
269 permission_list->Append(new base::StringValue("gcm"));
270 manifest.Set(manifest_keys::kPermissions, permission_list);
273 scoped_refptr<Extension> extension = Extension::Create(
278 "ldnnhddmnhbkjipkidpdiheffobcpfmf",
280 EXPECT_TRUE(extension.get()) << error;
282 extension->permissions_data()->HasAPIPermission(APIPermission::kGcm));
287 void LoadExtension(const Extension* extension) {
288 extension_service_->AddExtension(extension);
291 static bool IsCrxInstallerDone(extensions::CrxInstaller** installer,
292 const content::NotificationSource& source,
293 const content::NotificationDetails& details) {
294 return content::Source<extensions::CrxInstaller>(source).ptr() ==
298 void UpdateExtension(const Extension* extension,
299 const std::string& update_crx) {
300 base::FilePath data_dir;
301 if (!PathService::Get(chrome::DIR_TEST_DATA, &data_dir)) {
305 data_dir = data_dir.AppendASCII("extensions");
306 data_dir = data_dir.AppendASCII(update_crx);
308 base::FilePath path = temp_dir_.path();
309 path = path.Append(data_dir.BaseName());
310 ASSERT_TRUE(base::CopyFile(data_dir, path));
312 extensions::CrxInstaller* installer = NULL;
313 content::WindowedNotificationObserver observer(
314 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
315 base::Bind(&IsCrxInstallerDone, &installer));
316 extension_service_->UpdateExtension(
317 extension->id(), path, true, &installer);
323 void DisableExtension(const Extension* extension) {
324 extension_service_->DisableExtension(
325 extension->id(), Extension::DISABLE_USER_ACTION);
328 void EnableExtension(const Extension* extension) {
329 extension_service_->EnableExtension(extension->id());
332 void UninstallExtension(const Extension* extension) {
333 extension_service_->UninstallExtension(
335 extensions::UNINSTALL_REASON_FOR_TESTING,
336 base::Bind(&base::DoNothing),
340 void SignIn(const std::string& username) {
341 signin_manager_->SignIn(username);
342 waiter_.PumpIOLoop();
346 signin_manager_->SignOut(signin_metrics::SIGNOUT_TEST);
347 waiter_.PumpIOLoop();
350 void Register(const std::string& app_id,
351 const std::vector<std::string>& sender_ids) {
352 GetGCMDriver()->Register(
355 base::Bind(&ExtensionGCMAppHandlerTest::RegisterCompleted,
356 base::Unretained(this)));
359 void RegisterCompleted(const std::string& registration_id,
360 gcm::GCMClient::Result result) {
361 registration_result_ = result;
362 waiter_.SignalCompleted();
365 gcm::GCMDriver* GetGCMDriver() const {
366 return gcm::GCMProfileServiceFactory::GetForProfile(profile())->driver();
369 bool HasAppHandlers(const std::string& app_id) const {
370 return GetGCMDriver()->app_handlers().count(app_id);
373 Profile* profile() const { return profile_.get(); }
374 Waiter* waiter() { return &waiter_; }
375 FakeExtensionGCMAppHandler* gcm_app_handler() const {
376 return gcm_app_handler_.get();
378 gcm::GCMClient::Result registration_result() const {
379 return registration_result_;
381 gcm::GCMClient::Result unregistration_result() const {
382 return unregistration_result_;
386 scoped_ptr<content::TestBrowserThreadBundle> thread_bundle_;
387 scoped_ptr<content::InProcessUtilityThreadHelper>
388 in_process_utility_thread_helper_;
389 scoped_ptr<TestingProfile> profile_;
390 ExtensionService* extension_service_; // Not owned.
391 gcm::FakeSigninManager* signin_manager_; // Not owned.
392 base::ScopedTempDir temp_dir_;
394 // This is needed to create extension service under CrOS.
395 #if defined(OS_CHROMEOS)
396 chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
397 chromeos::ScopedTestCrosSettings test_cros_settings_;
398 scoped_ptr<chromeos::ScopedTestUserManager> test_user_manager_;
402 scoped_ptr<FakeExtensionGCMAppHandler> gcm_app_handler_;
403 gcm::GCMClient::Result registration_result_;
404 gcm::GCMClient::Result unregistration_result_;
406 DISALLOW_COPY_AND_ASSIGN(ExtensionGCMAppHandlerTest);
409 TEST_F(ExtensionGCMAppHandlerTest, AddAndRemoveAppHandler) {
410 scoped_refptr<Extension> extension(CreateExtension());
412 // App handler is added when extension is loaded.
413 LoadExtension(extension.get());
414 waiter()->PumpUILoop();
415 EXPECT_TRUE(HasAppHandlers(extension->id()));
417 // App handler is removed when extension is unloaded.
418 DisableExtension(extension.get());
419 waiter()->PumpUILoop();
420 EXPECT_FALSE(HasAppHandlers(extension->id()));
422 // App handler is added when extension is reloaded.
423 EnableExtension(extension.get());
424 waiter()->PumpUILoop();
425 EXPECT_TRUE(HasAppHandlers(extension->id()));
427 // App handler is removed when extension is uninstalled.
428 UninstallExtension(extension.get());
429 waiter()->PumpUILoop();
430 EXPECT_FALSE(HasAppHandlers(extension->id()));
433 TEST_F(ExtensionGCMAppHandlerTest, UnregisterOnExtensionUninstall) {
434 scoped_refptr<Extension> extension(CreateExtension());
435 LoadExtension(extension.get());
437 // Sign-in is needed for registration.
438 SignIn(kTestingUsername);
440 // Kick off registration.
441 std::vector<std::string> sender_ids;
442 sender_ids.push_back("sender1");
443 Register(extension->id(), sender_ids);
444 waiter()->WaitUntilCompleted();
445 EXPECT_EQ(gcm::GCMClient::SUCCESS, registration_result());
447 // Add another app handler in order to prevent the GCM service from being
448 // stopped when the extension is uninstalled. This is needed because otherwise
449 // we are not able to receive the unregistration result.
450 GetGCMDriver()->AddAppHandler("Foo", gcm_app_handler());
452 // Unregistration should be triggered when the extension is uninstalled.
453 UninstallExtension(extension.get());
454 waiter()->WaitUntilCompleted();
455 EXPECT_EQ(gcm::GCMClient::SUCCESS,
456 gcm_app_handler()->unregistration_result());
459 GetGCMDriver()->RemoveAppHandler("Foo");
462 TEST_F(ExtensionGCMAppHandlerTest, UpdateExtensionWithGcmPermissionKept) {
463 scoped_refptr<Extension> extension(CreateExtension());
465 // App handler is added when the extension is loaded.
466 LoadExtension(extension.get());
467 waiter()->PumpUILoop();
468 EXPECT_TRUE(HasAppHandlers(extension->id()));
470 // App handler count should not drop to zero when the extension is updated.
471 UpdateExtension(extension.get(), "gcm2.crx");
472 waiter()->PumpUILoop();
473 EXPECT_FALSE(gcm_app_handler()->app_handler_count_drop_to_zero());
474 EXPECT_TRUE(HasAppHandlers(extension->id()));
477 TEST_F(ExtensionGCMAppHandlerTest, UpdateExtensionWithGcmPermissionRemoved) {
478 scoped_refptr<Extension> extension(CreateExtension());
480 // App handler is added when the extension is loaded.
481 LoadExtension(extension.get());
482 waiter()->PumpUILoop();
483 EXPECT_TRUE(HasAppHandlers(extension->id()));
485 // App handler is removed when the extension is updated to the version that
486 // has GCM permission removed.
487 UpdateExtension(extension.get(), "good2.crx");
488 waiter()->PumpUILoop();
489 EXPECT_TRUE(gcm_app_handler()->app_handler_count_drop_to_zero());
490 EXPECT_FALSE(HasAppHandlers(extension->id()));
493 } // namespace extensions